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
RebootRevival/FFXI_Test
scripts/zones/Northern_San_dOria/npcs/Rodaillece.lua
3
1042
----------------------------------- -- Area: Northern San d'Oria -- NPC: Rodaillece -- Type: Standard Dialogue NPC -- @zone 231 -- !pos -246.943 7.000 46.836 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,RODAILLECE_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
jthomasbarry/aafmt
archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/model/Arc.lua
2
19772
-- 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/model/Arc.lua,v 1.7 2015/04/21 14:10:00 tantau Exp $ --- -- An arc is a light-weight object representing an arc from a vertex -- in a graph to another vertex. You may not create an |Arc| by -- yourself, which is why there is no |new| method, arc creation is -- done by the Digraph class. -- -- Every arc belongs to exactly one graph. If you want the same arc in -- another graph, you need to newly connect two vertices in the other graph. -- -- You may read the |head| and |tail| fields, but you may not write -- them. In order to store data for an arc, use |Storage| objects. -- -- Between any two vertices of a graph there can be only one arc, so -- all digraphs are always simple graphs. However, in the -- specification of a graph (the syntactic digraph), there might -- be multiple edges between two vertices. This means, in particular, -- that an arc has no |options| field. Rather, it has several -- |optionsXxxx| functions, that will search for options in all of the -- synactic edges that ``belong'' to an edge. -- -- In order to \emph{set} options of the edges, you can set the -- |generate_options| field of an arc (which is |nil| by default), see -- the |declare_parameter_sequence| function for the syntax. Similar -- to the |path| field below, the options set in this table are -- written back to the syntactic edges during a sync. -- -- In detail, the following happens: Even though an arc has a |path| -- field and a |generated_options| field, setting these fields does -- not immediately set the paths of the syntactic edges nor does it -- generate options. Indeed, you will normally want to setup and -- modify the |path| field of an arc during your algorithm and only at -- the very end, ``write it back'' to the multiple syntactic edges -- underlying the graph. For this purpose, the method |sync| is used, -- which is called automatically for the |ugraph| and |digraph| of a -- scope as well as for spanning trees. -- -- The bottom line concerning the |path| field is the following: If -- you just want a straight line along an arc, just leave the field as -- it is (namely, |nil|). If you want to have all edges along a path -- to follow a certain path, set the |path| field of the arc to the -- path you desire (typically, using the |setPolylinePath| or a -- similar method). This will cause all syntactic edges underlying the -- arc to be set to the specified path. In the event that you want to -- set different paths for the edges underlying a single arc -- differently, set the |path| fields of these edges and set the -- |path| field of the arc to |nil|. This will disable the syncing for -- the arc and will cause the edge |paths| to remain untouched. -- -- @field tail The tail vertex of the arc. -- @field head The head vertex of the arc. May be the same as the tail -- in case of a loop. -- @field path If non-nil, the path of the arc. See the description -- above. -- @field generated_options If non-nil, some options to be passed back -- to the original syntactic edges, see the description above. -- @field syntactic_edges In case this arc is an arc in the syntatic -- digraph (and only then), this field contains an array containing -- syntactic edges (``real'' edges in the syntactic digraph) that -- underly this arc. Otherwise, the field will be empty or |nil|. -- local Arc = {} Arc.__index = Arc -- Namespace require("pgf.gd.model").Arc = Arc -- Imports local Path = require 'pgf.gd.model.Path' local lib = require 'pgf.gd.lib' --- -- Get an array of options of the syntactic edges corresponding to an arc. -- -- An arc in a digraph is typically (but not always) present because -- there are one or more edges in the syntactic digraph between the -- tail and the head of the arc or between the head and the tail. -- -- Since for every arc there can be several edges present in the -- syntactic digraph, an option like |length| may have -- been given multiple times for the edges corresponding to the arc. -- -- If your algorithm gets confused by multiple edges, try saying -- |a:options(your_option)|. This will always give the ``most -- sensible'' choice of the option if there are multiple edges -- corresponding to the same arc. -- -- @param option A string option like |"length"|. -- -- @return A table with the following contents: -- \begin{enumerate} -- \item It is an array of all values the option has for edges -- corresponding to |self| in the syntactic digraph. Suppose, for -- instance, you write the following: --\begin{codeexample}[code only] --graph { -- tail -- [length=1] head, % multi edge 1 -- tail -- [length=3] head, % mulit edge 2 -- head -- [length=8] tail, % multi edge 3 -- tail -- head, % multi edge 4 -- head -- [length=7] tail, % multi edge 5 -- tail -- [length=2] head, % multi edge 6 --} --\end{codeexample} -- Suppose, furthermore, that |length| has been setup as an edge -- option. Now suppose that |a| is the arc from the vertex |tail| to -- the vertex |head|. Calling |a:optionsArray('length')| will -- yield the array part |{1,3,2,8,7}|. The reason for the ordering is -- as follows: First come all values |length| had for syntactic edges -- going from |self.tail| to |self.head| in the order they appear in the graph -- description. Then come all values the options has for syntactic -- edges going from |self.head| to |self.tail|. The reason for this -- slightly strange behaviour is that many algorithms do not really -- care whether someone writes |a --[length=1] b| or -- |b --[length=1] a|; in both cases they would ``just'' like to know -- that the length is~|1|. -- -- \item There is field called |aligned|, which is an array storing -- the actual syntactic edge objects whose values can be found in the -- array part of the returned table. However, |aligned| contains only -- the syntactic edges pointing ``in the same direction'' as the arc, -- that is, the tail and head of the syntactic edge are the same as -- those of the arc. In the above example, this array would contain -- the edges with the comment numbers |1|, |2|, and |6|. -- -- Using the length of this array and the fact that the ``aligned'' -- values come first in the table, you can easily iterate over the -- |option|'s values of only those edges that are aligned with the arc: -- --\begin{codeexample}[code only, tikz syntax=false] --local a = g:arc(tail.head) -- some arc --local opt = a:optionsArray('length') --local sum = 0 --for i=1,#opt.aligned do -- sum = sum + opt[i] --end --\end{codeexample} -- --\item There is a field called |anti_aligned|, which is an array -- containing exactly the edges in the array part of the table not -- aligned with the arc. The numbering start at |1| as usual, so the -- $i$th entry of this table corresponds to the entry at position $i + -- \verb!#opt.aligned!$ of the table. -- --\end{enumerate} -- function Arc:optionsArray(option) local cache = self.option_cache local t = cache[option] if t then return t end -- Accumulate the edges for which the option is set: local tail = self.tail local head = self.head local s_graph = self.syntactic_digraph local arc = s_graph:arc(tail, head) local aligned = {} if arc then for _,m in ipairs(arc.syntactic_edges) do if m.options[option] ~= nil then aligned[#aligned + 1] = m end end table.sort(aligned, function (a,b) return a.event.index < b.event.index end) end local arc = head ~= tail and s_graph:arc(head, tail) local anti_aligned = {} if arc then for _,m in ipairs(arc.syntactic_edges) do if m.options[option] ~= nil then anti_aligned[#anti_aligned + 1] = m end end table.sort(anti_aligned, function (a,b) return a.event.index < b.event.index end) end -- Now merge them together local t = { aligned = aligned, anti_aligned = anti_aligned } for i=1,#aligned do t[i] = aligned[i].options[option] end for i=1,#anti_aligned do t[#t+1] = anti_aligned[i].options[option] end cache[option] = t return t end --- -- Returns the first option, that is, the first entry of -- |Arc:optionsArray(option)|. However, if the |only_aligned| -- parameter is set to true and there is no option with any aligned -- synactic edge, |nil| is returned. -- -- @param option An option -- @param only_aligned If true, only aligned syntactic edges will be -- considered. -- @return The first entry of the |optionsArray| function Arc:options(option, only_aligned) if only_aligned then local opt = self:optionsArray(option) if #opt.aligned > 0 then return opt[1] end else return self:optionsArray(option)[1] end end --- -- Get an accumulated value of an option of the syntactic edges -- corresponding to an arc. -- -- @param option The option of interest -- @param accumulator A function taking two values. When there are -- more than one syntactic edges corresponding to |self| for which the -- |option| is set, this function will be called repeatedly for the -- different values. The first time it will be called for the first -- two values. Next, it will be called for the result of this call and -- the third value, and so on. -- @param only_aligned A boolean. If true, only the aligned syntactic -- edges will be considered. -- -- @return If the option is not set for any (aligned) syntactic edges -- corresponding to |self|, |nil| is returned. If there is exectly one -- edge, the value of this edge is returned. Otherwise, the result of -- repeatedly applying the |accumulator| function as described -- above. -- -- The result is cached, repeated calls will not invoke the -- |accumulator| function again. -- -- @usage Here is typical usage: --\begin{codeexample}[code only, tikz syntax=false] --local total_length = a:optionsAccumulated('length', function (a,b) return a+b end) or 0 --\end{codeexample} -- function Arc:optionsAccumulated(option, accumulator, only_aligned) local opt = self:options(option) if only_aligned then local aligned = opt.aligned local v = aligned[accumulator] if v == nil then v = opt[1] for i=2,#aligned do v = accumulator(v, opt[i]) end align[accumulator] = v end return v else local v = opt[accumulator] if v == nil then v = opt[1] for i=2,#opt do v = accumulator(v, opt[i]) end opt[accumulator] = v end return v end end --- -- Compute the syntactic head and tail of an arc. For this, we have a -- look at the syntactic digraph underlying the arc. If there is at -- least once syntactic edge going from the arc's tail to the arc's -- head, the arc's tail and head are returned. Otherweise, we test -- whether there is a syntactic edge in the other direction and, if -- so, return head and tail in reverse order. Finally, if there is no -- syntactic edge at all corresponding to the arc in either direction, -- |nil| is returned. -- -- @return The syntactic tail -- @return The syntactic head function Arc:syntacticTailAndHead () local s_graph = self.syntactic_digraph local tail = self.tail local head = self.head if s_graph:arc(tail, head) then return tail, head elseif s_graph:arc(head, tail) then return head, tail end end --- -- Compute the point cloud. -- -- @return This method will return the ``point cloud'' of an arc, -- which is an array of all points that must be rotated and shifted -- along with the endpoints of an edge. -- function Arc:pointCloud () if self.cached_point_cloud then return self.cached_point_cloud -- cached end local cloud = {} local a = self.syntactic_digraph:arc(self.tail,self.head) if a then for _,e in ipairs(a.syntactic_edges) do for _,p in ipairs(e.path) do if type(p) == "table" then cloud[#cloud + 1] = p end end end end self.cached_point_cloud = cloud return cloud end --- -- Compute an event index for the arc. -- -- @return The lowest event index of any edge involved -- in the arc (or nil, if there is no syntactic edge). -- function Arc:eventIndex () if self.cached_event_index then return self.cached_event_index end local head = self.head local tail = self.tail local e = math.huge local a = self.syntactic_digraph:arc(tail,head) if a then for _,m in ipairs(a.syntactic_edges) do e = math.min(e, m.event.index) end end local a = head ~= tail and self.syntactic_digraph:arc(head,tail) if a then for _,m in ipairs(a.syntactic_edges) do e = math.min(e, m.event.index) end end self.cached_event_index = e return e end --- -- The span collector -- -- This method returns the top (that is, smallest) priority of any -- edge involved in the arc. -- -- The priority of an edge is computed as follows: -- -- \begin{enumerate} -- \item If the option |"span priority"| is set, this number -- will be used. -- -- \item If the edge has the same head as the arc, we lookup the key\\ -- |"span priority " .. edge.direction|. If set, we use -- this value. -- -- \item If the edge has a different head from the arc (the arc is -- ``reversed'' with respect to the syntactic edge), we lookup the key -- |"span priority reversed " .. edge.direction|. If set, -- we use this value. -- -- \item Otherwise, we use priority 5. -- \end{enumerate} -- -- @return The priority of the arc, as described above. -- function Arc:spanPriority() if self.cached_span_priority then return self.cached_span_priority end local head = self.head local tail = self.tail local min local g = self.syntactic_digraph local a = g:arc(tail,head) if a then for _,m in ipairs(a.syntactic_edges) do local p = m.options["span priority"] or lib.lookup_option("span priority " .. m.direction, m, g) min = math.min(p or 5, min or math.huge) end end local a = head ~= tail and g:arc(head,tail) if a then for _,m in ipairs(a.syntactic_edges) do local p = m.options["span priority"] or lib.lookup_option("span priority reversed " .. m.direction, m, g) min = math.min(p or 5, min or math.huge) end end self.cached_span_priority = min or 5 return min or 5 end --- -- Sync an |Arc| with its syntactic edges with respect to the path and -- generated options. It causes the following to happen: -- If the |path| field of the arc is |nil|, nothing -- happens with respect to the path. Otherwise, a copy of the |path| -- is created. However, for every path element that is a function, -- this function is invoked with the syntactic edge as its -- parameter. The result of this call should now be a |Coordinate|, -- which will replace the function in the |Path|. -- -- You use this method like this: --\begin{codeexample}[code only, tikz syntax=false] --... --local arc = g:connect(s,t) --arc:setPolylinePath { Coordinate.new(x,y), Coordinate.new(x1,y1) } --... --arc:sync() --\end{codeexample} -- -- Next, similar to the path, the field |generated_options| is -- considered. If it is not |nil|, then all options listed in this -- field are appended to all syntactic edges underlying the arc. -- -- Note that this function will automatically be called for all arcs -- of the |ugraph|, the |digraph|, and the |spanning_tree| of an -- algorithm by the rendering pipeline. -- function Arc:sync() if self.path then local path = self.path local head = self.head local tail = self.tail local a = self.syntactic_digraph:arc(tail,head) if a and #a.syntactic_edges>0 then for _,e in ipairs(a.syntactic_edges) do local clone = path:clone() for i=1,#clone do local p = clone[i] if type(p) == "function" then clone[i] = p(e) if type(clone[i]) == "table" then clone[i] = clone[i]:clone() end end end e.path = clone end end local a = head ~= tail and self.syntactic_digraph:arc(head,tail) if a and #a.syntactic_edges>0 then for _,e in ipairs(a.syntactic_edges) do local clone = path:reversed() for i=1,#clone do local p = clone[i] if type(p) == "function" then clone[i] = p(e) if type(clone[i]) == "table" then clone[i] = clone[i]:clone() end end end e.path = clone end end end if self.generated_options then local head = self.head local tail = self.tail local a = self.syntactic_digraph:arc(tail,head) if a and #a.syntactic_edges>0 then for _,e in ipairs(a.syntactic_edges) do for _,o in ipairs(self.generated_options) do e.generated_options[#e.generated_options+1] = o end end end local a = head ~= tail and self.syntactic_digraph:arc(head,tail) if a and #a.syntactic_edges>0 then for _,e in ipairs(a.syntactic_edges) do for _,o in ipairs(self.generated_options) do e.generated_options[#e.generated_options+1] = o end end end end end --- -- This method returns a ``coordinate factory'' that can be used as -- the coordinate of a |moveto| at the beginning of a path starting at -- the |tail| of the arc. Suppose you want to create a path starting -- at the tail vertex, going to the coordinate $(10,10)$ and ending at -- the head vertex. The trouble is that when you create the path -- corresponding to this route, you typically do not know where the -- tail vertex is going to be. Even if that \emph{has} already been -- settled, you will still have the problem that different edges -- underlying the arc may wish to start their paths at different -- anchors inside the tail vertex. In such cases, you use this -- method to get a function that will, later on, compute the correct -- position of the anchor as needed. -- -- Here is the code you would use to create the abovementioned path: -- --\begin{codeexample}[code only, tikz syntax=false] --local a = g:connect(tail,head) --... --arc.path = Path.new() --arc.path:appendMoveto(arc:tailAnchorForArcPath()) --arc.path:appendLineto(10, 10) --arc.path:appendLineto(arc:headAnchorForArcPath()) --\end{codeexample} -- -- Normally, however, you will not write code as detailed as the above -- and you would just write instead of the last three lines: -- --\begin{codeexample}[code only, tikz syntax=false] --arc:setPolylinePath { Coordinate.new (10, 10) } --\end{codeexample} function Arc:tailAnchorForArcPath() return function (edge) local a = edge.options['tail anchor'] if a == "" then a = "center" end return self.tail:anchor(a) + self.tail.pos end end --- -- See |Arc:tailAnchorForArcPath|. function Arc:headAnchorForArcPath() return function (edge) local a = edge.options['head anchor'] if a == "" then a = "center" end return self.head:anchor(a) + self.head.pos end end --- -- Setup the |path| field of an arc in such a way that it corresponds -- to a sequence of straight line segments starting at the tail's -- anchor and ending at the head's anchor. -- -- @param coordinates An array of |Coordinates| through which the line -- will go through. function Arc:setPolylinePath(coordinates) local p = Path.new () p:appendMoveto(self:tailAnchorForArcPath()) for _,c in ipairs(coordinates) do p:appendLineto(c) end p:appendLineto(self:headAnchorForArcPath()) self.path = p end -- Returns a string representation of an arc. This is mainly for debugging -- -- @return The Arc as string. -- function Arc:__tostring() return tostring(self.tail) .. "->" .. tostring(self.head) end -- Done return Arc
gpl-2.0
shahabsaf1/fucker
plugins/admin.lua
230
6382
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](whois) (%d+)$" }, run = run, } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
gpl-2.0
rudolfmleziva/AdministratorTeritorial
cocos2d/cocos/scripting/lua-bindings/auto/api/ArmatureAnimation.lua
10
4411
-------------------------------- -- @module ArmatureAnimation -- @extend ProcessBase -- @parent_module ccs -------------------------------- -- -- @function [parent=#ArmatureAnimation] getSpeedScale -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Pause the Process -- @function [parent=#ArmatureAnimation] pause -- @param self -------------------------------- -- Scale animation play speed.<br> -- param animationScale Scale value -- @function [parent=#ArmatureAnimation] setSpeedScale -- @param self -- @param #float speedScale -------------------------------- -- Init with a Armature<br> -- param armature The Armature ArmatureAnimation will bind to -- @function [parent=#ArmatureAnimation] init -- @param self -- @param #ccs.Armature armature -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ArmatureAnimation] playWithIndexes -- @param self -- @param #array_table movementIndexes -- @param #int durationTo -- @param #bool loop -------------------------------- -- Play animation by animation name.<br> -- param animationName The animation name you want to play<br> -- param durationTo The frames between two animation changing-over.<br> -- It's meaning is changing to this animation need how many frames<br> -- -1 : use the value from MovementData get from flash design panel<br> -- param loop Whether the animation is loop<br> -- loop < 0 : use the value from MovementData get from flash design panel<br> -- loop = 0 : this animation is not loop<br> -- loop > 0 : this animation is loop -- @function [parent=#ArmatureAnimation] play -- @param self -- @param #string animationName -- @param #int durationTo -- @param #int loop -------------------------------- -- Go to specified frame and pause current movement. -- @function [parent=#ArmatureAnimation] gotoAndPause -- @param self -- @param #int frameIndex -------------------------------- -- Resume the Process -- @function [parent=#ArmatureAnimation] resume -- @param self -------------------------------- -- Stop the Process -- @function [parent=#ArmatureAnimation] stop -- @param self -------------------------------- -- -- @function [parent=#ArmatureAnimation] update -- @param self -- @param #float dt -------------------------------- -- -- @function [parent=#ArmatureAnimation] getAnimationData -- @param self -- @return AnimationData#AnimationData ret (return value: ccs.AnimationData) -------------------------------- -- -- @function [parent=#ArmatureAnimation] playWithIndex -- @param self -- @param #int animationIndex -- @param #int durationTo -- @param #int loop -------------------------------- -- Get current movementID<br> -- return The name of current movement -- @function [parent=#ArmatureAnimation] getCurrentMovementID -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ArmatureAnimation] setAnimationData -- @param self -- @param #ccs.AnimationData data -------------------------------- -- Go to specified frame and play current movement.<br> -- You need first switch to the movement you want to play, then call this function.<br> -- example : playByIndex(0);<br> -- gotoAndPlay(0);<br> -- playByIndex(1);<br> -- gotoAndPlay(0);<br> -- gotoAndPlay(15); -- @function [parent=#ArmatureAnimation] gotoAndPlay -- @param self -- @param #int frameIndex -------------------------------- -- -- @function [parent=#ArmatureAnimation] playWithNames -- @param self -- @param #array_table movementNames -- @param #int durationTo -- @param #bool loop -------------------------------- -- Get movement count -- @function [parent=#ArmatureAnimation] getMovementCount -- @param self -- @return long#long ret (return value: long) -------------------------------- -- Create with a Armature<br> -- param armature The Armature ArmatureAnimation will bind to -- @function [parent=#ArmatureAnimation] create -- @param self -- @param #ccs.Armature armature -- @return ArmatureAnimation#ArmatureAnimation ret (return value: ccs.ArmatureAnimation) -------------------------------- -- js ctor -- @function [parent=#ArmatureAnimation] ArmatureAnimation -- @param self return nil
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/cup_of_chamomile_tea.lua
12
1477
----------------------------------------- -- ID: 4603 -- Item: cup_of_chamomile_tea -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic 8 -- Vitality -2 -- Charisma 2 -- Magic Regen While Healing 1 -- Sleep resistance -30 ----------------------------------------- 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,4603); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 8); target:addMod(MOD_VIT, -2); target:addMod(MOD_CHR, 2); target:addMod(MOD_MPHEAL, 1); target:addMod(MOD_SLEEPRES, -30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 8); target:delMod(MOD_VIT, -2); target:delMod(MOD_CHR, 2); target:delMod(MOD_MPHEAL, 1); target:delMod(MOD_SLEEPRES, -30); end;
gpl-3.0
zzh442856860/skynet
lualib/multicast.lua
66
2283
local skynet = require "skynet" local mc = require "multicast.core" local multicastd local multicast = {} local dispatch = setmetatable({} , {__mode = "kv" }) local chan = {} local chan_meta = { __index = chan, __gc = function(self) self:unsubscribe() end, __tostring = function (self) return string.format("[Multicast:%x]",self.channel) end, } local function default_conf(conf) conf = conf or {} conf.pack = conf.pack or skynet.pack conf.unpack = conf.unpack or skynet.unpack return conf end function multicast.new(conf) assert(multicastd, "Init first") local self = {} conf = conf or self self.channel = conf.channel if self.channel == nil then self.channel = skynet.call(multicastd, "lua", "NEW") end self.__pack = conf.pack or skynet.pack self.__unpack = conf.unpack or skynet.unpack self.__dispatch = conf.dispatch return setmetatable(self, chan_meta) end function chan:delete() local c = assert(self.channel) skynet.send(multicastd, "lua", "DEL", c) self.channel = nil self.__subscribe = nil end function chan:publish(...) local c = assert(self.channel) skynet.call(multicastd, "lua", "PUB", c, mc.pack(self.__pack(...))) end function chan:subscribe() local c = assert(self.channel) if self.__subscribe then -- already subscribe return end skynet.call(multicastd, "lua", "SUB", c) self.__subscribe = true dispatch[c] = self end function chan:unsubscribe() if not self.__subscribe then -- already unsubscribe return end local c = assert(self.channel) skynet.send(multicastd, "lua", "USUB", c) self.__subscribe = nil end local function dispatch_subscribe(channel, source, pack, msg, sz) local self = dispatch[channel] if not self then mc.close(pack) error ("Unknown channel " .. channel) end if self.__subscribe then local ok, err = pcall(self.__dispatch, self, source, self.__unpack(msg, sz)) mc.close(pack) assert(ok, err) else -- maybe unsubscribe first, but the message is send out. drop the message unneed mc.close(pack) end end local function init() multicastd = skynet.uniqueservice "multicastd" skynet.register_protocol { name = "multicast", id = skynet.PTYPE_MULTICAST, unpack = mc.unpack, dispatch = dispatch_subscribe, } end skynet.init(init, "multicast") return multicast
mit
openwrt-es/openwrt-luci
applications/luci-app-pagekitec/luasrc/model/cbi/pagekitec.lua
10
1106
m = Map("pagekitec", translate("PageKite"), translate([[ <p/>Note: you need a working PageKite account, or at least, your own running front end for this form to work. Visit <a href="https://pagekite.net/home/">your account</a> to set up a name for your router and get a secret key for the connection. <p/><em>Note: this web configurator only supports some very very basic uses of pagekite.</em> ]])) s = m:section(TypedSection, "pagekitec", translate("PageKite")) s.anonymous = true p = s:option(Value, "kitename", translate("Kite Name")) p = s:option(Value, "kitesecret", translate("Kite Secret")) p.password = true p = s:option(Flag, "static", translate("Static Setup"), translate([[Static setup, disable FE failover and DDNS updates, set this if you are running your own frontend without a pagekite.me account]])) p = s:option(Flag, "simple_http", translate("Basic HTTP"), translate([[Enable a tunnel to the local HTTP server (in most cases, this admin site)]])) p = s:option(Flag, "simple_ssh", translate("Basic SSH"), translate([[Enable a tunnel to the local SSH server]])) return m
apache-2.0
mortal-city/zedspambotteleg
plugins/ingroup.lua
24
53144
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.5', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_arabic = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'به ریلیم جدید ما خوش آمدید') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.5', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_arabic = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'ریلیم اضافه شد!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.5', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_arabic = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'شما صاحب گروه شدید') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', lock_link = 'yes', sticker = 'ok', version = '3.5', groupmodel = 'normal', tag = 'no', lock_badw = 'no', lock_english = 'no', lock_arabic = 'no', welcome = 'group' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'گروه اضافه شد و شما صاحب آن شدید') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'ریلیم حذف شد') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'گروه حذف شد') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local lock_link = "Yes" if data[tostring(msg.to.id)]['settings']['lock_link'] then lock_link = data[tostring(msg.to.id)]['settings']['lock_link'] end local sticker = "ok" if data[tostring(msg.to.id)]['settings']['sticker'] then sticker = data[tostring(msg.to.id)]['settings']['sticker'] end local tag = "no" if data[tostring(msg.to.id)]['settings']['tag'] then tag = data[tostring(msg.to.id)]['settings']['tag'] end local lock_badw = "no" if data[tostring(msg.to.id)]['settings']['lock_badw'] then lock_badw = data[tostring(msg.to.id)]['settings']['lock_badw'] end local lock_english = "no" if data[tostring(msg.to.id)]['settings']['lock_english'] then lock_username = data[tostring(msg.to.id)]['settings']['lock_english'] end local lock_arabic = "no" if data[tostring(msg.to.id)]['settings']['lock_arabic'] then lock_arabic = data[tostring(msg.to.id)]['settings']['lock_arabic'] end local welcome = "group" if data[tostring(msg.to.id)]['settings']['welcome'] then welcome = data[tostring(msg.to.id)]['settings']['welcome'] end local settings = data[tostring(target)]['settings'] local text = "تنظیمات گروه:\n⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙\n>قفل نام گروه : "..settings.lock_name.."\n>قفل عکس گروه : "..settings.lock_photo.."\n>قفل اعضا : "..settings.lock_member.."\n>ممنوعیت ارسال لینک : "..lock_link.."\n>حساسیت اسپم : "..NUM_MSG_MAX.."\n>قفل ربات ها : "..bots_protection.."\n>قفل تگ : "..tag.."\n>قفل اینگلیسی :"..lock_english.."\n>قفل فحش : "..lock_badw.."\n>Sbss Open Source Version\n" return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "قفط مدیران" end local data_cat = 'توضیحات' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'توضیحات گروه به این متن تغییر یافت:\n'..about end local function get_description(msg, data) local data_cat = 'توضیحات' if not data[tostring(msg.to.id)][data_cat] then return 'توضیحی موجود نیست' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'درباره'..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "قفط مدیران" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'عربی از قبل قفل است' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'عربی قفل شد' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'عربی از قبل آزاد است' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'عربی آزاد شد' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'yes' then return 'تگ کردن از قبل قفل است🔒' else data[tostring(target)]['settings']['tag'] = 'yes' save_data(_config.moderation.data, data) return 'تگردن ممنوع شد✅🔒' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'no' then return 'تگ کردن از قبل آزاد است🔓' else data[tostring(target)]['settings']['tag'] = 'no' save_data(_config.moderation.data, data) return 'تگ کردن آزاد شد✅🔓' end end local function lock_group_username(msg, data, target) if not is_momod(msg) then return "قفط مدیران❗️" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'yes' then return 'ایگلیسی از قبل قفل است🔒' else data[tostring(target)]['settings']['lock_english'] = 'yes' save_data(_config.moderation.data, data) return 'اینگلیسی قفل شد✅🔒' end end local function unlock_group_english(msg, data, target) if not is_momod(msg) then return "قفط مدیران❗️" end local group_english_lock = data[tostring(target)]['settings']['lock_english'] if group_english_lock == 'no' then return 'اینگلیسی از قبل باز است🔓' else data[tostring(target)]['settings']['lock_english'] = 'no' save_data(_config.moderation.data, data) return 'اینگلیسی ازاد شد✅🔓' end end local function lock_group_badw(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'yes' then return 'فحاشی از قبل ممنوع است🔒' else data[tostring(target)]['settings']['lock_badw'] = 'yes' save_data(_config.moderation.data, data) return 'فحاشی قفل شد✅🔒' end end local function unlock_group_badw(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'no' then return 'فحاشی از قبل آزاد است🔓' else data[tostring(target)]['settings']['lock_badw'] = 'no' save_data(_config.moderation.data, data) return 'فحاشی آزاد شد✅🔓' end end local function lock_group_link(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'ارسال لینک از قبل ممنوع است🔒' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'ارسال لینک ممنوع شد✅🔒' end end local function unlock_group_link(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'ارسال لینک از قبل آزاد است🔓' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'lارسال لینک آزاد شد✅🔓' end end local function lock_group_username(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران❗️" end local group_username_lock = data[tostring(target)]['settings']['lock_username'] if group_username_lock == 'yes' then return 'یوزر نیم از قبل قفل است🔒' else data[tostring(target)]['settings']['lock_username'] = 'yes' save_data(_config.moderation.data, data) return 'یوزر نیم آزاد شد✅🔒' end end local function unlock_group_username(msg, data, target) if not is_momod(msg) then return "فقط مدیران❗️" end local group_username_lock = data[tostring(target)]['settings']['lock_username'] if group_username_lock == 'no' then return 'ارسال یوزر نیم از قبل آزاد است🔓' else data[tostring(target)]['settings']['lock_username'] = 'no' save_data(_config.moderation.data, data) return 'ارسال یوزر نیم آژاد شد✅🔓' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "قفط مدیران" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'قفل ربات ها از قبل فعال است' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'ورود ربات ها قفل شد' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'ورود ربات ها از قبل آزاد است' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'ورود ربات ها ازاد شد' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'نام گروه از قبل قفل است' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'نام گروه قفل شد' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'نام گروه از قبل باز است' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'نام گروه باز شد' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "فقط توسط گلوبال ادمین ها" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'ارسال پیام سریع ممنوع از قبل ممنوع بود' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'اسپم قفل شد' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "فقط برای گلوبال ادمین ها" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'اسپم قفل نیست!' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'ارسال سریع پیام آزاد شد' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'ورود اعضا از قبل قفل است' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'ورود اعضا قفل شد' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'عضو گیری ازاد است' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'عضو گیری ازاد شد' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "فقط برای مدیران" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'خروج از قبل ممنوع بود' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'کسانی که خارج میشوند بن خواهند شد' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "فقط مدیران!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'خروج آزاد بود' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'خروج آزاد شد' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'عکس گروه قفل نیست' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'عکس گروه باز شد' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "فقط مدیران" end local data_cat = 'قوانین' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'قوانین گروه به این متن تغییر یافت:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'گروه از قبل اد شده' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'ریلیم از قبل اد شده' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'گروه اضافه نشده' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "شما ادمین نیستید" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'ریلیم اد نشده' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'قوانین' if not data[tostring(msg.to.id)][data_cat] then return 'قانونی موجود نیست' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'قوانین گروه:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'عکس ذخیره شد!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'گروه اضافه نشده') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' از قبل مدیر است') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' ترفیع یافت') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'گروه اضافه نشده') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' مدیر نیست !') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' تنزل یافت') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setleader_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as leader") local text = msg.from.print_name:gsub("_", " ").." اکنون صاحب گروه است " return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'ترفیع' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'تنزل' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'گروه اد نشده' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'دراین گروه هیچ مدیری وجود ندارد' end local i = 1 local message = '\nلیست مدیر های گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'اضافه' and not matches[2] then if is_realm(msg) then return 'خطا : از قبل ریلیم بوده' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'اضافه' and matches[2] == 'ریلیم' then if is_group(msg) then return 'خطا : اینجا یک گروه است' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'حذف' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'حذف' and matches[2] == 'ریلیم' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'تنظیم نام' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'تنظیم عکس' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'لطفا عکس جدید گروه را ارسال کنید' end if matches[1] == 'ترفیع' and not matches[2] then if not is_owner(msg) then return "فقط توسط صاحب گروه" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'ترفیع' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "فقط توسط صاحب گروه" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'ترفیع', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'تنزل' and not matches[2] then if not is_owner(msg) then return "فقط توسط صاحب گروه" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'تنزل' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "فقط توسط صاحب گروه" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "شما نمیتوانید مقام خود را حذف کنید" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'تنزل', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'لیست مدیران' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'توضیحات' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'قوانین' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'تنظیم' then if matches[2] == 'قوانین' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'توضیحات' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'قفل' then local target = msg.to.id if matches[2] == 'نام' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'اعضا' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'اسپم' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'ربات ها' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'لینک' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link🔒 ") return lock_group_link(msg, data, target) end if matches[2] == 'تگ' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag🔒 ") return lock_group_tag(msg, data, target) end if matches[2] == 'فحش' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked badw🔒 ") return lock_group_badw(msg, data, target) end if matches[2] == 'اینگلیسی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english🔒 ") return lock_group_english(msg, data, target) end if matches[2] == 'خروج' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'بازکردن' then local target = msg.to.id if matches[2] == 'نام' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'اعضا' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'عکس' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'اسپم' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'ربات ها' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'لینک' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link🔓 ") return unlock_group_link(msg, data, target) end if matches[2] == 'تگ' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag🔓 ") return unlock_group_tag(msg, data, target) end if matches[2] == 'فحش' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked badw🔓 ") return unlock_group_badw(msg, data, target) end if matches[2] == 'اینگلیسی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english🔓 ") return unlock_group_english(msg, data, target) end if matches[2] == 'خروج' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' or matches[1] == 'تنظیمات' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'لینک جدید' and not is_realm(msg) then if not is_momod(msg) then return "فقط برای مدیران" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*خطا : \nربات سازنده گروه نیست') end send_large_msg(receiver, "لینک جدید ساخته شد") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'لینک' then if not is_momod(msg) then return "فقط مدیران" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "اول با لینک جدید یک لینک جدید بسازید" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link end if matches[1] == 'لینک خصوصی' then if not is_momod(msg) then return "فقط برای مدیران" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "اول با لینک جدید یک لینک جدید بسازید" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link) end if matches[1] == 'دارنده' and matches[2] then if not is_owner(msg) then return "شما مجاز نیستید" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as leader") local text = matches[2].." added as leader" return text end if matches[1] == 'دارنده' and not matches[2] then if not is_owner(msg) then return "شما مجاز نیستید" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setleader_by_reply, false) end end if matches[1] == 'صاحب گروه' then local group_leader = data[tostring(msg.to.id)]['set_owner'] if not group_leader then return "no leader,ask admins in support groups to set leader for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /leader") return "آیدی صاحب گروه : ["..group_leader..']' end if matches[1] == 'صاحب' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as leader" send_large_msg(receiver, text) return end if matches[1] == 'حساسیت' then if not is_momod(msg) then return "شما مجاز نیستید" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "عددی از بین 5 و 20 انتخاب کنید" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'حساسیت اسپم تغییر یافت به '..matches[2] end if matches[1] == 'پاک کردن' then if not is_owner(msg) then return "شما مجاز نیستید" end if matches[2] == 'اعضا' then if not is_owner(msg) then return "شما مجاز نیستید" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'مدیران' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'مدیری در گروه نیست' end local message = '\nلیست مدیران گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' and matches[2] == 'قوانین' then local data_cat = 'قوانین' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'توضیحات' then local data_cat = 'توضیحات' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'راهنما' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'کد' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^(اضافه)$", "^(اضافه) (ریلیم)$", "^(حذف)$", "^(حذف) (ریلیم)$", "^(قوانین)$", "^(توضیحات)$", "^(تنظیم نام) (.*)$", "^(تنظیم عکس)$", "^(ترفیع) (.*)$", "^(ترفیع)", "^(راهنما)$", "^(پاک کردن) (.*)$", "^(kill) (chat)$", "^(kill) (realm)$", "^(تنزل) (.*)$", "^(تنزل)", "^(تنظیم) ([^%s]+) (.*)$", "^(قفل) (.*)$", "^(دارنده) (%d+)$", "^(دارنده)", "^(صاحب گروه)$", "^(کد) (.*)$", "^(صاحب) (%d+) (%d+)$",-- (group id) (leader id) "^(بازکردن) (.*)$", "^(حساسیت) (%d+)$", "^(تنظیمات)$", -- "^(public) (.*)$", "^(لیست مدیران)$", "^(لینک جدید)$", "^(لینک)$", "^(kickinactive)$", "^(kickinactive) (%d+)$", "^(لینک خصوصی)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Northern_San_dOria/Zone.lua
13
4726
----------------------------------- -- -- Zone: Northern_San_dOria (231) -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/globals/events/harvest_festivals"); require("scripts/globals/zone"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) SetExplorerMoogles(17723648); zone:registerRegion(1, -7,-3,110, 7,-1,155); applyHalloweenNpcCostumes(zone:getID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 0x0217; end player:setPos(0,0,-11,191); player:setHomePoint(); end -- MOG HOUSE EXIT if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(130,-0.2,-3,160); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); end -- RDM AF3 CS if (player:getVar("peaceForTheSpiritCS") == 5 and player:getFreeSlotsCount() >= 1) then cs = 0x0031; elseif (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status") == 1) then --EMERALD_WATERS-- COP 3-3A: San d'Oria Route player:setVar("EMERALD_WATERS_Status",2); cs = 0x000E; elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 0) then cs = 0x0001; elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 4) then cs = 0x0000; elseif (player:hasCompletedMission(SANDORIA,COMING_OF_AGE) and tonumber(os.date("%j")) == player:getVar("Wait1DayM8-1_date")) then cs = 0x0010; 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) switch (region:GetRegionID()): caseof { [1] = function (x) -- Chateau d'Oraguille access pNation = player:getNation(); currentMission = player:getCurrentMission(pNation) if ((pNation == 0 and player:getRank() >= 2) or (pNation > 0 and player:hasCompletedMission(pNation,5) == 1) or (currentMission >= 5 and currentMission <= 9) or (player:getRank() >= 3)) then player:startEvent(0x0239); else player:startEvent(0x0238); end end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0217) then player:messageSpecial(ITEM_OBTAINED,0x218); elseif (csid == 0x0001) then player:setVar("MissionStatus",1); elseif (csid == 0x0000) then player:setVar("MissionStatus",5); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 0x0239) then player:setPos(0,0,-13,192,0xe9); elseif (csid == 0x0031) then player:addTitle(PARAGON_OF_RED_MAGE_EXCELLENCE); player:addItem(12513); player:messageSpecial(ITEM_OBTAINED, 12513); -- Warlock's Chapeau player:setVar("peaceForTheSpiritCS",0); player:addFame(SANDORIA,AF3_FAME); player:completeQuest(SANDORIA,PEACE_FOR_THE_SPIRIT); elseif (csid == 0x0010) then player:setVar("Wait1DayM8-1_date",0); player:setVar("Mission8-1Completed",1); end end;
gpl-3.0
CCAAHH/telegram-bot-supergroups
plugins/meme.lua
637
5791
local helpers = require "OAuth.helpers" local _file_memes = './data/memes.lua' local _cache = {} local function post_petition(url, arguments) local response_body = {} local request_constructor = { url = url, method = "POST", sink = ltn12.sink.table(response_body), headers = {}, redirect = false } local source = arguments if type(arguments) == "table" then local source = helpers.url_encode_arguments(arguments) end request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded" request_constructor.headers["Content-Length"] = tostring(#source) request_constructor.source = ltn12.source.string(source) local ok, response_code, response_headers, response_status_line = http.request(request_constructor) if not ok then return nil end response_body = json:decode(table.concat(response_body)) return response_body end local function upload_memes(memes) local base = "http://hastebin.com/" local pet = post_petition(base .. "documents", memes) if pet == nil then return '', '' end local key = pet.key return base .. key, base .. 'raw/' .. key end local function analyze_meme_list() local function get_m(res, n) local r = "<option.*>(.*)</option>.*" local start = string.find(res, "<option.*>", n) if start == nil then return nil, nil end local final = string.find(res, "</option>", n) + #"</option>" local sub = string.sub(res, start, final) local f = string.match(sub, r) return f, final end local res, code = http.request('http://apimeme.com/') local r = "<option.*>(.*)</option>.*" local n = 0 local f, n = get_m(res, n) local ult = {} while f ~= nil do print(f) table.insert(ult, f) f, n = get_m(res, n) end return ult end local function get_memes() local memes = analyze_meme_list() return { last_time = os.time(), memes = memes } end local function load_data() local data = load_from_file(_file_memes) if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then data = get_memes() -- Upload only if changed? link, rawlink = upload_memes(table.concat(data.memes, '\n')) data.link = link data.rawlink = rawlink serialize_to_file(data, _file_memes) end return data end local function match_n_word(list1, list2) local n = 0 for k,v in pairs(list1) do for k2, v2 in pairs(list2) do if v2:find(v) then n = n + 1 end end end return n end local function match_meme(name) local _memes = load_data() local name = name:lower():split(' ') local max = 0 local id = nil for k,v in pairs(_memes.memes) do local n = match_n_word(name, v:lower():split(' ')) if n > 0 and n > max then max = n id = v end end return id end local function generate_meme(id, textup, textdown) local base = "http://apimeme.com/meme" local arguments = { meme=id, top=textup, bottom=textdown } return base .. "?" .. helpers.url_encode_arguments(arguments) end local function get_all_memes_names() local _memes = load_data() local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n' for k, v in pairs(_memes.memes) do text = text .. '- ' .. v .. '\n' end text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/' return text end local function callback_send(cb_extra, success, data) if success == 0 then send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'list' then local _memes = load_data() return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link elseif matches[1] == 'listall' then if not is_sudo(msg) then return "You can't list this way, use \"!meme list\"" else return get_all_memes_names() end elseif matches[1] == "search" then local meme_id = match_meme(matches[2]) if meme_id == nil then return "I can't match that search with any meme." end return "With that search your meme is " .. meme_id end local searchterm = string.gsub(matches[1]:lower(), ' ', '') local meme_id = _cache[searchterm] or match_meme(matches[1]) if not meme_id then return 'I don\'t understand the meme name "' .. matches[1] .. '"' end _cache[searchterm] = meme_id print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3]) local url_gen = generate_meme(meme_id, matches[2], matches[3]) send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen}) return nil end return { description = "Generate a meme image with up and bottom texts.", usage = { "!meme search (name): Return the name of the meme that match.", "!meme list: Return the link where you can see the memes.", "!meme listall: Return the list of all memes. Only admin can call it.", '!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.', '!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.', }, patterns = { "^!meme (search) (.+)$", '^!meme (list)$', '^!meme (listall)$', '^!meme (.+) "(.*)" "(.*)"$', '^!meme "(.+)" "(.*)" "(.*)"$', "^!meme (.+) %- (.*) %- (.*)$" }, run = run }
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/West_Ronfaure/npcs/qm2.lua
3
1487
----------------------------------- -- Area: West Ronfaure -- NPC: qm2 (???) -- Involved in Quest: The Dismayed Customer -- !pos -550 -0 -542 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA, THE_DISMAYED_CUSTOMER) == QUEST_ACCEPTED and player:getVar("theDismayedCustomer") == 2) then player:addKeyItem(GULEMONTS_DOCUMENT); player:messageSpecial(KEYITEM_OBTAINED, GULEMONTS_DOCUMENT); player:setVar("theDismayedCustomer", 0); else player:messageSpecial(DISMAYED_CUSTOMER); 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
SinisterRectus/Discordia
libs/utils/Clock.lua
1
1268
--[=[ @c Clock x Emitter @t ui @mt mem @d Used to periodically execute code according to the ticking of the system clock instead of an arbitrary interval. ]=] local timer = require('timer') local Emitter = require('utils/Emitter') local date = os.date local setInterval, clearInterval = timer.setInterval, timer.clearInterval local Clock = require('class')('Clock', Emitter) function Clock:__init() Emitter.__init(self) end --[=[ @m start @op utc boolean @r nil @d Starts the main loop for the clock. If a truthy argument is passed, then UTC time is used; otherwise, local time is used. As the clock ticks, an event is emitted for every `os.date` value change. The event name is the key of the value that changed and the event argument is the corresponding date table. ]=] function Clock:start(utc) if self._interval then return end local fmt = utc and '!*t' or '*t' local prev = date(fmt) self._interval = setInterval(1000, function() local now = date(fmt) for k, v in pairs(now) do if v ~= prev[k] then self:emit(k, now) end end prev = now end) end --[=[ @m stop @r nil @d Stops the main loop for the clock. ]=] function Clock:stop() if self._interval then clearInterval(self._interval) self._interval = nil end end return Clock
mit
jpmac26/PGE-Project
Content/configs/SMBX/script/player/mario.lua
1
1619
class 'marioPlayer' function marioPlayer:__init(plr_obj) self.plr_obj = plr_obj if(self.plr_obj.stateID==1)then self.plr_obj.health = 1 elseif(self.plr_obj.stateID>=2)then self.plr_obj.health = 2 end end function marioPlayer:onLoop(tickTime) if(Settings.isDebugInfoShown())then Renderer.printText("It's me, Mario!", 100, 430, 0, 15, 0xFFFF0055) Renderer.printText("Player x: "..tostring(self.plr_obj.x), 100, 460, 0, 15, 0xFFFF0055) Renderer.printText("Player y: "..tostring(self.plr_obj.y), 100, 400, 0, 15, 0xFFFF0055) end if((self.plr_obj.stateID==4) or (self.plr_obj.stateID==5))then if((not self.plr_obj.onGround) and self.plr_obj:getKeyState(KEY_JUMP) )then if(self.plr_obj.speedY>=2)then self.plr_obj.speedY=2 self.plr_obj:setAnimation(15, 128) end end end end function marioPlayer:onHarm(harmEvent) processPlayerHarm(self.plr_obj, harmEvent) end function marioPlayer:onTakeNpc(npcObj) ProcessPlayerPowerUP(self.plr_obj, npcObj) end function marioPlayer:onKeyPressed(keyType) if( (self.plr_obj.stateID==3) and (keyType==KEY_RUN) and (not self.plr_obj.isDucking) )then self.plr_obj:playAnimationOnce(7, 128, true, false, 1) ShootFireball(self.plr_obj) end if( (self.plr_obj.stateID==6) and (keyType==KEY_RUN) and (not self.plr_obj.isDucking) )then self.plr_obj:playAnimationOnce(7, 128, true, false, 1) ShootHammer(self.plr_obj) end end return marioPlayer
gpl-3.0
openwrt-es/openwrt-luci
applications/luci-app-dnscrypt-proxy/luasrc/model/cbi/dnscrypt-proxy/cfg_resolvcrypt_tab.lua
18
1030
-- Copyright 2017 Dirk Brenken (dev@brenken.org) -- This is free software, licensed under the Apache License, Version 2.0 local nxfs = require("nixio.fs") local util = require("luci.util") local res_input = "/etc/resolv-crypt.conf" if not nxfs.access(res_input) then m = SimpleForm("error", nil, translate("Input file not found, please check your configuration.")) m.reset = false m.submit = false return m end m = SimpleForm("input", nil) m:append(Template("dnscrypt-proxy/config_css")) m.submit = translate("Save") m.reset = false s = m:section(SimpleSection, nil, translate("This form allows you to modify the content of the resolv-crypt configuration file (/etc/resolv-crypt.conf).")) f = s:option(TextValue, "data") f.rows = 20 f.rmempty = true function f.cfgvalue() return nxfs.readfile(res_input) or "" end function f.write(self, section, data) return nxfs.writefile(res_input, "\n" .. util.trim(data:gsub("\r\n", "\n")) .. "\n") end function s.handle(self, state, data) return true end return m
apache-2.0
petoju/awesome
tests/examples/wibox/container/defaults/margin.lua
5
1382
--DOC_HIDE_ALL --DOC_GEN_IMAGE local wibox = require("wibox") local beautiful = require("beautiful") return { nil, { nil, { { text = "Before", align = "center", valign = "center", widget = wibox.widget.textbox, }, bg = beautiful.bg_highlight, widget = wibox.container.background }, nil, expand = "none", layout = wibox.layout.align.horizontal, }, nil, expand = "none", layout = wibox.layout.align.vertical, }, { nil, { nil, { { { text = "After", align = "center", valign = "center", widget = wibox.widget.textbox, }, bg = beautiful.bg_highlight, widget = wibox.container.background }, top = 5, left = 20, color = "#ff0000", widget = wibox.container.margin, }, nil, expand = "none", layout = wibox.layout.align.horizontal, }, nil, expand = "none", layout = wibox.layout.align.vertical, } --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/West_Sarutabaruta/mobs/Mandragora.lua
3
1059
----------------------------------- -- Area: West Sarutabaruta -- MOB: Mandragora -- Note: PH for Tom Tit Tat ----------------------------------- require("scripts/globals/fieldsofvalor"); require("scripts/zones/West_Sarutabaruta/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player,mob,26,1); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Tom_Tit_Tat_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Tom_Tit_Tat"); if (ToD <= os.time() and GetMobAction(Tom_Tit_Tat) == 0) then if (math.random(1,15) == 5) then UpdateNMSpawnPoint(Tom_Tit_Tat); GetMobByID(Tom_Tit_Tat):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Tom_Tit_Tat", mobID); DisallowRespawn(mobID, true); end end end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Abyssea-Vunkerl/mobs/Sippoy.lua
16
1198
----------------------------------- -- Area: Abyssea - Vunkerl -- Mob: Sippoy ----------------------------------- require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) if (mob:getHPP() < 50) then mob:setMobMod(MOBMOD_SPELL_LIST, 159); else -- I'm assuming that if it heals up, it goes back to the its original spell list. mob:setMobMod(MOBMOD_SPELL_LIST, 158); -- This 'else' can be removed if that isn't the case, and a localVar added so it only execs once. end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(SIPPOY_CAPTURER); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Temenos/bcnms/temenos_northern_tower.lua
35
1173
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/keyitems"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[Temenos_N_Tower]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1299),TEMENOS); HideTemenosDoor(GetInstanceRegion(1299)); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[Temenos_N_Tower]UniqueID")); player:setVar("LimbusID",1299); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
llual/VIPTEAM
plugins/l2.lua
2
4478
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ By : @shaD_o ▀▄ ▄▀ ▀▄ ▄▀ BY dev (shaD_o) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY shaD_o ▀▄ ▄▀ ▀▄ ▄▀ chhanale : @vip_team1 ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄ --]] do local function run(msg,matches) if not is_momod(msg) then return "🙇🏻 عذرا "..msg.from.first_name.."\n" .."🚀للمدراء فقط " end if is_momod(msg) then return "مرحبا عزيزي 🔮 "..msg.from.first_name.."\n" .."🚀اسم المجموعة : ".."\n"..msg.to.title.."\n" .." ".."\n" ..[[ اوامر حماية المجموعة 🕹 تعمل جميع لاوامر ب {/!#} 💡 🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹 اوامر قفل الميديا ⁉️ /قفل 🕹 للمنع 🕹 /فتح 🕹 للسماح 🕹 🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹 📊/قفل الصور : لقفل الصور 🕹 📊/فتح الصور : لفتح الصور 🕹 📊/قفل المتحركة : لقفل الصور المتحركة 🕹 📊/فتح المتحركة : لفتح الصور المتحركة 🕹 📊/قفل الفديو : لقفل الفديو 🕹 📊/فتح الفديو : لفتح الفديو 🕹 📊/قفل الملفات : لقفل الملفات 🕹 📊/فتح الملفات : لفتح الملفات 🕹 📊/قفل الدردشة : لقفل الدردشة 🕹 📊/فتح الدردشة : لفتح الدردشة 🕹 📊/قفل الكل : لقفل الدردشة مع تحذير 🕹 📊/فتح الكل : لفتح الدردشة 🕹 🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹 اوامر قفل الحماية 🕹 /امنع 🕹 للمنع ➖ 🕹/اسمح 🕹 للسماح 🕹 🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹🔹 📊/امنع السبام : لقفل الكلايش الطويله 🕹 📊/اسمح السبام : لفتح الكلايش الطويله 🕹 📊/امنع التكرار : لقفل التكرار 🕹 📊/اسمح التكرار : لفتح التكرار 🕹 📊/امنع الملصقات : لقفل الملصقات 🕹 📊/اسمح الملصقات : لفتح الملصقات 🕹 📊/امنع الكلمات السيئة : لقفل الكلمات السيئة 🕹 📊/اسمح الكلمات السيئة : لفتح الكلمات السيئة 🕹 📊/امنع البوتات : لقفل البوتات 🕹 📊/اسمح البوتات : لفتح البوتات 🕹 📊/امنع التوجيه : لقفل اعادة توجيه 🕹 📊/اسمح التوجيه : لفتح اعادة توجيه 🕹 📊/امنع اشعارات الدخول : لقفل اشعارات الدخول 🕹 📊/اسمح اشعارات الدخول : لفتح اشعارات الدخول 🕹 📊/امنع الرتل : لقفل الرتل 🕹 📊/اسمح الرتل : لفتح الرتل 🕹 📊/امنع الدخول عبر الرابط : لقفل الدخول عبر الرابط 🕹 📊/امنع الردود : لقفل الردود 🕹 📊/اسمح الردود : لفتح الردود 🕹 📊/امنع الميديا : لقفل الميديا 🕹 📊/اسمح الميديا : لفتح الميديا 🕹 📊/امنع اليوزرنيم : لقفل التاك 🕹 📊/اسمح اليوزرنيم : لفتح التاك 🕹 📊/امنع الكلمات السيئة : لقفل الكلمات السيئة 🕹 📊/اسمح الكلمات السيئة : لفتح الكلمات السيئة🕹 📊/امنع الجهات : لمنع جهات الاتصال 🕹 📊/اسمح الجهات : لفتح جهات الاتصال 🕹 📊/امنع السمايلات : لقفل السمايل 🕹 📊/اسمح السمايلات : لفتح السمايل🕹 Dev : @shaD_o 💭 bot : @shado1bot 💭 ]].."\n" .."➖➖➖➖➖➖➖➖".."\n" .."📛قناتنا : @vip_team1 ".."\n" .."🔶التاريخ : "..os.date('%A, %B, %d, %Y\n' , timestamp) .."➖➖➖➖➖➖➖➖".."\n" .."🔹الوقت : "..os.date(' %T', os.time()).."\n" end end return { patterns = { "^[!/#](اوامر2)" }, run = run, } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Windurst_Woods/npcs/Ronana.lua
3
1810
----------------------------------- -- Area: Windurst Woods -- NPC: Ronana -- Type: Bonecraft Image Support -- !pos -1.540 -6.25 -144.517 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,2); local SkillCap = getCraftSkillCap(player,SKILL_BONECRAFT); local SkillLevel = player:getSkillLevel(SKILL_BONECRAFT); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_BONECRAFT_IMAGERY) == false) then player:startEvent(0x2723,SkillCap,SkillLevel,1,511,player:getGil(),0,36408,0); else player:startEvent(0x2723,SkillCap,SkillLevel,1,511,player:getGil(),7081,36408,0); end else player:startEvent(0x2723); -- 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 == 0x2723 and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,6,1); player:addStatusEffect(EFFECT_BONECRAFT_IMAGERY,1,0,120); end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Beaucedine_Glacier_[S]/npcs/Moana_CA.lua
3
1076
----------------------------------- -- Area: Beaucedine Glacier (S) -- NPC: Moana, C.A. -- Type: Campaign Arbiter -- @zone 136 -- !pos -27.237 -60.888 -48.111 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01c5); 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/dish_of_spaghetti_peperoncino.lua
12
1487
----------------------------------------- -- ID: 5188 -- Item: dish_of_spaghetti_peperoncino -- Food Effect: 30Min, All Races ----------------------------------------- -- Health % 30 -- Health Cap 70 -- Vitality 2 -- Store TP +6 -- Resist virus +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,1800,5188); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 30); target:addMod(MOD_FOOD_HP_CAP, 70); target:addMod(MOD_VIT, 2); target:addMod(MOD_STORETP, 6); target:addMod(MOD_VIRUSRES, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 30); target:delMod(MOD_FOOD_HP_CAP, 70); target:delMod(MOD_VIT, 2); target:delMod(MOD_STORETP, 6); target:delMod(MOD_VIRUSRES, 10); end;
gpl-3.0
CCAAHH/telegram-bot-supergroups
plugins/boobs.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
ashang/koreader
frontend/ui/widget/overlapgroup.lua
6
1297
local WidgetContainer = require("ui/widget/container/widgetcontainer") --[[ A Layout widget that puts objects above each other --]] local OverlapGroup = WidgetContainer:new{ _size = nil, } function OverlapGroup:getSize() if not self._size then self._size = {w = 0, h = 0} self._offsets = { x = math.huge, y = math.huge } for i, widget in ipairs(self) do local w_size = widget:getSize() if self._size.h < w_size.h then self._size.h = w_size.h end if self._size.w < w_size.w then self._size.w = w_size.w end end end if self.dimen.w then self._size.w = self.dimen.w end if self.dimen.h then self._size.h = self.dimen.h end return self._size end function OverlapGroup:paintTo(bb, x, y) local size = self:getSize() for i, wget in ipairs(self) do local wget_size = wget:getSize() if wget.align == "right" then wget:paintTo(bb, x+size.w-wget_size.w, y) elseif wget.align == "center" then wget:paintTo(bb, x+math.floor((size.w-wget_size.w)/2), y) else -- default to left wget:paintTo(bb, x, y) end end end return OverlapGroup
agpl-3.0
Afforess/Factorio-Stdlib
stdlib/utils/table.lua
1
21350
--- Extends Lua 5.2 table. -- @module Utils.table -- @see table -- @usage local table = require('__stdlib__/stdlib/utils/table') local Table = {} Table.remove = table.remove Table.sort = table.sort Table.pack = table.pack Table.unpack = table.unpack Table.insert = table.insert Table.concat = table.concat -- Import base lua table into Table for k, v in pairs(table) do if not Table[k] then Table[k] = v end end --- Given a mapping function, creates a transformed copy of the table -- by calling the function for each element in the table, and using -- the result as the new value for the key. Passes the index as second argument to the function. -- @usage a= { 1, 2, 3, 4, 5} -- table.map(a, function(v) return v * 10 end) --produces: { 10, 20, 30, 40, 50 } -- @usage a = {1, 2, 3, 4, 5} -- table.map(a, function(v, k, x) return v * k + x end, 100) --produces { 101, 104, 109, 116, 125} -- @tparam table tbl the table to be mapped to the transform -- @tparam function func the function to transform values -- @param[opt] ... additional arguments passed to the function -- @treturn table a new table containing the keys and mapped values function Table.map(tbl, func, ...) local new_tbl = {} for k, v in pairs(tbl) do new_tbl[k] = func(v, k, ...) end return new_tbl end --- Given a filter function, creates a filtered copy of the table -- by calling the function for each element in the table, and -- filtering out any key-value pairs for non-true results. Passes the index as second argument to the function. -- @usage a= { 1, 2, 3, 4, 5} -- table.filter(a, function(v) return v % 2 == 0 end) --produces: { 2, 4 } -- @usage a = {1, 2, 3, 4, 5} -- table.filter(a, function(v, k, x) return k % 2 == 1 end) --produces: { 1, 3, 5 } -- @tparam table tbl the table to be filtered -- @tparam function func the function to filter values -- @param[opt] ... additional arguments passed to the function -- @treturn table a new table containing the filtered key-value pairs function Table.filter(tbl, func, ...) local new_tbl = {} local add = #tbl > 0 for k, v in pairs(tbl) do if func(v, k, ...) then if add then Table.insert(new_tbl, v) else new_tbl[k] = v end end end return new_tbl end --- Given a candidate search function, iterates over the table, calling the function -- for each element in the table, and returns the first element the search function returned true. -- Passes the index as second argument to the function. -- @usage a= { 1, 2, 3, 4, 5} -- table.find(a, function(v) return v % 2 == 0 end) --produces: 2 -- @usage a = {1, 2, 3, 4, 5} -- table.find(a, function(v, k, x) return k % 2 == 1 end) --produces: 1 -- @tparam table tbl the table to be searched -- @tparam function func the function to use to search for any matching element -- @param[opt] ... additional arguments passed to the function -- @treturn ?|nil|Mixed the first found value, or nil if none was found function Table.find(tbl, func, ...) for k, v in pairs(tbl) do if func(v, k, ...) then return v, k end end return nil end --- Given a candidate search function, iterates over the table, calling the function -- for each element in the table, and returns true if search function returned true. -- Passes the index as second argument to the function. -- @see table.find -- @usage a= { 1, 2, 3, 4, 5} -- table.any(a, function(v) return v % 2 == 0 end) --produces: true -- @usage a = {1, 2, 3, 4, 5} -- table.any(a, function(v, k, x) return k % 2 == 1 end) --produces: true -- @tparam table tbl the table to be searched -- @tparam function func the function to use to search for any matching element -- @param[opt] ... additional arguments passed to the function -- @treturn boolean true if an element was found, false if none was found function Table.any(tbl, func, ...) return Table.find(tbl, func, ...) ~= nil end --- Given a candidate search function, iterates over the table, calling the function -- for each element in the table, and returns true if search function returned true -- for all items in the table. -- Passes the index as second argument to the function. -- @tparam table tbl the table to be searched -- @tparam function func the function to used to search -- @param[opt] ... additional arguments passed to the search function -- @treturn boolean true if all elements in the table return truthy function Table.all(tbl, func, ...) for k, v in pairs(tbl) do if not func(v, k, ...) then return false end end return true end --- Given a function, apply it to each element in the table. -- Passes the index as the second argument to the function. -- <p>Iteration is aborted if the applied function returns true for any element during iteration. -- @usage -- a = {10, 20, 30, 40} -- table.each(a, function(v) game.print(v) end) --prints 10, 20, 30, 40, 50 -- @tparam table tbl the table to be iterated -- @tparam function func the function to apply to elements -- @param[opt] ... additional arguments passed to the function -- @treturn table the table where the given function has been applied to its elements function Table.each(tbl, func, ...) for k, v in pairs(tbl) do if func(v, k, ...) then break end end return tbl end --- Returns a new array that is a one-dimensional recursive flattening of the given array. -- For every element that is an array, extract its elements into the new array. -- <p>The optional level argument determines the level of recursion to flatten. -- > This function flattens an integer-indexed array, but not an associative array. -- @tparam array tbl the array to be flattened -- @tparam[opt] uint level recursive levels, or no limit to recursion if not supplied -- @treturn array a new array that represents the flattened contents of the given array function Table.flatten(tbl, level) local flattened = {} Table.each(tbl, function(value) if type(value) == 'table' and #value > 0 then if level then if level > 0 then Table.merge(flattened, Table.flatten(value, level - 1), true) else Table.insert(flattened, value) end else Table.merge(flattened, Table.flatten(value), true) end else Table.insert(flattened, value) end end) return flattened end --- Given an array, returns the first element or nil if no element exists. -- @tparam array tbl the array -- @treturn ?|nil|Mixed the first element function Table.first(tbl) return tbl[1] end --- Given an array, returns the last element or nil if no elements exist. -- @tparam array tbl the array -- @treturn ?|nil|Mixed the last element or nil function Table.last(tbl) local size = #tbl if size == 0 then return nil end return tbl[size] end --- Given an array of only numeric values, returns the minimum or nil if no element exists. -- @tparam {number,...} tbl the array with only numeric values -- @treturn ?|nil|number the minimum value function Table.min(tbl) if #tbl == 0 then return nil end local min = tbl[1] for _, num in pairs(tbl) do min = num < min and num or min end return min end ---Given an array of only numeric values, returns the maximum or nil if no element exists. -- @tparam {number,...} tbl the array with only numeric values -- @treturn ?|nil|number the maximum value function Table.max(tbl) if #tbl == 0 then return nil end local max = tbl[1] for _, num in pairs(tbl) do max = num > max and num or max end return max end --- Given an array of only numeric values, return the sum of all values, or 0 for empty arrays. -- @tparam {number,...} tbl the array with only numeric values -- @treturn number the sum of the numbers or zero if the given array was empty function Table.sum(tbl) local sum = 0 for _, num in pairs(tbl) do sum = sum + num end return sum end --- Given an array of only numeric values, returns the average or nil if no element exists. -- @tparam {number,...} tbl the array with only numeric values -- @treturn ?|nil|number the average value function Table.avg(tbl) local cnt = #tbl return cnt ~= 0 and Table.sum(tbl) / cnt or nil end --- Return a new array slice. -- @tparam array tbl the table to slice -- @tparam[opt=1] number start -- @tparam[opt=#tbl] number stop stop at this index, use negative to stop from end. -- @usage local tab = { 10, 20, 30, 40, 50} -- slice(tab, 2, -2) --returns { 20, 30, 40 } function Table.slice(tbl, start, stop) local res = {} local n = #tbl start = start or 1 stop = stop or n stop = stop < 0 and (n + stop + 1) or stop if start < 1 or start > n then return {} end local k = 1 for i = start, stop do res[k] = tbl[i] k = k + 1 end return res end --- Merges two tables, values from first get overwritten by the second. -- @usage -- function some_func(x, y, args) -- args = table.merge({option1=false}, args) -- if opts.option1 == true then return x else return y end -- end -- some_func(1,2) -- returns 2 -- some_func(1,2,{option1=true}) -- returns 1 -- @tparam table tblA first table -- @tparam table tblB second table -- @tparam[opt=false] boolean array_merge set to true to merge the tables as an array or false for an associative array -- @tparam[opt=false] boolean raw use rawset for associated array -- @treturn array|table an array or an associated array where tblA and tblB have been merged function Table.merge(tblA, tblB, array_merge, raw) if not tblB then return tblA end if array_merge then for _, v in pairs(tblB) do Table.insert(tblA, v) end else for k, v in pairs(tblB) do if raw then rawset(tblA, k, v) else tblA[k] = v end end end return tblA end function Table.array_combine(...) local tables = { ... } local new = {} for _, tab in pairs(tables) do for _, v in pairs(tab) do Table.insert(new, v) end end return new end function Table.dictionary_combine(...) local tables = { ... } local new = {} for _, tab in pairs(tables) do for k, v in pairs(tab) do new[k] = v end end return new end --- Creates a new merged dictionary, if the values in tbl_b are in tbl_a they are not overwritten. -- @usage -- local a = {one = A} -- local b = {one = Z, two = B} -- local merged = table.dictionary_merge(tbl_a, tbl_b) -- --merged = {one = A, two = B} -- @tparam table tbl_a -- @tparam table tbl_b -- @treturn table with a and b merged together function Table.dictionary_merge(tbl_a, tbl_b) local meta_a = getmetatable(tbl_a) local meta_b = getmetatable(tbl_b) setmetatable(tbl_a, nil) setmetatable(tbl_b, nil) local new_t = {} for k, v in pairs(tbl_a) do new_t[k] = v end for k, v in pairs(tbl_b or {}) do if not new_t[k] then new_t[k] = v end end setmetatable(tbl_a, meta_a) setmetatable(tbl_b, meta_b) return new_t end --- Compares 2 tables for inner equality. -- Modified from factorio/data/core/lualib/util.lua -- @tparam table t1 -- @tparam table t2 -- @tparam[opt=false] boolean ignore_mt ignore eq metamethod -- @treturn boolean if the tables are the same -- @author Sparr, Nexela, luacode.org function Table.deep_compare(t1, t2, ignore_mt) local ty1, ty2 = type(t1), type(t2) if ty1 ~= ty2 then return false end -- non-table types can be directly compared if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end -- as well as tables which have the metamethod __eq if not ignore_mt then local mt = getmetatable(t1) if mt and mt.__eq then return t1 == t2 end end for k1, v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not Table.deep_compare(v1, v2) then return false end end for k in pairs(t2) do if t1[k] == nil then return false end end return true end Table.compare = Table.deep_compare --- Creates a deep copy of table without copying Factorio objects. -- copied from factorio/data/core/lualib/util.lua -- @usage local copy = table.deep_copy[data.raw.["stone-furnace"]["stone-furnace"]] -- -- returns a copy of the stone furnace entity -- @tparam table object the table to copy -- @treturn table a copy of the table function Table.deep_copy(object) local lookup_table = {} local function _copy(inner) if type(inner) ~= 'table' then return inner elseif inner.__self then return inner elseif lookup_table[inner] then return lookup_table[inner] end local new_table = {} lookup_table[inner] = new_table for index, value in pairs(inner) do new_table[_copy(index)] = _copy(value) end return setmetatable(new_table, getmetatable(inner)) end return _copy(object) end Table.deepcopy = Table.deep_copy --- Creates a deep copy of a table without copying factorio objects -- internal table refs are also deepcopy. The resulting table should -- @usage local copy = table.fullcopy[data.raw.["stone-furnace"]["stone-furnace"]] -- -- returns a deepcopy of the stone furnace entity with no internal table references. -- @tparam table object the table to copy -- @treturn table a copy of the table function Table.full_copy(object) local lookup_table = {} local function _copy(inner) if type(inner) ~= 'table' then return inner elseif inner.__self then return inner elseif lookup_table[inner] then return _copy(lookup_table[inner]) end local new_table = {} lookup_table[inner] = new_table for index, value in pairs(inner) do new_table[_copy(index)] = _copy(value) end return setmetatable(new_table, getmetatable(inner)) end return _copy(object) end Table.fullcopy = Table.full_copy --- Creates a flexible deep copy of an object, recursively copying sub-objects -- @usage local copy = table.flexcopy(data.raw.["stone-furnace"]["stone-furnace"]) -- -- returns a copy of the stone furnace entity -- @tparam table object the table to copy -- @treturn table a copy of the table function Table.flex_copy(object) local lookup_table = {} local function _copy(inner) if type(inner) ~= 'table' then return inner elseif inner.__self then return inner elseif lookup_table[inner] then return lookup_table[inner] elseif type(inner._copy_with) == 'function' then lookup_table[inner] = inner:_copy_with(_copy) return lookup_table[inner] end local new_table = {} lookup_table[inner] = new_table for index, value in pairs(inner) do new_table[_copy(index)] = _copy(value) end return setmetatable(new_table, getmetatable(inner)) end return _copy(object) end Table.flexcopy = Table.flex_copy --- Returns a copy of all of the values in the table. -- @tparam table tbl the table to copy the keys from, or an empty table if tbl is nil -- @tparam[opt] boolean sorted whether to sort the keys (slower) or keep the random order from pairs() -- @tparam[opt] boolean as_string whether to try and parse the values as strings, or leave them as their existing type -- @treturn array an array with a copy of all the values in the table function Table.values(tbl, sorted, as_string) if not tbl then return {} end local value_set = {} local n = 0 if as_string then -- checking as_string /before/ looping is faster for _, v in pairs(tbl) do n = n + 1 value_set[n] = tostring(v) end else for _, v in pairs(tbl) do n = n + 1 value_set[n] = v end end if sorted then table.sort(value_set, function(x, y) -- sorts tables with mixed index types. local tx = type(x) == 'number' local ty = type(y) == 'number' if tx == ty then return x < y and true or false -- similar type can be compared elseif tx == true then return true -- only x is a number and goes first else return false -- only y is a number and goes first end end) end return value_set end --- Returns a copy of all of the keys in the table. -- @tparam table tbl the table to copy the keys from, or an empty table if tbl is nil -- @tparam[opt] boolean sorted whether to sort the keys (slower) or keep the random order from pairs() -- @tparam[opt] boolean as_string whether to try and parse the keys as strings, or leave them as their existing type -- @treturn array an array with a copy of all the keys in the table function Table.keys(tbl, sorted, as_string) if not tbl then return {} end local key_set = {} local n = 0 if as_string then -- checking as_string /before/ looping is faster for k, _ in pairs(tbl) do n = n + 1 key_set[n] = tostring(k) end else for k, _ in pairs(tbl) do n = n + 1 key_set[n] = k end end if sorted then table.sort(key_set, function(x, y) -- sorts tables with mixed index types. local tx = type(x) == 'number' local ty = type(y) == 'number' if tx == ty then return x < y and true or false -- similar type can be compared elseif tx == true then return true -- only x is a number and goes first else return false -- only y is a number and goes first end end) end return key_set end --- Removes keys from a table by setting the values associated with the keys to nil. -- @usage local a = {1, 2, 3, 4} -- table.remove_keys(a, {1,3}) --returns {nil, 2, nil, 4} -- @usage local b = {k1 = 1, k2 = 'foo', old_key = 'bar'} -- table.remove_keys(b, {'old_key'}) --returns {k1 = 1, k2 = 'foo'} -- @tparam table tbl the table to remove the keys from -- @tparam {Mixed,...} keys an array of keys that exist in the given table -- @treturn table tbl without the specified keys function Table.remove_keys(tbl, keys) for i = 1, #keys do tbl[keys[i]] = nil end return tbl end --- Returns the number of keys in a table, if func is passed only count keys when the function is true. -- @tparam table tbl to count keys -- @tparam[opt] function func to increment counter -- @param[optchain] ... additional arguments passed to the function -- @treturn number The number of keys matching the function or the number of all keys if func isn't passed -- @treturn number The total number of keys -- @usage local a = { 1, 2, 3, 4, 5} -- table.count_keys(a) -- produces: 5, 5 -- @usage local a = {1, 2, 3, 4, 5} -- table.count_keys(a, function(v, k) return k % 2 == 1 end) -- produces: 3, 5 function Table.count_keys(tbl, func, ...) local count, total = 0, 0 if type(tbl) == 'table' then for k, v in pairs(tbl) do total = total + 1 if func then if func(v, k, ...) then count = count + 1 end else count = count + 1 end end end return count, total end --- Returns an inverted (***{[value] = key,...}***) copy of the given table. If the values are not unique, -- the assigned key depends on the order of pairs(). -- @usage local a = {k1 = 'foo', k2 = 'bar'} -- table.invert(a) --returns {'foo' = k1, 'bar' = k2} -- @usage local b = {k1 = 'foo', k2 = 'bar', k3 = 'bar'} -- table.invert(b) --returns {'foo' = k1, 'bar' = ?} -- @tparam table tbl the table to invert -- @treturn table a new table with inverted mapping function Table.invert(tbl) local inverted = {} for k, v in pairs(tbl) do inverted[v] = k end return inverted end local function _size(tbl) local count = 0 for _ in pairs(tbl or {}) do count = count + 1 end return count end --- Return the size of a table using the factorio built in table_size function -- @function size -- @tparam table table to use -- @treturn int size of the table Table.size = _ENV.table_size or _size --- For all string or number values in an array map them to a value = value table -- @usage local a = {"v1", "v2"} -- table.array_to_bool(a) -- return {["v1"] = "v1", ["v2"]= "v2"} -- @tparam table tbl the table to convert -- @tparam[opt=false] boolean as_bool map to true instead of value -- @treturn table the converted table function Table.array_to_dictionary(tbl, as_bool) local new_tbl = {} for _, v in ipairs(tbl) do if type(v) == 'string' or type(v) == 'number' then new_tbl[v] = as_bool and true or v end end return new_tbl end -- Returns an array of unique values from tbl -- @tparam table tbl -- @treturn table an array of unique values. function Table.unique_values(tbl) return Table.keys(Table.invert(tbl)) end --- Does the table contain any elements -- @tparam table tbl -- @treturn boolean function Table.is_empty(tbl) return _ENV.table_size and _ENV.table_size(tbl) == 0 or next(tbl) == nil end --- Clear all elements in a table -- @tparam table tbl the table to clear -- @treturn table the cleared table function Table.clear(tbl) for k in pairs(tbl) do tbl[k] = nil end return tbl end return Table
isc
apwiede/nodemcu-firmware-2.0
lua_examples/adc_rgb.lua
73
1163
-- -- Light sensor on ADC(0), RGB LED connected to gpio12(6) Green, gpio13(7) Blue & gpio15(8) Red. -- This works out of the box on the typical ESP8266 evaluation boards with Battery Holder -- -- It uses the input from the sensor to drive a "rainbow" effect on the RGB LED -- Includes a very "pseudoSin" function -- function led(r,Sg,b) pwm.setduty(8,r) pwm.setduty(6,g) pwm.setduty(7,b) end -- this is perhaps the lightest weight sin function in existance -- Given an integer from 0..128, 0..512 appximating 256 + 256 * sin(idx*Pi/256) -- This is first order square approximation of sin, it's accurate around 0 and any multiple of 128 (Pi/2), -- 92% accurate at 64 (Pi/4). function pseudoSin (idx) idx = idx % 128 lookUp = 32 - idx % 64 val = 256 - (lookUp * lookUp) / 4 if (idx > 64) then val = - val; end return 256+val end pwm.setup(6,500,512) pwm.setup(7,500,512) pwm.setup(8,500,512) pwm.start(6) pwm.start(7) pwm.start(8) tmr.alarm(1,20,1,function() idx = 3 * adc.read(0) / 2 r = pseudoSin(idx) g = pseudoSin(idx + 43) b = pseudoSin(idx + 85) led(r,g,b) idx = (idx + 1) % 128 end)
mit
padrinoo1/telegeek
plugins/add_bot.lua
189
1492
--[[ Bot can join into a group by replying a message contain an invite link or by typing !add [invite link]. URL.parse cannot parsing complicated message. So, this plugin only works for single [invite link] in a post. [invite link] may be preceeded but must not followed by another characters. --]] do local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) i = 0 for k,segment in pairs(parsed_path) do i = i + 1 if segment == 'joinchat' then invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '') break end end return invite_link end local function action_by_reply(extra, success, result) local hash = parsed_url(result.text) join = import_chat_link(hash, ok_cb, false) end function run(msg, matches) if is_sudo(msg) then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) elseif matches[1] then local hash = parsed_url(matches[1]) join = import_chat_link(hash, ok_cb, false) end end end return { description = 'Invite the bot into a group chat via its invite link.', usage = { '!AddBot : Join a group by replying a message containing invite link.', '!AddBot [invite_link] : Join into a group by providing their [invite_link].' }, patterns = { '^[/!](addBot)$', '^[/!](ddBot) (.*)$' }, run = run } end
gpl-2.0
bttscut/skynet
lualib/snax/gateserver.lua
16
3320
local skynet = require "skynet" local netpack = require "skynet.netpack" local socketdriver = require "skynet.socketdriver" local gateserver = {} local socket -- listen socket local queue -- message queue local maxclient -- max client local client_number = 0 local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end }) local nodelay = false local connection = {} function gateserver.openclient(fd) if connection[fd] then socketdriver.start(fd) end end function gateserver.closeclient(fd) local c = connection[fd] if c then connection[fd] = false socketdriver.close(fd) end end function gateserver.start(handler) assert(handler.message) assert(handler.connect) function CMD.open( source, conf ) assert(not socket) local address = conf.address or "0.0.0.0" local port = assert(conf.port) maxclient = conf.maxclient or 1024 nodelay = conf.nodelay skynet.error(string.format("Listen on %s:%d", address, port)) socket = socketdriver.listen(address, port) socketdriver.start(socket) if handler.open then return handler.open(source, conf) end end function CMD.close() assert(socket) socketdriver.close(socket) end local MSG = {} local function dispatch_msg(fd, msg, sz) if connection[fd] then handler.message(fd, msg, sz) else skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz))) end end MSG.data = dispatch_msg local function dispatch_queue() local fd, msg, sz = netpack.pop(queue) if fd then -- may dispatch even the handler.message blocked -- If the handler.message never block, the queue should be empty, so only fork once and then exit. skynet.fork(dispatch_queue) dispatch_msg(fd, msg, sz) for fd, msg, sz in netpack.pop, queue do dispatch_msg(fd, msg, sz) end end end MSG.more = dispatch_queue function MSG.open(fd, msg) if client_number >= maxclient then socketdriver.close(fd) return end if nodelay then socketdriver.nodelay(fd) end connection[fd] = true client_number = client_number + 1 handler.connect(fd, msg) end local function close_fd(fd) local c = connection[fd] if c ~= nil then connection[fd] = nil client_number = client_number - 1 end end function MSG.close(fd) if fd ~= socket then if handler.disconnect then handler.disconnect(fd) end close_fd(fd) else socket = nil end end function MSG.error(fd, msg) if fd == socket then socketdriver.close(fd) skynet.error("gateserver close listen socket, accpet error:",msg) else if handler.error then handler.error(fd, msg) end close_fd(fd) end end function MSG.warning(fd, size) if handler.warning then handler.warning(fd, size) end end skynet.register_protocol { name = "socket", id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6 unpack = function ( msg, sz ) return netpack.filter( queue, msg, sz) end, dispatch = function (_, _, q, type, ...) queue = q if type then MSG[type](...) end end } skynet.start(function() skynet.dispatch("lua", function (_, address, cmd, ...) local f = CMD[cmd] if f then skynet.ret(skynet.pack(f(address, ...))) else skynet.ret(skynet.pack(handler.command(cmd, address, ...))) end end) end) end return gateserver
mit
tgserver2018/Tarfand.farsi
plugins/mute-time.lua
1
1339
local function pre_process(msg) local hash = 'mute_time:'..msg.chat_id_ if redis:get(hash) and gp_type(msg.chat_id_) == 'channel' and not is_mod(msg) then tdcli.deleteMessages(msg.chat_id_, {[0] = tonumber(msg.id_)}) end end local function run(msg, matches) if matches[1]:lower() == 'mt' and is_mod(msg) then local hash = 'mute_time:'..msg.chat_id_ if not matches[2] then return "_لطفا ساعت و دقیقه را وارد نمایید!_" else local hour = string.gsub(matches[2], 'h', '') local num1 = tonumber(hour) * 3600 local minutes = string.gsub(matches[3], 'm', '') local num2 = tonumber(minutes) * 60 local num4 = tonumber(num1 + num2) redis:setex(hash, num4, true) return "⛔️گروه به مدت: \n`"..matches[2].."` ساعت\n`"..matches[3].."` دقیقه \nتعطیل میباشد.️" end end if matches[1]:lower() == 'بازکردن گروه' and is_mod(msg) then local hash = 'mute_time:'..msg.chat_id_ redis:del(hash) return "*✅گروه برای ارسال پیام کاربران باز شد.*" end end return { patterns = { '^([Mm][Tt])$', '^(بازکردن گروه)$', '^([Mm][Tt]) (%d+) (%d+)$', }, run = run, pre_process = pre_process } -- http://SaMaN_SaNstaR -- @SaMaN_SaNstar1 -- @MeGaNet_sbot
gpl-3.0
openwrt-es/openwrt-luci
libs/luci-lib-nixio/axTLS/www/lua/download.lua
180
1550
#!/usr/local/bin/lua require"luasocket" function receive (connection) connection:settimeout(0) local s, status = connection:receive (2^10) if status == "timeout" then coroutine.yield (connection) end return s, status end function download (host, file, outfile) --local f = assert (io.open (outfile, "w")) local c = assert (socket.connect (host, 80)) c:send ("GET "..file.." HTTP/1.0\r\n\r\n") while true do local s, status = receive (c) --f:write (s) if status == "closed" then break end end c:close() --f:close() end local threads = {} function get (host, file, outfile) print (string.format ("Downloading %s from %s to %s", file, host, outfile)) local co = coroutine.create (function () return download (host, file, outfile) end) table.insert (threads, co) end function dispatcher () while true do local n = table.getn (threads) if n == 0 then break end local connections = {} for i = 1, n do local status, res = coroutine.resume (threads[i]) if not res then table.remove (threads, i) break else table.insert (connections, res) end end if table.getn (connections) == n then socket.select (connections) end end end local url = arg[1] if not url then print (string.format ("usage: %s url [times]", arg[0])) os.exit() end local times = arg[2] or 5 url = string.gsub (url, "^http.?://", "") local _, _, host, file = string.find (url, "^([^/]+)(/.*)") local _, _, fn = string.find (file, "([^/]+)$") for i = 1, times do get (host, file, fn..i) end dispatcher ()
apache-2.0
RebootRevival/FFXI_Test
scripts/globals/mobskills/necrobane.lua
43
1075
--------------------------------------------- -- Necrobane --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1839) then return 0; else return 1; end end if(mob:getFamily() == 91) then local mobSkin = mob:getModelId(); if (mobSkin == 1840) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); MobStatusEffectMove(mob, target, EFFECT_CURSE_I, 1, 0, 60); return dmg; end;
gpl-3.0
olafhering/sysbench
src/lua/internal/sysbench.sql.lua
1
14001
-- Copyright (C) 2017 Alexey Kopytov <akopytov@gmail.com> -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -- ---------------------------------------------------------------------- -- SQL API -- ---------------------------------------------------------------------- ffi = require("ffi") sysbench.sql = {} ffi.cdef[[ /* The following definitions have been copied with modifications from db_driver.h */ typedef enum { DB_ERROR_NONE, /* no error(s) */ DB_ERROR_IGNORABLE, /* error should be ignored as defined by command line arguments or a custom error handler */ DB_ERROR_FATAL /* non-ignorable error */ } sql_error_t; typedef struct { const char *sname; /* short name */ const char *lname; /* long name */ const char opaque[?]; } sql_driver; typedef struct { uint32_t len; /* Value length */ const char *ptr; /* Value string */ } sql_value; /* Result set row definition */ typedef struct { void *ptr; /* Driver-specific row data */ sql_value *values; /* Array of column values */ } sql_row; /* Query type for statistics */ typedef enum { SB_CNT_OTHER, SB_CNT_READ, SB_CNT_WRITE, SB_CNT_TRX, SB_CNT_ERROR, SB_CNT_RECONNECT, SB_CNT_MAX } sb_counter_type; typedef struct { sql_error_t error; /* Driver-independent error code */ int sql_errno; /* Driver-specific error code */ const char *sql_state; /* Database-specific SQL state */ const char *sql_errmsg; /* Database-specific error message */ sql_driver *driver; /* DB driver for this connection */ const char opaque[?]; } sql_connection; typedef struct { sql_connection *connection; const char opaque[?]; } sql_statement; /* Result set definition */ typedef struct { sb_counter_type counter; /* Statistical counter type */ uint32_t nrows; /* Number of affected rows */ uint32_t nfields; /* Number of fields */ sql_statement *statement; /* Pointer to prepared statement (if used) */ void *ptr; /* Pointer to driver-specific data */ sql_row row; /* Last fetched row */ } sql_result; typedef enum { SQL_TYPE_NONE, SQL_TYPE_TINYINT, SQL_TYPE_SMALLINT, SQL_TYPE_INT, SQL_TYPE_BIGINT, SQL_TYPE_FLOAT, SQL_TYPE_DOUBLE, SQL_TYPE_TIME, SQL_TYPE_DATE, SQL_TYPE_DATETIME, SQL_TYPE_TIMESTAMP, SQL_TYPE_CHAR, SQL_TYPE_VARCHAR } sql_bind_type_t; typedef struct { sql_bind_type_t type; void *buffer; unsigned long *data_len; unsigned long max_len; char *is_null; } sql_bind; sql_driver *db_create(const char *); int db_destroy(sql_driver *drv); sql_connection *db_connection_create(sql_driver * drv); int db_connection_close(sql_connection *con); int db_connection_reconnect(sql_connection *con); void db_connection_free(sql_connection *con); int db_bulk_insert_init(sql_connection *, const char *, size_t); int db_bulk_insert_next(sql_connection *, const char *, size_t); void db_bulk_insert_done(sql_connection *); sql_result *db_query(sql_connection *con, const char *query, size_t len); sql_row *db_fetch_row(sql_result *rs); sql_statement *db_prepare(sql_connection *con, const char *query, size_t len); int db_bind_param(sql_statement *stmt, sql_bind *params, size_t len); int db_bind_result(sql_statement *stmt, sql_bind *results, size_t len); sql_result *db_execute(sql_statement *stmt); int db_close(sql_statement *stmt); int db_free_results(sql_result *); ]] local sql_driver = ffi.typeof('sql_driver *') local sql_connection = ffi.typeof('sql_connection *') local sql_statement = ffi.typeof('sql_statement *') local sql_bind = ffi.typeof('sql_bind'); local sql_result = ffi.typeof('sql_result'); local sql_value = ffi.typeof('sql_value'); local sql_row = ffi.typeof('sql_row'); sysbench.sql.type = { NONE = ffi.C.SQL_TYPE_NONE, TINYINT = ffi.C.SQL_TYPE_TINYINT, SMALLINT = ffi.C.SQL_TYPE_SMALLINT, INT = ffi.C.SQL_TYPE_INT, BIGINT = ffi.C.SQL_TYPE_BIGINT, FLOAT = ffi.C.SQL_TYPE_FLOAT, DOUBLE = ffi.C.SQL_TYPE_DOUBLE, TIME = ffi.C.SQL_TYPE_TIME, DATE = ffi.C.SQL_TYPE_DATE, DATETIME = ffi.C.SQL_TYPE_DATETIME, TIMESTAMP = ffi.C.SQL_TYPE_TIMESTAMP, CHAR = ffi.C.SQL_TYPE_CHAR, VARCHAR = ffi.C.SQL_TYPE_VARCHAR } -- Initialize a given SQL driver and return a handle to it to create -- connections. A nil driver name (i.e. no function argument) initializes the -- default driver, i.e. the one specified with --db-driver on the command line. function sysbench.sql.driver(driver_name) local drv = ffi.C.db_create(driver_name) if (drv == nil) then error("failed to initialize the DB driver", 2) end return ffi.gc(drv, ffi.C.db_destroy) end -- sql_driver methods local driver_methods = {} function driver_methods.connect(self) local con = ffi.C.db_connection_create(self) if con == nil then error("connection creation failed", 2) end return ffi.gc(con, ffi.C.db_connection_free) end function driver_methods.name(self) return ffi.string(self.sname) end -- sql_driver metatable local driver_mt = { __index = driver_methods, __gc = ffi.C.db_destroy, __tostring = function() return '<sql_driver>' end, } ffi.metatype("sql_driver", driver_mt) -- sql_connection methods local connection_methods = {} function connection_methods.disconnect(self) return assert(ffi.C.db_connection_close(self) == 0) end function connection_methods.reconnect(self) return assert(ffi.C.db_connection_reconnect(self) == 0) end function connection_methods.check_error(self, rs, query) if rs ~= nil or self.error == sysbench.sql.error.NONE then return rs end if self.sql_state == nil or self.sql_errmsg == nil then -- It must be an API error, don't bother trying to downgrade it an -- ignorable error error("SQL API error", 3) end local sql_state = ffi.string(self.sql_state) local sql_errmsg = ffi.string(self.sql_errmsg) -- Create an error descriptor containing connection, failed query, SQL error -- number, state and error message provided by the SQL driver errdesc = { connection = self, query = query, sql_errno = self.sql_errno, sql_state = sql_state, sql_errmsg = sql_errmsg } -- Check if the error has already been marked as ignorable by the driver, or -- there is an error hook that allows downgrading it to IGNORABLE if (self.error == sysbench.sql.error.FATAL and type(sysbench.hooks.sql_error_ignorable) == "function" and sysbench.hooks.sql_error_ignorable(errdesc)) or self.error == sysbench.sql.error.IGNORABLE then -- Throw a 'restart event' exception that can be caught by the user script -- to do some extra steps to restart a transaction (e.g. reprepare -- statements after a reconnect). Otherwise it will be caught by -- thread_run() in sysbench.lua, in which case the entire current event -- will be restarted without extra processing. errdesc.errcode = sysbench.error.RESTART_EVENT error(errdesc, 3) end -- Just throw a regular error message on a fatal error error(string.format("SQL error, errno = %d, state = '%s': %s", self.sql_errno, sql_state, sql_errmsg), 2) end function connection_methods.query(self, query) local rs = ffi.C.db_query(self, query, #query) return self:check_error(rs, query) end function connection_methods.bulk_insert_init(self, query) return ffi.C.db_bulk_insert_init(self, query, #query) end function connection_methods.bulk_insert_next(self, val) return ffi.C.db_bulk_insert_next(self, val, #val) end function connection_methods.bulk_insert_done(self) return ffi.C.db_bulk_insert_done(self) end function connection_methods.prepare(self, query) local stmt = ffi.C.db_prepare(self, query, #query) if stmt == nil then self:check_error(nil, query) end return stmt end -- A convenience wrapper around sql_connection:query() and -- sql_result:fetch_row(). Executes the specified query and returns the first -- row from the result set, if available, or nil otherwise function connection_methods.query_row(self, query) local rs = self:query(query) if rs == nil then return nil end return unpack(rs:fetch_row(), 1, rs.nfields) end -- sql_connection metatable local connection_mt = { __index = connection_methods, __tostring = function() return '<sql_connection>' end, __gc = ffi.C.db_connection_free, } ffi.metatype("sql_connection", connection_mt) -- sql_param local sql_param = {} function sql_param.set(self, value) local sql_type = sysbench.sql.type local btype = self.type if (value == nil) then self.is_null[0] = true return end self.is_null[0] = false if btype == sql_type.TINYINT or btype == sql_type.SMALLINT or btype == sql_type.INT or btype == sql_type.BIGINT then self.buffer[0] = value elseif btype == sql_type.FLOAT or btype == sql_type.DOUBLE then self.buffer[1] = value elseif btype == sql_type.CHAR or btype == sql_type.VARCHAR then local len = #value len = self.max_len < len and self.max_len or len ffi.copy(self.buffer, value, len) self.data_len[0] = len else error("Unsupported argument type: " .. btype, 2) end end function sql_param.set_rand_str(self, fmt) local sql_type = sysbench.sql.type local btype = self.type self.is_null[0] = false if btype == sql_type.CHAR or btype == sql_type.VARCHAR then local len = #fmt len = self.max_len < len and self.max_len or len ffi.C.sb_rand_str(fmt, self.buffer) self.data_len[0] = len else error("Unsupported argument type: " .. btype, 2) end end sql_param.__index = sql_param sql_param.__tostring = function () return '<sql_param>' end -- sql_statement methods local statement_methods = {} function statement_methods.bind_create(self, btype, max_len) local sql_type = sysbench.sql.type local param = setmetatable({}, sql_param) if btype == sql_type.TINYINT or btype == sql_type.SMALLINT or btype == sql_type.INT or btype == sql_type.BIGINT then param.type = sql_type.BIGINT param.buffer = ffi.new('int64_t[1]') param.max_len = 8 elseif btype == sql_type.FLOAT or btype == sql_type.DOUBLE then param.type = sql_type.DOUBLE param.buffer = ffi.new('double[1]') param.max_len = 8 elseif btype == sql_type.CHAR or btype == sql_type.VARCHAR then param.type = sql_type.VARCHAR param.buffer = ffi.new('char[?]', max_len) param.max_len = max_len else error("Unsupported argument type: " .. btype, 2) end param.data_len = ffi.new('unsigned long[1]') param.is_null = ffi.new('char[1]') return param end function statement_methods.bind_param(self, ...) local len = select('#', ...) if len < 1 then return nil end local binds = ffi.new("sql_bind[?]", len) local i, param for i, param in ipairs({...}) do binds[i-1].type = param.type binds[i-1].buffer = param.buffer binds[i-1].data_len = param.data_len binds[i-1].max_len = param.max_len binds[i-1].is_null = param.is_null end return ffi.C.db_bind_param(self, binds, len) end function statement_methods.execute(self) local rs = ffi.C.db_execute(self) return self.connection:check_error(rs, '<prepared statement>') end function statement_methods.close(self) return ffi.C.db_close(self) end -- sql_statement metatable local statement_mt = { __index = statement_methods, __tostring = function() return '<sql_statement>' end, __gc = ffi.C.db_close, } ffi.metatype("sql_statement", statement_mt) local bind_mt = { __tostring = function() return '<sql_bind>' end, } ffi.metatype("sql_bind", bind_mt) -- sql_result methods local result_methods = {} -- Returns the next row of values from a result set, or nil if there are no more -- rows to fetch. Values are returned as an array, i.e. a table with numeric -- indexes starting from 1. The total number of values (i.e. fields in a result -- set) can be obtained from sql_result.nfields. function result_methods.fetch_row(self) local res = {} local row = ffi.C.db_fetch_row(self) if row == nil then return nil end local i for i = 0, self.nfields-1 do if row.values[i].ptr ~= nil then -- not a NULL value res[i+1] = ffi.string(row.values[i].ptr, tonumber(row.values[i].len)) end end return res end function result_methods.free(self) return assert(ffi.C.db_free_results(self) == 0, "db_free_results() failed") end -- sql_results metatable local result_mt = { __index = result_methods, __tostring = function() return '<sql_result>' end, __gc = ffi.C.db_free_results } ffi.metatype("sql_result", result_mt) -- error codes sysbench.sql.error = {} sysbench.sql.error.NONE = ffi.C.DB_ERROR_NONE sysbench.sql.error.IGNORABLE = ffi.C.DB_ERROR_IGNORABLE sysbench.sql.error.FATAL = ffi.C.DB_ERROR_FATAL
gpl-2.0
llual/VIPTEAM
plugins/README..lua
3
15503
-- made by { @Mouamle } do ws = {} rs = {} -- some examples of how to use this :3 ws[1] = "هلاو" rs[1] = "هلاوو99وووات نورت/ي ❤️🙈" ws[2] = "هلو" -- msg rs[2] = "هلاوات 🙈❤️" -- reply ws[3] = "شلونكم" -- msg rs[3] = "الحمدلله وانته 🌚🍃" -- reply ws[4] = "دووم" -- msg rs[4] = "يدوم نبضك ❤️🍃" -- reply ws[5] = "شونك" rs[5] = "الحمدلله وانته" ws[6] = "شلونك" rs[6] = "الحمدلله وانته" ws[7] = "غنيلي" rs[7] = " 🙈 احبك اني 🙊 اني احبك 🙉 واتحدى واحد بلبشر مثلي يحبك 🙊" ws[8] = "شغل المبردة" rs[8] = " تم تشغيل المبردة بنجاح ❄️" ws[9] = "طفي المبردة" rs[9] = "طفيتهه 😒🍃" ws[10] = "شغل السبلت" rs[10] = "شغلته 🌚🍃 بس حثلجون معليه ترا " ws[11] = "مايا خليفه" rs[11] = " 😂 عيب صايمين" ws[12] = "فطور" rs[12] = "واخيراً 😍😍 خل اروح افطر " ws[13] = "الزمة الية" rs[13] = "😹😹ﻟـ✤ٰٰـٰيـٰٰش•❥ شبي " ws[14] = "جوني" rs[14] = " 😕💔 نعم حبي " ws[15] = "تخليني" rs[15] = " 😂 يي امين ابدي " ws[16] = "زاحف" rs[16] = "😂🌚 هاي عود انته جبير" ws[17] = "تركيا" rs[17] = "😐🍃 فديتهه" ws[18] = "داعش" rs[18] = "دي خل يولون 😒❤️" ws[19] = "الدولة الاسلامية" rs[19] = "انته داعشي ؟؟ 😒💔" ws[20] = "سني" rs[20] = "لتصير طائفي 😒🖐" ws[21] = "شيعي" rs[21] = "لتصير طائفي 😕" ws[22] = "تبادل" rs[22] = "كافي ملينه 😒😒 ما اريد اتبادل" ws[23] = "العراقيين" rs[23] = "احلى ناس ولله 😍🙈" ws[24] = "من وين" rs[24] = "شعليك زاحف 😂🔥 " ws[25] = "هاي" rs[25] = "هايات 🙈🍷" ws[26] = "البوت" rs[26] = "معاجبك ؟ 😕😒🍃" ws[27] = "البوت واكف" rs[27] = "لتجذب 😒" ws[28] = "منو ديحذف رسائلي" rs[28] = "اني عندك مانع ؟🌝😹" ws[29] = "كلاش اوف كلانس" rs[29] = "تلعبهه ؟ شكد لفلك ؟" ws[30] = "جوني" rs[30] = "😂 مأذيك ؟" ws[31] = "ازحف " rs[31] = " على اختك ازحف 🌚🍃 " ws[32] = "القناة" rs[32] = " @VIP_TEAM" ws[33] = "قناة" rs[33] = " @VIP_TEAM1 " ws[34] = "VIP" rs[34] = " ھ ـہذآ احسن تيم " ws[35] = "اريد ردح" rs[35] = "اي والله شغلونة ردح خل نركص😹" ws[37] = "وينكم" rs[37] = " ها حبي😐💋" ws[38] = "شبيكم" rs[38] = " ضايجين نريد نطلع 😞😹" ws[39] = "المنصور" rs[39] = " احلى ناس ولله " ws[40] = "المدرسه" rs[40] = " 😒🍃 الله لا يراوينه " ws[41] = "تحبني" rs[41] = " هوايه 😍🙈😍" ws[42] = "يعني شكد" rs[42] = " فوك متتوقع " ws[43] = "😂" rs[43] = " دوم حبي ❤️" ws[44] = "هههه" rs[44] = " دوم حبي ❤️" ws[45] = "ههههه" rs[45] = " دوم حبي ❤️" ws[46] = "😹" rs[46] = " دوم حبي ❤️" ws[47] = "🌚" rs[47] = " منور صخام الجدر 🌚🍃" ws[48] = "😍" rs[48] = " مح فديتك" ws[49] = "مح" rs[49] = " فوديتك❤️" ws[50] = "انمي" rs[50] = " اته اوتاكو ؟ ❤️" ws[51] = "منحرف" rs[51] = " وينه حطرده 🌚🌚" ws[52] = "😭" rs[52] = " 😢😢 لتبجي" ws[53] = "😢" rs[53] = " لتبجي 😭😭" ws[54] = "شكد عمرك" rs[54] = "زاحفه 😂😂" ws[55] = "شكد عمرج" rs[55] = " زاحف 😂" ws[56] = "اقرالي دعاء" rs[56] = " اللهم عذب المدرسين 😢 منهم الاحياء والاموات 😭🔥 اللهم عذب ام الانكليزي 😭💔 وكهربها بلتيار الرئيسي 😇 اللهم عذب ام الرياضيات وحولها الى غساله بطانيات 🙊 اللهم عذب ام الاسلاميه واجعلها بائعة الشاميه 😭🍃 اللهم عذب ام العربي وحولها الى بائعه البلبي اللهم عذب ام الجغرافيه واجعلها كلدجاجه الحافية اللهم عذب ام التاريخ وزحلقها بقشره من البطيخ وارسلها الى المريخ اللهم عذب ام الاحياء واجعلها كل مومياء اللهم عذب المعاون اقتله بلمدرسه بهاون 😂😂😂" ws[57] = "غبي" rs[57] = " انته الاغبى" ws[58] = "حبي" rs[58] = "كول حبي ❤️🍃" ws[59] = "منو حبيبك" rs[59] = " اختك 🙈" ws[60] = "تكرهني" rs[60] = " يي 😈" ws[61] = "اكرهك" rs[61] = " علساس اني احبك تهي بهي 😒🍃" ws[62] = "😂" rs[62] = " دوم حبي ❤️" ws[63] = "الاعضميه" rs[63] = " احسن ناس وربي❤️" ws[64] = "الكرادة" rs[64] = " احسن ناس وربي❤️" ws[65] = "شارع فلسطين" rs[65] = " احسن ناس وربي❤️" ws[66] = "ببكن ملف" rs[66] = " دي تحلم 😒😒" ws[67] = "😇" rs[67] = " اته مو ملاك اته جهنم بنفسهه 😂" ws[68] = "😐" rs[68] = " شبيك صافن 😒🔥" ws[69] = "انجب" rs[69] = " وك 😢😞" ws[70] = "حارة" rs[70] = "يي كولش 😭🍃🔥" ws[71] = "اريد السورس" rs[71] = " تدلل ادخل هنا @VIP_TEAM1 وخذة" ws[72] = "اطرد البوت" rs[72] = " راح ابقة احترمك❤️" ws[73] = "هه" rs[73] = " شدتحس" ws[74] = "شدتحس" rs[74] = " داحس بيك" ws[75] = "اكولك" rs[75] = " لتكول 😐😂" ws[76] = "اكلك" rs[76] = " لتكول 😐😂" ws[78] = "بغداد" rs[78] = " 😍 فديتهه" ws[79] = "البصرة" rs[79] = " احسن ناس وربي❤️" ws[80] = "تركماني" rs[80] = " والنعم منك❤️" ws[81] = "يا سورس هذا" rs[81] = "🌐VIP🏅TEAM🌐" ws[83] = "باي" rs[83] = " بايات ❤️🍃" ws[84] = "تنح" rs[84] = "عيب ابني 😒🍃" ws[85] = "جوعان" rs[85] = "تعال اكلني 😐😂" ws[86] = "عطشان" rs[86] = "روح اشرب مي" ws[87] = "صايم" rs[87] = "شسويلك 😐🍃" ws[88] = "☹️" rs[88] = "لضوج حبيبي 😢❤️🍃" ws[89] = "😔" rs[89] = " ليش الحلو ضايج ❤️🍃" ws[90] = "فرخ" rs[90] = " عيبب 😱😱" ws[92] = "كسمك" rs[92] = " عيب 😱😱😱" ws[93] = "نعال" rs[93] = " بوجهك 😐😂" ws[94] = "حروح اسبح" rs[94] = " واخيراً 😂" ws[95] = "حروح اغسل" rs[95] = " واخيراً 😂" ws[96] = "حروح اطب للحمام" rs[96] = " واخيراً 😂" ws[97] = "حبيبتي" rs[97] = " منو هاي 😱 تخوني 😔☹" ws[98] = "كبلت" rs[98] = " بلخير 😂💔" ws[99] = "البوت عاوي" rs[99] = " اطردك ؟ 😒" ws[100] = "منور" rs[100] = " بنورك حبي 😍🍷" ws[101] = "حفلش" rs[101] = " افلش راسك" ws[102] = "كردي" rs[102] = "والنعم منك ❤️" ws[103] = "طفي السبلت" rs[103] = " تم اطفاء السبلت بنجاح 🌚🍃" ws[104] = "🌝" rs[104] = "هه" ws[105] = "اذن المغرب" rs[105] = "كومو صلو" ws[106] = "حلو" rs[106] = "انت الاحلى 🌚❤️" ws[107] = "احبك" rs[107] = " اني اكثر 😍🍃" ws[108] = "😑" rs[108] = " شبيك 🍃☹" ws[109] = "😒" rs[109] = "😐 شبيك كالب وجهك " ws[110] = "منو تحب" rs[110] = "خالتك الشكرة" ws[111] = "باجر عيد ميلادي" rs[111] = "كل عام وانت بالف خير حبي 😇❤️" ws[112] = "فديت" rs[112] = "ها زاحف كمشتك" ws[113] = "مضغوط" rs[113] = "دي انضغظ منك ؟ 😂😂" ws[114] = "فديت" rs[114] = "ها زاحف كمشتك" ws[115] = "فديتك" rs[115] = "ها زاحف كمشتك" ws[116] = "فديتج" rs[116] = "ها زاحف كمشتك" ws[117] = "شوف خاصك" rs[117] = "شدازله 😱😨" ws[118] = "تعال خاص" rs[118] = "شحسوون 😱" ws[119] = "تعالي خاص" rs[119] = "شحسوون 😱" ws[120] = "دخل السبام" rs[120] = "🌝😹لو تجيبون الف سبام متكدرولي" ws[121] = "😎" rs[121] = "يلا عود انته فد نعال 😐🍃" ws[122] = "😱" rs[122] = "خير خوفتني 😨" ws[123] = "كحبه" rs[123] = "عيب 😱" ws[124] = "بيش ساعة" rs[124] = "ما اعرف 🌚🍃" ws[125] = "🚶🏻" rs[125] = "وين رايح🌝😞" ws[126] = "منو اكثر واحد تحبه" rs[126] = "خالتك" ws[127] = "ليش" rs[127] = "😐😹بكيفي" ws[128] = "طاسه" rs[128] = "امك حلوة ورقاصه 💃🏻" ws[129] = "عشرين" rs[129] = "تاكل جدر خنين 😫" ws[130] = "ميه" rs[130] = "😂تشرب مميه" ws[131] = "اربعة" rs[131] = "😂لحيه ابوك مربعه" ws[132] = "فارة" rs[132] = "😂دفترك كله صفارة" ws[133] = "ميتين" rs[133] = "😂فوك راسك قندرتين" ws[134] = "مات" rs[134] = "ابو الحمامات 🐦" ws[135] = "توفه" rs[135] = "ابو اللفه 🌯" ws[136] = "احترك" rs[136] = "🍾البو العرك" ws[137] = "غرك" rs[137] = "ابو العرك 🍾" ws[138] = "طار" rs[138] = "ابن الطيار" ws[139] = "ديسحك" rs[139] = "😂😂 هاي بعده" ws[140] = "لتسحك" rs[140] = "😐😂 وك" ws[141] = "اندرويد" rs[141] = "افشل نظام بلعالم 🌝🍷" ws[142] = "صادق" rs[142] = "وهل يخفى القمر🌝💋" ws[143] = "ايفون" rs[143] = "فديتك اته والايفون 🌚🔥" ws[144] = "مصطفى" rs[144] = "وهل يخفى القمر🌝💋" ws[145] = "محمد" rs[145] = "وهل يخفى القمر🌝💋" ws[146] = "لتزحف" rs[146] = "وك اسف 🙁😔" ws[147] = "حاته" rs[147] = "زاحف 😂 منو هاي دزلي صورتهه" ws[148] = "حات" rs[148] = "زاحفه 😂 منو هذا دزيلي صورته" ws[149] = "صاكه" rs[149] = "زاحف 😂 منو هاي دزلي صورتهه" ws[150] = "صاك" rs[150] = "زاحفه 😂 منو هذا دزيلي صورهه" ws[151] = "منو اني" rs[151] = "انته احلى شي بحياتي ❤️🍃" ws[152] = "ابن الكلب" rs[152] = "عيب ابني 🔥☹" ws[153] = "انجب انته" rs[153] = "وك وك 😭😔" ws[154] = "حطردك" rs[154] = "اعصابك 😨 لتتهور" ws[155] = "المطور" rs[155] = "ارسل كلمة المطورين" ws[156] = "منو اكثر واحد تكرهه" rs[156] = "انته" ws[157] = "شباب" rs[157] = "نعم حبي 🌝❤️" ws[158] = "اته زلمه" rs[158] = "تعال لزمه 😐😂" ws[159] = "الاحد" rs[159] = "هذا اليوم نحس بلنسبه الي" ws[160] = "الاثنين" rs[160] = "يوم اجة بي ناس عزيزين وفقدت بي ناس هم ☹" ws[161] = "هلاوو" rs[161] = "هلاوات ❤️🍃" ws[162] = "اختك" rs[162] = "شبيهه 😱" ws[163] = "كواد" rs[163] = "عيب 😨😨" ws[164] = "😌" rs[164] = "المطلوب ؟" ws[165] = "هلا" rs[165] = " 🌚🍃هلاوات" ws[166] = "مرحبا" rs[166] = "مرحبتين 😍🍃" ws[167] = "سلام" rs[167] = "السلام عليكم 🌝🍃" ws[168] = "السلام" rs[168] = "السلام عليكم 🌝🍃" ws[169] = "السلام عليكم" rs[169] = "عليكم السلام 🌝🍃" ws[170] = "تسلم" rs[170] = "الله يسلمك 😍" ws[171] = "😕" rs[171] = "🐸🍃 شبيك ضلعي" ws[172] = "/" rs[172] = "هاي عود اته جبير 😐😂 خزيتنه" ws[173] = "😐😂" rs[173] = "فديت للضحكة هاي ☺️💔🍃" ws[174] = "حارة" rs[174] = "يي كولش 😿💔🍃" ws[175] = "باردة" rs[175] = "😐💔 صيف وباردة" ws[176] = "تفليش" rs[176] = "دنجب جرجف🌝😹 " ws[177] = "علوكي" rs[177] = "وهل يخفى القمر🌝💋" ws[178] = "شادو" rs[178] = "وهل يخفى القمر؟🌝💋" ws[179] = "عبود" rs[179] = "وهل يخفى القمر؟🌝💋" ws[180] = "💃🏻" rs[180] = "شدد 💃🏻💃🏻" ws[181] = "🏃🏻" rs[181] = "لتركض تنجبح 😐😂" ws[182] = "ايباه" rs[182] = "🌚🚀 شعبالك لعد" ws[183] = "ابو المولدة" rs[183] = "مال حرك وربي ☺️🔥" ws[188] = "كلخرا" rs[188] = "��💨 جان اكلتك" ws[185] = "احم" rs[185] = "اشرب مي كلبي 🌝🍃" ws[186] = "جاو" rs[186] = "الله وياك والتكسي على حسابي 🚖" ws[187] = "دي" rs[187] = "اخلاقك حبي هذا الكروب محترم التزم لا تنشحت 😕💔🍃" ws[189] = "انتي منين" rs[189] = "اهوو هاي راح يبده الزحف انتي منين وبعدين عمرج و اسمج😼😾😹" ws[190] = "شسمج" rs[190] = "😂🍃كام يشتغل ابو الجناسي" ws[203] = "من وين من بغداد" rs[203] = "سبحان الله حيطلع جيرانكم 😹🤔" ws[191] = "خرب" rs[191] = "تمالك اعصابك كبدي اموااح 😘 عدة الشقة" ws[192] = "ولي" rs[192] = "راح اعبرها هلمره 🚶🏻💔" ws[193] = "اقرالي شعر" rs[193] = "بيدك تسد الباب🚪 وبيدك تفتحة وبيدك تفتح الباب وبيدك تستده 🌞🚀" ws[194] = "خاص" rs[194] = "بدة الزحف 😹🍃" ws[195] = "خاصك" rs[195] = "😹 اخذوني وياكم بس اتفرج ولله 😹😹" ws[196] = "🤔" rs[196] = "اعوذ بالله من تفكيرك🙁" ws[197] = "اتفل عليه" rs[197] = "🌝🍃 اعذرني مو من اخلاقي هاي" ws[198] = "🙇🏻" rs[198] = "ها حبي 😕🍃" ws[199] = "☺️" rs[199] = "فديت شكلك 😍🍃" ws[200] = "🌞" rs[200] = "منور حبي 😍🔥" ws[201] = "🙈" rs[201] = "اوي عيني الخجل يمه 🙈🙊" ws[202] = "تيم" rs[202] = "🌐VIP🏅TEAM🌐" -- the main function function run( msg, matches ) -- just a local variables that i used in my algorithm local i = 0; local w = false -- the main part that get the message that the user send and check if it equals to one of the words in the ws table :) -- this section loops through all the words table and assign { k } to the word index and { v } to the word itself for k,v in pairs(ws) do -- change the message text to uppercase and the { v } value that toke form the { ws } table and than compare it in a specific pattern if ( string.find(string.upper(msg.text), "^" .. string.upper(v) .. "$") ) then -- assign the { i } to the index of the reply and the { w } to true ( we will use it later ) i = k; w = true; end end -- check if { w } is not false and { i } not equals to 0 if ( (w ~= false) and (i ~= 0) ) then -- get the receiver :3 R = get_receiver(msg) -- send him the proper message from the index that { i } assigned to --send_large_msg ( R , rs[i] ); --send_reply(msg.id, rs[i]) reply_msg(msg.id, rs[i], ok_cb, false ) end -- don't edit this section if ( msg.text == "about" ) then if ( msg.from.username == "Mouamle" ) then R = get_receiver(msg) send_large_msg ( R , "Made by @Mouamle" ); end end end return { patterns = { "(.*)" }, run = run } end
gpl-2.0
artzde/openwrt_tp-link_wr1043nd
Modified_LuCI_Files/vlan.lua
1
9681
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network.")) local switches = { } m.uci:foreach("network", "switch", function(x) local sid = x['.name'] local switch_name = x.name or sid local has_vlan = nil local has_learn = nil local has_vlan4k = nil local has_qos = nil local has_jumbo3 = nil local has_mirror = nil local min_vid = 0 local max_vid = 16 local num_vlans = 16 local cpu_port = 5 local num_ports = 6 local switch_title local enable_vlan4k = false -- Parse some common switch properties from swconfig help output. local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name) if swc then local is_port_attr = false local is_vlan_attr = false while true do local line = swc:read("*l") if not line then break end if line:match("^%s+%-%-vlan") then is_vlan_attr = true elseif line:match("^%s+%-%-port") then is_vlan_attr = false is_port_attr = true elseif line:match("cpu @") then switch_title = line:match("^switch%d: %w+%((.-)%)") num_ports, cpu_port, num_vlans = line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)") num_ports = tonumber(num_ports) or 6 num_vlans = tonumber(num_vlans) or 16 cpu_port = tonumber(cpu_port) or 5 min_vid = 1 elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end elseif line:match(": enable_vlan4k") then enable_vlan4k = true elseif line:match(": enable_qos") then has_qos = "enable_qos" elseif line:match(": enable_vlan") then has_vlan = "enable_vlan" elseif line:match(": enable_learning") then has_learn = "enable_learning" elseif line:match(": enable_mirror_rx") then has_mirror = "enable_mirror_rx" elseif line:match(": max_length") then has_jumbo3 = "max_length" end end swc:close() end -- Switch properties s = m:section(NamedSection, x['.name'], "switch", switch_title and translatef("Switch %q (%s)", switch_name, switch_title) or translatef("Switch %q", switch_name)) s.addremove = false if has_vlan then s:option(Flag, has_vlan, translate("Enable VLAN functionality")) end if has_learn then x = s:option(Flag, has_learn, translate("Enable learning and aging")) x.default = x.enabled end if has_qos then s:option(Flag, has_qos, "Enable QoS") end if has_jumbo3 then x = s:option(ListValue, has_jumbo3, translate("Enable Jumbo Frame passthrough")) x:value("0", "1522") x:value("1", "1536") x:value("2", "1552") x:value("3", "9216") end -- Does this switch support port mirroring? if has_mirror then s:option(Flag, "enable_mirror_rx", translate("Enable mirroring of incoming packets")) s:option(Flag, "enable_mirror_tx", translate("Enable mirroring of outgoing packets")) s:option(Flag, "enable_mirror_pause_frames", translate("Enable mirroring of incoming pause frames")) local sp = s:option(ListValue, "mirror_source_port", translate("Mirror source port")) local mp = s:option(ListValue, "mirror_monitor_port", translate("Mirror monitor port")) local pt for pt = 0, num_ports - 1 do local name name = (pt == cpu_port) and translate("CPU") or translatef("Port %d", pt) sp:value(pt, name) mp:value(pt, name) end s:option(Flag, "enable_monitor_isolation", translate("Enable monitor isolation"),translate("This prevents forwarding of packets sent to the mirror port")) end -- VLAN table s = m:section(TypedSection, "switch_vlan", switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title) or translatef("VLANs on %q", switch_name)) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true -- Filter by switch s.filter = function(self, section) local device = m:get(section, "device") return (device and device == switch_name) end -- Override cfgsections callback to enforce row ordering by vlan id. s.cfgsections = function(self) local osections = TypedSection.cfgsections(self) local sections = { } local section for _, section in luci.util.spairs( osections, function(a, b) return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999) < (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999) end ) do sections[#sections+1] = section end return sections end -- When creating a new vlan, preset it with the highest found vid + 1. s.create = function(self, section, origin) -- Filter by switch if m:get(origin, "device") ~= switch_name then return end local sid = TypedSection.create(self, section) local max_nr = 0 local max_id = 0 m.uci:foreach("network", "switch_vlan", function(s) if s.device == switch_name then local nr = tonumber(s.vlan) local id = has_vlan4k and tonumber(s[has_vlan4k]) if nr ~= nil and nr > max_nr then max_nr = nr end if id ~= nil and id > max_id then max_id = id end end end) m:set(sid, "device", switch_name) m:set(sid, "vlan", max_nr + 1) if has_vlan4k then m:set(sid, has_vlan4k, max_id + 1) end return sid end local port_opts = { } local untagged = { } -- Parse current tagging state from the "ports" option. local portvalue = function(self, section) local pt for pt in (m:get(section, "ports") or ""):gmatch("%w+") do local pc, tu = pt:match("^(%d+)([tu]*)") if pc == self.option then return (#tu > 0) and tu or "u" end end return "" end -- Validate port tagging. Ensure that a port is only untagged once, -- bail out if not. local portvalidate = function(self, value, section) -- ensure that the ports appears untagged only once if value == "u" then if not untagged[self.option] then untagged[self.option] = true elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup return nil, translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1) end end return value end local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name) local mx_vid = has_vlan4k and 4094 or (num_vlans - 1) vid.rmempty = false vid.forcewrite = true vid.vlan_used = { } vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))" -- Validate user provided VLAN ID, make sure its within the bounds -- allowed by the switch. vid.validate = function(self, value, section) local v = tonumber(value) local m = has_vlan4k and 4094 or (num_vlans - 1) if v ~= nil and v >= min_vid and v <= m then if not self.vlan_used[v] then self.vlan_used[v] = true return value else return nil, translatef("Invalid VLAN ID given! Only unique IDs are allowed") end else return nil, translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m) end end -- When writing the "vid" or "vlan" option, serialize the port states -- as well and write them as "ports" option to uci. vid.write = function(self, section, value) local o local p = { } for _, o in ipairs(port_opts) do local v = o:formvalue(section) if v == "t" then p[#p+1] = o.option .. v elseif v == "u" then p[#p+1] = o.option end end if enable_vlan4k then m:set(sid, "enable_vlan4k", "1") end m:set(section, "ports", table.concat(p, " ")) return Value.write(self, section, value) end -- Fallback to "vlan" option if "vid" option is supported but unset. vid.cfgvalue = function(self, section) return m:get(section, has_vlan4k or "vlan") or m:get(section, "vlan") end -- Build per-port off/untagged/tagged choice lists. local pt for pt = 0, num_ports - 1 do local title if pt == cpu_port then title = translate("CPU") else title = translatef("Port %d", pt) end local po = s:option(ListValue, tostring(pt), title) po:value("", translate("off")) po:value("u", translate("untagged")) po:value("t", translate("tagged")) po.cfgvalue = portvalue po.validate = portvalidate po.write = function() end port_opts[#port_opts+1] = po end switches[#switches+1] = switch_name end ) -- Switch status template s = m:section(SimpleSection) s.template = "admin_network/switch_status" s.switches = switches return m
gpl-2.0
rudolfmleziva/AdministratorTeritorial
cocos2d/external/lua/luasocket/script/socket/headers.lua
31
3706
----------------------------------------------------------------------------- -- Canonic header field capitalization -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- local socket = require("socket.socket") socket.headers = {} local _M = socket.headers _M.canonic = { ["accept"] = "Accept", ["accept-charset"] = "Accept-Charset", ["accept-encoding"] = "Accept-Encoding", ["accept-language"] = "Accept-Language", ["accept-ranges"] = "Accept-Ranges", ["action"] = "Action", ["alternate-recipient"] = "Alternate-Recipient", ["age"] = "Age", ["allow"] = "Allow", ["arrival-date"] = "Arrival-Date", ["authorization"] = "Authorization", ["bcc"] = "Bcc", ["cache-control"] = "Cache-Control", ["cc"] = "Cc", ["comments"] = "Comments", ["connection"] = "Connection", ["content-description"] = "Content-Description", ["content-disposition"] = "Content-Disposition", ["content-encoding"] = "Content-Encoding", ["content-id"] = "Content-ID", ["content-language"] = "Content-Language", ["content-length"] = "Content-Length", ["content-location"] = "Content-Location", ["content-md5"] = "Content-MD5", ["content-range"] = "Content-Range", ["content-transfer-encoding"] = "Content-Transfer-Encoding", ["content-type"] = "Content-Type", ["cookie"] = "Cookie", ["date"] = "Date", ["diagnostic-code"] = "Diagnostic-Code", ["dsn-gateway"] = "DSN-Gateway", ["etag"] = "ETag", ["expect"] = "Expect", ["expires"] = "Expires", ["final-log-id"] = "Final-Log-ID", ["final-recipient"] = "Final-Recipient", ["from"] = "From", ["host"] = "Host", ["if-match"] = "If-Match", ["if-modified-since"] = "If-Modified-Since", ["if-none-match"] = "If-None-Match", ["if-range"] = "If-Range", ["if-unmodified-since"] = "If-Unmodified-Since", ["in-reply-to"] = "In-Reply-To", ["keywords"] = "Keywords", ["last-attempt-date"] = "Last-Attempt-Date", ["last-modified"] = "Last-Modified", ["location"] = "Location", ["max-forwards"] = "Max-Forwards", ["message-id"] = "Message-ID", ["mime-version"] = "MIME-Version", ["original-envelope-id"] = "Original-Envelope-ID", ["original-recipient"] = "Original-Recipient", ["pragma"] = "Pragma", ["proxy-authenticate"] = "Proxy-Authenticate", ["proxy-authorization"] = "Proxy-Authorization", ["range"] = "Range", ["received"] = "Received", ["received-from-mta"] = "Received-From-MTA", ["references"] = "References", ["referer"] = "Referer", ["remote-mta"] = "Remote-MTA", ["reply-to"] = "Reply-To", ["reporting-mta"] = "Reporting-MTA", ["resent-bcc"] = "Resent-Bcc", ["resent-cc"] = "Resent-Cc", ["resent-date"] = "Resent-Date", ["resent-from"] = "Resent-From", ["resent-message-id"] = "Resent-Message-ID", ["resent-reply-to"] = "Resent-Reply-To", ["resent-sender"] = "Resent-Sender", ["resent-to"] = "Resent-To", ["retry-after"] = "Retry-After", ["return-path"] = "Return-Path", ["sender"] = "Sender", ["server"] = "Server", ["smtp-remote-recipient"] = "SMTP-Remote-Recipient", ["status"] = "Status", ["subject"] = "Subject", ["te"] = "TE", ["to"] = "To", ["trailer"] = "Trailer", ["transfer-encoding"] = "Transfer-Encoding", ["upgrade"] = "Upgrade", ["user-agent"] = "User-Agent", ["vary"] = "Vary", ["via"] = "Via", ["warning"] = "Warning", ["will-retry-until"] = "Will-Retry-Until", ["www-authenticate"] = "WWW-Authenticate", ["x-mailer"] = "X-Mailer", } return _M
gpl-3.0
mzguanglin/LuCI
applications/luci-multiwan/luasrc/model/cbi/multiwan/multiwan.lua
7
5178
require("luci.tools.webadmin") m = Map("multiwan", translate("Multi-WAN"), translate("Multi-WAN allows for the use of multiple uplinks for load balancing and failover.")) s = m:section(NamedSection, "config", "multiwan", "") e = s:option(Flag, "enabled", translate("Enable")) e.rmempty = false function e.write(self, section, value) local cmd = (value == "1") and "enable" or "disable" if value ~= "1" then os.execute("/etc/init.d/multiwan stop") end os.execute("/etc/init.d/multiwan " .. cmd) end function e.cfgvalue(self, section) return (os.execute("/etc/init.d/multiwan enabled") == 0) and "1" or "0" end s = m:section(TypedSection, "interface", translate("WAN Interfaces"), translate("Health Monitor detects and corrects network changes and failed connections.")) s.addremove = true weight = s:option(ListValue, "weight", translate("Load Balancer Distribution")) weight:value("10", "10") weight:value("9", "9") weight:value("8", "8") weight:value("7", "7") weight:value("6", "6") weight:value("5", "5") weight:value("4", "4") weight:value("3", "3") weight:value("2", "2") weight:value("1", "1") weight:value("disable", translate("None")) weight.default = "10" weight.optional = false weight.rmempty = false interval = s:option(ListValue, "health_interval", translate("Health Monitor Interval")) interval:value("disable", translate("Disable")) interval:value("5", "5 sec.") interval:value("10", "10 sec.") interval:value("20", "20 sec.") interval:value("30", "30 sec.") interval:value("60", "60 sec.") interval:value("120", "120 sec.") interval.default = "10" interval.optional = false interval.rmempty = false icmp_hosts = s:option(Value, "icmp_hosts", translate("Health Monitor ICMP Host(s)")) icmp_hosts:value("disable", translate("Disable")) icmp_hosts:value("dns", "DNS Server(s)") icmp_hosts:value("gateway", "WAN Gateway") icmp_hosts.default = "dns" icmp_hosts.optional = false icmp_hosts.rmempty = false timeout = s:option(ListValue, "timeout", translate("Health Monitor ICMP Timeout")) timeout:value("1", "1 sec.") timeout:value("2", "2 sec.") timeout:value("3", "3 sec.") timeout:value("4", "4 sec.") timeout:value("5", "5 sec.") timeout:value("10", "10 sec.") timeout.default = "3" timeout.optional = false timeout.rmempty = false fail = s:option(ListValue, "health_fail_retries", translate("Attempts Before WAN Failover")) fail:value("1", "1") fail:value("3", "3") fail:value("5", "5") fail:value("10", "10") fail:value("15", "15") fail:value("20", "20") fail.default = "3" fail.optional = false fail.rmempty = false recovery = s:option(ListValue, "health_recovery_retries", translate("Attempts Before WAN Recovery")) recovery:value("1", "1") recovery:value("3", "3") recovery:value("5", "5") recovery:value("10", "10") recovery:value("15", "15") recovery:value("20", "20") recovery.default = "5" recovery.optional = false recovery.rmempty = false failover_to = s:option(ListValue, "failover_to", translate("Failover Traffic Destination")) failover_to:value("disable", translate("None")) luci.tools.webadmin.cbi_add_networks(failover_to) failover_to:value("fastbalancer", translate("Load Balancer(Performance)")) failover_to:value("balancer", translate("Load Balancer(Compatibility)")) failover_to.default = "balancer" failover_to.optional = false failover_to.rmempty = false dns = s:option(Value, "dns", translate("DNS Server(s)")) dns:value("auto", translate("Auto")) dns.default = "auto" dns.optional = false dns.rmempty = true s = m:section(TypedSection, "mwanfw", translate("Multi-WAN Traffic Rules"), translate("Configure rules for directing outbound traffic through specified WAN Uplinks.")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true src = s:option(Value, "src", translate("Source Address")) src.rmempty = true src:value("", translate("all")) luci.tools.webadmin.cbi_add_knownips(src) dst = s:option(Value, "dst", translate("Destination Address")) dst.rmempty = true dst:value("", translate("all")) luci.tools.webadmin.cbi_add_knownips(dst) proto = s:option(Value, "proto", translate("Protocol")) proto:value("", translate("all")) proto:value("tcp", "TCP") proto:value("udp", "UDP") proto:value("icmp", "ICMP") proto.rmempty = true ports = s:option(Value, "ports", translate("Ports")) ports.rmempty = true ports:value("", translate("all", translate("all"))) wanrule = s:option(ListValue, "wanrule", translate("WAN Uplink")) luci.tools.webadmin.cbi_add_networks(wanrule) wanrule:value("fastbalancer", translate("Load Balancer(Performance)")) wanrule:value("balancer", translate("Load Balancer(Compatibility)")) wanrule.default = "fastbalancer" wanrule.optional = false wanrule.rmempty = false s = m:section(NamedSection, "config", "", "") s.addremove = false default_route = s:option(ListValue, "default_route", translate("Default Route")) luci.tools.webadmin.cbi_add_networks(default_route) default_route:value("fastbalancer", translate("Load Balancer(Performance)")) default_route:value("balancer", translate("Load Balancer(Compatibility)")) default_route.default = "balancer" default_route.optional = false default_route.rmempty = false return m
apache-2.0
RebootRevival/FFXI_Test
scripts/globals/mobskills/mijin_gakure.lua
32
1342
--------------------------------------------------- -- Mijin Gakure --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:getMobMod(MOBMOD_SCRIPTED_2HOUR) == 1) then return 0; elseif (skill:getParam() == 2 and math.random() <= 0.5) then -- not always used return 1; elseif (mob:getHPP() <= mob:getMobMod(MOBMOD_2HOUR_PROC)) then return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = 1; local hpmod = skill:getHPP() / 100; local basePower = 6; -- Maat has a weaker Mijin if (mob:getFamily() == 335) then basePower = 4; end local power = hpmod * 10 + basePower; local baseDmg = mob:getWeaponDmg() * power; local info = MobMagicalMove(mob,target,skill,baseDmg,ELE_NONE,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,MOBPARAM_IGNORE_SHADOWS); if (mob:isInDynamis()) then -- dynamis mobs will kill themselves -- other mobs might not mob:setHP(0); end target:delHP(dmg); return dmg; end;
gpl-3.0
petoju/awesome
tests/examples/shims/root.lua
3
4718
local root = {_tags={}} local gtable = require("gears.table") function root:tags() return root._tags end function root.size() local geo = {x1 = math.huge, y1 = math.huge, x2 = 0, y2 = 0} for s in screen do geo.x1 = math.min( geo.x1, s.geometry.x ) geo.y1 = math.min( geo.y1, s.geometry.y ) geo.x2 = math.max( geo.x2, s.geometry.x+s.geometry.width ) geo.y2 = math.max( geo.y2, s.geometry.y+s.geometry.height ) end return math.max(0, geo.x2-geo.x1), math.max(0, geo.y2 - geo.y1) end function root.size_mm() local w, h = root.size() return (w/96)*25.4, (h/96)*25.4 end function root.cursor() end -- GLOBAL KEYBINDINGS -- local keys = {} function root._keys(k) keys = k or keys return keys end -- FAKE INPUTS -- -- Turn keysym into modkey names local conversion = { Super_L = "Mod4", Control_L = "Control", Shift_L = "Shift", Alt_L = "Mod1", Super_R = "Mod4", Control_R = "Control", Shift_R = "Shift", Alt_R = "Mod1", } -- The currently pressed modkeys. local mods = {} local function get_mods() local ret = {} for mod in pairs(mods) do table.insert(ret, mod) end return ret end local function add_modkey(key) if not conversion[key] then return end mods[conversion[key]] = true end local function remove_modkey(key) if not conversion[key] then return end mods[conversion[key]] = nil end local function match_modifiers(mods1, mods2) if #mods1 ~= #mods2 then return false end for _, mod1 in ipairs(mods1) do if not gtable.hasitem(mods2, mod1) then return false end end return true end local function execute_keybinding(key, event) for _, v in ipairs(keys) do if key == v.key and match_modifiers(v.modifiers, get_mods()) then v:emit_signal(event) return end end end local fake_input_handlers = { key_press = function(key) add_modkey(key) if keygrabber._current_grabber then keygrabber._current_grabber(get_mods(), key, "press") else execute_keybinding(key, "press") end end, key_release = function(key) remove_modkey(key) if keygrabber._current_grabber then keygrabber._current_grabber(get_mods(), key, "release") else execute_keybinding(key, "release") end end, button_press = function() --[[TODO]] end, button_release = function() --[[TODO]] end, motion_notify = function() --[[TODO]] end, } function root.fake_input(event_type, detail, x, y) assert(fake_input_handlers[event_type], "Unknown event_type") fake_input_handlers[event_type](detail, x, y) end function root._buttons() return {} end -- Send an artificial set of key events to trigger a key combination. -- It only works in the shims and should not be used with UTF-8 chars. function root._execute_keybinding(modifiers, key) for _, mod in ipairs(modifiers) do for real_key, mod_name in pairs(conversion) do if mod == mod_name then root.fake_input("key_press", real_key) break end end end root.fake_input("key_press" , key) root.fake_input("key_release", key) for _, mod in ipairs(modifiers) do for real_key, mod_name in pairs(conversion) do if mod == mod_name then root.fake_input("key_release", real_key) break end end end end -- Send artificial key events to write a string. -- It only works in the shims and should not be used with UTF-8 strings. function root._write_string(string, c) local old_c = client.focus if c then client.focus = c end for i=1, #string do local char = string:sub(i,i) root.fake_input("key_press" , char) root.fake_input("key_release", char) end if c then client.focus = old_c end end function root.set_newindex_miss_handler(h) rawset(root, "_ni_handler", h) end function root.set_index_miss_handler(h) rawset(root, "_i_handler", h) end return setmetatable(root, { __index = function(self, key) if key == "screen" then return screen[1] end local h = rawget(root,"_i_handler") if h then return h(self, key) end end, __newindex = function(...) local h = rawget(root,"_ni_handler") if h then h(...) end end, }) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Apollyon/Zone.lua
31
11702
----------------------------------- -- -- Zone: Apollyon -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; require("scripts/zones/Apollyon/TextIDs"); require("scripts/globals/limbus"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) SetServerVariable("[NW_Apollyon]UniqueID",0); SetServerVariable("[SW_Apollyon]UniqueID",0); SetServerVariable("[NE_Apollyon]UniqueID",0) ; SetServerVariable("[SE_Apollyon]UniqueID",0); SetServerVariable("[CS_Apollyon]UniqueID",0); SetServerVariable("[CS_Apollyon_II]UniqueID",0); SetServerVariable("[Central_Apollyon]UniqueID",0); SetServerVariable("[Central_Apollyon_II]UniqueID",0); zone:registerRegion(1, 637,-4,-642,642,4,-637); -- APPOLLYON_SE_NE exit zone:registerRegion(2, -642,-4,-642,-637,4,-637); -- APPOLLYON_NW_SW exit zone:registerRegion(3, 468,-4,-637, 478,4,-622); -- appolyon SE register zone:registerRegion(4, 421,-4,-98, 455,4,-78); -- appolyon NE register zone:registerRegion(5, -470,-4,-629, -459,4,-620); -- appolyon SW register zone:registerRegion(6, -455,-4,-95, -425,4,-67); -- appolyon NW register zone:registerRegion(7, -3,-4,-214, 3,4,-210); -- appolyon CS register zone:registerRegion(8, -3,-4, 207, 3,4, 215); -- appolyon Center register zone:registerRegion(20, 396,-4,-522, 403,4,-516); -- appolyon SE telporter floor1 to floor2 zone:registerRegion(21, 116,-4,-443, 123,4,-436); -- appolyon SE telporter floor2 to floor3 zone:registerRegion(22, 276,-4,-283, 283,4,-276); -- appolyon SE telporter floor3 to floor4 zone:registerRegion(23, 517,-4,-323, 523,4,-316); -- appolyon SE telporter floor4 to entrance zone:registerRegion(24, 396,-4,76, 403,4,83); -- appolyon NE telporter floor1 to floor2 zone:registerRegion(25, 276,-4,356, 283,4,363); -- appolyon NE telporter floor2 to floor3 zone:registerRegion(26, 236,-4,517, 243,4,523); -- appolyon NE telporter floor3 to floor4 zone:registerRegion(27, 517,-4,637, 523,4,643); -- appolyon NE telporter floor4 to floor5 zone:registerRegion(28, 557,-4,356, 563,4,363); -- appolyon NE telporter floor5 to entrance zone:registerRegion(29, -403,-4,-523, -396,4,-516); -- appolyon SW telporter floor1 to floor2 zone:registerRegion(30, -123,-4,-443, -116,4,-436); -- appolyon SW telporter floor2 to floor3 zone:registerRegion(31, -283,-4,-283, -276,4,-276); -- appolyon SW telporter floor3 to floor4 zone:registerRegion(32, -523,-4,-323, -517,4,-316); -- appolyon SW telporter floor4 to entrance zone:registerRegion(33, -403,-4,76, -396,4,83); -- appolyon NW telporter floor1 to floor2 zone:registerRegion(34, -283,-4,356, -276,4,363); -- appolyon NW telporter floor2 to floor3 zone:registerRegion(35, -243,-4,516, -236,4,523); -- appolyon NW telporter floor3 to floor4 zone:registerRegion(36, -523,-4,636, -516,4,643); -- appolyon NW telporter floor4 to floor5 zone:registerRegion(37, -563,-4,356, -556,4,363); -- appolyon NW telporter floor5 to entrance 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; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if (prevZone~=33) then local playerLimbusID = player:getVar("LimbusID"); if (playerLimbusID== 1290 or playerLimbusID== 1291 or playerLimbusID== 1294 or playerLimbusID== 1295 or playerLimbusID== 1296 or playerLimbusID== 1297) then player:setPos(-668,0.1,-666); else player:setPos(643,0.1,-600); end elseif ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(643,0.1,-600); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) local regionID = region:GetRegionID(); switch (regionID): caseof { [1] = function (x) player:startEvent(0x0064); -- APPOLLYON_SE_NE exit end, [2] = function (x) player:startEvent(0x0065); -- APPOLLYON_NW_SW exit -- print("APPOLLYON_NW_SW"); end, [3] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1293); end --create instance appolyon SE end, [4] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1292); end --create instance appolyon NE end, [5] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1291); end --create instance appolyon SW end, [6] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1290); end --create instance appolyon NW end, [7] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1294); end --create instance appolyon CS end, [8] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1296); end --create instance appolyon CENTER end, -- ///////////////////////APPOLLYON SE TELEPORTER/////////////////////////////////////////// [20] = function (x) -- print("SE_telporter_f1_to_f2"); if (IsMobDead(16932992)==true and player:getAnimation()==0) then player:startEvent(0x00DB);end end, [21] = function (x) -- print("SE_telporter_f2_to_f3"); if (IsMobDead(16933006)==true and player:getAnimation()==0) then player:startEvent(0x00DA);end end, [22] = function (x) -- print("SE_telporter_f3_to_f4"); if (IsMobDead(16933020)==true and player:getAnimation()==0) then player:startEvent(0x00D8);end end, [23] = function (x) -- print("SE_telporter_f3_to_entrance"); if (IsMobDead(16933032)==true and player:getAnimation()==0) then player:startEvent(0x00D9);end end, -- /////////////////////////////////////////////////////////////////////////////////////////// -- ///////////////////// APPOLLYON NE TELEPORTER //////////////////////////////// [24] = function (x) -- print("NE_telporter_f1_to_f2"); if (IsMobDead(16933044)==true and player:getAnimation()==0) then player:startEvent(0x00D6);end end, [25] = function (x) -- print("NE_telporter_f2_to_f3"); if (IsMobDead(16933064)==true and player:getAnimation()==0) then player:startEvent(0x00D4);end --212 end, [26] = function (x) -- print("NE_telporter_f3_to_f4"); if (IsMobDead(16933086)==true and player:getAnimation()==0) then player:startEvent(0x00D2);end --210 end, [27] = function (x) -- print("NE_telporter_f4_to_f5"); if (IsMobDead(16933101)==true and player:getAnimation()==0) then player:startEvent(0x00D7);end --215 end, [28] = function (x) -- print("NE_telporter_f5_to_entrance"); if ( (IsMobDead(16933114)==true or IsMobDead(16933113)==true) and player:getAnimation()==0) then player:startEvent(0x00D5);end --213 end, -- ////////////////////////////////////////////////////////////////////////////////////////////////// -- ///////////////////// APPOLLYON SW TELEPORTER //////////////////////////////// [29] = function (x) if (IsMobDead(16932873)==true and player:getAnimation()==0) then player:startEvent(0x00D0);end --208 end, [30] = function (x) if (IsMobDead(16932885)==true and player:getAnimation()==0) then player:startEvent(0x00D1);end --209 --printf("Mimics should be 0: %u",GetServerVariable("[SW_Apollyon]MimicTrigger")); end, [31] = function (x) if (( IsMobDead(16932896)==true or IsMobDead(16932897)==true or IsMobDead(16932898)==true or IsMobDead(16932899)==true )and player:getAnimation()==0) then player:startEvent(0x00CF);end -- 207 end, [32] = function (x) if (IselementalDayAreDead()==true and player:getAnimation()==0) then player:startEvent(0x00CE);end -- 206 end, -- ////////////////////////////////////////////////////////////////////////////////////////////////// -- ///////////////////// APPOLLYON NW TELEPORTER //////////////////////////////// [33] = function (x) if (IsMobDead(16932937)==true and player:getAnimation()==0) then player:startEvent(0x00CD);end --205 end, [34] = function (x) if (IsMobDead(16932950)==true and player:getAnimation()==0) then player:startEvent(0x00CB);end --203 end, [35] = function (x) if (IsMobDead(16932963)==true and player:getAnimation()==0) then player:startEvent(0x00C9);end --201 end, [36] = function (x) if (IsMobDead(16932976)==true and player:getAnimation()==0) then player:startEvent(0x00C8);end --200 end, [37] = function (x) if (IsMobDead(16932985)==true and player:getAnimation()==0) then player:startEvent(0x00CA);end --202 end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D1 and option == 0 and GetServerVariable("[SW_Apollyon]MimicTrigger")==0) then SpawnCofferSWfloor3(); --printf("Mimics should be 1: %u",GetServerVariable("[SW_Apollyon]MimicTrigger")); elseif (csid == 0x00CF and option == 0 and GetServerVariable("[SW_Apollyon]ElementalTrigger")==0) then SetServerVariable("[SW_Apollyon]ElementalTrigger",VanadielDayElement()+1); -- printf("Elementals should be 1: %u",GetServerVariable("[SW_Apollyon]ElementalTrigger")); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0064 and option == 1) then player:setPos(557,-1,441,128,0x21); -- APPOLLYON_SE_NE exit elseif (csid == 0x0065 and option == 1) then player:setPos(-561,0,443,242,0x21); -- APPOLLYON_NW_SW exit end end;
gpl-3.0
djianq/Game
Design/Tools/xls2lua/xlslua_reader/util/colrule.lua
1
3334
------------------------------------------------------- -- 本模块用于检查列规则 -- 现在可用的列规则有: -- * ukey 相当于数据库中的Unique KEY,表示该列值需两两不同 -- * default 该列的单元格允许为空,程序分析时将使用缺省值 -- ------------------------------------------------------- local HEADER_COUNT = 2 -- 相当于数据库中的Unique KEY,表示该列值需两两不同 local function ukey(ColTable, ValidRowCount) local UniqueMap = {} -- 一定要求支持列类型 assert(#ColTable >= HEADER_COUNT, "该列不能没有列类型和列标题定义") for i=1, ValidRowCount + HEADER_COUNT do if i <= HEADER_COUNT then --skip else local Data = ColTable[i] if UniqueMap[Data] then return false, i - HEADER_COUNT, "已经存在该值:"..tostring(Data) end if not Data then return false, i - HEADER_COUNT, "出现空值!" end UniqueMap[Data] = true end end return true end -- 允许nil值 local function default(ColTable, ValidRowCount) return true end -- 表示该列每单元格必须有内容(即不为lua中的nil) local function not_default(ColTable, ValidRowCount) for i=1, ValidRowCount + HEADER_COUNT do if i <= HEADER_COUNT then --skip else local Data = ColTable[i] if Data == nil then return false, i - HEADER_COUNT, "出现空值!" end end end return true end local RuleMap = { ["ukey"] = {Func = ukey, Doc = "该列值需两两不同;且每单元格不能为空"}, ["default"] = {Func= default, Doc = "该列的单元格允许为空,程序分析时将使用缺省值"}, -- 外部不应该直接使用 ["not_default"] = {Func = not_default, Doc = "该列单元格必须全部不为空"} } ------------------------------------------------------- -- 自动处理默认的规则关系 -- 如果调整成功,则返回调整后的RuleList对象。 -- 否则,返回nil, Errmsg ------------------------------------------------------- function GetAdjustedRuleList(RuleList) local DefaultRules = {["not_default"] = true} -- 检查是否需要插入删除默认的__notnil for _, RuleName in ipairs(RuleList) do if RuleName == "ukey" then DefaultRules["not_default"] = nil elseif RuleName == "default" then DefaultRules["not_default"] = nil end end -- 将没有被排除的默认规则放到规则的前面 for RuleName, _ in pairs(DefaultRules) do table.insert(RuleList, 1, RuleName) end -- 最后检查是否规则集合有重复 local UniqueSet = {} for _, RuleName in ipairs(RuleList) do if UniqueSet[RuleName] then return nil, "列规则重复:"..RuleName end UniqueSet[RuleName] = true end return RuleList end function GetRuleDoc(RuleName) local Cfg = RuleMap[RuleName] if not Cfg then return "无规则说明" end return Cfg.Doc or "无规则说明" end ------------------------------------------------------- -- 列规则的检查函数需要返回三个值: -- 是否检查通过,出错的行号,出错信息 ------------------------------------------------------- function CheckColRule(ColTable, ValidRowCount, RuleName) local Info = RuleMap[RuleName] if not Info then return false, -1, "存在未定义的列规则名:"..tostring(RuleName) end return Info.Func(ColTable, ValidRowCount) end
mit
RebootRevival/FFXI_Test
scripts/zones/Giddeus/npcs/qm1.lua
3
1741
----------------------------------- -- Area: Giddeus -- NPC: ??? -- Involved In Quest: Dark Legacy -- @zone 145 -- !pos -58 0 -449 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) darkLegacyCS = player:getVar("darkLegacyCS"); if (darkLegacyCS == 3 or darkLegacyCS == 4) then if (trade:hasItemQty(4445,1) and trade:getItemCount() == 1) then -- Trade Yagudo Cherries player:tradeComplete(); player:messageSpecial(SENSE_OF_FOREBODING); SpawnMob(17371579):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("darkLegacyCS") == 5 and player:hasKeyItem(DARKSTEEL_FORMULA) == false) then player:addKeyItem(DARKSTEEL_FORMULA); player:messageSpecial(KEYITEM_OBTAINED,DARKSTEEL_FORMULA); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ChargeIn/CandyUI
UnitFrames/CandyUI_UnitFrames.lua
2
71252
----------------------------------------------------------------------------------------------- -- Client Lua Script for CandyUI_UnitFrames -- Copyright (c) NCsoft. All rights reserved ----------------------------------------------------------------------------------------------- -- DEVELOPER LICENSE -- CandyUI - Copyright (C) 2014 Neil Smith -- This work is licensed under the GNU GENERAL PUBLIC LICENSE. -- A copy of this license is included with this release. ----------------------------------------------------------------------------------------------- require "Window" ----------------------------------------------------------------------------------------------- -- CandyUI_UnitFrames Module Definition ----------------------------------------------------------------------------------------------- local CandyUI_UnitFrames = {} local function round(num, idp) local mult = 10 ^ (idp or 0) if num >= 0 then return math.floor(num * mult + 0.5) / mult else return math.ceil(num * mult - 0.5) / mult end end ----------------------------------------------------------------------------------------------- -- Constants ----------------------------------------------------------------------------------------------- local karClassToIcon = { [GameLib.CodeEnumClass.Warrior] = "Sprites:Class_Warrior", [GameLib.CodeEnumClass.Engineer] = "Sprites:Class_Engineer", [GameLib.CodeEnumClass.Esper] = "Sprites:Class_Esper", [GameLib.CodeEnumClass.Medic] = "Sprites:Class_Medic", [GameLib.CodeEnumClass.Stalker] = "Sprites:Class_Stalker", [GameLib.CodeEnumClass.Spellslinger] = "Sprites:Class_Spellslinger", } ----------------------------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------------------------- function CandyUI_UnitFrames:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function CandyUI_UnitFrames:Init() local bHasConfigureFunction = false local strConfigureButtonText = "" local tDependencies = { } Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies) end ----------------------------------------------------------------------------------------------- -- CandyUI_UnitFrames OnLoad ----------------------------------------------------------------------------------------------- function CandyUI_UnitFrames:OnLoad() -- load our form file self.xmlDoc = XmlDoc.CreateFromFile("CandyUI_UnitFrames.xml") self.xmlDoc:RegisterCallback("OnDocLoaded", self) self.db = Apollo.GetPackage("Gemini:DB-1.0").tPackage:New(self, kcuiUFDefaults) end ----------------------------------------------------------------------------------------------- -- CandyUI_UnitFrames OnDocLoaded ----------------------------------------------------------------------------------------------- function CandyUI_UnitFrames:OnDocLoaded() if self.db.char.currentProfile == nil and self.db:GetCurrentProfile() ~= nil then self.db.char.currentProfile = self.db:GetCurrentProfile() elseif self.db.char.currentProfile ~= nil and self.db.char.currentProfile ~= self.db:GetCurrentProfile() then self.db:SetProfile(self.db.char.currentProfile) end Apollo.LoadSprites("Sprites.xml") self.wndPlayerUF = Apollo.LoadForm(self.xmlDoc, "PlayerUF", nil, self) for i = 1, 4 do local wndCurr = Apollo.LoadForm(self.xmlDoc, "ClusterTarget", self.wndPlayerUF:FindChild("ClusterFrame"), self) end self.wndPlayerUF:FindChild("ClusterFrame"):ArrangeChildrenVert() self.wndTargetUF = Apollo.LoadForm(self.xmlDoc, "TargetUF", nil, self) for i = 1, 4 do local wndCurr = Apollo.LoadForm(self.xmlDoc, "ClusterTarget", self.wndTargetUF:FindChild("ClusterFrame"), self) end self.wndTargetUF:FindChild("ClusterFrame"):ArrangeChildrenVert() self.wndToTUF = Apollo.LoadForm(self.xmlDoc, "ToTUF", nil, self) self.wndToTUF:Show(false, true) self.wndFocusUF = Apollo.LoadForm(self.xmlDoc, "TargetUF", nil, self) self.wndFocusUF:SetName("FocusUF") self.wndFocusUF:Show(false, true) self.wndFocusUF:FindChild("Glow"):Show(true, true) --Check for Options addon local bOptionsLoaded = _cui.bOptionsLoaded if bOptionsLoaded then self:OnCUIOptionsLoaded() else Apollo.RegisterEventHandler("CandyUI_Loaded", "OnCUIOptionsLoaded", self) end --Color Picker GeminiColor = Apollo.GetPackage("GeminiColor").tPackage self.colorPicker = GeminiColor:CreateColorPicker(self, "ColorPickerCallback", false, "ffffffff") self.colorPicker:Show(false, true) Apollo.RegisterEventHandler("NextFrame", "OnCharacterLoaded", self) Apollo.RegisterEventHandler("CharacterCreated", "OnCharacterLoaded", self) Apollo.RegisterEventHandler("TargetUnitChanged", "OnTargetUnitChanged", self) Apollo.RegisterEventHandler("AlternateTargetUnitChanged", "OnAlternateTargetUnitChanged", self) Apollo.RegisterEventHandler("WindowManagementReady", "OnWindowManagementReady", self) if GameLib.GetPlayerUnit() and GameLib.GetPlayerUnit():GetTarget() then self:OnTargetUnitChanged(GameLib.GetPlayerUnit():GetTarget()) end -- Because there exists a race condition between the initialization and registration -- with the windowmanager, we're going to call the function ourselves manually. -- Just to be safe. self:OnWindowManagementReady() end -- This function is called by the Wildstar WindowManager when it's loaded and ready -- to handle all requests related to the UI. This allows us to offload this to the -- client and not track everything ourselves. function CandyUI_UnitFrames:OnWindowManagementReady() -- Register the Player UnitFrame Event_FireGenericEvent("WindowManagementRegister", { strName = "CandyUI - UnitFrames - Player", nSaveVersion = 1}) Event_FireGenericEvent("WindowManagementAdd", { wnd = self.wndPlayerUF, strName = "CandyUI - UnitFrames - Player", nSaveVersion = 1}) -- Register the Target UnitFrame Event_FireGenericEvent("WindowManagementRegister", { strName = "CandyUI - UnitFrames - Target", nSaveVersion = 1}) Event_FireGenericEvent("WindowManagementAdd", { wnd = self.wndTargetUF, strName = "CandyUI - UnitFrames - Target", nSaveVersion = 1}) -- Register the Focus UnitFrame Event_FireGenericEvent("WindowManagementRegister", { strName = "CandyUI - UnitFrames - Focus Target", nSaveVersion = 1}) Event_FireGenericEvent("WindowManagementAdd", { wnd = self.wndFocusUF, strName = "CandyUI - UnitFrames - Focus Target", nSaveVersion = 1 }) -- Register the Target of Target UnitFrame Event_FireGenericEvent("WindowManagementRegister", { strName = "CandyUI - UnitFrames - Target of Target", nSaveVersion = 1}) Event_FireGenericEvent("WindowManagementAdd", { wnd = self.wndToTUF, strName = "CandyUI - UnitFrames - Target of Target", nSaveVersion = 1 }) end function CandyUI_UnitFrames:OnCUIOptionsLoaded() --Load Options local wndOptionsControls = Apollo.GetAddon("CandyUI").wndOptions:FindChild("OptionsDialogueControls") self.wndControls = Apollo.LoadForm(self.xmlDoc, "OptionsControlsList", wndOptionsControls, self) CUI_RegisterOptions("UnitFrames", self.wndControls) self:SetOptions() self:SetLooks() end function CandyUI_UnitFrames:OnOptionsHome() self.wndOptionsMain:FindChild("ListControls"):DestroyChildren() for i, v in ipairs(self.wndControls:GetChildren()) do if v:GetName() ~= "Help" then local strCategory = v:FindChild("Title"):GetText() local wndCurr = Apollo.LoadForm(self.xmlDoc, "OptionsListItem", self.wndOptionsMain:FindChild("ListControls"), self) wndCurr:SetText(strCategory) end end self.wndOptionsMain:FindChild("ListControls"):ArrangeChildrenVert() self.wndOptionsMain:FindChild("OptionsDialogueControls"):DestroyChildren() self.wndControls = Apollo.LoadForm(self.xmlDoc, "OptionsControlsList", self.wndOptionsMain:FindChild("OptionsDialogueControls"), self) self:SetOptions() end function CandyUI_UnitFrames:OnOptionsHeaderCheck(wndHandler, wndControl, eMouseButton) for i, v in ipairs(self.wndControls:GetChildren()) do if v:FindChild("Title"):GetText() == wndControl:GetText() then v:Show(true) else v:Show(false) end end end function CandyUI_UnitFrames:OnTargetUnitChanged(unitTarget) if unitTarget ~= nil and unitTarget:GetMaxHealth() ~= nil and unitTarget:GetMaxHealth() > 0 then self.wndTargetUF:Show(true) --self.arTargetClusters = self:GetClusters(unitTarget) self:UpdateUnitFrame(self.wndTargetUF, unitTarget) if unitTarget:GetTarget() ~= nil and unitTarget:GetTarget():GetMaxHealth() ~= nil and unitTarget:GetTarget():GetMaxHealth() > 0 and self.db.profile.tot.bShow then self.wndToTUF:Show(true) self:UpdateToT(unitTarget:GetTarget()) else self.wndToTUF:Show(false) end else self.wndTargetUF:Show(false) self.wndToTUF:Show(false) end end function CandyUI_UnitFrames:OnAlternateTargetUnitChanged(unitTarget) if unitTarget ~= nil and unitTarget:GetMaxHealth() ~= nil and unitTarget:GetMaxHealth() > 0 then self.wndFocusUF:Show(true) self:UpdateUnitFrame(self.wndFocusUF, unitTarget) else self.wndFocusUF:Show(false) end end function CandyUI_UnitFrames:OnUpdate() local uPlayer = GameLib.GetPlayerUnit() if not uPlayer then --self:OnCharacterCreated() return end local x = math.floor(uPlayer:GetHealth()) local y = math.floor(uPlayer:GetMaxHealth()) self.wndPlayerUF:FindChild("HealthBar"):SetMax(y) self.wndPlayerUF:FindChild("ShieldBar"):SetMax(uPlayer:GetShieldCapacityMax()) self.wndPlayerUF:FindChild("FocusBar"):SetMax(uPlayer:GetMaxFocus()) self.wndPlayerUF:FindChild("Name"):SetText(uPlayer:GetName()) self.wndPlayerUF:FindChild("BuffContainerWindow"):SetUnit(uPlayer) self.wndPlayerUF:FindChild("HealthBar"):SetProgress(x) --Print(x) self.wndPlayerUF:FindChild("ShieldBar"):SetProgress(uPlayer:GetShieldCapacity()) self.wndPlayerUF:FindChild("FocusBar"):SetProgress(uPlayer:GetFocus()) end function CandyUI_UnitFrames:OnCharacterLoaded() local unitPlayer = GameLib.GetPlayerUnit() if unitPlayer ~= nil then local unitTarget = unitPlayer:GetTarget() local unitFocus = unitPlayer:GetAlternateTarget() self.arPlayerClusters = self:GetClusters(unitPlayer) self:UpdateUnitFrame(self.wndPlayerUF, unitPlayer) self:UpdateClusters(self.arPlayerClusters, self.wndPlayerUF) self.wndPlayerUF:SetData(unitPlayer) if unitTarget ~= nil and unitTarget:GetMaxHealth() ~= nil and unitTarget:GetMaxHealth() > 0 then self.arTargetClusters = self:GetClusters(unitTarget) self:UpdateClusters(self.arTargetClusters, self.wndTargetUF) self:UpdateUnitFrame(self.wndTargetUF, unitTarget) self.wndTargetUF:SetData(unitTarget) if unitTarget:GetTarget() ~= nil and unitTarget:GetTarget():GetMaxHealth() ~= nil and unitTarget:GetTarget():GetMaxHealth() > 0 then --self.wndToTUF:Show(true) self.wndToTUF:SetData(unitTarget:GetTarget()) self:UpdateToT(unitTarget:GetTarget()) end end self:UpdateUnitFrame(self.wndFocusUF, unitFocus) self.wndFocusUF:SetData(unitFocus) end end function CandyUI_UnitFrames:HelperFormatBigNumber(nArg) if nArg < 1000 then strResult = tostring(nArg) elseif nArg < 1000000 then if math.floor(nArg % 1000 / 100) == 0 then strResult = String_GetWeaselString(Apollo.GetString("TargetFrame_ShortNumberWhole"), math.floor(nArg / 1000)) else strResult = String_GetWeaselString(Apollo.GetString("TargetFrame_ShortNumberFloat"), nArg / 1000) end elseif nArg < 1000000000 then if math.floor(nArg % 1000000 / 100000) == 0 then strResult = String_GetWeaselString(Apollo.GetString("TargetFrame_MillionsNumberWhole"), math.floor(nArg / 1000000)) else strResult = String_GetWeaselString(Apollo.GetString("TargetFrame_MillionsNumberFloat"), nArg / 1000000) end elseif nArg < 1000000000000 then if math.floor(nArg % 1000000 / 100000) == 0 then strResult = String_GetWeaselString(Apollo.GetString("TargetFrame_BillionsNumberWhole"), math.floor(nArg / 1000000)) else strResult = String_GetWeaselString(Apollo.GetString("TargetFrame_BillionsNumberFloat"), nArg / 1000000) end else strResult = tostring(nArg) end return strResult end function CandyUI_UnitFrames:UpdateUnitFrame(wndFrame, uUnit) if uUnit == nil then return end --wndFrame:Show(true) --set up frame --name local strSeperator = " - " local strName = uUnit:GetName() local nLevel = uUnit:GetLevel() or "" local crName = uUnit:GetNameplateColor() --Name wndFrame:FindChild("Name"):SetText(strName .. strSeperator .. nLevel) wndFrame:FindChild("Name"):SetTextColor(crName) --Buffs/Debuffs wndFrame:FindChild("BuffContainerWindow"):SetUnit(uUnit) wndFrame:FindChild("DebuffContainerWindow"):SetUnit(uUnit) --Bars local barHealth = wndFrame:FindChild("HealthBar:Bar") local barShield = wndFrame:FindChild("ShieldBar:Bar") local barFocus = wndFrame:FindChild("FocusBar:Bar") --wndFrame:FindChild("HealthBarBG"):Show(false, true) --wndFrame:FindChild("HealthBarBG"):Show(true, true) --wndFrame:FindChild("HealthBarBG"):ToFront(true) --barHealth:ToFront(true) --Font Size barHealth:FindChild("Text"):SetFont(self.db.profile.general.strFontSize) barShield:FindChild("Text"):SetFont(self.db.profile.general.strFontSize) barFocus:FindChild("Text"):SetFont(self.db.profile.general.strFontSize) --Absorb local nAbsorbCurr = 0 local nAbsorbMax = uUnit:GetAbsorptionMax() if nAbsorbMax > 0 then nAbsorbCurr = uUnit:GetAbsorptionValue() end self:SetBarValue(wndFrame:FindChild("HealthBar:AbsorbBar"), nAbsorbCurr, 0, nAbsorbMax) --[[ local bShowAbsorbText = wndFrame:GetName() == "PlayerUF" and self.db.profile.player.bAbsorbText or wndFrame:GetName() == "TargetUF" and self.db.profile.target.bAbsorbText or wndFrame:GetName() == "FocusUF" and self.db.profile.focus.bAbsorbText if bShowAbsorbText and nAbsorbMax > 0 then wndFrame:FindChild("HealthBar:AbsorbBar"):SetText(self:HelperFormatBigNumber(nAbsorbCurr).." / "..self:HelperFormatBigNumber(nAbsorbMax)) else wndFrame:FindChild("HealthBar:AbsorbBar"):SetText("") end ]] --Health local nHealthMax = uUnit:GetMaxHealth() local nHealthCurr = uUnit:GetHealth() local nHealthPerc = round((nHealthCurr / nHealthMax) * 100) if nAbsorbMax > 0 then self:SetBarValue(barHealth, nHealthCurr, 0,(nHealthMax/80)*100) else self:SetBarValue(barHealth, nHealthCurr, 0, nHealthMax) end --Health Text local nShowHealthText = wndFrame:GetName() == "PlayerUF" and self.db.profile.player.nHealthText or wndFrame:GetName() == "TargetUF" and self.db.profile.target.nHealthText or wndFrame:GetName() == "FocusUF" and self.db.profile.focus.nHealthText local nHealthFormat = wndFrame:GetName() == "PlayerUF" and self.db.profile.player.nHealthFormat or wndFrame:GetName() == "TargetUF" and self.db.profile.target.nHealthFormat or wndFrame:GetName() == "FocusUF" and self.db.profile.focus.nHealthFormat local bShowHealthText = nShowHealthText == 1 or nShowHealthText == 2 barHealth:FindChild("Text"):Show(bShowHealthText, true) barHealth:FindChild("Text"):SetStyle("AutoFade", nShowHealthText == 2) if nShowHealthText == 1 and barHealth:FindChild("Text"):GetOpacity() < 1 then barHealth:FindChild("Text"):SetOpacity(1) end local strHealthText = "" if nHealthFormat == 0 then --Min / Max strHealthText = nHealthCurr .. " / " .. nHealthMax elseif nHealthFormat == 1 then --Min / Max (Short) strHealthText = self:HelperFormatBigNumber(nHealthCurr) .. " / " .. self:HelperFormatBigNumber(nHealthMax) elseif nHealthFormat == 2 then --Percent strHealthText = nHealthPerc .. "%" elseif nHealthFormat == 3 then --Min / Max (Percent) strHealthText = self:HelperFormatBigNumber(nHealthCurr) .. " / " .. self:HelperFormatBigNumber(nHealthMax) .. " (" .. nHealthPerc .. "%)" end local bShowShieldText = false --wndFrame:GetName() == "PlayerUF" and self.db.profile.player.bShowShieldText or wndFrame:GetName() == "TargetUF" and self.db.profile.target.bShowShieldText or wndFrame:GetName() == "FocusUF" and self.db.profile.focus.bShowShieldText local nShieldPerc = "" --replace with text local nShieldText = "[" .. nShieldPerc .. "%]" if bShowShieldText then barHealth:FindChild("Text"):SetText(strHealthText .. " " .. nShieldText) else barHealth:FindChild("Text"):SetText(strHealthText) end --Color by health local bColorByHealth = wndFrame:GetName() == "PlayerUF" and self.db.profile.player.bColorByHealth or wndFrame:GetName() == "TargetUF" and self.db.profile.target.bColorByHealth or wndFrame:GetName() == "FocusUF" and self.db.profile.focus.bColorByHealth if bColorByHealth then local nPercDec = nHealthPerc / 100 local crRed = 1 - nPercDec local crGreen = nPercDec local crBlue = 0 barHealth:SetBarColor(ApolloColor.new(crRed, crGreen, crBlue)) end --Shield --wndFrame:FindChild("HealthBarBG"):SetSprite("Sprites:HealthEmpty_Grey") local nShieldMax = uUnit:GetShieldCapacityMax() local nShieldCurr = uUnit:GetShieldCapacity() nShieldPerc = round((nShieldCurr / nShieldMax) * 100) --Print(nShieldCurr) if nShieldMax ~= nil and nShieldMax > 0 then if wndFrame:FindChild("ShieldBar"):IsShown() then self:SetBarValue(barShield, nShieldCurr, 0, nShieldMax) barShield:FindChild("Text"):SetText(nShieldPerc .. "%") else --barShield:Show(true, true) wndFrame:FindChild("ShieldBar"):Show(true, true) wndFrame:FindChild("HealthBar"):SetSprite("Sprites:HealthEmpty_Grey") --barHealth:SetEmptySprite("Sprites:HealthEmpty_Grey") barHealth:SetFullSprite("Sprites:HealthFull_Grey") wndFrame:FindChild("HealthBar:AbsorbBar"):SetFullSprite("Sprites:ShieldFull_Grey") local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() wndFrame:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nsl - 4, nhb) --barHealth:SetAnchorOffsets(nhl, nht, nsl-4, nhb) self:SetBarValue(barShield, nShieldCurr, 0, nShieldMax) barShield:FindChild("Text"):SetText(nShieldPerc .. "%") end else --Print(nShieldCurr) if not wndFrame:FindChild("ShieldBar"):IsShown() then -- self:SetBarValue(barShield, nShieldCurr, 0, nShieldMax) else --barShield:Show(false, true) wndFrame:FindChild("ShieldBar"):Show(false, true) wndFrame:FindChild("HealthBar"):SetSprite("Sprites:HealthEmpty_RoundedGrey") --barHealth:SetEmptySprite("Sprites:HealthEmpty_RoundedGrey") barHealth:SetFullSprite("Sprites:HealthFull_RoundedGrey") wndFrame:FindChild("HealthBar:AbsorbBar"):SetFullSprite("Sprites:ShieldFull_Grey") local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() wndFrame:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nsr, nhb) --barHealth:SetAnchorOffsets(nhl, nht, nsr, nhb) end end --Focus local nFocusMax = uUnit:GetMaxFocus() or 0 local nFocusCurr = uUnit:GetFocus() or 0 local nShowFocusText = wndFrame:GetName() == "PlayerUF" and self.db.profile.player.nFocusText or wndFrame:GetName() == "TargetUF" and self.db.profile.target.nFocusText or wndFrame:GetName() == "FocusUF" and self.db.profile.focus.nFocusText local nFocusFormat = wndFrame:GetName() == "PlayerUF" and self.db.profile.player.nFocusFormat or wndFrame:GetName() == "TargetUF" and self.db.profile.target.nFocusFormat or wndFrame:GetName() == "FocusUF" and self.db.profile.focus.nFocusFormat local bShowFocusText = nShowFocusText == 1 or nShowFocusText == 2 local nFocusPerc = round((nFocusCurr / nFocusMax) * 100) if nFocusMax ~= nil and nFocusMax > 5 then if barFocus:IsShown() then self:SetBarValue(barFocus, nFocusCurr, 0, nFocusMax) --Text barFocus:FindChild("Text"):Show(bShowFocusText, true) barFocus:FindChild("Text"):SetStyle("AutoFade", nShowFocusText == 2) if nShowFocusText == 1 and barFocus:FindChild("Text"):GetOpacity() < 1 then barFocus:FindChild("Text"):SetOpacity(1) end local strFocusText = "" if nFocusFormat == 0 then --Min / Max strFocusText = nFocusCurr .. " / " .. nFocusMax elseif nFocusFormat == 1 then --Min / Max (Short) strFocusText = self:HelperFormatBigNumber(nFocusCurr) .. " / " .. self:HelperFormatBigNumber(nFocusMax) elseif nFocusFormat == 2 then --Percent strFocusText = nFocusPerc .. "%" elseif nFocusFormat == 3 then --Min / Max (Percent) strFocusText = self:HelperFormatBigNumber(nFocusCurr) .. " / " .. self:HelperFormatBigNumber(nFocusMax) .. " (" .. nFocusPerc .. "%)" end barFocus:FindChild("Text"):SetText(strFocusText) else --barFocus:Show(true, true) wndFrame:FindChild("FocusBar"):Show(true) local nml, nmt, nmr, nmb = wndFrame:FindChild("FocusBar"):GetAnchorOffsets() local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() --barHealth:SetAnchorOffsets(nhl, nht, nhr, nht+29) wndFrame:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nhr, nht + 29) --barShield:SetAnchorOffsets(nsl, nst, nsr, nst+29) wndFrame:FindChild("ShieldBar"):SetAnchorOffsets(nsl, nst, nsr, nst + 29) self:SetBarValue(barFocus, nFocusCurr, 0, nFocusMax) --Text barFocus:FindChild("Text"):Show(bShowFocusText, true) barFocus:FindChild("Text"):SetStyle("AutoFade", nShowFocusText == 2) if nShowFocusText == 1 and barFocus:FindChild("Text"):GetOpacity() < 1 then barFocus:FindChild("Text"):SetOpacity(1) end local strFocusText = "" if nFocusFormat == 0 then --Min / Max strFocusText = nFocusCurr .. " / " .. nFocusMax elseif nFocusFormat == 1 then --Min / Max (Short) strFocusText = self:HelperFormatBigNumber(nFocusCurr) .. " / " .. self:HelperFormatBigNumber(nFocusMax) elseif nFocusFormat == 2 then --Percent strFocusText = nFocusPerc .. "%" elseif nFocusFormat == 3 then --Min / Max (Percent) strFocusText = self:HelperFormatBigNumber(nFocusCurr) .. " / " .. self:HelperFormatBigNumber(nFocusMax) .. " (" .. nFocusPerc .. "%)" end barFocus:FindChild("Text"):SetText(strFocusText) end else --barFocus:Show(false, true) wndFrame:FindChild("FocusBar"):Show(false) local nml, nmt, nmr, nmb = wndFrame:FindChild("FocusBar"):GetAnchorOffsets() local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() --barHealth:SetAnchorOffsets(nhl, nht, nhr, nmb) wndFrame:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nhr, nmb) --barShield:SetAnchorOffsets(nsl, nst, nsr, nmb) wndFrame:FindChild("ShieldBar"):SetAnchorOffsets(nsl, nst, nsr, nmb) end --Icon local eRank = uUnit:GetRank() local strClassIconSprite = "" local strPlayerIconSprite = "" if uUnit:GetType() == "Player" then strPlayerIconSprite = karClassToIcon[uUnit:GetClassId()] elseif eRank == Unit.CodeEnumRank.Elite then strClassIconSprite = "Sprites:TargetIcon_Elite" strPlayerIconSprite = strClassIconSprite .. "_Large" elseif eRank == Unit.CodeEnumRank.Superior then strClassIconSprite = "Sprites:TargetIcon_Superior" strPlayerIconSprite = strClassIconSprite .. "_Large" elseif eRank == Unit.CodeEnumRank.Champion then strClassIconSprite = "Sprites:TargetIcon_Champion" strPlayerIconSprite = strClassIconSprite .. "_Large" elseif eRank == Unit.CodeEnumRank.Standard then strClassIconSprite = "Sprites:TargetIcon_Standard" strPlayerIconSprite = strClassIconSprite .. "_Large" elseif eRank == Unit.CodeEnumRank.Minion then strClassIconSprite = "Sprites:TargetIcon_Minion" strPlayerIconSprite = strClassIconSprite .. "_Large" elseif eRank == Unit.CodeEnumRank.Fodder then strClassIconSprite = "Sprites:TargetIcon_Fodder" strPlayerIconSprite = strClassIconSprite .. "_Large" end wndFrame:FindChild("TargetIcons"):FindChild("TargetIcon"):SetSprite(strClassIconSprite) wndFrame:FindChild("Icon"):FindChild("IconPic"):SetSprite(strPlayerIconSprite) --if wndFrame:FindChild("Icon"):FindChild("IconPic"):GetOpacity() ~= 0.4 then -- wndFrame:FindChild("Icon"):FindChild("IconPic"):SetOpacity(0.4) --end --Group Size if wndFrame:FindChild("TargetIcons:GroupSize") then wndFrame:FindChild("TargetIcons:GroupSize"):Show(uUnit:GetGroupValue() > 0) wndFrame:FindChild("TargetIcons:GroupSize"):SetText(uUnit:GetGroupValue()) end --Quest Icon if RewardIcons ~= nil and RewardIcons.GetUnitRewardIconsForm ~= nil and wndFrame:FindChild("TargetGoalPanel") then RewardIcons.GetUnitRewardIconsForm(wndFrame:FindChild("TargetIcons:TargetGoal:Img"), uUnit, nil) end local strRewardImg = wndFrame:FindChild("TargetIcons:TargetGoal:Img"):GetSprite() if strRewardImg == "CRB_TargetFrameRewardPanelSprites:sprTargetFrame_ActiveQuest" or strRewardImg == "sprTargetFrame_ActiveQuest" then wndFrame:FindChild("TargetIcons:TargetGoal:Img"):SetSprite("Sprites:QuestIcon") --TODO: Make other Icons!!! end --Icon/Portrait local nPortStyle = wndFrame:GetName() == "PlayerUF" and self.db.profile.player.nPortraitStyle or wndFrame:GetName() == "TargetUF" and self.db.profile.target.nPortraitStyle --Replace with option if nPortStyle == 0 then --Hide local npl, npt, npr, npb = wndFrame:FindChild("Icon"):GetAnchorOffsets() local nnl, nnt, nnr, nnb = wndFrame:FindChild("Name"):GetAnchorOffsets() local nml, nmt, nmr, nmb = wndFrame:FindChild("FocusBar"):GetAnchorOffsets() --barFocus:GetAnchorOffsets() local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() -- barShield:GetAnchorOffsets() if wndFrame:GetName() == "PlayerUF" then --barHealth:SetAnchorOffsets(npl+6, nht, nhr, nhb) wndFrame:FindChild("HealthBar"):SetAnchorOffsets(npl + 6, nht, nhr, nhb) --barFocus:SetAnchorOffsets(npl+6, nmt, nmr, nmb) wndFrame:FindChild("FocusBar"):SetAnchorOffsets(npl + 6, nmt, nmr, nmb) elseif wndFrame:GetName() == "TargetUF" then barShield:SetAnchorOffsets(nsl, nst, npr - 6, nsb) wndFrame:FindChild("ShieldBar"):SetAnchorOffsets(nsl, nst, npr - 6, nsb) --barFocus:SetAnchorOffsets(nml, nmt, npr-6, nmb) wndFrame:FindChild("FocusBar"):SetAnchorOffsets(nml, nmt, npr - 6, nmb) end wndFrame:FindChild("Icon:IconPic"):Show(false, true) wndFrame:FindChild("Icon:Portrait"):Show(false, true) elseif nPortStyle == 1 then --Model local npl, npt, npr, npb = wndFrame:FindChild("Icon"):GetAnchorOffsets() local nnl, nnt, nnr, nnb = wndFrame:FindChild("Name"):GetAnchorOffsets() local nml, nmt, nmr, nmb = wndFrame:FindChild("FocusBar"):GetAnchorOffsets() --barFocus:GetAnchorOffsets() local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() -- barShield:GetAnchorOffsets() if wndFrame:GetName() == "PlayerUF" then --barHealth:SetAnchorOffsets(npr, nht, nhr, nhb) wndFrame:FindChild("HealthBar"):SetAnchorOffsets(npr, nht, nhr, nhb) --barFocus:SetAnchorOffsets(npr, nmt, nmr, nmb) wndFrame:FindChild("FocusBar"):SetAnchorOffsets(npr, nmt, nmr, nmb) elseif wndFrame:GetName() == "TargetUF" then --barShield:SetAnchorOffsets(nsl, nst, npl, nsb) wndFrame:FindChild("ShieldBar"):SetAnchorOffsets(nsl, nst, npl, nsb) --barFocus:SetAnchorOffsets(nml, nmt, npl, nmb) wndFrame:FindChild("FocusBar"):SetAnchorOffsets(nml, nmt, npl, nmb) end wndFrame:FindChild("Icon:Portrait"):Show(true) wndFrame:FindChild("Icon:Portrait"):SetData(uUnit) wndFrame:FindChild("Icon:Portrait"):SetCostume(uUnit) wndFrame:FindChild("Icon:IconPic"):Show(false, true) else --Icon local npl, npt, npr, npb = wndFrame:FindChild("Icon"):GetAnchorOffsets() local nnl, nnt, nnr, nnb = wndFrame:FindChild("Name"):GetAnchorOffsets() local nml, nmt, nmr, nmb = wndFrame:FindChild("FocusBar"):GetAnchorOffsets() --barFocus:GetAnchorOffsets() local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() -- barShield:GetAnchorOffsets() if wndFrame:GetName() == "PlayerUF" then --barHealth:SetAnchorOffsets(npr, nht, nhr, nhb) wndFrame:FindChild("HealthBar"):SetAnchorOffsets(npr, nht, nhr, nhb) --barFocus:SetAnchorOffsets(npr, nmt, nmr, nmb) wndFrame:FindChild("FocusBar"):SetAnchorOffsets(npr, nmt, nmr, nmb) elseif wndFrame:GetName() == "TargetUF" then --barShield:SetAnchorOffsets(nsl, nst, npl, nsb) wndFrame:FindChild("ShieldBar"):SetAnchorOffsets(nsl, nst, npl, nsb) --barFocus:SetAnchorOffsets(nml, nmt, npl, nmb) wndFrame:FindChild("FocusBar"):SetAnchorOffsets(nml, nmt, npl, nmb) end wndFrame:FindChild("Icon:IconPic"):Show(true, true) wndFrame:FindChild("Icon:Portrait"):Show(false, true) end --Interrupt Armor local nInterruptMax = uUnit:GetInterruptArmorMax() local nInterruptValue = uUnit:GetInterruptArmorValue() wndFrame:FindChild("InterruptArmor"):Show(nInterruptValue > 0) wndFrame:FindChild("InterruptArmor"):SetText(nInterruptValue) --Focus Glow if wndFrame:GetName() == "FocusUF" then wndFrame:FindChild("Glow"):Show(self.db.profile.focus.bGlow, true) end -- CastBar if wndFrame:GetName() == "TargetUF" then self:UpdateCastBar(wndFrame) end self:UpdateSelfCastBar(self.wndPlayerUF) self:UpdateIntArmor() --[[ -RewardInfo nCompleted nNeeded strType = Quest, Challenge, (Soldier, Settler, Explorer), Scientist, PublicEvent idQuest nShowCount strTitle splObjective -- not always there idChallenge --only for challenges ]] end function CandyUI_UnitFrames:UpdateIntArmor() --SendVarToRover("testing var: tItem1", self.db.profile["general"]["bShowOldInt"]) if self.db.profile["general"]["bShowOldInt"] then --Player self.wndPlayerUF:FindChild("InterruptArmor"):SetSprite("HUD_TargetFrame:spr_TargetFrame_InterruptArmor_Value") self.wndPlayerUF:FindChild("InterruptArmor"):SetBGColor("white") local npl, npt, npr, npb = self.wndPlayerUF:FindChild("CastBarPlayer"):GetAnchorOffsets() self.wndPlayerUF:FindChild("InterruptArmor"):SetAnchorOffsets(npl + 256, npt - 8, npr + 58, npb + 2) --Target self.wndTargetUF:FindChild("InterruptArmor"):SetSprite("HUD_TargetFrame:spr_TargetFrame_InterruptArmor_Value") self.wndTargetUF:FindChild("InterruptArmor"):SetBGColor("white") local nnl, nnt, nnr, nnb = self.wndTargetUF:FindChild("CastBar"):GetAnchorOffsets() self.wndTargetUF:FindChild("InterruptArmor"):SetAnchorOffsets(nnl + 256, nnt - 8, nnr + 58, nnb + 2) else --Player self.wndPlayerUF:FindChild("InterruptArmor"):SetSprite("Sprites:InterruptArmor") local npl, npt, npr, npb = self.wndPlayerUF:FindChild("CastBarPlayer"):GetAnchorOffsets() self.wndPlayerUF:FindChild("InterruptArmor"):SetBGColor("AddonError") self.wndPlayerUF:FindChild("InterruptArmor"):SetAnchorOffsets(npl + 256, npt + 1, npr + 54, npb - 2) --Target self.wndTargetUF:FindChild("InterruptArmor"):SetSprite("Sprites:InterruptArmor") local nnl, nnt, nnr, nnb = self.wndTargetUF:FindChild("CastBar"):GetAnchorOffsets() self.wndTargetUF:FindChild("InterruptArmor"):SetBGColor("AddonError") self.wndTargetUF:FindChild("InterruptArmor"):SetAnchorOffsets(nnl + 256, nnt + 1, nnr + 54, nnb - 2) end end function CandyUI_UnitFrames:UpdateSelfCastBar(wndFrame) local iUnit = GameLib.GetPlayerUnit() if iUnit:ShouldShowCastBar() then wndFrame:FindChild("CastBarPlayer"):FindChild("CastBarFull"):SetMax(iUnit:GetCastDuration()) wndFrame:FindChild("CastBarPlayer"):FindChild("CastBarFull"):SetProgress(iUnit:GetCastElapsed()) else wndFrame:FindChild("CastBarPlayer"):FindChild("CastBarFull"):SetProgress(0) end local nVulnerable = iUnit:GetCCStateTimeRemaining(Unit.CodeEnumCCState.Vulnerability) or 0 if nVulnerable > 0 then wndFrame:FindChild("CastBarPlayer"):FindChild("Moo"):SetProgress(iUnit:GetCastDuration()) wndFrame:FindChild("CastBarPlayer"):FindChild("Moo"):SetProgress(nVulnerable) wndFrame:FindChild("HealthBar"):FindChild("Bar"):SetBarColor("magenta") else wndFrame:FindChild("CastBarPlayer"):FindChild("Moo"):SetProgress(0) end end function CandyUI_UnitFrames:UpdateCastBar(wndFrame) local tUnit = GameLib.GetTargetUnit() local iUnit = GameLib.GetPlayerUnit() if tUnit ~= nil then if tUnit:ShouldShowCastBar() then wndFrame:FindChild("CastBar"):FindChild("CastBarFull"):SetMax(tUnit:GetCastDuration()) wndFrame:FindChild("CastBar"):FindChild("CastBarFull"):SetProgress(tUnit:GetCastElapsed()) else wndFrame:FindChild("CastBar"):FindChild("CastBarFull"):SetProgress(0) end local nVulnerable = tUnit:GetCCStateTimeRemaining(Unit.CodeEnumCCState.Vulnerability) or 0 if nVulnerable > 0 then wndFrame:FindChild("CastBar"):FindChild("Moo"):SetProgress(tUnit:GetCastDuration()) wndFrame:FindChild("CastBar"):FindChild("Moo"):SetProgress(nVulnerable) wndFrame:FindChild("HealthBar"):FindChild("Bar"):SetBarColor("magenta") else wndFrame:FindChild("CastBar"):FindChild("Moo"):SetProgress(0) end end end function CandyUI_UnitFrames:UpdateToT(uUnit) local wndFrame = self.wndToTUF --Name local strSeperator = " - " local strName = uUnit:GetName() local nLevel = uUnit:GetLevel() or "" local crName = uUnit:GetNameplateColor() self.wndToTUF:FindChild("Name"):SetText(strName .. strSeperator .. nLevel) self.wndToTUF:FindChild("Name"):SetTextColor(crName) --Buffs/Debuffs self.wndToTUF:FindChild("BuffContainerWindow"):SetUnit(uUnit) --are debuffs --self.wndToTUF:FindChild("DebuffContainerWindow"):SetUnit(uUnit) --Bars local barHealth = wndFrame:FindChild("HealthBar:Bar") local barShield = wndFrame:FindChild("ShieldBar:Bar") --Absorb local nAbsorbCurr = 0 local nAbsorbMax = uUnit:GetAbsorptionMax() if nAbsorbMax > 0 then nAbsorbCurr = uUnit:GetAbsorptionValue() end self:SetBarValue(wndFrame:FindChild("HealthBar:AbsorbBar"), nAbsorbCurr, 0, nAbsorbMax) --[[ local bShowAbsorbText = self.db.profile.tot.bAbsorbText if bShowAbsorbText and nAbsorbMax > 0 then wndFrame:FindChild("HealthBar:AbsorbBar"):SetText(self:HelperFormatBigNumber(nAbsorbCurr).." / "..self:HelperFormatBigNumber(nAbsorbMax)) else wndFrame:FindChild("HealthBar:AbsorbBar"):SetText("") end ]] --Health local nHealthMax = uUnit:GetMaxHealth() local nHealthCurr = uUnit:GetHealth() local nHealthPerc = round((nHealthCurr / nHealthMax) * 100) self:SetBarValue(barHealth, nHealthCurr, 0, nHealthMax) --Health Text local nShowHealthText = self.db.profile.tot.nHealthText local nHealthFormat = self.db.profile.tot.nHealthFormat local bShowHealthText = nShowHealthText == 1 or nShowHealthText == 2 barHealth:FindChild("Text"):Show(bShowHealthText, true) barHealth:FindChild("Text"):SetStyle("AutoFade", nShowHealthText == 2) if nShowHealthText == 1 and barHealth:FindChild("Text"):GetOpacity() < 1 then barHealth:FindChild("Text"):SetOpacity(1) end local strHealthText = "" if nHealthFormat == 0 then --Min / Max strHealthText = nHealthCurr .. " / " .. nHealthMax elseif nHealthFormat == 1 then --Min / Max (Short) strHealthText = self:HelperFormatBigNumber(nHealthCurr) .. " / " .. self:HelperFormatBigNumber(nHealthMax) elseif nHealthFormat == 2 then --Percent strHealthText = nHealthPerc .. "%" elseif nHealthFormat == 3 then --Min / Max (Percent) strHealthText = self:HelperFormatBigNumber(nHealthCurr) .. " / " .. self:HelperFormatBigNumber(nHealthMax) .. " (" .. nHealthPerc .. "%)" end local bShowShieldText = false --self.db.profile.tot.bShowShieldText local nShieldPerc = "" --replace with text local nShieldText = "[" .. nShieldPerc .. "%]" if bShowShieldText then barHealth:FindChild("Text"):SetText(strHealthText .. " " .. nShieldText) else barHealth:FindChild("Text"):SetText(strHealthText) end --Color by health local bColorByHealth = self.db.profile.tot.bColorByHealth if bColorByHealth then local nPercDec = nHealthPerc / 100 local crRed = 1 - nPercDec local crGreen = nPercDec local crBlue = 0 barHealth:SetBarColor(ApolloColor.new(crRed, crGreen, crBlue)) end --Shield --wndFrame:FindChild("HealthBarBG"):SetSprite("Sprites:HealthEmpty_Grey") local nShieldMax = uUnit:GetShieldCapacityMax() local nShieldCurr = uUnit:GetShieldCapacity() nShieldPerc = round((nShieldCurr / nShieldMax) * 100) if nShieldMax ~= nil and nShieldMax > 0 then if wndFrame:FindChild("ShieldBar"):IsShown() then self:SetBarValue(barShield, nShieldCurr, 0, nShieldMax) barShield:FindChild("Text"):SetText(nShieldPerc .. "%") else --barShield:Show(true, true) wndFrame:FindChild("ShieldBar"):Show(true, true) wndFrame:FindChild("HealthBar"):SetSprite("Sprites:HealthEmpty_Grey") --barHealth:SetEmptySprite("Sprites:HealthEmpty_Grey") barHealth:SetFullSprite("Sprites:HealthFull_Grey") wndFrame:FindChild("HealthBar:AbsorbBar"):SetFullSprite("Sprites:HealthFull_Grey") local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() wndFrame:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nsl - 4, nhb) --barHealth:SetAnchorOffsets(nhl, nht, nsl-4, nhb) self:SetBarValue(barShield, nShieldCurr, 0, nShieldMax) barShield:FindChild("Text"):SetText(nShieldPerc .. "%") end else if not wndFrame:FindChild("ShieldBar"):IsShown() then --self:SetBarValue(barShield, nShieldCurr, 0, nShieldMax) else --barShield:Show(false, true) wndFrame:FindChild("ShieldBar"):Show(false, true) wndFrame:FindChild("HealthBar"):SetSprite("Sprites:HealthEmpty_RoundedGrey") --barHealth:SetEmptySprite("Sprites:HealthEmpty_RoundedGrey") barHealth:SetFullSprite("Sprites:HealthFull_RoundedGrey") wndFrame:FindChild("HealthBar:AbsorbBar"):SetFullSprite("Sprites:HealthFull_RoundedGrey") local nhl, nht, nhr, nhb = wndFrame:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = wndFrame:FindChild("ShieldBar"):GetAnchorOffsets() wndFrame:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nsr, nhb) --barHealth:SetAnchorOffsets(nhl, nht, nsr, nhb) end end end function CandyUI_UnitFrames:GetClusters(uUnit) local unitTarget = uUnit local unitPlayer = GameLib.GetPlayerUnit() local tCluster = nil -- Cluster info tCluster = unitTarget:GetClusterUnits() if unitTarget == unitPlayer then --Treat Mount as a Cluster Target if unitPlayer:IsMounted() then table.insert(tCluster, unitPlayer:GetUnitMount()) end end --Make the unit a cluster of a vehicle if they're in one. if unitTarget:IsInVehicle() then --local uPlayer = unitTarget --unitTarget = uPlayer:GetVehicle() table.insert(tCluster, unitTarget:GetVehicle()) end -- Treat Pets as Cluster Targets --self.wndPetFrame:FindChild("PetContainerDespawnBtn"):SetData(nil) local tPlayerPets = GameLib.GetPlayerPets() --self.wndPetFrame:Show(false) for k, v in ipairs(tPlayerPets) do if k < 3 and unitTarget == unitPlayer then table.insert(tCluster, v) end end if tCluster == nil or #tCluster < 1 then tCluster = nil end return tCluster end function CandyUI_UnitFrames:UpdateClusters(tClusters, wndUnitFrame) local arClusterWindows = wndUnitFrame:FindChild("ClusterFrame"):GetChildren() wndUnitFrame:FindChild("ClusterFrame"):ArrangeChildrenVert() for i, v in ipairs(arClusterWindows) do v:Show(false) end if wndUnitFrame:FindChild("ClusterFrame") == nil or tClusters == nil then return end for i, v in ipairs(tClusters) do if arClusterWindows ~= nil and arClusterWindows[i] ~= nil then arClusterWindows[i]:Show(v:GetName() ~= nil) if v:GetName() ~= nil and v:GetHealth() ~= nil then arClusterWindows[i]:FindChild("Name"):SetText(v:GetName()) self:SetBarValue(arClusterWindows[i]:FindChild("HealthBar"), v:GetHealth(), 0, v:GetMaxHealth()) --self:SetBarValue(arClusterWindows[i]:FindChild("HealthBar"), v:GetHealth(), 0, v:GetHealthMax()) --Shield local nShieldMax = v:GetShieldCapacityMax() local nShieldCurr = v:GetShieldCapacity() if nShieldMax ~= nil and nShieldMax > 0 then if arClusterWindows[i]:FindChild("ShieldBar"):IsShown() then self:SetBarValue(arClusterWindows[i]:FindChild("ShieldBar"), nShieldCurr, 0, nShieldMax) else arClusterWindows[i]:FindChild("ShieldBar"):Show(true, true) local nsl, nst, nsr, nsb = arClusterWindows[i]:FindChild("ShieldBar"):GetAnchorOffsets() local nhl, nht, nhr, nhb = arClusterWindows[i]:FindChild("HealthBar"):GetAnchorOffsets() arClusterWindows[i]:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nsl, nhb) self:SetBarValue(arClusterWindows[i]:FindChild("ShieldBar"), nShieldCurr, 0, nShieldMax) end else arClusterWindows[i]:FindChild("ShieldBar"):Show(false, true) local nhl, nht, nhr, nhb = arClusterWindows[i]:FindChild("HealthBar"):GetAnchorOffsets() local nsl, nst, nsr, nsb = arClusterWindows[i]:FindChild("ShieldBar"):GetAnchorOffsets() arClusterWindows[i]:FindChild("HealthBar"):SetAnchorOffsets(nhl, nht, nsr, nhb) end end end end end function CandyUI_UnitFrames:SetBarValue(wndBar, fValue, fMin, fMax) fValue = math.floor(fValue) fMin = math.floor(fMin) fMax = math.floor(fMax) wndBar:SetMax(fMax) wndBar:SetFloor(fMin) wndBar:SetProgress(fValue) if wndBar:FindChild("Text") then --Add code for options local strSeperator = " / " wndBar:FindChild("Text"):SetText(fValue .. strSeperator .. fMax) end end --------------------------------------------------------------------------------------------------- -- PlayerUF Functions --------------------------------------------------------------------------------------------------- function CandyUI_UnitFrames:OnGenerateBuffTooltip(wndHandler, wndControl, tType, splBuff) if wndHandler == wndControl or Tooltip == nil then return end Tooltip.GetBuffTooltipForm(self, wndControl, splBuff, { bFutureSpell = false }) end -- This function is triggered whenever one of the windows is moved by the player. -- When the event is triggered, we get the new anchor offsets of the control that raised the event -- and store them inside our internal database for tracking the position and saving it. function CandyUI_UnitFrames:OnUFMoved(wndHandler, wndControl, nOldLeft, nOldTop, nOldRight, nOldBottom) local strName = wndControl:GetName() local tAnchors = { wndControl:GetAnchorOffsets() } if strName == "PlayerUF" then self.db.profile.player.tAnchorOffsets = tAnchors elseif strName == "TargetUF" then self.db.profile.target.tAnchorOffsets = tAnchors elseif strName == "FocusUF" then self.db.profile.focus.tAnchorOffsets = tAnchors elseif strName == "ToTUF" then self.db.profile.tot.tAnchorOffsets = tAnchors end end function CandyUI_UnitFrames:OnMouseUp(wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY) local unit = wndControl:GetData() if eMouseButton == GameLib.CodeEnumInputMouse.Left and unit ~= nil then GameLib.SetTargetUnit(unit) return false end if eMouseButton == GameLib.CodeEnumInputMouse.Right and unit ~= nil then Event_FireGenericEvent("GenericEvent_NewContextMenuPlayerDetailed", nil, unit:GetName(), unit) return true end end ----------------------------------------------------------------------------------------------- -- OPTIONS ----------------------------------------------------------------------------------------------- -- ############################################################################################# kcuiUFDefaults = { char = { currentProfile = nil, }, profile = { general = { strFontSize = "CRB_InterfaceTiny_BB", --Show Old Interupt bShowOldInt = false }, player = { nPortraitStyle = 2, nWidth = 256, nHealthText = 2, nHealthFormat = 3, crHealthBar = "ffff0000", --default for color? bColorByHealth = true, crShieldBar = "ff00bff3", nFocusText = 2, nFocusFormat = 3, crFocusBar = "fffe7b00", bAbsorbText = true, crAbsorbBar = "xkcdAmber", nAbsorbOpacity = 1, nOpacity = 1, nBGOpacity = 1, tAnchorOffsets = { 0, -324, 256, -268 } }, target = { nPortraitStyle = 2, nWidth = 256, nHealthText = 2, nHealthFormat = 3, crHealthBar = "ffff0000", --default for color? bColorByHealth = true, crShieldBar = "ff00bff3", nFocusText = 2, nFocusFormat = 3, crFocusBar = "fffe7b00", bAbsorbText = true, crAbsorbBar = "xkcdAmber", nAbsorbOpacity = 1, nOpacity = 1, nBGOpacity = 1, tAnchorOffsets = { -256, -324, 0, -268 } }, focus = { nPortraitStyle = 1, nWidth = 256, nHealthText = 2, nHealthFormat = 3, crHealthBar = "ffff0000", --default for color? bColorByHealth = true, crShieldBar = "ff00bff3", nFocusText = 2, nFocusFormat = 3, crFocusBar = "fffe7b00", bAbsorbText = true, crAbsorbBar = "xkcdAmber", nAbsorbOpacity = 1, nOpacity = 1, nBGOpacity = 1, bGlow = true, tAnchorOffsets = { -256, -258, 0, -202 } }, tot = { bShow = true, nHealthText = 2, nHealthFormat = 3, crHealthBar = "ffff0000", bColorByHealth = true, crShieldBar = "ff00bff3", bAbsorbText = true, crAbsorbBar = "xkcdAmber", nAbsorbOpacity = 1, nOpacity = 1, nBGOpacity = 1, tAnchorOffsets = { -261, -293, -111, -268 } }, }, } --%%%%%%%%%%%%% --Key By Value --%%%%%%%%%%%%% local function GetKey(tTable, strValue) for k, v in pairs(tTable) do if tostring(v) == tostring(strValue) then return k end end return nil end --%%%%%%%%%%%%%%%%% -- Create Dropdown --%%%%%%%%%%%%%%%%% local function CreateDropdownMenu(self, wndDropdown, tOptions, strEventHandler, bDisable) --wndDropdown needs to be the whole window object i.e. containing the label, button, and box local wndDropdownButton = wndDropdown:FindChild("Dropdown") local wndDropdownBox = wndDropdown:FindChild("DropdownBox") if #wndDropdownBox:FindChild("ScrollList"):GetChildren() > 0 then return end for name, value in pairs(tOptions) do local currButton = Apollo.LoadForm(self.xmlDoc, "DropdownItem", wndDropdownBox:FindChild("ScrollList"), self) currButton:SetText(name) currButton:SetData(value) currButton:AddEventHandler("ButtonUp", strEventHandler) end wndDropdownBox:FindChild("ScrollList"):ArrangeChildrenVert() if bDisable then --[[ for k, v in pairs(wndDropdown:GetParent():GetChildren()) do if v:GetName() ~= wndDropdown:GetName() and v:GetName() ~= "Title" and v:GetName() ~= "Description" then v:Enable(false) --Print(v:GetName()) end end ]] end end --------------------------------- -- Dropdown Options --------------------------------- local tPortraitOptions = { ["Hide"] = 0, ["Model"] = 1, ["Class Icon"] = 2, } local tTargetPortraitOptions = { ["Hide"] = 0, ["Model"] = 1, --["Class Icon"] = 2, } local tBarTextOptions = { ["Hide"] = 0, ["Show"] = 1, ["Hover"] = 2, } local tFontSizeOptions = { ["Small"] = "CRB_InterfaceTiny_BB", ["Medium"] = "CRB_InterfaceMedium_BO", ["Large"] = "CRB_InterfaceLarge_BO", ["Huge"] = "CRB_Interface14_BO", } local tBarTextFormatOptions = { ["Min / Max"] = 0, ["Min / Max (Short)"] = 1, ["Percent"] = 2, ["Min / Max (Percent)"] = 3, } --=============================== -- Set Options --=============================== function CandyUI_UnitFrames:SetOptions() --Show Old Interupt self.wndControls:FindChild("GeneralControls"):FindChild("OldInterupt"):SetCheck(self.db.profile["general"]["bShowOldInt"]) --Unit Options for _, strUnit in ipairs({ "Player", "Target", "Focus" }) do local strUnitLower = string.lower(strUnit) local controls = self.wndControls:FindChild(strUnit .. "Controls") --Portrait controls:FindChild("Portrait:Dropdown"):SetText(GetKey(tPortraitOptions, self.db.profile[strUnitLower]["nPortraitStyle"])) --Width controls:FindChild("Width:Input"):SetText(self.db.profile[strUnitLower]["nWidth"]) local l, t, r, b = self["wnd" .. strUnit .. "UF"]:GetAnchorOffsets() self["wnd" .. strUnit .. "UF"]:SetAnchorOffsets(l, t, l + self.db.profile[strUnitLower]["nWidth"], b) --Opacity controls:FindChild("Opacity:SliderBar"):SetValue(self.db.profile[strUnitLower]["nOpacity"]) controls:FindChild("Opacity:EditBox"):SetText(self.db.profile[strUnitLower]["nOpacity"]) --BGOpacity controls:FindChild("BGOpacity:SliderBar"):SetValue(self.db.profile[strUnitLower]["nBGOpacity"]) controls:FindChild("BGOpacity:EditBox"):SetText(self.db.profile[strUnitLower]["nBGOpacity"]) --==BARS==-- --Health Text controls:FindChild("HealthText:Dropdown"):SetText(GetKey(tBarTextOptions, self.db.profile[strUnitLower]["nHealthText"])) --Health Format controls:FindChild("HealthFormat:Dropdown"):SetText(GetKey(tBarTextFormatOptions, self.db.profile[strUnitLower]["nHealthFormat"])) --Health Bar Color controls:FindChild("HealthBarColor:Swatch"):SetBGColor(self.db.profile[strUnitLower]["crHealthBar"]) --Color By Health controls:FindChild("ColorByHealthToggle"):SetCheck(self.db.profile[strUnitLower]["bColorByHealth"]) --Shield Bar Color controls:FindChild("ShieldBarColor:Swatch"):SetBGColor(self.db.profile[strUnitLower]["crShieldBar"]) --Absorb Bar Color controls:FindChild("AbsorbBarColor:Swatch"):SetBGColor(self.db.profile[strUnitLower]["crAbsorbBar"]) --Absorb Text controls:FindChild("ShowAbsorbTextToggle"):SetCheck(self.db.profile[strUnitLower]["bAbsorbText"]) --Absorb Opacity controls:FindChild("AbsorbOpacity:SliderBar"):SetValue(self.db.profile[strUnitLower]["nAbsorbOpacity"]) controls:FindChild("AbsorbOpacity:EditBox"):SetText(self.db.profile[strUnitLower]["nAbsorbOpacity"]) end --General self.wndControls:FindChild("GeneralControls"):FindChild("FontSize:Dropdown"):SetText(GetKey(tFontSizeOptions, self.db.profile.general.strFontSize)) --Player --Focus Text self.wndControls:FindChild("PlayerControls"):FindChild("FocusText:Dropdown"):SetText(GetKey(tBarTextOptions, self.db.profile.player.nFocusText)) --Focus Format self.wndControls:FindChild("PlayerControls"):FindChild("FocusFormat:Dropdown"):SetText(GetKey(tBarTextFormatOptions, self.db.profile.player.nFocusFormat)) --Focus Bar Color self.wndControls:FindChild("PlayerControls"):FindChild("FocusBarColor:Swatch"):SetBGColor(self.db.profile.player.crFocusBar) --Focus --Focus Glow self.wndControls:FindChild("FocusControls"):FindChild("GlowToggle"):SetCheck(self.db.profile.focus.bGlow) --ToT --show self.wndControls:FindChild("ToTControls"):FindChild("ShowToggle"):SetCheck(self.db.profile.tot.bShow) --Health Text self.wndControls:FindChild("ToTControls"):FindChild("HealthText:Dropdown"):SetText(GetKey(tBarTextOptions, self.db.profile.tot.nHealthText)) --Health Format self.wndControls:FindChild("ToTControls"):FindChild("HealthFormat:Dropdown"):SetText(GetKey(tBarTextFormatOptions, self.db.profile.tot.nHealthFormat)) --Health Bar Color self.wndControls:FindChild("ToTControls"):FindChild("HealthBarColor:Swatch"):SetBGColor(self.db.profile.tot.crHealthBar) --Color By Health self.wndControls:FindChild("ToTControls"):FindChild("ColorByHealthToggle"):SetCheck(self.db.profile.tot.bColorByHealth) --Shield Bar Color self.wndControls:FindChild("ToTControls"):FindChild("ShieldBarColor:Swatch"):SetBGColor(self.db.profile.tot.crShieldBar) end function CandyUI_UnitFrames:SetLooks() --Player --Bar Colors self.wndPlayerUF:FindChild("HealthBar"):FindChild("Bar"):SetBarColor(self.db.profile.player.crHealthBar) self.wndPlayerUF:FindChild("HealthBar"):SetBGColor(self.db.profile.player.crHealthBar) self.wndPlayerUF:FindChild("ShieldBar"):FindChild("Bar"):SetBarColor(self.db.profile.player.crShieldBar) self.wndPlayerUF:FindChild("ShieldBar"):SetBGColor(self.db.profile.player.crShieldBar) self.wndPlayerUF:FindChild("FocusBar"):FindChild("Bar"):SetBarColor(self.db.profile.player.crFocusBar) self.wndPlayerUF:FindChild("FocusBar"):SetBGColor(self.db.profile.player.crFocusBar) self.wndPlayerUF:FindChild("HealthBar:AbsorbBar"):SetBarColor(self.db.profile.player.crAbsorbBar) self.wndPlayerUF:FindChild("HealthBar:AbsorbBar"):SetOpacity(self.db.profile.player.nAbsorbOpacity) --self.wndPlayerUF:FindChild("HealthBar:AbsorbBar"):SetOpacity(0.5) --Opacity self.wndPlayerUF:SetOpacity(self.db.profile.player.nOpacity) self.wndPlayerUF:FindChild("BG"):SetOpacity(self.db.profile.player.nBGOpacity) --target --Bar Colors self.wndTargetUF:FindChild("HealthBar"):FindChild("Bar"):SetBarColor(self.db.profile.target.crHealthBar) self.wndTargetUF:FindChild("HealthBar"):SetBGColor(self.db.profile.target.crHealthBar) self.wndTargetUF:FindChild("ShieldBar"):FindChild("Bar"):SetBarColor(self.db.profile.target.crShieldBar) self.wndTargetUF:FindChild("ShieldBar"):SetBGColor(self.db.profile.target.crShieldBar) self.wndTargetUF:FindChild("FocusBar"):FindChild("Bar"):SetBarColor(self.db.profile.target.crFocusBar) self.wndTargetUF:FindChild("FocusBar"):SetBGColor(self.db.profile.target.crFocusBar) self.wndTargetUF:FindChild("HealthBar:AbsorbBar"):SetBarColor(self.db.profile.target.crAbsorbBar) self.wndTargetUF:FindChild("HealthBar:AbsorbBar"):SetOpacity(self.db.profile.target.nAbsorbOpacity) --Opacity self.wndTargetUF:SetOpacity(self.db.profile.target.nOpacity) self.wndTargetUF:FindChild("BG"):SetOpacity(self.db.profile.target.nBGOpacity) --focus --Bar Colors self.wndFocusUF:FindChild("HealthBar"):FindChild("Bar"):SetBarColor(self.db.profile.focus.crHealthBar) self.wndFocusUF:FindChild("HealthBar"):SetBGColor(self.db.profile.focus.crHealthBar) self.wndFocusUF:FindChild("ShieldBar"):FindChild("Bar"):SetBarColor(self.db.profile.focus.crShieldBar) self.wndFocusUF:FindChild("ShieldBar"):SetBGColor(self.db.profile.focus.crShieldBar) self.wndFocusUF:FindChild("FocusBar"):FindChild("Bar"):SetBarColor(self.db.profile.focus.crFocusBar) self.wndFocusUF:FindChild("FocusBar"):SetBGColor(self.db.profile.focus.crFocusBar) self.wndFocusUF:FindChild("HealthBar:AbsorbBar"):SetBarColor(self.db.profile.focus.crAbsorbBar) self.wndFocusUF:FindChild("HealthBar:AbsorbBar"):SetOpacity(self.db.profile.focus.nAbsorbOpacity) --Opacity self.wndFocusUF:SetOpacity(self.db.profile.focus.nOpacity) self.wndFocusUF:FindChild("BG"):SetOpacity(self.db.profile.focus.nBGOpacity) --ToT --Bar Colors self.wndToTUF:FindChild("HealthBar"):FindChild("Bar"):SetBarColor(self.db.profile.tot.crHealthBar) self.wndToTUF:FindChild("HealthBar"):SetBGColor(self.db.profile.tot.crHealthBar) self.wndToTUF:FindChild("ShieldBar"):FindChild("Bar"):SetBarColor(self.db.profile.tot.crShieldBar) self.wndToTUF:FindChild("ShieldBar"):SetBGColor(self.db.profile.tot.crShieldBar) self.wndToTUF:FindChild("HealthBar:AbsorbBar"):SetBarColor(self.db.profile.tot.crAbsorbBar) self.wndToTUF:FindChild("HealthBar:AbsorbBar"):SetOpacity(self.db.profile.tot.nAbsorbOpacity) --Opacity self.wndToTUF:SetOpacity(self.db.profile.tot.nOpacity) self.wndToTUF:FindChild("BG"):SetOpacity(self.db.profile.tot.nBGOpacity) end ------------------------- -- General Option Events ------------------------- function CandyUI_UnitFrames:OnShowOldIntClick(wndHandler, wndControl) self.db.profile["general"]["bShowOldInt"] = wndControl:GetParent():FindChild("OldInterupt"):IsChecked() self:UpdateIntArmor() end ------------------------- -- Player Option Events ------------------------- function CandyUI_UnitFrames:ColorPickerCallback(strColor) local strUnit = self.strColorPickerTargetUnit local strUnitLower = string.lower(strUnit) if self.strColorPickerTargetControl == "HealthBar" then self.db.profile[strUnitLower].crHealthBar = strColor self.wndControls:FindChild(strUnit .. "Controls"):FindChild("HealthBarColor"):FindChild("Swatch"):SetBGColor(strColor) self["wnd" .. strUnit .. "UF"]:FindChild("HealthBar"):FindChild("Bar"):SetBarColor(self.db.profile[strUnitLower].crHealthBar) self["wnd" .. strUnit .. "UF"]:FindChild("HealthBar"):SetBGColor(self.db.profile[strUnitLower].crHealthBar) elseif self.strColorPickerTargetControl == "ShieldBar" then self.db.profile[strUnitLower].crShieldBar = strColor self.wndControls:FindChild(strUnit .. "Controls"):FindChild("ShieldBarColor"):FindChild("Swatch"):SetBGColor(strColor) self["wnd" .. strUnit .. "UF"]:FindChild("ShieldBar"):FindChild("Bar"):SetBarColor(self.db.profile[strUnitLower].crShieldBar) self["wnd" .. strUnit .. "UF"]:FindChild("ShieldBar"):SetBGColor(self.db.profile[strUnitLower].crShieldBar) elseif self.strColorPickerTargetControl == "FocusBar" then self.db.profile[strUnitLower].crFocusBar = strColor self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusBarColor"):FindChild("Swatch"):SetBGColor(strColor) self["wnd" .. strUnit .. "UF"]:FindChild("FocusBar"):FindChild("Bar"):SetBarColor(self.db.profile[strUnitLower].crFocusBar) self["wnd" .. strUnit .. "UF"]:FindChild("FocusBar"):SetBGColor(self.db.profile[strUnitLower].crFocusBar) elseif self.strColorPickerTargetControl == "AbsorbBar" then self.db.profile[strUnitLower].crAbsorbBar = strColor self.wndControls:FindChild(strUnit .. "Controls"):FindChild("AbsorbBarColor"):FindChild("Swatch"):SetBGColor(strColor) self["wnd" .. strUnit .. "UF"]:FindChild("HealthBar"):FindChild("AbsorbBar"):SetBarColor(self.db.profile[strUnitLower].crAbsorbBar) --self["wnd"..strUnit.."UF"]:FindChild("HealthBar"):SetBGColor(self.db.profile[strUnitLower].crHealthBar) end end --Portrait Style function CandyUI_UnitFrames:OnPortraitStyleClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() CreateDropdownMenu(self, wndControl:GetParent(), tPortraitOptions, "OnPortraitStyleItemClick", true) --self.wndControls:FindChild("PlayerControls") self.wndControls:FindChild(strUnit .. "Controls"):FindChild("Opacity"):Enable(false) wndControl:GetParent():FindChild("DropdownBox"):Show(true) end function CandyUI_UnitFrames:OnPortraitStyleItemClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():GetParent():GetParent():FindChild("Title"):GetText() wndControl:GetParent():GetParent():GetParent():FindChild("Dropdown"):SetText(wndControl:GetText()) self.db.profile[string.lower(strUnit)]["nPortraitStyle"] = wndControl:GetData() wndControl:GetParent():GetParent():Show(false) end function CandyUI_UnitFrames:OnPortraitStyleHide(wndHandler, wndControl) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() self.wndControls:FindChild(strUnit .. "Controls"):FindChild("Opacity"):Enable(true) end function CandyUI_UnitFrames:OnWidthReturn(wndHandler, wndControl, strText) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end local value = round(tonumber(strText)) self.db.profile[string.lower(strUnit)]["nWidth"] = value local l, t, r, b = self["wnd" .. strUnit .. "UF"]:GetAnchorOffsets() self["wnd" .. strUnit .. "UF"]:SetAnchorOffsets(l, t, l + value, b) end function CandyUI_UnitFrames:OnBGOpacityChanged(wndHandler, wndControl, fNewValue, fOldValue) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end local value = round(fNewValue, 1) wndControl:GetParent():FindChild("EditBox"):SetText(value) self.db.profile[string.lower(strUnit)]["nBGOpacity"] = value if self["wnd" .. strUnit .. "UF"] then self["wnd" .. strUnit .. "UF"]:FindChild("BG"):SetOpacity(value) end end function CandyUI_UnitFrames:OnOpacityChanged(wndHandler, wndControl, fNewValue, fOldValue) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end --self["wnd"..strUnit.."UF"] local value = round(fNewValue, 1) wndControl:GetParent():FindChild("EditBox"):SetText(value) self.db.profile[string.lower(strUnit)]["nOpacity"] = value if self["wnd" .. strUnit .. "UF"] then self["wnd" .. strUnit .. "UF"]:SetOpacity(value) end end function CandyUI_UnitFrames:OnHealthTextClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end CreateDropdownMenu(self, wndControl:GetParent(), tBarTextOptions, "OnHealthTextItemClick") self.wndControls:FindChild(strUnit .. "Controls"):FindChild("HealthBarColor"):Enable(false) self.wndControls:FindChild(strUnit .. "Controls"):FindChild("ShieldBarColor"):Enable(false) if self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusText") then self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusText"):Enable(false) end wndControl:GetParent():FindChild("DropdownBox"):Show(true) end function CandyUI_UnitFrames:OnHealthTextItemClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end wndControl:GetParent():GetParent():GetParent():FindChild("Dropdown"):SetText(wndControl:GetText()) self.db.profile[string.lower(strUnit)]["nHealthText"] = wndControl:GetData() wndControl:GetParent():GetParent():Show(false) end function CandyUI_UnitFrames:OnHealthTextHide(wndHandler, wndControl) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end self.wndControls:FindChild(strUnit .. "Controls"):FindChild("HealthBarColor"):Enable(true) self.wndControls:FindChild(strUnit .. "Controls"):FindChild("ShieldBarColor"):Enable(true) if self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusText") then self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusText"):Enable(true) end end function CandyUI_UnitFrames:OnHealthFormatClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end CreateDropdownMenu(self, wndControl:GetParent(), tBarTextFormatOptions, "OnHealthFormatItemClick") self.wndControls:FindChild(strUnit .. "Controls"):FindChild("ColorByHealthToggle"):Enable(false) --self.wndControls:FindChild(strUnit.."Controls"):FindChild("ShieldBarColor"):Enable(false) if self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusFormat") then self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusFormat"):Enable(false) end wndControl:GetParent():FindChild("DropdownBox"):Show(true) end function CandyUI_UnitFrames:OnHealthFormatItemClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end wndControl:GetParent():GetParent():GetParent():FindChild("Dropdown"):SetText(wndControl:GetText()) self.db.profile[string.lower(strUnit)]["nHealthFormat"] = wndControl:GetData() wndControl:GetParent():GetParent():Show(false) end function CandyUI_UnitFrames:OnHealthFormatHide(wndHandler, wndControl) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end self.wndControls:FindChild(strUnit .. "Controls"):FindChild("ColorByHealthToggle"):Enable(true) --self.wndControls:FindChild(strUnit.."Controls"):FindChild("ShieldBarColor"):Enable(false) if self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusFormat") then self.wndControls:FindChild(strUnit .. "Controls"):FindChild("FocusFormat"):Enable(true) end end function CandyUI_UnitFrames:OnHealthBarColorClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end --Open Color Picker self.strColorPickerTargetUnit = strUnit self.strColorPickerTargetControl = "HealthBar" self.colorPicker:Show(true) self.colorPicker:ToFront() end function CandyUI_UnitFrames:OnColorByHealthClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end self.db.profile[string.lower(strUnit)]["bColorByHealth"] = wndControl:IsChecked() if not wndControl:IsChecked() then self:SetLooks() end end function CandyUI_UnitFrames:OnShieldBarColorClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end --Open Color Picker self.strColorPickerTargetUnit = strUnit self.strColorPickerTargetControl = "ShieldBar" self.colorPicker:Show(true) self.colorPicker:ToFront() end function CandyUI_UnitFrames:OnPlayerFocusTextClick(wndHandler, wndControl, eMouseButton) CreateDropdownMenu(self, wndControl:GetParent(), tBarTextOptions, "OnPlayerFocusTextItemClick") self.wndControls:FindChild("PlayerControls"):FindChild("FocusBarColor"):Enable(false) wndControl:GetParent():FindChild("DropdownBox"):Show(true) end function CandyUI_UnitFrames:OnPlayerFocusTextItemClick(wndHandler, wndControl, eMouseButton) wndControl:GetParent():GetParent():GetParent():FindChild("Dropdown"):SetText(wndControl:GetText()) self.db.profile.player.nFocusText = wndControl:GetData() wndControl:GetParent():GetParent():Show(false) end function CandyUI_UnitFrames:OnPlayerFocusTextHide(wndHandler, wndControl) self.wndControls:FindChild("PlayerControls"):FindChild("FocusBarColor"):Enable(true) end function CandyUI_UnitFrames:OnPlayerFocusFormatClick(wndHandler, wndControl, eMouseButton) CreateDropdownMenu(self, wndControl:GetParent(), tBarTextFormatOptions, "OnPlayerFocusFormatItemClick") wndControl:GetParent():FindChild("DropdownBox"):Show(true) end function CandyUI_UnitFrames:OnPlayerFocusFormatItemClick(wndHandler, wndControl, eMouseButton) wndControl:GetParent():GetParent():GetParent():FindChild("Dropdown"):SetText(wndControl:GetText()) self.db.profile.player.nFocusFormat = wndControl:GetData() wndControl:GetParent():GetParent():Show(false) end function CandyUI_UnitFrames:OnPlayerFocusBarColorClick(wndHandler, wndControl, eMouseButton) --Open Color Picker self.strColorPickerTargetUnit = "Player" self.strColorPickerTargetControl = "FocusBar" self.colorPicker:Show(true) self.colorPicker:ToFront() end function CandyUI_UnitFrames:OnFocusShowGlowClick(wndHandler, wndControl, eMouseButton) self.db.profile.focus.bGlow = wndControl:IsChecked() end function CandyUI_UnitFrames:OnToTShowClick(wndHandler, wndControl, eMouseButton) self.db.profile.tot.bShow = wndControl:IsChecked() self:OnTargetUnitChanged(GameLib.GetTargetUnit()) end --------------------------------------------------------------------------------------------------- -- OptionsControlsList Functions --------------------------------------------------------------------------------------------------- function CandyUI_UnitFrames:OnAbsorbBarColorClick(wndHandler, wndControl, eMouseButton) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end --Open Color Picker self.strColorPickerTargetUnit = strUnit self.strColorPickerTargetControl = "AbsorbBar" self.colorPicker:Show(true) self.colorPicker:ToFront() end function CandyUI_UnitFrames:OnShowAbsorbTextClick(wndHandler, wndControl, eMouseButton) end function CandyUI_UnitFrames:OnAbsorbOpacityChanged(wndHandler, wndControl, fNewValue, fOldValue) local strUnit = wndControl:GetParent():GetParent():FindChild("Title"):GetText() if strUnit == "Target of Target" then strUnit = "ToT" end local value = round(fNewValue, 1) wndControl:GetParent():FindChild("EditBox"):SetText(value) self.db.profile[string.lower(strUnit)]["nAbsorbOpacity"] = value if self["wnd" .. strUnit .. "UF"]:FindChild("HealthBar:AbsorbBar"):IsValid() then self["wnd" .. strUnit .. "UF"]:FindChild("HealthBar:AbsorbBar"):SetOpacity(value) end end --General? function CandyUI_UnitFrames:OnFontSizeClick(wndHandler, wndControl, eMouseButton) CreateDropdownMenu(self, wndControl:GetParent(), tFontSizeOptions, "OnFontSizeItemClick") --self.wndControls:FindChild("PlayerControls"):FindChild("FocusBarColor"):Enable(false) wndControl:GetParent():FindChild("DropdownBox"):Show(true) end function CandyUI_UnitFrames:OnFontSizeItemClick(wndHandler, wndControl, eMouseButton) wndControl:GetParent():GetParent():GetParent():FindChild("Dropdown"):SetText(wndControl:GetText()) self.db.profile.general.strFontSize = wndControl:GetData() wndControl:GetParent():GetParent():Show(false) end function CandyUI_UnitFrames:OnFontSizeHide(wndHandler, wndControl) --self.wndControls:FindChild("PlayerControls"):FindChild("FocusBarColor"):Enable(true) end ----------------------------------------------------------------------------------------------- -- CandyUI_UnitFrames Instance ----------------------------------------------------------------------------------------------- local CandyUI_UnitFramesInst = CandyUI_UnitFrames:new() CandyUI_UnitFramesInst:Init()
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Temple_of_Uggalepih/npcs/_mf8.lua
3
1407
----------------------------------- -- Area: Temple of Uggalepih -- NPC: _mf8 (Granite Door) -- Notes: Opens with Prelate Key -- !pos -11 -8 -99 159 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1137,1) and trade:getItemCount() == 1) then -- Trade Prelate Key player:tradeComplete(); player:messageSpecial(YOUR_KEY_BREAKS,0000,1137); npc:openDoor(6.5); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getXPos() <= -8) then player:messageSpecial(THE_DOOR_IS_LOCKED,1137); else npc:openDoor(11); -- retail timed 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); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/bunch_of_wild_pamamas.lua
12
1409
----------------------------------------- -- ID: 4596 -- Item: Bunch of Wild Pamamas -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Intelligence 1 -- Additional Effect with Opo-Opo Crown -- HP 50 -- MP 50 -- CHR 14 -- Additional Effect with Kinkobo or -- Primate Staff -- DELAY -90 -- ACC 10 -- Additional Effect with Primate Staff +1 -- DELAY -80 -- ACC 12 ----------------------------------------- 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,4596); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Bastok_Mines/Zone.lua
12
2795
----------------------------------- -- -- Zone: Bastok_Mines (234) -- ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/globals/events/harvest_festivals"); require("scripts/globals/zone"); require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/titles"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) SetExplorerMoogles(17735856); applyHalloweenNpcCostumes(zone:getID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 0x01; end player:setPos(-45,-0,26,213); player:setHomePoint(); end -- MOG HOUSE EXIT if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then position = math.random(1,5) - 75; player:setPos(116,0.99,position,127); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); end if (prevZone == 172) then if (player:getCurrentMission(BASTOK) == ENTER_THE_TALEKEEPER and player:getVar("MissionStatus") == 5) then cs = 0x00b0 end end -- this if was leaking into the other functions return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x01) then player:messageSpecial(ITEM_OBTAINED,0x218); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 0x00b0) then finishMissionTimeline(player,1,csid,option); end -- you're not useing the script i sent youuu end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Yhoator_Jungle/TextIDs.lua
3
1432
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6386; -- Obtained: <item>. GIL_OBTAINED = 6387; -- Obtained <number> gil. KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>. NOTHING_OUT_OF_ORDINARY = 6400; -- There is nothing out of the ordinary here. BEASTMEN_BANNER = 7128; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7548; -- You can't fish here. ALREADY_OBTAINED_TELE = 7648; -- You already possess the gate crystal for this telepoint. -- Conquest CONQUEST = 7215; -- You've earned conquest points! -- Logging LOGGING_IS_POSSIBLE_HERE = 7661; -- Logging is possible here if you have HARVESTING_IS_POSSIBLE_HERE = 7668; -- Harvesting is possible here if you have -- Other dialog TREE_CHECK = 7675; -- The hole in this tree is filled with a sweet-smelling liquid. TREE_FULL = 7676; -- Your wine barrel is already full. -- conquest Base CONQUEST_BASE = 7047; -- Tallying conquest results... -- chocobo digging DIG_THROW_AWAY = 7561; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full. FIND_NOTHING = 7563; -- You dig and you dig, but find nothing.?Prompt?
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Selbina/npcs/Humilitie.lua
3
1475
----------------------------------- -- Area: Selbina -- NPC: Humilitie -- Reports the time remaining before boat arrival. -- !pos 17.979 -2.39 -58.800 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua local timer = 1152 - ((os.time() - 1009810800)%1152); local direction = 0; -- Arrive, 1 for depart local waiting = 216; -- Offset for Mhaura if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(231,timer,direction); 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/Windurst_Walls/npcs/Ojha_Rhawash.lua
3
3742
----------------------------------- -- Area: Windurst Walls -- NPC: Ojha Rhawash -- Starts and Finishes Quest: Flower Child -- @zone 239 -- !pos -209 0 -134 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Walls/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); gil = trade:getGil(); itemQuality = 0; if (trade:getItemCount() == 1 and trade:getGil() == 0) then if (trade:hasItemQty(956,1)) then -- Lilac itemQuality = 2; elseif (trade:hasItemQty(957,1) or -- Amaryllis trade:hasItemQty(2554,1) or -- Asphodel trade:hasItemQty(948,1) or -- Carnation trade:hasItemQty(1120,1) or -- Casablanca trade:hasItemQty(1413,1) or -- Cattleya trade:hasItemQty(636,1) or -- Chamomile trade:hasItemQty(959,1) or -- Dahlia trade:hasItemQty(835,1) or -- Flax Flower trade:hasItemQty(2507,1) or -- Lycopodium Flower trade:hasItemQty(958,1) or -- Marguerite trade:hasItemQty(1412,1) or -- Olive Flower trade:hasItemQty(938,1) or -- Papaka Grass trade:hasItemQty(1411,1) or -- Phalaenopsis trade:hasItemQty(949,1) or -- Rain Lily trade:hasItemQty(941,1) or -- Red Rose trade:hasItemQty(1725,1) or -- Snow Lily trade:hasItemQty(1410,1) or -- Sweet William trade:hasItemQty(950,1) or -- Tahrongi Cactus trade:hasItemQty(2960,1) or -- Water Lily trade:hasItemQty(951,1)) then -- Wijnruit itemQuality = 1; end end FlowerChild = player:getQuestStatus(WINDURST,FLOWER_CHILD); if (itemQuality == 2) then if (FlowerChild == QUEST_COMPLETED) then player:startEvent(0x2710, 0, 239, 4); else player:startEvent(0x2710, 0, 239, 2); end elseif (itemQuality == 1) then if (FlowerChild == QUEST_COMPLETED) then player:startEvent(0x2710, 0, 239, 5); elseif (FlowerChild == QUEST_ACCEPTED) then player:startEvent(0x2710, 0, 239, 3); else player:startEvent(0x2710, 0, 239, 1); end else player:startEvent(0x2710, 0, 239, 0); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2710, 0, 239, 10); 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 == 0x2710 and option == 3002) then player:tradeComplete(); player:completeQuest(WINDURST,FLOWER_CHILD); player:addFame(WINDURST,120); player:moghouseFlag(4); player:messageSpecial(MOGHOUSE_EXIT); elseif (csid == 0x2710 and option == 1) then player:tradeComplete(); player:addQuest(WINDURST,FLOWER_CHILD); end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/broiled_carp.lua
12
1384
----------------------------------------- -- ID: 4586 -- Item: Broiled Carp -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 2 -- Mind -1 -- Ranged ATT % 14 (cap 45) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4586); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -1); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 45); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -1); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 45); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Gusgen_Mines/npcs/Clay.lua
3
1229
----------------------------------- -- Area: Gusgen Mines -- NPC: Clay -- Involved in Quest: A Potter's Preference -- !pos 117 -21 432 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:addItem(569,1); --569 - dish_of_gusgen_clay player:messageSpecial(ITEM_OBTAINED,569); -- dish_of_gusgen_clay 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); end;
gpl-3.0
SoLoHiC/neural-style
loadcaffe_wrapper.lua
58
2411
local ffi = require 'ffi' require 'loadcaffe' local C = loadcaffe.C --[[ Most of this function is copied from https://github.com/szagoruyko/loadcaffe/blob/master/loadcaffe.lua with some horrible horrible hacks added by Justin Johnson to make it possible to load VGG-19 without any CUDA dependency. --]] local function loadcaffe_load(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.loadBinary creates a .lua source file that builds up a table -- containing the layers of the network. As a horrible dirty hack, -- we'll modify this file when backend "nn-cpu" is requested by -- doing the following: -- -- (1) Delete the lines that import cunn and inn, which are always -- at lines 2 and 4 local model = nil if backend == 'nn-cpu' then C.convertProtoToLua(handle, lua_name, 'nn') local lua_name_cpu = prototxt_name..'.cpu.lua' local fin = assert(io.open(lua_name), 'r') local fout = assert(io.open(lua_name_cpu, 'w')) local line_num = 1 while true do local line = fin:read('*line') if line == nil then break end if line_num ~= 2 and line_num ~= 4 then fout:write(line, '\n') end line_num = line_num + 1 end fin:close() fout:close() model = dofile(lua_name_cpu) else C.convertProtoToLua(handle, lua_name, backend) model = dofile(lua_name) end -- 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 return { load = loadcaffe_load }
mit
RebootRevival/FFXI_Test
scripts/zones/Abyssea-Tahrongi/npcs/qm20.lua
3
1904
----------------------------------- -- Zone: Abyssea-Tahrongi -- NPC: ??? -- Spawns Glavoid -- !pos ? ? ? 45 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(16961947) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(FAT_LINED_COCKATRICE_SKIN) and player:hasKeyItem(SODDEN_SANDWORM_HUSK) and player:hasKeyItem(LUXURIANT_MANTICORE_MANE) -- I broke it into 3 lines at the 'and' because it was so long. and player:hasKeyItem(STICKY_GNAT_WING)) then player:startEvent(1020, FAT_LINED_COCKATRICE_SKIN, SODDEN_SANDWORM_HUSK, LUXURIANT_MANTICORE_MANE, STICKY_GNAT_WING); -- Ask if player wants to use KIs else player:startEvent(1021, FAT_LINED_COCKATRICE_SKIN, SODDEN_SANDWORM_HUSK, LUXURIANT_MANTICORE_MANE, STICKY_GNAT_WING); -- 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(16961947):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(FAT_LINED_COCKATRICE_SKIN); player:delKeyItem(SODDEN_SANDWORM_HUSK); player:delKeyItem(LUXURIANT_MANTICORE_MANE); player:delKeyItem(STICKY_GNAT_WING); 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/webapi/bit.lua
1
2393
module("luci.webapi.bit", package.seeall) --[[ Presentation: In fact, it is not necessary to call this part of functions now only if you do not believe the library of Lua... This file will be removed after all skills disconnect from simulated bitwise operations. ]]-- --[[ bit:_xor == bit32.bxor bit:_and == bit32.band bit:_or == bit32.bor bit:_not == bit32.bnot bit:_rshift == bit32.rshift bit:_lshift == bit32.lshift ]]-- bit={data32={2147483648,1073741824,536870912,268435456,134217728,67108864,33554432,16777216,8388608,4194304,2097152,1048576,524288,262144,131072,65536,32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1}} function bit:d2b(arg) local tr={} for i=1,32 do if arg >= self.data32[i] then tr[i]=1 arg=arg-self.data32[i] else tr[i]=0 end end return tr end --bit:d2b function bit:b2d(arg) local nr=0 for i=1,32 do if arg[i] ==1 then nr=nr+2^(32-i) end end return nr end --bit:b2d function bit:_xor(a,b) local op1=self:d2b(a) local op2=self:d2b(b) local r={} for i=1,32 do if op1[i]==op2[i] then r[i]=0 else r[i]=1 end end return self:b2d(r) end --bit:xor function bit:_and(a,b) local op1=self:d2b(a) local op2=self:d2b(b) local r={} for i=1,32 do if op1[i]==1 and op2[i]==1 then r[i]=1 else r[i]=0 end end return self:b2d(r) end --bit:_and function bit:_or(a,b) local op1=self:d2b(a) local op2=self:d2b(b) local r={} for i=1,32 do if op1[i]==1 or op2[i]==1 then r[i]=1 else r[i]=0 end end return self:b2d(r) end --bit:_or function bit:_not(a) local op1=self:d2b(a) local r={} for i=1,32 do if op1[i]==1 then r[i]=0 else r[i]=1 end end return self:b2d(r) end --bit:_not function bit:_rshift(a,n) local op1=self:d2b(a) local r=self:d2b(0) if n < 32 and n > 0 then for i=1,n do for i=31,1,-1 do op1[i+1]=op1[i] end op1[1]=0 end r=op1 end return self:b2d(r) end --bit:_rshift function bit:_lshift(a,n) local op1=self:d2b(a) local r=self:d2b(0) if n < 32 and n > 0 then for i=1,n do for i=1,31 do op1[i]=op1[i+1] end op1[32]=0 end r=op1 end return self:b2d(r) end --bit:_lshift function bit:print(ta) local sr="" for i=1,32 do sr=sr..ta[i] end print(sr) end --end of bit.lua
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/La_Theine_Plateau/npcs/Dimensional_Portal.lua
17
1389
----------------------------------- -- Area: La Theine Plateau -- NPC: Dimensional Portal ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) > THE_WARRIOR_S_PATH) or (DIMENSIONAL_PORTAL_UNLOCK == true) then player:startEvent(0x00CC); else player:messageSpecial(ALREADY_OBTAINED_TELE+1); -- Telepoint Disappeared 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 == 0x00CC and option == 1) then player:setPos(25.299,-2.799,579,193,33); -- To AlTaieu {R} end end;
gpl-3.0
ChargeIn/CandyUI
InterfaceMenu/CandyUI_InterfaceMenu.lua
2
17411
----------------------------------------------------------------------------------------------- -- Client Lua Script for CandyUI_InterfaceMenu -- Copyright (c) NCsoft. All rights reserved ----------------------------------------------------------------------------------------------- --DEVELOPER LICENSE -- CandyUI - Copyright (C) 2014 Neil Smith -- This work is licensed under the GNU GENERAL PUBLIC LICENSE. -- A copy of this license is included with this release. ----------------------------------------------------------------------------------------------- require "Window" require "GameLib" require "Apollo" local CandyUI_InterfaceMenu = {} --%%%%%%%%%%% -- ROUND --%%%%%%%%%%% local function round(num, idp) local mult = 10^(idp or 0) if num >= 0 then return math.floor(num * mult + 0.5) / mult else return math.ceil(num * mult - 0.5) / mult end end ----------------------------------------------------------------------------------------------- -- Constants ----------------------------------------------------------------------------------------------- kcuiIMDefaults = { char = { currentProfile = nil, tPinnedAddons = { Apollo.GetString("InterfaceMenu_AccountInventory"), Apollo.GetString("InterfaceMenu_Character"), Apollo.GetString("InterfaceMenu_AbilityBuilder"), Apollo.GetString("InterfaceMenu_QuestLog"), Apollo.GetString("InterfaceMenu_GroupFinder"), Apollo.GetString("InterfaceMenu_Social"), Apollo.GetString("InterfaceMenu_Mail"), Apollo.GetString("InterfaceMenu_Lore"), }, }, } ----------------------------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------------------------- function CandyUI_InterfaceMenu:new(o) o = o or {} setmetatable(o, self) self.__index = self -- initialize variables here return o end function CandyUI_InterfaceMenu:Init() local bHasConfigureFunction = false local strConfigureButtonText = "" local tDependencies = { -- "UnitOrPackageName", } Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies) end ----------------------------------------------------------------------------------------------- -- CandyUI_InterfaceMenu OnLoad ----------------------------------------------------------------------------------------------- function CandyUI_InterfaceMenu:OnLoad() self.xmlDoc = XmlDoc.CreateFromFile("CandyUI_InterfaceMenu.xml") self.xmlDoc:RegisterCallback("OnDocLoaded", self) self.db = Apollo.GetPackage("Gemini:DB-1.0").tPackage:New(self, kcuiIMDefaults) end ----------------------------------------------------------------------------------------------- -- CandyUI_InterfaceMenu OnDocLoaded ----------------------------------------------------------------------------------------------- function CandyUI_InterfaceMenu:OnDocLoaded() if self.xmlDoc == nil then return end if self.db.char.currentProfile == nil and self.db:GetCurrentProfile() ~= nil then self.db.char.currentProfile = self.db:GetCurrentProfile() elseif self.db.char.currentProfile ~= nil and self.db.char.currentProfile ~= self.db:GetCurrentProfile() then self.db:SetProfile(self.db.char.currentProfile) end Apollo.LoadSprites("Sprites.xml") Apollo.RegisterEventHandler("InterfaceMenuList_NewAddOn", "OnNewAddonListed", self) Apollo.RegisterEventHandler("InterfaceMenuList_AlertAddOn", "OnDrawAlert", self) Apollo.RegisterEventHandler("CharacterCreated", "OnCharacterCreated", self) Apollo.RegisterTimerHandler("TimeUpdateTimer", "OnUpdateTimer", self) Apollo.RegisterTimerHandler("QueueRedrawTimer", "OnQueuedRedraw", self) Apollo.RegisterEventHandler("ApplicationWindowSizeChanged", "ButtonListRedraw", self) self.wndMain = Apollo.LoadForm(self.xmlDoc , "InterfaceMenuListForm", "FixedHudStratumHigh", self) self.wndList = Apollo.LoadForm(self.xmlDoc , "FullListFrame", nil, self) if self.db.char.tAnchorOffsets then local l, t, r, b = unpack(self.db.char.tAnchorOffsets) local nWidth = self.wndList:GetWidth() local nHeight = self.wndList:GetHeight() self.wndMain:SetAnchorOffsets(l, t, r, b) self.wndList:SetAnchorOffsets(l, b, l+nWidth, b+nHeight) end self.wndMain:FindChild("OpenFullListBtn"):AttachWindow(self.wndList) self.wndMain:FindChild("OpenFullListBtn"):Enable(false) Apollo.CreateTimer("QueueRedrawTimer", 0.3, false) Apollo.RegisterSlashCommand("redrawbuttonlist", "OnRedrawButtonListCommand", self) self.tMenuData = { [Apollo.GetString("InterfaceMenu_SystemMenu")] = { "", "", "Icon_Windows32_UI_CRB_InterfaceMenu_EscMenu" }, } self.tMenuTooltips = {} self.tMenuAlerts = {} ----------------------------------------- -- StarPanel and CUI_DataTexts check ----------------------------------------- local bStarPanelLoaded = Apollo.GetAddon("StarPanel") ~= nil local bCUIDataTextsLoaded = Apollo.GetAddon("CandyUI_DataTexts") ~= nil if bStarPanelLoaded or bCUIDataTextsLoaded then if not self.db.char.tAnchorOffsets then local l, t, r, b = self.wndMain:GetAnchorOffsets() self.wndMain:SetAnchorOffsets(l, t+30, r, b+30) end end ----------------------------------------- self:ButtonListRedraw() if GameLib.GetPlayerUnit() then self:OnCharacterCreated() end end function CandyUI_InterfaceMenu:OnCharacterCreated() Apollo.CreateTimer("TimeUpdateTimer", 1.0, true) end function CandyUI_InterfaceMenu:OnUpdateTimer() if not self.bHasLoaded then Event_FireGenericEvent("InterfaceMenuListHasLoaded") self.wndMain:FindChild("OpenFullListBtn"):Enable(true) self.bHasLoaded = true end --Toggle Visibility based on ui preference local unitPlayer = GameLib.GetPlayerUnit() if not unitPlayer then return end local bIsInCombat = unitPlayer:IsInCombat() local nVisibility = Apollo.GetConsoleVariable("hud.TimeDisplay") local bShowTime = true if nVisibility == 2 then --always off bShowTime = false elseif nVisibility == 3 then --on in combat bShowTime = bIsInCombat elseif nVisibility == 4 then --on out of combat bShowTime = not bIsInCombat else bShowTime = true end local tTime = GameLib.GetLocalTime() self.wndMain:FindChild("Time"):SetText("") --bShowTime and string.format("%02d:%02d", tostring(tTime.nHour), tostring(tTime.nMinute)) or "") end function CandyUI_InterfaceMenu:OnRedrawButtonListCommand() self:ButtonListRedraw() end function CandyUI_InterfaceMenu:OnNewAddonListed(strKey, tParams) strKey = string.gsub(strKey, ":", "|") -- ":'s don't work for window names, sorry!" self.tMenuData[strKey] = tParams self:FullListRedraw() self:ButtonListRedraw() end function CandyUI_InterfaceMenu:IsPinned(strText) for idx, strWindowText in pairs(self.db.char.tPinnedAddons) do if (strText == strWindowText) then return true end end return false end function CandyUI_InterfaceMenu:FullListRedraw() local strUnbound = Apollo.GetString("Keybinding_Unbound") local wndParent = self.wndList:FindChild("InsetBG:FullListScroll") local strQuery = string.lower(tostring(self.wndList:FindChild("SearchEditBox"):GetText()) or "") if strQuery == nil or strQuery == "" or not strQuery:match("[%w%s]+") then strQuery = "" end for strWindowText, tData in pairs(self.tMenuData) do local bSearchResultMatch = string.find(string.lower(strWindowText), strQuery) ~= nil if strQuery == "" or bSearchResultMatch then local wndMenuItem = self:LoadByName("MenuListItem", wndParent, strWindowText) local wndMenuButton = self:LoadByName("InterfaceMenuButton", wndMenuItem:FindChild("Icon"), strWindowText) local strTooltip = strWindowText if string.len(tData[2]) > 0 then local strKeyBindLetter = GameLib.GetKeyBinding(tData[2]) strKeyBindLetter = strKeyBindLetter == strUnbound and "" or string.format(" (%s)", strKeyBindLetter) strTooltip = strKeyBindLetter ~= "" and strTooltip .. strKeyBindLetter or strTooltip end if tData[3] ~= "" then wndMenuButton:FindChild("Icon"):SetSprite(tData[3]) else wndMenuButton:FindChild("Icon"):SetText(string.sub(strTooltip, 1, 1)) end wndMenuButton:FindChild("ShortcutBtn"):SetData(strWindowText) wndMenuButton:FindChild("Icon"):SetTooltip(strTooltip) self.tMenuTooltips[strWindowText] = strTooltip wndMenuItem:FindChild("MenuListItemBtn"):SetText(strWindowText) wndMenuItem:FindChild("MenuListItemBtn"):SetData(tData[1]) wndMenuItem:FindChild("PinBtn"):SetCheck(self:IsPinned(strWindowText)) wndMenuItem:FindChild("PinBtn"):SetData(strWindowText) if string.len(tData[2]) > 0 then local strKeyBindLetter = GameLib.GetKeyBinding(tData[2]) wndMenuItem:FindChild("MenuListItemBtn"):FindChild("MenuListItemKeybind"):SetText(strKeyBindLetter == strUnbound and "" or string.format("(%s)", strKeyBindLetter)) -- LOCALIZE end elseif not bSearchResultMatch and wndParent:FindChild(strWindowText) then wndParent:FindChild(strWindowText):Destroy() end end wndParent:ArrangeChildrenVert(0, function (a,b) return a:GetName() < b:GetName() end) end function CandyUI_InterfaceMenu:ButtonListRedraw() Apollo.StopTimer("QueueRedrawTimer") Apollo.StartTimer("QueueRedrawTimer") end function CandyUI_InterfaceMenu:OnQueuedRedraw() local strUnbound = Apollo.GetString("Keybinding_Unbound") local wndParent = self.wndMain:FindChild("ButtonList") wndParent:DestroyChildren() local nParentWidth = wndParent:GetWidth() local nLastButtonWidth = 0 local nTotalWidth = 0 for idx, strWindowText in pairs(self.db.char.tPinnedAddons) do tData = self.tMenuData[strWindowText] --Magic number below is allowing the 1 pixel gutter on the right if tData and nTotalWidth + nLastButtonWidth <= nParentWidth + 1 then local wndMenuItem = self:LoadByName("InterfaceMenuButton", wndParent, strWindowText) local strTooltip = strWindowText nLastButtonWidth = wndMenuItem:GetWidth() nTotalWidth = nTotalWidth + nLastButtonWidth if string.len(tData[2]) > 0 then local strKeyBindLetter = GameLib.GetKeyBinding(tData[2]) strKeyBindLetter = strKeyBindLetter == strUnbound and "" or string.format(" (%s)", strKeyBindLetter) strTooltip = strKeyBindLetter ~= "" and strTooltip .. strKeyBindLetter or strTooltip end if tData[3] ~= "" then wndMenuItem:FindChild("Icon"):SetSprite(tData[3]) else wndMenuItem:FindChild("Icon"):SetText(string.sub(strTooltip, 1, 1)) end wndMenuItem:FindChild("ShortcutBtn"):SetData(strWindowText) wndMenuItem:FindChild("Icon"):SetTooltip(strTooltip) end if self.tMenuAlerts[strWindowText] then self:OnDrawAlert(strWindowText, self.tMenuAlerts[strWindowText]) end end wndParent:ArrangeChildrenHorz(0) end ----------------------------------------------------------------------------------------------- -- Search ----------------------------------------------------------------------------------------------- function CandyUI_InterfaceMenu:OnSearchEditBoxChanged(wndHandler, wndControl) self.wndList:FindChild("SearchClearBtn"):Show(string.len(wndHandler:GetText() or "") > 0) self:FullListRedraw() end function CandyUI_InterfaceMenu:OnSearchClearBtn(wndHandler, wndControl) self.wndList:FindChild("SearchFlash"):SetSprite("CRB_WindowAnimationSprites:sprWinAnim_BirthSmallTemp") self.wndList:FindChild("SearchFlash"):SetFocus() self.wndList:FindChild("SearchClearBtn"):Show(false) self.wndList:FindChild("SearchEditBox"):SetText("") self:FullListRedraw() end function CandyUI_InterfaceMenu:OnSearchCommitBtn(wndHandler, wndControl) self.wndList:FindChild("SearchFlash"):SetSprite("CRB_WindowAnimationSprites:sprWinAnim_BirthSmallTemp") self.wndList:FindChild("SearchFlash"):SetFocus() self:FullListRedraw() end ----------------------------------------------------------------------------------------------- -- Alerts ----------------------------------------------------------------------------------------------- function CandyUI_InterfaceMenu:OnDrawAlert(strWindowName, tParams) self.tMenuAlerts[strWindowName] = tParams for idx, wndTarget in pairs(self.wndMain:FindChild("ButtonList"):GetChildren()) do if wndTarget and tParams then local wndButton = wndTarget:FindChild("ShortcutBtn") if wndButton then local wndIcon = wndButton:FindChild("Icon") if wndButton:GetData() == strWindowName then if tParams[1] then local wndIndicator = self:LoadByName("AlertIndicator", wndButton:FindChild("Alert"), "AlertIndicator") elseif wndButton:FindChild("AlertIndicator") ~= nil then wndButton:FindChild("AlertIndicator"):Destroy() end if tParams[2] then wndIcon:SetTooltip(string.format("%s\n\n%s", self.tMenuTooltips[strWindowName], tParams[2])) end if tParams[3] and tParams[3] > 0 then local strColor = tParams[1] and "UI_WindowTextOrange" or "UI_TextHoloTitle" wndButton:FindChild("Number"):Show(true) wndButton:FindChild("Number"):SetText(tParams[3]) wndButton:FindChild("Number"):SetTextColor(ApolloColor.new(strColor)) else wndButton:FindChild("Number"):Show(false) wndButton:FindChild("Number"):SetText("") wndButton:FindChild("Number"):SetTextColor(ApolloColor.new("UI_TextHoloTitle")) end end end end end local wndParent = self.wndList:FindChild("FullListScroll") for idx, wndTarget in pairs(wndParent:GetChildren()) do local wndButton = wndTarget:FindChild("ShortcutBtn") local wndIcon = wndButton:FindChild("Icon") if wndButton:GetData() == strWindowName then if tParams[1] then local wndIndicator = self:LoadByName("AlertIndicator", wndButton:FindChild("Alert"), "AlertIndicator") elseif wndButton:FindChild("AlertIndicator") ~= nil then wndButton:FindChild("AlertIndicator"):Destroy() end if tParams[2] then wndIcon:SetTooltip(string.format("%s\n\n%s", self.tMenuTooltips[strWindowName], tParams[2])) end if tParams[3] and tParams[3] > 0 then local strColor = tParams[1] and "UI_WindowTextOrange" or "UI_TextHoloTitle" wndButton:FindChild("Number"):Show(true) wndButton:FindChild("Number"):SetText(tParams[3]) wndButton:FindChild("Number"):SetTextColor(ApolloColor.new(strColor)) else wndButton:FindChild("Number"):Show(false) end end end end ----------------------------------------------------------------------------------------------- -- Helpers and Errata ----------------------------------------------------------------------------------------------- function CandyUI_InterfaceMenu:OnMenuListItemClick(wndHandler, wndControl) if wndHandler ~= wndControl then return end if string.len(wndControl:GetData()) > 0 then Event_FireGenericEvent(wndControl:GetData()) else InvokeOptionsScreen() end self.wndList:Show(false) end function CandyUI_InterfaceMenu:OnPinBtnChecked(wndHandler, wndControl) if wndHandler ~= wndControl then return end local wndParent = wndControl:GetParent():GetParent() self.db.char.tPinnedAddons = {} for idx, wndMenuItem in pairs(wndParent:GetChildren()) do if wndMenuItem:FindChild("PinBtn"):IsChecked() then table.insert(self.db.char.tPinnedAddons, wndMenuItem:FindChild("PinBtn"):GetData()) end end self:ButtonListRedraw() end function CandyUI_InterfaceMenu:OnListBtnClick(wndHandler, wndControl) -- These are the five always on icons on the top if wndHandler ~= wndControl then return end local strMappingResult = self.tMenuData[wndHandler:GetData()][1] or "" if string.len(strMappingResult) > 0 then Event_FireGenericEvent(strMappingResult) else InvokeOptionsScreen() end end function CandyUI_InterfaceMenu:OnListBtnMouseEnter(wndHandler, wndControl) wndHandler:SetBGColor("ffffffff") if wndHandler ~= wndControl or self.wndList:IsVisible() then return end end function CandyUI_InterfaceMenu:OnListBtnMouseExit(wndHandler, wndControl) -- Also self.wndMain MouseExit and ButtonList MouseExit wndHandler:SetBGColor("9dffffff") end function CandyUI_InterfaceMenu:OnOpenFullListCheck(wndHandler, wndControl) self.wndList:FindChild("SearchEditBox"):SetFocus() self:FullListRedraw() end function CandyUI_InterfaceMenu:LoadByName(strForm, wndParent, strCustomName) local wndNew = wndParent:FindChild(strCustomName) if not wndNew then wndNew = Apollo.LoadForm(self.xmlDoc , strForm, wndParent, self) wndNew:SetName(strCustomName) end return wndNew end --------------------------------------------------------------------------------------------------- -- InterfaceMenuListForm Functions --------------------------------------------------------------------------------------------------- function CandyUI_InterfaceMenu:OnMoved( wndHandler, wndControl, nOldLeft, nOldTop, nOldRight, nOldBottom ) local tAnchors = {wndControl:GetAnchorOffsets()} self.db.char.tAnchorOffsets = tAnchors local l, t, r, b = unpack(tAnchors) local nWidth = self.wndList:GetWidth() local nHeight = self.wndList:GetHeight() self.wndList:SetAnchorOffsets(l, b, l+nWidth, b+nHeight) end ----------------------------------------------------------------------------------------------- -- CandyUI_InterfaceMenu Instance ----------------------------------------------------------------------------------------------- local CandyUI_InterfaceMenuInst = CandyUI_InterfaceMenu:new() CandyUI_InterfaceMenuInst:Init()
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/West_Sarutabaruta/npcs/Slow_Axe_IM.lua
3
3344
----------------------------------- -- Area: West Sarutabaruta -- NPC: Slow Axe, I.M. -- Type: Border Conquest Guards -- !pos 399.450 -25.858 727.545 115 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Sarutabaruta/TextIDs"); local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = SARUTABARUTA; local csid = 0x7ff8; ----------------------------------- -- 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
RebootRevival/FFXI_Test
scripts/globals/items/plate_of_salmon_sushi_+1.lua
12
1583
----------------------------------------- -- ID: 5664 -- Item: plate_of_salmon_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Strength 2 -- Accuracy % 15 (cap 72) -- Ranged ACC % 15 (cap 72) -- Resist Sleep +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5664); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 72); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 72); target:addMod(MOD_SLEEPRES, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 72); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 72); target:delMod(MOD_SLEEPRES, 2); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/plate_of_bream_sushi.lua
12
1667
----------------------------------------- -- ID: 5176 -- Item: plate_of_bream_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 6 -- Vitality 5 -- Accuracy % 16 (cap 76) -- Ranged ACC % 16 (cap 76) -- Sleep Resist 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5176); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 6); target:addMod(MOD_VIT, 5); target:addMod(MOD_FOOD_ACCP, 16); target:addMod(MOD_FOOD_ACC_CAP, 76); target:addMod(MOD_FOOD_RACCP, 16); target:addMod(MOD_FOOD_RACC_CAP, 76); target:addMod(MOD_SLEEPRES, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 6); target:delMod(MOD_VIT, 5); target:delMod(MOD_FOOD_ACCP, 16); target:delMod(MOD_FOOD_ACC_CAP, 76); target:delMod(MOD_FOOD_RACCP, 16); target:delMod(MOD_FOOD_RACC_CAP, 76); target:delMod(MOD_SLEEPRES, 1); end;
gpl-3.0
onpon4/naev
dat/missions/rehab_common.lua
1
4763
--common --[[ -- -- Rehabilitation Mission -- -- This mission allows you to remain neutral with a faction until you've done services for them. -- This file is used by the various faction missions, which must set the faction variable. -- --]] require "scripts/numstring" misn_title = _("%s Rehabilitation") misn_desc = _([[You may pay a fine for a chance to redeem yourself in the eyes of a faction you have offended. You may interact with this faction as if your reputation were neutral, but your reputation will not actually improve until you've regained their trust. ANY hostile action against this faction will immediately void this agreement. Faction: %s Cost: %s]]) misn_reward = _("None") lowmoney = _("You don't have enough money. You need at least %s to buy a cessation of hostilities with this faction.") accepted = _([[Your application has been processed. The %s security forces will no longer attack you on sight. You may conduct your business in %s space again, but remember that you still have a criminal record! If you attack any traders, civilians or %s ships, or commit any other felony against this faction, you will immediately become their enemy again. While this agreement is active your reputation will not change, but if you continue to behave properly and perform beneficial services, your past offenses will eventually be stricken from the record.]]) failuretitle = _("%s Rehabilitation Canceled") failuretext = _([[You have committed another offense against this faction! Your rehabilitation procedure has been canceled, and your reputation is once again bad. You may start another rehabilitation procedure at a later time.]]) successtitle = _("%s Rehabilitation Successful") successtext = _([[Congratulations, you have successfully worked your way back into good standing with this faction. Try not to relapse into your life of crime!]]) osd_msg = {} osd_msg[1] = "(null)" osd_msg["__save"] = true function create() -- Note: this mission does not make any system claims. -- Only spawn this mission if the player needs it. rep = fac:playerStanding() if rep >= 0 then misn.finish() end -- Don't spawn this mission if the player is buddies with this faction's enemies. for _, enemy in pairs(fac:enemies()) do if enemy:playerStanding() > 20 then misn.finish() end end setFine(rep) misn.setTitle(misn_title:format(fac:name())) misn.setDesc(misn_desc:format(fac:name(), creditstring(fine))) misn.setReward(misn_reward) end function accept() if player.credits() < fine then tk.msg("", lowmoney:format(creditstring(fine))) misn.finish() end player.pay(-fine, "adjust") tk.msg(misn_title:format(fac:name()), accepted:format(fac:name(), fac:name(), fac:name())) fac:modPlayerRaw(-rep) misn.accept() osd_msg[1] = gettext.ngettext( "You need to gain %d more reputation", "You need to gain %d more reputation", -rep ):format(-rep) misn.osdCreate(misn_title:format(fac:name()), osd_msg) standhook = hook.standing("standing") excess = 5 -- The maximum amount of reputation the player can LOSE before the contract is void. end -- Function to set the height of the fine. Missions that require this script may override this. function setFine(standing) fine = (-standing)^2 * 1000 -- A value between 0 and 10M credits end -- Standing hook. Manages faction reputation, keeping it at 0 until it goes positive. function standing(hookfac, delta) if hookfac == fac then if delta >= 0 then rep = rep + delta if rep >= 0 then -- The player has successfully erased his criminal record. excess = excess + delta fac:modPlayerRaw(-delta + rep) tk.msg(successtitle:format(fac:name()), successtext) misn.finish(true) end excess = excess + delta fac:modPlayerRaw(-delta) osd_msg[1] = gettext.ngettext( "You need to gain %d more reputation", "You need to gain %d more reputation", -rep ):format(-rep) misn.osdCreate(misn_title:format(fac:name()), osd_msg) else excess = excess + delta if excess < 0 or fac:playerStanding() < 0 then abort() end end end end -- On abort, reset reputation. function abort() -- Remove the standing hook prior to modifying reputation. hook.rm(standhook) -- Reapply the original negative reputation. fac:modPlayerRaw(rep) tk.msg(failuretitle:format(fac:name()), failuretext) misn.finish(false) end
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Southern_San_dOria/npcs/Diary.lua
3
2164
----------------------------------- -- Area: Northern San d'Oria -- NPC: Diary -- Involved in Quest: To Cure a Cough -- @zone 230 -- !pos -75 -12 65 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) medicineWoman = player:getQuestStatus(SANDORIA,THE_MEDICINE_WOMAN); toCureaCough = player:getQuestStatus(SANDORIA,TO_CURE_A_COUGH); -- player:startEvent(0x02d2) -- read page 4 -- player:startEvent(0x02d3) read last page if (toCureaCough == QUEST_AVAILABLE and player:getVar("DiaryPage") == 0) then player:startEvent(0x27F); -- see diary, option to read elseif (player:getVar("DiaryPage") == 1) then player:startEvent(0x280); -- diary page 2 elseif (player:getVar("DiaryPage") >= 2 and medicineWoman == QUEST_COMPLETED) then player:startEvent(0x281); -- read page 3 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 == 0x027F and option == 0 ) then player:setVar("DiaryPage",1); -- has read page 1 elseif (csid == 0x280 and option == 1) then player:setVar("DiaryPage",1); -- can read p2, but reads page 1 instead elseif (csid == 0x280 and option == 2) then player:setVar("DiaryPage",2); -- has read page 2 elseif (csid == 0x281) then player:setVar("DiaryPage",3); -- has read page 3 end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/spells/paralyga.lua
1
1772
----------------------------------------- -- Spell: Paralyze -- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (target:hasStatusEffect(EFFECT_PARALYSIS)) then --effect already on, do nothing spell:setMsg(75); else -- Calculate duration. local duration = 120; local dMND = caster:getStat(MOD_MND) - target:getStat(MOD_MND); -- Calculate potency. local potency = math.floor(dMND / 4) + 15; if (potency > 25) then potency = 25; end if (potency < 5) then potency = 5; end --printf("Duration : %u",duration); --printf("Potency : %u",potency); local params = {}; params.diff = nil; params.attribute = MOD_MND; params.skillType = 35; params.bonus = 0; params.effect = EFFECT_PARALYSIS; resist = applyResistanceEffect(caster, target, spell, params); if (resist >= 0.5) then --there are no quarter or less hits, if target resists more than .5 spell is resisted completely if (target:addStatusEffect(EFFECT_PARALYSIS,potency,0,duration*resist)) then spell:setMsg(236); else -- no effect spell:setMsg(75); end else -- resist spell:setMsg(85); end end return EFFECT_PARALYSIS; end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Cloister_of_Flames/npcs/Fire_Protocrystal.lua
3
1897
----------------------------------- -- Area: Cloister of Flames -- NPC: Fire Protocrystal -- Involved in Quests: Trial by Fire, Trial Size Trial by Fire -- !pos -721 0 -598 207 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); require("scripts/zones/Cloister_of_Flames/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:getVar("ASA4_Scarlet") == 1) then player:startEvent(0x0002); elseif (EventTriggerBCNM(player,npc)) then return; else player:messageSpecial(PROTOCRYSTAL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (csid==0x0002) then player:delKeyItem(DOMINAS_SCARLET_SEAL); player:addKeyItem(SCARLET_COUNTERSEAL); player:messageSpecial(KEYITEM_OBTAINED,SCARLET_COUNTERSEAL); player:setVar("ASA4_Scarlet","2"); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Jugner_Forest_[S]/npcs/Glowing_Pebbles.lua
3
1896
----------------------------------- -- Area: Jugner Forest (S) -- NPC: Glowing Pebbles -- Type: Involved in Quest -- !pos -- player:startEvent(0x006a); Left over Cutscene ----------------------------------- package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Jugner_Forest_[S]/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local yagudoGlue = 2558; if (trade:hasItemQty(yagudoGlue,1)) then local nextRoadToDivadomCS = 0x006B; -- CSID 107 if (player:getVar("roadToDivadomCS") == 3) then player:tradeComplete(); player:startEvent(nextRoadToDivadomCS); player:setVar("roadToDivadomCS",4); end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("Lakeside_Minuet_Progress") == 3 and player:hasKeyItem(STARDUST_PEBBLE) == false) then player:startEvent(0x0064); player:addKeyItem(STARDUST_PEBBLE); player:messageSpecial(KEYITEM_OBTAINED,STARDUST_PEBBLE); elseif (player:getVar("roadToDivadomCS") == 2) then local nextRoadToDivadomCS = 0x006A; -- CSID 106 player:startEvent(nextRoadToDivadomCS); player:setVar("roadToDivadomCS", 3); 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
openwrt-es/openwrt-luci
applications/luci-app-uhttpd/luasrc/model/cbi/uhttpd/uhttpd.lua
7
9354
-- Copyright 2015 Daniel Dickinson <openwrt@daniel.thecshore.com> -- Licensed to the public under the Apache License 2.0. local fs = require("nixio.fs") local m = Map("uhttpd", translate("uHTTPd"), translate("A lightweight single-threaded HTTP(S) server")) local ucs = m:section(TypedSection, "uhttpd", "") ucs.addremove = true ucs.anonymous = false local lhttp = nil local lhttps = nil local cert_file = nil local key_file = nil ucs:tab("general", translate("General Settings")) ucs:tab("server", translate("Full Web Server Settings"), translate("For settings primarily geared to serving more than the web UI")) ucs:tab("advanced", translate("Advanced Settings"), translate("Settings which are either rarely needed or which affect serving the WebUI")) lhttp = ucs:taboption("general", DynamicList, "listen_http", translate("HTTP listeners (address:port)"), translate("Bind to specific interface:port (by specifying interface address")) lhttp.datatype = "list(ipaddrport(1))" function lhttp.validate(self, value, section) local have_https_listener = false local have_http_listener = false if lhttp and lhttp:formvalue(section) and (#(lhttp:formvalue(section)) > 0) then for k, v in pairs(lhttp:formvalue(section)) do if v and (v ~= "") then have_http_listener = true break end end end if lhttps and lhttps:formvalue(section) and (#(lhttps:formvalue(section)) > 0) then for k, v in pairs(lhttps:formvalue(section)) do if v and (v ~= "") then have_https_listener = true break end end end if not (have_http_listener or have_https_listener) then return nil, "must listen on at least one address:port" end return DynamicList.validate(self, value, section) end lhttps = ucs:taboption("general", DynamicList, "listen_https", translate("HTTPS listener (address:port)"), translate("Bind to specific interface:port (by specifying interface address")) lhttps.datatype = "list(ipaddrport(1))" lhttps:depends("cert") lhttps:depends("key") function lhttps.validate(self, value, section) local have_https_listener = false local have_http_listener = false if lhttps and lhttps:formvalue(section) and (#(lhttps:formvalue(section)) > 0) then for k, v in pairs(lhttps:formvalue(section)) do if v and (v ~= "") then have_https_listener = true break end end if have_https_listener and ((not cert_file) or (not cert_file:formvalue(section)) or (cert_file:formvalue(section) == "")) then return nil, "must have certificate when using https" end if have_https_listener and ((not key_file) or (not key_file:formvalue(section)) or (key_file:formvalue(section) == "")) then return nil, "must have key when using https" end end if lhttp and (lhttp:formvalue(section)) and (#lhttp:formvalue(section) > 0) then for k, v in pairs(lhttp:formvalue(section)) do if v and (v ~= "") then have_http_listener = true break end end end if not (have_http_listener or have_https_listener) then return nil, "must listen on at least one address:port" end return DynamicList.validate(self, value, section) end o = ucs:taboption("general", Flag, "redirect_https", translate("Redirect all HTTP to HTTPS")) o.default = o.enabled o.rmempty = false o = ucs:taboption("general", Flag, "rfc1918_filter", translate("Ignore private IPs on public interface"), translate("Prevent access from private (RFC1918) IPs on an interface if it has an public IP address")) o.default = o.enabled o.rmempty = false cert_file = ucs:taboption("general", FileUpload, "cert", translate("HTTPS Certificate (DER Encoded)")) key_file = ucs:taboption("general", FileUpload, "key", translate("HTTPS Private Key (DER Encoded)")) o = ucs:taboption("general", Button, "remove_old", translate("Remove old certificate and key"), translate("uHTTPd will generate a new self-signed certificate using the configuration shown below.")) o.inputstyle = "remove" function o.write(self, section) if cert_file:cfgvalue(section) and fs.access(cert_file:cfgvalue(section)) then fs.unlink(cert_file:cfgvalue(section)) end if key_file:cfgvalue(section) and fs.access(key_file:cfgvalue(section)) then fs.unlink(key_file:cfgvalue(section)) end luci.sys.call("/etc/init.d/uhttpd restart") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "uhttpd")) end o = ucs:taboption("general", Button, "remove_conf", translate("Remove configuration for certificate and key"), translate("This permanently deletes the cert, key, and configuration to use same.")) o.inputstyle = "remove" function o.write(self, section) if cert_file:cfgvalue(section) and fs.access(cert_file:cfgvalue(section)) then fs.unlink(cert_file:cfgvalue(section)) end if key_file:cfgvalue(section) and fs.access(key_file:cfgvalue(section)) then fs.unlink(key_file:cfgvalue(section)) end self.map:del(section, "cert") self.map:del(section, "key") self.map:del(section, "listen_https") luci.http.redirect(luci.dispatcher.build_url("admin", "services", "uhttpd")) end o = ucs:taboption("server", DynamicList, "index_page", translate("Index page(s)"), translate("E.g specify with index.html and index.php when using PHP")) o.optional = true o.placeholder = "index.html" o = ucs:taboption("server", DynamicList, "interpreter", translate("CGI filetype handler"), translate("Interpreter to associate with file endings ('suffix=handler', e.g. '.php=/usr/bin/php-cgi')")) o.optional = true o = ucs:taboption("server", Flag, "no_symlinks", translate("Do not follow symlinks outside document root")) o.optional = true o = ucs:taboption("server", Flag, "no_dirlists", translate("Do not generate directory listings.")) o.default = o.disabled o = ucs:taboption("server", DynamicList, "alias", translate("Aliases"), translate("(/old/path=/new/path) or (just /old/path which becomes /cgi-prefix/old/path)")) o.optional = true o = ucs:taboption("server", Value, "realm", translate("Realm for Basic Auth")) o.optional = true o.placeholder = luci.sys.hostname() or "OpenWrt" local httpconfig = ucs:taboption("server", Value, "config", translate("Config file (e.g. for credentials for Basic Auth)"), translate("Will not use HTTP authentication if not present")) httpconfig.optional = true o = ucs:taboption("server", Value, "error_page", translate("404 Error"), translate("Virtual URL or CGI script to display on status '404 Not Found'. Must begin with '/'")) o.optional = true o = ucs:taboption("advanced", Value, "home", translate("Document root"), translate("Base directory for files to be served")) o.default = "/www" o.datatype = "directory" o = ucs:taboption("advanced", Value, "cgi_prefix", translate("Path prefix for CGI scripts"), translate("CGI is disabled if not present.")) o.optional = true o = ucs:taboption("advanced", Value, "lua_prefix", translate("Virtual path prefix for Lua scripts")) o.placeholder = "/lua" o.optional = true o = ucs:taboption("advanced", Value, "lua_handler", translate("Full real path to handler for Lua scripts"), translate("Embedded Lua interpreter is disabled if not present.")) o.optional = true o = ucs:taboption("advanced", Value, "ubus_prefix", translate("Virtual path prefix for ubus via JSON-RPC integration"), translate("ubus integration is disabled if not present")) o.optional = true o = ucs:taboption("advanced", Value, "ubus_socket", translate("Override path for ubus socket")) o.optional = true o = ucs:taboption("advanced", Flag, "ubus_cors", translate("Enable JSON-RPC Cross-Origin Resource Support")) o.default = o.disabled o.optional = true o = ucs:taboption("advanced", Flag, "no_ubusauth", translate("Disable JSON-RPC authorization via ubus session API")) o.optional= true o.default = o.disabled o = ucs:taboption("advanced", Value, "script_timeout", translate("Maximum wait time for Lua, CGI, or ubus execution")) o.placeholder = 60 o.datatype = "uinteger" o.optional = true o = ucs:taboption("advanced", Value, "network_timeout", translate("Maximum wait time for network activity")) o.placeholder = 30 o.datatype = "uinteger" o.optional = true o = ucs:taboption("advanced", Value, "http_keepalive", translate("Connection reuse")) o.placeholder = 20 o.datatype = "uinteger" o.optional = true o = ucs:taboption("advanced", Value, "tcp_keepalive", translate("TCP Keepalive")) o.optional = true o.datatype = "uinteger" o.default = 1 o = ucs:taboption("advanced", Value, "max_connections", translate("Maximum number of connections")) o.optional = true o.datatype = "uinteger" o = ucs:taboption("advanced", Value, "max_requests", translate("Maximum number of script requests")) o.optional = true o.datatype = "uinteger" local s = m:section(TypedSection, "cert", translate("uHTTPd Self-signed Certificate Parameters")) s.template = "cbi/tsection" s.anonymous = true o = s:option(Value, "days", translate("Valid for # of Days")) o.default = 730 o.datatype = "uinteger" o = s:option(Value, "bits", translate("Length of key in bits")) o.default = 2048 o.datatype = "min(1024)" o = s:option(Value, "commonname", translate("Server Hostname"), translate("a.k.a CommonName")) o.default = luci.sys.hostname() o = s:option(Value, "country", translate("Country")) o.default = "ZZ" o = s:option(Value, "state", translate("State")) o.default = "Unknown" o = s:option(Value, "location", translate("Location")) o.default = "Unknown" return m
apache-2.0
petoju/awesome
lib/naughty/notification.lua
1
33479
--------------------------------------------------------------------------- --- A notification object. -- -- This class creates individual notification objects that can be manipulated -- to extend the default behavior. -- -- This class doesn't define the actual widget, but is rather intended as a data -- object to hold the properties. All examples assume the default widgets, but -- the whole implementation can be replaced. -- --@DOC_naughty_actions_EXAMPLE@ -- -- @author Emmanuel Lepage Vallee -- @copyright 2008 koniu -- @copyright 2017 Emmanuel Lepage Vallee -- @coreclassmod naughty.notification --------------------------------------------------------------------------- local capi = { screen = screen } local gobject = require("gears.object") local gtable = require("gears.table") local timer = require("gears.timer") local gfs = require("gears.filesystem") local cst = require("naughty.constants") local naughty = require("naughty.core") local gdebug = require("gears.debug") local pcommon = require("awful.permissions._common") local notification = {} --- Notifications font. -- @beautiful beautiful.notification_font -- @tparam string|lgi.Pango.FontDescription notification_font --- Notifications background color. -- @beautiful beautiful.notification_bg -- @tparam color notification_bg --- Notifications foreground color. -- @beautiful beautiful.notification_fg -- @tparam color notification_fg --- Notifications border width. -- @beautiful beautiful.notification_border_width -- @tparam int notification_border_width --- Notifications border color. -- @beautiful beautiful.notification_border_color -- @tparam color notification_border_color --- Notifications shape. -- @beautiful beautiful.notification_shape -- @tparam[opt] gears.shape notification_shape -- @see gears.shape --- Notifications opacity. -- @beautiful beautiful.notification_opacity -- @tparam[opt] int notification_opacity --- The margins inside of the notification widget (or popup). -- @beautiful beautiful.notification_margin -- @tparam int notification_margin --- Notifications width. -- @beautiful beautiful.notification_width -- @tparam int notification_width --- Notifications height. -- @beautiful beautiful.notification_height -- @tparam int notification_height --- The spacing between the notifications. -- @beautiful beautiful.notification_spacing -- @param[opt=2] number -- @see gears.surface -- Unique identifier of the notification. -- This is the equivalent to a PID as allows external applications to select -- notifications. -- @property id -- @tparam number id -- @propemits true false --- Text of the notification. -- -- This exists only for the pre-AwesomeWM v4.4 new notification implementation. -- Please always use `title`. -- -- @deprecatedproperty text -- @param string -- @see title --- Title of the notification. --@DOC_naughty_helloworld_EXAMPLE@ -- @property title -- @tparam string title -- @propemits true false --- Time in seconds after which popup expires. -- Set 0 for no timeout. -- @property timeout -- @tparam number timeout -- @propemits true false --- The notification urgency level. -- -- The default urgency levels are: -- -- * low -- * normal -- * critical -- -- @property urgency -- @param string -- @propemits true false --- The notification category. -- -- The category should be named using the `x-vendor.class.name` naming scheme or -- use one of the default categories: -- -- <table class='widget_list' border=1> -- <tr style='font-weight: bold;'> -- <th align='center'>Name</th> -- <th align='center'>Description</th> -- </tr> -- <tr><td><b>device</b></td><td>A generic device-related notification that -- doesn't fit into any other category.</td></tr> -- <tr><td><b>device.added</b></td><td>A device, such as a USB device, was added to the system.</td></tr> -- <tr><td><b>device.error</b></td><td>A device had some kind of error.</td></tr> -- <tr><td><b>device.removed</b></td><td>A device, such as a USB device, was removed from the system.</td></tr> -- <tr><td><b>email</b></td><td>A generic e-mail-related notification that doesn't fit into -- any other category.</td></tr> -- <tr><td><b>email.arrived</b></td><td>A new e-mail notification.</td></tr> -- <tr><td><b>email.bounced</b></td><td>A notification stating that an e-mail has bounced.</td></tr> -- <tr><td><b>im</b></td><td>A generic instant message-related notification that doesn't fit into -- any other category.</td></tr> -- <tr><td><b>im.error</b></td><td>An instant message error notification.</td></tr> -- <tr><td><b>im.received</b></td><td>A received instant message notification.</td></tr> -- <tr><td><b>network</b></td><td>A generic network notification that doesn't fit into any other -- category.</td></tr> -- <tr><td><b>network.connected</b></td><td>A network connection notification, such as successful -- sign-on to a network service. <br /> -- This should not be confused with device.added for new network devices.</td></tr> -- <tr><td><b>network.disconnected</b></td><td>A network disconnected notification. This should not -- be confused with <br /> -- device.removed for disconnected network devices.</td></tr> -- <tr><td><b>network.error</b></td><td>A network-related or connection-related error.</td></tr> -- <tr><td><b>presence</b></td><td>A generic presence change notification that doesn't fit into any -- other category, <br /> -- such as going away or idle.</td></tr> -- <tr><td><b>presence.offline</b></td><td>An offline presence change notification.</td></tr> -- <tr><td><b>presence.online</b></td><td>An online presence change notification.</td></tr> -- <tr><td><b>transfer</b></td><td>A generic file transfer or download notification that doesn't -- fit into any other category.</td></tr> -- <tr><td><b>transfer.complete</b></td><td>A file transfer or download complete notification.</td></tr> -- <tr><td><b>transfer.error</b></td><td>A file transfer or download error.</td></tr> -- </table> -- -- @property category -- @tparam string|nil category -- @propemits true false --- True if the notification should be kept when an action is pressed. -- -- By default, invoking an action will destroy the notification. Some actions, -- like the "Snooze" action of alarm clock, will cause the notification to -- be updated with a date further in the future. -- -- @property resident -- @param[opt=false] boolean -- @propemits true false --- Delay in seconds after which hovered popup disappears. -- @property hover_timeout -- @param number -- @propemits true false --- Target screen for the notification. -- @property screen -- @param screen -- @propemits true false --- Corner of the workarea displaying the popups. -- -- The possible values are: -- -- * *top_right* -- * *top_left* -- * *bottom_left* -- * *bottom_right* -- * *top_middle* -- * *bottom_middle* -- * *middle* -- --@DOC_awful_notification_box_corner_EXAMPLE@ -- -- @property position -- @param string -- @propemits true false -- @see awful.placement.next_to --- Boolean forcing popups to display on top. -- @property ontop -- @param boolean --- Popup height. -- --@DOC_awful_notification_geometry_EXAMPLE@ -- -- @property height -- @param number -- @propemits true false -- @see width --- Popup width. -- @property width -- @param number -- @propemits true false -- @see height --- Notification font. --@DOC_naughty_colors_EXAMPLE@ -- @property font -- @param string -- @propemits true false --- "All in one" way to access the default image or icon. -- -- A notification can provide a combination of an icon, a static image, or if -- enabled, a looping animation. Add to that the ability to import the icon -- information from the client or from a `.desktop` file, there is multiple -- conflicting sources of "icons". -- -- On the other hand, the vast majority of notifications don't multiple or -- ambiguous sources of icons. This property will pick the first of the -- following. -- -- * The `image`. -- * The `app_icon`. -- * The `icon` from a client with `normal` type. -- * The `icon` of a client with `dialog` type. -- -- @property icon -- @tparam string|surface icon -- @propemits true false -- @see app_icon -- @see image --- Desired icon size in px. -- @property icon_size -- @param number -- @propemits true false --- The icon provided in the `app_icon` field of the DBus notification. -- -- This should always be either the URI (path) to an icon or a valid XDG -- icon name to be fetched from the theme. -- -- @property app_icon -- @param string -- @propemits true false --- The notification image. -- -- This is usually provided as a `gears.surface` object. The image is used -- instead of the `app_icon` by notification assets which are auto-generated -- or stored elsewhere than the filesystem (databases, web, Android phones, etc). -- -- @property image -- @tparam string|surface image -- @propemits true false --- The notification (animated) images. -- -- Note that calling this without first setting -- `naughty.image_animations_enabled` to true will throw an exception. -- -- Also note that there is *zero* support for this anywhere else in `naughty` -- and very, very few applications support this. -- -- @property images -- @tparam nil|table images -- @propemits true false --- Foreground color. -- --@DOC_awful_notification_fg_EXAMPLE@ -- -- @property fg -- @tparam string|color|pattern fg -- @propemits true false -- @see title -- @see gears.color --- Background color. -- --@DOC_awful_notification_bg_EXAMPLE@ -- -- @property bg -- @tparam string|color|pattern bg -- @propemits true false -- @see title -- @see gears.color --- Border width. -- @property border_width -- @param number -- @propemits true false --- Border color. -- --@DOC_awful_notification_border_color_EXAMPLE@ -- -- @property border_color -- @param string -- @propemits true false -- @see gears.color --- Widget shape. -- -- Note that when using a custom `request::display` handler or `naughty.rules`, -- choosing between multiple shapes depending on the content can be done using -- expressions like: -- -- -- The notification object is called `n` -- shape = #n.actions > 0 and -- gears.shape.rounded_rect or gears.shape.rounded_bar, -- --@DOC_awful_notification_shape_EXAMPLE@ -- --@DOC_naughty_shape_EXAMPLE@ -- -- @property shape -- @tparam gears.shape shape -- @propemits true false --- Widget opacity. -- @property opacity -- @tparam number opacity Between 0 to 1. -- @propemits true false --- Widget margin. -- --@DOC_awful_notification_margin_EXAMPLE@ -- -- @property margin -- @tparam number|table margin -- @propemits true false -- @see shape --- Function to run on left click. -- -- Use the signals rather than this. -- -- @deprecatedproperty run -- @param function -- @see destroyed --- Function to run when notification is destroyed. -- -- Use the signals rather than this. -- -- @deprecatedproperty destroy -- @param function -- @see destroyed --- Table with any of the above parameters. -- args will override ones defined -- in the preset. -- @property preset -- @param table -- @propemits true false --- Function that will be called with all arguments. -- The notification will only be displayed if the function returns true. -- Note: this function is only relevant to notifications sent via dbus. -- @property callback -- @param function -- @propemits true false --- A table containing strings that represents actions to buttons. -- -- The table key (a number) is used by DBus to set map the action. -- -- @property actions -- @param table -- @propemits true false --- Ignore this notification, do not display. -- -- Note that this property has to be set in a `preset` or in a `request::preset` -- handler. -- -- @property ignore -- @param boolean -- @propemits true false --- Tell if the notification is currently suspended (read only). -- -- This is always equal to `naughty.suspended` --@property suspended --@param boolean -- @propemits true false --- If the notification is expired. -- @property is_expired -- @param boolean -- @propemits true false -- @see naughty.expiration_paused --- If the timeout needs to be reset when a property changes. -- -- By default it fallsback to `naughty.auto_reset_timeout`, which itself is -- true by default. -- -- @property auto_reset_timeout -- @tparam[opt=true] boolean auto_reset_timeout -- @propemits true false --- Emitted when the notification is destroyed. -- @signal destroyed -- @tparam number reason Why it was destroyed -- @tparam boolean keep_visible If it was kept visible. -- @see naughty.notification_closed_reason -- . --FIXME needs a description -- @property ignore_suspend If set to true this notification -- will be shown even if notifications are suspended via `naughty.suspend`. --- A list of clients associated with this notification. -- -- When used with DBus notifications, this returns all clients sharing the PID -- of the notification sender. Note that this is highly unreliable. -- Applications that use a different process to send the notification or -- applications (and scripts) calling the `notify-send` command wont have any -- client. -- -- @property clients -- @param table --- The maximum popup width. -- -- Some notifications have overlong message, cap them to this width. Note that -- this is ignored by `naughty.list.notifications` because it delegate this -- decision to the layout. -- -- @property[opt=500] max_width -- @param number -- @propemits true false --- The application name specified by the notification. -- -- This can be anything. It is usually less relevant than the `clients` -- property, but can sometime be specified for remote or headless notifications. -- In these case, it helps to triage and detect the notification from the rules. -- @property app_name -- @param string -- @propemits true false --- The widget template used to represent the notification. -- -- Some notifications, such as chat messages or music applications are better -- off with a specialized notification widget. -- -- @property widget_template -- @param table -- @propemits true false --- Destroy notification by notification object. -- -- @method destroy -- @tparam string reason One of the reasons from `notification_closed_reason` -- @tparam[opt=false] boolean keep_visible If true, keep the notification visible -- @treturn boolean True if the popup was successfully destroyed, false otherwise. -- @emits destroyed -- @emitstparam destroyed integer reason The reason. -- @emitstparam destroyed boolean keep_visible If the notification should be kept. -- @see naughty.notification_closed_reason function notification:destroy(reason, keep_visible) if self._private.is_destroyed then gdebug.print_warning("Trying to destroy the same notification twice. It".. " was destroyed because: "..self._private.destroy_reason) return false end reason = reason or cst.notification_closed_reason.dismissed_by_user self:emit_signal("destroyed", reason, keep_visible) self._private.is_destroyed = true self._private.destroy_reason = reason return true end --- Set new notification timeout. -- @method reset_timeout -- @tparam number new_timeout Time in seconds after which notification disappears. function notification:reset_timeout(new_timeout) if self.timer then self.timer:stop() end -- Do not set `self.timeout` to `self.timeout` since that would create the -- timer before the constructor ends. if new_timeout and self.timer then self.timeout = new_timeout end if self.timer and not self.timer.started then self.timer:start() end end function notification:set_id(new_id) assert(self._private.id == nil, "Notification identifier can only be set once") self._private.id = new_id self:emit_signal("property::id", new_id) end function notification:set_timeout(timeout) timeout = timeout or 0 local die = function (reason) if reason == cst.notification_closed_reason.expired then self.is_expired = true if naughty.expiration_paused then table.insert(naughty.notifications._expired[1], self) return end end self:destroy(reason) end if self.timer and self._private.timeout == timeout then return end -- 0 == never if timeout > 0 then local timer_die = timer { timeout = timeout } timer_die:connect_signal("timeout", function() pcall(die, cst.notification_closed_reason.expired) -- Prevent infinite timers events on errors. if timer_die.started then timer_die:stop() end end) --FIXME there's still a dependency loop to fix before it works if not self.suspended then timer_die:start() end -- Prevent a memory leak and the accumulation of active timers if self.timer and self.timer.started then self.timer:stop() end self.timer = timer_die end self.die = die self._private.timeout = timeout self:emit_signal("property::timeout", timeout) end function notification:set_text(txt) gdebug.deprecate( "The `text` attribute is deprecated, use `message`", {deprecated_in=5} ) self:set_message(txt) end function notification:get_text() gdebug.deprecate( "The `text` attribute is deprecated, use `message`", {deprecated_in=5} ) return self:get_message() end local properties = { "message" , "title" , "timeout" , "hover_timeout" , "app_name", "position", "ontop" , "border_width" , "width" , "font" , "icon" , "icon_size" , "fg" , "bg" , "height" , "border_color" , "shape" , "opacity" , "margin" , "ignore_suspend", "destroy" , "preset" , "callback", "actions" , "run" , "id" , "ignore" , "auto_reset_timeout", "urgency" , "image" , "images" , "widget_template", "max_width", } for _, prop in ipairs(properties) do notification["get_"..prop] = notification["get_"..prop] or function(self) -- It's possible this could be called from the `request::preset` handler. -- `rawget()` is necessary to avoid a stack overflow. local preset = rawget(self, "preset") return self._private[prop] or (preset and preset[prop]) or cst.config.defaults[prop] end notification["set_"..prop] = notification["set_"..prop] or function(self, value) self._private[prop] = value self:emit_signal("property::"..prop, value) -- When a notification is updated over dbus or by setting a property, -- it is usually convenient to reset the timeout. local reset = ((not self.suspended) and self.auto_reset_timeout ~= false and naughty.auto_reset_timeout) if reset then self:reset_timeout() end end end -- Changing the image will change the icon, make sure property::icon is emitted. for _, prop in ipairs {"image", "images" } do local cur = notification["set_"..prop] notification["set_"..prop] = function(self, value) cur(self, value) self._private.icon = nil self:emit_signal("property::icon") end end local hints_default = { urgency = "normal", resident = false, } for _, prop in ipairs { "category", "resident" } do notification["get_"..prop] = notification["get_"..prop] or function(self) return self._private[prop] or ( self._private.freedesktop_hints and self._private.freedesktop_hints[prop] ) or hints_default[prop] end notification["set_"..prop] = notification["set_"..prop] or function(self, value) self._private[prop] = value self:emit_signal("property::"..prop, value) end end -- Stop the request::icon when one is found. local function request_filter(self, context, _) if not pcommon.check(self, "notification", "icon", context) then return true end if self._private.icon then return true end end -- Convert encoded local URI to Unix paths. local function check_path(input) if type(input) ~= "string" then return nil end if input:sub(1,7) == "file://" then input = input:sub(8) end -- urldecode input = input:gsub("%%(%x%x)", function(x) return string.char(tonumber(x, 16)) end ) return gfs.file_readable(input) and input or nil end function notification.get_icon(self) -- Honor all overrides. if self._private.icon then return self._private.icon == "" and nil or self._private.icon end -- First, check if the image is passed as a surface or a path. if self.image and self.image ~= "" then naughty._emit_signal_if("request::icon", request_filter, self, "image", { image = self.image }) elseif self.images then naughty._emit_signal_if("request::icon", request_filter, self, "images", { images = self.images }) end if self._private.icon then return self._private.icon == "" and nil or self._private.icon end -- Second level of fallback, icon paths. local path = check_path(self._private.app_icon) if path then naughty._emit_signal_if("request::icon", request_filter, self, "path", { path = path }) end if self._private.icon then return self._private.icon == "" and nil or self._private.icon end -- Third level fallback is `app_icon`. if self._private.app_icon then naughty._emit_signal_if("request::icon", request_filter, self, "app_icon", { app_icon = self._private.app_icon }) end -- Finally, the clients. naughty._emit_signal_if("request::icon", request_filter, self, "clients", {}) return self._private.icon == "" and nil or self._private.icon end function notification.get_clients(self) -- Clients from the future don't send notification, it's useless to reload -- the list over and over. if self._private.clients then return self._private.clients end if not self._private._unique_sender then return {} end self._private.clients = require("naughty.dbus").get_clients(self) return self._private.clients end function notification.set_actions(self, new_actions) for _, a in ipairs(self._private.actions or {}) do a:disconnect_signal("_changed", self._private.action_cb ) a:disconnect_signal("invoked" , self._private.invoked_cb) end -- Clone so `append_actions` doesn't add unwanted actions to other -- notifications. self._private.actions = gtable.clone(new_actions, false) for _, a in ipairs(self._private.actions or {}) do a:connect_signal("_changed", self._private.action_cb ) a:connect_signal("invoked" , self._private.invoked_cb) end self:emit_signal("property::actions", new_actions) -- When a notification is updated over dbus or by setting a property, -- it is usually convenient to reset the timeout. local reset = ((not self.suspended) and self.auto_reset_timeout ~= false and naughty.auto_reset_timeout) if reset then self:reset_timeout() end end --- Add more actions to the notification. -- @method append_actions -- @tparam table new_actions function notification:append_actions(new_actions) self._private.actions = self._private.actions or {} for _, a in ipairs(new_actions or {}) do a:connect_signal("_changed", self._private.action_cb ) a:connect_signal("invoked" , self._private.invoked_cb) table.insert(self._private.actions, a) end end function notification:set_screen(s) assert(not self._private.screen) s = s and capi.screen[s] or nil -- Avoid an infinite loop in the management code. if s == self._private.weak_screen[1] then return end self._private.weak_screen = setmetatable({s}, {__mode="v"}) self:emit_signal("property::screen", s) end function notification:get_screen() return self._private.weak_screen[1] end --TODO v6: remove this local function convert_actions(actions) gdebug.deprecate( "The notification actions should now be of type `naughty.action`, ".. "not strings or callback functions", {deprecated_in=5} ) local naction = require("naughty.action") local new_actions = {} -- Does not attempt to handle when there is a mix of strings and objects for idx, name in pairs(actions) do local cb, old_idx = nil, idx if type(name) == "function" then cb = name end if type(idx) == "string" then name, idx = idx, #actions+1 end local a = naction { position = idx, name = name, } if cb then a:connect_signal("invoked", cb) end new_actions[old_idx] = a end -- Yes, it modifies `args`, this is legacy code, cloning the args -- just for this isn't worth it. for old_idx, a in pairs(new_actions) do actions[a.position] = a actions[ old_idx ] = nil end end -- The old API used monkey-patched variable presets. -- -- Monkey-patched anything is always an issue and prevent module from safely -- doing anything without stepping on each other foot. In the background, -- presets were selected with a rule-like API anyway. local function select_legacy_preset(n, args) for _, obj in pairs(cst.config.mapping) do local filter, preset = obj[1], obj[2] if (not filter.urgency or filter.urgency == args.urgency) and (not filter.category or filter.category == args.category) and (not filter.appname or filter.appname == args.appname) then args.preset = gtable.join(args.preset or {}, preset) end end -- gather variables together rawset(n, "preset", gtable.join( cst.config.defaults or {}, args.preset or cst.config.presets.normal or {}, rawget(n, "preset") or {} )) for k, v in pairs(n.preset) do n._private[k] = v end end --- Create a notification. -- -- @tparam table args The argument table containing any of the arguments below. -- @string[opt=""] args.text Text of the notification. -- @string[opt] args.title Title of the notification. -- @int[opt=5] args.timeout Time in seconds after which popup expires. -- Set 0 for no timeout. -- @int[opt] args.hover_timeout Delay in seconds after which hovered popup disappears. -- @tparam[opt=focused] integer|screen args.screen Target screen for the notification. -- @string[opt="top_right"] args.position Corner of the workarea displaying the popups. -- Values: `"top_right"`, `"top_left"`, `"bottom_left"`, -- `"bottom_right"`, `"top_middle"`, `"bottom_middle"`, `"middle"`. -- @bool[opt=true] args.ontop Boolean forcing popups to display on top. -- @int[opt=`beautiful.notification_height` or auto] args.height Popup height. -- @int[opt=`beautiful.notification_width` or auto] args.width Popup width. -- @string[opt=`beautiful.notification_font` or `beautiful.font` or `awesome.font`] args.font Notification font. -- @string[opt] args.icon Path to icon. -- @int[opt] args.icon_size Desired icon size in px. -- @string[opt=`beautiful.notification_fg` or `beautiful.fg_focus` or `'#ffffff'`] args.fg Foreground color. -- @string[opt=`beautiful.notification_fg` or `beautiful.bg_focus` or `'#535d6c'`] args.bg Background color. -- @int[opt=`beautiful.notification_border_width` or 1] args.border_width Border width. -- @string[opt=`beautiful.notification_border_color` or -- `beautiful.border_color_active` or `'#535d6c'`] args.border_color Border color. -- @tparam[opt=`beautiful.notification_shape`] gears.shape args.shape Widget shape. -- @tparam[opt=`beautiful.notification_opacity`] gears.opacity args.opacity Widget opacity. -- @tparam[opt=`beautiful.notification_margin`] gears.margin args.margin Widget margin. -- @tparam[opt] func args.run Function to run on left click. The notification -- object will be passed to it as an argument. -- You need to call e.g. -- `notification.die(naughty.notification_closed_reason.dismissedByUser)` from -- there to dismiss the notification yourself. -- @tparam[opt] func args.destroy Function to run when notification is destroyed. -- @tparam[opt] table args.preset Table with any of the above parameters. -- Note: Any parameters specified directly in args will override ones defined -- in the preset. -- @tparam[opt] func args.callback Function that will be called with all arguments. -- The notification will only be displayed if the function returns true. -- Note: this function is only relevant to notifications sent via dbus. -- @tparam[opt] table args.actions A list of `naughty.action`s. -- @bool[opt=false] args.ignore_suspend If set to true this notification -- will be shown even if notifications are suspended via `naughty.suspend`. -- @usage naughty.notify({ title = "Achtung!", message = "You're idling", timeout = 0 }) -- @treturn ?table The notification object, or nil in case a notification was -- not displayed. -- @constructorfct naughty.notification local function create(args) if cst.config.notify_callback then args = cst.config.notify_callback(args) if not args then return end end assert(not args.id, "Identifiers cannot be specified externally") args = args or {} -- Old actions usually have callbacks and names. But this isn't non -- compliant with the spec. The spec has explicit ordering and optional -- icons. The old format doesn't allow these metadata to be stored. local is_old_action = args.actions and ( (args.actions[1] and type(args.actions[1]) == "string") or (type(next(args.actions)) == "string") ) local n = gobject { enable_properties = true, } if args.text then gdebug.deprecate( "The `text` attribute is deprecated, use `message`", {deprecated_in=5} ) args.message = args.text end assert(naughty.emit_signal) -- Make sure all signals bubble up n:_connect_everything(naughty.emit_signal) -- Avoid modifying the original table local private = {weak_screen = setmetatable({}, {__mode="v"})} rawset(n, "_private", private) -- Allow extensions to create override the preset with custom data if not naughty._has_preset_handler then select_legacy_preset(n, args) end if is_old_action then convert_actions(args.actions) end for k, v in pairs(args) do -- Don't keep a strong reference to the screen, Lua 5.1 GC wont be -- smart enough to unwind the mess of circular weak references. if k ~= "screen" then private[k] = v end end -- It's an automatic property n.is_expired = false gtable.crush(n, notification, true) -- Always emit property::actions when any of the action change to allow -- some widgets to be updated without over complicated built-in tracking -- of all options. function n._private.action_cb() n:emit_signal("property::actions") end -- Listen to action press and destroy non-resident notifications. function n._private.invoked_cb(a, notif) if (not notif) or notif == n then n:emit_signal("invoked", a) if not n.resident then n:destroy(cst.notification_closed_reason.dismissed_by_user) end end end -- notif.actions should not be nil to allow checking if there is actions -- using the shorthand `if #notif.actions > 0 then` private.actions = {} if args.actions then notification.set_actions(n, args.actions) end n.id = n.id or notification._gen_next_id() -- Register the notification before requesting a widget n:emit_signal("new", args) -- The rules are attached to this. if naughty._has_preset_handler then naughty.emit_signal("request::preset", n, "new", args) end -- Let all listeners handle the actual visual aspects if (not n.ignore) and ((not n.preset) or n.preset.ignore ~= true) then naughty.emit_signal("request::display" , n, "new", args) naughty.emit_signal("request::fallback", n, "new", args) end -- Because otherwise the setter logic would not be executed if n._private.timeout then n:set_timeout(n._private.timeout or (n.preset and n.preset.timeout) or cst.config.timeout ) end return n end --- Grant a permission for a notification. -- -- @method grant -- @tparam string permission The permission name (just the name, no `request::`). -- @tparam string context The reason why this permission is requested. -- @see awful.permissions --- Deny a permission for a notification -- -- @method deny -- @tparam string permission The permission name (just the name, no `request::`). -- @tparam string context The reason why this permission is requested. -- @see awful.permissions pcommon.setup_grant(notification, "notification") -- This allows notification to be updated later. local counter = 1 -- Identifier support. function notification._gen_next_id() counter = counter+1 return counter end --@DOC_object_COMMON@ return setmetatable(notification, {__call = function(_, ...) return create(...) end})
gpl-2.0
RebootRevival/FFXI_Test
scripts/globals/items/cobalt_jellyfish.lua
12
1342
----------------------------------------- -- ID: 4443 -- Item: cobalt_jellyfish -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity 1 -- Mind -3 ----------------------------------------- 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,4443); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_MND,-3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_MND,-3); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Port_San_dOria/npcs/Brifalien.lua
3
1815
----------------------------------- -- Area: Port San d'Oria -- NPC: Brifalien -- Involved in Quests: Riding on the Clouds -- @zone 232 -- !pos -20 -4 -74 ----------------------------------- 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") == 7) 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) player:startEvent(0x024d); 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
sajadaltaie/sejobot
plugins/commands.lua
31
2957
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -------------------------------------------------- do local function run(msg, matches) text = '#⃣ '..lang_text(msg.to.id, 'commandsT')..':\n' local space = '\n' if matches[1] == 'commands' and not matches[2] then if permissions(msg.from.id, msg.to.id, "mod_commands") then local langHash = 'langset:'..msg.to.id local lang = redis:get(langHash) for v,plugin in pairs(_config.enabled_plugins) do local textHash = 'lang:'..lang..':'..plugin..':0' if redis:get(textHash) then for i=1, tonumber(lang_text(msg.to.id, plugin..':0')), 1 do text = text..lang_text(msg.to.id, plugin..':'..i)..'\n' end text = text..space end end else text = text..lang_text(msg.to.id, 'moderation:5')..'\n' text = text..lang_text(msg.to.id, 'version:1')..'\n' text = text..lang_text(msg.to.id, 'rules:1')..'\n' end elseif matches[1] == 'commands' and matches[2] then if permissions(msg.from.id, msg.to.id, "mod_commands") then local langHash = 'langset:'..msg.to.id local lang = redis:get(langHash) for v,plugin in pairs(_config.enabled_plugins) do if plugin == matches[2] then local textHash = 'lang:'..lang..':'..plugin..':0' if redis:get(textHash) then for i=1, tonumber(lang_text(msg.to.id, plugin..':0')), 1 do text = text..lang_text(msg.to.id, plugin..':'..i)..'\n' end end return text end end return 'ℹ️ '..lang_text(msg.to.id, 'errorNoPlug') else return '🚫 '..lang_text(msg.to.id, 'require_mod') end end return text end return { patterns = { "^#(commands)$", "^#(commands) (.+)" }, run = run } end for v,user in pairs(_gbans.gbans_users) do if tonumber(user) == tonumber(user_id) then return true end end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/South_Gustaberg/mobs/Tococo.lua
16
1203
----------------------------------- -- Area: South Gustaberg -- NM: Tococo ----------------------------------- require("scripts/globals/status"); ----------------------------------- ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- Guesstimating 1 in 3 chance to poison on melee. if ((math.random(1,100) >= 33) or (target:hasStatusEffect(EFFECT_POISON) == true)) then return 0,0,0; else local duration = math.random(5,15); target:addStatusEffect(EFFECT_POISON,5,3,duration); return SUBEFFECT_POISON,0,EFFECT_POISON; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(3600,4200)); end;
gpl-3.0
fabianmurariu/FrameworkBenchmarks
frameworks/Lua/lapis/web.lua
72
5957
local lapis = require("lapis") local db = require("lapis.db") local Model do local _obj_0 = require("lapis.db.model") Model = _obj_0.Model end local config do local _obj_0 = require("lapis.config") config = _obj_0.config end local insert do local _obj_0 = table insert = _obj_0.insert end local sort do local _obj_0 = table sort = _obj_0.sort end local min, random do local _obj_0 = math min, random = _obj_0.min, _obj_0.random end local Fortune do local _parent_0 = Model local _base_0 = { } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "Fortune", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end Fortune = _class_0 end local World do local _parent_0 = Model local _base_0 = { } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "World", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end World = _class_0 end local Benchmark do local _parent_0 = lapis.Application local _base_0 = { ["/"] = function(self) return { json = { message = "Hello, World!" } } end, ["/db"] = function(self) local w = World:find(random(1, 10000)) return { json = { id = w.id, randomNumber = w.randomnumber } } end, ["/queries"] = function(self) local num_queries = tonumber(self.params.queries) or 1 if num_queries < 2 then local w = World:find(random(1, 10000)) return { json = { { id = w.id, randomNumber = w.randomnumber } } } end local worlds = { } num_queries = min(500, num_queries) for i = 1, num_queries do local w = World:find(random(1, 10000)) insert(worlds, { id = w.id, randomNumber = w.randomnumber }) end return { json = worlds } end, ["/fortunes"] = function(self) self.fortunes = Fortune:select("") insert(self.fortunes, { id = 0, message = "Additional fortune added at request time." }) sort(self.fortunes, function(a, b) return a.message < b.message end) return { layout = false }, self:html(function() raw('<!DOCTYPE HTML>') return html(function() head(function() return title("Fortunes") end) return body(function() return element("table", function() tr(function() th(function() return text("id") end) return th(function() return text("message") end) end) local _list_0 = self.fortunes for _index_0 = 1, #_list_0 do local fortune = _list_0[_index_0] tr(function() td(function() return text(fortune.id) end) return td(function() return text(fortune.message) end) end) end end) end) end) end) end, ["/update"] = function(self) local num_queries = tonumber(self.params.queries) or 1 if num_queries == 0 then num_queries = 1 end local worlds = { } num_queries = min(500, num_queries) for i = 1, num_queries do local wid = random(1, 10000) local world = World:find(wid) world.randomnumber = random(1, 10000) world:update("randomnumber") insert(worlds, { id = world.id, randomNumber = world.randomnumber }) end if num_queries < 2 then return { json = { worlds[1] } } end return { json = worlds } end, ["/plaintext"] = function(self) return { content_type = "text/plain", layout = false }, "Hello, World!" end } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "Benchmark", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end Benchmark = _class_0 return _class_0 end
bsd-3-clause
RebootRevival/FFXI_Test
scripts/zones/Temple_of_Uggalepih/mobs/Manipulator.lua
17
2255
---------------------------------- -- Area: Temple of Uggalipeh -- NM: Manipulator -- Notes: Paths around the 2 staircases ----------------------------------- local path = { -17.930, -8.500, -93.215, -18.553, -7.713, -91.224, -20.226, -6.250, -89.091, -21.651, -5.005, -87.401, -23.137, -3.917, -85.818, -24.750, -2.650, -84.440, -26.487, -1.300, -83.362, -28.366, -0.068, -82.488, -30.361, 0.500, -81.880, -32.450, 0.500, -81.498, -34.553, 0.500, -81.367, -36.575, 0.500, -81.401, -38.601, 0.500, -81.632, -40.699, 0.500, -82.133, -43.542, -1.300, -83.312, -45.403, -2.650, -84.455, -47.108, -3.804, -85.804, -48.567, -4.900, -87.243, -49.894, -6.250, -88.891, -50.957, -7.518, -90.686, -51.714, -8.500, -92.696, -52.136, -8.500, -94.655, -52.358, -8.500, -96.757, -52.482, -8.500, -99.253, -52.530, -8.500, -102.142, -52.409, -8.500, -104.364, -51.995, -8.500, -106.498, -51.329, -7.998, -108.403, -50.419, -6.700, -110.216, -49.221, -5.514, -111.939, -47.741, -4.367, -113.588, -46.122, -3.100, -115.009, -44.418, -1.750, -116.181, -42.611, -0.797, -117.185, -40.653, 0.500, -117.857, -38.622, 0.500, -118.275, -36.614, 0.500, -118.518, -34.459, 0.500, -118.650, -32.303, 0.500, -118.591, -30.276, 0.500, -118.249, -28.199, -0.318, -117.605, -26.325, -1.300, -116.748, -24.522, -2.650, -115.637, -22.911, -3.550, -114.378, -21.430, -4.900, -112.942, -20.121, -6.250, -111.382, -18.967, -7.150, -109.509, -18.191, -8.500, -107.518, -17.743, -8.500, -105.495, -17.541, -8.500, -103.466, -17.497, -8.500, -101.427, -17.408, -8.500, -97.263, -17.573, -8.500, -95.179 }; function onMobSpawn(mob) onMobRoam(mob); -- what? end; function onPath(mob) pathfind.patrol(mob, path); end; function onMobRoam(mob) -- move to start position if not moving if (mob:isFollowingPath() == false) then mob:pathThrough(pathfind.first(path)); end end; function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) -- Set Manipulator's spawnpoint and respawn time mob:setRespawnTime(7200); -- 2 hours end;
gpl-3.0
olafhering/sysbench
src/lua/oltp_update_index.lua
2
1118
#!/usr/bin/env sysbench -- Copyright (C) 2006-2017 Alexey Kopytov <akopytov@gmail.com> -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -- ---------------------------------------------------------------------- -- Update-Index OLTP benchmark -- ---------------------------------------------------------------------- require("oltp_common") function prepare_statements() prepare_index_updates() end function event() execute_index_updates(con) end
gpl-2.0
ashang/koreader
spec/unit/readerui_spec.lua
5
1389
require("commonrequire") local DocumentRegistry = require("document/documentregistry") local ReaderUI = require("apps/reader/readerui") local DocSettings = require("docsettings") local UIManager = require("ui/uimanager") describe("Readerui module", function() local sample_epub = "spec/front/unit/data/leaves.epub" local readerui setup(function() readerui = ReaderUI:new{ document = DocumentRegistry:openDocument(sample_epub), } end) it("should save settings", function() -- remove history settings and sidecar settings DocSettings:open(sample_epub):clear() local doc_settings = DocSettings:open(sample_epub) assert.are.same(doc_settings.data, {}) readerui:saveSettings() assert.are_not.same(readerui.doc_settings.data, {}) doc_settings = DocSettings:open(sample_epub) assert.truthy(doc_settings.data.last_xpointer) assert.are.same(doc_settings.data.last_xpointer, readerui.doc_settings.data.last_xpointer) end) it("should show reader", function() UIManager:quit() UIManager:show(readerui) UIManager:scheduleIn(1, function() UIManager:close(readerui) end) UIManager:run() end) it("should close document", function() readerui:closeDocument() assert(readerui.document == nil) end) end)
agpl-3.0
mahdikord/mahdibary
plugins/img_google.lua
660
3196
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search image with Google API and sends it.", usage = "!img [term]: Random search an image with Google API.", patterns = { "^!img (.*)$" }, run = run } end
gpl-2.0
koppa/wireshark
test/lua/luatest.lua
35
4498
-- See Copyright Notice in the file LICENSE -- arrays: deep comparison local function eq (t1, t2, lut) if t1 == t2 then return true end if type(t1) ~= "table" or type(t2) ~= "table" or #t1 ~= #t2 then return false end lut = lut or {} -- look-up table: are these 2 arrays already compared? lut[t1] = lut[t1] or {} if lut[t1][t2] then return true end lut[t2] = lut[t2] or {} lut[t1][t2], lut[t2][t1] = true, true for k,v in ipairs (t1) do if not eq (t2[k], v, lut) then return false end -- recursion end return true end -- a "nil GUID", to be used instead of nils in datasets local NT = "b5f74fe5-46f4-483a-8321-e58ba2fa0e17" -- pack vararg in table, replacing nils with "NT" items local function packNT (...) local t = {} for i=1, select ("#", ...) do local v = select (i, ...) t[i] = (v == nil) and NT or v end return t end -- unpack table into vararg, replacing "NT" items with nils local function unpackNT (t) local len = #t local function unpack_from (i) local v = t[i] if v == NT then v = nil end if i == len then return v end return v, unpack_from (i+1) end if len > 0 then return unpack_from (1) end end -- print results (deep into arrays) local function print_results (val, indent, lut) indent = indent or "" lut = lut or {} -- look-up table local str = tostring (val) if type (val) == "table" then if lut[val] then io.write (indent, str, "\n") else lut[val] = true io.write (indent, str, "\n") for i,v in ipairs (val) do print_results (v, " " .. indent, lut) -- recursion end end else io.write (indent, val == NT and "nil" or str, "\n") end end -- returns: -- 1) true, if success; false, if failure -- 2) test results table or error_message local function test_function (test, func) local res local t = packNT (pcall (func, unpackNT (test[1]))) if t[1] then table.remove (t, 1) res = t if alien then local subject = test[1][1] local buf = alien.buffer (#subject) if #subject > 0 then alien.memmove (buf:topointer (), subject, #subject) end test[1][1] = buf local t = packNT (pcall (func, unpackNT (test[1]))) if t[1] then table.remove (t, 1) res = t else print "alien test failed" res = t[2] --> error_message end end else res = t[2] --> error_message end local how = (type (res) == type (test[2])) and (type (res) == "string" or eq (res, test[2])) -- allow error messages to differ return how, res end -- returns: -- 1) true, if success; false, if failure -- 2) test results table or error_message -- 3) test results table or error_message local function test_method (test, constructor, name) local res1, res2 local subject = test[2][1] local ok, r = pcall (constructor, unpackNT (test[1])) if ok then local t = packNT (pcall (r[name], r, unpackNT (test[2]))) if t[1] then table.remove (t, 1) res1, res2 = t else res1, res2 = 2, t[2] --> 2, error_message end else res1, res2 = 1, r --> 1, error_message end return eq (res1, test[3]), res1, res2 end -- returns: a list of failed tests local function test_set (set, lib, verbose) local list = {} if type (set.Func) == "function" then local func = set.Func for i,test in ipairs (set) do if verbose then io.write (" running function test "..i.."...") io.flush () end local ok, res = test_function (test, func) if not ok then if verbose then io.stdout:write("failed!\n") end table.insert (list, {i=i, test[2], res}) elseif verbose then io.write ("passed\n") io.flush () end end elseif type (set.Method) == "string" then for i,test in ipairs (set) do if verbose then io.write (" running method test "..i.."...") io.flush () end local ok, res1, res2 = test_method (test, lib.new, set.Method) if not ok then if verbose then io.stdout:write("failed!\n") end table.insert (list, {i=i, test[3], res1, res2}) elseif verbose then io.write ("passed\n") io.flush () end end else error ("neither set.Func nor set.Method is valid") end return list end return { eq = eq, NT = NT, print_results = print_results, test_function = test_function, test_method = test_method, test_set = test_set, }
gpl-2.0
babymannen/theforgottenserver-7.4
server/data/creaturescripts/scripts/login.lua
1
1312
-- Ordered as in creaturescripts.xml local events = { 'PlayerDeath', 'DropLoot' } function onLogin(player) local loginStr = "" local timeZone = "" if player:getLastLoginSaved() <= 0 then loginStr = "Welcome to " .. configManager.getString(configKeys.SERVER_NAME) .. "!" loginStr = loginStr .. " Please choose your outfit." player:sendOutfitWindow() else if loginStr ~= "" then player:sendTextMessage(MESSAGE_STATUS_DEFAULT, loginStr) end if os.date("%Z").isdst ~= nil then timeZone = "CET" else timeZone = "CEST" end loginStr = string.format("Your last visit in " .. configManager.getString(configKeys.SERVER_NAME) .. ": %s " .. timeZone .. ".", os.date("%d. %b %Y %X", player:getLastLoginSaved())) end player:sendTextMessage(MESSAGE_STATUS_DEFAULT, loginStr) -- Promotion local vocation = player:getVocation() local promotion = vocation:getPromotion() if player:isPremium() then local value = player:getStorageValue(STORAGEVALUE_PROMOTION) if not promotion and value ~= 1 then player:setStorageValue(STORAGEVALUE_PROMOTION, 1) elseif value == 1 then player:setVocation(promotion) end elseif not promotion then player:setVocation(vocation:getDemotion()) end -- Events for i = 1, #events do player:registerEvent(events[i]) end return true end
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Yhoator_Jungle/npcs/Ilieumort_RK.lua
3
3332
----------------------------------- -- Area: Yhoator Jungle -- NPC: Ilieumort, R.K. -- Outpost Conquest Guards -- !pos 200.254 -1 -80.324 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yhoator_Jungle/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ELSHIMOUPLANDS; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
openwrt-es/openwrt-luci
protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua
2
4048
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local username, password, ac, service local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true ac = section:taboption("general", Value, "ac", translate("Access Concentrator"), translate("Leave empty to autodetect")) ac.placeholder = translate("auto") service = section:taboption("general", Value, "service", translate("Service Name"), translate("Leave empty to autodetect")) service.placeholder = translate("auto") if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6", translate("Obtain IPv6-Address"), translate("Enable IPv6 negotiation on the PPP link")) ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:set(section, "keepalive", "0") end end keepalive_interval.remove = keepalive_interval.write keepalive_failure.write = keepalive_interval.write keepalive_failure.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" host_uniq = section:taboption("advanced", Value, "host_uniq", translate("Host-Uniq tag content"), translate("Raw hex-encoded bytes. Leave empty unless your ISP require this")) host_uniq.placeholder = translate("auto") host_uniq.datatype = "hexstring" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
apache-2.0
RebootRevival/FFXI_Test
scripts/zones/Full_Moon_Fountain/npcs/Moon_Spiral.lua
8
1442
----------------------------------- -- Area: Full Moon Fountain -- NPC: Moon Spiral -- Involved in Quests: The Moonlit Path -- !pos -302 9 -260 170 ----------------------------------- package.loaded["scripts/zones/Full_Moon_Fountain/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Full_Moon_Fountain/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) printf("onUpdate CSID: %u",csid); printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) printf("onFinish CSID: %u",csid); printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
dannybloe/domoticz
scripts/dzVents/examples/simple room heating with hysteresis control.lua
19
3118
-- assumptions: -- the setpoint is set by a selector dummy device where the values are numeric temperatures -- but you can easily change it to a setpoint device local BOILER_DEVICE = 'Boiler' -- switch device local SETPOINT_DEVICE = 'Setpoint' -- selector dummy device local TEMPERATURE_SENSOR = 'Temperature' local HYSTERESIS = 0.5 -- temp has to drop this value below setpoint before boiler is on again local SMOOTH_FACTOR = 3 local LOGGING = true return { on = { ['timer'] = { 'every minute', }, devices = { TEMPERATURE_SENSOR, SETPOINT_DEVICE } }, data = { temperatureReadings = { history = true, maxItems = SMOOTH_FACTOR } }, active = true, execute = function(domoticz, item) local avgTemp local temperatureReadings = domoticz.data.temperatureReadings local sensor = domoticz.devices(TEMPERATURE_SENSOR) local current = sensor.temperature local boiler = domoticz.devices(BOILER_DEVICE) local setpoint = domoticz.devices(SETPOINT_DEVICE) -- first check if the sensor got a new reading or the setpoint was changed: if (item.isDevice) then if (sensor.changed) then -- sensor just reported a new reading -- add it to the readings table if (current ~= 0 and current ~= nil) then temperatureReadings.add(current) else -- no need to be here, weird state detected domoticz.log('Strange sensor reading.. skiping', domoticz.LOG_ERROR) return end elseif (domoticz.devices(SETPOINT_DEVICE).changed) then -- a new setpoint was set if LOGGING then domoticz.log('Setpoint was set to ' .. item.state) end else -- no business here, bail out... return end end -- now determine what to do if (setpoint.state == nil or setpoint.state == 'Off') then boiler.switchOff() return -- we're done here end local setpointValue = tonumber(setpoint.state) -- determine at which temperature the boiler should be -- switched on local switchOnTemp = setpointValue - HYSTERESIS -- don't use the current reading but average it out over -- the past <SMOOTH_FACTOR> readings (data smoothing) to get rid of noise, wrong readings etc local avgTemp = temperatureReadings.avg(1, SMOOTH_FACTOR, current) -- fallback to current when history is empty if LOGGING then domoticz.log('Average: ' .. avgTemp, domoticz.LOG_INFO) domoticz.log('Setpoint: ' .. setpointValue, domoticz.LOG_INFO) domoticz.log('Current boiler state: ' .. boiler.state, domoticz.LOG_INFO) domoticz.log('Switch-on temperature: ' .. switchOnTemp, domoticz.LOG_INFO) end if (avgTemp >= setpointValue and boiler.state == 'On') then if LOGGING then domoticz.log('Target temperature reached, boiler off') end boiler.switchOff() end if (avgTemp < setpointValue and boiler.state == 'Off') then if (avgTemp < switchOnTemp) then if LOGGING then domoticz.log('Heating is required, boiler switched on') end boiler.switchOn() else if LOGGING then domoticz.log('Average temperature below setpoint but within hysteresis range, waiting for temperature to drop to ' .. switchOnTemp) end end end end }
gpl-3.0
AmirPGA/pgahide
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
hfjgjfg/jjjn
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Windurst_Waters_[S]/npcs/Rakih_Lyhall.lua
3
1062
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Rakih Lyhall -- Type: Standard NPC -- @zone 94 -- !pos -48.111 -4.5 69.712 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01ad); 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/Windurst_Waters_[S]/npcs/Gevarg.lua
3
1065
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Gevarg -- Type: Past Event Watcher -- @zone 94 -- !pos -46.448 -6.312 212.384 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0000); 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
openwrt-es/openwrt-luci
applications/luci-app-dynapoint/luasrc/model/cbi/dynapoint.lua
17
3590
local uci = require "luci.model.uci".cursor() local a = require "luci.model.ipkg" local DISP = require "luci.dispatcher" local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end m = Map("dynapoint") m:chain("wireless") s = m:section(NamedSection, "internet", "rule", translate("Configuration"), translate("Check Internet connectivity via HTTP header download")) hosts = s:option(DynamicList, "hosts", translate("List of host addresses"), translate("List of host addresses (url or IP) to track and request http headers from")) hosts.datatype = "string" interval = s:option(Value, "interval", translate("Test-run interval"), translate("Time interval in seconds to re-start a new test run")) interval.datatype = "uinteger" interval.default = "30" offline_treshold = s:option(Value, "offline_threshold", translate("Switch_to_offline threshold"), translate("Failure counter after how many failed download attempts, the state is considered as offline")) offline_treshold.datatype = "uinteger" offline_treshold.default = "1" add_hostname_to_ssid = s:option(Flag, "add_hostname_to_ssid", translate("Append hostname to ssid"), translate("Append the router's hostname to the SSID when connectivity check fails")) add_hostname_to_ssid.rmempty = false if (a.installed("curl") == true) then use_curl = s:option(Flag, "use_curl", translate("Use curl"), translate("Use curl instead of wget for testing the connectivity.")) use_curl.rmempty = false curl_interface = s:option(Value, "curl_interface", translate("Used interface"), translate("Which interface should curl use. (Use ifconfig to find out)")) curl_interface.datatype = "string" curl_interface:depends("use_curl","1") curl_interface.placeholder = "eth0" else use_curl = s:option(Flag, "use_curl", translate("Use curl instead of wget"), translate("Curl is currently not installed. Please install the package in the") ..[[ <a href="]] .. DISP.build_url("admin", "system", "packages") .. "?display=available&query=curl"..[[">]] .. translate ("Software Section") .. [[</a>]] .. "." ) use_curl.rmempty = false use_curl.template = "dynapoint/cbi_checkbox" end m1 = Map("wireless", "DynaPoint", translate("Dynamic Access Point Manager")) aps = m1:section(TypedSection, "wifi-iface", translate("List of Wireless Virtual Interfaces (wVIF)")) aps.addremove = false aps.anonymous = true aps.template = "cbi/tblsection" status = aps:option(DummyValue, "disabled", translate("WiFi Status")) status.template = "dynapoint/cbi_color" function status.cfgvalue(self,section) local val = m1:get(section, "disabled") if val == "1" then return translate("Disabled") end if (val == nil or val == "0") then return translate("Enabled") end return val end device = aps:option(DummyValue, "device", translate("Device")) function device.cfgvalue(self,section) local dev = m1:get(section, "device") local val = m1:get(dev, "hwmode") if val == "11a" then return dev .. " (5 GHz)" else return dev .. " (2,4 GHz)" end return val end mode = aps:option(DummyValue, "mode", translate("Mode")) ssid = aps:option(DummyValue, "ssid", translate("SSID")) action = aps:option(ListValue, "dynapoint_rule", translate("Activate this wVIF if status is:")) action.widget="select" action:value("internet",translate("Online")) action:value("!internet",translate("Offline")) action:value("",translate("Not used by DynaPoint")) action.default = "" return m1,m
apache-2.0
RebootRevival/FFXI_Test
scripts/zones/Abyssea-Konschtat/npcs/qm11.lua
3
1344
----------------------------------- -- Zone: Abyssea-Konschtat -- NPC: qm11 (???) -- Spawns Arimaspi -- !pos ? ? ? 15 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2913,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(16838993) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(16838993):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2913); -- Inform payer what items they need. 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/Eastern_Altepa_Desert/npcs/qm.lua
3
1624
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: ??? -- Involved In Quest: A Craftsman's Work -- !pos 113 -7.972 -72 114 ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Decurio_I_IIIKilled = player:getVar("Decurio_I_IIIKilled"); if (player:getVar("aCraftsmanWork") == 1 and Decurio_I_IIIKilled == 0) then SpawnMob(17244523,300):updateClaim(player); elseif (Decurio_I_IIIKilled == 1) then player:addKeyItem(ALTEPA_POLISHING_STONE); player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_POLISHING_STONE); player:setVar("aCraftsmanWork",2); player:setVar("Decurio_I_IIIKilled",0); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
openwrt-es/openwrt-luci
applications/luci-app-travelmate/luasrc/model/cbi/travelmate/overview_tab.lua
1
5035
-- Copyright 2017-2019 Dirk Brenken (dev@brenken.org) -- This is free software, licensed under the Apache License, Version 2.0 local fs = require("nixio.fs") local uci = require("luci.model.uci").cursor() local util = require("luci.util") local nw = require("luci.model.network").init() local fw = require("luci.model.firewall").init() local dump = util.ubus("network.interface", "dump", {}) local trmiface = uci:get("travelmate", "global", "trm_iface") or "trm_wwan" local uplink = uci:get("network", trmiface) or "" m = Map("travelmate", translate("Travelmate"), translate("Configuration of the travelmate package to to enable travel router functionality. ") .. translatef("For further information " .. "<a href=\"%s\" target=\"_blank\">" .. "see online documentation</a>", "https://github.com/openwrt/packages/blob/master/net/travelmate/files/README.md")) m:chain("network") m:chain("firewall") -- Interface Wizard if uplink == "" then ds = m:section(NamedSection, "global", "travelmate", translate("Interface Wizard")) o = ds:option(Value, "trm_iface", translate("Create Uplink interface"), translate("Create a new wireless wan uplink interface, configure it to use dhcp and ") .. translate("add it to the wan zone of the firewall. ") .. translate("This step has only to be done once.")) o.datatype = "and(uciname,rangelength(3,15))" o.default = trmiface o.rmempty = false function o.validate(self, value) if value then local nwnet = nw:get_network(value) local zone = fw:get_zone("wan") local fwnet = fw:get_zone_by_network(value) if not nwnet then nwnet = nw:add_network(value, { proto = "dhcp" }) end if zone and not fwnet then fwnet = zone:add_network(value) end end return value end return m end -- Main travelmate options s = m:section(NamedSection, "global", "travelmate") o1 = s:option(Flag, "trm_enabled", translate("Enable Travelmate")) o1.default = o1.disabled o1.rmempty = false o2 = s:option(Flag, "trm_captive", translate("Captive Portal Detection"), translate("Check the internet availability, log captive portal redirections and keep the uplink connection 'alive'.")) o2.default = o2.enabled o2.rmempty = false o3 = s:option(Flag, "trm_netcheck", translate("Net Error Check"), translate("Treat missing internet availability as an error.")) o3:depends("trm_captive", 1) o3.default = o3.disabled o3.rmempty = false o4 = s:option(Flag, "trm_proactive", translate("ProActive Uplink Switch"), translate("Proactively scan and switch to a higher prioritized uplink, despite of an already existing connection.")) o4.default = o4.enabled o4.rmempty = false o5 = s:option(ListValue, "trm_iface", translate("Uplink / Trigger interface"), translate("Name of the used uplink interface.")) if dump then local i, v for i, v in ipairs(dump.interface) do if v.interface ~= "loopback" and v.interface ~= "lan" then local device = v.l3_device or v.device or "-" o5:value(v.interface, v.interface.. " (" ..device.. ")") end end end o5.default = trmiface o5.rmempty = false -- Runtime information ds = s:option(DummyValue, "_dummy") ds.template = "travelmate/runtime" -- Extra options e = m:section(NamedSection, "global", "travelmate", translate("Extra Options"), translate("Options for further tweaking in case the defaults are not suitable for you.")) e1 = e:option(Flag, "trm_debug", translate("Enable Verbose Debug Logging")) e1.default = e1.disabled e1.rmempty = false e2 = e:option(Value, "trm_radio", translate("Radio Selection / Order"), translate("Restrict travelmate to a single radio (e.g. 'radio1') or change the overall scanning order (e.g. 'radio1 radio2 radio0').")) e2.rmempty = true e3 = e:option(Value, "trm_listexpiry", translate("List Auto Expiry"), translate("Automatically resets the 'Faulty Stations' list after n minutes. Default is '0' which means no expiry.")) e3.datatype = "range(0,300)" e3.default = 0 e3.rmempty = false e4 = e:option(Value, "trm_triggerdelay", translate("Trigger Delay"), translate("Additional trigger delay in seconds before travelmate processing begins.")) e4.datatype = "range(1,60)" e4.default = 2 e4.rmempty = false e5 = e:option(Value, "trm_maxretry", translate("Connection Limit"), translate("Retry limit to connect to an uplink.")) e5.default = 5 e5.datatype = "range(1,10)" e5.rmempty = false e6 = e:option(Value, "trm_minquality", translate("Signal Quality Threshold"), translate("Minimum signal quality threshold as percent for conditional uplink (dis-) connections.")) e6.default = 35 e6.datatype = "range(20,80)" e6.rmempty = false e7 = e:option(Value, "trm_maxwait", translate("Interface Timeout"), translate("How long should travelmate wait for a successful wlan uplink connection.")) e7.default = 30 e7.datatype = "range(20,40)" e7.rmempty = false e8 = e:option(Value, "trm_timeout", translate("Overall Timeout"), translate("Overall retry timeout in seconds.")) e8.default = 60 e8.datatype = "range(30,300)" e8.rmempty = false return m
apache-2.0
djianq/Game
lualib/mqueue.lua
115
1798
-- This is a deprecated module, use skynet.queue instead. local skynet = require "skynet" local c = require "skynet.core" local mqueue = {} local init_once local thread_id local message_queue = {} skynet.register_protocol { name = "queue", -- please read skynet.h for magic number 8 id = 8, pack = skynet.pack, unpack = skynet.unpack, dispatch = function(session, from, ...) table.insert(message_queue, {session = session, addr = from, ... }) if thread_id then skynet.wakeup(thread_id) thread_id = nil end end } local function do_func(f, msg) return pcall(f, table.unpack(msg)) end local function message_dispatch(f) while true do if #message_queue==0 then thread_id = coroutine.running() skynet.wait() else local msg = table.remove(message_queue,1) local session = msg.session if session == 0 then local ok, msg = do_func(f, msg) if ok then if msg then skynet.fork(message_dispatch,f) error(string.format("[:%x] send a message to [:%x] return something", msg.addr, skynet.self())) end else skynet.fork(message_dispatch,f) error(string.format("[:%x] send a message to [:%x] throw an error : %s", msg.addr, skynet.self(),msg)) end else local data, size = skynet.pack(do_func(f,msg)) -- 1 means response c.send(msg.addr, 1, session, data, size) end end end end function mqueue.register(f) assert(init_once == nil) init_once = true skynet.fork(message_dispatch,f) end local function catch(succ, ...) if succ then return ... else error(...) end end function mqueue.call(addr, ...) return catch(skynet.call(addr, "queue", ...)) end function mqueue.send(addr, ...) return skynet.send(addr, "queue", ...) end function mqueue.size() return #message_queue end return mqueue
mit
jthomasbarry/aafmt
archive/book_chapters_LaTeX_original/pgf_3.0.1.tds/tex/generic/pgf/graphdrawing/lua/pgf/gd/control/FineTune.lua
3
4290
-- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/control/FineTune.lua,v 1.3 2013/05/23 20:01:25 tantau Exp $ local declare = require "pgf.gd.interface.InterfaceToAlgorithms".declare local Coordinate = require "pgf.gd.model.Coordinate" local lib = require "pgf.gd.lib" --- -- @section subsection {Fine-Tuning Positions of Nodes} -- -- @end --- declare { key = "nudge", type = "canvas coordinate", summary = [[" This option allows you to slightly ``nudge'' (move) nodes after they have been positioned by the given offset. The idea is that this nudging is done after the position of the node has been computed, so nudging has no influence on the actual graph drawing algorithms. This, in turn, means that you can use nudging to ``correct'' or ``optimize'' the positioning of nodes after the algorithm has computed something. "]], examples = [[" \tikz \graph [edges=rounded corners, nodes=draw, layered layout, sibling distance=0] { a -- {b, c, d[nudge=(up:2mm)]} -- e -- a; }; "]] } --- -- @param distance A distance by which the node is nudges. declare { key = "nudge up", type = "length", use = { { key = "nudge", value = function (v) return Coordinate.new(0,v) end } }, summary = "A shorthand for nudging a node upwards.", examples = [[" \tikz \graph [edges=rounded corners, nodes=draw, layered layout, sibling distance=0] { a -- {b, c, d[nudge up=2mm]} -- e -- a; }; "]] } --- -- @param distance A distance by which the node is nudges. declare { key = "nudge down", type = "length", use = { { key = "nudge", value = function (v) return Coordinate.new(0,-v) end } }, summary = "Like |nudge up|, but downwards." } --- -- @param distance A distance by which the node is nudges. declare { key = "nudge left", type = "length", use = { { key = "nudge", value = function (v) return Coordinate.new(-v,0) end } }, summary = "Like |nudge up|, but left.", examples = [[" \tikz \graph [edges=rounded corners, nodes=draw, layered layout, sibling distance=0] { a -- {b, c, d[nudge left=2mm]} -- e -- a; }; "]] } --- -- @param distance A distance by which the node is nudges. declare { key = "nudge right", type = "length", use = { { key = "nudge", value = function (v) return Coordinate.new(v,0) end } }, summary = "Like |nudge left|, but right." } --- declare { key = "regardless at", type = "canvas coordinate", summary = [[" Using this option you can provide a position for a node to wish it will be forced after the graph algorithms have run. So, the node is positioned normally and the graph drawing algorithm does not know about the position specified using |regardless at|. However, afterwards, the node is placed there, regardless of what the algorithm has computed (all other nodes are unaffected). "]], examples = [[" \tikz \graph [edges=rounded corners, nodes=draw, layered layout, sibling distance=0] { a -- {b,c,d[regardless at={(1,0)}]} -- e -- a; }; "]] } --- -- @param pos A canvas position (a coordinate). declare { key = "nail at", type = "canvas coordinate", use = { { key = "desired at", value = lib.id }, { key = "regardless at", value = lib.id }, }, summary = [[" This option combines |desired at| and |regardless at|. Thus, the algorithm is ``told'' about the desired position. If it fails to place the node at the desired position, it will be put there regardless. The name of the key is intended to remind one of a node being ``nailed'' to the canvas. "]], examples = [[" \tikz \graph [edges=rounded corners, nodes=draw, layered layout, sibling distance=0] { a -- {b,c,d[nail at={(1,0)}]} -- e[nail at={(1.5,-1)}] -- a; }; "]] }
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/Norg/npcs/Keal.lua
10
4278
----------------------------------- -- Area: Norg -- NPC: Keal -- Starts and Ends Quest: It's Not Your Vault ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); local path = { -5.453587, 0.151494, -16.361458, -5.997250, 0.229052, -15.475480, -6.582538, 0.317294, -14.524694, -7.573528, 0.365118, -12.941586, -7.069273, 0.384884, -13.867216, -6.565747, 0.311785, -14.741985, -5.676943, 0.173223, -16.241194, -5.162223, 0.020922, -17.108603, -4.725273, -0.022554, -18.175083, -4.882753, -0.041670, -19.252790, -5.294413, 0.020847, -20.336269, -5.632565, 0.112649, -21.417961, -5.905818, 0.202903, -22.541668, -5.657803, 0.116744, -21.445057, -5.273734, 0.023316, -20.410303, -4.831870, -0.049031, -19.478870, -4.749702, -0.024804, -18.311924, -5.152854, 0.002354, -17.248878, -5.639069, 0.185855, -16.335281, -6.158780, 0.247668, -15.445805, -7.253261, 0.405026, -13.567613, -7.803670, 0.348802, -12.626184, -8.375298, 0.223101, -11.645775, -8.895057, 0.076541, -10.770375, -9.384287, 0.015579, -9.884774, -9.939011, 0.143451, -8.935238, -9.422630, -0.025280, -9.816562, -8.589481, 0.151451, -11.248314, -8.095008, 0.275576, -12.123538, -7.561854, 0.373715, -13.045633, -5.644930, 0.185392, -16.292952, -5.058481, -0.014674, -17.285294, -4.724863, -0.024709, -18.265087, -4.923457, -0.042915, -19.378429, -5.293544, 0.020505, -20.338196, -5.606711, 0.104830, -21.323364, -5.849701, 0.183865, -22.302536, -5.586438, 0.097169, -21.222555, -5.214560, 0.046522, -20.280220, -4.779529, -0.048305, -19.351633, -4.757209, -0.021693, -18.194023, -5.138152, -0.000450, -17.254173, -5.685457, 0.173866, -16.248564, -6.275849, 0.266052, -15.243981, -7.196375, 0.403362, -13.666089, -7.766060, 0.352119, -12.689950, -8.280642, 0.241637, -11.799251, -8.828505, 0.098458, -10.895535, -9.351592, 0.039748, -9.948843, -9.856394, 0.036026, -9.068656 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); -- onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Vault = player:getQuestStatus(OUTLANDS,ITS_NOT_YOUR_VAULT); mLvl = player:getMainLvl(); IronBox = player:hasKeyItem(SEALED_IRON_BOX); if (Vault == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3 and mLvl >= 5) then player:startEvent(0x0024,SEALED_IRON_BOX); -- Start quest elseif (Vault == QUEST_ACCEPTED) then if (IronBox == true) then player:startEvent(0x0026); -- Finish quest else player:startEvent(0x0025,MAP_OF_THE_SEA_SERPENT_GROTTO); -- Reminder/Directions Dialogue end elseif (Vault == QUEST_COMPLETED) then player:startEvent(0x0027); -- New Standard Dialogue for everyone who has completed the quest else player:startEvent(0x0059); -- Standard Conversation end npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0024 and option == 1) then player:addQuest(OUTLANDS,ITS_NOT_YOUR_VAULT); elseif (csid == 0x0026) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4961); else player:delKeyItem(SEALED_IRON_BOX); player:addItem(4961); -- Scroll of Tonko: Ichi player:messageSpecial(ITEM_OBTAINED, 4961); player:addFame(NORG,50); player:completeQuest(OUTLANDS,ITS_NOT_YOUR_VAULT); end end npc:wait(0); end;
gpl-3.0
majidhp888/Hack
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
RebootRevival/FFXI_Test
scripts/globals/mobskills/equalizer.lua
35
1146
--------------------------------------------------- -- Equalizer -- AoE damage (~600-800), -- --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) -- skillList 54 = Omega -- skillList 727 = Proto-Omega -- skillList 728 = Ultima -- skillList 729 = Proto-Ultima local skillList = mob:getMobMod(MOBMOD_SKILL_LIST); local mobhp = mob:getHPP(); local phase = mob:getLocalVar("battlePhase"); if ((skillList == 729 and phase >= 2 and phase <= 3) or (mobhp < 40 and mobhp > 20 and skillList == 728)) then return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) local numhits = 2; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/East_Ronfaure_[S]/npcs/Logging_Point.lua
17
1097
----------------------------------- -- Area: East Ronfaure [S] -- NPC: Logging Point ----------------------------------- package.loaded["scripts/zones/East_Ronfaure_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/logging"); require("scripts/zones/East_Ronfaure_[S]/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startLogging(player,player:getZoneID(),npc,trade,0x0385); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); 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
mzguanglin/LuCI
contrib/luadoc/lua/luadoc/taglet/standard/tags.lua
93
5221
------------------------------------------------------------------------------- -- Handlers for several tags -- @release $Id: tags.lua,v 1.8 2007/09/05 12:39:09 tomas Exp $ ------------------------------------------------------------------------------- local luadoc = require "luadoc" local util = require "luadoc.util" local string = require "string" local table = require "table" local assert, type, tostring = assert, type, tostring module "luadoc.taglet.standard.tags" ------------------------------------------------------------------------------- local function author (tag, block, text) block[tag] = block[tag] or {} if not text then luadoc.logger:warn("author `name' not defined [["..text.."]]: skipping") return end table.insert (block[tag], text) end ------------------------------------------------------------------------------- -- Set the class of a comment block. Classes can be "module", "function", -- "table". The first two classes are automatic, extracted from the source code local function class (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function cstyle (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function copyright (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function description (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function field (tag, block, text) if block["class"] ~= "table" then luadoc.logger:warn("documenting `field' for block that is not a `table'") end block[tag] = block[tag] or {} local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") assert(name, "field name not defined") table.insert(block[tag], name) block[tag][name] = desc end ------------------------------------------------------------------------------- -- Set the name of the comment block. If the block already has a name, issue -- an error and do not change the previous value local function name (tag, block, text) if block[tag] and block[tag] ~= text then luadoc.logger:error(string.format("block name conflict: `%s' -> `%s'", block[tag], text)) end block[tag] = text end ------------------------------------------------------------------------------- -- Processes a parameter documentation. -- @param tag String with the name of the tag (it must be "param" always). -- @param block Table with previous information about the block. -- @param text String with the current line beeing processed. local function param (tag, block, text) block[tag] = block[tag] or {} -- TODO: make this pattern more flexible, accepting empty descriptions local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") if not name then luadoc.logger:warn("parameter `name' not defined [["..text.."]]: skipping") return end local i = table.foreachi(block[tag], function (i, v) if v == name then return i end end) if i == nil then luadoc.logger:warn(string.format("documenting undefined parameter `%s'", name)) table.insert(block[tag], name) end block[tag][name] = desc end ------------------------------------------------------------------------------- local function release (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function ret (tag, block, text) tag = "ret" if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- -- @see ret local function see (tag, block, text) -- see is always an array block[tag] = block[tag] or {} -- remove trailing "." text = string.gsub(text, "(.*)%.$", "%1") local s = util.split("%s*,%s*", text) table.foreachi(s, function (_, v) table.insert(block[tag], v) end) end ------------------------------------------------------------------------------- -- @see ret local function usage (tag, block, text) if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- local handlers = {} handlers["author"] = author handlers["class"] = class handlers["cstyle"] = cstyle handlers["copyright"] = copyright handlers["description"] = description handlers["field"] = field handlers["name"] = name handlers["param"] = param handlers["release"] = release handlers["return"] = ret handlers["see"] = see handlers["usage"] = usage ------------------------------------------------------------------------------- function handle (tag, block, text) if not handlers[tag] then luadoc.logger:error(string.format("undefined handler for tag `%s'", tag)) return end -- assert(handlers[tag], string.format("undefined handler for tag `%s'", tag)) return handlers[tag](tag, block, text) end
apache-2.0
petoju/awesome
tests/examples/wibox/layout/manual/add_at.lua
6
1140
--DOC_GEN_IMAGE --DOC_HIDE local generic_widget = ... --DOC_HIDE local wibox = require("wibox") --DOC_HIDE local awful = {placement = require("awful.placement")} --DOC_HIDE local l = wibox.layout { layout = wibox.layout.manual } -- -- Option 1: Set the point directly in the widget local w1 = generic_widget() w1.point = {x=75, y=5} w1.text = "first" w1.forced_width = 50 l:add(w1) -- -- Option 2: Set the point directly in the widget as a function local w2 = generic_widget() w2.text = "second" w2.point = function(geo, args) return { x = args.parent.width - geo.width, y = 0 } end l:add(w2) -- -- Option 3: Set the point directly in the widget as an `awful.placement` -- function. local w3 = generic_widget() w3.text = "third" w3.point = awful.placement.bottom_right l:add(w3) -- -- Option 4: Use `:add_at` instead of using the `.point` property. This works -- with all 3 ways to define the point. -- function. local w4 = generic_widget() w4.text = "fourth" l:add_at(w4, awful.placement.centered + awful.placement.maximize_horizontally) return l, 200, 100 --DOC_HIDE
gpl-2.0
rafradek/wire
lua/entities/gmod_wire_lever.lua
10
3441
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Analog Lever" ENT.WireDebugName = "Lever" if CLIENT then return end -- No more client function ENT:Initialize() self:SetModel("models/props_wasteland/tram_lever01.mdl") self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self.EntToOutput = NULL self.Ang = 0 self.Value = 0 self:Setup(0, 1) self.Inputs = WireLib.CreateInputs(self, {"SetValue", "Min", "Max"}) self.Outputs = WireLib.CreateOutputs(self, {"Value", "Entity [ENTITY]"}) end function ENT:Setup(min, max) if min then self.Min = min end if max then self.Max = max end end function ENT:TriggerInput(iname, value) if iname == "SetValue" then self.Ang = (math.Clamp(value, self.Min, self.Max) - self.Min)/(self.Max - self.Min) * 90 - 45 elseif (iname == "Min") then self.Min = value elseif (iname == "Max") then self.Max = value end end function ENT:Use( ply ) if not IsValid(ply) or not ply:IsPlayer() or IsValid(self.User) then return end self.User = ply WireLib.TriggerOutput( self, "Entity", ply) end function ENT:Think() self.BaseClass.Think(self) if not IsValid(self.BaseEnt) then return end if IsValid(self.User) then local dist = self.User:GetShootPos():Distance(self:GetPos()) if dist < 160 and (self.User:KeyDown(IN_USE) or self.User:KeyDown(IN_ATTACK)) then local TargPos = self.User:GetShootPos() + self.User:GetAimVector() * dist local distMax = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetForward() * 30) local distMin = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetForward() * -30) local FPos = (distMax - distMin) * 0.5 distMax = TargPos:Distance(self.BaseEnt:GetPos()) distMin = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetUp() * 40) local HPos = 20 - ((distMin - distMax) * 0.5) self.Ang = math.Clamp( math.deg( math.atan2( HPos, FPos ) ) - 90, -45, 45 ) else self.User = NULL WireLib.TriggerOutput( self, "Entity", NULL) end end self.Value = Lerp((self.Ang + 45) / 90, self.Min, self.Max) Wire_TriggerOutput(self, "Value", self.Value) local NAng = self.BaseEnt:GetAngles() NAng:RotateAroundAxis( NAng:Right(), -self.Ang ) local RAng = self.BaseEnt:WorldToLocalAngles(NAng) self:SetLocalPos( RAng:Up() * 21 ) self:SetLocalAngles( RAng ) self:ShowOutput() self:NextThink(CurTime()) return true end function ENT:ShowOutput() self:SetOverlayText(string.format("(%.2f - %.2f) = %.2f", self.Min, self.Max, self.Value)) end function ENT:OnRemove( ) if IsValid(self.BaseEnt) then self.BaseEnt:Remove() self.BaseEnt = nil end end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if IsValid(self.BaseEnt) then info.baseent = self.BaseEnt:EntIndex() constraint.Weld(self, self.BaseEnt, 0, 0, 0, true) -- Just in case the weld has been broken somehow, remake to ensure inclusion in dupe end info.value = self.Value return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) if info.baseent then self.BaseEnt = GetEntByID(info.baseent) end if info.value then self.Value = info.value self:TriggerInput("SetValue", self.Value) end end duplicator.RegisterEntityClass("gmod_wire_lever", WireLib.MakeWireEnt, "Data", "Min", "Max" )
apache-2.0
RebootRevival/FFXI_Test
scripts/zones/Monarch_Linn/bcnms/ancient_vows.lua
17
1926
----------------------------------- -- Area: Monarch Linn -- Name: Ancient Vows ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/missions"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- printf("leavecode: %u",leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) if (csid == 0x7d01) then player:addExp(1000); player:addTitle(TAVNAZIAN_TRAVELER); if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then player:setVar("VowsDone",1); player:setVar("PromathiaStatus",0); player:completeMission(COP,ANCIENT_VOWS); player:addMission(COP,THE_CALL_OF_THE_WYRMKING); player:setPos(694,-5.5,-619,74,107); -- To South Gustaberg end end end;
gpl-3.0
onpon4/naev
dat/missions/flf/flf_pirates.lua
1
8259
--[[ <?xml version='1.0' encoding='utf8'?> <mission name="FLF Pirate Disturbance"> <avail> <priority>33</priority> <chance>330</chance> <done>Alliance of Inconvenience</done> <location>Computer</location> <faction>FLF</faction> <faction>Frontier</faction> <cond>not diff.isApplied( "flf_dead" )</cond> </avail> </mission> --]] --[[ FLF pirate elimination mission. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] require "numstring" local fleet = require "fleet" require "missions/flf/flf_common" misn_title = {} misn_title[1] = _("FLF: Lone Pirate Disturbance in %s") misn_title[2] = _("FLF: Minor Pirate Disturbance in %s") misn_title[3] = _("FLF: Moderate Pirate Disturbance in %s") misn_title[4] = _("FLF: Substantial Pirate Disturbance in %s") misn_title[5] = _("FLF: Dangerous Pirate Disturbance in %s") misn_title[6] = _("FLF: Highly Dangerous Pirate Disturbance in %s") pay_text = {} pay_text[1] = _("The official mumbles something about the pirates being irritating as a credit chip is pressed into your hand.") pay_text[2] = _("While polite, something seems off about the smile plastered on the official who hands you your pay.") pay_text[3] = _("The official thanks you dryly for your service and hands you a credit chip.") pay_text[4] = _("The official takes an inordinate amount of time to do so, but eventually hands you your pay as promised.") flfcomm = {} flfcomm[1] = _("Alright, let's have at them!") flfcomm[2] = _("Sorry we're late! Did we miss anything?") osd_title = _("Pirate Disturbance") osd_desc = {} osd_desc[1] = _("Fly to the %s system") osd_desc[2] = _("Eliminate the pirates") osd_desc[3] = _("Return to FLF base") osd_desc["__save"] = true function setDescription () local desc desc = gettext.ngettext( "There is %d pirate ship disturbing FLF operations in the %s system. Eliminate this ship.", "There is a pirate group with %d ships disturbing FLF operations in the %s system. Eliminate this group.", ships ):format( ships, missys:name() ) if has_phalanx then desc = desc .. _(" There is a Phalanx among them, so you must proceed with caution.") end if has_kestrel then desc = desc .. _(" There is a Kestrel among them, so you must be very careful.") end if flfships > 0 then desc = desc .. gettext.ngettext( " You will be accompanied by %d other FLF pilot for this mission.", " You will be accompanied by %d other FLF pilots for this mission.", flfships ):format( flfships ) end return desc end function create () missys = flf_getPirateSystem() if not misn.claim( missys ) then misn.finish( false ) end level = rnd.rnd( 1, #misn_title ) ships = 0 has_boss = false has_phalanx = false has_kestrel = false flfships = 0 reputation = 0 if level == 1 then ships = 1 elseif level == 2 then ships = rnd.rnd( 2, 3 ) reputation = 1 elseif level == 3 then ships = 5 flfships = rnd.rnd( 0, 2 ) reputation = 2 elseif level == 4 then ships = 6 has_boss = true flfships = rnd.rnd( 4, 6 ) reputation = 5 elseif level == 5 then ships = 6 has_phalanx = true flfships = rnd.rnd( 4, 6 ) reputation = 10 elseif level == 6 then ships = rnd.rnd( 6, 9 ) has_kestrel = true flfships = rnd.rnd( 8, 10 ) reputation = 20 end credits = ships * 190000 - flfships * 1000 if has_phalanx then credits = credits + 310000 end if has_kestrel then credits = credits + 810000 end credits = credits + rnd.sigma() * 8000 local desc = setDescription() late_arrival = rnd.rnd() < 0.05 late_arrival_delay = rnd.rnd( 10.0, 120.0 ) -- Set mission details misn.setTitle( misn_title[level]:format( missys:name() ) ) misn.setDesc( desc ) misn.setReward( creditstring( credits ) ) marker = misn.markerAdd( missys, "computer" ) end function accept () misn.accept() osd_desc[1] = osd_desc[1]:format( missys:name() ) misn.osdCreate( osd_title, osd_desc ) pirate_ships_left = 0 job_done = false last_system = planet.cur() hook.enter( "enter" ) hook.jumpout( "leave" ) hook.land( "leave" ) end function enter () if not job_done then if system.cur() == missys then misn.osdActive( 2 ) local boss if has_kestrel then boss = "Pirate Kestrel" elseif has_phalanx then boss = "Pirate Phalanx" elseif has_boss then local choices = { "Pirate Admonisher", "Pirate Rhino" } boss = choices[ rnd.rnd( 1, #choices ) ] end patrol_spawnPirates( ships, boss ) if flfships > 0 then if not late_arrival then patrol_spawnFLF( flfships, last_system, flfcomm[1] ) else hook.timer( late_arrival_delay, "timer_lateFLF" ) end end else misn.osdActive( 1 ) end end end function leave () if spawner ~= nil then hook.rm( spawner ) end pirate_ships_left = 0 last_system = system.cur() end function timer_lateFLF () local systems = system.cur():adjacentSystems() local source = systems[ rnd.rnd( 1, #systems ) ] patrol_spawnFLF( flfships, source, flfcomm[2] ) end function pilot_death_pirate () pirate_ships_left = pirate_ships_left - 1 if pirate_ships_left <= 0 then job_done = true misn.osdActive( 3 ) misn.markerRm( marker ) hook.land( "land_flf" ) pilot.toggleSpawn( true ) if fleetFLF ~= nil then for i, j in ipairs( fleetFLF ) do if j:exists() then j:changeAI( "flf" ) end end end end end function land_flf () leave() last_system = planet.cur() if planet.cur():faction() == faction.get("FLF") then tk.msg( "", pay_text[ rnd.rnd( 1, #pay_text ) ] ) player.pay( credits ) faction.get("FLF"):modPlayerSingle( reputation ) misn.finish( true ) end end -- Spawn a pirate patrol with n ships. function patrol_spawnPirates( n, boss ) pilot.clear() pilot.toggleSpawn( false ) player.pilot():setVisible( true ) if rnd.rnd() < 0.05 then n = n + 1 end local r = system.cur():radius() fleetPirate = {} for i = 1, n do local x = rnd.rnd( -r, r ) local y = rnd.rnd( -r, r ) local shipname if i == 1 and boss ~= nil then shipname = boss else local shipnames = { "Pirate Hyena", "Pirate Shark", "Pirate Vendetta", "Pirate Ancestor" } shipname = shipnames[ rnd.rnd( 1, #shipnames ) ] end local pstk = pilot.addFleet( shipname, vec2.new( x, y ), {ai="baddie_norun"} ) local p = pstk[1] hook.pilot( p, "death", "pilot_death_pirate" ) p:setFaction( "Rogue Pirate" ) p:setHostile() p:setVisible( true ) p:setHilight( true ) fleetPirate[i] = p pirate_ships_left = pirate_ships_left + 1 end end -- Spawn n FLF ships at/from the location param. function patrol_spawnFLF( n, param, comm ) if rnd.rnd() < 0.05 then n = n - 1 end local lancelots = rnd.rnd( n ) fleetFLF = fleet.add( lancelots, "Lancelot", "FLF", param, _("FLF Lancelot"), {ai="flf_norun"} ) local vendetta_fleet = fleet.add( n - lancelots, "Vendetta", "FLF", param, _("FLF Vendetta"), {ai="flf_norun"} ) for i, j in ipairs( vendetta_fleet ) do fleetFLF[ #fleetFLF + 1 ] = j end for i, j in ipairs( fleetFLF ) do j:setFriendly() j:setVisible( true ) end fleetFLF[1]:comm( player.pilot(), comm ) end
gpl-3.0
petoju/awesome
tests/examples/awful/popup/position3.lua
6
1205
--DOC_GEN_IMAGE --DOC_HIDE local awful = { --DOC_HIDE --DOC_NO_USAGE popup = require("awful.popup"), --DOC_HIDE placement = require("awful.placement"), --DOC_HIDE widget = {clienticon =require("awful.widget.clienticon"), --DOC_HIDE tasklist = require("awful.widget.tasklist")} --DOC_HIDE } --DOC_HIDE local wibox = require("wibox") --DOC_HIDE local beautiful = require("beautiful") --DOC_HIDE local previous = nil for i=1, 5 do local p2 = awful.popup { widget = wibox.widget { text = "Hello world! "..i.." aaaa.", widget = wibox.widget.textbox }, border_color = beautiful.border_color, preferred_positions = "bottom", border_width = 2, preferred_anchors = "back", placement = (not previous) and awful.placement.top or nil, offset = { y = 10, }, } p2:_apply_size_now() --DOC_HIDE p2:move_next_to(previous) previous = p2 previous:_apply_size_now() --DOC_HIDE end --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0