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
bjornswenson/RxLua
tests/zip.lua
2
1597
describe('zip', function() it('behaves as an identity function if only one Observable argument is specified', function() expect(Rx.Observable.fromRange(1, 5):zip()).to.produce(1, 2, 3, 4, 5) end) it('unsubscribes from all input observables', function() local unsubscribeA = spy() local subscriptionA = Rx.Subscription.create(unsubscribeA) local observableA = Rx.Observable.create(function(observer) return subscriptionA end) local unsubscribeB = spy() local subscriptionB = Rx.Subscription.create(unsubscribeB) local observableB = Rx.Observable.create(function(observer) return subscriptionB end) local subscription = Rx.Observable.zip(observableA, observableB):subscribe() subscription:unsubscribe() expect(#unsubscribeA).to.equal(1) expect(#unsubscribeB).to.equal(1) end) it('groups values produced by the sources by their index', function() local observableA = Rx.Observable.fromRange(1, 3) local observableB = Rx.Observable.fromRange(2, 4) local observableC = Rx.Observable.fromRange(3, 5) expect(Rx.Observable.zip(observableA, observableB, observableC)).to.produce({{1, 2, 3}, {2, 3, 4}, {3, 4, 5}}) end) it('tolerates nils', function() local observableA = Rx.Observable.create(function(observer) observer:onNext(nil) observer:onNext(nil) observer:onNext(nil) observer:onCompleted() end) local observableB = Rx.Observable.fromRange(3) local onNext = observableSpy(Rx.Observable.zip(observableA, observableB)) expect(#onNext).to.equal(3) end) end)
mit
olostan/mudlet
src/mudlet-lua/lua/StringUtils.lua
7
4650
---------------------------------------------------------------------------------- --- Mudlet String Utils ---------------------------------------------------------------------------------- --- Cut string to specified maximum length. --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @usage Following call will return 'abc'. --- <pre> --- string.cut("abcde", 3) --- </pre> --- @usage You can easily pad string to certain length. --- Example bellow will print 'abcde ' e.g. pad/cut string to 10 characters. --- <pre> --- local s = "abcde" --- s = string.cut(s .. " ", 10) -- append 10 spaces --- echo("'" .. s .. "'") --- </pre> function string.cut(s, maxLen) if string.len(s) > maxLen then return string.sub(s, 1, maxLen) else return s end end --- Enclose string by long brackets. <br/> --- <b><u>TODO</u></b> what is purpose of this function? function string.enclose(s, maxlevel) s = "["..s.."]" local level = 0 while 1 do if maxlevel and level == maxlevel then error( "error: maxlevel too low, "..maxlevel ) elseif string.find( s, "%["..string.rep( "=", level ).."%[" ) or string.find( s, "]"..string.rep( "=", level ).."]" ) then level = level + 1 else return "["..string.rep( "=", level )..s..string.rep( "=", level ).."]" end end end --- Test if string is ending with specified suffix. --- --- @see string.starts function string.ends(String, Suffix) return Suffix=='' or string.sub(String,-string.len(Suffix))==Suffix end --- Generate case insensitive search pattern from string. --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @return case insensitive pattern string --- --- @usage Following example will generate and print <i>"123[aA][bB][cC]"</i> string. --- <pre> --- echo(string.genNocasePattern("123abc")) --- </pre> function string.genNocasePattern(s) s = string.gsub(s, "%a", function (c) return string.format("[%s%s]", string.lower(c), string.upper(c)) end) return s end --- Return first matching substring or nil. --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @return nil or first matching substring --- --- @usage Following example will print: "I did find: Troll" string. --- <pre> --- local match = string.findPattern("Troll is here!", "Troll") --- if match then --- echo("I did find: " .. match) --- end --- </pre> --- @usage This example will find substring regardless of case. --- <pre> --- local match = string.findPattern("Troll is here!", string.genNocasePattern("troll")) --- if match then --- echo("I did find: " .. match) --- end --- </pre> --- --- @see string.genNocasePattern function string.findPattern(text, pattern) if string.find(text, pattern, 1) then return string.sub(text, string.find(text, pattern, 1)) else return nil end end --- Splits a string into a table by the given delimiter. --- --- @usage Split string by ", " delimiter. --- <pre> --- names = "Alice, Bob, Peter" --- name_table = names:split(", ") --- display(name_table) --- </pre> --- --- Previous code will print out: --- <pre> --- table { --- 1: 'Alice' --- 2: 'Bob' --- 3: 'Peter' --- } --- </pre> --- --- @return array with split strings function string:split(delimiter) local result = { } local from = 1 local delim_from, delim_to = string.find( self, delimiter, from ) while delim_from do table.insert( result, string.sub( self, from , delim_from-1 ) ) from = delim_to + 1 delim_from, delim_to = string.find( self, delimiter, from ) end table.insert( result, string.sub( self, from ) ) return result end --- Test if string is starting with specified prefix. --- --- @see string.ends function string.starts(String, Prefix) return string.sub(String,1,string.len(Prefix))==Prefix end --- Capitalize first character in a string. --- --- @usage Variable testname is now Anna. --- <pre> --- testname = string.title("anna") --- </pre> --- @usage Example will set test to "Bob". --- <pre> --- test = "bob" --- test = string.title(test) --- </pre> function string:title() self = self:gsub("^%l", string.upper, 1) return self end --- Trim string (remove all white spaces around string). --- --- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>) --- --- @usage Example will print 'Troll is here!'. --- <pre> --- local str = string.trim(" Troll is here! ") --- echo("'" .. str .. "'") --- </pre> function string.trim(s) if s then return string.gsub(s, "^%s*(.-)%s*$", "%1") else return s end end
gpl-2.0
ealegol/kolla-newton
docker/heka/plugins/decoders/os_openstack_log.lua
6
4720
-- Copyright 2015-2016 Mirantis, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. require "string" require "table" local l = require 'lpeg' l.locale(l) local patt = require 'os_patterns' local utils = require 'os_utils' local msg = { Timestamp = nil, Type = 'log', Hostname = nil, Payload = nil, Pid = nil, Fields = nil, Severity = nil, } -- traceback_lines is a reference to a table used to accumulate lines of -- a Traceback. traceback_key represent the key of the Traceback lines -- being accumulated in traceback_lines. This is used to know when to -- stop accumulating and inject the Heka message. local traceback_key = nil local traceback_lines = nil function prepare_message (service, timestamp, pid, severity_label, python_module, programname, payload) msg.Logger = 'openstack.' .. service msg.Timestamp = timestamp msg.Payload = payload msg.Pid = pid msg.Severity = utils.label_to_severity_map[severity_label] or 7 msg.Fields = {} msg.Fields.severity_label = severity_label msg.Fields.python_module = python_module msg.Fields.programname = programname msg.Payload = payload end -- OpenStack log messages are of this form: -- 2015-11-30 08:38:59.306 3434 INFO oslo_service.periodic_task [-] Blabla... -- -- [-] is the "request" part, it can take multiple forms. function process_message () -- Logger is of form "<service>_<program>" (e.g. "nova_nova-api", -- "neutron_l3-agent"). local logger = read_message("Logger") local service, program = string.match(logger, '([^_]+)_(.+)') local log = read_message("Payload") local m m = patt.openstack:match(log) if not m then return -1, string.format("Failed to parse %s log: %s", logger, string.sub(log, 1, 64)) end local key = { Timestamp = m.Timestamp, Pid = m.Pid, SeverityLabel = m.SeverityLabel, PythonModule = m.PythonModule, service = service, program = program, } if traceback_key ~= nil then -- If traceback_key is not nil then it means we've started accumulated -- lines of a Python traceback. We keep accumulating the traceback -- lines util we get a different log key. if utils.table_equal(traceback_key, key) then table.insert(traceback_lines, m.Message) return 0 else prepare_message(traceback_key.service, traceback_key.Timestamp, traceback_key.Pid, traceback_key.SeverityLabel, traceback_key.PythonModule, traceback_key.program, table.concat(traceback_lines, '')) traceback_key = nil traceback_lines = nil -- Ignore safe_inject_message status code here to still get a -- chance to inject the current log message. utils.safe_inject_message(msg) end end if patt.traceback:match(m.Message) then -- Python traceback detected, begin accumulating the lines making -- up the traceback. traceback_key = key traceback_lines = {} table.insert(traceback_lines, m.Message) return 0 end prepare_message(service, m.Timestamp, m.Pid, m.SeverityLabel, m.PythonModule, program, m.Message) m = patt.openstack_request_context:match(msg.Payload) if m then msg.Fields.request_id = m.RequestId if m.UserId then msg.Fields.user_id = m.UserId end if m.TenantId then msg.Fields.tenant_id = m.TenantId end end m = patt.openstack_http:match(msg.Payload) if m then msg.Fields.http_method = m.http_method msg.Fields.http_status = m.http_status msg.Fields.http_url = m.http_url msg.Fields.http_version = m.http_version msg.Fields.http_response_size = m.http_response_size msg.Fields.http_response_time = m.http_response_time m = patt.ip_address:match(msg.Payload) if m then msg.Fields.http_client_ip_address = m.ip_address end end return utils.safe_inject_message(msg) end
apache-2.0
sundream/gamesrv
script/net/war.lua
1
1822
local function callwar(player,cmd,request) local warsrvname = assert(player:query("fight.warsrvname")) local warid = assert(player:query("fight.warid")) local pid = player.pid request.warid = warid request.pid = pid return cluster.call(warsrvname,"war",cmd,request) end netwar = netwar or {} -- c2s local REQUEST = {} netwar.REQUEST = REQUEST -- forward to warsrvmgr function REQUEST.selectcardtable(player,request) local cardtableid = assert(request.cardtableid) local type = assert(request.type) if type == "fight" then player:set("fight.cardtableid",cardtableid) end end function REQUEST.search_opponent(player,request) local type = assert(request.type) if type == "fight" then local profile = player:pack_fight_profile(type) return cluster.call("warsrvmgr","war","search_opponent",profile) end end function REQUEST.unsearch_opponent(player,request) return cluster.call("warsrvmgr","war","unsearch_opponent",player.pid) end -- forward -- gamesrv -> warsrv function REQUEST.confirm_handcard(player,request) return callwar(player,"confirm_handcard",request) end function REQUEST.playcard(player,request) return callwar(player,"playcard",request) end function REQUEST.endround(player,request) return callwar(player,"endround",request) end function REQUEST.launchattack(player,request) return callwar(player,"launchattack",request) end function REQUEST.useskill(player,request) return callwar(player,"useskill",request) end function REQUEST.giveupwar(player,request) return callwar(player,"giveupwar",request) end function REQUEST.lookcards_confirm(player,request) return callwar(player,"lookcards_confirm",request) end function REQUEST.playcard(player,request) return callwar(player,"playcard",request) end local RESPONSE = {} netwar.RESPONSE = RESPONSE -- s2c return netwar
gpl-2.0
sundream/gamesrv
script/card/soil/card153003.lua
1
2435
--<<card 导表开始>> local super = require "script.card.init" ccard153003 = class("ccard153003",super,{ sid = 153003, race = 5, name = "野蛮之击", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 1, targettype = 22, halo = nil, desc = "对一个随从造成等同于你的英雄攻击力的伤害。", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard153003:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard153003:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard153003:save() local data = super.save(self) -- todo: save data return data end function ccard153003:onuse(pos,targetid,choice) local owner = self:getowner() local target = owner:gettarget(targetid) target:addhp(-owner.hero:getatk(),self.id) end return ccard153003
gpl-2.0
EvPowerTeam/EV_OP
feeds/luci/modules/base/luasrc/ip.lua
86
18154
--[[ LuCI ip calculation libarary (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> (c) 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- --- LuCI IP calculation library. module( "luci.ip", package.seeall ) require "nixio" local bit = nixio.bit local util = require "luci.util" --- Boolean; true if system is little endian LITTLE_ENDIAN = not util.bigendian() --- Boolean; true if system is big endian BIG_ENDIAN = not LITTLE_ENDIAN --- Specifier for IPv4 address family FAMILY_INET4 = 0x04 --- Specifier for IPv6 address family FAMILY_INET6 = 0x06 local function __bless(x) return setmetatable( x, { __index = luci.ip.cidr, __add = luci.ip.cidr.add, __sub = luci.ip.cidr.sub, __lt = luci.ip.cidr.lower, __eq = luci.ip.cidr.equal, __le = function(...) return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...) end } ) end local function __array16( x, family ) local list if type(x) == "number" then list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) } elseif type(x) == "string" then if x:find(":") then x = IPv6(x) else x = IPv4(x) end if x then assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" ) list = { unpack(x[2]) } end elseif type(x) == "table" and type(x[2]) == "table" then assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" ) list = { unpack(x[2]) } elseif type(x) == "table" then list = { unpack(x) } end assert( list, "Invalid operand" ) return list end local function __mask16(bits) return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 ) end local function __not16(bits) return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF ) end local function __maxlen(family) return ( family == FAMILY_INET4 ) and 32 or 128 end local function __sublen(family) return ( family == FAMILY_INET4 ) and 30 or 127 end --- Convert given short value to network byte order on little endian hosts -- @param x Unsigned integer value between 0x0000 and 0xFFFF -- @return Byte-swapped value -- @see htonl -- @see ntohs function htons(x) if LITTLE_ENDIAN then return bit.bor( bit.rshift( x, 8 ), bit.band( bit.lshift( x, 8 ), 0xFF00 ) ) else return x end end --- Convert given long value to network byte order on little endian hosts -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF -- @return Byte-swapped value -- @see htons -- @see ntohl function htonl(x) if LITTLE_ENDIAN then return bit.bor( bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ), htons( bit.rshift( x, 16 ) ) ) else return x end end --- Convert given short value to host byte order on little endian hosts -- @class function -- @name ntohs -- @param x Unsigned integer value between 0x0000 and 0xFFFF -- @return Byte-swapped value -- @see htonl -- @see ntohs ntohs = htons --- Convert given short value to host byte order on little endian hosts -- @class function -- @name ntohl -- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF -- @return Byte-swapped value -- @see htons -- @see ntohl ntohl = htonl --- Parse given IPv4 address in dotted quad or CIDR notation. If an optional -- netmask is given as second argument and the IP address is encoded in CIDR -- notation then the netmask parameter takes precedence. If neither a CIDR -- encoded prefix nor a netmask parameter is given, then a prefix length of -- 32 bit is assumed. -- @param address IPv4 address in dotted quad or CIDR notation -- @param netmask IPv4 netmask in dotted quad notation (optional) -- @return luci.ip.cidr instance or nil if given address was invalid -- @see IPv6 -- @see Hex function IPv4(address, netmask) address = address or "0.0.0.0/0" local obj = __bless({ FAMILY_INET4 }) local data = {} local prefix = address:match("/(.+)") address = address:gsub("/.+","") address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "") if netmask then prefix = obj:prefix(netmask) elseif prefix then prefix = tonumber(prefix) if not prefix or prefix < 0 or prefix > 32 then return nil end else prefix = 32 end local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") b1 = tonumber(b1) b2 = tonumber(b2) b3 = tonumber(b3) b4 = tonumber(b4) if b1 and b1 <= 255 and b2 and b2 <= 255 and b3 and b3 <= 255 and b4 and b4 <= 255 and prefix then table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 }) table.insert(obj, prefix) return obj end end --- Parse given IPv6 address in full, compressed, mixed or CIDR notation. -- If an optional netmask is given as second argument and the IP address is -- encoded in CIDR notation then the netmask parameter takes precedence. -- If neither a CIDR encoded prefix nor a netmask parameter is given, then a -- prefix length of 128 bit is assumed. -- @param address IPv6 address in full/compressed/mixed or CIDR notation -- @param netmask IPv6 netmask in full/compressed/mixed notation (optional) -- @return luci.ip.cidr instance or nil if given address was invalid -- @see IPv4 -- @see Hex function IPv6(address, netmask) address = address or "::/0" local obj = __bless({ FAMILY_INET6 }) local data = {} local prefix = address:match("/(.+)") address = address:gsub("/.+","") address = address:gsub("^%[(.*)%]$", "%1") if netmask then prefix = obj:prefix(netmask) elseif prefix then prefix = tonumber(prefix) if not prefix or prefix < 0 or prefix > 128 then return nil end else prefix = 128 end local borderl = address:sub(1, 1) == ":" and 2 or 1 local borderh, zeroh, chunk, block, i if #address > 45 then return nil end repeat borderh = address:find(":", borderl, true) if not borderh then break end block = tonumber(address:sub(borderl, borderh - 1), 16) if block and block <= 0xFFFF then data[#data+1] = block else if zeroh or borderh - borderl > 1 then return nil end zeroh = #data + 1 end borderl = borderh + 1 until #data == 7 chunk = address:sub(borderl) if #chunk > 0 and #chunk <= 4 then block = tonumber(chunk, 16) if not block or block > 0xFFFF then return nil end data[#data+1] = block elseif #chunk > 4 then if #data == 7 or #chunk > 15 then return nil end borderl = 1 for i=1, 4 do borderh = chunk:find(".", borderl, true) if not borderh and i < 4 then return nil end borderh = borderh and borderh - 1 block = tonumber(chunk:sub(borderl, borderh)) if not block or block > 255 then return nil end if i == 1 or i == 3 then data[#data+1] = block * 256 else data[#data] = data[#data] + block end borderl = borderh and borderh + 2 end end if zeroh then if #data == 8 then return nil end while #data < 8 do table.insert(data, zeroh, 0) end end if #data == 8 and prefix then table.insert(obj, data) table.insert(obj, prefix) return obj end end --- Transform given hex-encoded value to luci.ip.cidr instance of specified -- address family. -- @param hex String containing hex encoded value -- @param prefix Prefix length of CIDR instance (optional, default is 32/128) -- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6 -- @param swap Bool indicating whether to swap byteorder on low endian host -- @return luci.ip.cidr instance or nil if given value was invalid -- @see IPv4 -- @see IPv6 function Hex( hex, prefix, family, swap ) family = ( family ~= nil ) and family or FAMILY_INET4 swap = ( swap == nil ) and true or swap prefix = prefix or __maxlen(family) local len = __maxlen(family) local tmp = "" local data = { } local i for i = 1, (len/4) - #hex do tmp = tmp .. '0' end if swap and LITTLE_ENDIAN then for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end else tmp = tmp .. hex end hex = tmp for i = 1, ( len / 4 ), 4 do local n = tonumber( hex:sub( i, i+3 ), 16 ) if n then data[#data+1] = n else return nil end end return __bless({ family, data, prefix }) end --- LuCI IP Library / CIDR instances -- @class module -- @cstyle instance -- @name luci.ip.cidr cidr = util.class() --- Test whether the instance is a IPv4 address. -- @return Boolean indicating a IPv4 address type -- @see cidr.is6 function cidr.is4( self ) return self[1] == FAMILY_INET4 end --- Test whether this instance is an IPv4 RFC1918 private address -- @return Boolean indicating whether this instance is an RFC1918 address function cidr.is4rfc1918( self ) if self[1] == FAMILY_INET4 then return ((self[2][1] >= 0x0A00) and (self[2][1] <= 0x0AFF)) or ((self[2][1] >= 0xAC10) and (self[2][1] <= 0xAC1F)) or (self[2][1] == 0xC0A8) end return false end --- Test whether this instance is an IPv4 link-local address (Zeroconf) -- @return Boolean indicating whether this instance is IPv4 link-local function cidr.is4linklocal( self ) if self[1] == FAMILY_INET4 then return (self[2][1] == 0xA9FE) end return false end --- Test whether the instance is a IPv6 address. -- @return Boolean indicating a IPv6 address type -- @see cidr.is4 function cidr.is6( self ) return self[1] == FAMILY_INET6 end --- Test whether this instance is an IPv6 link-local address -- @return Boolean indicating whether this instance is IPv6 link-local function cidr.is6linklocal( self ) if self[1] == FAMILY_INET6 then return (self[2][1] >= 0xFE80) and (self[2][1] <= 0xFEBF) end return false end --- Return a corresponding string representation of the instance. -- If the prefix length is lower then the maximum possible prefix length for the -- corresponding address type then the address is returned in CIDR notation, -- otherwise the prefix will be left out. function cidr.string( self ) local str if self:is4() then str = string.format( "%d.%d.%d.%d", bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF), bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF) ) if self[3] < 32 then str = str .. "/" .. self[3] end elseif self:is6() then str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) ) if self[3] < 128 then str = str .. "/" .. self[3] end end return str end --- Test whether the value of the instance is lower then the given address. -- This function will throw an exception if the given address has a different -- family than this instance. -- @param addr A luci.ip.cidr instance to compare against -- @return Boolean indicating whether this instance is lower -- @see cidr.higher -- @see cidr.equal function cidr.lower( self, addr ) assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) local i for i = 1, #self[2] do if self[2][i] ~= addr[2][i] then return self[2][i] < addr[2][i] end end return false end --- Test whether the value of the instance is higher then the given address. -- This function will throw an exception if the given address has a different -- family than this instance. -- @param addr A luci.ip.cidr instance to compare against -- @return Boolean indicating whether this instance is higher -- @see cidr.lower -- @see cidr.equal function cidr.higher( self, addr ) assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) local i for i = 1, #self[2] do if self[2][i] ~= addr[2][i] then return self[2][i] > addr[2][i] end end return false end --- Test whether the value of the instance is equal to the given address. -- This function will throw an exception if the given address is a different -- family than this instance. -- @param addr A luci.ip.cidr instance to compare against -- @return Boolean indicating whether this instance is equal -- @see cidr.lower -- @see cidr.higher function cidr.equal( self, addr ) assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) local i for i = 1, #self[2] do if self[2][i] ~= addr[2][i] then return false end end return true end --- Return the prefix length of this CIDR instance. -- @param mask Override instance prefix with given netmask (optional) -- @return Prefix length in bit function cidr.prefix( self, mask ) local prefix = self[3] if mask then prefix = 0 local stop = false local obj = type(mask) ~= "table" and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask if not obj then return nil end local _, word for _, word in ipairs(obj[2]) do if word == 0xFFFF then prefix = prefix + 16 else local bitmask = bit.lshift(1, 15) while bit.band(word, bitmask) == bitmask do prefix = prefix + 1 bitmask = bit.lshift(1, 15 - (prefix % 16)) end break end end end return prefix end --- Return a corresponding CIDR representing the network address of this -- instance. -- @param bits Override prefix length of this instance (optional) -- @return CIDR instance containing the network address -- @see cidr.host -- @see cidr.broadcast -- @see cidr.mask function cidr.network( self, bits ) local data = { } bits = bits or self[3] local i for i = 1, math.floor( bits / 16 ) do data[#data+1] = self[2][i] end if #data < #self[2] then data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) ) for i = #data + 1, #self[2] do data[#data+1] = 0 end end return __bless({ self[1], data, __maxlen(self[1]) }) end --- Return a corresponding CIDR representing the host address of this -- instance. This is intended to extract the host address from larger subnet. -- @return CIDR instance containing the network address -- @see cidr.network -- @see cidr.broadcast -- @see cidr.mask function cidr.host( self ) return __bless({ self[1], self[2], __maxlen(self[1]) }) end --- Return a corresponding CIDR representing the netmask of this instance. -- @param bits Override prefix length of this instance (optional) -- @return CIDR instance containing the netmask -- @see cidr.network -- @see cidr.host -- @see cidr.broadcast function cidr.mask( self, bits ) local data = { } bits = bits or self[3] for i = 1, math.floor( bits / 16 ) do data[#data+1] = 0xFFFF end if #data < #self[2] then data[#data+1] = __mask16(bits) for i = #data + 1, #self[2] do data[#data+1] = 0 end end return __bless({ self[1], data, __maxlen(self[1]) }) end --- Return CIDR containing the broadcast address of this instance. -- @return CIDR instance containing the netmask, always nil for IPv6 -- @see cidr.network -- @see cidr.host -- @see cidr.mask function cidr.broadcast( self ) -- IPv6 has no broadcast addresses (XXX: assert() instead?) if self[1] == FAMILY_INET4 then local data = { unpack(self[2]) } local offset = math.floor( self[3] / 16 ) + 1 if offset <= #data then data[offset] = bit.bor( data[offset], __not16(self[3]) ) for i = offset + 1, #data do data[i] = 0xFFFF end return __bless({ self[1], data, __maxlen(self[1]) }) end end end --- Test whether this instance fully contains the given CIDR instance. -- @param addr CIDR instance to test against -- @return Boolean indicating whether this instance contains the given CIDR function cidr.contains( self, addr ) assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) if self:prefix() <= addr:prefix() then return self:network() == addr:network(self:prefix()) end return false end --- Add specified amount of hosts to this instance. -- @param amount Number of hosts to add to this instance -- @param inplace Boolen indicating whether to alter values inplace (optional) -- @return CIDR representing the new address or nil on overflow error -- @see cidr.sub function cidr.add( self, amount, inplace ) local pos local data = { unpack(self[2]) } local shorts = __array16( amount, self[1] ) for pos = #data, 1, -1 do local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0 if ( data[pos] + add ) > 0xFFFF then data[pos] = ( data[pos] + add ) % 0xFFFF if pos > 1 then data[pos-1] = data[pos-1] + ( add - data[pos] ) else return nil end else data[pos] = data[pos] + add end end if inplace then self[2] = data return self else return __bless({ self[1], data, self[3] }) end end --- Substract specified amount of hosts from this instance. -- @param amount Number of hosts to substract from this instance -- @param inplace Boolen indicating whether to alter values inplace (optional) -- @return CIDR representing the new address or nil on underflow error -- @see cidr.add function cidr.sub( self, amount, inplace ) local pos local data = { unpack(self[2]) } local shorts = __array16( amount, self[1] ) for pos = #data, 1, -1 do local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0 if ( data[pos] - sub ) < 0 then data[pos] = ( sub - data[pos] ) % 0xFFFF if pos > 1 then data[pos-1] = data[pos-1] - ( sub + data[pos] ) else return nil end else data[pos] = data[pos] - sub end end if inplace then self[2] = data return self else return __bless({ self[1], data, self[3] }) end end --- Return CIDR containing the lowest available host address within this subnet. -- @return CIDR containing the host address, nil if subnet is too small -- @see cidr.maxhost function cidr.minhost( self ) if self[3] <= __sublen(self[1]) then -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6 return self:network():add(1, true) end end --- Return CIDR containing the highest available host address within the subnet. -- @return CIDR containing the host address, nil if subnet is too small -- @see cidr.minhost function cidr.maxhost( self ) if self[3] <= __sublen(self[1]) then local i local data = { unpack(self[2]) } local offset = math.floor( self[3] / 16 ) + 1 data[offset] = bit.bor( data[offset], __not16(self[3]) ) for i = offset + 1, #data do data[i] = 0xFFFF end data = __bless({ self[1], data, __maxlen(self[1]) }) -- Last address in reserved for Broadcast Address in IPv4 if data[1] == FAMILY_INET4 then data:sub(1, true) end return data end end
gpl-2.0
dmccuskey/dmc-websockets
examples/dmc-websockets-pusher/dmc_corona/lib/dmc_lua/lua_utils.lua
46
15359
--====================================================================-- -- lua_utils.lua -- -- Documentation: http://docs.davidmccuskey.com/display/docs/lua_utils.lua --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014 David McCuskey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Lua Library : Lua Utils --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.2.0" --====================================================================-- --== Setup, Constants local slower = string.lower local tconcat = table.concat local tinsert = table.insert local Utils = {} -- Utils object --====================================================================-- --== Callback Functions --====================================================================-- -- createObjectCallback() -- Creates a closure used to bind a method to an object. -- Useful for creating a custom callback. -- -- @param object the object which has the method -- @param method the method to call -- function Utils.createObjectCallback( object, method ) assert( object, "dmc_utils.createObjectCallback: missing object" ) assert( method, "dmc_utils.createObjectCallback: missing method" ) --==-- return function( ... ) return method( object, ... ) end end function Utils.getTransitionCompleteFunc( count, callback ) assert( type(count)=='number', "requires number for count" ) assert( type(callback)=='function', "requires callback function" ) --==-- local total = 0 local func = function(...) total = total + 1 if total >= count then callback(...) end end return func end --====================================================================-- --== Date Functions --====================================================================-- --[[ Given a UNIX time (seconds), split that duration into number of weeks, days, etc eg, { months=0, weeks=2, days=3, hours=8, minutes=35, seconds=21 } --]] local week_s, day_s, hour_s, min_s, sec_s sec_s = 1 min_s = 60 * sec_s hour_s = 60 * min_s day_s = 24 * hour_s week_s = 7 * day_s -- give number and remainder local function diff( time, divisor ) return { math.floor( time/divisor ), ( time % divisor ) } end function Utils.calcTimeBreakdown( seconds, params ) seconds = math.abs( seconds ) params = params or {} params.days = params.days or true params.hours = params.hours or true params.minutes = params.minutes or true local result, tmp = {}, { 0, seconds } result.weeks = 0 if params.weeks and tmp[2] >= week_s then tmp = diff( tmp[2], week_s ) result.weeks = tmp[1] end result.days = 0 if params.days and tmp[2] >= day_s then tmp = diff( tmp[2], day_s ) result.days = tmp[1] end result.hours = 0 if params.hours and tmp[2] >= hour_s then tmp = diff( tmp[2], hour_s ) result.hours = tmp[1] end result.minutes = 0 if params.minutes and tmp[2] >= min_s then tmp = diff( tmp[2], min_s ) result.minutes = tmp[1] end result.seconds = tmp[2] return result end --====================================================================-- --== Image Functions --====================================================================-- -- imageScale() -- container, image - table with width/height keys -- returns scale -- param.bind : 'inside', 'outside' function Utils.imageScale( container, image, params ) params = params or {} if params.bind == nil then params.bind = 'outside' end --==-- local bind = params.bind local box_ratio, img_ratio local scale = 1 box_ratio = container.width / container.height img_ratio = image.width / image.height if ( bind=='outside' and img_ratio > box_ratio ) or ( bind=='inside' and img_ratio < box_ratio ) then -- constrained by height scale = container.height / image.height else -- constrained by width scale = container.width / image.width end return scale end --====================================================================-- --== Math Functions --====================================================================-- function Utils.getUniqueRandom( include, exclude ) --print( "Utils.getUniqueRandom" ) include = include or {} if #include == 0 then return end exclude = exclude or {} local exclude_hash = {} -- used as dict local pruned_list = {} local item math.randomseed( os.time() ) -- process as normal if no exclusions if #exclude == 0 then item = include[ math.random( #include ) ] else -- make a hash for quicker lookup when creating pruned list for _, name in ipairs( exclude ) do exclude_hash[ name ] = true end -- create our pruned list for _, name in ipairs( include ) do if exclude_hash[ name ] ~= true then table.insert( pruned_list, name ) end end -- Sanity Check if #pruned_list == 0 then print( "WARNING: Utils.getUniqueRandom()" ) print( "The 'exclude' list is equal to the 'include' list" ) return nil end -- get our item item = pruned_list[ math.random( #pruned_list ) ] end return item end -- hexDump() -- pretty-print data in hex table -- function Utils.hexDump( buf ) for i=1,math.ceil(#buf/16) * 16 do if (i-1) % 16 == 0 then io.write(string.format('%08X ', i-1)) end io.write( i > #buf and ' ' or string.format('%02X ', buf:byte(i)) ) if i % 8 == 0 then io.write(' ') end if i % 16 == 0 then io.write( buf:sub(i-16+1, i):gsub('%c','.'), '\n' ) end end end --====================================================================-- --== String Functions --====================================================================-- -- split string up in parts, using separator -- returns array of pieces function Utils.split( str, sep ) if sep == nil then sep = "%s" end local t, i = {}, 1 for str in string.gmatch( str, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end -- stringFormatting() -- implement Python-style string replacement -- http://lua-users.org/wiki/StringInterpolation -- function Utils.stringFormatting( a, b ) if not b then return a elseif type(b) == "table" then return string.format(a, unpack(b)) else return string.format(a, b) end end --====================================================================-- --== Table Functions --====================================================================-- -- destroy() -- Deletes all of the items in a table structure. -- This is intended for generic tables and structures, *not* objects -- -- @param table the table from which to delete contents -- function Utils.destroy( table ) if type( table ) ~= "table" then return end function _destroy( t ) for k,v in pairs( t ) do if type( t[ k ] ) == "table" then _destroy( t[ k ] ) end t[ k ] = nil end end -- start destruction process _destroy( table ) end -- extend() -- Copy key/values from one table to another -- Will deep copy any value from first table which is itself a table. -- -- @param fromTable the table (object) from which to take key/value pairs -- @param toTable the table (object) in which to copy key/value pairs -- @return table the table (object) that received the copied items -- function Utils.extend( fromTable, toTable ) if not fromTable or not toTable then error( "table can't be nil" ) end function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end -- hasOwnProperty() -- Find a property directly on an object (not via inheritance prototype) -- -- @param table the table (object) to search -- @param prop the name (string) of the property to find -- @return true if property is found, false otherwise -- function Utils.hasOwnProperty( table, property ) if rawget( table, property ) ~= nil then return true end return false end -- print() -- print out the keys contained within a table. -- by default, does not process items with underscore '_' -- -- @param table the table (object) to print -- @param include a list of names to include -- @param exclude a list of names to exclude -- function Utils.print( table, include, exclude, params ) local indent = "" local step = 0 local include = include or {} local exclude = exclude or {} local params = params or {} local options = { limit = 10, } opts = Utils.extend( params, options ) --print("Printing object table =============================") function _print( t, ind, s ) -- limit number of rounds if s > options.limit then return end for k, v in pairs( t ) do local ok_to_process = true if Utils.propertyIn( include, k ) then ok_to_process = true elseif type( t[k] ) == "function" or Utils.propertyIn( exclude, k ) or type( k ) == "string" and k:sub(1,1) == '_' then ok_to_process = false end if ok_to_process then if type( t[ k ] ) == "table" then local o = t[ k ] local address = tostring( o ) local items = #o print ( ind .. k .. " --> " .. address .. " w " .. items .. " items" ) _print( t[ k ], ( ind .. " " ), ( s + 1 ) ) else if type( v ) == "string" then print ( ind .. k .. " = '" .. v .. "'" ) else print ( ind .. k .. " = " .. tostring( v ) ) end end end end end -- start printing process _print( table, indent, step + 1 ) end -- propertyIn() -- Determines whether a property is within a list of items in a table (acting as an array) -- -- @param list the table with *list* of properties -- @param property the name of the property to search for -- function Utils.propertyIn( list, property ) for i = 1, #list do if list[i] == property then return true end end return false end -- searches for item in table (as array), removes and returns item -- function Utils.removeFromTable( t, item ) local o = nil for i=#t,1,-1 do if t[i] == item then o = table.remove( t, i ) break end end return o end -- http://rosettacode.org/wiki/Knuth_shuffle#Lua -- function Utils.shuffle( t ) local n = #t while n > 1 do local k = math.random(n) t[n], t[k] = t[k], t[n] n = n - 1 end return t end -- tableLength() -- Count the number of items in a table -- http://stackoverflow.com/questions/2705793/how-to-get-number-of-entries-in-a-lua-table -- -- @param t the table in which to count items -- @return number of items in table -- function Utils.tableLength( t ) local count = 0 for _, _ in pairs(t) do count = count + 1 end return count end -- take objects from hashed table, make array table -- function Utils.tableList( t ) assert( type(t)=='table', "Utils.tableList expected table" ) local list = {} for _, o in pairs( t ) do tinsert( list, o ) end return list end -- calculates size of table, mostly used as a dictionary -- function Utils.tableSize( t1 ) local size = 0 for _,v in pairs( t1 ) do size = size + 1 end return size end -- http://snippets.luacode.org/snippets/Table_Slice_116 function Utils.tableSlice( values, i1, i2 ) local res = {} local n = #values -- default values for range i1 = i1 or 1 i2 = i2 or n if i2 < 0 then i2 = n + i2 + 1 elseif i2 > n then i2 = n end if i1 < 1 or i1 > n then return {} end local k = 1 for i = i1,i2 do res[k] = values[i] k = k + 1 end return res end --====================================================================-- --== Web Functions --====================================================================-- function Utils.createHttpRequest( params ) -- print( "Utils.createHttpRequest") params = params or {} --==-- local http_params = params.http_params local req_t = { "%s / HTTP/1.1" % params.method, "Host: %s" % params.host, } if type( http_params.headers ) == 'table' then for k,v in pairs( http_params.headers ) do tinsert( req_t, #req_t+1, "%s:%s" % { k, v } ) end end if http_params.body ~= nil then tinsert( req_t, #req_t+1, "" ) tinsert( req_t, #req_t+1, http_params.body ) end tinsert( req_t, #req_t+1, "\r\n" ) return tconcat( req_t, "\r\n" ) end function Utils.normalizeHeaders( headers, params ) params = params or {} params.case = params.case or 'lower' -- camel, lower params.debug = params.debug ~= nil and params.debug or false --==-- local h = {} local f if false and params.case == 'camel' then f = nil -- TODO else f = string.lower end for k,v in pairs( headers ) do if params.debug then print(k,v) end h[ f(k) ] = v end return h end -- http://lua-users.org/wiki/StringRecipes function Utils.urlDecode( str ) assert( type(str)=='string', "Utils.urlDecode: input not a string" ) str = string.gsub (str, "+", " ") str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end) str = string.gsub (str, "\r\n", "\n") return str end -- http://lua-users.org/wiki/StringRecipes function Utils.urlEncode( str ) assert( type(str)=='string', "Utils.urlEncode: input not a string" ) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end -- parseQuery() -- splits an HTTP query string (eg, 'one=1&two=2' ) into its components -- -- @param str string containing url-type key/value pairs -- @returns a table with the key/value pairs -- function Utils.parseQuery( str ) assert( type(str)=='string', "Utils.parseQuery: input not a string" ) local t = {} if str ~= nil then for k, v in string.gmatch( str, "([^=&]+)=([^=&]+)") do t[k] = v end end return t end -- createQuery() -- creates query string from table items -- -- @param tbl table as dictionary -- returns query string -- function Utils.createQuery( tbl ) assert( type(tbl)=='table', "Utils.createQuery: input not a table" ) local encode = Utils.urlEncode local str = '' for k,v in pairs( tbl ) do if str ~= '' then str = str .. '&' end str = str .. tostring( k ) .. '=' .. encode( tostring(v) ) end return str end return Utils
mit
Sour/pfUI
modules/debuffs.lua
1
11587
pfUI:RegisterModule("debuffs", function () if C.appearance.cd.debuffs ~= "1" then return end pfUI.debuffs = CreateFrame("Frame", "pfdebuffsScanner", UIParent) pfUI.debuffs.pfDebuffNameScan = CreateFrame('GameTooltip', "pfDebuffNameScan", UIParent, "GameTooltipTemplate") pfUI.debuffs:RegisterEvent("CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_DAMAGE") pfUI.debuffs:RegisterEvent("CHAT_MSG_SPELL_PERIODIC_CREATURE_DAMAGE") pfUI.debuffs:RegisterEvent("CHAT_MSG_SPELL_FAILED_LOCALPLAYER") pfUI.debuffs:RegisterEvent("CHAT_MSG_SPELL_SELF_DAMAGE") pfUI.debuffs:RegisterEvent("PLAYER_TARGET_CHANGED") pfUI.debuffs:RegisterEvent("UNIT_AURA") pfUI.debuffs.active = true -- CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_DAMAGE // CHAT_MSG_SPELL_PERIODIC_CREATURE_DAMAGE pfUI.debuffs.AURAADDEDOTHERHARMFUL = SanitizePattern(AURAADDEDOTHERHARMFUL) -- CHAT_MSG_SPELL_FAILED_LOCALPLAYER pfUI.debuffs.SPELLFAILCASTSELF = SanitizePattern(SPELLFAILCASTSELF) pfUI.debuffs.SPELLFAILPERFORMSELF = SanitizePattern(SPELLFAILPERFORMSELF) pfUI.debuffs.SPELLIMMUNESELFOTHER = SanitizePattern(SPELLIMMUNESELFOTHER) -- CHAT_MSG_SPELL_SELF_DAMAGE pfUI.debuffs.IMMUNEDAMAGECLASSSELFOTHER = SanitizePattern(IMMUNEDAMAGECLASSSELFOTHER) pfUI.debuffs.SPELLMISSSELFOTHER = SanitizePattern(SPELLMISSSELFOTHER) pfUI.debuffs.SPELLRESISTSELFOTHER = SanitizePattern(SPELLRESISTSELFOTHER) pfUI.debuffs.SPELLEVADEDSELFOTHER = SanitizePattern(SPELLEVADEDSELFOTHER) pfUI.debuffs.SPELLDODGEDSELFOTHER = SanitizePattern(SPELLDODGEDSELFOTHER) pfUI.debuffs.SPELLDEFLECTEDSELFOTHER = SanitizePattern(SPELLDEFLECTEDSELFOTHER) pfUI.debuffs.SPELLREFLECTSELFOTHER = SanitizePattern(SPELLREFLECTSELFOTHER) pfUI.debuffs.SPELLPARRIEDSELFOTHER = SanitizePattern(SPELLPARRIEDSELFOTHER) pfUI.debuffs.SPELLLOGABSORBSELFOTHER = SanitizePattern(SPELLLOGABSORBSELFOTHER) pfUI.debuffs.objects = {} -- Gather Data by Events pfUI.debuffs:SetScript("OnEvent", function() -- Add Combat Log if event == "CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_DAMAGE" or event == "CHAT_MSG_SPELL_PERIODIC_CREATURE_DAMAGE" then for unit, effect in string.gfind(arg1, pfUI.debuffs.AURAADDEDOTHERHARMFUL) do if UnitName("target") == unit then this:AddEffect(unit, UnitLevel("target"), effect) else this:AddEffect(unit, 0, effect) end end -- Add Missing Buffs by Iteration elseif ( event == "UNIT_AURA" and arg1 == "target" ) or event == "PLAYER_TARGET_CHANGED" then for i=1, 16 do texture, _, _ = UnitDebuff("target" , i) if texture then local effect = this:GetDebuffName("target", i) if effect ~= "" and this:GetDebuffInfo("target", effect) == 0 then this:AddEffect(UnitName("target"), UnitLevel("target"), effect) end end end -- Remove Pending Spells on Failure elseif event == "SPELLCAST_FAILED" or event == "CHAT_MSG_SPELL_FAILED_LOCALPLAYER" or event == "CHAT_MSG_SPELL_SELF_DAMAGE" then -- CHAT_MSG_SPELL_FAILED_LOCALPLAYER for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLFAILCASTSELF) do -- "You fail to cast %s: %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLFAILPERFORMSELF) do -- "You fail to perform %s: %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLIMMUNESELFOTHER) do -- "Your %s failed. %s is immune."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end -- CHAT_MSG_SPELL_SELF_DAMAGE for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLMISSSELFOTHER) do -- "Your %s was resisted by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLEVADEDSELFOTHER) do -- "Your %s was evaded by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLDODGEDSELFOTHER) do -- "Your %s was deflected by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLDODGEDSELFOTHER) do -- "Your %s was dodged by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLDEFLECTEDSELFOTHER) do -- "Your %s was deflected by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLREFLECTSELFOTHER) do -- "Your %s is reflected back by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLPARRIEDSELFOTHER) do -- "Your %s is parried by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end for effect, _ in string.gfind(arg1, pfUI.debuffs.SPELLLOGABSORBSELFOTHER) do -- "Your %s is absorbed by %s."; pfUI.debuffs:RemovePending(pfUI.debuffs.lastUnit, pfUI.debuffs.lastLevel, effect) return end end end) -- Gather Data by User Actions hooksecurefunc("CastSpell", function(id, bookType) local effect = GetSpellName(id, bookType) pfUI.debuffs:AddPending(UnitName("target"), UnitLevel("target"), effect) end, true) hooksecurefunc("CastSpellByName", function(effect, target) pfUI.debuffs:AddPending(UnitName("target"), UnitLevel("target"), effect) end, true) local scanner = CreateFrame("GameTooltip", "pfDebuffSpellScanner", nil, "GameTooltipTemplate") scanner:SetOwner(WorldFrame, "ANCHOR_NONE") hooksecurefunc("UseAction", function(slot, target, button) if GetActionText(slot) or not IsCurrentAction(slot) then return end scanner:ClearLines() scanner:SetAction(slot) local effect = pfDebuffSpellScannerTextLeft1:GetText() pfUI.debuffs:AddPending(UnitName("target"), UnitLevel("target"), effect) end, true) function pfUI.debuffs:RemovePending(unit, unitlevel, effect) if unit and unitlevel and effect then if pfUI.debuffs.objects[unit] and pfUI.debuffs.objects[unit][unitlevel] and pfUI.debuffs.objects[unit][unitlevel][effect] and pfUI.debuffs.objects[unit][unitlevel][effect].old and pfUI.debuffs.objects[unit][unitlevel][effect].old.start then local new = floor(pfUI.debuffs.objects[unit][unitlevel][effect].start + pfUI.debuffs.objects[unit][unitlevel][effect].duration - GetTime()) local saved = floor(pfUI.debuffs.objects[unit][unitlevel][effect].old.start + pfUI.debuffs.objects[unit][unitlevel][effect].old.duration - GetTime()) pfUI.debuffs.objects[unit][unitlevel][effect].start = pfUI.debuffs.objects[unit][unitlevel][effect].old.start pfUI.debuffs.objects[unit][unitlevel][effect].duration = pfUI.debuffs.objects[unit][unitlevel][effect].old.duration pfUI.debuffs.objects[unit][unitlevel][effect].old = {} if pfUI.uf.target then pfUI.uf:RefreshUnit(pfUI.uf.target, "aura") end end end end function pfUI.debuffs:AddPending(unit, unitlevel, effect) if not unit then return end if not L["debuffs"][effect] then return end unitlevel = unitlevel or 0 --message("add pending effect " .. unit .. "(" .. unitlevel .. ") - " .. effect) if not pfUI.debuffs.objects[unit] then pfUI.debuffs.objects[unit] = {} end if not pfUI.debuffs.objects[unit][unitlevel] then pfUI.debuffs.objects[unit][unitlevel] = {} end if not pfUI.debuffs.objects[unit][unitlevel][effect] then pfUI.debuffs.objects[unit][unitlevel][effect] = {} end if pfUI.debuffs.objects[unit][unitlevel][effect].old and pfUI.debuffs.objects[unit][unitlevel][effect].old.start then --message("already pending") return end -- save old values in case of failure pfUI.debuffs.objects[unit][unitlevel][effect].old = {} pfUI.debuffs.objects[unit][unitlevel][effect].old.start = pfUI.debuffs.objects[unit][unitlevel][effect].start pfUI.debuffs.objects[unit][unitlevel][effect].old.duration = pfUI.debuffs.objects[unit][unitlevel][effect].duration -- set new ones pfUI.debuffs.objects[unit][unitlevel][effect].start = GetTime() pfUI.debuffs.objects[unit][unitlevel][effect].duration = L["debuffs"][effect] or 0 -- save last unit pfUI.debuffs.lastUnit = unit pfUI.debuffs.lastLevel = unitlevel if pfUI.uf.target then pfUI.uf:RefreshUnit(pfUI.uf.target, "aura") end end function pfUI.debuffs:AddEffect(unit, unitlevel, effect) if not unit or not effect then return end unitlevel = unitlevel or 0 if not pfUI.debuffs.objects[unit] then pfUI.debuffs.objects[unit] = {} end if not pfUI.debuffs.objects[unit][unitlevel] then pfUI.debuffs.objects[unit][unitlevel] = {} end if not pfUI.debuffs.objects[unit][unitlevel][effect] then pfUI.debuffs.objects[unit][unitlevel][effect] = {} end pfUI.debuffs.objects[unit][unitlevel][effect].old = {} pfUI.debuffs.objects[unit][unitlevel][effect].start = GetTime() pfUI.debuffs.objects[unit][unitlevel][effect].duration = L["debuffs"][effect] or 0 if pfUI.uf.target then pfUI.uf:RefreshUnit(pfUI.uf.target, "aura") end end -- [[ global debuff functions ]] -- function pfUI.debuffs:GetDebuffName(unit, index) pfUI.debuffs.pfDebuffNameScan:SetOwner(UIParent, "ANCHOR_NONE") pfUI.debuffs.pfDebuffNameScan:SetUnitDebuff(unit, index) local text = getglobal("pfDebuffNameScanTextLeft1") return ( text ) and text:GetText() or "" end function pfUI.debuffs:GetDebuffInfo(unit, effect) local unitname = UnitName(unit) local unitlevel = UnitLevel(unit) if pfUI.debuffs.objects[unitname] and pfUI.debuffs.objects[unitname][unitlevel] and pfUI.debuffs.objects[unitname][unitlevel][effect] then -- clean up db if pfUI.debuffs.objects[unitname][unitlevel][effect].duration + pfUI.debuffs.objects[unitname][unitlevel][effect].start < GetTime() then pfUI.debuffs.objects[unitname][unitlevel][effect] = nil return 0, 0, 0 end local start = pfUI.debuffs.objects[unitname][unitlevel][effect].start local duration = pfUI.debuffs.objects[unitname][unitlevel][effect].duration local timeleft = duration + start - GetTime() return start, duration, timeleft -- no level data elseif pfUI.debuffs.objects[unitname] and pfUI.debuffs.objects[unitname][0] and pfUI.debuffs.objects[unitname][0][effect] then -- clean up db if pfUI.debuffs.objects[unitname][0][effect].duration + pfUI.debuffs.objects[unitname][0][effect].start < GetTime() then pfUI.debuffs.objects[unitname][0][effect] = nil return 0, 0, 0 end local start = pfUI.debuffs.objects[unitname][0][effect].start local duration = pfUI.debuffs.objects[unitname][0][effect].duration local timeleft = duration + start - GetTime() return start, duration, timeleft else return 0, 0, 0 end end end)
mit
sundream/gamesrv
script/card/neutral/card164003.lua
1
2210
--<<card 导表开始>> local super = require "script.card.init" ccard164003 = class("ccard164003",super,{ sid = 164003, race = 6, name = "狼人渗透者", type = 201, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 0, dieeffect = 0, sneak = 1, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 2, maxhp = 1, crystalcost = 1, targettype = 0, halo = nil, desc = "潜行", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard164003:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard164003:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard164003:save() local data = super.save(self) -- todo: save data return data end return ccard164003
gpl-2.0
tltneon/NutScript
gamemode/core/derma/cl_dev_icon.lua
2
12374
ICON_INFO = ICON_INFO or {} ICON_INFO.camPos = ICON_INFO.camPos or Vector() ICON_INFO.camAng = ICON_INFO.camAng or Angle() ICON_INFO.FOV = ICON_INFO.FOV or 50 ICON_INFO.w = ICON_INFO.w or 1 ICON_INFO.h = ICON_INFO.h or 1 ICON_INFO.modelAng = ICON_INFO.modelAng or Angle() ICON_INFO.modelName = ICON_INFO.modelName or "models/Items/grenadeAmmo.mdl" ICON_INFO.outline = ICON_INFO.outline or false ICON_INFO.outlineColor = ICON_INFO.outlineColor or Color(255, 255, 255) local vTxt = "xyz" local aTxt = "pyr" local bTxt = { "best", "full", "above", "right", "origin", } local PANEL = {} local iconSize = 64 /* 3D ICON PREVIEW WINDOW */ function PANEL:Init() self:SetPos(50, 50) self:ShowCloseButton(false) self:SetTitle("RENDER PREVIEW") self.model = self:Add("DModelPanel") self.model:SetPos(5, 22) function self.model:PaintOver(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end function self.model:LayoutEntity() end self:AdjustSize(ICON_INFO.w, ICON_INFO.h) end function PANEL:Paint(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end function PANEL:AdjustSize(x, y) self:SetSize(10 + (x or 1)*64, 27 + (y or 1)*64) self.model:SetSize((x or 1)*64, (y or 1)*64) end vgui.Register("iconPreview", PANEL, "DFrame") /* RENDER ICON PREVIEW */ PANEL = {} AccessorFunc( PANEL, "m_strModel", "Model" ) AccessorFunc( PANEL, "m_pOrigin", "Origin" ) AccessorFunc( PANEL, "m_bCustomIcon", "CustomIcon" ) function PANEL:Init() self:SetPos(50, 300) self:ShowCloseButton(false) self:SetTitle("PREVIEW") self.model = self:Add("SpawnIcon") self.model:InvalidateLayout(true) self.model:SetPos(5, 22) function self.model:PaintOver(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end self.model.Icon:SetVisible(false) self.model.Paint = function(self, x, y) local exIcon = ikon:getIcon("iconEditor") if (exIcon) then surface.SetMaterial(exIcon) surface.SetDrawColor(color_white) surface.DrawTexturedRect(0, 0, x, y) end end self:AdjustSize(ICON_INFO.w, ICON_INFO.h) end function PANEL:Paint(w, h) surface.SetDrawColor(255, 255, 255) surface.DrawOutlinedRect(0, 0, w, h) end function PANEL:AdjustSize(x, y) self:SetSize(10 + (x or 1)*64, 27 + (y or 1)*64) self.model:SetSize((x or 1)*64, (y or 1)*64) end vgui.Register("iconRenderPreview", PANEL, "DFrame") /* EDITOR FUNCTION */ local function action(self) local p1 = self.prev local p = self.prev2 local icon = p.model local iconModel = p1.model local ent = iconModel:GetEntity() local tab = {} tab.ent = ent tab.cam_pos = iconModel:GetCamPos() tab.cam_ang = iconModel:GetLookAng() tab.cam_fov = iconModel:GetFOV() local text = "ITEM.model = \""..ICON_INFO.modelName:gsub("\\", "/"):lower().."\"" .. "\n".. "ITEM.width = "..ICON_INFO.w .."\n".. "ITEM.height = "..ICON_INFO.h .."\n".. "ITEM.iconCam = {" .."\n".. "\tpos = Vector("..tab.cam_pos.x..", "..tab.cam_pos.y..", "..tab.cam_pos.z..")" .."\n".. "\tang = Angle("..tab.cam_ang.p..", "..tab.cam_ang.y..", "..tab.cam_ang.r..")" .."\n".. "\tfov = "..tab.cam_fov .. "," .."\n" if (ICON_INFO.outline) then text = text .. "\toutline = true," .. "\n" .. "\toutlineColor = Color(".. ICON_INFO.outlineColor.r .. ", " .. ICON_INFO.outlineColor.g .. ", " .. ICON_INFO.outlineColor.b .. ")" .. "\n" end text = text .. "}" SetClipboardText(text) end local function renderAction(self) local p1 = self.prev local p = self.prev2 local icon = p.model local iconModel = p1.model if (icon and iconModel) then local ent = iconModel:GetEntity() local tab = {} tab.ent = ent tab.cam_pos = iconModel:GetCamPos() tab.cam_ang = iconModel:GetLookAng() tab.cam_fov = iconModel:GetFOV() icon:SetModel(ent:GetModel()) ikon:renderIcon( "iconEditor", ICON_INFO.w, ICON_INFO.h, ICON_INFO.modelName, { pos = ICON_INFO.camPos, ang = ICON_INFO.camAng, fov = ICON_INFO.FOV, outline = ICON_INFO.outline, outlineColor = ICON_INFO.outlineColor }, true ) local text = "ITEM.model = \""..ICON_INFO.modelName:gsub("\\", "/"):lower().."\"" .. "\n".. "ITEM.width = "..ICON_INFO.w .."\n".. "ITEM.height = "..ICON_INFO.h .."\n".. "ITEM.iconCam = {" .."\n".. "\tpos = Vector("..tab.cam_pos.x..", "..tab.cam_pos.y..", "..tab.cam_pos.z..",)" .."\n".. "\tang = Angle("..tab.cam_ang.p..", "..tab.cam_ang.y..", "..tab.cam_ang.r..",)" .."\n".. "\tfov = "..tab.cam_fov .. "," .."\n" if (ICON_INFO.outline) then text = text .. "\toutline = true," .. "\n" .. "\toutlineColor = Color(".. ICON_INFO.outlineColor.r .. ", " .. ICON_INFO.outlineColor.g .. ", " .. ICON_INFO.outlineColor.b .. ")" .. "\n" end text = text .. "}" print(text) end end PANEL = {} function PANEL:Init() if (editorPanel and editorPanel:IsVisible()) then editorPanel:Close() end editorPanel = self self:SetTitle("MODEL ADJUST") self:MakePopup() self:SetSize(400, ScrH()*.8) self:Center() self.prev = vgui.Create("iconPreview") self.prev2 = vgui.Create("iconRenderPreview") self.list = self:Add("DScrollPanel") self.list:Dock(FILL) self:AddText("Actions") self.render = self.list:Add("DButton") self.render:Dock(TOP) self.render:SetFont("ChatFont") self.render:SetText("RENDER") self.render:SetTall(30) self.render:DockMargin(5, 5, 5, 0) self.render.DoClick = function() renderAction(self) end self.copy = self.list:Add("DButton") self.copy:Dock(TOP) self.copy:SetFont("ChatFont") self.copy:SetText("COPY") self.copy:SetTall(30) self.copy:DockMargin(5, 5, 5, 0) self.copy.DoClick = function() action(self) end self:AddText("Presets") for i = 1, 5 do local btn = self.list:Add("DButton") btn:Dock(TOP) btn:SetFont("ChatFont") btn:SetText(bTxt[i]) btn:SetTall(30) btn:DockMargin(5, 5, 5, 0) btn.DoClick = function() self:SetupEditor(true, i) self:UpdateShits() end end self:AddText("Model Name") self.mdl = self.list:Add("DTextEntry") self.mdl:Dock(TOP) self.mdl:SetFont("Default") self.mdl:SetText("Copy that :)") self.mdl:SetTall(25) self.mdl:DockMargin(5, 5, 5, 0) self.mdl.OnEnter = function() ICON_INFO.modelName = self.mdl:GetValue() self:SetupEditor(true) self:UpdateShits() end self:AddText("Icon Size") local cfg = self.list:Add("DNumSlider") cfg:Dock(TOP) cfg:SetText("W") cfg:SetMin(0) cfg:SetMax(10) cfg:SetDecimals(0) cfg:SetValue(ICON_INFO.w) cfg:DockMargin(10, 0, 0, 5) cfg.OnValueChanged = function(cfg, value) ICON_INFO.w = value self.prev:AdjustSize(ICON_INFO.w, ICON_INFO.h) self.prev2:AdjustSize(ICON_INFO.w, ICON_INFO.h) end local cfg = self.list:Add("DNumSlider") cfg:Dock(TOP) cfg:SetText("H") cfg:SetMin(0) cfg:SetMax(10) cfg:SetDecimals(0) cfg:SetValue(ICON_INFO.h) cfg:DockMargin(10, 0, 0, 5) cfg.OnValueChanged = function(cfg, value) print(self) ICON_INFO.h = value self.prev:AdjustSize(ICON_INFO.w, ICON_INFO.h) self.prev2:AdjustSize(ICON_INFO.w, ICON_INFO.h) end self:AddText("Camera FOV") self.camFOV = self.list:Add("DNumSlider") self.camFOV:Dock(TOP) self.camFOV:SetText("CAMFOV") self.camFOV:SetMin(0) self.camFOV:SetMax(180) self.camFOV:SetDecimals(3) self.camFOV:SetValue(ICON_INFO.FOV) self.camFOV:DockMargin(10, 0, 0, 5) self.camFOV.OnValueChanged = function(cfg, value) if (!fagLord) then ICON_INFO.FOV = value local p = self.prev if (p and p:IsVisible()) then p.model:SetFOV(ICON_INFO.FOV) end end end self:AddText("Camera Position") self.camPos = {} for i = 1, 3 do self.camPos[i] = self.list:Add("DNumSlider") self.camPos[i]:Dock(TOP) self.camPos[i]:SetText("CAMPOS_" .. vTxt[i]) self.camPos[i]:SetMin(-500) self.camPos[i]:SetMax(500) self.camPos[i]:SetDecimals(3) self.camPos[i]:SetValue(ICON_INFO.camPos[i]) self.camPos[i]:DockMargin(10, 0, 0, 5) self.camPos[i].OnValueChanged = function(cfg, value) if (!fagLord) then ICON_INFO.camPos[i] = value end end end self:AddText("Camera Angle") self.camAng = {} for i = 1, 3 do self.camAng[i] = self.list:Add("DNumSlider") self.camAng[i]:Dock(TOP) self.camAng[i]:SetText("CAMANG_" .. aTxt[i]) self.camAng[i]:SetMin(-180) self.camAng[i]:SetMax(180) self.camAng[i]:SetDecimals(3) self.camAng[i]:SetValue(ICON_INFO.camAng[i]) self.camAng[i]:DockMargin(10, 0, 0, 5) self.camAng[i].OnValueChanged = function(cfg, value) if (!fagLord) then ICON_INFO.camAng[i] = value end end end local aaoa = self.list:Add("DPanel") aaoa:Dock(TOP) aaoa:DockMargin(10, 0, 0, 5) aaoa:SetHeight(250) self.color = aaoa:Add("DCheckBoxLabel") self.color:SetText("Draw Outline?") self.color:SetValue(ICON_INFO.outline) self.color:DockMargin(10, 5, 0, 5) self.color:Dock(TOP) function self.color:OnChange(bool) ICON_INFO.outline = bool end self.colormixer = aaoa:Add( "DColorMixer" ) self.colormixer:Dock( FILL ) --Make self.colormixer fill place of Frame self.colormixer:SetPalette( true ) --Show/hide the palette DEF:true self.colormixer:SetAlphaBar( false ) --Show/hide the alpha bar DEF:true self.colormixer:SetWangs( true ) --Show/hide the R G B A indicators DEF:true self.colormixer:SetColor( ICON_INFO.outlineColor ) --Set the default color self.colormixer:DockMargin(10, 5, 0, 5) function self.colormixer:ValueChanged(value) ICON_INFO.outlineColor = value end self:SetupEditor() self:UpdateShits(true) end function PANEL:UpdateShits() fagLord = true self.camFOV:SetValue(ICON_INFO.FOV) for i = 1, 3 do self.camPos[i]:SetValue(ICON_INFO.camPos[i]) self.camAng[i]:SetValue(ICON_INFO.camAng[i]) end fagLord = false end function PANEL:SetupEditor(update, mode) local p = self.prev local p2 = self.prev2 if (p and p:IsVisible() and p2 and p2:IsVisible()) then p.model:SetModel(ICON_INFO.modelName) p2.model:SetModel(ICON_INFO.modelName) if (!update) then self.mdl:SetText(ICON_INFO.modelName) end if (mode) then if (mode == 1) then self:BestGuessLayout() elseif (mode == 2) then self:FullFrontalLayout() elseif (mode == 3) then self:AboveLayout() elseif (mode == 4) then self:RightLayout() elseif (mode == 5) then self:OriginLayout() end else self:BestGuessLayout() end p.model:SetCamPos(ICON_INFO.camPos) p.model:SetFOV(ICON_INFO.FOV) p.model:SetLookAng(ICON_INFO.camAng) end end function PANEL:BestGuessLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local tab = PositionSpawnIcon(ent, pos) if ( tab ) then ICON_INFO.camPos = tab.origin ICON_INFO.FOV = tab.fov ICON_INFO.camAng = tab.angles end end function PANEL:FullFrontalLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( -200, 0, 0 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = (campos * -1):Angle() end function PANEL:AboveLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( 0, 0, 200 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = (campos * -1):Angle() end function PANEL:RightLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( 0, 200, 0 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = (campos * -1):Angle() end function PANEL:OriginLayout() local p = self.prev local ent = p.model:GetEntity() local pos = ent:GetPos() local campos = pos + Vector( 0, 0, 0 ) ICON_INFO.camPos = campos ICON_INFO.FOV = 45 ICON_INFO.camAng = Angle( 0, -180, 0 ) end function PANEL:AddText(str) local label = self.list:Add("DLabel") label:SetFont("ChatFont") label:SetTextColor(color_white) label:Dock(TOP) label:DockMargin(5, 5, 5, 0) label:SetContentAlignment(5) label:SetText(str) end function PANEL:OnRemove() if (self.prev and self.prev:IsVisible()) then self.prev:Close() end if (self.prev2 and self.prev2:IsVisible()) then self.prev2:Close() end end vgui.Register("iconEditor", PANEL, "DFrame") concommand.Add("nut_dev_icon", function() if (LocalPlayer():IsAdmin()) then vgui.Create("iconEditor") end end)
mit
sundream/gamesrv
script/card/golden/card214004.lua
1
2282
--<<card 导表开始>> local super = require "script.card.golden.card114004" ccard214004 = class("ccard214004",super,{ sid = 214004, race = 1, name = "法力浮龙", type = 201, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 1, maxhp = 3, crystalcost = 1, targettype = 0, halo = nil, desc = "每当你施放一个法术时,便获得+1攻击力", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = {addbuff={addatk=1}}, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard214004:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard214004:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard214004:save() local data = super.save(self) -- todo: save data return data end return ccard214004
gpl-2.0
gsingh93/ipscanner
app/src/main/assets/nmap/share/nmap/nselib/imap.lua
2
9379
--- -- A library implementing a minor subset of the IMAP protocol, currently the -- CAPABILITY, LOGIN and AUTHENTICATE functions. The library was initially -- written by Brandon Enright and later extended and converted to OO-form by -- Patrik Karlsson <patrik@cqure.net> -- -- The library consists of a <code>Helper</code>, class which is the main -- interface for script writers, and the <code>IMAP</code> class providing -- all protocol-level functionality. -- -- The following example illustrates the reommended use of the library: -- <code> -- local helper = imap.Helper:new(host, port) -- helper:connect() -- helper:login("user","password","PLAIN") -- helper:close() -- </code> -- -- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html -- @author = "Brandon Enright, Patrik Karlsson" -- Version 0.2 -- Revised 07/15/2011 - v0.2 - added the IMAP and Helper classes -- added support for LOGIN and AUTHENTICATE -- <patrik@cqure.net> module(... or "imap", package.seeall) require 'stdnse' require 'comm' require 'base64' require 'sasl' IMAP = { --- Creates a new instance of the IMAP class -- -- @param host table as received by the script action method -- @param port table as received by the script action method -- @param options table containing options, currently -- <code>timeout<code> - number containing the seconds to wait for -- a response new = function(self, host, port, options) local o = { host = host, port = port, counter = 1, timeout = ( options and options.timeout ) or 10000 } setmetatable(o, self) self.__index = self return o end, --- Receives a response from the IMAP server -- -- @return status true on success, false on failure -- @return data string containing the received data receive = function(self) local data = "" repeat local status, tmp = self.socket:receive_buf("\r\n", false) if( not(status) ) then return false, tmp end data = data .. tmp until( tmp:match(("^A%04d"):format(self.counter - 1)) or tmp:match("^%+")) return true, data end, --- Sends a request to the IMAP server -- -- @param cmd string containing the command to send to the server eg. -- eg. (AUTHENTICATE, LOGIN) -- @param params string containing the command parameters -- @return true on success, false on failure -- @return err string containing the error if status was false send = function(self, cmd, params) local data if ( not(params) ) then data = ("A%04d %s\r\n"):format(self.counter, cmd) else data = ("A%04d %s %s\r\n"):format(self.counter, cmd, params) end local status, err = self.socket:send(data) if ( not(status) ) then return false, err end self.counter = self.counter + 1 return true end, --- Connect to the server -- -- @return status true on success, false on failure -- @return banner string containing the server banner connect = function(self) local socket, banner, opt = comm.tryssl( self.host, self.port, "", { recv_before = true } ) if ( not(socket) ) then return false, "ERROR: Failed to connect to server" end socket:set_timeout(self.timeout) if ( not(socket) or not(banner) ) then return false, "ERROR: Failed to connect to server" end self.socket = socket return true, banner end, --- Authenticate to the server (non PLAIN text mode) -- Currently supported algorithms are CRAM-MD5 and CRAM-SHA1 -- -- @param username string containing the username -- @param pass string containing the password -- @param mech string containing a authentication mechanism, currently -- CRAM-MD5 or CRAM-SHA1 -- @return status true if login was successful, false on failure -- @return err string containing the error message if status was false authenticate = function(self, username, pass, mech) assert( mech == "NTLM" or mech == "DIGEST-MD5" or mech == "CRAM-MD5" or mech == "PLAIN", "Unsupported authentication mechanism") local status, err = self:send("AUTHENTICATE", mech) if( not(status) ) then return false, "ERROR: Failed to send data" end local status, data = self:receive() if( not(status) ) then return false, "ERROR: Failed to receive challenge" end if ( mech == "NTLM" ) then -- sniffed of the wire, seems to always be the same -- decodes to some NTLMSSP blob greatness status, data = self.socket:send("TlRMTVNTUAABAAAAB7IIogYABgA3AAAADwAPACgAAAAFASgKAAAAD0FCVVNFLUFJUi5MT0NBTERPTUFJTg==\r\n") if ( not(status) ) then return false, "ERROR: Failed to send NTLM packet" end status, data = self:receive() if ( not(status) ) then return false, "ERROR: Failed to receieve NTLM challenge" end end if ( data:match(("^A%04d "):format(self.counter-1)) ) then return false, "ERROR: Authentication mechanism not supported" end local digest, auth_data if ( not(data:match("^+")) ) then return false, "ERROR: Failed to receive proper response from server" end data = base64.dec(data:match("^+ (.*)")) -- All mechanisms expect username and pass -- add the otheronce for those who need them local mech_params = { username, pass, data, "imap" } auth_data = sasl.Helper:new(mech):encode(unpack(mech_params)) auth_data = base64.enc(auth_data) .. "\r\n" status, data = self.socket:send(auth_data) if( not(status) ) then return false, "ERROR: Failed to send data" end status, data = self:receive() if( not(status) ) then return false, "ERROR: Failed to receive data" end if ( mech == "DIGEST-MD5" ) then local rspauth = data:match("^+ (.*)") if ( rspauth ) then rspauth = base64.dec(rspauth) status, data = self.socket:send("\r\n") status, data = self:receive() end end if ( data:match(("^A%04d OK"):format(self.counter - 1)) ) then return true end return false, "Login failed" end, --- Login to the server using PLAIN text authentication -- -- @param username string containing the username -- @param password string containing the password -- @return status true on success, false on failure -- @return err string containing the error message if status was false login = function(self, username, password) local status, err = self:send("LOGIN", ("\"%s\" \"%s\""):format(username, password)) if( not(status) ) then return false, "ERROR: Failed to send data" end local status, data = self:receive() if( not(status) ) then return false, "ERROR: Failed to receive data" end if ( data:match(("^A%04d OK"):format(self.counter - 1)) ) then return true end return false, "Login failed" end, --- Retrieves a list of server capabilities (eg. supported authentication -- mechanisms, QUOTA, UIDPLUS, ACL ...) -- -- @return status true on success, false on failure -- @return capas array containing the capabilities that are supported capabilities = function(self) local capas = {} local proto = (self.port.version and self.port.version.service_tunnel == "ssl" and "ssl") or "tcp" local status, err = self:send("CAPABILITY") if( not(status) ) then return false, err end local status, line = self:receive() if (not(status)) then capas.CAPABILITY = false else while status do if ( line:match("^%*%s+CAPABILITY") ) then line = line:gsub("^%*%s+CAPABILITY", "") for capability in line:gmatch("[%w%+=-]+") do capas[capability] = true end break end status, line = self.socket:receive() end end return true, capas end, --- Closes the connection to the IMAP server -- @return true on success, false on failure close = function(self) return self.socket:close() end } -- The helper class, that servers as interface to script writers Helper = { -- @param host table as received by the script action method -- @param port table as received by the script action method -- @param options table containing options, currently -- <code>timeout<code> - number containing the seconds to wait for -- a response new = function(self, host, port, options) local o = { client = IMAP:new( host, port, options ) } setmetatable(o, self) self.__index = self return o end, --- Connects to the IMAP server -- @return status true on success, false on failure connect = function(self) return self.client:connect() end, --- Login to the server using eithe plain-text or using the authentication -- mechanism provided in the mech argument. -- -- @param username string containing the username -- @param password string containing the password -- @param mech [optional] containing the authentication mechanism to use -- @return status true on success, false on failure login = function(self, username, password, mech) if ( not(mech) or mech == "LOGIN" ) then return self.client:login(username, password) else return self.client:authenticate(username, password, mech) end end, --- Retrieves a list of server capabilities (eg. supported authentication -- mechanisms, QUOTA, UIDPLUS, ACL ...) -- -- @return status true on success, false on failure -- @return capas array containing the capabilities that are supported capabilities = function(self) return self.client:capabilities() end, --- Closes the connection to the IMAP server -- @return true on success, false on failure close = function(self) return self.client:close() end, }
mit
ibuler/ngx_lua_waf
test2.lua
1
1275
-- -- Created by IntelliJ IDEA. -- User: guang -- Date: 16/9/22 -- Time: 下午6:25 -- To change this template use File | Settings | File Templates. -- --local lua_waf = require "core" local lua_waf = require "test" local waf = lua_waf:new("test") local _cidr_cache = {} print(waf.name) local iputils = require "iputils" function cidr_match(ip, cidr_pattern) local t = {} local n = 1 if (type(cidr_pattern) ~= "table") then cidr_pattern = { cidr_pattern } end for _, v in ipairs(cidr_pattern) do -- try to grab the parsed cidr from out module cache local cidr = _cidr_cache[v] -- if it wasn't there, compute and cache the value if (not cidr) then local lower, upper = iputils.parse_cidr(v) cidr = { lower, upper } _cidr_cache[v] = cidr end t[n] = cidr n = n + 1 end return iputils.ip_in_cidrs(ip, t), ip end a = cidr_match('192.168.128.230', {'192.168.128.0/24', '127.0.0.1'}) print(a) a = cidr_match('172.16.1.1', {'172.16.1.2'}) print(a) --for k, v in pairs(waf["config"]) do -- print(k, v) --end -- --waf:set_option("active", true) -- --for k, v in pairs(waf["config"]) do -- pritt(k, v) --end --print(waf.config.active) -- -- waf:deny_cc() -- waf2:deny_cc() --waf:log("hello world") --waf2:log("world") --waf:get_name()
apache-2.0
NelsonCrosby/ncedit
lua/async.lua
1
1481
local Async = new.class() function Async:init() self.q = {} end -- Run event loop function Async:begin() while #(self.q) > 0 do -- Loop through queue -- Loop must be resistant to mutation local i = 1 while i <= #(self.q) do -- Resume next coroutine local co = self.q[i] local status, msg = coroutine.resume(co) -- Handle possible error if not status then error(msg) -- TODO: Some better form of error handling end if coroutine.status(co) == 'dead' then table.remove(self.q, i) -- Current i is now next coro in queue else -- Advance to next coro in queue i = i + 1 end end -- Finished this round through the queue end -- Queue is emptied end -- Add a coroutine to event queue -- If a function is passed a coroutine -- will be created from it. function Async:addfunc(f) if type(f) == 'function' then f = coroutine.create(f) end if type(f) == 'thread' then table.insert(self.q, f) else error('cannot add ' .. type(f) .. ' ' .. f .. ' to event loop') end end -- For simplicity, instances can be called -- directly to add to the queue Async.__call = Async.addfunc -- This module's export will be an instance, -- ready to use as local async = require('async') return new(Async)
mit
Lynx3d/tinker_tools
UI/Measurements_UI.lua
2
7441
local Dta = select(2, ...) Dta.measurements_ui = {} ------------------------------- -- BUILD THE DIMENSIONTOOLS MeasurementsWINDOW ------------------------------- local MeasurementsWindowSettings = { WIDTH = 315, HEIGHT = 190, CLOSABLE = true, MOVABLE = true, POS_X = "MeasurementswindowPosX", POS_Y = "MeasurementswindowPosY" } function Dta.measurements_ui.buildWindow() local x = Dta.settings.get("MeasurementswindowPosX") local y = Dta.settings.get("MeasurementswindowPosY") local newWindow = Dta.ui.Window.Create("MeasurementsWindow", Dta.ui.context, Dta.Locale.Titles.OffsetCalc, MeasurementsWindowSettings.WIDTH, MeasurementsWindowSettings.HEIGHT, x, y, MeasurementsWindowSettings.CLOSABLE, MeasurementsWindowSettings.MOVABLE, Dta.measurements_ui.hideWindow, Dta.ui.WindowMoved ) newWindow.settings = MeasurementsWindowSettings local Measurementswindow = newWindow.content Measurementswindow.background2 = UI.CreateFrame("Texture", "MeasurementsVindowBackground2", Measurementswindow) Measurementswindow.background2:SetPoint("BOTTOMCENTER", Measurementswindow, "BOTTOMCENTER") Measurementswindow.background2:SetWidth(MeasurementsWindowSettings.WIDTH) Measurementswindow.background2:SetHeight(80) Measurementswindow.background2:SetAlpha(0.3) Measurementswindow.background2:SetTexture("Rift", "dimensions_tools_header.png.dds") Measurementswindow.background2:SetLayer(5) ------------------------------- -- Offset Calc Inputs ------------------------------- local measure = Dta.ui.createFrame("Measurements", Measurementswindow, 10, 5, Measurementswindow:GetWidth()-20, Measurementswindow:GetHeight()-20) measure:SetLayer(30) --Measurementswindow.modifyRotation:SetBackgroundColor(1, 0, 0, 0.5) --Debug measure.TypeLabel = Dta.ui.createText("MeasurementsTypeLabel", measure, 0, 0, Dta.Locale.Text.Type, 14) measure.TypeLoad = Dta.ui.createDropdown("MeasurementsTypeLoad", measure, 90, 0, 180) measure.TypeLoad:SetItems(Dta.Locale.Menus.ItemType) measure.TypeLoad.Event.ItemSelect = Dta.measurements_ui.ShapeChanged measure.OrientationLabel = Dta.ui.createText("MeasurementsOrientationLabel", measure, 0, 25, Dta.Locale.Text.Orientation, 14) measure.OrientationLoad = Dta.ui.createDropdown("MeasurementsOrientationLoad", measure, 90, 25, 180) measure.OrientationLoad:SetItems(Dta.Locale.Menus.Orientation) measure.OrientationLoad.Event.ItemSelect = Dta.measurements_ui.OrientationChanged measure.SizeLabel = Dta.ui.createText("MeasurementsSizeLabel", measure, 0, 50, Dta.Locale.Text.Scale, 14) measure.Size = Dta.ui.createTextfield("MeasurementsSize", measure, 90, 50, 50) measure.SizeHint = Dta.ui.createText("MeasurementsSizeHint", measure, 150, 50, "", 14) measure.MultiLabel = Dta.ui.createText("MeasurementsMultiLabel", measure, 0, 75, Dta.Locale.Text.Multiplier, 14) measure.Multi = Dta.ui.createTextfield("MeasurementsMulti", measure, 90, 75, 50) measure.Calculate = Dta.ui.createButton("MeasurementsCalculate", measure, 0, 145, nil, nil, Dta.Locale.Buttons.Calculate, nil, Dta.measurements.CalculationsClicked) measure.Detect = Dta.ui.createButton("MeasurementsDetect", measure, 135, 145, nil, nil, Dta.Locale.Buttons.Detect, nil, Dta.measurements.DetectClicked) measure.TransferBtn = Dta.ui.Button.Create("MeasurementsTransfer", measure, Dta.measurements.TogglePopup, "DimensionWindow_I107.dds", "DimensionWindow_I109.dds", "DimensionWindow_I10B.dds", "DimensionWindow_I10D.dds") measure.TransferBtn:SetWidth(32) measure.TransferBtn:SetHeight(32) measure.TransferBtn:SetPoint("TOPLEFT", measure, "TOPLEFT", 275, 145) measure.Divider1 = Dta.ui.createTexture("MeasurementsDivider1", measure, "Rift", "divider_06.png.dds", 0, 100, measure:GetWidth()) measure.xLabel = Dta.ui.createText("MeasurementsXLabel", measure, 0, 120, "X", 16, {1, 0, 0, 1}) measure.yLabel = Dta.ui.createText("MeasurementsYLabel", measure, 100, 120, "Y", 16, {0, 1, 0, 1}) measure.zLabel = Dta.ui.createText("MeasurementsZLabel", measure, 200, 120, "Z", 16, {0, 1, 1, 1}) measure.x = Dta.ui.createText("MeasurementsX", measure, 25, 120, "-", 16) measure.y = Dta.ui.createText("MeasurementsY", measure, 125, 120, "-", 16) measure.z = Dta.ui.createText("MeasurementsZ", measure, 225, 120, "-", 16) -- "abuse" cycle function for clearing input focus on 'return' key Measurementswindow:EventAttach(Event.UI.Input.Key.Down.Dive, Dta.ui.FocusCycleCallback, "Measurementswindow_TabFocusCycle") -- TODO: temp fix for new window hierarchy newWindow.Measurements = measure newWindow.TransferPopup = Dta.measurements_ui.buildTransferPopup(Measurementswindow) newWindow.TransferPopup:ClearPoint("TOPLEFT") newWindow.TransferPopup:SetPoint("BOTTOMLEFT", Measurementswindow, "BOTTOMRIGHT", 10, 0) return newWindow end function Dta.measurements_ui.buildTransferPopup(parent) local popup = Dta.ui.Window.CreatePopup("Xfer popup", parent, 200, 180, 0, 0, false) popup:SetVisible(false) popup.Title = Dta.ui.createText("Xfer Title", popup, 20, 10, Dta.Locale.Titles.TransferValues , 16) popup.ToMove = Dta.ui.createCheckbox("ToMove", popup, 20, 40, Dta.Locale.Buttons.MoveWindow) popup.ToCopa = Dta.ui.createCheckbox("ToCopa", popup, 20, 65, Dta.Locale.Buttons.CopyPaste) popup.x = Dta.ui.createCheckbox("XferX", popup, 20, 90, "X", true, {1, 0, 0, 1}) popup.y = Dta.ui.createCheckbox("XferY", popup, 60, 90, "Y", true, {0, 1, 0, 1}) popup.z = Dta.ui.createCheckbox("XferZ", popup, 100, 90, "Z", true, {0, 1, 1, 1}) popup.Invert = Dta.ui.createCheckbox("XferInvert", popup, 20, 115, Dta.Locale.Text.Invert) popup.Transfer = Dta.ui.createButton("Transfer", popup, 30, 140, nil, nil, Dta.Locale.Buttons.Transfer, nil, Dta.measurements.TransferClicked) return popup end function Dta.measurements_ui.OrientationChanged(self, entry, value, index) local Measurement_UI = Dta.Tools.Offset.window.Measurements if index == 7 then -- Selection Delta Measurement_UI.TypeLabel:SetAlpha(0.5) Measurement_UI.TypeLoad:SetEnabled(false) Measurement_UI.SizeLabel:SetAlpha(0.5) Measurement_UI.SizeHint:SetAlpha(0.5) --TODO: implement a Measurement_UI.Size:SetEnabled(false) else Measurement_UI.TypeLabel:SetAlpha(1) Measurement_UI.TypeLoad:SetEnabled(true) Measurement_UI.SizeLabel:SetAlpha(1) Measurement_UI.SizeHint:SetAlpha(1) --TODO: implement a Measurement_UI.Size:SetEnabled(true) end end function Dta.measurements_ui.ShapeChanged(self, entry, value, index) local Measurement_UI = Dta.Tools.Offset.window.Measurements if not index then Measurement_UI.SizeHint:SetText("") else local sizes = Dta.measurements.Dimensions[index] Measurement_UI.SizeHint:SetText(string.format("(%g ... %g)", sizes.minScale, sizes.maxScale)) end end -- Show the toolbox window function Dta.measurements_ui.showWindow(mm_window) mm_window:SetVisible(true) mm_window.Measurements.TypeLoad:SetEnabled(true) mm_window.Measurements.OrientationLoad:SetEnabled(true) end -- Hide the toolbox window function Dta.measurements_ui.hideWindow(mm_window) mm_window:SetVisible(false) mm_window:ClearKeyFocus() -- workaround for dropdown not closing automatically mm_window.Measurements.TypeLoad:SetEnabled(false) mm_window.Measurements.OrientationLoad:SetEnabled(false) end Dta.RegisterTool("Offset", Dta.measurements_ui.buildWindow, Dta.measurements_ui.showWindow, Dta.measurements_ui.hideWindow)
bsd-3-clause
dalvorsn/tests
data/actions/scripts/other/fluids.lua
5
2573
local drunk = Condition(CONDITION_DRUNK) drunk:setParameter(CONDITION_PARAM_TICKS, 60000) local poison = Condition(CONDITION_POISON) poison:setParameter(CONDITION_PARAM_DELAYED, true) poison:setParameter(CONDITION_PARAM_MINVALUE, -50) poison:setParameter(CONDITION_PARAM_MAXVALUE, -120) poison:setParameter(CONDITION_PARAM_STARTVALUE, -5) poison:setParameter(CONDITION_PARAM_TICKINTERVAL, 4000) poison:setParameter(CONDITION_PARAM_FORCEUPDATE, true) local fluidType = {3, 4, 5, 7, 10, 11, 13, 15, 19} local fluidMessage = {"Aah...", "Urgh!", "Mmmh.", "Aaaah...", "Aaaah...", "Urgh!", "Urgh!", "Aah...", "Urgh!"} function onUse(cid, item, fromPosition, itemEx, toPosition) local itemExType = ItemType(itemEx.itemid) if itemExType and itemExType:isFluidContainer() then if itemEx.type == 0 and item.type ~= 0 then Item(itemEx.uid):transform(itemEx.itemid, item.type) Item(item.uid):transform(item.itemid, 0) return true elseif itemEx.type ~= 0 and item.type == 0 then Item(itemEx.uid):transform(itemEx.itemid, 0) Item(item.uid):transform(item.itemid, itemEx.type) return true end end if itemEx.itemid == 1 then if item.type == 0 then Player(cid):sendTextMessage(MESSAGE_STATUS_SMALL, "It is empty.") elseif itemEx.uid == cid then local player = Player(cid) Item(item.uid):transform(item.itemid, 0) if item.type == 3 or item.type == 15 then doTargetCombatCondition(0, cid, drunk, CONST_ME_NONE) elseif item.type == 4 then doTargetCombatCondition(0, cid, poison, CONST_ME_NONE) elseif item.type == 7 then player:addMana(math.random(50, 150)) fromPosition:sendMagicEffect(CONST_ME_MAGIC_BLUE) elseif item.type == 10 then player:addHealth(60) fromPosition:sendMagicEffect(CONST_ME_MAGIC_BLUE) end for i = 0, #fluidType do if item.type == fluidType[i] then player:say(fluidMessage[i], TALKTYPE_MONSTER_SAY) return true end end player:say("Gulp.", TALKTYPE_MONSTER_SAY) else Item(item.uid):transform(item.itemid, 0) Game.createItem(2016, item.type, toPosition):decay() end else local fluidSource = itemExType and itemExType:getFluidSource() or 0 if fluidSource ~= 0 then Item(item.uid):transform(item.itemid, fluidSource) elseif item.type == 0 then Player(cid):sendTextMessage(MESSAGE_STATUS_SMALL, "It is empty.") else if toPosition.x == CONTAINER_POSITION then toPosition = Player(cid):getPosition() end Item(item.uid):transform(item.itemid, 0) Game.createItem(2016, item.type, toPosition):decay() end end return true end
gpl-2.0
alidess/aliali
plugins/bot.lua
32
2277
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -------------------------------------------------- -- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver, to_id) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return lang_text(to_id, 'botOn')..' 😏' end _config.disabled_channels[receiver] = false save_config() return lang_text(to_id, 'botOn')..' 😏' end local function disable_channel(receiver, to_id) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return lang_text(to_id, 'botOff')..' 🚀' end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is sudo then re-enable the channel if is_sudo(msg) then if msg.text == "#bot on" then enable_channel(receiver, msg.to.id) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) if permissions(msg.from.id, msg.to.id, "bot") then local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'on' then return enable_channel(receiver, msg.to.id) end -- Disable a channel if matches[1] == 'off' then return disable_channel(receiver, msg.to.id) end else return '🚫 '..lang_text(msg.to.id, 'require_sudo') end end return { patterns = { "^#bot? (on)", "^#bot? (off)" }, run = run, pre_process = pre_process }
gpl-2.0
sundream/gamesrv
script/card/neutral/card263002.lua
1
2296
--<<card 导表开始>> local super = require "script.card.neutral.card163002" ccard263002 = class("ccard263002",super,{ sid = 263002, race = 6, name = "任务达人", type = 201, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 2, maxhp = 2, crystalcost = 3, targettype = 0, halo = nil, desc = "每当你使用一张牌时,便获得+1/+1。", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = {addbuff={addatk=1,addmaxhp=1,addhp=1}}, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard263002:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard263002:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard263002:save() local data = super.save(self) -- todo: save data return data end return ccard263002
gpl-2.0
EvPowerTeam/EV_OP
feeds/luci/applications/luci-asterisk/luasrc/model/cbi/asterisk/dialplans.lua
80
2807
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require("luci.asterisk") cbimap = Map("asterisk", "Registered Trunks") cbimap.pageaction = false local sip_peers = { } cbimap.uci:foreach("asterisk", "sip", function(s) if s.type == "peer" then s.name = s['.name'] s.info = ast.sip.peer(s.name) sip_peers[s.name] = s end end) sip_table = cbimap:section(TypedSection, "sip", "SIP Trunks") sip_table.template = "cbi/tblsection" sip_table.extedit = luci.dispatcher.build_url("admin", "asterisk", "trunks", "sip", "%s") sip_table.addremove = true sip_table.sectionhead = "Extension" function sip_table.filter(self, s) return s and ( cbimap.uci:get("asterisk", s, "type") == nil or cbimap.uci:get_bool("asterisk", s, "provider") ) end function sip_table.create(self, section) if TypedSection.create(self, section) then created = section else self.invalid_cts = true end end function sip_table.parse(self, ...) TypedSection.parse(self, ...) if created then cbimap.uci:tset("asterisk", created, { type = "friend", qualify = "yes", provider = "yes" }) cbimap.uci:save("asterisk") luci.http.redirect(luci.dispatcher.build_url( "admin", "asterisk", "trunks", "sip", created )) end end user = sip_table:option(DummyValue, "username", "Username") host = sip_table:option(DummyValue, "host", "Hostname") function host.cfgvalue(self, s) if sip_peers[s] and sip_peers[s].info.address then return "%s:%i" %{ sip_peers[s].info.address, sip_peers[s].info.port } else return "n/a" end end context = sip_table:option(DummyValue, "context", "Dialplan") context.href = luci.dispatcher.build_url("admin", "asterisk", "dialplan") function context.cfgvalue(...) return AbstractValue.cfgvalue(...) or "(default)" end online = sip_table:option(DummyValue, "online", "Registered") function online.cfgvalue(self, s) if sip_peers[s] and sip_peers[s].info.online == nil then return "n/a" else return sip_peers[s] and sip_peers[s].info.online and "yes" or "no (%s)" %{ sip_peers[s] and sip_peers[s].info.Status:lower() or "unknown" } end end delay = sip_table:option(DummyValue, "delay", "Delay") function delay.cfgvalue(self, s) if sip_peers[s] and sip_peers[s].info.online then return "%i ms" % sip_peers[s].info.delay else return "n/a" end end info = sip_table:option(Button, "_info", "Info") function info.write(self, s) luci.http.redirect(luci.dispatcher.build_url( "admin", "asterisk", "trunks", "sip", s, "info" )) end return cbimap
gpl-2.0
dalvorsn/tests
data/npc/scripts/runes.lua
11
8218
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) local talkState = {} function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local shopModule = ShopModule:new() npcHandler:addModule(shopModule) shopModule:addBuyableItem({'spellbook'}, 2175, 150, 'spellbook') shopModule:addBuyableItem({'magic lightwand'}, 2163, 400, 'magic lightwand') shopModule:addBuyableItem({'small health'}, 8704, 20, 1, 'small health potion') shopModule:addBuyableItem({'health potion'}, 7618, 45, 1, 'health potion') shopModule:addBuyableItem({'mana potion'}, 7620, 50, 1, 'mana potion') shopModule:addBuyableItem({'strong health'}, 7588, 100, 1, 'strong health potion') shopModule:addBuyableItem({'strong mana'}, 7589, 80, 1, 'strong mana potion') shopModule:addBuyableItem({'great health'}, 7591, 190, 1, 'great health potion') shopModule:addBuyableItem({'great mana'}, 7590, 120, 1, 'great mana potion') shopModule:addBuyableItem({'great spirit'}, 8472, 190, 1, 'great spirit potion') shopModule:addBuyableItem({'ultimate health'}, 8473, 310, 1, 'ultimate health potion') shopModule:addBuyableItem({'antidote potion'}, 8474, 50, 1, 'antidote potion') shopModule:addSellableItem({'normal potion flask', 'normal flask'}, 7636, 5, 'empty small potion flask') shopModule:addSellableItem({'strong potion flask', 'strong flask'}, 7634, 10, 'empty strong potion flask') shopModule:addSellableItem({'great potion flask', 'great flask'}, 7635, 15, 'empty great potion flask') shopModule:addBuyableItem({'instense healing'}, 2265, 95, 1, 'intense healing rune') shopModule:addBuyableItem({'ultimate healing'}, 2273, 175, 1, 'ultimate healing rune') shopModule:addBuyableItem({'magic wall'}, 2293, 350, 3, 'magic wall rune') shopModule:addBuyableItem({'destroy field'}, 2261, 45, 3, 'destroy field rune') shopModule:addBuyableItem({'light magic missile'}, 2287, 40, 10, 'light magic missile rune') shopModule:addBuyableItem({'heavy magic missile'}, 2311, 120, 10, 'heavy magic missile rune') shopModule:addBuyableItem({'great fireball'}, 2304, 180, 4, 'great fireball rune') shopModule:addBuyableItem({'explosion'}, 2313, 250, 6, 'explosion rune') shopModule:addBuyableItem({'sudden death'}, 2268, 350, 3, 'sudden death rune') shopModule:addBuyableItem({'death arrow'}, 2263, 300, 3, 'death arrow rune') shopModule:addBuyableItem({'paralyze'}, 2278, 700, 1, 'paralyze rune') shopModule:addBuyableItem({'animate dead'}, 2316, 375, 1, 'animate dead rune') shopModule:addBuyableItem({'convince creature'}, 2290, 80, 1, 'convince creature rune') shopModule:addBuyableItem({'chameleon'}, 2291, 210, 1, 'chameleon rune') shopModule:addBuyableItem({'desintegrate'}, 2310, 80, 3, 'desintegreate rune') shopModule:addBuyableItemContainer({'bp ap'}, 2002, 8378, 2000, 1, 'backpack of antidote potions') shopModule:addBuyableItemContainer({'bp slhp'}, 2000, 8610, 400, 1, 'backpack of small health potions') shopModule:addBuyableItemContainer({'bp hp'}, 2000, 7618, 900, 1, 'backpack of health potions') shopModule:addBuyableItemContainer({'bp mp'}, 2001, 7620, 1000, 1, 'backpack of mana potions') shopModule:addBuyableItemContainer({'bp shp'}, 2000, 7588, 2000, 1, 'backpack of strong health potions') shopModule:addBuyableItemContainer({'bp smp'}, 2001, 7589, 1600, 1, 'backpack of strong mana potions') shopModule:addBuyableItemContainer({'bp ghp'}, 2000, 7591, 3800, 1, 'backpack of great health potions') shopModule:addBuyableItemContainer({'bp gmp'}, 2001, 7590, 2400, 1, 'backpack of great mana potions') shopModule:addBuyableItemContainer({'bp gsp'}, 1999, 8376, 3800, 1, 'backpack of great spirit potions') shopModule:addBuyableItemContainer({'bp uhp'}, 2000, 8377, 6200, 1, 'backpack of ultimate health potions') shopModule:addBuyableItem({'wand of vortex', 'vortex'}, 2190, 500, 'wand of vortex') shopModule:addBuyableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 1000, 'wand of dragonbreath') shopModule:addBuyableItem({'wand of decay', 'decay'}, 2188, 5000, 'wand of decay') shopModule:addBuyableItem({'wand of draconia', 'draconia'}, 8921, 7500, 'wand of draconia') shopModule:addBuyableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 10000, 'wand of cosmic energy') shopModule:addBuyableItem({'wand of inferno', 'inferno'}, 2187, 15000, 'wand of inferno') shopModule:addBuyableItem({'wand of starstorm', 'starstorm'}, 8920, 18000, 'wand of starstorm') shopModule:addBuyableItem({'wand of voodoo', 'voodoo'}, 8922, 22000, 'wand of voodoo') shopModule:addBuyableItem({'snakebite rod', 'snakebite'}, 2182, 500, 'snakebite rod') shopModule:addBuyableItem({'moonlight rod', 'moonlight'}, 2186, 1000, 'moonlight rod') shopModule:addBuyableItem({'necrotic rod', 'necrotic'}, 2185, 5000, 'necrotic rod') shopModule:addBuyableItem({'northwind rod', 'northwind'}, 8911, 7500, 'northwind rod') shopModule:addBuyableItem({'terra rod', 'terra'}, 2181, 10000, 'terra rod') shopModule:addBuyableItem({'hailstorm rod', 'hailstorm'}, 2183, 15000, 'hailstorm rod') shopModule:addBuyableItem({'springsprout rod', 'springsprout'}, 8912, 18000, 'springsprout rod') shopModule:addBuyableItem({'underworld rod', 'underworld'}, 8910, 22000, 'underworld rod') shopModule:addSellableItem({'wand of vortex', 'vortex'}, 2190, 250, 'wand of vortex') shopModule:addSellableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 500, 'wand of dragonbreath') shopModule:addSellableItem({'wand of decay', 'decay'}, 2188, 2500, 'wand of decay') shopModule:addSellableItem({'wand of draconia', 'draconia'}, 8921, 3750, 'wand of draconia') shopModule:addSellableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 5000, 'wand of cosmic energy') shopModule:addSellableItem({'wand of inferno', 'inferno'},2187, 7500, 'wand of inferno') shopModule:addSellableItem({'wand of starstorm', 'starstorm'}, 8920, 9000, 'wand of starstorm') shopModule:addSellableItem({'wand of voodoo', 'voodoo'}, 8922, 11000, 'wand of voodoo') shopModule:addSellableItem({'snakebite rod', 'snakebite'}, 2182, 250,'snakebite rod') shopModule:addSellableItem({'moonlight rod', 'moonlight'}, 2186, 500, 'moonlight rod') shopModule:addSellableItem({'necrotic rod', 'necrotic'}, 2185, 2500, 'necrotic rod') shopModule:addSellableItem({'northwind rod', 'northwind'}, 8911, 3750, 'northwind rod') shopModule:addSellableItem({'terra rod', 'terra'}, 2181, 5000, 'terra rod') shopModule:addSellableItem({'hailstorm rod', 'hailstorm'}, 2183, 7500, 'hailstorm rod') shopModule:addSellableItem({'springsprout rod', 'springsprout'}, 8912, 9000, 'springsprout rod') shopModule:addSellableItem({'underworld rod', 'underworld'}, 8910, 11000, 'underworld rod') function creatureSayCallback(cid, type, msg) if(not npcHandler:isFocused(cid)) then return false end local talkUser = NPCHANDLER_CONVBEHAVIOR == CONVERSATION_DEFAULT and 0 or cid local items = {[1] = 2190, [2] = 2182, [5] = 2190, [6] = 2182} if(msgcontains(msg, 'first rod') or msgcontains(msg, 'first wand')) then if(isSorcerer(cid) or isDruid(cid)) then if(getPlayerStorageValue(cid, 30002) == -1) then selfSay('So you ask me for a {' .. getItemNameById(items[getPlayerVocation(cid)]) .. '} to begin your advanture?', cid) talkState[talkUser] = 1 else selfSay('What? I have already gave you one {' .. getItemNameById(items[getPlayerVocation(cid)]) .. '}!', cid) end else selfSay('Sorry, you aren\'t a druid either a sorcerer.', cid) end elseif(msgcontains(msg, 'yes')) then if(talkState[talkUser] == 1) then doPlayerAddItem(cid, items[getPlayerVocation(cid)], 1) selfSay('Here you are young adept, take care yourself.', cid) setPlayerStorageValue(cid, 30002, 1) end talkState[talkUser] = 0 elseif(msgcontains(msg, 'no') and isInArray({1}, talkState[talkUser]) == TRUE) then selfSay('Ok then.', cid) talkState[talkUser] = 0 end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
gpl-2.0
tomm/pioneer
data/ui/QuitConfirmation.lua
1
1268
-- Copyright © 2008-2016 Pioneer Developers. See AUTHORS.txt for details -- Licensed under the terms of the GPL v3. See licenses/GPL-3.txt local Engine = import("Engine") local Lang = import("Lang") local ui = Engine.ui local l = Lang.GetResource("quitconfirmation-core") local max_flavours = 18 ui.templates.QuitConfirmation = function (args) local title = l.QUIT local confirmLabel = l.YES local cancelLabel = l.NO local onConfirm = args.onConfirm local onCancel = args.onCancel local message = string.interp(l["MSG_" .. Engine.rand:Integer(1, max_flavours)],{yes = l.YES, no = l.NO}) local confirmButton = ui:Button(ui:Label(confirmLabel):SetFont("HEADING_NORMAL")) local cancelButton = ui:Button(ui:Label(cancelLabel):SetFont("HEADING_NORMAL")) cancelButton.onClick:Connect(onCancel) confirmButton.onClick:Connect(onConfirm) local dialog = ui:ColorBackground(0,0,0,0.5, ui:Align("MIDDLE", ui:Background( ui:Table():SetRowSpacing(10) :AddRow(ui:Label(title):SetFont("HEADING_NORMAL")) :AddRow(ui:MultiLineText(message)) :AddRow(ui:Grid(2,1) :SetRow(0, { ui:Align("LEFT", confirmButton), ui:Align("RIGHT", cancelButton), })) ) ) ) return dialog end
gpl-3.0
Houshalter/lw-replay
irc/init.lua
6
4500
local socket = require "socket" local error = error local setmetatable = setmetatable local rawget = rawget local unpack = unpack local pairs = pairs local assert = assert local require = require local tonumber = tonumber local type = type local pcall = pcall module "irc" local meta = {} meta.__index = meta _META = meta require "irc.util" require "irc.asyncoperations" require "irc.handlers" local meta_preconnect = {} function meta_preconnect.__index(o, k) local v = rawget(meta_preconnect, k) if not v and meta[k] then error(("field '%s' is not accessible before connecting"):format(k), 2) end return v end function new(data) local o = { nick = assert(data.nick, "Field 'nick' is required"); username = data.username or "lua"; realname = data.realname or "Lua owns"; nickGenerator = data.nickGenerator or defaultNickGenerator; hooks = {}; track_users = true; } assert(checkNick(o.nick), "Erroneous nickname passed to irc.new") return setmetatable(o, meta_preconnect) end function meta:hook(name, id, f) f = f or id self.hooks[name] = self.hooks[name] or {} self.hooks[name][id] = f return id or f end meta_preconnect.hook = meta.hook function meta:unhook(name, id) local hooks = self.hooks[name] assert(hooks, "no hooks exist for this event") assert(hooks[id], "hook ID not found") hooks[id] = nil end meta_preconnect.unhook = meta.unhook function meta:invoke(name, ...) local hooks = self.hooks[name] if hooks then for id,f in pairs(hooks) do if f(...) then return true end end end end function meta_preconnect:connect(_host, _port) local host, port, password, secure, timeout if type(_host) == "table" then host = _host.host port = _host.port timeout = _host.timeout password = _host.password secure = _host.secure else host = _host port = _port end host = host or error("host name required to connect", 2) port = port or 6667 local s = socket.tcp() s:settimeout(timeout or 30) assert(s:connect(host, port)) if secure then local work, ssl = pcall(require, "ssl") if not work then error("LuaSec required for secure connections", 2) end local params if type(secure) == "table" then params = secure else params = {mode = "client", protocol = "tlsv1"} end s = ssl.wrap(s, params) success, errmsg = s:dohandshake() if not success then error(("could not make secure connection: %s"):format(errmsg), 2) end end self.socket = s setmetatable(self, meta) self:send("CAP REQ multi-prefix") self:invoke("PreRegister", self) self:send("CAP END") if password then self:send("PASS %s", password) end self:send("NICK %s", self.nick) self:send("USER %s 0 * :%s", self.username, self.realname) self.channels = {} s:settimeout(0) repeat self:think() socket.select(nil, nil, 0.1) -- Sleep so that we don't eat CPU until self.authed end function meta:disconnect(message) message = message or "Bye!" self:invoke("OnDisconnect", message, false) self:send("QUIT :%s", message) self:shutdown() end function meta:shutdown() self.socket:close() setmetatable(self, nil) end local function getline(self, errlevel) local line, err = self.socket:receive("*l") if not line and err ~= "timeout" and err ~= "wantread" then self:invoke("OnDisconnect", err, true) self:shutdown() error(err, errlevel) end return line end function meta:think() while true do local line = getline(self, 3) if line and #line > 0 then if not self:invoke("OnRaw", line) then self:handle(parse(line)) end else break end end end local handlers = handlers function meta:handle(prefix, cmd, params) local handler = handlers[cmd] if handler then return handler(self, prefix, unpack(params)) end end local whoisHandlers = { ["311"] = "userinfo"; ["312"] = "node"; ["319"] = "channels"; ["330"] = "account"; -- Freenode ["307"] = "registered"; -- Unreal } function meta:whois(nick) self:send("WHOIS %s", nick) local result = {} while true do local line = getline(self, 3) if line then local prefix, cmd, args = parse(line) local handler = whoisHandlers[cmd] if handler then result[handler] = args elseif cmd == "318" then break else self:handle(prefix, cmd, args) end end end if result.account then result.account = result.account[3] elseif result.registered then result.account = result.registered[2] end return result end function meta:topic(channel) self:send("TOPIC %s", channel) end
mit
sundream/gamesrv
script/card/golden/card213002.lua
1
2307
--<<card 导表开始>> local super = require "script.card.golden.card113002" ccard213002 = class("ccard213002",super,{ sid = 213002, race = 1, name = "暴风雪", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 6, targettype = 0, halo = nil, desc = "对所有敌方随从造成2点伤害,并使其冻结", effect = { onuse = {magic_hurt=2,addbuff={freeze=1,lifecircle=2}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard213002:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard213002:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard213002:save() local data = super.save(self) -- todo: save data return data end return ccard213002
gpl-2.0
sundream/gamesrv
script/card/neutral/card166012.lua
1
2499
--<<card 导表开始>> local super = require "script.card.init" ccard166012 = class("ccard166012",super,{ sid = 166012, race = 6, name = "梦境", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 0, composechip = 0, decomposechip = 0, atk = 0, maxhp = 0, crystalcost = 0, targettype = 22, halo = nil, desc = "使一名仆从回到其拥有者的手牌中。", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard166012:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard166012:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard166012:save() local data = super.save(self) -- todo: save data return data end function ccard166012:onuse(pos,targetid,choice) local owner = self:getowner() local footman = owner:gettarget(targetid) local footman_owner = footman:getowner() if footman_owner:removefromwar(footman) then footman_owner:putinhand(footman.id) end end return ccard166012
gpl-2.0
mahyarnajibi/fast-rcnn-torch
datasets/DataSetCoco.lua
1
17072
local DataSetCoco,parent = torch.class('detection.DataSetCoco', 'detection.DataSetDetection') local env = require 'argcheck.env' local argcheck = dofile'datasets/argcheck.lua' local json = require 'dkjson' matio.use_lua_strings = true local env = require 'argcheck.env' -- retrieve argcheck environement -- this is the default type function -- which can be overrided by the user function env.istype(obj, typename) local t = torch.type(obj) if t:find('torch.*Tensor') then return 'torch.Tensor' == typename end return torch.type(obj) == typename end local initcheck = argcheck{ pack=true, noordered=true, help=[[ Coco dataset for the detection package. ]], {name="image_set", type="string", help="ImageSet name"}, {name="datadir", type="string", help="Path to dataset", check=function(datadir) return paths.dirp(datadir) end}, {name="with_cloud", type="boolean", help="Whether to load proposals with cloud annotation", opt = true}, {name="year", type="string", help="MSCOCO year", opt = true}, {name="proposal_root_path", type="string", help="This class is written to work with the format provided by Hosang et. al.", opt = true}, {name="annotaion_root_path", type="string", help="Path to the annotations", opt = true}, {name="dataset_name", type="string", help="Name of the dataset", opt = true}, {name = "proposal_method", type = "string", help = "Name of the annotation method", opt = true}, {name = "img_path", type = "string", help = "image path", opt = true }, {name = "crowd_threshold", type = "number", help = "threshold used for prunning proposals overlapping the crowd groun truth boxes", opt = true }, {name = "top_k", type = "number", help = "Number of proposals to be used", opt = true }, { name = "res_save_path", type = "string", opt = true }, {name = "eval_res_save_path", typr = "string", opt = true }, {name = "load_from_cache", type = "boolean", opt = true } } function DataSetCoco:__init(...) parent.__init(self) local args = initcheck(...) for k,v in pairs(args) do self[k] = v end if not self.image_set then error 'The image-set should be specified for MSCOCO dataset' end if not self.year then self.year = 2014 end if not self.load_from_cache then self.load_from_cache = true end if not self.top_k then self.top_k = 2000 end if not self.crowd_threshold then self.crowd_threshold = 0.7 end if not self.datadir then self.datadir = config.dataset_path end if not self.res_save_path then local res_path = paths.concat(self.datadir,'results') if not paths.dirp(res_path) then paths.mkdir(res_path) end self.res_save_path = paths.concat(res_path,'detections_'..self.image_set..self.year..'.json') end if not self.eval_res_save_path then local res_path = paths.concat(self.datadir,'results') if not paths.dirp(res_path) then paths.mkdir(res_path) end self.eval_res_save_path = paths.concat(res_path,'evaluation_results_'..self.image_set..self.year..'.json') end if not self.img_path then self.img_path = paths.concat(self.datadir,self.image_set..self.year) end if not self.dataset_name then self.dataset_name = config.dataset end if not self.proposal_method then self.proposal_method = 'selective_search' end if not self.annotation_root_path then self.annotation_root_path = paths.concat(self.datadir,'annotations') end if not self.proposal_root_path then local file_name = 'COCO_'..self.image_set..self.year if self.image_set == 'test' then file_name = file_name .. '_' end if self.image_set == 'val' then file_name = file_name .. '_0' end self.proposal_root_path = paths.concat(self.datadir, 'precomputed-coco', self.proposal_method,'mat','COCO_'..self.image_set..self.year) end -- Loading annotation file local annotations_cache_path = paths.concat(config.cache,'coco_'.. self.image_set ..self.year ..'_annotations_cached.t7') if paths.filep(annotations_cache_path) and self.load_from_cache then print('Reading annotations from cached file...') local loaded_annotations = torch.load(annotations_cache_path) for name,value in pairs(loaded_annotations) do self[name] = value end self.num_classes = #self.classes else -- Load and save only the needed data print('Loading COCO annotations...') self:_loadAnnotations() -- Mapping between our class ids and coco class ids local n_class = #self.annotations['categories'] self.class_mapping_from_coco = tds.Hash() self.class_mapping_to_coco = tds.Hash() self.classes = tds.Hash() for c = 1, n_class do self.class_mapping_from_coco[self.annotations['categories'][c].id] = c self.class_mapping_to_coco[c] = self.annotations['categories'][c].id self.classes[c] = self.annotations['categories'][c].name end self.num_classes = n_class -- Map image ids self:_mapImageIDs() -- Loading GTs self:_prepareGTs() -- Save the computations print('Caching the dataset...') local saved_annotations = tds.Hash() saved_annotations.class_mapping_from_coco = self.class_mapping_from_coco saved_annotations.class_mapping_to_coco = self.class_mapping_to_coco saved_annotations.classes = self.classes saved_annotations.image_paths = self.image_paths saved_annotations.image_ids = self.image_ids saved_annotations.image_sizes = self.image_sizes saved_annotations.inverted_image_ids = self.inverted_image_ids saved_annotations.gts = self.gts torch.save(annotations_cache_path,saved_annotations) end -- Loading and pruning the proposals self:loadROIDB() self:_filterCrowd() end function DataSetCoco:getImage(i) return image.load(self.image_paths[i],3,'float') end function DataSetCoco:_mapImageIDs() local n_images = #self.annotations['images'] self.image_ids = torch.IntTensor(n_images) self.inverted_image_ids = tds.Hash() self.image_paths = tds.Hash() self.image_sizes = torch.IntTensor(n_images,2) for i=1,n_images do local cur_id = self.annotations['images'][i].id self.image_ids[i] = cur_id self.inverted_image_ids[cur_id] = i self.image_paths[i] = paths.concat(self.img_path,self.annotations['images'][i].file_name) self.image_sizes[{{i},{}}] = torch.IntTensor({self.annotations['images'][i].width,self.annotations['images'][i].height}) end end function DataSetCoco:_createSampleSet(nSample_per_class,min_objs_per_img,new_image_set_name) local n_images = self:size() local n_class = self:nclass() local class_counts = torch.IntTensor(n_images,n_class):zero() for i=1,n_images do local cur_classes = self.gts[i].classes for c=1,cur_classes:numel() do class_counts[i][cur_classes[c]] = class_counts[i][cur_classes[c]] + 1 end end local already_selected = torch.ByteTensor(n_images):zero() local new_roidb = tds.Hash() local new_gts = tds.Hash() local new_paths = tds.Hash() local new_image_ids = torch.IntTensor() local new_image_sizes = torch.IntTensor() local new_inverted_image_ids = tds.Hash() local objs_per_img = class_counts:sum(2) local img_count = 1 debugger.enter() for c=1,n_class do local valid_samples = class_counts[{{},{c}}]:ge(1):cmul(objs_per_img:ge(min_objs_per_img)):cmul(already_selected:eq(0)):eq(1) valid_samples = utils:logical2ind(valid_samples) -- select a random subset valid_samples = utils:shuffle(1,valid_samples) local n_samples = math.min(valid_samples:numel(),nSample_per_class) for i =1, n_samples do already_selected[valid_samples[i]] = 1 new_gts[img_count] = self.gts[valid_samples[i]] new_paths[img_count] = self.image_paths[valid_samples[i]] new_inverted_image_ids[self.image_ids[valid_samples[i]]] = img_count new_roidb[img_count] = self.roidb[valid_samples[i]] if img_count == 1 then new_image_sizes = self.image_sizes[valid_samples[i]]:view(1,2) new_image_ids = torch.IntTensor({self.image_ids[valid_samples[i]]}) else new_image_ids = new_image_ids:cat(torch.IntTensor({self.image_ids[valid_samples[i]]})) new_image_sizes = new_image_sizes:cat(self.image_sizes[valid_samples[i]]:view(1,2),1) end img_count = img_count + 1 end end -- Save the new imageset annotations local annotations_cache_path = paths.concat(config.cache,'coco_'.. new_image_set_name ..self.year ..'_annotations_cached.t7') local saved_annotations = tds.Hash() saved_annotations.class_mapping_from_coco = self.class_mapping_from_coco saved_annotations.class_mapping_to_coco = self.class_mapping_to_coco saved_annotations.classes = self.classes saved_annotations.image_paths = new_paths saved_annotations.image_ids = new_image_ids saved_annotations.image_sizes = new_image_sizes saved_annotations.inverted_image_ids = new_inverted_image_ids saved_annotations.gts = new_gts torch.save(annotations_cache_path,saved_annotations) -- Save the new proposals file local cache_name = 'proposals_' .. self.proposal_method ..'_coco' .. self.year .. '_' .. new_image_set_name .. '_top' .. self.top_k ..'.t7' local cache_path = paths.concat(config.cache,cache_name) torch.save(cache_path,new_roidb) end function DataSetCoco:_prepareGTs() -- Index annotations by image number if self.gts then return end self.gts = tds.Hash() for i=1,#self.annotations['images'] do self.gts[i] = tds.Hash() self.gts[i].bboxes = torch.FloatTensor() self.gts[i].areas = torch.FloatTensor() self.gts[i].iscrowd = torch.ByteTensor() -- Uncomment the following line if you are interested in the segmetation data --self.gts[i].segmentation = tds.Hash() self.gts[i].classes = torch.ByteTensor() end -- Look for annotations for each image for i=1,#self.annotations['annotations'] do local cur_id = self.inverted_image_ids[self.annotations['annotations'][i].image_id] if cur_id==56 then debugger.enter() end local cur_box = self.annotations['annotations'][i].bbox cur_box = torch.FloatTensor({{cur_box[1],cur_box[2],cur_box[3],cur_box[4]}}) cur_box = self:_convert_to_x1y1x2y2(cur_box) + 1 local cur_class = self.class_mapping_from_coco[self.annotations['annotations'][i].category_id] if self.gts[cur_id].bboxes:numel() ==0 then self.gts[cur_id].bboxes = cur_box self.gts[cur_id].areas = torch.FloatTensor({self.annotations['annotations'][i].area}) self.gts[cur_id].iscrowd = torch.ByteTensor({self.annotations['annotations'][i].iscrowd}) -- Uncomment the following line if you are interested in the segmentation data --self.gts[cur_id].segmentation[1] = self.annotations['annotations'][i].segmentation self.gts[cur_id].classes = torch.ByteTensor({cur_class}) else self.gts[cur_id].bboxes = self.gts[cur_id].bboxes:cat(torch.FloatTensor(cur_box),1) self.gts[cur_id].areas = self.gts[cur_id].areas:cat(torch.FloatTensor({self.annotations['annotations'][i].area})) self.gts[cur_id].iscrowd = self.gts[cur_id].iscrowd:cat(torch.ByteTensor({self.annotations['annotations'][i].iscrowd})) -- Uncomment the following line if you are interested in the segmentation data --self.gts[cur_id].segmentation[#self.gts[cur_id].segmentation+1] = self.annotations['annotations'][i].segmentation self.gts[cur_id].classes = self.gts[cur_id].classes:cat(torch.ByteTensor({cur_class})) end end end function DataSetCoco:getROIBoxes(i) if not self.roidb then self:loadROIDB() end return self.roidb[i]--self.roidb[self.img2roidb[self.img_ids[i] ] ] end function DataSetCoco:getGTBoxes(i) local good_boxes = utils:logical2ind(self.gts[i].iscrowd:eq(0)) if good_boxes:numel()==0 then return torch.FloatTensor(),{} end local cur_gts = self.gts[i].bboxes:index(1,good_boxes) local cur_labels = self.gts[i].classes:index(1,good_boxes) -- return a table consisting the labels local tabLabels = {} for i=1,cur_labels:numel() do tabLabels[i] = cur_labels[i] end return cur_gts,tabLabels end function DataSetCoco:size() return #self.image_paths end function DataSetCoco:_convert_to_x1y1x2y2(boxes) return boxes[{{},{1,2}}]:cat(boxes[{{},{1,2}}]+boxes[{{},{3,4}}] - 1) end function DataSetCoco:_convert_to_xywh(boxes) return boxes[{{},{1,2}}]:cat(boxes[{{},{3,4}}]-boxes[{{},{1,2}}] + 1) end function DataSetCoco:loadROIDB() if self.roidb then return end local cache_name = 'proposals_' .. self.proposal_method ..'_coco' .. self.year .. '_' .. self.image_set .. '_top' .. self.top_k ..'.t7' local cache_path = paths.concat(config.cache,cache_name) if paths.filep(cache_path) then print('Loading proposals from a cached file...') self.roidb = torch.load(cache_path) return end self.roidb = tds.Hash() for i=1,#self:size() do if i%1000 ==0 then print(string.format('Loaded proposals for %d images!',i)) end -- determine the file name local folder_name = tostring(self.image_paths[i]):sub(1,22) local file_path = paths.concat(self.proposal_root_path,folder_name,paths.basename(self.image_paths[i],'jpg')..'.mat') local proposals = matio.load(file_path)['boxes'] local n_box = math.min(self.top_k,proposals:size(1)) self.roidb[i] = proposals[{{1,n_box},{}}] end -- Cache the loaded proposals self:_filterCrowed() torch.save(cache_path,self.roidb) end function DataSetCoco:_loadAnnotations() local annotation_file_path = paths.concat(self.annotation_root_path,'instances_'..self.image_set .. self.year .. '.tds.t7') self.annotations = torch.load(annotation_file_path) end function DataSetCoco:getImageSize(i) return self.image_sizes[i] end function DataSetCoco:nclass() return #self.classes end function DataSetCoco:evaluate(all_detections) self:_write_detections(all_detections) -- Doing the evaluation using Python COCO API local coco_wrapper_path = paths.concat('utils','COCO-python-wrapper','evaluate_coco.py') local coco_anno_path = paths.concat(self.annotation_root_path,'instances_'..self.image_set..self.year..'.json') local args = string.format(' -i \'%s\' -o \'%s\' -a \'%s\'', self.res_save_path, self.eval_res_save_path,coco_anno_path) local cmd = 'python ' .. coco_wrapper_path .. args return os.execute(cmd) end function DataSetCoco:_test_evaluation() local all_detections = tds.Hash() for i=1,#self.classes do all_detections[i] = tds.Hash() end for i=1, self:size() do local gts = self.gts[i].bboxes local classes = self.gts[i].classes if classes == nil then debugger.enter() end for j=1,#self.classes do local cur_inds = utils:logical2ind(classes:eq(j)) if cur_inds:numel() > 0 then all_detections[j][i] = gts:index(1,cur_inds):cat(torch.FloatTensor(cur_inds:numel()):fill(1)) else all_detections[j][i] = torch.FloatTensor() end end end self:evaluate(all_detections) end function DataSetCoco:_write_detections(all_detections) -- Writing detections in the coco format print(string.format('Writing detections to: %s \n',self.res_save_path)) local file = io.open(self.res_save_path,'w') file:write('[') local n_class = self:nclass() local n_images = self:size() local first_write = true for c = 1,n_class do for i=1,n_images do local cur_detections = all_detections[c][i] if cur_detections:numel() > 0 then cur_detections[{{},{1,4}}] = self:_convert_to_xywh(cur_detections[{{},{1,4}}] -1 ) -- Convert to json and write to the file local n_detections = cur_detections:size(1) for d=1,n_detections do if first_write then first_write = false else file:write(',') end local cur_det = cur_detections[{{d},{1,4}}][1] local cur_score = cur_detections[d][-1] local json_entry = {image_id = self.image_ids[i], category_id = self.class_mapping_to_coco[c], bbox = {cur_det[1],cur_det[2],cur_det[3],cur_det[4]}, score = cur_score} json_entry = json.encode(json_entry) file:write(json_entry) end end end end file:write(']') file:close() end function DataSetCoco:getImagePath(i) return self.image_paths[i] end function DataSetCoco:_filterCrowd() for i=1,self:size() do local boxes = self:getROIBoxes(i) -- Filter the bboxes local cur_gts = self.gts[i].bboxes if cur_gts:numel() > 0 then local cur_iscrowd = self.gts[i].iscrowd local bad_gt_ids = utils:logical2ind(cur_iscrowd:eq(1)) if bad_gt_ids:numel() == cur_gts:size(1) then print('There is an image with all crowd GTs!') end if bad_gt_ids:numel()>0 then local bad_gts = cur_gts:index(1,bad_gt_ids) local good_bbox_ids = torch.LongTensor() for j=1,bad_gt_ids:numel() do local cur_overlaps = utils:boxoverlap(boxes,bad_gts[j]) if good_bbox_ids:numel()==0 then good_bbox_ids = utils:logical2ind(cur_overlaps:lt(self.crowd_threshold)) else good_bbox_ids = good_bbox_ids:cat(utils:logical2ind(cur_overlaps:lt(self.crowd_threshold))) end end if good_bbox_ids:numel()==0 then print('There is an image with no good bounding boxes!') else self.roidb[i] = boxes:index(1,good_bbox_ids) end end end end end
mit
EvPowerTeam/EV_OP
feeds/luci/applications/luci-pbx/luasrc/model/cbi/pbx-calls.lua
117
18881
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx 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. luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-calls" voipmodulename = "pbx-voip" googlemodulename = "pbx-google" usersmodulename = "pbx-users" allvalidaccounts = {} nallvalidaccounts = 0 validoutaccounts = {} nvalidoutaccounts = 0 validinaccounts = {} nvalidinaccounts = 0 allvalidusers = {} nallvalidusers = 0 validoutusers = {} nvalidoutusers = 0 -- Checks whether the entered extension is valid syntactically. function is_valid_extension(exten) return (exten:match("[#*+0-9NXZ]+$") ~= nil) end m = Map (modulename, translate("Call Routing"), translate("This is where you indicate which Google/SIP accounts are used to call what \ country/area codes, which users can use what SIP/Google accounts, how incoming \ calls are routed, what numbers can get into this PBX with a password, and what \ numbers are blacklisted.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") end -- Add Google accounts to all valid accounts, and accounts valid for incoming and outgoing calls. m.uci:foreach(googlemodulename, "gtalk_jabber", function(s1) -- Add this provider to list of valid accounts. if s1.username ~= nil and s1.name ~= nil then allvalidaccounts[s1.name] = s1.username nallvalidaccounts = nallvalidaccounts + 1 if s1.make_outgoing_calls == "yes" then -- Add provider to the associative array of valid outgoing accounts. validoutaccounts[s1.name] = s1.username nvalidoutaccounts = nvalidoutaccounts + 1 end if s1.register == "yes" then -- Add provider to the associative array of valid outgoing accounts. validinaccounts[s1.name] = s1.username nvalidinaccounts = nvalidinaccounts + 1 end end end) -- Add SIP accounts to all valid accounts, and accounts valid for incoming and outgoing calls. m.uci:foreach(voipmodulename, "voip_provider", function(s1) -- Add this provider to list of valid accounts. if s1.defaultuser ~= nil and s1.host ~= nil and s1.name ~= nil then allvalidaccounts[s1.name] = s1.defaultuser .. "@" .. s1.host nallvalidaccounts = nallvalidaccounts + 1 if s1.make_outgoing_calls == "yes" then -- Add provider to the associative array of valid outgoing accounts. validoutaccounts[s1.name] = s1.defaultuser .. "@" .. s1.host nvalidoutaccounts = nvalidoutaccounts + 1 end if s1.register == "yes" then -- Add provider to the associative array of valid outgoing accounts. validinaccounts[s1.name] = s1.defaultuser .. "@" .. s1.host nvalidinaccounts = nvalidinaccounts + 1 end end end) -- Add Local User accounts to all valid users, and users allowed to make outgoing calls. m.uci:foreach(usersmodulename, "local_user", function(s1) -- Add user to list of all valid users. if s1.defaultuser ~= nil then allvalidusers[s1.defaultuser] = true nallvalidusers = nallvalidusers + 1 if s1.can_call == "yes" then validoutusers[s1.defaultuser] = true nvalidoutusers = nvalidoutusers + 1 end end end) ---------------------------------------------------------------------------------------------------- -- If there are no accounts configured, or no accounts enabled for outgoing calls, display a warning. -- Otherwise, display the usual help text within the section. if nallvalidaccounts == 0 then text = translate("NOTE: There are no Google or SIP provider accounts configured.") elseif nvalidoutaccounts == 0 then text = translate("NOTE: There are no Google or SIP provider accounts enabled for outgoing calls.") else text = translate("If you have more than one account that can make outgoing calls, you \ should enter a list of phone numbers and/or prefixes in the following fields for each \ provider listed. Invalid prefixes are removed silently, and only 0-9, X, Z, N, #, *, \ and + are valid characters. The letter X matches 0-9, Z matches 1-9, and N matches 2-9. \ For example to make calls to Germany through a provider, you can enter 49. To make calls \ to North America, you can enter 1NXXNXXXXXX. If one of your providers can make \"local\" \ calls to an area code like New York's 646, you can enter 646NXXXXXX for that \ provider. You should leave one account with an empty list to make calls with \ it by default, if no other provider's prefixes match. The system will automatically \ replace an empty list with a message that the provider dials all numbers not matched by another \ provider's prefixes. Be as specific as possible (i.e. 1NXXNXXXXXX is better than 1). Please note \ all international dial codes are discarded (e.g. 00, 011, 010, 0011). Entries can be made in a \ space-separated list, and/or one per line by hitting enter after every one.") end s = m:section(NamedSection, "outgoing_calls", "call_routing", translate("Outgoing Calls"), text) s.anonymous = true for k,v in pairs(validoutaccounts) do patterns = s:option(DynamicList, k, v) -- If the saved field is empty, we return a string -- telling the user that this provider would dial any exten. function patterns.cfgvalue(self, section) value = self.map:get(section, self.option) if value == nil then return {translate("Dials numbers unmatched elsewhere")} else return value end end -- Write only valid extensions into the config file. function patterns.write(self, section, value) newvalue = {} nindex = 1 for index, field in ipairs(value) do val = luci.util.trim(value[index]) if is_valid_extension(val) == true then newvalue[nindex] = val nindex = nindex + 1 end end DynamicList.write(self, section, newvalue) end end ---------------------------------------------------------------------------------------------------- -- If there are no accounts configured, or no accounts enabled for incoming calls, display a warning. -- Otherwise, display the usual help text within the section. if nallvalidaccounts == 0 then text = translate("NOTE: There are no Google or SIP provider accounts configured.") elseif nvalidinaccounts == 0 then text = translate("NOTE: There are no Google or SIP provider accounts enabled for incoming calls.") else text = translate("For each provider enabled for incoming calls, here you can restrict which users to\ ring on incoming calls. If the list is empty, the system will indicate that all users \ enabled for incoming calls will ring. Invalid usernames will be rejected \ silently. Also, entering a username here overrides the user's setting to not receive \ incoming calls. This way, you can make certain users ring only for specific providers. \ Entries can be made in a space-separated list, and/or one per line by hitting enter after \ every one.") end s = m:section(NamedSection, "incoming_calls", "call_routing", translate("Incoming Calls"), text) s.anonymous = true for k,v in pairs(validinaccounts) do users = s:option(DynamicList, k, v) -- If the saved field is empty, we return a string telling the user that -- this provider would ring all users configured for incoming calls. function users.cfgvalue(self, section) value = self.map:get(section, self.option) if value == nil then return {translate("Rings users enabled for incoming calls")} else return value end end -- Write only valid user names. function users.write(self, section, value) newvalue = {} nindex = 1 for index, field in ipairs(value) do trimuser = luci.util.trim(value[index]) if allvalidusers[trimuser] == true then newvalue[nindex] = trimuser nindex = nindex + 1 end end DynamicList.write(self, section, newvalue) end end ---------------------------------------------------------------------------------------------------- -- If there are no user accounts configured, no user accounts enabled for outgoing calls, -- display a warning. Otherwise, display the usual help text within the section. if nallvalidusers == 0 then text = translate("NOTE: There are no local user accounts configured.") elseif nvalidoutusers == 0 then text = translate("NOTE: There are no local user accounts enabled for outgoing calls.") else text = translate("For each user enabled for outgoing calls you can restrict what providers the user \ can use for outgoing calls. By default all users can use all providers. To show up in the list \ below the user should be allowed to make outgoing calls in the \"User Accounts\" page. Enter VoIP \ providers in the format username@some.host.name, as listed in \"Outgoing Calls\" above. It's \ easiest to copy and paste the providers from above. Invalid entries, including providers not \ enabled for outgoing calls, will be rejected silently. Entries can be made in a space-separated \ list, and/or one per line by hitting enter after every one.") end s = m:section(NamedSection, "providers_user_can_use", "call_routing", translate("Providers Used for Outgoing Calls"), text) s.anonymous = true for k,v in pairs(validoutusers) do providers = s:option(DynamicList, k, k) -- If the saved field is empty, we return a string telling the user -- that this user uses all providers enavled for outgoing calls. function providers.cfgvalue(self, section) value = self.map:get(section, self.option) if value == nil then return {translate("Uses providers enabled for outgoing calls")} else newvalue = {} -- Convert internal names to user@host values. for i,v in ipairs(value) do newvalue[i] = validoutaccounts[v] end return newvalue end end -- Cook the new values prior to entering them into the config file. -- Also, enter them only if they are valid. function providers.write(self, section, value) cookedvalue = {} cindex = 1 for index, field in ipairs(value) do cooked = string.gsub(luci.util.trim(value[index]), "%W", "_") if validoutaccounts[cooked] ~= nil then cookedvalue[cindex] = cooked cindex = cindex + 1 end end DynamicList.write(self, section, cookedvalue) end end ---------------------------------------------------------------------------------------------------- s = m:section(TypedSection, "callthrough_numbers", translate("Call-through Numbers"), translate("Designate numbers that are allowed to call through this system and which user's \ privileges they will have.")) s.anonymous = true s.addremove = true num = s:option(DynamicList, "callthrough_number_list", translate("Call-through Numbers"), translate("Specify numbers individually here. Press enter to add more numbers. \ You will have to experiment with what country and area codes you need to add \ to the number.")) num.datatype = "uinteger" p = s:option(ListValue, "enabled", translate("Enabled")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" user = s:option(Value, "defaultuser", translate("User Name"), translate("The number(s) specified above will be able to dial out with this user's providers. \ Invalid usernames, including users not enabled for outgoing calls, are dropped silently. \ Please verify that the entry was accepted.")) function user.write(self, section, value) trimuser = luci.util.trim(value) if allvalidusers[trimuser] == true then Value.write(self, section, trimuser) end end pwd = s:option(Value, "pin", translate("PIN"), translate("Your PIN disappears when saved for your protection. It will be changed \ only when you enter a value different from the saved one. Leaving the PIN \ empty is possible, but please beware of the security implications.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end ---------------------------------------------------------------------------------------------------- s = m:section(TypedSection, "callback_numbers", translate("Call-back Numbers"), translate("Designate numbers to whom the system will hang up and call back, which provider will \ be used to call them, and which user's privileges will be granted to them.")) s.anonymous = true s.addremove = true num = s:option(DynamicList, "callback_number_list", translate("Call-back Numbers"), translate("Specify numbers individually here. Press enter to add more numbers. \ You will have to experiment with what country and area codes you need to add \ to the number.")) num.datatype = "uinteger" p = s:option(ListValue, "enabled", translate("Enabled")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" delay = s:option(Value, "callback_hangup_delay", translate("Hang-up Delay"), translate("How long to wait before hanging up. If the provider you use to dial automatically forwards \ to voicemail, you can set this value to a delay that will allow you to hang up before your call gets \ forwarded and you get billed for it.")) delay.datatype = "uinteger" delay.default = 0 user = s:option(Value, "defaultuser", translate("User Name"), translate("The number(s) specified above will be able to dial out with this user's providers. \ Invalid usernames, including users not enabled for outgoing calls, are dropped silently. \ Please verify that the entry was accepted.")) function user.write(self, section, value) trimuser = luci.util.trim(value) if allvalidusers[trimuser] == true then Value.write(self, section, trimuser) end end pwd = s:option(Value, "pin", translate("PIN"), translate("Your PIN disappears when saved for your protection. It will be changed \ only when you enter a value different from the saved one. Leaving the PIN \ empty is possible, but please beware of the security implications.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end provider = s:option(Value, "callback_provider", translate("Call-back Provider"), translate("Enter a VoIP provider to use for call-back in the format username@some.host.name, as listed in \ \"Outgoing Calls\" above. It's easiest to copy and paste the providers from above. Invalid entries, including \ providers not enabled for outgoing calls, will be rejected silently.")) function provider.write(self, section, value) cooked = string.gsub(luci.util.trim(value), "%W", "_") if validoutaccounts[cooked] ~= nil then Value.write(self, section, value) end end ---------------------------------------------------------------------------------------------------- s = m:section(NamedSection, "blacklisting", "call_routing", translate("Blacklisted Numbers"), translate("Enter phone numbers that you want to decline calls from automatically. \ You should probably omit the country code and any leading zeroes, but please \ experiment to make sure you are blocking numbers from your desired area successfully.")) s.anonymous = true b = s:option(DynamicList, "blacklist1", translate("Dynamic List of Blacklisted Numbers"), translate("Specify numbers individually here. Press enter to add more numbers.")) b.cast = "string" b.datatype = "uinteger" b = s:option(Value, "blacklist2", translate("Space-Separated List of Blacklisted Numbers"), translate("Copy-paste large lists of numbers here.")) b.template = "cbi/tvalue" b.rows = 3 return m
gpl-2.0
wez2020/bow
plugins/info.lua
72
5575
--[[ Print user identification/informations by replying their post or by providing their username or print_name. !info <text> is the least reliable because it will scan trough all of members and print all member with <text> in their print_name. chat_info can be displayed on group, send it into PM, or save as file then send it into group or PM. --]] do local function scan_name(extra, success, result) local founds = {} for k,member in pairs(result.members) do if extra.name then gp_member = extra.name fields = {'first_name', 'last_name', 'print_name'} elseif extra.user then gp_member = string.gsub(extra.user, '@', '') fields = {'username'} end for k,field in pairs(fields) do if member[field] and type(member[field]) == 'string' then if member[field]:match(gp_member) then founds[tostring(member.id)] = member end end end end if next(founds) == nil then -- Empty table send_large_msg(extra.receiver, (extra.name or extra.user)..' not found on this chat.') else local text = '' for k,user in pairs(founds) do text = text..'Name: '..(user.first_name or '')..' '..(user.last_name or '')..'\n' ..'First name: '..(user.first_name or '')..'\n' ..'Last name: '..(user.last_name or '')..'\n' ..'User name: @'..(user.username or '')..'\n' ..'ID: '..(user.id or '')..'\n\n' end send_large_msg(extra.receiver, text) end end local function action_by_reply(extra, success, result) local text = 'Name: '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'First name: '..(result.from.first_name or '')..'\n' ..'Last name: '..(result.from.last_name or '')..'\n' ..'User name: @'..(result.from.username or '')..'\n' ..'ID: '..result.from.id send_large_msg(extra.receiver, text) end local function returnids(extra, success, result) local chat_id = extra.msg.to.id local text = '['..result.id..'] '..result.title..'.\n' ..result.members_num..' members.\n\n' i = 0 for k,v in pairs(result.members) do i = i+1 if v.username then user_name = ' @'..v.username else user_name = '' end text = text..i..'. ['..v.id..'] '..user_name..' '..(v.first_name or '')..(v.last_name or '')..'\n' end if extra.matches == 'pm' then send_large_msg('user#id'..extra.msg.from.id, text) elseif extra.matches == 'txt' or extra.matches == 'pmtxt' then local textfile = '/tmp/chat_info_'..chat_id..'_'..os.date("%y%m%d.%H%M%S")..'.txt' local file = io.open(textfile, 'w') file:write(text) file:flush() file:close() if extra.matches == 'txt' then send_document('chat#id'..chat_id, textfile, rmtmp_cb, {file_path=textfile}) elseif extra.matches == 'pmtxt' then send_document('user#id'..extra.msg.from.id, textfile, rmtmp_cb, {file_path=textfile}) end elseif not extra.matches then send_large_msg('chat#id'..chat_id, text) end end local function run(msg, matches) local receiver = get_receiver(msg) if is_chat_msg(msg) then if msg.text == '!info' then if msg.reply_id then if is_mod(msg) then msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver}) end else local text = 'Name: '..(msg.from.first_name or '')..' '..(msg.from.last_name or '')..'\n' ..'First name: '..(msg.from.first_name or '')..'\n' ..'Last name: '..(msg.from.last_name or '')..'\n' ..'User name: @'..(msg.from.username or '')..'\n' ..'ID: ' .. msg.from.id local text = text..'\n\nYou are in group ' ..msg.to.title..' (ID: '..msg.to.id..')' return text end elseif is_mod(msg) and matches[1] == 'chat' then if matches[2] == 'pm' or matches[2] == 'txt' or matches[2] == 'pmtxt' then chat_info(receiver, returnids, {msg=msg, matches=matches[2]}) else chat_info(receiver, returnids, {msg=msg}) end elseif is_mod(msg) and string.match(matches[1], '^@.+$') then chat_info(receiver, scan_name, {receiver=receiver, user=matches[1]}) elseif is_mod(msg) and string.gsub(matches[1], ' ', '_') then user = string.gsub(matches[1], ' ', '_') chat_info(receiver, scan_name, {receiver=receiver, name=matches[1]}) end else return 'You are not in a group.' end end return { description = 'Know your id or the id of a chat members.', usage = { user = { '!info: will show your id and group id .' }, moderator = { '!info : will give you the id of member or yourself', '!info chat : the ids of chat', '!info chat txt : will give the ids of chat in text file', '!info chat pm : will give chat ids in Private ', '!info chat pmtxt : will give chat ids in text file to your privat', '!info <id> : will shot the ids of chat group', '!info @<user_name> : will return the info of username ', '!info <text> : will return the info of that name or last name' }, }, patterns = { "^!info$", "^!info (chat) (.*)$", "^!info (chat) (.*)$", "^!info (.*)$" }, run = run } end
gpl-2.0
mogh77/merseed
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
facebokiii/facebookplug
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
sundream/gamesrv
script/card/neutral/card263008.lua
1
2277
--<<card 导表开始>> local super = require "script.card.neutral.card163008" ccard263008 = class("ccard263008",super,{ sid = 263008, race = 6, name = "日怒保卫者", type = 201, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 1, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 2, maxhp = 3, crystalcost = 2, targettype = 0, halo = nil, desc = "战吼:使邻近的随从获得嘲讽。", effect = { onuse = {addbuff={sneer=60}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard263008:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard263008:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard263008:save() local data = super.save(self) -- todo: save data return data end return ccard263008
gpl-2.0
sBaildon/sInterface
embeds/rActionBar/bars.lua
1
9020
-- rActionBar: bars -- zork, 2016 ----------------------------- -- Variables ----------------------------- local A, L = ... ----------------------------- -- Init ----------------------------- --BagBar function rActionBar:CreateBagBar(addonName,cfg) cfg.blizzardBar = nil cfg.frameName = addonName.."BagBar" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle] hide; show" local buttonList = { MainMenuBarBackpackButton, CharacterBag0Slot, CharacterBag1Slot, CharacterBag2Slot, CharacterBag3Slot } local frame = L:CreateButtonFrame(cfg,buttonList) end --MicroMenuBar function rActionBar:CreateMicroMenuBar(addonName,cfg) cfg.blizzardBar = nil cfg.frameName = addonName.."MicroMenuBar" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle] hide; show" local buttonList = {} for idx, buttonName in next, MICRO_BUTTONS do local button = _G[buttonName] if button and button:IsShown() then table.insert(buttonList, button) end end local frame = L:CreateButtonFrame(cfg,buttonList) --special PetBattleFrame.BottomFrame.MicroButtonFrame:SetScript("OnShow", nil) OverrideActionBar:SetScript("OnShow", nil) MainMenuBar:SetScript("OnShow", nil) end --Bar1 function rActionBar:CreateActionBar1(addonName,cfg) L:HideMainMenuBar() cfg.blizzardBar = nil cfg.frameName = addonName.."Bar1" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle] hide; show" cfg.actionPage = cfg.actionPage or "[bar:6]6;[bar:5]5;[bar:4]4;[bar:3]3;[bar:2]2;[overridebar]14;[shapeshift]13;[vehicleui]12;[possessbar]12;[bonusbar:5]11;[bonusbar:4]10;[bonusbar:3]9;[bonusbar:2]8;[bonusbar:1]7;1" local buttonName = "ActionButton" local numButtons = NUM_ACTIONBAR_BUTTONS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) --fix the button grid for actionbar1 local function ToggleButtonGrid() if InCombatLockdown() then print("Grid toggle for actionbar1 is not possible in combat.") return end local showgrid = tonumber(GetCVar("alwaysShowActionBars")) for i, button in next, buttonList do button:SetAttribute("showgrid", showgrid) end end hooksecurefunc("MultiActionBar_UpdateGridVisibility", ToggleButtonGrid) --_onstate-page state driver for i, button in next, buttonList do frame:SetFrameRef(buttonName..i, button) end frame:Execute(([[ buttons = table.new() for i=1, %d do table.insert(buttons, self:GetFrameRef("%s"..i)) end ]]):format(numButtons, buttonName)) frame:SetAttribute("_onstate-page", [[ --print("_onstate-page","index",newstate) for i, button in next, buttons do button:SetAttribute("actionpage", newstate) end ]]) RegisterStateDriver(frame, "page", cfg.actionPage) end --Bar2 function rActionBar:CreateActionBar2(addonName,cfg) cfg.blizzardBar = MultiBarBottomLeft cfg.frameName = addonName.."Bar2" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle][overridebar][vehicleui][possessbar][shapeshift] hide; show" local buttonName = "MultiBarBottomLeftButton" local numButtons = NUM_ACTIONBAR_BUTTONS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) end --Bar3 function rActionBar:CreateActionBar3(addonName,cfg) cfg.blizzardBar = MultiBarBottomRight cfg.frameName = addonName.."Bar3" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle][overridebar][vehicleui][possessbar][shapeshift] hide; show" local buttonName = "MultiBarBottomRightButton" local numButtons = NUM_ACTIONBAR_BUTTONS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) end --Bar4 function rActionBar:CreateActionBar4(addonName,cfg) cfg.blizzardBar = MultiBarRight cfg.frameName = addonName.."Bar4" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle][overridebar][vehicleui][possessbar][shapeshift] hide; show" local buttonName = "MultiBarRightButton" local numButtons = NUM_ACTIONBAR_BUTTONS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) end --Bar5 function rActionBar:CreateActionBar5(addonName,cfg) cfg.blizzardBar = MultiBarLeft cfg.frameName = addonName.."Bar5" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle][overridebar][vehicleui][possessbar][shapeshift] hide; show" local buttonName = "MultiBarLeftButton" local numButtons = NUM_ACTIONBAR_BUTTONS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) end --StanceBar function rActionBar:CreateStanceBar(addonName,cfg) cfg.blizzardBar = StanceBarFrame cfg.frameName = addonName.."StanceBar" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle][overridebar][vehicleui][possessbar][shapeshift] hide; show" local buttonName = "StanceButton" local numButtons = NUM_STANCE_SLOTS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) --special StanceBarLeft:SetTexture(nil) StanceBarMiddle:SetTexture(nil) StanceBarRight:SetTexture(nil) end --PetBar function rActionBar:CreatePetBar(addonName,cfg) cfg.blizzardBar = PetActionBarFrame cfg.frameName = addonName.."PetBar" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[petbattle][overridebar][vehicleui][possessbar][shapeshift] hide; [pet] show; hide" local buttonName = "PetActionButton" local numButtons = NUM_PET_ACTION_SLOTS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) --special SlidingActionBarTexture0:SetTexture(nil) SlidingActionBarTexture1:SetTexture(nil) end --ExtraBar function rActionBar:CreateExtraBar(addonName,cfg) cfg.blizzardBar = ExtraActionBarFrame cfg.frameName = addonName.."ExtraBar" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[extrabar] show; hide" local buttonName = "ExtraActionButton" local numButtons = NUM_ACTIONBAR_BUTTONS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) --special ExtraActionBarFrame.ignoreFramePositionManager = true end --VehicleExitBar function rActionBar:CreateVehicleExitBar(addonName,cfg) cfg.blizzardBar = nil cfg.frameName = addonName.."VehicleExitBar" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[canexitvehicle]c;[mounted]m;n" cfg.frameVisibilityFunc = "exit" --create vehicle exit button local button = CreateFrame("CHECKBUTTON", A.."VehicleExitButton", nil, "ActionButtonTemplate, SecureHandlerClickTemplate") button.icon:SetTexture("interface\\addons\\"..A.."\\embeds\\rActionBar\\media\\vehicleexit") button:RegisterForClicks("AnyUp") local function OnClick(self) if UnitOnTaxi("player") then TaxiRequestEarlyLanding() else VehicleExit() end self:SetChecked(false) end button:SetScript("OnClick", OnClick) local buttonList = { button } local frame = L:CreateButtonFrame(cfg, buttonList) --[canexitvehicle] is not triggered on taxi, exit workaround frame:SetAttribute("_onstate-exit", [[ if CanExitVehicle() then self:Show() else self:Hide() end ]]) if not CanExitVehicle() then frame:Hide() end end --PossessExitBar, this is the two button bar to cancel a possess in progress function rActionBar:CreatePossessExitBar(addonName,cfg) cfg.blizzardBar = PossessBarFrame cfg.frameName = addonName.."PossessExitBar" cfg.frameParent = cfg.frameParent or UIParent cfg.frameTemplate = "SecureHandlerStateTemplate" cfg.frameVisibility = cfg.frameVisibility or "[possessbar] show; hide" local buttonName = "PossessButton" local numButtons = NUM_POSSESS_SLOTS local buttonList = L:GetButtonList(buttonName, numButtons) local frame = L:CreateButtonFrame(cfg,buttonList) --special PossessBackground1:SetTexture(nil) PossessBackground2:SetTexture(nil) end
mit
EvPowerTeam/EV_OP
feeds/luci/modules/admin-full/luasrc/model/cbi/admin_network/proto_ahcp.lua
96
2209
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local device, apn, service, pincode, username, password local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand mca = s:taboption("ahcp", Value, "multicast_address", translate("Multicast address")) mca.optional = true mca.placeholder = "ff02::cca6:c0f9:e182:5359" mca.datatype = "ip6addr" mca:depends("proto", "ahcp") port = s:taboption("ahcp", Value, "port", translate("Port")) port.optional = true port.placeholder = 5359 port.datatype = "port" port:depends("proto", "ahcp") fam = s:taboption("ahcp", ListValue, "_family", translate("Protocol family")) fam:value("", translate("IPv4 and IPv6")) fam:value("ipv4", translate("IPv4 only")) fam:value("ipv6", translate("IPv6 only")) fam:depends("proto", "ahcp") function fam.cfgvalue(self, section) local v4 = m.uci:get_bool("network", section, "ipv4_only") local v6 = m.uci:get_bool("network", section, "ipv6_only") if v4 then return "ipv4" elseif v6 then return "ipv6" end return "" end function fam.write(self, section, value) if value == "ipv4" then m.uci:set("network", section, "ipv4_only", "true") m.uci:delete("network", section, "ipv6_only") elseif value == "ipv6" then m.uci:set("network", section, "ipv6_only", "true") m.uci:delete("network", section, "ipv4_only") end end function fam.remove(self, section) m.uci:delete("network", section, "ipv4_only") m.uci:delete("network", section, "ipv6_only") end nodns = s:taboption("ahcp", Flag, "no_dns", translate("Disable DNS setup")) nodns.optional = true nodns.enabled = "true" nodns.disabled = "false" nodns.default = nodns.disabled nodns:depends("proto", "ahcp") ltime = s:taboption("ahcp", Value, "lease_time", translate("Lease validity time")) ltime.optional = true ltime.placeholder = 3666 ltime.datatype = "uinteger" ltime:depends("proto", "ahcp")
gpl-2.0
HubertRonald/FoulJob
Library/gtween.lua
1
18146
--[[ GTween for Gideros This code is MIT licensed, see http://www.opensource.org/licenses/mit-license.php Copyright (c) 2010 - 2011 Gideros Mobile Based on GTween 2.01 for ActionScript 3 http://gskinner.com/libraries/gtween/ GTween 2.01 for ActionScript 3 is MIT licensed, see http://www.opensource.org/licenses/mit-license.php Copyright (c) 2009 Grant Skinner Notes: * Documentation is derived from GTween 2.01's original documentation. * Plugins, GTweenTimeline and proxy objects are not supported. ]] --[[ * GTween is a light-weight instance oriented tween engine. This means that you instantiate tweens for specific purposes, and then reuse, update or discard them. * This is different than centralized tween engines where you "register" tweens with a global object. This provides a more familiar and useful interface * for object oriented programmers. * GTween boasts a number of advanced features: * - frame and time based durations/positions which can be set per tween * - simple sequenced tweens using .nextTween * - pause and resume individual tweens or all tweens * - jump directly to the end or beginning of a tween with :toEnd() or :toBeginning() * - jump to any arbitrary point in the tween with :setPosition() * - complete, init, and change callbacks * - smart garbage collector interactions (prevents collection while active, allows collection if target is collected) * - easy to set up in a single line of code * - can repeat or reflect a tween a specified number of times * - deterministic, so setting a position on a tween will (almost) always result in predictable results ]] --[[ GTween class allows to animate Gideros objects like Sprite, and everything inherited from Sprites. So what can you tween: ---------------------- x position y position alpha value scaleX ratio scaleY ratio rotation degrees Additional options: --------------------- delay - delay tweening for specified amount of second or frames (default: 0) ease - easing from easing.lua (default: linear) repeatCount - how many times to repeat animation (default: 1) reflect - reverse animation back (default: false) autoPlay - automatically start animation (default: true) swapValues - use provided values as starting ones and existing values as target values(default: false) timeScale - ratio of speed of animation (default: 1) useFrames - bool, use frames instead of seconds for tween duration dispatchEvents - dispatch tween event (default: false) possible events: init - initialization change - each time values are changed complete - when animation completes Here is an example of using GTween class: ----------------------------------------- --define what to animate local animate = {} animate.y = 100 animate.x = 100 animate.alpha = 0.5 animate.scaleX = 0.5 animate.scaleY = 0.5 animate.rotation = random(0, 360) --define GTween properties local properties = {} properties.delay = 0 -- wait until start gtween properties.ease = easing.inElastic properties.dispatchEvents = true --animate them --- First argument: sprite to animate --- Second argument: duration of animation in seconds or frames --- Third argument: properties to animate --- Fourth argument: GTween properties local tween = GTween.new(sprite, 10, animate, properties) --adding event on animaiton complete tween:addEventListener("complete", function() stage:removeChild(sprite) sprite = nil end) GTween class also provides some methods to manage tween animation: ------------------------------------------------------------------- GTween:isPaused() - check is tween is paused GTween:setPaused(value) - true or false to pause/unpause GTween:getPosition() - position of animation (time span) from -delay to repeatCount*duration GTween:setPosition(value) - jump to specified position of animation GTween:getDelay() - get delay value GTween:setDelay(value) - set delay in seconds or frames GTween:setValue(name, value) - change animation value, example setValue("alpha", 1) GTween:getValue(name) - get end value for specified property GTween:deleteValue(name) - delete value, so it won't be animated GTween:setValues(values) - set values to animate GTween:resetValues(values) - resets previous animation values and sets new ones GTween:getValues() - returns table with animation values GTween:getInitValue(name) - returns initial value of specified property GTween:swapValues() - make existing animation values as target values and start animation from provided animation values GTween:toBeginning() - go to beggining of animation and pause it GTween:toEnd() - go to the end of animation GTween.pauseAll = true or false stop all GTween Bonus content: You can use easing for GTween animations using easing.lua and here are the easing options: ---------------------------------------------------------------------------------------------------------- easing.inBack -- funny Winki Aircraft easing.outBack -- Nice easing.inOutBack easing.inBounce easing.outBounce -- maybe easing.inOutBounce easing.inCircular easing.outCircular easing.inOutCircular easing.inCubic easing.outCubic -- Nice easing.inOutCubic easing.inElastic easing.outElastic -- Nice easing.inOutElastic easing.inExponential easing.outExponential easing.inOutExponential easing.linear easing.inQuadratic easing.outQuadratic easing.inOutQuadratic easing.inQuartic easing.outQuartic easing.inOutQuartic easing.inQuintic easing.outQuintic easing.inOutQuintic easing.inSine easing.outSine easing.inOutSine -- Nice additional examples (thanks to Atilim ) ---------------------------------------------------------------------------------------------- And here is the correct way to chain tweens: local tween1 = GTween.new(sprite, 1, {x = 240}, {}) local tween2 = GTween.new(sprite, 1, {y = 100}, {autoPlay = false}) local tween3 = GTween.new(sprite, 1, {alpha = 0}, {autoPlay = false}) tween1.nextTween = tween2 tween2.nextTween = tween3 Also this is same: local tween3 = GTween.new(sprite, 1, {alpha = 0}, {autoPlay = false}) local tween2 = GTween.new(sprite, 1, {y = 100}, {autoPlay = false, nextTween = tween3}) local tween1 = GTween.new(sprite, 1, {x = 240}, {nextTween = tween2}) - See more at: http://appcodingeasy.com/Gideros-Mobile/Gideros-GTween-with-easing#sthash.vVpOetO7.dpuf ]] --------------------------- -- math functions --------------------------- local log = math.log local floor = math.floor --------------------------- GTween = Core.class(EventDispatcher) function GTween.linearEase(a, b, c, d) return a end local function copy(o1, o2) if o1 ~= nil then for n,v in pairs(o1) do local setter = o2._setters and o2._setters[n] if setter ~= nil then setter(o2, v) else o2[n] = v end end end return o2 end local function isNaN(z) return z ~= z end GTween.defaultDispatchEvents = false GTween.defaultEase = GTween.linearEase GTween.pauseAll = false GTween.timeScaleAll = 1 GTween.tickList = setmetatable({}, {__mode="k"}) GTween.tempTickList = {} GTween.gcLockList = {} function GTween.staticInit() GTween.shape = Shape.new() GTween.shape:addEventListener(Event.ENTER_FRAME, GTween.staticTick) GTween.time = os.timer() end function GTween.staticTick() local t = GTween.time GTween.time = os.timer() if GTween.pauseAll then return end local dt = (GTween.time - t) * GTween.timeScaleAll for tween in pairs(GTween.tickList) do tween:setPosition(tween._position + (tween.useFrames and GTween.timeScaleAll or dt) * tween.timeScale) end for k,v in pairs(GTween.tempTickList) do GTween.tickList[k] = v GTween.tempTickList[k] = nil end end --[[ * Constructs a new GTween instance. * * target: The object whose properties will be tweened. * duration: The length of the tween in frames or seconds depending on the timingMode. * values: An object containing end property values. For example, to tween to x=100, y=100, you could pass {x=100, y=100} as the values object. * props: An object containing properties to set on this tween. For example, you could pass {ease=myEase} to set the ease property of the new instance. It also supports a single special property "swapValues" that will cause :swapValues() to be called after the values specified in the values parameter are set. ]] function GTween:init(target, duration, values, props) self._delay = 0 self._paused = true self._position = log(-1) -- NaN self.autoPlay = true self.repeatCount = 1 self.timeScale = 1 self.ease = GTween.defaultEase self.dispatchEvents = GTween.defaultDispatchEvents self.target = target self.duration = duration local swap = nil if props then swap = props.swapValues props.swapValues = nil end copy(props, self) self:resetValues(values) if swap then self:swapValues() end if self.duration == 0 and self:getDelay() == 0 and self.autoPlay then self:setPosition(0) end end --[[ * Plays or pauses a tween. You can still change the position value externally on a paused * tween, but it will not be updated automatically. While paused is false, the tween is also prevented * from being garbage collected while it is active. * This is achieved in one of two ways: * 1. If the target object derives from EventDispatcher, then the tween will subscribe to a dummy event using a hard reference. This allows * the tween to be garbage collected if its target is also collected, and there are no other external references to it. * 2. If the target object is not an EventDispatcher, then the tween is placed in a global list, to prevent collection until it is paused or completes. * Note that pausing all tweens via the GTween.pauseAll static property will not free the tweens for collection. ]] function GTween:isPaused() return self._paused end function GTween:setPaused(value) if value == self._paused then return end self._paused = value if self._paused then GTween.tickList[self] = nil if self.target.removeEventListener ~= nil then self.target:removeEventListener("_", self.invalidate, self) end GTween.gcLockList[self] = nil else if isNaN(self._position) or (self.repeatCount ~= 0 and self._position >= self.repeatCount * self.duration) then -- reached the end, reset. self._inited = false; self.calculatedPosition = 0 self.calculatedPositionOld = 0 self.ratio = 0 self.ratioOld = 0 self.positionOld = 0 self._position = -self:getDelay() end GTween.tempTickList[self] = true if self.target.addEventListener ~= nil then self.target:addEventListener("_", self.invalidate, self) else GTween.gcLockList[self] = true end end end --[[ * Gets and sets the position of the tween in frames or seconds (depending on .useFrames). This value will * be constrained between -delay and repeatCount*duration. It will be resolved to a .calculatedPosition before * being applied. * * Negative values: * Values below 0 will always resolve to a calculatedPosition of 0. Negative values can be used to set up a delay on the tween, as the tween will have to count up to 0 before initing. * * Positive values: * Positive values are resolved based on the duration, repeatCount, and reflect properties. ]] function GTween:getPosition() return self._position end function GTween:setPosition(value) self.positionOld = self._position self.ratioOld = self.ratio self.calculatedPositionOld = self.calculatedPosition local maxPosition = self.repeatCount * self.duration local end_ = value >= maxPosition and self.repeatCount > 0 if end_ then if self.calculatedPositionOld == maxPosition then return end self._position = maxPosition self.calculatedPosition = (self.reflect and (self.repeatCount % 2 == 0)) and 0 or self.duration else self._position = value self.calculatedPosition = (self._position < 0) and 0 or (self._position % self.duration) if self.reflect and floor(self:getPosition() / self.duration) % 2 ~= 0 then self.calculatedPosition = self.duration - self.calculatedPosition end end self.ratio = (self.duration == 0 and self._position >= 0) and 1 or self.ease(self.calculatedPosition / self.duration, 0, 1, 1) if self.target and (self._position >= 0 or self.positionOld >= 0) and self.calculatedPosition ~= self.calculatedPositionOld then if not self._inited then self:init2() end for n in pairs(self._values) do local initVal = self._initValues[n] local rangeVal = self._rangeValues[n] local val = initVal + rangeVal * self.ratio self.target:set(n, val) end end if not self.suppressEvents then if self.dispatchEvents then self:dispatchEvt("change") end if self.onChange ~= nil then self:onChange() end end if end_ then self:setPaused(true) if self.nextTween then self.nextTween:setPaused(false) end if not self.suppressEvents then if self.dispatchEvents then self:dispatchEvt("complete") end if self.onComplete ~= nil then self:onComplete() end end end end --[[ * The length of the delay in frames or seconds (depending on .useFrames). * The delay occurs before a tween reads initial values or starts playing. ]] function GTween:getDelay() return self._delay end function GTween:setDelay(value) if self._position <= 0 then self._position = -value; end self._delay = value; end --[[ * Sets the numeric end value for a property on the target object that you would like to tween. * For example, if you wanted to tween to a new x position, you could use: myGTween:setValue("x",400). * * name: The name of the property to tween. * value: The numeric end value (the value to tween to). ]] function GTween:setValue(name, value) self._values[name] = value self:invalidate() end --[[ * Returns the end value for the specified property if one exists. * * name: The name of the property to return a end value for. ]] function GTween:getValue(name) return self._values[name] end --[[ * Removes a end value from the tween. This prevents the GTween instance from tweening the property. * * name: The name of the end property to delete. ]] function GTween:deleteValue(name) self._rangeValues[name] = nil self._initValues[name] = nil local result = self._values[name] ~= nil self._values[name] = nil return result end --[[ * Shorthand method for making multiple setProperty calls quickly. * This adds the specified properties to the values list. * * Example: set x and y end values: * myGTween:setProperties({x=200, y=400}) * * properties: An object containing end property values. ]] function GTween:setValues(values) copy(values, self._values, true) self:invalidate() end --[[ * Similar to :setValues(), but clears all previous end values * before setting the new ones. * * properties: An object containing end property values. ]] function GTween:resetValues(values) self._values = {} self:setValues(values) end --[[ * Returns the table of all end properties and their values. This is a copy of values, so modifying * the returned object will not affect the tween. ]] function GTween:getValues() return copy(self._values, {}) end --[[ * Returns the initial value for the specified property. * Note that the value will not be available until the tween inits. ]] function GTween:getInitValue(name) return self._initValues[name] end --[[ * Swaps the init and end values for the tween, effectively reversing it. * This should generally only be called before the tween starts playing. * This will force the tween to init if it hasn't already done so, which * may result in an onInit call. * It will also force a render (so the target immediately jumps to the new values * immediately) which will result in the onChange callback being called. * * You can also use the special "swapValues" property on the props parameter of * the GTween constructor to call :swapValues() after the values are set. * * The following example would tween the target from 100,100 to its current position: * GTween.new(ball, 2, {x=100, y=100}, {swapValues=true}) ]] function GTween:swapValues() if not self._inited then self:init2() end local o = self._values; self._values = self._initValues; self._initValues = o; for n,v in pairs(self._rangeValues) do self._rangeValues[n] = -v end if self._position < 0 then local pos = self.positionOld self:setPosition(0) self._position = self.positionOld self.positionOld = pos else self:setPosition(self._position) end end --[[ * Reads all of the initial values from target and calls the onInit callback. * This is called automatically when a tween becomes active (finishes delaying) * and when :swapValues() is called. It would rarely be used directly * but is exposed for possible use by power users. ]] function GTween:init2() self._inited = true self._initValues = {} self._rangeValues = {} for n in pairs(self._values) do self._initValues[n] = self.target:get(n) self._rangeValues[n] = self._values[n] - self._initValues[n]; end if not self.suppressEvents then if self.dispatchEvents then self:dispatchEvt("init") end if self.onInit ~= nil then self:onInit() end end end --[[ * Jumps the tween to its beginning and pauses it. This is the same as calling :setPosition(0) and :setPaused(true). ]] function GTween:toBeginning() self:setPosition(0) self:setPaused(true) end --[[ * Jumps the tween to its end and pauses it. This is roughly the same as calling :setPosition(repeatCount*duration). ]] function GTween:toEnd() self:setPosition((self.repeatCount > 0) and self.repeatCount * self.duration or self.duration) end function GTween:invalidate() self._inited = false; if self._position > 0 then self._position = 0 end if self.autoPlay then self:setPaused(false) end end function GTween:dispatchEvt(name) if self:hasEventListener(name) then self:dispatchEvent(Event.new(name)) end end GTween._getters = {paused = GTween.getPaused, delay = GTween.getDelay, position = GTween.getPosition} GTween._setters = {paused = GTween.setPaused, delay = GTween.setDelay, position = GTween.setPosition} GTween.staticInit()
mit
BrokenROM/external_skia
tools/lua/classify_rrect_clips.lua
160
3346
function sk_scrape_startcanvas(c, fileName) end function sk_scrape_endcanvas(c, fileName) end function classify_rrect(rrect) if (rrect:type() == "simple") then local x, y = rrect:radii(0) if (x == y) then return "simple_circle" else return "simple_oval" end elseif (rrect:type() == "complex") then local numNotSquare = 0 local rx, ry local same = true; local first_not_square_corner local last_not_square_corner for i = 1, 4 do local x, y = rrect:radii(i-1) if (x ~= 0 and y ~= 0) then if (numNotSquare == 0) then rx = x ry = y first_not_square_corner = i else last_not_square_corner = i if (rx ~= x or ry ~=y) then same = false end end numNotSquare = numNotSquare + 1 end end local numSquare = 4 - numNotSquare if (numSquare > 0 and same) then local corners = "corners" if (numSquare == 2) then if ((last_not_square_corner - 1 == first_not_square_corner) or (1 == first_not_square_corner and 4 == last_not_square_corner )) then corners = "adjacent_" .. corners else corners = "opposite_" .. corners end elseif (1 == numSquare) then corners = "corner" end if (rx == ry) then return "circles_with_" .. numSquare .. "_square_" .. corners else return "ovals_with_" .. numSquare .. "_square_" .. corners end end return "complex_unclassified" elseif (rrect:type() == "rect") then return "rect" elseif (rrect:type() == "oval") then local x, y = rrect:radii(0) if (x == y) then return "circle" else return "oval" end elseif (rrect:type() == "empty") then return "empty" else return "unknown" end end function print_classes(class_table) function sort_classes(a, b) return a.count > b.count end array = {} for k, v in pairs(class_table) do if (type(v) == "number") then array[#array + 1] = {class = k, count = v}; end end table.sort(array, sort_classes) local i for i = 1, #array do io.write(array[i].class, ": ", array[i].count, " (", array[i].count/class_table["total"] * 100, "%)\n"); end end function sk_scrape_accumulate(t) if (t.verb == "clipRRect") then local rrect = t.rrect table["total"] = (table["total"] or 0) + 1 local class = classify_rrect(rrect) table[class] = (table[class] or 0) + 1 end end function sk_scrape_summarize() print_classes(table) --[[ To use the web scraper comment out the above call to print_classes, run the code below, and in the aggregator pass agg_table to print_classes. for k, v in pairs(table) do if (type(v) == "number") then local t = "agg_table[\"" .. k .. "\"]" io.write(t, " = (", t, " or 0) + ", table[k], "\n" ); end end --]] end
bsd-3-clause
jdourlens/Driver-Arduino-IDE
LoveFrames/debug.lua
3
3463
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- debug library loveframes.debug = {} --[[--------------------------------------------------------- - func: draw() - desc: draws debug information --]]--------------------------------------------------------- function loveframes.debug.draw() -- do not draw anthing if debug is off local debug = loveframes.config["DEBUG"] if not debug then return end local infox = 5 local infoy = 40 local cols = loveframes.util.GetCollisions() local topcol = {type = none, children = {}, x = 0, y = 0, width = 0, height = 0} local objects = loveframes.util.GetAllObjects() local version = loveframes.version local stage = loveframes.stage local basedir = loveframes.config["DIRECTORY"] local loveversion = love._version local fps = love.timer.getFPS() local deltatime = love.timer.getDelta() local font = loveframes.basicfontsmall -- set the top most collision object for k, v in ipairs(cols) do if v:IsTopCollision() then topcol = v break end end -- show frame docking zones if topcol.type == "frame" then for k, v in pairs(topcol.dockzones) do love.graphics.setLineWidth(1) love.graphics.setColor(255, 0, 0, 100) love.graphics.rectangle("fill", v.x, v.y, v.width, v.height) love.graphics.setColor(255, 0, 0, 255) love.graphics.rectangle("line", v.x, v.y, v.width, v.height) end end -- outline the object that the mouse is hovering over love.graphics.setColor(255, 204, 51, 255) love.graphics.setLineWidth(2) love.graphics.rectangle("line", topcol.x - 1, topcol.y - 1, topcol.width + 2, topcol.height + 2) -- draw main debug box love.graphics.setFont(font) love.graphics.setColor(0, 0, 0, 200) love.graphics.rectangle("fill", infox, infoy, 200, 70) love.graphics.setColor(255, 0, 0, 255) love.graphics.print("Love Frames - Debug (" ..version.. " - " ..stage.. ")", infox + 5, infoy + 5) love.graphics.setColor(255, 255, 255, 255) love.graphics.print("LOVE Version: " ..loveversion, infox + 10, infoy + 20) love.graphics.print("FPS: " ..fps, infox + 10, infoy + 30) love.graphics.print("Delta Time: " ..deltatime, infox + 10, infoy + 40) love.graphics.print("Total Objects: " ..#objects, infox + 10, infoy + 50) -- draw object information if needed if #cols > 0 and topcol.type ~= "base" then love.graphics.setColor(0, 0, 0, 200) love.graphics.rectangle("fill", infox, infoy + 75, 200, 100) love.graphics.setColor(255, 0, 0, 255) love.graphics.print("Object Information", infox + 5, infoy + 80) love.graphics.setColor(255, 255, 255, 255) love.graphics.print("Type: " ..topcol.type, infox + 10, infoy + 95) if topcol.children then love.graphics.print("# of children: " .. #topcol.children, infox + 10, infoy + 105) else love.graphics.print("# of children: 0", infox + 10, infoy + 105) end if topcol.internals then love.graphics.print("# of internals: " .. #topcol.internals, infox + 10, infoy + 115) else love.graphics.print("# of internals: 0", infox + 10, infoy + 115) end love.graphics.print("X: " ..topcol.x, infox + 10, infoy + 125) love.graphics.print("Y: " ..topcol.y, infox + 10, infoy + 135) love.graphics.print("Width: " ..topcol.width, infox + 10, infoy + 145) love.graphics.print("Height: " ..topcol.height, infox + 10, infoy + 155) end end
mit
Android-AOSP/external_skia
tools/lua/dump_clipstack_at_restore.lua
147
1096
function sk_scrape_startcanvas(c, fileName) canvas = c clipstack = {} restoreCount = 0 end function sk_scrape_endcanvas(c, fileName) canvas = nil end function sk_scrape_accumulate(t) if (t.verb == "restore") then restoreCount = restoreCount + 1; -- io.write("Clip Stack at restore #", restoreCount, ":\n") io.write("Reduced Clip Stack at restore #", restoreCount, ":\n") for i = 1, #clipstack do local element = clipstack[i]; io.write("\t", element["op"], ", ", element["type"], ", aa:", tostring(element["aa"])) if (element["type"] == "path") then io.write(", fill: ", element["path"]:getFillType()) io.write(", segments: \"", element["path"]:getSegmentTypes(), "\"") io.write(", convex:", tostring(element["path"]:isConvex())) end io.write("\n") end io.write("\n") else -- clipstack = canvas:getClipStack() clipstack = canvas:getReducedClipStack() end end function sk_scrape_summarize() end
bsd-3-clause
ashfinal/awesome-hammerspoon
Spoons/CountDown.spoon/init.lua
2
3839
--- === CountDown === --- --- Tiny countdown with visual indicator --- --- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/CountDown.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/CountDown.spoon.zip) local obj = {} obj.__index = obj -- Metadata obj.name = "CountDown" obj.version = "1.0" obj.author = "ashfinal <ashfinal@gmail.com>" obj.homepage = "https://github.com/Hammerspoon/Spoons" obj.license = "MIT - https://opensource.org/licenses/MIT" obj.canvas = nil obj.timer = nil function obj:init() self.canvas = hs.canvas.new({x=0, y=0, w=0, h=0}):show() self.canvas:behavior(hs.canvas.windowBehaviors.canJoinAllSpaces) self.canvas:level(hs.canvas.windowLevels.status) self.canvas:alpha(0.35) self.canvas[1] = { type = "rectangle", action = "fill", fillColor = hs.drawing.color.osx_red, frame = {x="0%", y="0%", w="0%", h="100%"} } self.canvas[2] = { type = "rectangle", action = "fill", fillColor = hs.drawing.color.osx_green, frame = {x="0%", y="0%", w="0%", h="100%"} } end --- CountDown:startFor(minutes) --- Method --- Start a countdown for `minutes` minutes immediately. Calling this method again will kill the existing countdown instance. --- --- Parameters: --- * minutes - How many minutes local function canvasCleanup() if obj.timer then obj.timer:stop() obj.timer = nil end obj.canvas[1].frame.w = "0%" obj.canvas[2].frame.x = "0%" obj.canvas[2].frame.w = "0%" obj.canvas:frame({x=0, y=0, w=0, h=0}) end function obj:startFor(minutes) if obj.timer then canvasCleanup() else local mainScreen = hs.screen.mainScreen() local mainRes = mainScreen:fullFrame() obj.canvas:frame({x=mainRes.x, y=mainRes.y+mainRes.h-5, w=mainRes.w, h=5}) -- Set minimum visual step to 2px (i.e. Make sure every trigger updates 2px on screen at least.) local minimumStep = 2 local secCount = math.ceil(60*minutes) obj.loopCount = 0 if mainRes.w/secCount >= 2 then obj.timer = hs.timer.doEvery(1, function() obj.loopCount = obj.loopCount+1/secCount obj:setProgress(obj.loopCount, minutes) end) else local interval = 2/(mainRes.w/secCount) obj.timer = hs.timer.doEvery(interval, function() obj.loopCount = obj.loopCount+1/mainRes.w*2 obj:setProgress(obj.loopCount, minutes) end) end end return self end --- CountDown:pauseOrResume() --- Method --- Pause or resume the existing countdown. --- function obj:pauseOrResume() if obj.timer then if obj.timer:running() then obj.timer:stop() else obj.timer:start() end end end --- CountDown:setProgress(progress) --- Method --- Set the progress of visual indicator to `progress`. --- --- Parameters: --- * progress - an number specifying the value of progress (0.0 - 1.0) function obj:setProgress(progress, notifystr) if obj.canvas:frame().h == 0 then -- Make the canvas actully visible local mainScreen = hs.screen.mainScreen() local mainRes = mainScreen:fullFrame() obj.canvas:frame({x=mainRes.x, y=mainRes.y+mainRes.h-5, w=mainRes.w, h=5}) end if progress >= 1 then canvasCleanup() if notifystr then hs.notify.new({ title = "Time(" .. notifystr .. " mins) is up!", informativeText = "Now is " .. os.date("%X") }):send() end else obj.canvas[1].frame.w = tostring(progress) obj.canvas[2].frame.x = tostring(progress) obj.canvas[2].frame.w = tostring(1-progress) end end return obj
mit
sami2448/set
plugins/invite.lua
8
1153
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then -- Ignore bans send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then -- Ignore globall bans send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end --if not is_admin(msg) then -- For admins only ! --return 'Only admins can invite.' --end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^[Ii]nvite (.*)$" }, run = run } end
gpl-2.0
sBaildon/sInterface
modules/progressbar/reputation.lua
1
3973
local _, ns = ... local E = ns.E if not E:C('progressbars', 'enabled') then return end; local ProgressBars = ns.sInterfaceProgressBars local barName = "reputation" local PARAGON = PARAGON local reactions = {} for eclass, color in next, FACTION_BAR_COLORS do reactions[eclass] = {color.r, color.g, color.b} end -- Paragon reactions[MAX_REPUTATION_REACTION + 1] = {0, 0.5, 0.9} -- local function getReputationCurrent() -- local _, _, _, _, cur = GetWatchedFactionInfo() -- return cur -- end -- local function getReputationMax() -- local _, _, _, max = GetWatchedFactionInfo() -- return max -- end -- local function getReputationName() -- local name = GetWatchedFactionInfo() -- return name -- end local function GetReputation() local pendingReward local name, standingID, min, max, cur, factionID = GetWatchedFactionInfo() local friendID, _, _, _, _, _, standingText, _, nextThreshold = GetFriendshipReputation(factionID) if (friendID) then if (not nextThreshold) then min, max, cur = 0, 1, 1 -- force a full bar when maxed out end standingID = 5 -- force friends' color else local value, paragonNextThreshold, _, hasRewardPending = C_Reputation.GetFactionParagonInfo(factionID) if (value) then cur = value % paragonNextThreshold min = 0 max = paragonNextThreshold pendingReward = hasRewardPending standingID = MAX_REPUTATION_REACTION + 1 -- force paragon's color standingText = PARAGON end end max = max - min cur = cur - min -- cur and max are both 0 for maxed out factions if(cur == max) then cur, max = 1, 1 end standingText = standingText or GetText('FACTION_STANDING_LABEL' .. standingID, UnitSex('player')) return cur, max, name, factionID, standingID, standingText, pendingReward end local function Update(bar) local cur, max, name, _, standingID = GetReputation() if (name) then bar:SetAnimatedValues(cur, 0, max, standingID) local colors = reactions[standingID] bar:SetStatusBarColor(colors[1], colors[2], colors[3]) end end local function Disable(bar) bar:UnregisterEvent("UPDATE_FACTION") end local function Enable(bar) bar:RegisterEvent("UPDATE_FACTION") Update(bar) end local function reputationVisibility(self, selectedFactionIndex) local shouldEnable if (selectedFactionIndex ~= nil) then if (selectedFactionIndex > 0) and (selectedFactionIndex <= GetNumFactions()) then shouldEnable = true end elseif (not not (GetWatchedFactionInfo())) then shouldEnable = true end if (shouldEnable) then Enable(self.Reputation) ProgressBars:EnableBar(barName) else Disable(self.Reputation) ProgressBars:DisableBar(barName) end end local reputationHolder = ProgressBars:CreateBar(barName) reputationHolder:SetHeight(E:C('progressbars', 'reputation', 'height')) reputationHolder:SetScript("OnEvent", reputationVisibility) hooksecurefunc('SetWatchedFactionIndex', function(selectedFactionIndex) reputationVisibility(reputationHolder, selectedFactionIndex or 0) end) local reputation = CreateFrame("StatusBar", "ProgressBar", reputationHolder, "AnimatedStatusBarTemplate") reputation:SetMatchBarValueToAnimation(true) reputation:SetAllPoints(reputationHolder) reputation:SetStatusBarTexture(E:C('general', 'texture'), "ARTWORK") reputation:SetScript("OnEvent", Update) reputationHolder.Reputation = reputation C_Timer.After(1, function() reputationVisibility(reputationHolder, nil) end) local tooltip = GameTooltip reputationHolder:SetScript("OnEnter", function(self) local cur, max, name, _, _, standingText = GetReputation() tooltip:SetOwner(self, "ANCHOR_CURSOR") tooltip:ClearLines() tooltip:AddLine(name) tooltip:AddDoubleLine("Standing", standingText, 1, 1, 1) tooltip:AddDoubleLine("Current", E:CommaValue(cur), 1, 1, 1) tooltip:AddDoubleLine("Required", E:CommaValue(max), 1, 1, 1) tooltip:AddDoubleLine("To level", E:CommaValue((max-cur)), 1, 1, 1) tooltip:Show() end) reputationHolder:SetScript("OnLeave", function(self) tooltip:Hide() end)
mit
sundream/gamesrv
script/card/neutral/card162002.lua
1
3001
--<<card 导表开始>> local super = require "script.card.init" ccard162002 = class("ccard162002",super,{ sid = 162002, race = 6, name = "海巨人", type = 201, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 8, maxhp = 8, crystalcost = 10, targettype = 0, halo = nil, desc = "战场上每有一个其他随从,该牌的法力值消耗便减少(1)点。", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard162002:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard162002:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard162002:save() local data = super.save(self) -- todo: save data return data end function ccard162002:recompute() if self.addcrystalcost_buffid then self:delbuff(self.addcrystalcost_buffid) self.addcrystalcost_buffid = nil end local owner = self:getowner() local addcrystalcost = -#owner.warcards if addcrystalcost == 0 then return end local buff = self:newbuff({ addcrystalcost = addcrystalcost, }) self.addcrystalcost_buffid = self:addbuff(buff) end function ccard162002:onputinhand() ccard162002.recompute(self) end function ccard162002:after_putinwar(footman,pos,reason) if self.inarea ~= "hand" then return end ccard162002.recompute(self) end function ccard162002:after_removefromwar(footman) if self.inarea ~= "hand" then return end ccard162002.recompute(self) end return ccard162002
gpl-2.0
mahdikord/mahdi5
plugins/anti_spam.lua
435
3886
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds local data = load_data(_config.moderation.data) -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is one or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 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'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id -- Ignore mods,owner and admins if is_momod(msg) then return msg end local chat = msg.to.id local user = msg.from.id -- Return end if user was kicked before if kicktable[user] == true then return end kick_user(user, chat) if msg.to.type == "user" then block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end local name = user_print_name(msg.from) --save it to log file savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ") -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) local username = " " if msg.from.username ~= nil then username = msg.from.username end local name = user_print_name(msg.from) --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)") local log_group = 1 --set log group caht id --send it to log group send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)") end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
Lynx3d/tinker_tools
Libraries/LibSimpleWidgets/select.lua
2
8161
local BUTTON_NORMAL = "textures/dropdownbutton.png" local BUTTON_HIGHLIGHT = "textures/dropdownbutton_highlight.png" local BUTTON_CLICKED = "textures/dropdownbutton_clicked.png" -- Helper Functions local function contains(tbl, val) for k, v in pairs(tbl) do if v == val then return true end end return false end local function FindContext(frame) local parent = frame.GetParent and frame:GetParent() or nil if parent == nil then return frame else return FindContext(parent) end end local function UpdateCurrent(self) local item = self.dropdown:GetSelectedItem() if item == nil then self.current:SetText("Select...") else self.current:SetText(item) end end local function ResizeDropdown(self) local currentHeight = self.current:GetHeight() local itemsHeight = #self.dropdown:GetItems() * currentHeight self.dropdown:SetHeight(math.max(currentHeight, math.min(self.maxDropdownHeight, itemsHeight))) end -- Current Frame Events local function CurrentClick(self) local widget = self:GetParent() if not widget.enabled then return end local dropdown = widget.dropdown dropdown:SetVisible(not dropdown:GetVisible()) end -- Dropdown Frame Events local function DropdownItemSelect(self, item, value, index) local widget = self.widget UpdateCurrent(widget) if widget.Event.ItemSelect then widget.Event.ItemSelect(widget, item, value, index) end self:SetVisible(false) end -- Public Functions local function SetBorder(self, width, r, g, b, a) Library.LibSimpleWidgets.SetBorder(self.current, width, r, g, b, a) Library.LibSimpleWidgets.SetBorder(self.dropdown, width, r, g, b, a) end local function SetBackgroundColor(self, r, g, b, a) self.current:SetBackgroundColor(r, g, b, a) self.dropdown:SetBackgroundColor(r, g, b, a) end local function GetFontSize(self) return self.current:GetFontSize() end local function SetFontSize(self, size) assert(type(size) == "number", "param 1 must be a number!") self.current:SetFontSize(size) self.dropdown:SetFontSize(size) self:ResizeToFit() end local function GetShowArrow(self) return self.button:GetVisible() end local function SetShowArrow(self, showArrow) self.button:SetVisible(showArrow) end local function ResizeToFit(self) self.current:ClearAll() self:SetHeight(self.current:GetHeight()) local maxWidth = math.max(self.current:GetWidth(), self.dropdown:GetMaxWidth()) self.current:SetAllPoints(self) self:SetWidth(maxWidth + self.button:GetWidth()) ResizeDropdown(self) end local function GetEnabled(self) return self.enabled end local function SetEnabled(self, enabled) assert(type(enabled) == "boolean", "param 1 must be a boolean!") self.enabled = enabled if enabled then self.current:SetFontColor(1, 1, 1, 1) else self.current:SetFontColor(0.5, 0.5, 0.5, 1) self.dropdown:SetVisible(false) end self.dropdown:SetEnabled(enabled) end local function GetMaxDropdownHeight(self) return self.maxDropdownHeight end local function SetMaxDropdownHeight(self, maxDropdownHeight) self.maxDropdownHeight = maxDropdownHeight ResizeDropdown(self) end local function GetItems(self) return self.dropdown:GetItems() end local function SetItems(self, items, values) assert(type(items) == "table", "param 1 must be a table!") assert(values == nil or type(values) == "table", "param 2 must be a table!") self.dropdown:SetItems(items, values) ResizeDropdown(self) UpdateCurrent(self) end local function GetValues(self) return self.dropdown:GetValues() end local function GetSelectedItem(self) return self.dropdown:GetSelectedItem() end local function SetSelectedItem(self, item, silent) self.dropdown:SetSelectedItem(item, true) UpdateCurrent(self) if not silent and self.Event.ItemSelect then self.Event.ItemSelect(self, self.dropdown:GetSelectedItem(), self.dropdown:GetSelectedValue(), self.dropdown:GetSelectedIndex()) end end local function GetSelectedValue(self) return self.dropdown:GetSelectedValue() end local function SetSelectedValue(self, value, silent) self.dropdown:SetSelectedValue(value, true) UpdateCurrent(self) if not silent and self.Event.ItemSelect then self.Event.ItemSelect(self, self.dropdown:GetSelectedItem(), self.dropdown:GetSelectedValue(), self.dropdown:GetSelectedIndex()) end end local function GetSelectedIndex(self) return self.dropdown:GetSelectedIndex() end local function SetSelectedIndex(self, index, silent) self.dropdown:SetSelectedIndex(index, true) UpdateCurrent(self) if not silent and self.Event.ItemSelect then self.Event.ItemSelect(self, self.dropdown:GetSelectedItem(), self.dropdown:GetSelectedValue(), self.dropdown:GetSelectedIndex()) end end -- Constructor Function function Library.LibSimpleWidgets.Select(name, parent) local context = FindContext(parent) local widget = UI.CreateFrame("Frame", name, parent) widget.current = UI.CreateFrame("Text", widget:GetName().."Current", widget) widget.button = UI.CreateFrame("Texture", widget:GetName().."Button", widget) widget.dropdown = UI.CreateFrame("SimpleScrollList", widget:GetName().."DropdownScroller", context) widget.enabled = true widget.current:SetBackgroundColor(0, 0, 0, 1) widget.current:SetText("Select...") widget.current:SetLayer(1) widget.current.Event.LeftClick = CurrentClick widget.maxDropdownHeight = widget.current:GetHeight() * 10 widget.button:SetTexture("LibSimpleWidgets", BUTTON_NORMAL) local buttonWidth = widget.button:GetWidth() local buttonHeight = widget.button:GetHeight() widget.button:SetPoint("TOPRIGHT", widget.current, "TOPRIGHT", 1, -1) widget.button:SetPoint("BOTTOMRIGHT", widget.current, "BOTTOMRIGHT", 1, 1) widget.button:SetLayer(2) widget.button.Event.LeftClick = CurrentClick widget.button.Event.MouseIn = function(self) self:SetTexture("LibSimpleWidgets", BUTTON_HIGHLIGHT) end widget.button.Event.MouseOut = function(self) self:SetTexture("LibSimpleWidgets", BUTTON_NORMAL) end widget.button.Event.LeftDown = function(self) self:SetTexture("LibSimpleWidgets", BUTTON_CLICKED) end widget.button.Event.LeftUp = function(self) self:SetTexture("LibSimpleWidgets", BUTTON_HIGHLIGHT) end widget.button.Event.Size = function(self) self:SetWidth(self:GetHeight() / 19 * 21) end widget.dropdown.widget = widget widget.dropdown:SetPoint("TOPLEFT", widget.current, "BOTTOMLEFT", 0, 2) widget.dropdown:SetPoint("TOPRIGHT", widget.current, "BOTTOMRIGHT", 0, 2) widget.dropdown:SetLayer(1000000) widget.dropdown:SetVisible(false) widget.dropdown:SetBackgroundColor(0, 0, 0, 1) widget.dropdown.Event.ItemSelect = DropdownItemSelect ResizeDropdown(widget) widget:SetWidth(widget.current:GetWidth() + buttonWidth) widget:SetHeight(widget.current:GetHeight()) widget.current:SetAllPoints(widget) widget.SetBorder = SetBorder widget.SetBackgroundColor = SetBackgroundColor widget.GetFontSize = GetFontSize widget.SetFontSize = SetFontSize widget.GetShowArrow = GetShowArrow widget.SetShowArrow = SetShowArrow widget.ResizeToDefault = ResizeToFit -- TODO: Deprecated. widget.ResizeToFit = ResizeToFit widget.GetEnabled = GetEnabled widget.SetEnabled = SetEnabled widget.GetMaxDropdownHeight = GetMaxDropdownHeight widget.SetMaxDropdownHeight = SetMaxDropdownHeight widget.GetItems = GetItems widget.SetItems = SetItems widget.GetValues = GetValues widget.GetSelectedIndex = GetSelectedIndex widget.SetSelectedIndex = SetSelectedIndex widget.GetSelectedItem = GetSelectedItem widget.SetSelectedItem = SetSelectedItem widget.GetSelectedValue = GetSelectedValue widget.SetSelectedValue = SetSelectedValue Library.LibSimpleWidgets.EventProxy(widget, {"ItemSelect"}) Library.LibSimpleWidgets.SetBorder(widget.current, 1, 165/255, 162/255, 134/255, 1, "t") Library.LibSimpleWidgets.SetBorder(widget.current, 1, 103/255, 98/255, 88/255, 1, "lr") Library.LibSimpleWidgets.SetBorder(widget.current, 1, 17/255, 66/255, 55/255, 1, "b") Library.LibSimpleWidgets.SetBorder(widget.dropdown, 1, 165/255, 162/255, 134/255, 1, "tblr") return widget end
bsd-3-clause
codemon66/Urho3D
bin/Data/LuaScripts/13_Ragdolls.lua
24
19430
-- Ragdoll example. -- This sample demonstrates: -- - Detecting physics collisions -- - Moving an AnimatedModel's bones with physics and connecting them with constraints -- - Using rolling friction to stop rolling objects from moving infinitely require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("PhysicsWorld") scene_:CreateComponent("DebugRenderer") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y local floorNode = scene_:CreateChild("Floor") floorNode.position = Vector3(0.0, -0.5, 0.0) floorNode.scale = Vector3(500.0, 1.0, 500.0) local floorObject = floorNode:CreateComponent("StaticModel") floorObject.model = cache:GetResource("Model", "Models/Box.mdl") floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Make the floor physical by adding RigidBody and CollisionShape components local body = floorNode:CreateComponent("RigidBody") -- We will be spawning spherical objects in this sample. The ground also needs non-zero rolling friction so that -- the spheres will eventually come to rest body.rollingFriction = 0.15 local shape = floorNode:CreateComponent("CollisionShape") -- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.) shape:SetBox(Vector3(1.0, 1.0, 1.0)) -- Create animated models for z = -1, 1 do for x = -4, 4 do local modelNode = scene_:CreateChild("Jack") modelNode.position = Vector3(x * 5.0, 0.0, z * 5.0) modelNode.rotation = Quaternion(0.0, 180.0, 0.0) local modelObject = modelNode:CreateComponent("AnimatedModel") modelObject.model = cache:GetResource("Model", "Models/Jack.mdl") modelObject.material = cache:GetResource("Material", "Materials/Jack.xml") modelObject.castShadows = true -- Set the model to also update when invisible to avoid staying invisible when the model should come into -- view, but does not as the bounding box is not updated modelObject.updateInvisible = true -- Create a rigid body and a collision shape. These will act as a trigger for transforming the -- model into a ragdoll when hit by a moving object local body = modelNode:CreateComponent("RigidBody") -- The trigger mode makes the rigid body only detect collisions, but impart no forces on the -- colliding objects body.trigger = true local shape = modelNode:CreateComponent("CollisionShape") -- Create the capsule shape with an offset so that it is correctly aligned with the model, which -- has its origin at the feet shape:SetCapsule(0.7, 2.0, Vector3(0.0, 1.0, 0.0)) -- Create a custom script object that reacts to collisions and creates the ragdoll modelNode:CreateScriptObject("CreateRagdoll") end end -- Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside -- the scene, because we want it to be unaffected by scene load / save cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the floor cameraNode.position = Vector3(0.0, 5.0, -20.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText( "Use WASD keys and mouse to move\n".. "LMB to spawn physics objects\n".. "F5 to save scene, F7 to load\n".. "Space to toggle physics debug geometry") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request -- debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch +MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- "Shoot" a physics object with left mousebutton if input:GetMouseButtonPress(MOUSEB_LEFT) then SpawnObject() end -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable -- directory if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Ragdolls.xml") end if input:GetKeyPress(KEY_F7) then scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Ragdolls.xml") end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end end function SpawnObject() local boxNode = scene_:CreateChild("Sphere") boxNode.position = cameraNode.position boxNode.rotation = cameraNode.rotation boxNode:SetScale(0.25) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Sphere.mdl") boxObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml") boxObject.castShadows = true local body = boxNode:CreateComponent("RigidBody") body.mass = 1.0 body.rollingFriction = 0.15 local shape = boxNode:CreateComponent("CollisionShape") shape:SetSphere(1.0) local OBJECT_VELOCITY = 10.0 -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component -- to overcome gravity better body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end function HandlePostRenderUpdate(eventType, eventData) -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret if drawDebug then scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true) end end -- CreateRagdoll script object class CreateRagdoll = ScriptObject() function CreateRagdoll:Start() -- Subscribe physics collisions that concern this scene node self:SubscribeToEvent(self.node, "NodeCollision", "CreateRagdoll:HandleNodeCollision") end function CreateRagdoll:HandleNodeCollision(eventType, eventData) -- Get the other colliding body, make sure it is moving (has nonzero mass) local otherBody = eventData["OtherBody"]:GetPtr("RigidBody") if otherBody.mass > 0.0 then -- We do not need the physics components in the AnimatedModel's root scene node anymore self.node:RemoveComponent("RigidBody") self.node:RemoveComponent("CollisionShape") -- Create RigidBody & CollisionShape components to bones self:CreateRagdollBone("Bip01_Pelvis", SHAPE_BOX, Vector3(0.3, 0.2, 0.25), Vector3(0.0, 0.0, 0.0), Quaternion(0.0, 0.0, 0.0)) self:CreateRagdollBone("Bip01_Spine1", SHAPE_BOX, Vector3(0.35, 0.2, 0.3), Vector3(0.15, 0.0, 0.0), Quaternion(0.0, 0.0, 0.0)) self:CreateRagdollBone("Bip01_L_Thigh", SHAPE_CAPSULE, Vector3(0.175, 0.45, 0.175), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_Thigh", SHAPE_CAPSULE, Vector3(0.175, 0.45, 0.175), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_L_Calf", SHAPE_CAPSULE, Vector3(0.15, 0.55, 0.15), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_Calf", SHAPE_CAPSULE, Vector3(0.15, 0.55, 0.15), Vector3(0.25, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_Head", SHAPE_BOX, Vector3(0.2, 0.2, 0.2), Vector3(0.1, 0.0, 0.0), Quaternion(0.0, 0.0, 0.0)) self:CreateRagdollBone("Bip01_L_UpperArm", SHAPE_CAPSULE, Vector3(0.15, 0.35, 0.15), Vector3(0.1, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_UpperArm", SHAPE_CAPSULE, Vector3(0.15, 0.35, 0.15), Vector3(0.1, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_L_Forearm", SHAPE_CAPSULE, Vector3(0.125, 0.4, 0.125), Vector3(0.2, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) self:CreateRagdollBone("Bip01_R_Forearm", SHAPE_CAPSULE, Vector3(0.125, 0.4, 0.125), Vector3(0.2, 0.0, 0.0), Quaternion(0.0, 0.0, 90.0)) -- Create Constraints between bones self:CreateRagdollConstraint("Bip01_L_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, 1.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_R_Thigh", "Bip01_Pelvis", CONSTRAINT_CONETWIST, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, 1.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_L_Calf", "Bip01_L_Thigh", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_R_Calf", "Bip01_R_Thigh", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_Spine1", "Bip01_Pelvis", CONSTRAINT_HINGE, Vector3(0.0, 0.0, 1.0), Vector3(0.0, 0.0, 1.0), Vector2(45.0, 0.0), Vector2(-10.0, 0.0), true) self:CreateRagdollConstraint("Bip01_Head", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(-1.0, 0.0, 0.0), Vector3(-1.0, 0.0, 0.0), Vector2(0.0, 30.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_L_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0, -1.0, 0.0), Vector3(0.0, 1.0, 0.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), false) self:CreateRagdollConstraint("Bip01_R_UpperArm", "Bip01_Spine1", CONSTRAINT_CONETWIST, Vector3(0.0, -1.0, 0.0), Vector3(0.0, 1.0, 0.0), Vector2(45.0, 45.0), Vector2(0.0, 0.0), false) self:CreateRagdollConstraint("Bip01_L_Forearm", "Bip01_L_UpperArm", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) self:CreateRagdollConstraint("Bip01_R_Forearm", "Bip01_R_UpperArm", CONSTRAINT_HINGE, Vector3(0.0, 0.0, -1.0), Vector3(0.0, 0.0, -1.0), Vector2(90.0, 0.0), Vector2(0.0, 0.0), true) -- Disable keyframe animation from all bones so that they will not interfere with the ragdoll local model = self.node:GetComponent("AnimatedModel") local skeleton = model.skeleton for i = 0, skeleton.numBones - 1 do skeleton:GetBone(i).animated = false end -- Finally remove self (the ScriptInstance which holds this script object) from the scene node. Note that this must -- be the last operation performed in the function self.instance:Remove() end end function CreateRagdoll:CreateRagdollBone(boneName, type, size, position, rotation) -- Find the correct child scene node recursively local boneNode = self.node:GetChild(boneName, true) if boneNode == nil then print("Could not find bone " .. boneName .. " for creating ragdoll physics components\n") return end local body = boneNode:CreateComponent("RigidBody") -- Set mass to make movable body.mass = 1.0 -- Set damping parameters to smooth out the motion body.linearDamping = 0.05 body.angularDamping = 0.85 -- Set rest thresholds to ensure the ragdoll rigid bodies come to rest to not consume CPU endlessly body.linearRestThreshold = 1.5 body.angularRestThreshold = 2.5 local shape = boneNode:CreateComponent("CollisionShape") -- We use either a box or a capsule shape for all of the bones if type == SHAPE_BOX then shape:SetBox(size, position, rotation) else shape:SetCapsule(size.x, size.y, position, rotation) end end function CreateRagdoll:CreateRagdollConstraint(boneName, parentName, type, axis, parentAxis, highLimit, lowLimit, disableCollision) local boneNode = self.node:GetChild(boneName, true) local parentNode = self.node:GetChild(parentName, true) if boneNode == nil then print("Could not find bone " .. boneName .. " for creating ragdoll constraint\n") return end if parentNode == nil then print("Could not find bone " .. parentName .. " for creating ragdoll constraint\n") return end local constraint = boneNode:CreateComponent("Constraint") constraint.constraintType = type -- Most of the constraints in the ragdoll will work better when the connected bodies don't collide against each other constraint.disableCollision = disableCollision -- The connected body must be specified before setting the world position constraint.otherBody = parentNode:GetComponent("RigidBody") -- Position the constraint at the child bone we are connecting constraint.worldPosition = boneNode.worldPosition -- Configure axes and limits constraint.axis = axis constraint.otherAxis = parentAxis constraint.highLimit = highLimit constraint.lowLimit = lowLimit end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
EvPowerTeam/EV_OP
feeds/luci/applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-chan.lua
80
1726
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true chan_agent = module:option(ListValue, "chan_agent", "Agent Proxy Channel", "") chan_agent:value("yes", "Load") chan_agent:value("no", "Do Not Load") chan_agent:value("auto", "Load as Required") chan_agent.rmempty = true chan_alsa = module:option(ListValue, "chan_alsa", "Channel driver for GTalk", "") chan_alsa:value("yes", "Load") chan_alsa:value("no", "Do Not Load") chan_alsa:value("auto", "Load as Required") chan_alsa.rmempty = true chan_gtalk = module:option(ListValue, "chan_gtalk", "Channel driver for GTalk", "") chan_gtalk:value("yes", "Load") chan_gtalk:value("no", "Do Not Load") chan_gtalk:value("auto", "Load as Required") chan_gtalk.rmempty = true chan_iax2 = module:option(Flag, "chan_iax2", "Option chan_iax2", "") chan_iax2.rmempty = true chan_local = module:option(ListValue, "chan_local", "Local Proxy Channel", "") chan_local:value("yes", "Load") chan_local:value("no", "Do Not Load") chan_local:value("auto", "Load as Required") chan_local.rmempty = true chan_sip = module:option(ListValue, "chan_sip", "Session Initiation Protocol (SIP)", "") chan_sip:value("yes", "Load") chan_sip:value("no", "Do Not Load") chan_sip:value("auto", "Load as Required") chan_sip.rmempty = true return cbimap
gpl-2.0
sundream/gamesrv
script/card/golden/card214001.lua
1
2320
--<<card 导表开始>> local super = require "script.card.golden.card114001" ccard214001 = class("ccard214001",super,{ sid = 214001, race = 1, name = "冰锥术", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 4, targettype = 22, halo = nil, desc = "冻结一个随从和其相邻随从,并对他们造成1点伤害", effect = { onuse = {magic_hurt=1,addbuff={freeze=1,lifecircle=2}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard214001:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard214001:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard214001:save() local data = super.save(self) -- todo: save data return data end return ccard214001
gpl-2.0
cls1991/DataManager
dataserver/webservice.lua
1
4013
local skynet = require "skynet" local socket = require "socket" local httpd = require "http.httpd" local sockethelper = require "http.sockethelper" local urllib = require "http.url" local table = table local string = string local print_r = require "print_r" local Player = require "player" local PlayerManager = require "playermanager" local DeskManager = require "deskmanager" local mode = ... if mode == "agent" then local REQUEST = {} -- http request分发器, 简单实现 -- 后期需要url格式验证 local function request_dispatch(path, query) if path ~= "/" then return "" else local cmd = tonumber(query["cmd"]) local f = assert(REQUEST[COMMAND_HANDLER_MAP[cmd]]) return f(query) end end local function response(id, ...) local ok, err = httpd.write_response(sockethelper.writefunc(id), ...) if not ok then -- if err == sockethelper.socket_error , that means socket closed. skynet.error(string.format("fd = %d, %s", id, err)) end end skynet.start(function() skynet.dispatch("lua", function (_,_,id) socket.start(id) -- limit request body size to 8192 (you can pass nil to unlimit) local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), 8192) if code then if code ~= 200 then response(id, code) else local path, query = urllib.parse(url) local q = {} if query then q = urllib.parse_query(query) end local result = request_dispatch(path, q) response(id, code, result) end else if url == sockethelper.socket_error then skynet.error("socket closed") else skynet.error(url) end end socket.close(id) end) end) else skynet.start(function() local agent = {} for i= 1, 20 do agent[i] = skynet.newservice(SERVICE_NAME, "agent") end -- -- test player -- local p = Player.new(145) -- PlayerManager:get_instance():add_player(p) -- local all_players = PlayerManager:get_instance():get_all_players() -- print_r(all_players) -- local data = p:get_player_data() -- print_r(data) -- p:set_username("cls1991") -- p:save() -- local data2 = p:get_player_data() -- print_r(data2) -- local p2 = PlayerManager:get_instance():get_player(p:get_playerid()) -- print_r(p2:get_player_data()) -- test desk local dm = DeskManager:get_instance() local desk_new = dm:create_desk(1) local all_desks = dm:get_all_desks() -- print_r(all_desks) local deskid = 0 for _, desk in pairs(all_desks) do deskid = desk:get_deskid() -- local desk_player_ids = desk:get_desk_players() -- print_r(desk:get_desk_data()) -- local desk_players = dm:get_desk_all_players(deskid) -- print_r(desk_players) end -- test desk player local desk_player_new = dm:create_desk_player(deskid, 152) print_r(desk_player_new) local desk_players = dm:get_desk_all_players(deskid) print_r(desk_players) local balance = 1 local id = socket.listen("0.0.0.0", 20001) skynet.error("Listen web port 20001") socket.start(id , function(id, addr) skynet.error(string.format("%s connected, pass it to agent :%08x", addr, agent[balance])) skynet.send(agent[balance], "lua", id) balance = balance + 1 if balance > #agent then balance = 1 end end) end) end
apache-2.0
olostan/mudlet
src/mudlet-lua/lua/luadoc/taglet/standard/tags.lua
20
5259
-- added filename tag ------------------------------------------------------------------------------- -- 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 copyright (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function description (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function filename (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["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 handlers["filename"] = filename ------------------------------------------------------------------------------- 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
gpl-2.0
teasquat/bestfriend
src/entities/player.lua
1
6719
local player_factory = {} function player_factory.make(x, y) local player = { frontness = 100, x = x, y = y, spawn = { x = x, y = y, }, -- velocity dx = 0, dy = 0, -- movement acc = 30, -- acceleration frcx = 0.1, -- friction x frcy = 1.5, -- friction y -- (kinda-lol) static w = 16, -- width h = 16, -- height right = "right", left = "left", jump = "x", pew = "c", -- jumping grounded = false, -- whether or not am touching ground jump_force = 7, -- how much force to apply when normal jumping -- wall jumping wall_force = 6, -- how much force to apply when wall jumping wall = 0, -- static gravity = 30, -- pet stuff pet = nil, picked_up = true, -- status status = "ignore", type = "player", -- animation walk = {}, walk_n = {}, neutral = {}, neutral_n = {}, index = 1, dir = 1, tshirt = {}, beard = {}, tshirt_image = nil, beard_image = nil } function player:load() world:add(self, self.x, self.y, self.w, self.h) self.walk[1] = love.graphics.newImage("assets/player/walk1.png") self.walk[2] = love.graphics.newImage("assets/player/walk2.png") self.walk_n[1] = love.graphics.newImage("assets/player/walk_n1.png") self.walk_n[2] = love.graphics.newImage("assets/player/walk_n2.png") self.neutral[1] = love.graphics.newImage("assets/player/neutral.png") self.neutral_n[1] = love.graphics.newImage("assets/player/neutral_n.png") self.current = self.walk self.tshirt = {r = math.random(50, 230), g = math.random(50, 230), b=math.random(50, 230) } self.beard = {r = math.random(50, 230), g = math.random(50, 230), b=math.random(50, 230) } self.tshirt_image = love.graphics.newImage("assets/cosmetics/tshirt" .. math.random(1,2) .. ".png") self.beard_image = love.graphics.newImage("assets/cosmetics/beard1.png") -- bad konami stuff local pet_ref = self.pet self.konami_rainbow = konami.add({ pattern = {"left", "right", "right", "left", "x", "x", "c", "x"}, onStart = function() pet_ref.rainbow_stuff = true end, }) end function player:update(dt) konami.update(dt) self.index = self.index + dt * 2 * self.dx self.dir = math.sign(self.dx) or self.dir if self.picked_up then self.pet.dir = self.dir end local still = self.dx < 0.005 and self.dx > -0.005 if self.picked_up then if still then self.current = self.neutral_n else self.current = self.walk end else if still then self.current = self.neutral else self.current = self.walk_n end end if love.keyboard.isDown(self.right) then self.dx = self.dx + self.acc * dt end if love.keyboard.isDown(self.left) then self.dx = self.dx - self.acc * dt end self.dx = self.dx - self.wall * dt self.dy = self.dy + self.gravity * dt -- friction self.dx = self.dx - (self.dx / self.frcx) * dt self.dy = self.dy - (self.dy / self.frcy) * dt -- movement self.x, self.y, self.cols = world:move(self, self.x + self.dx, self.y + self.dy, ignore_filter) self.grounded = false local ww, wh = camera:view_dimensions() camera.x = math.lerp(camera.x, self.x + self.w / 2 - ww / 2, dt * 3) -- interpolate camera towards player camera.y = math.lerp(camera.y, self.y + self.h / 2 - wh / 1.45, dt * 2.5) -- interpolate camera towards player self.wall = 0 for i, v in ipairs(self.cols) do if v.normal.y ~= 0 then if v.normal.y == -1 then local shake = self.dy * 2 local epsilon = 2 if shake < epsilon then shake = 0 elseif -shake > -epsilon then shake = 0 end self.grounded = true end if v.other ~= self.pet then self.dy = 0 end end if v.normal.x ~= 0 then self.dx = 0 if not self.grounded then self.wall = v.normal.x end end end if self.y > love.graphics.getHeight() * 3 then self:die() end if self.picked_up then self.pet.y = self.y - self.h self.pet.x = self.x end end function player:draw() -- TODO: make good graphics love.graphics.setColor(255, 255, 255) love.graphics.draw(self.current[math.floor(self.index % #self.current) + 1], self.x + self.w / 2, self.y, 0, self.dir, 1, self.w / 2) love.graphics.setColor(self.tshirt.r, self.tshirt.g, self.tshirt.b) love.graphics.draw(self.tshirt_image, self.x + self.w / 2, self.y, 0, self.dir, 1, self.w / 2) love.graphics.setColor(self.beard.r, self.beard.g, self.beard.b) love.graphics.draw(self.beard_image, self.x + self.w / 2, self.y, 0, self.dir, 1, self.w / 2) end function player:throw() if self.picked_up then self.picked_up = false self.pet.picked_up = false local throw_x, throw_y = self.dx, self.dy if throw_x + throw_y < 0.5 and throw_x + throw_y > -0.5 then if throw_y < 0.005 and throw_y > -0.005 then throw_y = throw_y - 1.5 end if throw_x < 0.5 and throw_x > -0.5 then throw_x = throw_x * 10 end if throw_y < 0.5 and throw_y > -0.5 then throw_y = throw_y * 10 end end self.pet.dx = throw_x * 5 self.pet.dy = throw_y * 4 end end function player:pick_up() for i, v in ipairs(self.cols) do if v.other == self.pet then self.picked_up = true self.pet.picked_up = true end end end function player:press(key, isrepeat) konami.keypressed(key, isrepeat) if key == self.jump then if self.grounded then self.dy = -self.jump_force elseif self.wall ~= 0 then self.dy = -self.wall_force self.dx = self.wall_force / 1.5 * self.wall end elseif key == self.pew then if self.picked_up then self:throw() else self:pick_up() end elseif key == "q" then client:send("close") for i=1,100000 do client:receive() end love.event.quit() end end function player:die() spawnpoint = spawns[math.random(1, #spawns)] self.x, self.y = spawnpoint.x, spawnpoint.y world:update(self, self.x, self.y) self.picked_up = true self.pet.picked_up = true end function player:socket() client:send("pl_" .. self.x .. ":" .. self.y .. ":" .. self.dx .. ":" .. self.dy .. "\n") end return player end return player_factory
mit
vincent-vivian-liu/redis
deps/lua/test/life.lua
888
2635
-- life.lua -- original by Dave Bollinger <DBollinger@compuserve.com> posted to lua-l -- modified to use ANSI terminal escape sequences -- modified to use for instead of while local write=io.write ALIVE="¥" DEAD="þ" ALIVE="O" DEAD="-" function delay() -- NOTE: SYSTEM-DEPENDENT, adjust as necessary for i=1,10000 do end -- local i=os.clock()+1 while(os.clock()<i) do end end function ARRAY2D(w,h) local t = {w=w,h=h} for y=1,h do t[y] = {} for x=1,w do t[y][x]=0 end end return t end _CELLS = {} -- give birth to a "shape" within the cell array function _CELLS:spawn(shape,left,top) for y=0,shape.h-1 do for x=0,shape.w-1 do self[top+y][left+x] = shape[y*shape.w+x+1] end end end -- run the CA and produce the next generation function _CELLS:evolve(next) local ym1,y,yp1,yi=self.h-1,self.h,1,self.h while yi > 0 do local xm1,x,xp1,xi=self.w-1,self.w,1,self.w while xi > 0 do local sum = self[ym1][xm1] + self[ym1][x] + self[ym1][xp1] + self[y][xm1] + self[y][xp1] + self[yp1][xm1] + self[yp1][x] + self[yp1][xp1] next[y][x] = ((sum==2) and self[y][x]) or ((sum==3) and 1) or 0 xm1,x,xp1,xi = x,xp1,xp1+1,xi-1 end ym1,y,yp1,yi = y,yp1,yp1+1,yi-1 end end -- output the array to screen function _CELLS:draw() local out="" -- accumulate to reduce flicker for y=1,self.h do for x=1,self.w do out=out..(((self[y][x]>0) and ALIVE) or DEAD) end out=out.."\n" end write(out) end -- constructor function CELLS(w,h) local c = ARRAY2D(w,h) c.spawn = _CELLS.spawn c.evolve = _CELLS.evolve c.draw = _CELLS.draw return c end -- -- shapes suitable for use with spawn() above -- HEART = { 1,0,1,1,0,1,1,1,1; w=3,h=3 } GLIDER = { 0,0,1,1,0,1,0,1,1; w=3,h=3 } EXPLODE = { 0,1,0,1,1,1,1,0,1,0,1,0; w=3,h=4 } FISH = { 0,1,1,1,1,1,0,0,0,1,0,0,0,0,1,1,0,0,1,0; w=5,h=4 } BUTTERFLY = { 1,0,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,0,1,1,0,0,0,1; w=5,h=5 } -- the main routine function LIFE(w,h) -- create two arrays local thisgen = CELLS(w,h) local nextgen = CELLS(w,h) -- create some life -- about 1000 generations of fun, then a glider steady-state thisgen:spawn(GLIDER,5,4) thisgen:spawn(EXPLODE,25,10) thisgen:spawn(FISH,4,12) -- run until break local gen=1 write("\027[2J") -- ANSI clear screen while 1 do thisgen:evolve(nextgen) thisgen,nextgen = nextgen,thisgen write("\027[H") -- ANSI home cursor thisgen:draw() write("Life - generation ",gen,"\n") gen=gen+1 if gen>2000 then break end --delay() -- no delay end end LIFE(40,20)
bsd-3-clause
CodingKitsune/Riritools
riritools/lua/gui_link.lua
1
1346
local class = require("riritools.lua.class") local gui_component = require("riritools.lua.gui_component") local gui_clickable_mixin = require("riritools.lua.gui_clickable_mixin") local link = class("rt.link", gui_component) function link:__initialize(name, parent) gui_component.__initialize(self, name, parent, name, true) self.pressed_function = nil self.pressed_function_args = nil self.pressed_color = vmath.vector4(0.5, 0.5, 0.5, 1.0) self.normal_color = vmath.vector4(1.0, 1.0, 1.0, 1.0) self.disabled_color = vmath.vector4(0.2, 0.2, 0.2, 1.0) end function link:on_input(action_id, action) local is_action_on_button = self.__is_active and self:__has_clicked_ok_on_component(action_id, action, self.__base_node) local is_button_pressed = (action.pressed and is_action_on_button) local is_cooldown_over = self.__cooldown_timer:as_seconds() > self.cooldown if is_button_pressed then if is_cooldown_over then self:__emit_ok() if self.pressed_function then self.pressed_function(self.pressed_function_args) end self.__cooldown_timer:restart() end gui.set_color(self.__base_node, self.pressed_color) else gui.set_color(self.__base_node, self.__is_active and self.normal_color or self.disabled_color) end end link:include(gui_clickable_mixin) return link
mit
LuaDist2/lua-curl
examples/lcurl/curl_debug.lua
1
1284
-- -- convert `debug.c` example from libcurl examples -- local curl = require "lcurl" local function printf(...) io.stderr:write(string.format(...)) end local function dumb(title, data, n) n = n or 16 printf("%s, %10.10d bytes (0x%8.8x)\n", title, #data, #data) for i = 1, #data do if (i - 1) % n == 0 then printf("%4.4x: ", i-1) end printf("%02x ", string.byte(data, i, i)) if i % n == 0 then printf("\n") end end if #data % n ~= 0 then printf("\n") end end local function my_trace(type, data) local text if type == curl.INFO_TEXT then printf("== Info: %s", data) end if type == curl.INFO_HEADER_OUT then text = "=> Send header" end if type == curl.INFO_DATA_OUT then text = "=> Send data" end if type == curl.INFO_SSL_DATA_OUT then text = "=> Send SSL data" end if type == curl.INFO_HEADER_IN then text = "<= Recv header" end if type == curl.INFO_DATA_IN then text = "<= Recv data" end if type == curl.INFO_SSL_DATA_IN then text = "<= Recv SSL data" end if text then dumb(text, data) end end local easy = curl.easy{ url = "http://google.com", verbose = true, debugfunction = my_trace, followlocation = true, writefunction = function()end, } easy:perform()
mit
nginxsuper/gin
gin/db/sql/orm.lua
2
2396
-- perf local require = require local function tappend(t, v) t[#t+1] = v end local SqlOrm = {} function SqlOrm.define_model(sql_database, table_name) local GinModel = {} GinModel.__index = GinModel -- init local function quote(str) return sql_database:quote(str) end local orm = require('gin.db.sql.' .. sql_database.options.adapter .. '.orm').new(table_name, quote) function GinModel.new(attrs) local instance = attrs or {} setmetatable(instance, GinModel) return instance end function GinModel.create(attrs) local sql = orm:create(attrs) local id = sql_database:execute_and_return_last_id(sql) local model = GinModel.new(attrs) model.id = id return model end function GinModel.where(attrs, options) local sql = orm:where(attrs, options) local results = sql_database:execute(sql) local models = {} for i = 1, #results do tappend(models, GinModel.new(results[i])) end return models end function GinModel.all(options) return GinModel.where({}, options) end function GinModel.find_by(attrs, options) local merged_options = { limit = 1 } if options and options.order then merged_options.order = options.order end return GinModel.where(attrs, merged_options)[1] end function GinModel.delete_where(attrs, options) local sql = orm:delete_where(attrs, options) return sql_database:execute(sql) end function GinModel.delete_all(options) return GinModel.delete_where({}, options) end function GinModel.update_where(attrs, options) local sql = orm:update_where(attrs, options) return sql_database:execute(sql) end function GinModel:save() if self.id ~= nil then local id = self.id self.id = nil local result = GinModel.update_where(self, { id = id }) self.id = id return result else return GinModel.create(self) end end function GinModel:delete() if self.id ~= nil then return GinModel.delete_where({ id = self.id }) else error("cannot delete a model without an id") end end return GinModel end return SqlOrm
mit
EvPowerTeam/EV_OP
feeds/luci/protocols/relay/luasrc/model/network/proto_relay.lua
77
3432
--[[ LuCI - Network model - relay protocol extension Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local netmod = luci.model.network local device = luci.util.class(netmod.interface) netmod:register_pattern_virtual("^relay-%w") local proto = netmod:register_protocol("relay") function proto.get_i18n(self) return luci.i18n.translate("Relay bridge") end function proto.ifname(self) return "relay-" .. self.sid end function proto.opkg_package(self) return "relayd" end function proto.is_installed(self) return nixio.fs.access("/etc/init.d/relayd") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interface(self) return device(self.sid, self) end function proto.get_interfaces(self) if not self.ifaces then local ifs = { } local _, net, dev for net in luci.util.imatch(self:_get("network")) do net = netmod:get_network(net) if net then dev = net:get_interface() if dev then ifs[dev:name()] = dev end end end for dev in luci.util.imatch(self:_get("ifname")) do dev = netmod:get_interface(dev) if dev then ifs[dev:name()] = dev end end self.ifaces = { } for _, dev in luci.util.kspairs(ifs) do self.ifaces[#self.ifaces+1] = dev end end return self.ifaces end function proto.uptime(self) local net local upt = 0 for net in luci.util.imatch(self:_get("network")) do net = netmod:get_network(net) if net then upt = math.max(upt, net:uptime()) end end return upt end function device.__init__(self, ifname, network) self.ifname = ifname self.network = network end function device.type(self) return "tunnel" end function device.is_up(self) if self.network then local _, dev for _, dev in ipairs(self.network:get_interfaces()) do if not dev:is_up() then return false end end return true end return false end function device._stat(self, what) local v = 0 if self.network then local _, dev for _, dev in ipairs(self.network:get_interfaces()) do v = v + dev[what](dev) end end return v end function device.rx_bytes(self) return self:_stat("rx_bytes") end function device.tx_bytes(self) return self:_stat("tx_bytes") end function device.rx_packets(self) return self:_stat("rx_packets") end function device.tx_packets(self) return self:_stat("tx_packets") end function device.mac(self) if self.network then local _, dev for _, dev in ipairs(self.network:get_interfaces()) do return dev:mac() end end end function device.ipaddrs(self) local addrs = { } if self.network then addrs[1] = luci.ip.IPv4(self.network:_get("ipaddr")) end return addrs end function device.ip6addrs(self) return { } end function device.shortname(self) return "%s %q" % { luci.i18n.translate("Relay"), self.ifname } end function device.get_type_i18n(self) return luci.i18n.translate("Relay Bridge") end
gpl-2.0
sundream/gamesrv
script/card/water/card234006.lua
1
2278
--<<card 导表开始>> local super = require "script.card.water.card134006" ccard234006 = class("ccard234006",super,{ sid = 234006, race = 3, name = "思维窃取", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 3, targettype = 0, halo = nil, desc = "复制对手的牌库中的2张牌,并将其置入你的手牌。", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard234006:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard234006:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard234006:save() local data = super.save(self) -- todo: save data return data end return ccard234006
gpl-2.0
dalvorsn/tests
data/talkactions/scripts/create_item.lua
10
1097
function onSay(cid, words, param) local player = Player(cid) if not player:getGroup():getAccess() then return true end if player:getAccountType() < ACCOUNT_TYPE_GOD then return false end local split = param:split(",") local itemType = ItemType(split[1]) if itemType:getId() == 0 then itemType = ItemType(tonumber(split[1])) if itemType:getId() == 0 then player:sendCancelMessage("There is no item with that id or name.") return false end end local count = tonumber(split[2]) if count ~= nil then if itemType:isStackable() then count = math.min(10000, math.max(1, count)) elseif not itemType:hasSubType() then count = math.min(100, math.max(1, count)) else count = math.max(1, count) end else count = 1 end local result = player:addItem(itemType:getId(), count) if result ~= nil then if not itemType:isStackable() then if type(result) == "table" then for _, item in ipairs(result) do item:decay() end else result:decay() end end player:getPosition():sendMagicEffect(CONST_ME_MAGIC_GREEN) end return false end
gpl-2.0
sundream/gamesrv
script/card/neutral/card265009.lua
1
2257
--<<card 导表开始>> local super = require "script.card.neutral.card165009" ccard265009 = class("ccard265009",super,{ sid = 265009, race = 6, name = "工程师学徒", type = 205, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 1, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 1, maxhp = 1, crystalcost = 2, targettype = 0, halo = nil, desc = "战吼:抽一张牌。", effect = { onuse = {pickcard={num=1}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard265009:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard265009:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard265009:save() local data = super.save(self) -- todo: save data return data end return ccard265009
gpl-2.0
yangboz/petulant-octo-dubstep
HP_ID_Print_App/cocos2d-x-3.2/cocos/scripting/lua-bindings/auto/api/Bone.lua
1
6115
-------------------------------- -- @module Bone -- @extend Node -------------------------------- -- @function [parent=#Bone] isTransformDirty -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Bone] isIgnoreMovementBoneData -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Bone] updateZOrder -- @param self -------------------------------- -- @function [parent=#Bone] getDisplayRenderNode -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- @function [parent=#Bone] isBlendDirty -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Bone] addChildBone -- @param self -- @param #ccs.Bone bone -------------------------------- -- @function [parent=#Bone] getWorldInfo -- @param self -- @return BaseData#BaseData ret (return value: ccs.BaseData) -------------------------------- -- @function [parent=#Bone] getTween -- @param self -- @return Tween#Tween ret (return value: ccs.Tween) -------------------------------- -- @function [parent=#Bone] getParentBone -- @param self -- @return Bone#Bone ret (return value: ccs.Bone) -------------------------------- -- @function [parent=#Bone] updateColor -- @param self -------------------------------- -- @function [parent=#Bone] getName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Bone] setTransformDirty -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Bone] getDisplayRenderNodeType -- @param self -- @return DisplayType#DisplayType ret (return value: ccs.DisplayType) -------------------------------- -- @function [parent=#Bone] removeDisplay -- @param self -- @param #int int -------------------------------- -- @function [parent=#Bone] setBoneData -- @param self -- @param #ccs.BoneData bonedata -------------------------------- -- overload function: init(string) -- -- overload function: init() -- -- @function [parent=#Bone] init -- @param self -- @param #string str -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Bone] setParentBone -- @param self -- @param #ccs.Bone bone -------------------------------- -- overload function: addDisplay(cc.Node, int) -- -- overload function: addDisplay(ccs.DisplayData, int) -- -- @function [parent=#Bone] addDisplay -- @param self -- @param #ccs.DisplayData displaydata -- @param #int int -------------------------------- -- @function [parent=#Bone] setName -- @param self -- @param #string str -------------------------------- -- @function [parent=#Bone] removeFromParent -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Bone] getColliderDetector -- @param self -- @return ColliderDetector#ColliderDetector ret (return value: ccs.ColliderDetector) -------------------------------- -- @function [parent=#Bone] getChildArmature -- @param self -- @return Armature#Armature ret (return value: ccs.Armature) -------------------------------- -- @function [parent=#Bone] getTweenData -- @param self -- @return FrameData#FrameData ret (return value: ccs.FrameData) -------------------------------- -- @function [parent=#Bone] changeDisplayWithIndex -- @param self -- @param #int int -- @param #bool bool -------------------------------- -- @function [parent=#Bone] changeDisplayWithName -- @param self -- @param #string str -- @param #bool bool -------------------------------- -- @function [parent=#Bone] setArmature -- @param self -- @param #ccs.Armature armature -------------------------------- -- @function [parent=#Bone] setBlendDirty -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Bone] removeChildBone -- @param self -- @param #ccs.Bone bone -- @param #bool bool -------------------------------- -- @function [parent=#Bone] setChildArmature -- @param self -- @param #ccs.Armature armature -------------------------------- -- @function [parent=#Bone] getNodeToArmatureTransform -- @param self -- @return mat4_table#mat4_table ret (return value: mat4_table) -------------------------------- -- @function [parent=#Bone] getDisplayManager -- @param self -- @return DisplayManager#DisplayManager ret (return value: ccs.DisplayManager) -------------------------------- -- @function [parent=#Bone] getArmature -- @param self -- @return Armature#Armature ret (return value: ccs.Armature) -------------------------------- -- @function [parent=#Bone] getBoneData -- @param self -- @return BoneData#BoneData ret (return value: ccs.BoneData) -------------------------------- -- overload function: create(string) -- -- overload function: create() -- -- @function [parent=#Bone] create -- @param self -- @param #string str -- @return Bone#Bone ret (retunr value: ccs.Bone) -------------------------------- -- @function [parent=#Bone] updateDisplayedColor -- @param self -- @param #color3b_table color3b -------------------------------- -- @function [parent=#Bone] setLocalZOrder -- @param self -- @param #int int -------------------------------- -- @function [parent=#Bone] getNodeToWorldTransform -- @param self -- @return mat4_table#mat4_table ret (return value: mat4_table) -------------------------------- -- @function [parent=#Bone] update -- @param self -- @param #float float -------------------------------- -- @function [parent=#Bone] updateDisplayedOpacity -- @param self -- @param #unsigned char char -------------------------------- -- @function [parent=#Bone] Bone -- @param self return nil
mit
sundream/gamesrv
script/card/neutral/card166027.lua
1
2464
--<<card 导表开始>> local super = require "script.card.init" ccard166027 = class("ccard166027",super,{ sid = 166027, race = 6, name = "香蕉", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 0, composechip = 0, decomposechip = 0, atk = 0, maxhp = 0, crystalcost = 1, targettype = 22, halo = nil, desc = "使一个随从获得+1/+1", effect = { onuse = {addbuff={addatk=1,addmaxhp=1,addhp=1}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard166027:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard166027:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard166027:save() local data = super.save(self) -- todo: save data return data end function ccard166027:onuse(pos,targetid,choice) local owner = self:getowner() local target = owner:gettarget(targetid) local buff = self:newbuff(ccard166027.effect.onuse.addbuff) target:addbuff(buff) end return ccard166027
gpl-2.0
tltneon/NutScript
gamemode/languages/sh_russian.lua
1
15882
 --Russian translation by Shadow Nova (http://steamcommunity.com/profiles/76561197989134302) --Edited/fixed by Schwarz Kruppzo (http://steamcommunity.com/id/schwarzkruppzo) --Edited and added new by Neon (http://steamcommunity.com/id/ru_neon) NAME = "Русский" LANGUAGE = { loading = "Загружается", dbError = "Подключение к базе данных провалилось", unknown = "Неизвестно", noDesc = "Описание отсутствует", create = "Создать", createTip = "Создать нового персонажа, за которого вы будете играть.", load = "Загрузить", loadTip = "Выберите ранее созданного вами персонажа.", leave = "Выйти", leaveTip = "Выйти из текущего сервера.", ["return"] = "Вернуться", returnTip = "Вернуться к предыдущему меню.", name = "Имя", desc = "Описание", model = "Модель", attribs = "Умения", charCreateTip = "Заполните строчки ниже и нажмите 'Завершить', чтобы создать вашего персонажа.", invalid = "Вы предъявили недействительный %s", descMinLen = "Ваше описание должно хотя бы иметь %d количество букв.", model = "Модель", player = "Игрок", finish = "Завершить", finish = "Завершить", finishTip = "Завершить создание персонажа.", needModel = "Вы должны выбрать действительную модель", creating = "Ваш персонаж создаётся...", unknownError = "Обнаружена неизвестная ошибка", delConfirm = "Вы уверены, что хотите НАВСЕГДА удалить %s?", no = "Нет", yes = "Да", choose = "Выбрать", delete = "Удалить", chooseTip = "Выбрать этого персонажа", deleteTip = "Удалить этого персонажа", itemInfo = "Название: %s\nОписание: %s", cloud_no_repo = "Выбранное хранилише недействительное.", cloud_no_plugin = "Выбранный плагин недействителен.", inv = "Инвентарь", plugins = "Плагин", author = "Автор", version = "Версия", characters = "Персонажи", business = "Бизнес", settings = "Настройки", config = "Конфиг", chat = "Чат", appearance = "Внешний вид", misc = "Остальное", oocDelay = "Вы должны дождаться %s секунд, чтобы воспользоватся OOC чатом снова.", loocDelay = "Вы должны дождаться %s секунд чтобы воспользоватся LOOC чатом снова.", usingChar = "Вы уже используете этого персонажа.", notAllowed = "Извините, но вы не можете этого сделать.", itemNoExist = "Извините, но предмет, который вы просите не существует.", cmdNoExist = "Извините, но эта команда не существует.", plyNoExist = "Извините, игрок с таким именем не найден.", cfgSet = "%s изменил \"%s\" на %s.", drop = "Выбросить", dropTip = "Выбросить этот предмет из инвентаря.", take = "Взять", takeTip = "Взять предмет и положить его в инвентарь.", dTitle = "Бесхозная дверь", dTitleOwned = "Арендованная дверь", dIsNotOwnable = "Эту дверь невозможно арендовать.", dIsOwnable = "Вы можете арендовать эту дверь, нажимая кнопку F2.", dMadeUnownable = "Вы сделали эту дверь не подлежащей к аренде.", dMadeOwnable = "Вы сделали эту дверь подлежащей к аренде.", dNotAllowedToOwn = "Вам не позволено арендовать эту дверь.", dSetDisabled = "Вы сделали эту дверь нерабочей.", dSetNotDisabled = "Вы сделали эту дверь вновь рабочей.", dSetHidden = "Вы сделали эту дверь невидимой.", dSetNotHidden = "Вы сделали эту дверь вновь видимой.", dSetParentDoor = "Вы сделали эту дверь главной.", dCanNotSetAsChild = "Вы не можете сделать главную дверь второстепенной.", dAddChildDoor = "Вы добавили эту дверь как второстепенную.", dRemoveChildren = "Вы убрали все второстепенные двери из перечня главной.", dRemoveChildDoor = "Вы убрали второстепенную дверь из перечня главной.", dNoParentDoor = "У вас не установленна главная дверь.", dOwnedBy = "Эта дверь принадлежит %s.", dConfigName = "Дверь", dSetFaction = "Сейчас эта дверь принадлежит %s фракций.", dRemoveFaction = "Эта дверь не принадлежит никакой фракции.", dNotValid = "Вы смотрите не на подлинную дверь.", canNotAfford = "У вас недостаточно средств, чтобы купить это.", dPurchased = "Вы арендовали эту дверь за %s.", dSold = "Вы продали эту дверь за %s.", notOwner = "Вы не владелец этого.", invalidArg = "Вы предоставили недопустимое значение аргумента #%s.", invalidFaction = "Фракцию, которую вы представили невозможно найти.", flagGive = "%s дал %s '%s' флаги.", flagTake = "%s взял '%s' флаги у %s.", flagNoMatch = "У вас должны быть \"%s\" флаги, чтобы выполнить это действие.", textAdded = "Вы добавили текст.", textRemoved = "Вы удалили %s текст(ов).", moneyTaken = "Вы нашли %s.", businessPurchase = "Вы купили %s за %s.", businessSell = "Вы продали %s за %s.", cChangeModel = "%s поменял %s's модель на %s.", cChangeName = "%s поменял %s's имя на %s.", cChangeSkin = "%s поменял %s's скин на %s.", cChangeGroups = "%s поменял %s's \"%s\" бодигруппу на %s.", cChangeFaction = "%s переместил %s в фракцию %s.", playerCharBelonging = "Этот объект принадлежит другому вашему персонажу.", business = "Бизнес", invalidFaction = "Вы предъявили недействительную фракцию.", spawnAdd = "Вы создали точку возрождения для %s.", spawnDeleted = "Вы удалили %s точку (точки) возрождения.", someone = "Кто-то", rgnLookingAt = "Позволить человеку, на которого вы смотрите вас распознать.", rgnWhisper = "Позволить людям в радиусе слышимости шепота вас распознать.", rgnTalk = "Позволить людям в радиусе слышимости речи вас распознать.", rgnYell = "Позволить людям в радиусе слышимости крика вас распознать.", icFormat = "%s говорит \"%s\"", rollFormat = "%s выпало число %s.", wFormat = "%s шепчет \"%s\"", yFormat = "%s кричит \"%s\"", sbOptions = "Нажмите, чтобы увидеть опции для %s.", spawnAdded = "Вы создали точку возрождения для %s.", whitelist = "%s добавил %s в перечень фракции %s.", unwhitelist = "%s исключил %s из перечня фракции %s.", gettingUp = "Вы встаете...", wakingUp = "Вы приходите в чувство...", Weapons = "Оружие", checkout = "Перейти к оформлению заказа (%s)", purchase = "Покупка", purchasing = "Покупаем...", success = "Успех", buyFailed = "Покупка провалилась.", buyGood = "Покупка успешна!", shipment = "Груз", shipmentDesc = "Этот груз принадлежит %s.", class = "Класс", classes = "Классы", illegalAccess = "Запрещённый доступ.", becomeClassFail = "Не получилось стать %s.", becomeClass = "Вы стали %s.", attribSet = "Вы поменяли %s's %s на %s.", attribUpdate = "Вы добавили %s's %s by %s.", noFit = "Этот предмет не помещается в инвентаре.", help = "Помощь", commands = "Команды", helpDefault = "Выберите категорию", doorSettings = "Настройки дверей", sell = "Продать", access = "Доступ", locking = "Запираем этот объект...", unlocking = "Открываем этот объект...", modelNoSeq = "Эта модель не поддерживает эту анимацию.", notNow = "Вы не можете это сделать сейчас.", faceWall = "Вы должны стоять лицом к стене, чтобы сделать это.", faceWallBack = "Ваша спина должна быть прижата к стене, чтобы сделать это.", descChanged = "Вы поменяли описание вашего персонажа.", livesLeft = "Жизней осталось: %s", charIsDead = "Ваш персонаж умер", charMoney = "У вас сейчас %s.", charFaction = "Вы являетесь членом фракции %s.", charClass = "Вы %s фракций.", noSpace = "Ваш инвентарь полон.", noOwner = "Владелец недействителен.", notAllowed = "Это действие запрещено.", invalidIndex = "Индекс предмета недействителен.", invalidItem = "Объект предмета недействителен.", invalidInventory = "Объект инвентаря недействителен.", home = "Дом", charKick = "%s кикнул персонажа %s.", charBan = "%s забанил персонажа %s.", charBanned = "Этот персонаж забанен.", setMoney = "Вы установили %s's количество денег на %s.", itemPriceInfo = "Вы можете купить этот предмет за %s.\nВы можете продать этот предмет за %s", free = "Бесплатно", vendorNoSellItems = "Здесь нету предметов для продажи.", vendorNoBuyItems = "Здесь нету предметов для покупки.", vendorSettings = "Настроики раздатчика", vendorUseMoney = "Будет ли раздатчик брать деньги?", vendorNoBubble = "Спрятать облачко раздатчика?", mode = "Мод", price = "Цена", stock = "Запас", none = "Ничего", vendorBoth = "Купить и продать", vendorBuy = "Только купить", vendorSell = "Только продать", maxStock = "Максимальный запас", vendorFaction = "Настройки фракций", buy = "Купить", vendorWelcome = "Приветствую вас в моем магазине, что пожелаете?", vendorBye = "Приходите еще!", charSearching = "Вы уже ищите другого персонажа, пожалуйста, подождите.", charUnBan = "%s разбанил персонажа %s.", charNotBanned = "Этот персонаж не забанен.", storPass = "Вы установили пароль контейнера на %s.", storPassRmv = "Вы убрали пароль контейнера.", storPassWrite = "Введите пароль.", wrongPassword = "Вы ввели неправильный пароль.", cheapBlur = "Выключить размытие? (Повышает FPS)", quickSettings = "Быстрые настройки", vmSet = "Вы установили ваш автоответчик.", vmRem = "Вы избавились от автоответчика.", altLower = "Спрятать руки, пока они опущены?", noPerm = "Вам не позволено сделать это.", youreDead = "Вы мертвы", injMajor = "Похоже, что он очень сильно ранен.", injLittle = "Похоже, что он ранен", toggleESP = "Включить Admin ESP", chgName = "Поменять имя", chgNameDesc = "Впишите новое имя для персонажа.", thirdpersonToggle = "Включить вид от третьего лица", thirdpersonClassic = "Использовать классический вид от третьего лица", equippedBag = "Сумка, которую вы сдвинули имеет одетую вами вещь.", useTip = "Использовать предмет.", equipTip = "Одеть предмет.", unequipTip = "Снять предмет.", consumables = "Потребности", plyNotValid = "Вы смотрите не на подлинного игрока.", restricted = "Вы были связаны.", viewProfile = "Показать профиль Steam", salary = "Вы получили %s из вашей зарплаты.", noRecog = "Вы не узнаёте этого человека.", curTime = "Текущее время: %s.", vendorEditor = "Редактор торговца", edit = "Изменить", disable = "Отключить", vendorPriceReq = "Введите новую цену предмета.", vendorEditCurStock = "Изменить количество", radioFreq = "Изменить частоту радиоприёма", radioSubmit = "Сохранить", you = "Вы", isTied = "Связан", tying = "Связывание...", unTying = "Развязывание...", On = "Включен", Off = "Выключен", vendorSellScale = "Множитель цен продажи", vendorNoTrade = "Вы не можете взаимодействовать с этим торговцем.", vendorNoMoney = "Торговец не может купить у вас предмет.", vendorNoStock = "У этого торговца нет в наличии этого предмета.", contentTitle = "Отсутствует контент NutScript", contentWarning = "У вас не установлен контент NutScript. Некоторые функции могут не работать.\nВы желаете перейти на страницу скачивания контента?", Assign = "Присвоить", Freq = "Частота", Toggle = "Переключить", Use = "Использовать", UseForward = "Использовать на игроке", Equip = "Экипировать", Unequip = "Снять", Load = "Распаковать", View = "Открыть", flags = "Флаги", chooseTip = "Выбрать этого персонажа.", deleteTip = "Удалить этого персонажа.", moneyLeft = "Ваши деньги: ", currentMoney = "Осталось денег: " }
mit
jxskiss/orange
orange/plugins/rate_limiting/handler.lua
3
5119
local ipairs = ipairs local type = type local tostring = tostring local utils = require("orange.utils.utils") local orange_db = require("orange.store.orange_db") local judge_util = require("orange.utils.judge") local BasePlugin = require("orange.plugins.base_handler") local counter = require("orange.plugins.rate_limiting.counter") local function get_current_stat(limit_key) return counter.get(limit_key) end local function incr_stat(limit_key, limit_type) counter.incr(limit_key, 1, limit_type) end local function get_limit_type(period) if not period then return nil end if period == 1 then return "Second" elseif period == 60 then return "Minute" elseif period == 3600 then return "Hour" elseif period == 86400 then return "Day" else return nil end end local function filter_rules(sid, plugin, ngx_var_uri) local rules = orange_db.get_json(plugin .. ".selector." .. sid .. ".rules") if not rules or type(rules) ~= "table" or #rules <= 0 then return false end for i, rule in ipairs(rules) do if rule.enable == true then -- judge阶段 local pass = judge_util.judge_rule(rule, plugin) -- handle阶段 local handle = rule.handle if pass then local limit_type = get_limit_type(handle.period) -- only work for valid limit type(1 second/minute/hour/day) if limit_type then local current_timetable = utils.current_timetable() local time_key = current_timetable[limit_type] local limit_key = rule.id .. "#" .. time_key local current_stat = get_current_stat(limit_key) or 0 ngx.header["X-RateLimit-Limit" .. "-" .. limit_type] = handle.count if current_stat >= handle.count then if handle.log == true then ngx.log(ngx.INFO, "[RateLimiting-Forbidden-Rule] ", rule.name, " uri:", ngx_var_uri, " limit:", handle.count, " reached:", current_stat, " remaining:", 0) end ngx.header["X-RateLimit-Remaining" .. "-" .. limit_type] = 0 ngx.exit(429) return true else ngx.header["X-RateLimit-Remaining" .. "-" .. limit_type] = handle.count - current_stat - 1 incr_stat(limit_key, limit_type) -- only for test, comment it in production -- if handle.log == true then -- ngx.log(ngx.INFO, "[RateLimiting-Rule] ", rule.name, " uri:", ngx_var_uri, " limit:", handle.count, " reached:", current_stat + 1) -- end end end end -- end `pass` end -- end `enable` end -- end for return false end local RateLimitingHandler = BasePlugin:extend() RateLimitingHandler.PRIORITY = 1000 function RateLimitingHandler:new(store) RateLimitingHandler.super.new(self, "rate-limiting-plugin") self.store = store end function RateLimitingHandler:access(conf) RateLimitingHandler.super.access(self) local enable = orange_db.get("rate_limiting.enable") local meta = orange_db.get_json("rate_limiting.meta") local selectors = orange_db.get_json("rate_limiting.selectors") local ordered_selectors = meta and meta.selectors if not enable or enable ~= true or not meta or not ordered_selectors or not selectors then return end local ngx_var_uri = ngx.var.uri for i, sid in ipairs(ordered_selectors) do ngx.log(ngx.INFO, "==[RateLimiting][PASS THROUGH SELECTOR:", sid, "]") local selector = selectors[sid] if selector and selector.enable == true then local selector_pass if selector.type == 0 then -- 全流量选择器 selector_pass = true else selector_pass = judge_util.judge_selector(selector, "rate_limiting")-- selector judge end if selector_pass then if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[RateLimiting][PASS-SELECTOR:", sid, "] ", ngx_var_uri) end local stop = filter_rules(sid, "rate_limiting", ngx_var_uri) if stop then -- 不再执行此插件其他逻辑 return end else if selector.handle and selector.handle.log == true then ngx.log(ngx.INFO, "[RateLimiting][NOT-PASS-SELECTOR:", sid, "] ", ngx_var_uri) end end -- if continue or break the loop if selector.handle and selector.handle.continue == true then -- continue next selector else break end end end end return RateLimitingHandler
mit
cls1991/DataManager
entity/const/cachebase.lua
1
2218
local skynet = require "skynet" local CacheBase = class("CacheBase") function CacheBase:ctor(key_name, table_name, fields) self._k = key_name self._t = table_name self._f = fields self._m_cache = {} end function CacheBase:get_key(key) return string.format("%s:%s", self._t, key) end function CacheBase:convert_to_lua_data_type(key, value) local column_data = get_schema_data(self._t) local field_type = column_data["fields"][key] if field_type == "number" then return tonumber(value) end return value end function CacheBase:convert_to_lua_data(origin_data) local column_data = get_schema_data(self._t) local result_data = {} for key, value in pairs(origin_data) do local is_in = false local tmp_value = value for field_name, field_type in pairs(column_data["fields"]) do if key == field_name then is_in = true break end end if is_in and column_data["fields"][key] == "number" then tmp_value = tonumber(value) end result_data[key] = tmp_value end return result_data end function CacheBase:convert_value(key, value) return value end function CacheBase:cache_data() local query_sql = construct_query_str(self._t, {}, self._f) local ret = skynet.call("mysqlpool", "lua", "execute", query_sql) if table.empty(ret) then return end if ret["error"] ~= nil or ret["badresult"] ~= nil then return end for _, item in pairs(ret) do local key = item[self._k] local redis_key = self:get_key(key) skynet.call("redispool", "lua", "hmset", redis_key, item) self._m_cache[key] = self:convert_to_lua_data(item) end end function CacheBase:get_data(key) local data = self._m_cache[key] if data == nil then local ret = skynet.call("redispool", "lua", "hgetall", self:get_key(key)) if not table.empty(ret) then -- parse redis data data = {} for i=1, #ret, 2 do data[ret[i]] = ret[i+1] end self._m_cache[key] = self:convert_to_lua_data(data) data = self._m_cache[key] end end return data end function CacheBase:get_all_data() return self._m_cache end return CacheBase
apache-2.0
nimaghorbani/THOR
plugins/inrealm.lua
12
17415
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.' end end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function group_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("groups.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end function run(msg, matches) --vardump(msg) if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] return create_group(msg) end if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if not is_realm(msg) then return end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'setting' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) end end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then group_list(msg) send_document("chat#id"..msg.to.id, "groups.txt", ok_cb, false) return " Group list created" --group_list(msg) end end return { patterns = { "^[!/$&]([Cc]reategroup) (.*)$", "^[!/$&]([Ss]etabout) (%d+) (.*)$", "^[!/$&]([Ss]etrules) (%d+) (.*)$", "^[!/$&]([Ss]etname) (%d+) (.*)$", "^[!/$&]([Ll]ock) (%d+) (.*)$", "^[!/$&]([Uu]nlock) (%d+) (.*)$", "^[!/$&]([Ss]etting) (%d+)$", "^[!/$&]([Ww]holist)$", "^[!/$&]([Ww]ho)$", "^[!/$&]([Aa]ddadmin) (.*)$", -- sudoers only "^[!/$&]([Rr]emoveadmin) (.*)$", -- sudoers only "^[!/$&]([Ll]ist) (.*)$", "^[!/$&]([Ll]og)$", "^!!tgservice (.+)$", "^([Cc]reategroup) (.*)$", "^([Ss]etabout) (%d+) (.*)$", "^([Ss]etrules) (%d+) (.*)$", "^([Ss]etname) (%d+) (.*)$", "^([Ll]ock) (%d+) (.*)$", "^([Uu]nlock) (%d+) (.*)$", "^([Ss]etting) (%d+)$", "^([Ww]holist)$", "^([Ww]ho)$", "^([Aa]ddadmin) (.*)$", -- sudoers only "^([Rr]emoveadmin) (.*)$", -- sudoers only "^([Ll]ist) (.*)$", "^([Ll]og)$", }, run = run } end
gpl-2.0
sundream/gamesrv
script/card/soil/card155002.lua
1
2518
--<<card 导表开始>> local super = require "script.card.init" ccard155002 = class("ccard155002",super,{ sid = 155002, race = 5, name = "野性印记", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 2, targettype = 22, halo = nil, desc = "使1个随从获得嘲讽以及+2/+2。(+2攻击/+2生命)", effect = { onuse = {addbuff={sneer=60,addatk=2,addmaxhp=2,addhp=2}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard155002:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard155002:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard155002:save() local data = super.save(self) -- todo: save data return data end function ccard155002:onuse(pos,targetid,choice) local owner = self:getowner() local target = owner:gettarget(targetid) local buff = self:newbuff(ccard155002.effect.onuse.addbuff) target:addbuff(buff) end return ccard155002
gpl-2.0
reonZ/Release-the-Hounds
game/dota_addons/release_the_hounds/scripts/vscripts/addon_game_mode.lua
1
8712
require( 'constants' ) require( 'timers' ) require( 'utils' ) if GameMode == nil then GameMode = class({}) end -- This function is used to precache resources/units/items/abilities that will be needed -- for sure in your game and that cannot or should not be precached asynchronously or -- after the game loads. function Precache( context ) PrecacheUnitByNameSync( CUSTOM_HERO_HOUND, context ) PrecacheUnitByNameSync( CUSTOM_HERO_HOUNDMASTER, context ) for _, boss in ipairs(NPC_BOSS_LIST) do PrecacheUnitByNameSync( boss, context ) end PrecacheItemByNameSync( CUSTOM_ITEM_HORN, context ) PrecacheItemByNameSync( CUSTOM_ITEM_HOWLING, context ) PrecacheResource( 'model', MODEL_HOUND_2, context ) PrecacheResource( 'model', MODEL_HOUND_3, context ) PrecacheResource( 'model', MODEL_HOUND_4, context ) end -- Create the game mode when we activate function Activate() GameRules.AddonTemplate = GameMode() GameRules.AddonTemplate:InitGameMode() end -- This function initializes the game mode and is called before anyone loads into the game -- It can be used to pre-initialize any values/tables that will be needed later function GameMode:InitGameMode() print( 'InitGameMode' ) GameRules:SetCustomGameEndDelay( CUSTOM_GAME_END_DELAY ) GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_BADGUYS, CUSTOM_GAME_BADGUYS_MAX_PLAYERS) GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_GOODGUYS, CUSTOM_GAME_GOODGUYS_MAX_PLAYERS) GameRules:SetFirstBloodActive( FIRST_BLOOD_ACTIVE ) GameRules:SetGoldPerTick( GOLD_PER_TICK ) GameRules:SetGoldTickTime( GOLD_TICK_TIME ) GameRules:SetHeroRespawnEnabled( HERO_RESPAWN_ENABLED ) GameRules:SetHeroSelectionTime( HERO_SELECTION_TIME ) GameRules:SetHideKillMessageHeaders( HIDE_KILL_MESSAGE_HEADERS ) GameRules:SetPostGameTime( POST_GAME_TIME ) GameRules:SetPreGameTime( PRE_GAME_TIME ) GameRules:SetSameHeroSelectionEnabled( SAME_HERO_SELECTION_ENABLED ) GameRules:SetTreeRegrowTime( TREE_REGROW_TIME ) GameRules:SetUseUniversalShopMode( USE_UNIVERSAL_SHOP_MODE ) ListenToGameEvent( 'player_connect_full', Dynamic_Wrap(GameMode, 'OnConnectFull'), self ) ListenToGameEvent( 'game_rules_state_change', Dynamic_Wrap( GameMode, 'OnGameRulesStateChange' ), self ) ListenToGameEvent( 'dota_player_pick_hero', Dynamic_Wrap(GameMode, 'OnPlayerPickHero'), self ) ListenToGameEvent('npc_spawned', Dynamic_Wrap(GameMode, 'OnNPCSpawned'), self) Convars:RegisterCommand( 'hounds_switch_hero', Dynamic_Wrap(GameMode, 'OnSwitchHero'), '', 0 ) Convars:RegisterCommand( 'hounds_spawn_boss', Dynamic_Wrap(GameMode, 'OnSpawnBoss'), '', 0 ) end -- This function is called as the first player loads and sets up the GameMode parameters function GameMode:CaptureGameMode() print( 'CaptureGameMode' ) if not GameModeEntity then GameModeEntity = GameRules:GetGameModeEntity() GameModeEntity:SetAnnouncerDisabled( ANNOUNCER_DISABLED ) GameModeEntity:SetBotThinkingEnabled( BOT_THINKING_ENABLED ) GameModeEntity:SetBuybackEnabled( BUYBACK_ENABLED ) GameModeEntity:SetCameraDistanceOverride( CAMERA_DISTANCE_OVERRIDE ) GameModeEntity:SetCustomGameForceHero( CUSTOM_HERO_HOUND ) GameModeEntity:SetLoseGoldOnDeath( LOSE_GOLD_ON_DEATH ) GameModeEntity:SetRecommendedItemsDisabled( RECOMMENDED_ITEMS_DISABLED ) GameModeEntity:SetRemoveIllusionsOnDeath( REMOVE_ILLUSIONS_ON_DEATH ) GameModeEntity:SetStashPurchasingDisabled( STASH_PURCHASING_DISABLED ) GameModeEntity:SetTopBarTeamValuesOverride( TOP_BAR_TEAM_VALUES_OVERRIDE ) GameModeEntity:SetTopBarTeamValuesVisible( TOP_BAR_TEAM_VALUES_VISIBLE ) end end -- This function is called once when the player fully connects and becomes 'Ready' during Loading function GameMode:OnConnectFull( keys ) print ( 'OnConnectFull' ) --DeepPrintTable( keys ) local player_id = keys.index -- Setup the GameMode parameters GameMode:CaptureGameMode() -- Set starting player gold Timers:CreateTimer( function() PlayerResource:SetGold( player_id, STARTING_GOLD, false ) end ) end -- The overall game state has changed function GameMode:OnGameRulesStateChange( keys ) local new_state = GameRules:State_Get() if new_state == DOTA_GAMERULES_STATE_STRATEGY_TIME then GameMode:OnStrategyTimeState() elseif new_state == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then GameMode:OnGameInProgressState() end end -- Game strategy time state function GameMode:OnStrategyTimeState() print ( 'OnStrategyTimeState' ) local nb_players = PlayerResource:GetPlayerCountForTeam( DOTA_TEAM_GOODGUYS ) -- Select the player who will be playing the Houndmaster self.houndmaster = RandomInt( 0, nb_players - 1 ) DeepPrintTable( { nb_players = nb_players, houndmaster = self.houndmaster } ) end -- This function is called once and only once when the game completely begins (about 0:00 on the clock). At this point, -- gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function -- is useful for starting any game logic timers/thinkers, beginning the first round, etc. function GameMode:OnGameInProgressState() print( 'OnGameInProgressState' ) GameMode:SpawnNPC( NPC_BOSS_LIST[1], ENTITY_SPAWNER_AREA_0, 1 ) end -- An NPC has spawned somewhere in game. This includes heroes function GameMode:OnNPCSpawned( keys ) --print( 'OnNPCSpawned' ) --DeepPrintTable( keys ) end -- A player picked a hero function GameMode:OnPlayerPickHero( keys ) print ( 'OnPlayerPickHero' ) --DeepPrintTable(keys) local hero = EntIndexToHScript( keys.heroindex ) local hero_classname = hero:GetClassname() local player_id = hero:GetPlayerID() -- We change the selected player's Hound hero with the Houndmaster self.houndmasterSpawned = true -- DEBUG if not self.houndmasterSpawned and player_id == self.houndmaster then self.houndmasterSpawned = true -- We start the ReplaceHeroWith next frame, because we have to.. Timers:CreateTimer( function() GameMode:ReplaceHero( player_id, CUSTOM_HERO_HOUNDMASTER ) end ) -- Another OnPlayerPickHero will be triggered due to ReplaceHeroWith, so we stop there return end -- Hero setup GameMode:RemoveWearables( hero ) if hero_classname == CUSTOM_HERO_HOUND then GameMode:HeroSetupHound( hero ) elseif hero_classname == CUSTOM_HERO_HOUNDMASTER then hero:AddItemByName( CUSTOM_ITEM_HORN ) end end function GameMode:HeroSetupHound( hero ) self.nbHounds = self.nbHounds and self.nbHounds + 1 or 1 if self.nbHounds > 1 then -- Set a different model for each Hound local model = _G[ 'MODEL_HOUND_' .. self.nbHounds ] if model then hero:SetModel( model ) hero:SetOriginalModel( model ) end end -- Add the howling item to inventory hero:AddItemByName( CUSTOM_ITEM_HOWLING ) end -- Replace current hero with a new one function GameMode:ReplaceHero( player_id, new_hero_classname ) --print ( 'ReplaceHero' ) local player = PlayerResource:GetPlayer( player_id ) local hero = player:GetAssignedHero() local hero_id = hero:GetEntityIndex() local gold = hero:GetGold() local xp = hero:GetCurrentXP() DeepPrintTable( { player_id = player_id, new_hero_classname = new_hero_classname, gold = gold, xp = xp } ) -- Replace the player's hero with the current gold and experience PlayerResource:ReplaceHeroWith( player_id, new_hero_classname, gold, xp ) hero:RemoveSelf() end -- Remove all hero wearables function GameMode:RemoveWearables( hero ) --print ( 'RemoveWearables' ) local model = hero:FirstMoveChild() while model ~= nil do if model:GetClassname() == 'dota_item_wearable' then -- Replace each wearable item with an invisible one model:SetModel( MODEL_INVISIBLEBOX ) end model = model:NextMovePeer() end end -- function GameMode:SpawnNPC( npc_classname, spawner_name, level ) local spawner = Entities:FindByName( nil, spawner_name ) local spawner_coords = spawner:GetAbsOrigin() local npc = CreateUnitByName( npc_classname, spawner_coords, true, nil, nil, DOTA_TEAM_NEUTRALS ) if npc and level > 1 then npc:CreatureLevelUp( level - 1 ) end end -------------------- -- DEBUG COMMANDS -- -------------------- function GameMode:OnSwitchHero() local player = Convars:GetCommandClient() local player_id = player:GetPlayerID() local hero_classname = player:GetAssignedHero():GetClassname() local new_hero_classname = hero_classname == CUSTOM_HERO_HOUND and CUSTOM_HERO_HOUNDMASTER or hero_classname == CUSTOM_HERO_HOUNDMASTER and CUSTOM_HERO_HOUND GameMode:ReplaceHero( player_id, new_hero_classname ) end function GameMode:OnSpawnBoss() local npc_classname = NPC_BOSS_LIST[1] local spawner_name = ENTITY_SPAWNER_AREA_0 GameMode:SpawnNPC( npc_classname, spawner_name, 4 ) end
mit
alimashmamali/test
plugins/owners.lua
1467
12478
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) 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 settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
nginxsuper/gin
spec/core/request_spec.lua
2
3654
require 'spec.spec_helper' -- gin local Request = require 'gin.core.request' describe("Request", function() before_each(function() ngx = { var = { uri = "/uri", request_method = 'POST' }, req = { read_body = function() return end, get_body_data = function() return nil end, get_uri_args = function() return { uri_param = '2' } end, get_headers = function() return { ["Content-Type"] = "application/json" } end, get_post_args = function() return { body_param = '2' } end } } end) after_each(function() ngx = nil end) describe("body", function() it("reads the body on init", function() spy.on(ngx.req, "read_body") local request = Request.new(ngx) assert.spy(ngx.req.read_body).was.called(1) ngx.req.read_body:revert() end) it("sets raw body to the returned value", function() ngx.req.get_body_data = function() return '{"param":"value"}' end local request = Request.new(ngx) assert.are.equal('{"param":"value"}', request.body_raw) end) describe("when body is a valid JSON", function() it("sets request body to a table", function() ngx.req.get_body_data = function() return '{"param":"value"}' end local request = Request.new(ngx) assert.are.same({ param = "value" }, request.body) end) end) describe("when body is nil", function() it("sets request body to nil", function() ngx.req.get_body_data = function() return nil end local request = Request.new(ngx) assert.are.same(nil, request.body) end) end) describe("when body is an invalid JSON", function() it("raises an error", function() ngx.req.get_body_data = function() return "not-json" end ok, err = pcall(function() return Request.new(ngx) end) assert.are.equal(false, ok) assert.are.equal(103, err.code) end) end) describe("when body is not a JSON hash", function() it("raises an error", function() ngx.req.get_body_data = function() return'["one", "two"]' end ok, err = pcall(function() return Request.new(ngx) end) assert.are.equal(false, ok) assert.are.equal(104, err.code) end) end) end) describe("common attributes", function() before_each(function() request = Request.new(ngx) end) after_each(function() request = nil end) it("returns nil for unset attrs", function() assert.are.same(nil, request.unexisting_attr) end) it("returns uri", function() assert.are.same('/uri', request.uri) end) it("returns method", function() assert.are.same('POST', request.method) end) it("returns uri_params", function() assert.are.same({ uri_param = '2' }, request.uri_params) end) it("returns headers", function() assert.are.same({ ["Content-Type"] = "application/json" }, request.headers) end) it("sets and returns api_version", function() request.api_version = '1.2' assert.are.same('1.2', request.api_version) end) end) end)
mit
pandaforks/tido-rainbow
demos/lights/main.lua
1
1732
-- Copyright (c) 2010-14 Bifrost Entertainment AS and Tommy Nguyen -- Distributed under the MIT License. -- (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) g_scene = g_scene or {} function init() local assets = rainbow.texture("normal_map_test.png") local background = rainbow.spritebatch(1) background:set_normal(assets) background:set_texture(assets) local screen = rainbow.platform.screen --[[ local sprite = background:create_sprite(512, 440) sprite:set_position(screen.width * 0.5, screen.height * 0.5) sprite:set_normal(assets:create(1, 443, 512, 440)) sprite:set_texture(assets:create(1, 1, 512, 440)) --]] local sprite = background:create_sprite(450, 338) sprite:set_position(screen.width * 0.5, screen.height * 0.5) sprite:set_normal(assets:create(515, 341, 450, 338)) sprite:set_texture(assets:create(515, 1, 450, 338)) local sprite_node = rainbow.scenegraph:add_batch(background) g_scene.background = background local diffuse = rainbow.shaders.diffuse(true) diffuse:set_cutoff(1000) local screen = rainbow.platform.screen diffuse:set_position(screen.width * 0.5, screen.height * 0.5) diffuse:set_radius(1000) rainbow.scenegraph:attach_program(sprite_node, diffuse) g_scene.lighting = diffuse g_scene.delegate = { key_down = function() end, key_up = function() end, touch_began = function() end, touch_canceled = function() end, touch_ended = function() end, touch_moved = function() end, } rainbow.input.subscribe(g_scene.delegate) end function tick() end function update() g_scene.delegate.touch_moved = function(self, touches) for h,t in pairs(touches) do g_scene.lighting:set_position(t.x, t.y, 100) break end end update = tick end
mit
Choumiko/Factorio-Stdlib
stdlib/entity/inventory.lua
2
3172
--- For working with inventories -- @module Inventory -- @usage local Inventory = require('stdlib/entity/inventory') local fail_if_missing = require 'stdlib/core'['fail_if_missing'] Inventory = {} --luacheck: allow defined top --- Copies an inventory contents to a destination inventory using simple item stacks. -- @tparam LuaInventory src source inventory to copy from -- @tparam LuaInventory dest destination inventory, to copy to -- @tparam[opt=false] boolean clear clear the contents of the source inventory -- @treturn {LuaSimpleItemStack,...} an array of left over items that could not be inserted into dest. function Inventory.copy_as_simple_stacks(src, dest, clear) fail_if_missing(src, "missing source inventory") fail_if_missing(dest, "missing destination inventory") local left_over = {} for i = 1, #src do local stack = src[i] if stack and stack.valid and stack.valid_for_read then local simple_stack = { name = stack.name, count = stack.count, health = stack.health or 1, durability = stack.durability } -- ammo is a special case field, accessing it on non-ammo itemstacks causes an exception simple_stack.ammo = stack.prototype.magazine_size and stack.ammo --Insert simple stack into inventory, add to left_over if not all were inserted. simple_stack.count = simple_stack.count - dest.insert(simple_stack) if simple_stack.count > 0 then table.insert(left_over, simple_stack) end end end if clear then src.clear() end return left_over end --- Given a function, apply it to each slot in the inventory. Passes the slot index as second argument to the function. -- <p>Iteration is aborted if the applied function returns true for any element during iteration. -- @tparam LuaInventory inventory to be iterated -- @tparam function func to apply to values -- @param[opt] ... additional arguments passed to the function -- @treturn ?|LuaItemStack the slot interation was aborted at or nil function Inventory.each(inventory, func, ...) local index for i=1, #inventory do if func(inventory[i], i, ...) then index = i break end end return index and inventory[index] end --- Given a function, apply it to each slot in the inventory. Passes the slot index as second argument to the function. -- <p>Iteration is aborted if the applied function returns true for any element during iteration. Iteration is performed from -- last to first in order to support dynamically sized inventories.</p> -- @tparam LuaInventory inventory to be iterated -- @tparam function func to apply to values -- @param[opt] ... additional arguments passed to the function -- @treturn ?|LuaItemStack the slot iteration was aborted at or nil function Inventory.each_reverse(inventory, func, ...) local index for i=#inventory, 1, -1 do if func(inventory[i], i, ...) then index = i break end end return index and inventory[index] end return Inventory
isc
rockdragon/LuaPractice
src/maths/weighingRand.lua
1
1925
WeighingRand = {} --[[ 加权随机 要求输入: a table { ["result1"] = 10, ["result2"] = 20 ... } --]] ---[[生成 用于查找的轴表 function new_pivot_table() local pivot_meta = {} function pivot_meta:locate(k) if type(k) ~= "number" then error("should supply a numerical key.") end local p = 0 for _, r in ipairs(self) do p = p + r.weight if p >= k then print("found:", k, "in", r.result, "range", r.weight.."~"..p) return r.result end end return nil end -- source { key is result, v is weight} function pivot_meta:shift_in(source, ordered) local pos = 0 for k, v in pairs(source) do pos = pos + v if pos > 100 then break end local i = ordered:pos(v) if i ~= nil then self[i] = { weight = v, result = k} end end end local pivot_table = {} setmetatable(pivot_table, { __index = pivot_meta }) return pivot_table; end --]] ---[[ 将无序表转为有序结构 {1: 5, 2: 10...} function make_ordered(t) local ordered_meta = {} function ordered_meta.pos(self, k) for i, v in ipairs(self) do if v == k then return i end -- return index end end local ordered = {} for k, v in pairs(t) do table.insert(ordered, v) end table.sort(ordered, function(a, b) return a < b end) setmetatable(ordered, { __index = ordered_meta }) return ordered end --]] ---[[ 产生一个随机数生产器 function WeighingRand.new(source) local ordered = make_ordered(source) local pivot_table = new_pivot_table() pivot_table:shift_in(source, ordered) return function() -- interface local r = math.random(100) print("random seed:", r) return pivot_table:locate(r) end end --]] return WeighingRand
mit
apletnev/koreader-base
ffi/framebuffer_SDL2_0.lua
1
2162
-- load common SDL input/video library local SDL = require("ffi/SDL2_0") local BB = require("ffi/blitbuffer") local util = require("ffi/util") local framebuffer = { -- this blitbuffer will be used when we use refresh emulation sdl_bb = nil, } function framebuffer:init() if not self.dummy then SDL.open() -- we present this buffer to the outside local bb = BB.new(SDL.w, SDL.h, BB.TYPE_BBRGB32) local flash = os.getenv("EMULATE_READER_FLASH") if flash then -- in refresh emulation mode, we use a shadow blitbuffer -- and blit refresh areas from it. self.sdl_bb = bb self.bb = BB.new(SDL.w, SDL.h, BB.TYPE_BBRGB32) else self.bb = bb end self.invert_bb = BB.new(SDL.w, SDL.h, BB.TYPE_BBRGB32) else self.bb = BB.new(600, 800) end self.bb:fill(BB.COLOR_WHITE) self:refreshFull() framebuffer.parent.init(self) end function framebuffer:_render(bb) if bb:getInverse() == 1 then self.invert_bb:invertblitFrom(bb) SDL.SDL.SDL_UpdateTexture(SDL.texture, nil, self.invert_bb.data, self.invert_bb.pitch) else SDL.SDL.SDL_UpdateTexture(SDL.texture, nil, bb.data, bb.pitch) end SDL.SDL.SDL_RenderClear(SDL.renderer) SDL.SDL.SDL_RenderCopy(SDL.renderer, SDL.texture, nil, nil) SDL.SDL.SDL_RenderPresent(SDL.renderer) end function framebuffer:refreshFullImp(x, y, w, h) if self.dummy then return end local bb = self.full_bb or self.bb if not (x and y and w and h) then x = 0 y = 0 w = bb:getWidth() h = bb:getHeight() end self.debug("refresh on physical rectangle", x, y, w, h) local flash = os.getenv("EMULATE_READER_FLASH") if flash then self.sdl_bb:invertRect(x, y, w, h) self:_render(bb) util.usleep(tonumber(flash)*1000) self.sdl_bb:setRotation(bb:getRotation()) self.sdl_bb:setInverse(bb:getInverse()) self.sdl_bb:blitFrom(bb, x, y, x, y, w, h) end self:_render(bb) end function framebuffer:close() SDL.SDL.SDL_Quit() end return require("ffi/framebuffer"):extend(framebuffer)
agpl-3.0
movb/Algorithm-Implementations
A_Star_Search/Lua/Yonaba/utils/bheap.lua
78
2454
-- Binary Heap data structure implementation -- See: http://www.policyalmanac.org/games/binaryHeaps.htm -- Adapted from: https://github.com/Yonaba/Binary-Heaps local PATH = (...):gsub('%.bheap$','') local class = require (PATH .. '.class') -- Looks for item in an array local function findIndex(array, item) for k,v in ipairs(array) do if v == item then return k end end end -- Percolates up to restore heap property local function sift_up(bheap, index) if index == 1 then return end local pIndex if index <= 1 then return end if index%2 == 0 then pIndex = index/2 else pIndex = (index-1)/2 end if not bheap._sort(bheap._heap[pIndex], bheap._heap[index]) then bheap._heap[pIndex], bheap._heap[index] = bheap._heap[index], bheap._heap[pIndex] sift_up(bheap, pIndex) end end -- Percolates down to restore heap property local function sift_down(bheap,index) local lfIndex,rtIndex,minIndex lfIndex = 2*index rtIndex = lfIndex + 1 if rtIndex > bheap.size then if lfIndex > bheap.size then return else minIndex = lfIndex end else if bheap._sort(bheap._heap[lfIndex],bheap._heap[rtIndex]) then minIndex = lfIndex else minIndex = rtIndex end end if not bheap._sort(bheap._heap[index],bheap._heap[minIndex]) then bheap._heap[index],bheap._heap[minIndex] = bheap._heap[minIndex],bheap._heap[index] sift_down(bheap,minIndex) end end -- Binary heap class -- Instantiates minHeaps by default local bheap = class() function bheap:initialize() self.size = 0 self._sort = function(a,b) return a < b end self._heap = {} end -- Clears the heap function bheap:clear() self._heap = {} self.size = 0 end -- Checks if the heap is empty function bheap:isEmpty() return (self.size==0) end -- Pushes a new item into the heap function bheap:push(item) self.size = self.size + 1 self._heap[self.size] = item sift_up(self, self.size) end -- Pops the lowest (or highest) best item out of the heap function bheap:pop() local root if self.size > 0 then root = self._heap[1] self._heap[1] = self._heap[self.size] self._heap[self.size] = nil self.size = self.size-1 if self.size > 1 then sift_down(self, 1) end end return root end -- Sorts a specific item in the heap function bheap:sort(item) if self.size <= 1 then return end local i = findIndex(self._heap, item) if i then sift_up(self, i) end end return bheap
mit
soccermitchy/luamodo
Utils/Misc_Utils.lua
2
5656
covered = {} Timers = {} TableTypes = {} TableTypes["table"] = true SaniTable = {} SaniTable["<"] = "&lt;" SaniTable[">"] = "&gt;" SaniTable["\""] = "&#34;" SaniTable["'"] = "&#39;" SaniTable["\\"] = "&#92;" SaniTable["/"] = "&#47;" SaniTable["`"] = "&#96;" SaniTable["\r"] = "" SaniTable["\n"] = "" do -- modify type() to look at __type if the object has one local oldtype = type function type(object) if (oldtype(object) == "table") then mt = getmetatable(object) if (object.__type) then return object.__type else if (mt) then return mt.__type or oldtype(object) end end end return oldtype(object) end end function Reminder(str) print(str) os.exit() end function concat(tab,sep,i,j) if (i == nil) then i = 1 end if (j == nil) then j = #tab end for k = i,j do tab[k] = tostring(tab[k]) end return table.concat(tab,sep,i,j) end function Merge(table1,table2) for k,v in pairs(table2) do table1[k] = v end return table1 end function AssertType(var,vartype,varname) assert(type(var) == vartype,"Expected ".. vartype .." for ".. varname ..", got ".. type(var)) return var end function OutputTable(ttable,idchr,func,level) if (idchr == nil) then idchr = " " end if (func == nil) then func = print end covered[tostring(ttable)] = true if (level == nil) then level = 1 end for k,v in pairs(ttable) do func(string.rep(idchr,level) .. tostring(k) .." = ".. tostring(v)) if (TableTypes[type(v)]) then if (covered[tostring(v)] ~= true) then OutputTable(v,idchr,func,level + 1) else func(string.rep(idchr,level + 1) .."Already printed") end end end if (level == 1) then covered = {} end end function explode(div,str) if (div == "") then arr = {} for i = 1, string.len(str) do arr[i] = string.sub(str,i,i) end return arr end local pos,arr = 0,{} for st,sp in function() return string.find(str,div,pos,true) end do table.insert(arr,string.sub(str,pos,st-1)) pos = sp + 1 end table.insert(arr,string.sub(str,pos)) return arr end function DoTimers() for k,v in pairs(Timers) do difference = os.time() - Timers[k].starttime if (difference >= Timers[k].delay) then if (Timers[k].reps ~= -1) then Timers[k].reps = Timers[k].reps - 1 func = Timers[k].func Timers[k].func(unpack(Timers[k].args)) if (Timers[k]) then -- make sure the function we just called didn't remove the timer to avoid some nasty errors Timers[k].starttime = os.time() if (Timers[k].reps == 0) then Timers[k] = nil end end else Timers[k].func(unpack(Timers[k].args)) if (Timers[k]) then Timers[k].starttime = os.time() end end end end end function Timer(name,delay,reps,func,args) if (reps == 0) then reps = -1 end if (delay == "off") then Timers[name] = nil return end if (name == nil) then error("Timer name expected for first parameter, got nil") end if (type(name) ~= "string") and (type(name) ~= "number") then error("String or number expected for timer name, got ".. type(name)) end if (delay == nil) and (reps == nil) and (func == nil) and (args == nil) then if (Timers[name]) then local ttable = Timers[name] ttable.exists = true return ttable else return {exists = false} end end if (Timers[name]) then local ttable = {} ttable.delay = delay ttable.reps = reps ttable.func = func ttable.args = args ttable.starttime = os.time() Timers[name] = Merge(Timers[name],ttable) AssertType(Timers[name].delay,"number","Delay") AssertType(Timers[name].reps,"number","Repetitions") AssertType(Timers[name].func,"function","Function") AssertType(Timers[name].args,"table","Arguments") else Timers[name] = {} Timers[name].delay = AssertType(delay,"number","Delay") Timers[name].reps = AssertType(reps,"number","Repetitions") Timers[name].func = AssertType(func,"function","Function") Timers[name].args = AssertType(args,"table","Arguments") Timers[name].starttime = os.time() end end function ShallowCopy(tab) --shallow copy rtab = {} for k,v in pairs(tab) do rtab[k] = v end return rtab end function DeepCopy(object) local lookup_table = {} local function _copy(object) if type(object) ~= "table" then return object elseif lookup_table[object] then return lookup_table[object] end local new_table = {} lookup_table[object] = new_table for index, value in pairs(object) do new_table[_copy(index)] = _copy(value) end return setmetatable(new_table, _copy(getmetatable(object))) end return _copy(object) end do local meta = {__call = function(t, ...) return t.__function(t, ...) end, __type = "TableFunc" } function TableFunc(fn) return setmetatable({__function = fn}, meta) end end function LoadDir(dir) for file in lfs.dir(dir) do if (file ~= ".") and (file ~= "..") and (lfs.attributes(dir .."/".. file).mode ~= "directory") and (string.match(dir .."/".. file,"(.+).lua$")) then dofile(dir .."/".. file) end end end function Sanitize(str) for k,v in pairs(SaniTable) do str = string.gsub(str,k,v) end return str end
mit
siggame/Joueur.lua
games/checkers/gameObject.lua
9
2227
-- GameObject: An object in the game. The most basic class that all game classes should inherit from automatically. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local BaseGameObject = require("joueur.baseGameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- An object in the game. The most basic class that all game classes should inherit from automatically. -- @classmod GameObject local GameObject = class(BaseGameObject) -- initializes a GameObject with basic logic as provided by the Creer code generator function GameObject:init(...) BaseGameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. self.gameObjectName = "" --- A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. self.id = "" --- Any strings logged will be stored here. Intended for debugging. self.logs = Table() end --- Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @tparam string message A string to add to this GameObject's log. Intended for debugging. function GameObject:log(message) return (self:_runOnServer("log", { message = message, })) end -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return GameObject
mit
siggame/Joueur.lua
games/chess/gameObject.lua
9
2227
-- GameObject: An object in the game. The most basic class that all game classes should inherit from automatically. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local BaseGameObject = require("joueur.baseGameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- An object in the game. The most basic class that all game classes should inherit from automatically. -- @classmod GameObject local GameObject = class(BaseGameObject) -- initializes a GameObject with basic logic as provided by the Creer code generator function GameObject:init(...) BaseGameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. self.gameObjectName = "" --- A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. self.id = "" --- Any strings logged will be stored here. Intended for debugging. self.logs = Table() end --- Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @tparam string message A string to add to this GameObject's log. Intended for debugging. function GameObject:log(message) return (self:_runOnServer("log", { message = message, })) end -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return GameObject
mit
lulin/trivial
learn-lua/sample.lua
1
1145
cmdline = {...} nargs = #cmdline local print_version local _usage local _usage_info local _unpack local cmd, exec, args _usage_info = "Usage:\ cmd args" ---- function _sequence_shift (seq) local new, i = {} for i = 2, #seq do new[i - 1] = seq[i] end return new end function _usage (self) print(_usage_info) self.list(self) end function print_version (self) print("Version: " .. self._version) end function _unpack (t, f, s, k, v) if (not f) then f, s, k = pairs(t) end k, v = f(s, k) if (not k) then return end return v, _unpack(t, f, s, k, v) end function _dump (self, method, ...) if (not method) then return end print(self[method](self, ...)) end function _list_methods(self) local k, v print("Supported commands:") for k, v in pairs(self) do if (type(v) == "function") then print(" "..k) end end end ---- sample = { _version = 0, usage = _usage, unpack = _unpack, test = _dump, list = _list_methods } ---- cmd = cmdline[1] args = _sequence_shift(cmdline) if (not cmd) then return print_version(sample) end if (not sample[cmd]) then sample.usage() return end sample[cmd](sample, unpack(args))
mit
sundream/gamesrv
script/attrblock/delaytonextlogin.lua
1
1036
--/* -- 延迟到玩家下次登录执行的操作 --*/ cdelaytonextlogin = class("cdelaytonextlogin") function cdelaytonextlogin:init(pid) self._self_call_onlogin = true -- 需要手动调用onlogin self.pid = pid self.queue = {} end function cdelaytonextlogin:load(data) if not data or not next(data) then return end self.queue = data.queue end function cdelaytonextlogin:save() local data = {} data.queue = self.queue return data end function cdelaytonextlogin:executex(cmd,...) local packfunc = pack_function(cmd,...) table.insert(self.queue,packfunc) end function cdelaytonextlogin:execute(cmd,...) local firstchar = string.char(string.byte(cmd,1,1)) assert(firstchar=="." or firstchar == ":") cmd = string.format("playermgr.getplayer(%d)%s",self.pid,cmd) return self:executex(cmd,...) end function cdelaytonextlogin:entergame() local queue = self.queue self.queue = {} for i,packfunc in ipairs(queue) do local func = unpack_function(packfunc) xpcall(func,onerror) end end return cdelaytonextlogin
gpl-2.0
harryzeng/skynet
lualib/snax/gateserver.lua
29
3258
local skynet = require "skynet" local netpack = require "netpack" local socketdriver = require "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(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
tbetbetbe/upb
tools/test_cinit.lua
3
2124
--[[ Tests for dump_cinit.lua. Runs first in a mode that generates some C code for an extension. The C code is compiled and then loaded by a second invocation of the test which checks that the generated defs are as expected. --]] local dump_cinit = require "dump_cinit" local upb = require "upb" -- Once APIs for loading descriptors are fleshed out, we should replace this -- with a descriptor for a meaty protobuf like descriptor.proto. local symtab = upb.SymbolTable{ upb.EnumDef{full_name = "MyEnum", values = { {"FOO", 1}, {"BAR", 77} } }, upb.MessageDef{full_name = "MyMessage", fields = { upb.FieldDef{label = upb.LABEL_REQUIRED, name = "field1", number = 1, type = upb.TYPE_INT32}, upb.FieldDef{label = upb.LABEL_REPEATED, name = "field2", number = 2, type = upb.TYPE_ENUM, subdef_name = ".MyEnum"}, upb.FieldDef{name = "field3", number = 3, type = upb.TYPE_MESSAGE, subdef_name = ".MyMessage"} } } } if arg[1] == "generate" then local f = assert(io.open(arg[2], "w")) local f_h = assert(io.open(arg[2] .. ".h", "w")) local appendc = dump_cinit.file_appender(f) local appendh = dump_cinit.file_appender(f_h) f:write('#include "lua.h"\n') f:write('#include "upb/bindings/lua/upb.h"\n') dump_cinit.dump_defs(symtab, "testdefs", appendh, appendc) f:write([[int luaopen_staticdefs(lua_State *L) { const upb_symtab *s = upbdefs_testdefs(&s); lupb_symtab_pushwrapper(L, s, &s); return 1; }]]) f_h:close() f:close() elseif arg[1] == "test" then local symtab = require "staticdefs" local msg = assert(symtab:lookup("MyMessage")) local enum = assert(symtab:lookup("MyEnum")) local f2 = assert(msg:field("field2")) assert(msg:def_type() == upb.DEF_MSG) assert(msg:full_name() == "MyMessage") assert(enum:def_type() == upb.DEF_ENUM) assert(enum:full_name() == "MyEnum") assert(enum:value("FOO") == 1) assert(f2:name() == "field2") assert(f2:containing_type() == msg) assert(f2:subdef() == enum) else error("Unknown operation " .. arg[1]) end
bsd-3-clause
sundream/gamesrv
script/card/fire/card242003.lua
1
2307
--<<card 导表开始>> local super = require "script.card.fire.card142003" ccard242003 = class("ccard242003",super,{ sid = 242003, race = 4, name = "狂野怒火", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 1, targettype = 22, halo = nil, desc = "在本回合内,使1个野兽获得+2攻击和免疫。", effect = { onuse = {addbuff={addatk=2,immune=1,lifecircle=1}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard242003:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard242003:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard242003:save() local data = super.save(self) -- todo: save data return data end return ccard242003
gpl-2.0
Midiman/Concrete
map.lua
1
2567
Class = require "lib.hump.class" GameState = require "lib.hump.gamestate" Camera = require "lib.hump.camera" bump = require "lib.bump.bump" sti = require "lib.sti" -- Entity = require "entities.entity" Block = require "entities.block" Enemy = require "entities.enemy" Player = require "entities.player" -- Map = Class { init = function(self, width, height) self.size = { w = width, h = height } self.camera = Camera(0,0) self.cameraBounds = { x = SCREEN_CENTER_X, y = SCREEN_CENTER_Y, w = width, h = height } self.world = bump.newWorld() -- self.entities = {} self.players = {} self:addEntities() self:addPlayers() self:addEnemies() -- end, -- addEntity = function(self, e, x, y, w, h) table.insert( self.entities, e ) end, removeEntity = function(self, e) for i, e in ipairs(self.entities) do if self.world:hasItem(self.entities[i]) then table.remove(self.entities, i) end end end, addEntities = function(self) for i=1,128 do local _x = 32 * (i-1) local _y = 480 local e = Block(self.world,_x,_y,32,32) self:addEntity(e) end end, addPlayers = function(self) for i=1,1 do local _x = 128 + math.random(0,960) local _y = 240-64 local e = Player(self.world,_x,_y) table.insert( self.players, e ) end end, addEnemies = function(self) for i=1,2 do local _x = 800 + math.random(0,320) local _y = 432 self.entities[#self.entities+1] = Enemy(self.world,_x,_y) end end, pruneDeadEntities = function(self) for i, e in ipairs(self.entities) do if e.isDestroyed then table.remove(self.entities, i) end end end, getEntitiesInRect = function(self,x,y,w,h) local ents = {} for i, e in ipairs(self.entities) do local _x, _y = e:getPosition() if _x > x and _x <= (x+w) and _y > y and _y <= (y+h) then ents[#ents+1] = e end end return ents end, moveCameraWithBounds = function(self, dt) local _x, _y = self.players[1]:getPosition() self.camera:lookAt( math.min(math.max(self.cameraBounds.x, _x), self.cameraBounds.w), math.min(math.max(self.cameraBounds.y, _y), self.cameraBounds.h)) end, -- update = function(self,dt) for i, p in ipairs(self.players) do p:update(dt) end for i, e in ipairs(self.entities) do e:update(dt) end self:pruneDeadEntities() self:moveCameraWithBounds(dt) end, draw = function(self) self.camera:attach() for i, p in ipairs(self.players) do p:draw() end for i, e in ipairs(self.entities) do e:draw() end self.camera:detach() end } return Map
mit
siggame/Joueur.lua
games/stumped/ai.lua
2
5211
-- This is where you build your AI for the Stumped game. local class = require("joueur.utilities.class") local BaseAI = require("joueur.baseAI") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- the AI functions for the Stumped game. -- @classmod AI local AI = class(BaseAI) --- The reference to the Game instance this AI is playing. -- @field[Game] self.game -- @see Game --- The reference to the Player this AI controls in the Game. -- @field[Player] self.player -- @see Player --- this is the name you send to the server to play as. function AI:getName() -- <<-- Creer-Merge: get-name -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. return "Stumped Lua Player" -- REPLACE THIS WITH YOUR TEAM NAME! -- <<-- /Creer-Merge: get-name -->> end --- this is called once the game starts and your AI knows its playerID and game. You can initialize your AI here. function AI:start() -- <<-- Creer-Merge: start -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- replace with your start logic -- <<-- /Creer-Merge: start -->> end --- this is called when the game's state updates, so if you are tracking anything you can update it here. function AI:gameUpdated() -- <<-- Creer-Merge: game-updated -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- replace with your game updated logic -- <<-- /Creer-Merge: game-updated -->> end --- this is called when the game ends, you can clean up your data and dump files here if need be -- @tparam boolean won true means you won, won == false means you lost -- @tparam string reason why you won or lost function AI:ended(won, reason) -- <<-- Creer-Merge: ended -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- replace with your ended -- <<-- /Creer-Merge: ended -->> end -- Game Logic Functions: functions you must fill out to send data to the game server to actually play the game! -- --- This is called every time it is this AI.player's turn. -- @treturn bool Represents if you want to end your turn. True means end your turn, False means to keep your turn going and re-call this function. function AI:runTurn() -- <<-- Creer-Merge: runTurn -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- Put your game logic here for runTurn return true -- <<-- /Creer-Merge: runTurn -->> end --- A very basic path finding algorithm (Breadth First Search) that when given a starting Tile, will return a valid path to the goal Tile. -- @tparam Tile start the starting Tile -- @tparam Tile goal the goal Tile -- @treturns Table(Tile) An array of Tiles representing the path, the the first element being a valid adjacent Tile to the start, and the last element being the goal. function AI:findPath(start, goal) if start == goal then -- no need to make a path to here... return Table() end -- queue of the tiles that will have their neighbors searched for 'goal' local fringe = Table() -- How we got to each tile that went into the fringe. local cameFrom = Table() -- Enqueue start as the first tile to have its neighbors searched. fringe:insert(start); -- keep exploring neighbors of neighbors... until there are no more. while #fringe > 0 do -- the tile we are currently exploring. local inspect = fringe:popFront(); -- cycle through the tile's neighbors. for i, neighbor in ipairs(inspect:getNeighbors()) do -- if we found the goal, we have the path! if neighbor == goal then -- Follow the path backward to the start from the goal and return it. local path = Table(goal) -- Starting at the tile we are currently at, insert them retracing our steps till we get to the starting tile while inspect ~= start do path:pushFront(inspect) inspect = cameFrom[inspect.id] end return path; end -- else we did not find the goal, so enqueue this tile's neighbors to be inspected -- if the tile exists, has not been explored or added to the fringe yet, and it is pathable if neighbor and not cameFrom[neighbor.id] and neighbor:isPathable() then -- add it to the tiles to be explored and add where it came from for path reconstruction. fringe:insert(neighbor) cameFrom[neighbor.id] = inspect end end end -- if we got here, no path was found return Table() end -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you need additional functions for your AI you can add them here -- <<-- /Creer-Merge: functions -->> return AI
mit
codemon66/Urho3D
Source/ThirdParty/LuaJIT/src/jit/p.lua
40
9092
---------------------------------------------------------------------------- -- LuaJIT profiler. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module is a simple command line interface to the built-in -- low-overhead profiler of LuaJIT. -- -- The lower-level API of the profiler is accessible via the "jit.profile" -- module or the luaJIT_profile_* C API. -- -- Example usage: -- -- luajit -jp myapp.lua -- luajit -jp=s myapp.lua -- luajit -jp=-s myapp.lua -- luajit -jp=vl myapp.lua -- luajit -jp=G,profile.txt myapp.lua -- -- The following dump features are available: -- -- f Stack dump: function name, otherwise module:line. Default mode. -- F Stack dump: ditto, but always prepend module. -- l Stack dump: module:line. -- <number> stack dump depth (callee < caller). Default: 1. -- -<number> Inverse stack dump depth (caller > callee). -- s Split stack dump after first stack level. Implies abs(depth) >= 2. -- p Show full path for module names. -- v Show VM states. Can be combined with stack dumps, e.g. vf or fv. -- z Show zones. Can be combined with stack dumps, e.g. zf or fz. -- r Show raw sample counts. Default: show percentages. -- a Annotate excerpts from source code files. -- A Annotate complete source code files. -- G Produce raw output suitable for graphical tools (e.g. flame graphs). -- m<number> Minimum sample percentage to be shown. Default: 3. -- i<number> Sampling interval in milliseconds. Default: 10. -- ---------------------------------------------------------------------------- -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local profile = require("jit.profile") local vmdef = require("jit.vmdef") local math = math local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor local sort, format = table.sort, string.format local stdout = io.stdout local zone -- Load jit.zone module on demand. -- Output file handle. local out ------------------------------------------------------------------------------ local prof_ud local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth local prof_ann, prof_count1, prof_count2, prof_samples local map_vmmode = { N = "Compiled", I = "Interpreted", C = "C code", G = "Garbage Collector", J = "JIT Compiler", } -- Profiler callback. local function prof_cb(th, samples, vmmode) prof_samples = prof_samples + samples local key_stack, key_stack2, key_state -- Collect keys for sample. if prof_states then if prof_states == "v" then key_state = map_vmmode[vmmode] or vmmode else key_state = zone:get() or "(none)" end end if prof_fmt then key_stack = profile.dumpstack(th, prof_fmt, prof_depth) key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x) return vmdef.ffnames[tonumber(x)] end) if prof_split == 2 then local k1, k2 = key_stack:match("(.-) [<>] (.*)") if k2 then key_stack, key_stack2 = k1, k2 end elseif prof_split == 3 then key_stack2 = profile.dumpstack(th, "l", 1) end end -- Order keys. local k1, k2 if prof_split == 1 then if key_state then k1 = key_state if key_stack then k2 = key_stack end end elseif key_stack then k1 = key_stack if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end end -- Coalesce samples in one or two levels. if k1 then local t1 = prof_count1 t1[k1] = (t1[k1] or 0) + samples if k2 then local t2 = prof_count2 local t3 = t2[k1] if not t3 then t3 = {}; t2[k1] = t3 end t3[k2] = (t3[k2] or 0) + samples end end end ------------------------------------------------------------------------------ -- Show top N list. local function prof_top(count1, count2, samples, indent) local t, n = {}, 0 for k, v in pairs(count1) do n = n + 1 t[n] = k end sort(t, function(a, b) return count1[a] > count1[b] end) for i=1,n do local k = t[i] local v = count1[k] local pct = floor(v*100/samples + 0.5) if pct < prof_min then break end if not prof_raw then out:write(format("%s%2d%% %s\n", indent, pct, k)) elseif prof_raw == "r" then out:write(format("%s%5d %s\n", indent, v, k)) else out:write(format("%s %d\n", k, v)) end if count2 then local r = count2[k] if r then prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or (prof_depth < 0 and " -> " or " <- ")) end end end end -- Annotate source code local function prof_annotate(count1, samples) local files = {} local ms = 0 for k, v in pairs(count1) do local pct = floor(v*100/samples + 0.5) ms = math.max(ms, v) if pct >= prof_min then local file, line = k:match("^(.*):(%d+)$") local fl = files[file] if not fl then fl = {}; files[file] = fl; files[#files+1] = file end line = tonumber(line) fl[line] = prof_raw and v or pct end end sort(files) local fmtv, fmtn = " %3d%% | %s\n", " | %s\n" if prof_raw then local n = math.max(5, math.ceil(math.log10(ms))) fmtv = "%"..n.."d | %s\n" fmtn = (" "):rep(n).." | %s\n" end local ann = prof_ann for _, file in ipairs(files) do local f0 = file:byte() if f0 == 40 or f0 == 91 then out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file)) break end local fp, err = io.open(file) if not fp then out:write(format("====== ERROR: %s: %s\n", file, err)) break end out:write(format("\n====== %s ======\n", file)) local fl = files[file] local n, show = 1, false if ann ~= 0 then for i=1,ann do if fl[i] then show = true; out:write("@@ 1 @@\n"); break end end end for line in fp:lines() do if line:byte() == 27 then out:write("[Cannot annotate bytecode file]\n") break end local v = fl[n] if ann ~= 0 then local v2 = fl[n+ann] if show then if v2 then show = n+ann elseif v then show = n elseif show+ann < n then show = false end elseif v2 then show = n+ann out:write(format("@@ %d @@\n", n)) end if not show then goto next end end if v then out:write(format(fmtv, v, line)) else out:write(format(fmtn, line)) end ::next:: n = n + 1 end fp:close() end end ------------------------------------------------------------------------------ -- Finish profiling and dump result. local function prof_finish() if prof_ud then profile.stop() local samples = prof_samples if samples == 0 then if prof_raw ~= true then out:write("[No samples collected]\n") end return end if prof_ann then prof_annotate(prof_count1, samples) else prof_top(prof_count1, prof_count2, samples, "") end prof_count1 = nil prof_count2 = nil prof_ud = nil end end -- Start profiling. local function prof_start(mode) local interval = "" mode = mode:gsub("i%d*", function(s) interval = s; return "" end) prof_min = 3 mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end) prof_depth = 1 mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end) local m = {} for c in mode:gmatch(".") do m[c] = c end prof_states = m.z or m.v if prof_states == "z" then zone = require("jit.zone") end local scope = m.l or m.f or m.F or (prof_states and "" or "f") local flags = (m.p or "") prof_raw = m.r if m.s then prof_split = 2 if prof_depth == -1 or m["-"] then prof_depth = -2 elseif prof_depth == 1 then prof_depth = 2 end elseif mode:find("[fF].*l") then scope = "l" prof_split = 3 else prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0 end prof_ann = m.A and 0 or (m.a and 3) if prof_ann then scope = "l" prof_fmt = "pl" prof_split = 0 prof_depth = 1 elseif m.G and scope ~= "" then prof_fmt = flags..scope.."Z;" prof_depth = -100 prof_raw = true prof_min = 0 elseif scope == "" then prof_fmt = false else local sc = prof_split == 3 and m.f or m.F or scope prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ") end prof_count1 = {} prof_count2 = {} prof_samples = 0 profile.start(scope:lower()..interval, prof_cb) prof_ud = newproxy(true) getmetatable(prof_ud).__gc = prof_finish end ------------------------------------------------------------------------------ local function start(mode, outfile) if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stdout end prof_start(mode or "f") end -- Public module functions. return { start = start, -- For -j command line option. stop = prof_finish }
mit
jacklicn/mysql-proxy
tests/suite/base/t/tokens2.lua
4
2328
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] local proto = assert(require("mysql.proto")) local tokenizer = assert(require("mysql.tokenizer")) function connect_server() -- emulate a server proxy.response = { type = proxy.MYSQLD_PACKET_RAW, packets = { proto.to_challenge_packet({}) } } return proxy.PROXY_SEND_RESULT end -- -- returns the tokens of every query -- -- Uncomment the following line if using with MySQL command line. -- Keep it commented if using inside the test suite -- local counter = 0 function read_query( packet ) if packet:byte() ~= proxy.COM_QUERY then proxy.response = { type = proxy.MYSQLD_PACKET_OK } return proxy.PROXY_SEND_RESULT end local query = packet:sub(2) -- -- Uncomment the following two lines if using with MySQL command line. -- Keep them commented if using inside the test suite -- counter = counter + 1 -- if counter < 3 then return end local tokens = tokenizer.tokenize(query) proxy.response.type = proxy.MYSQLD_PACKET_OK proxy.response.resultset = { fields = { { type = proxy.MYSQL_TYPE_STRING, name = "id", }, { type = proxy.MYSQL_TYPE_STRING, name = "name", }, { type = proxy.MYSQL_TYPE_STRING, name = "text", }, }, rows = { } } for i = 1, #tokens do local token = tokens[i] table.insert(proxy.response.resultset.rows, { token['token_id'], token['token_name'], token['text'] } ) end return proxy.PROXY_SEND_RESULT end
gpl-2.0
asylium/BankHelper
locale.fr.lua
1
1298
-- Global UI string - fr if (GetLocale() == "frFR") then BH_UI_TITLE = "Bank Helper (fr)"; BH_UI_ITEMFILTER = "Filtre:"; -- Key binding BINDING_NAME_BH_UITOGGLE = "Afficher/Masquer BankHelper"; BINDING_HEADER_BH_UIBINDS= "Bank Helper"; BH_DAYS_NAME = {"Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"}; BH_WEEK_THURSDAY = 3; BH_ALL_CHAR = "Tous"; BH_UI_LEVEL = "Niv"; BH_UI_QUANTITY = "Nb"; BH_UI_TAB_BANK = "Banque"; BH_UI_TAB_MAIL = "Courriers"; BH_UI_TAB_CONTRIB = "Contrib."; BH_UI_TAB_OPTIONS = "Options"; BH_UI_MAIL_DAYS_LEFT = "%d jour(s) restant"; BH_UI_MAIL_RECV_DATE = "%s %d/%d/%d %d:%d"; BH_UI_MAIL_RECOVER = "Récupérer"; BH_UI_MAIL_UPDATE = "Mise à jour"; BH_UI_SAVE_RESET = "Enregistrer"; BH_UI_OPT_ACCOUNT = "Compte:"; BH_UI_OPT_GUILD = "Guilde:"; BH_UI_OPT_SAVEEQUIP = "Sauvegarder l'équipement équipé"; BH_UI_OPT_DEBUG = "Afficher les messages de debug"; BH_UI_OPT_SAVECONTRIB = "Enregistrer les contributions"; -- Item quality BH_QUALITY = {}; BH_QUALITY[0] = "Médiocre"; BH_QUALITY[1] = "Classique"; BH_QUALITY[2] = "Bonne"; BH_QUALITY[3] = "Rare"; BH_QUALITY[4] = "Épique"; BH_QUALITY[5] = "Légendaire"; BH_QUALITY[6] = "Artefact"; end
gpl-3.0
davidkazlauskas/safelists
src/lua/utilobjects.lua
1
2582
ObjectRetainer = { __index = { newId = function(self) local id = self.count self.count = self.count + 1 return id end, retain = function(self,id,object) self.table[id] = object end, retainNewId = function(self,object) local id = self:newId() self:retain(id,object) return id end, release = function(self,id) self.table[id] = nil end }, new = function() local res = { count = 0, table = {} } setmetatable(res,ObjectRetainer) return res end } -- download speed DownloadSpeedChecker = { __index = { new = function(samples) assert( type(samples) == "number", "expected num..." ) assert( samples >= 0, "Zigga nease..." ) local res = { iter = 0, intervals = {}, samples = samples } for i=1,samples do table.insert( res.intervals, DownloadSpeedChecker.__index.newInterval() ) end setmetatable(res,DownloadSpeedChecker) return res end, newInterval = function() return { unixStamp = 0, sum = 0 } end, regBytes = function(self,bytes) local current = os.time() local mod = current % self.samples + 1 if (self.iter ~= current) then self.iter = current self.intervals[mod].unixStamp = current self.intervals[mod].sum = 0 end self.intervals[mod].sum = self.intervals[mod].sum + bytes end, bytesPerSec = function(self) local total = 0 for k,v in ipairs(self.intervals) do total = total + v.sum end return total / self.samples end } } -- struct that holds current safelist path CurrentSafelist = { __index = { isSamePath = function(self,path) return self.path == path end, setPath = function(self,path) self.path = path end, isEmpty = function(self) return self.path == "" end, new = function() local res = { path = "" } setmetatable(res,CurrentSafelist) return res end } }
gpl-2.0
lhCheung1991/flappybird_cocos2dx_2
cocos2d/plugin/luabindings/auto/api/ProtocolAds.lua
146
1442
-------------------------------- -- @module ProtocolAds -- @extend PluginProtocol -- @parent_module plugin -------------------------------- -- brief show adview<br> -- param info The information of adview will be shown<br> -- Pay attention to the subclass definition<br> -- param pos The position where the adview be shown. -- @function [parent=#ProtocolAds] showAds -- @param self -- @param #map_table info -- @param #int pos -------------------------------- -- brief Hide the adview<br> -- param info The information of adview will be hided -- @function [parent=#ProtocolAds] hideAds -- @param self -- @param #map_table info -------------------------------- -- brief Query the points of player -- @function [parent=#ProtocolAds] queryPoints -- @param self -------------------------------- -- brief Spend the points.<br> -- Use this method to notify server spend points.<br> -- param points Need spend number of points -- @function [parent=#ProtocolAds] spendPoints -- @param self -- @param #int points -------------------------------- -- brief config the application info<br> -- param devInfo This parameter is the info of aplication,<br> -- different plugin have different format<br> -- warning Must invoke this interface before other interfaces.<br> -- And invoked only once. -- @function [parent=#ProtocolAds] configDeveloperInfo -- @param self -- @param #map_table devInfo return nil
mit
coordcn/miss-core
src/query.lua
1
2982
-- Copyright © 2017 coord.cn. All rights reserved. -- @author QianYe(coordcn@163.com) -- @license MIT license local uri = require("miss-core.src.uri") local utils = require("miss-core.src.utils") local _M = {} -- @breif query string to lua table -- @param query {string} -- @return tab {object} function _M.decode(str, limit) local fields = utils.split(str, "&") local tab = {} if fields then local len = #fields if limit and len > limit then len = limit end for i = 1, len do local field = fields[i] local key, val = string.match(field, "([^=]*)=(.*)") if key then key = uri.decodeComponent(key) val = uri.decodeComponent(val) local fieldType = type(tab[key]) if fieldType == "nil" then tab[key] = val elseif fieldType == "table" then table.insert(tab[key], val) else tab[key] = {tab[key], val} end end end end return tab end local function insertField(fields, key, val) if type(val) == "table" then for j = 1, #val do local field = key .. "=" .. val[j] table.insert(fields, field) end else local field = key .. "=" .. val table.insert(fields, field) end end -- @brief build query string -- @param tab {object} -- @param keys {array[string]} -- @return query {string} function _M.build(tab, keys) local fields = {} if keys then for i = 1, #keys do local key = keys[i] local val = tab[key] insertField(fields, key, val) end else for key, val in pairs(tab) do insertField(fields, key, val) end end return table.concat(fields, "&") end local function insertEncodedField(fields, key, val) if type(val) == "table" then for j = 1, #val do local field = utils.encodeComponent(key) .. "=" .. utils.encodeComponent(val[j]) table.insert(fields, field) end else local field = utils.encodeComponent(key) .. "=" .. utils.encodeComponent(val) table.insert(fields, field) end end -- @brief build query string, key and value encoded -- @param tab {object} -- @param keys {array[string]} -- @return query {string} function _M.encode(tab, keys) local fields = {} if keys then for i = 1, #keys do local key = keys[i] local val = tab[key] insertEncodedField(fields, key, val) end else for key, val in pairs(tab) do insertEncodedField(fields, key, val) end end return table.concat(fields, "&") end return _M
mit
sundream/gamesrv
script/card/cardtabledb.lua
1
1990
ccardtabledb = class("ccardtabledb",ccontainer) function ccardtabledb:init(conf) self.name = assert(conf.name) ccontainer.init(self,conf) self.pos_id = {} -- 卡表位置:卡表ID self.maxlen = 8 -- 最大卡表数 end function ccardtabledb:load(data) if not data or not next(data) then return end ccontainer.load(self,data) for id,cardtable in pairs(self.objs) do local pos = assert(cardtable.pos) self.pos_id[pos] = id end end function ccardtabledb:save() return ccontainer.save(self) end function ccardtabledb:clear() ccontainer.clear(self) self.pos_id = {} end function ccardtabledb:getcardtable(id) return self:get(id) end function ccardtabledb:getcardtablebypos(pos) local id = self.pos_id[pos] if id then return self:getcardtable(id) end end function ccardtabledb:getfreepos() for pos=1,self.maxlen do if not self.pos_id[pos] then return pos end end end --/* --增加卡表 --@param table cardtable --@example: --xxx:addcardtable({ -- id = 1, -- name = "测试卡表", -- race = 1, -- cards = {141001,...} -- 30个卡牌 --},"test") --*/ function ccardtabledb:addcardtable(cardtable,reason) local id = assert(cardtable.id) local pos = self:getfreepos() if not pos then return end logger.log("info","cardtable",format("[addcardtable] name=%s pid=%s id=%s pos=%s cardtable=%s reason=%s",self.name,self.pid,id,pos,cardtable,reason)) cardtable.pos = pos self.pos_id[pos] = id self:add(cardtable,id) return pos end function ccardtabledb:delcardtable(id,reason) local cardtable = self:getcardtable(id) if not cardtable then return end local pos = assert(cardtable.pos) logger.log("info","cardtable",string.format("[delcardtable] name=%s pid=%s id=%s pos=%s reason=%s",self.name,self.pid,id,pos,reason)) self.pos_id[pos] = nil self:del(id) return cardtable end function ccardtabledb:delcardtablebypos(pos,reason) local id = self.pos_id[pos] if id then return self:delcardtable(id,reason) end end return ccardtabledb
gpl-2.0
venusdeveloper/venus_beta
plugins/admin.lua
381
7085
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] == "addcontact" and matches[2] then add_contact(matches[2],matches[3],matches[4],ok_cb,false) return "Number "..matches[2].." add from contact list" 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 if matches[1] == "sync_gbans" then if not is_sudo(msg) then-- Sudo only return end local url = "http://seedteam.org/Teleseed/Global_bans.json" local SEED_gbans = http.request(url) local jdat = json:decode(SEED_gbans) for k,v in pairs(jdat) do redis:hset('user:'..v, 'print_name', k) banall_user(v) print(k, v.." Globally banned") end end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](addcontact) (.*) (.*) (.*)$", "^[!/](whois) (%d+)$", "^/(sync_gbans)$"--sync your global bans with seed }, run = run, } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
gpl-2.0
ld-test/lua-log
examples/syslog.lua
4
1052
local LogLib = require"log" local Format = require "log.writer.format" local SysLog = require "log.logformat.syslog" local writer = require "log.writer.list".new( Format.new( -- explicit set logformat to console require "log.logformat.default".new(), require "log.writer.stdout".new() ), require "log.writer.net.udp".new('127.0.0.1', 514) ) local LOG_FMT = LogLib.new('trace', writer, require "log.formatter.format".new(), SysLog.new('kern') ) local LOG_CON = LogLib.new('trace', writer, require "log.formatter.concat".new(), SysLog.new('USER') ) local LOG = LogLib.new('trace', writer, nil, SysLog.new('USER')) LOG.emerg ('!! EMERG !!') LOG_FMT.alert ('!! %-7s !!', 'ALERT' ) LOG_FMT.fatal ('!! %-7s !!', 'FATAL' ) LOG_FMT.error ('!! %-7s !!', 'ERROR' ) LOG_CON.warning ('!!', 'WARNING', '!!') LOG_FMT.notice ('!! %-7s !!', 'NOTICE' ) LOG_FMT.info ('!! %-7s !!', 'INFO' ) LOG_FMT.debug ('!! %-7s !!', 'DEBUG' ) LOG_FMT.trace ('!! %-7s !!', 'TRACE' )
mit
ctozlm/Dato-Core
src/unity/python/graphlab/lua/pl/text.lua
34
7257
--- Text processing utilities. -- -- This provides a Template class (modeled after the same from the Python -- libraries, see string.Template). It also provides similar functions to those -- found in the textwrap module. -- -- See @{03-strings.md.String_Templates|the Guide}. -- -- Calling `text.format_operator()` overloads the % operator for strings to give Python/Ruby style formated output. -- This is extended to also do template-like substitution for map-like data. -- -- > require 'pl.text'.format_operator() -- > = '%s = %5.3f' % {'PI',math.pi} -- PI = 3.142 -- > = '$name = $value' % {name='dog',value='Pluto'} -- dog = Pluto -- -- Dependencies: `pl.utils`, `pl.types` -- @module pl.text local gsub = string.gsub local concat,append = table.concat,table.insert local utils = require 'pl.utils' local bind1,usplit,assert_arg = utils.bind1,utils.split,utils.assert_arg local is_callable = require 'pl.types'.is_callable local unpack = utils.unpack local function lstrip(str) return (str:gsub('^%s+','')) end local function strip(str) return (lstrip(str):gsub('%s+$','')) end local function make_list(l) return setmetatable(l,utils.stdmt.List) end local function split(s,delim) return make_list(usplit(s,delim)) end local function imap(f,t,...) local res = {} for i = 1,#t do res[i] = f(t[i],...) end return res end --[[ module ('pl.text',utils._module) ]] local text = {} local function _indent (s,sp) local sl = split(s,'\n') return concat(imap(bind1('..',sp),sl),'\n')..'\n' end --- indent a multiline string. -- @param s the string -- @param n the size of the indent -- @param ch the character to use when indenting (default ' ') -- @return indented string function text.indent (s,n,ch) assert_arg(1,s,'string') assert_arg(2,n,'number') return _indent(s,string.rep(ch or ' ',n)) end --- dedent a multiline string by removing any initial indent. -- useful when working with [[..]] strings. -- @param s the string -- @return a string with initial indent zero. function text.dedent (s) assert_arg(1,s,'string') local sl = split(s,'\n') local i1,i2 = sl[1]:find('^%s*') sl = imap(string.sub,sl,i2+1) return concat(sl,'\n')..'\n' end --- format a paragraph into lines so that they fit into a line width. -- It will not break long words, so lines can be over the length -- to that extent. -- @param s the string -- @param width the margin width, default 70 -- @return a list of lines function text.wrap (s,width) assert_arg(1,s,'string') width = width or 70 s = s:gsub('\n',' ') local i,nxt = 1 local lines,line = {} while i < #s do nxt = i+width if s:find("[%w']",nxt) then -- inside a word nxt = s:find('%W',nxt+1) -- so find word boundary end line = s:sub(i,nxt) i = i + #line append(lines,strip(line)) end return make_list(lines) end --- format a paragraph so that it fits into a line width. -- @param s the string -- @param width the margin width, default 70 -- @return a string -- @see wrap function text.fill (s,width) return concat(text.wrap(s,width),'\n') .. '\n' end local Template = {} text.Template = Template Template.__index = Template setmetatable(Template, { __call = function(obj,tmpl) return Template.new(tmpl) end}) function Template.new(tmpl) assert_arg(1,tmpl,'string') local res = {} res.tmpl = tmpl setmetatable(res,Template) return res end local function _substitute(s,tbl,safe) local subst if is_callable(tbl) then subst = tbl else function subst(f) local s = tbl[f] if not s then if safe then return f else error("not present in table "..f) end else return s end end end local res = gsub(s,'%${([%w_]+)}',subst) return (gsub(res,'%$([%w_]+)',subst)) end --- substitute values into a template, throwing an error. -- This will throw an error if no name is found. -- @param tbl a table of name-value pairs. function Template:substitute(tbl) assert_arg(1,tbl,'table') return _substitute(self.tmpl,tbl,false) end --- substitute values into a template. -- This version just passes unknown names through. -- @param tbl a table of name-value pairs. function Template:safe_substitute(tbl) assert_arg(1,tbl,'table') return _substitute(self.tmpl,tbl,true) end --- substitute values into a template, preserving indentation. <br> -- If the value is a multiline string _or_ a template, it will insert -- the lines at the correct indentation. <br> -- Furthermore, if a template, then that template will be subsituted -- using the same table. -- @param tbl a table of name-value pairs. function Template:indent_substitute(tbl) assert_arg(1,tbl,'table') if not self.strings then self.strings = split(self.tmpl,'\n') end -- the idea is to substitute line by line, grabbing any spaces as -- well as the $var. If the value to be substituted contains newlines, -- then we split that into lines and adjust the indent before inserting. local function subst(line) return line:gsub('(%s*)%$([%w_]+)',function(sp,f) local subtmpl local s = tbl[f] if not s then error("not present in table "..f) end if getmetatable(s) == Template then subtmpl = s s = s.tmpl else s = tostring(s) end if s:find '\n' then s = _indent(s,sp) end if subtmpl then return _substitute(s,tbl) else return s end end) end local lines = imap(subst,self.strings) return concat(lines,'\n')..'\n' end ------- Python-style formatting operator ------ -- (see <a href="http://lua-users.org/wiki/StringInterpolation">the lua-users wiki</a>) -- function text.format_operator() local format = string.format -- a more forgiving version of string.format, which applies -- tostring() to any value with a %s format. local function formatx (fmt,...) local args = {...} local i = 1 for p in fmt:gmatch('%%.') do if p == '%s' and type(args[i]) ~= 'string' then args[i] = tostring(args[i]) end i = i + 1 end return format(fmt,unpack(args)) end local function basic_subst(s,t) return (s:gsub('%$([%w_]+)',t)) end -- Note this goes further than the original, and will allow these cases: -- 1. a single value -- 2. a list of values -- 3. a map of var=value pairs -- 4. a function, as in gsub -- For the second two cases, it uses $-variable substituion. getmetatable("").__mod = function(a, b) if b == nil then return a elseif type(b) == "table" and getmetatable(b) == nil then if #b == 0 then -- assume a map-like table return _substitute(a,b,true) else return formatx(a,unpack(b)) end elseif type(b) == 'function' then return basic_subst(a,b) else return formatx(a,b) end end end return text
agpl-3.0
alidess/aliali
bot/permissions.lua
1
1332
local sudos = { "plugins", "rank_admin", "bot", "lang_install", "set_lang", "tosupergroup", "gban_installer" } local admins = { "gban", "ungban", "setrules", "setphoto", "creategroup", "setname", "addbots", "setlink", "description", "export_gban" } local mods = { "whois", "rank_mod", "rank_guest", "kick", "add", "ban", "unban", "lockmember", "mute", "unmute", "admins", "members", "mods", "flood", "commands", "lang", "settings", "mod_commands", "no_flood_ban", "muteall", "rules", "pre_process" } local function get_tag(plugin_tag) for v,tag in pairs(sudos) do if tag == plugin_tag then return 3 end end for v,tag in pairs(admins) do if tag == plugin_tag then return 2 end end for v,tag in pairs(mods) do if tag == plugin_tag then return 1 end end return 0 end local function user_num(user_id, chat_id) if new_is_sudo(user_id) then return 3 elseif is_admin(user_id) then return 2 elseif is_mod(chat_id, user_id) then return 1 else return 0 end end function permissions(user_id, chat_id, plugin_tag) local user_is = get_tag(plugin_tag) local user_n = user_num(user_id, chat_id) if user_n >= user_is then return true else return false end end
gpl-2.0
EvPowerTeam/EV_OP
feeds/luci/applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
80
10048
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() -------------------- Init -------------------- -- -- Find link-local address -- LL_PREFIX = luci.ip.IPv6("fe80::/64") function find_ll() for _, r in ipairs(luci.sys.net.routes6()) do if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end -- -- Determine defaults -- local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000" local ipv4_pool = uci:get("siit", "ipv4", "pool") or "172.16.0.0/12" local ipv4_netsz = uci:get("siit", "ipv4", "netsize") or "24" -- -- Find IPv4 allocation pool -- local gv4_net = luci.ip.IPv4(ipv4_pool) -- -- Generate ULA -- local ula = luci.ip.IPv6("::/64") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll()) -------------------- View -------------------- f = SimpleForm("siitwizward", "SIIT-Wizzard", "This wizzard helps to setup SIIT (IPv4-over-IPv6) translation according to RFC2765.") f:field(DummyValue, "info_ula", "Mesh ULA address").value = ula:string() f:field(DummyValue, "ipv4_pool", "IPv4 allocation pool").value = "%s (%i hosts)" %{ gv4_net:string(), 2 ^ ( 32 - gv4_net:prefix() ) - 2 } f:field(DummyValue, "ipv4_size", "IPv4 LAN network prefix").value = "%i bit (%i hosts)" %{ ipv4_netsz, 2 ^ ( 32 - ipv4_netsz ) - 2 } mode = f:field(ListValue, "mode", "Operation mode") mode:value("client", "Client") mode:value("gateway", "Gateway") dev = f:field(ListValue, "device", "Wireless device") uci:foreach("wireless", "wifi-device", function(section) dev:value(section[".name"]) end) lanip = f:field(Value, "ipaddr", "LAN IPv4 subnet") function lanip.formvalue(self, section) local val = self.map:formvalue(self:cbid(section)) local net = luci.ip.IPv4("%s/%i" %{ val, ipv4_netsz }) if net then if gv4_net:contains(net) then if not net:minhost():equal(net:host()) then self.error = { [section] = true } f.errmessage = "IPv4 address is not the first host of " .. "subnet, expected " .. net:minhost():string() end else self.error = { [section] = true } f.errmessage = "IPv4 address is not within the allocation pool" end else self.error = { [section] = true } f.errmessage = "Invalid IPv4 address given" end return val end dns = f:field(Value, "dns", "DNS server for LAN clients") dns.value = "141.1.1.1" -------------------- Control -------------------- function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false end return true end function mode.write(self, section, value) -- -- Find LAN IPv4 range -- local lan_net = luci.ip.IPv4( ( lanip:formvalue(section) or "172.16.0.1" ) .. "/" .. ipv4_netsz ) if not lan_net then return end -- -- Find wifi interface, dns server and hostname -- local device = dev:formvalue(section) local dns_server = dns:formvalue(section) or "141.1.1.1" local hostname = "siit-" .. lan_net:host():string():gsub("%.","-") -- -- Configure wifi device -- local wifi_device = dev:formvalue(section) local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net" local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be" local wifi_channel = uci:get("siit", "wifi", "channel") or "1" -- nuke old device definition uci:delete_all("wireless", "wifi-iface", function(s) return s.device == wifi_device end ) uci:delete_all("network", "interface", function(s) return s['.name'] == wifi_device end ) -- create wifi device definition uci:tset("wireless", wifi_device, { disabled = 0, channel = wifi_channel, -- txantenna = 1, -- rxantenna = 1, -- diversity = 0 }) uci:section("wireless", "wifi-iface", nil, { encryption = "none", mode = "adhoc", txpower = 10, sw_merge = 1, network = wifi_device, device = wifi_device, ssid = wifi_essid, bssid = wifi_bssid, }) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then -- wan mtu uci:set("network", "wan", "mtu", 1240) -- lan settings uci:tset("network", "lan", { mtu = 1240, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string(), proto = "static" }) -- use full siit subnet siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- v4 <-> siit route uci:delete_all("network", "route", function(s) return s.interface == "siit0" end) uci:section("network", "route", nil, { interface = "siit0", target = gv4_net:network():string(), netmask = gv4_net:mask():string() }) -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else -- lan settings uci:tset("network", "lan", { mtu = 1240, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string() }) -- derive siit subnet from lan config siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_net:prefix()) ):add(lan_net[2]) -- ipv4 <-> siit route uci:delete_all("network", "route", function(s) return s.interface == "siit0" end) -- XXX: kind of a catch all, gv4_net would be better -- but does not cover non-local v4 space uci:section("network", "route", nil, { interface = "siit0", target = "0.0.0.0", netmask = "0.0.0.0" }) end -- setup the firewall uci:delete_all("firewall", "zone", function(s) return ( s['.name'] == "siit0" or s.name == "siit0" or s.network == "siit0" or s['.name'] == wifi_device or s.name == wifi_device or s.network == wifi_device ) end) uci:delete_all("firewall", "forwarding", function(s) return ( s.src == wifi_device and s.dest == "siit0" or s.dest == wifi_device and s.src == "siit0" or s.src == "lan" and s.dest == "siit0" or s.dest == "lan" and s.src == "siit0" ) end) uci:section("firewall", "zone", "siit0", { name = "siit0", network = "siit0", input = "ACCEPT", output = "ACCEPT", forward = "ACCEPT" }) uci:section("firewall", "zone", wifi_device, { name = wifi_device, network = wifi_device, input = "ACCEPT", output = "ACCEPT", forward = "ACCEPT" }) uci:section("firewall", "forwarding", nil, { src = wifi_device, dest = "siit0" }) uci:section("firewall", "forwarding", nil, { src = "siit0", dest = wifi_device }) uci:section("firewall", "forwarding", nil, { src = "lan", dest = "siit0" }) uci:section("firewall", "forwarding", nil, { src = "siit0", dest = "lan" }) -- firewall include uci:delete_all("firewall", "include", function(s) return s.path == "/etc/firewall.user" end) uci:section("firewall", "include", nil, { path = "/etc/firewall.user" }) -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "none" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = "siit0", target = siit_route:string() }) -- create wifi network interface uci:section("network", "interface", wifi_device, { proto = "static", mtu = 1400, ip6addr = ula:string() }) -- nuke old olsrd interfaces uci:delete_all("olsrd", "Interface", function(s) return s.interface == wifi_device end) -- configure olsrd interface uci:foreach("olsrd", "olsrd", function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end) uci:section("olsrd", "Interface", nil, { ignore = 0, interface = wifi_device, Ip6AddrType = "unique-local" }) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) return true end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) -- txtinfo v6 & olsrd nameservice uci:foreach("olsrd", "LoadPlugin", function(s) if s.library == "olsrd_txtinfo.so.0.1" then uci:set("olsrd", s['.name'], "accept", "::1") elseif s.library == "olsrd_nameservice.so.0.3" then uci:set("olsrd", s['.name'], "name", hostname) end end) -- lan dns uci:tset("dhcp", "lan", { dhcp_option = "6," .. dns_server, start = bit.band(lan_net:minhost():add(1)[2][2], 0xFF), limit = ( 2 ^ ( 32 - lan_net:prefix() ) ) - 3 }) -- hostname uci:foreach("system", "system", function(s) uci:set("system", s['.name'], "hostname", hostname) end) uci:save("wireless") uci:save("firewall") uci:save("network") uci:save("system") uci:save("olsrd") uci:save("dhcp") end return f
gpl-2.0
jacklicn/mysql-proxy
examples/tutorial-warnings.lua
6
2248
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] --- -- read_query() can rewrite packets -- -- You can use read_query() to replace the packet sent by the client and rewrite -- query as you like -- -- @param packet the mysql-packet sent by the client -- -- @return -- * nothing to pass on the packet as is, -- * proxy.PROXY_SEND_QUERY to send the queries from the proxy.queries queue -- * proxy.PROXY_SEND_RESULT to send your own result-set -- function read_query( packet ) if string.byte(packet) == proxy.COM_QUERY then proxy.queries:append(1, packet, { resultset_is_needed = true } ) return proxy.PROXY_SEND_QUERY end end --- -- dumps the warnings of queries -- -- read_query_result() is called when we receive a query result -- from the server -- -- for all queries which pass by we check if the warning-count is > 0 and -- inject a SHOW WARNINGS and dump it to the stdout -- -- @return -- * nothing or proxy.PROXY_SEND_RESULT to pass the result-set to the client -- * proxy.PROXY_IGNORE_RESULT to drop the result-set -- function read_query_result(inj) if (inj.id == 1) then local res = assert(inj.resultset) if res.warning_count > 0 then print("Query had warnings: " .. inj.query:sub(2)) proxy.queries:append(2, string.char(proxy.COM_QUERY) .. "SHOW WARNINGS", { resultset_is_needed = true } ) end elseif (inj.id == 2) then for row in inj.resultset.rows do print(string.format("warning: [%d] %s", row[2], row[1])) end return proxy.PROXY_IGNORE_RESULT end end
gpl-2.0
weera00/nodemcu-firmware
lua_modules/bh1750/bh1750_Example2.lua
89
1719
-- *************************************************************************** -- BH1750 Example Program for ESP8266 with nodeMCU -- BH1750 compatible tested 2015-1-30 -- -- Written by xiaohu -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** --Updata to Lelian --Ps 需要改动的地方LW_GATEWAY(乐联的设备标示),USERKEY(乐联userkey) --Ps You nees to rewrite the LW_GATEWAY(Lelian's Device ID),USERKEY(Lelian's userkey) tmr.alarm(0, 60000, 1, function() SDA_PIN = 6 -- sda pin, GPIO12 SCL_PIN = 5 -- scl pin, GPIO14 BH1750 = require("BH1750") BH1750.init(SDA_PIN, SCL_PIN) BH1750.read(OSS) l = BH1750.getlux() --定义数据变量格式 Define the veriables formate PostData = "[{\"Name\":\"T\",\"Value\":\"" ..(l / 100).."."..(l % 100).."\"}]" --创建一个TCP连接 Create a TCP Connection socket=net.createConnection(net.TCP, 0) --域名解析IP地址并赋值 DNS...it socket:dns("www.lewei50.com", function(conn, ip) ServerIP = ip print("Connection IP:" .. ServerIP) end) --开始连接服务器 Connect the sever socket:connect(80, ServerIP) socket:on("connection", function(sck) end) --HTTP请求头定义 HTTP Head socket:send("POST /api/V1/gateway/UpdateSensors/LW_GATEWAY HTTP/1.1\r\n" .. "Host: www.lewei50.com\r\n" .. "Content-Length: " .. string.len(PostData) .. "\r\n" .. "userkey: USERKEY\r\n\r\n" .. PostData .. "\r\n") --HTTP响应内容 Print the HTTP response socket:on("receive", function(sck, response) print(response) end) end)
mit
kikito/love-loader
love-loader.lua
1
7469
require "love.filesystem" require "love.image" require "love.audio" require "love.sound" local loader = { _VERSION = 'love-loader v2.0.3', _DESCRIPTION = 'Threaded resource loading for LÖVE', _URL = 'https://github.com/kikito/love-loader', _LICENSE = [[ MIT LICENSE Copyright (c) 2014 Enrique García Cota, Tanner Rogalsky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] } local resourceKinds = { image = { requestKey = "imagePath", resourceKey = "imageData", constructor = function (path) if love.image.isCompressed(path) then return love.image.newCompressedData(path) else return love.image.newImageData(path) end end, postProcess = function(data) return love.graphics.newImage(data) end }, staticSource = { requestKey = "staticPath", resourceKey = "staticSource", constructor = function(path) return love.audio.newSource(path, "static") end }, font = { requestKey = "fontPath", resourceKey = "fontData", constructor = function(path) -- we don't use love.filesystem.newFileData directly here because there -- are actually two arguments passed to this constructor which in turn -- invokes the wrong love.filesystem.newFileData overload return love.filesystem.newFileData(path) end, postProcess = function(data, resource) local path, size = unpack(resource.requestParams) return love.graphics.newFont(data, size) end }, BMFont = { requestKey = "fontBMPath", resourceKey = "fontBMData", constructor = function(path) return love.filesystem.newFileData(path) end, postProcess = function(data, resource) local imagePath, glyphsPath = unpack(resource.requestParams) local glyphs = love.filesystem.newFileData(glyphsPath) return love.graphics.newFont(glyphs,data) end }, streamSource = { requestKey = "streamPath", resourceKey = "streamSource", constructor = function(path) return love.audio.newSource(path, "stream") end }, soundData = { requestKey = "soundDataPathOrDecoder", resourceKey = "soundData", constructor = love.sound.newSoundData }, imageData = { requestKey = "imageDataPath", resourceKey = "rawImageData", constructor = love.image.newImageData }, compressedData = { requestKey = "compressedDataPath", resourceKey = "rawCompressedData", constructor = love.image.newCompressedData } } local CHANNEL_PREFIX = "loader_" local loaded = ... if loaded == true then local requestParams, resource local done = false local doneChannel = love.thread.getChannel(CHANNEL_PREFIX .. "is_done") while not done do for _,kind in pairs(resourceKinds) do local loader = love.thread.getChannel(CHANNEL_PREFIX .. kind.requestKey) requestParams = loader:pop() if requestParams then resource = kind.constructor(unpack(requestParams)) local producer = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey) producer:push(resource) end end done = doneChannel:pop() end else local pending = {} local callbacks = {} local resourceBeingLoaded local pathToThisFile = (...):gsub("%.", "/") .. ".lua" local function shift(t) return table.remove(t,1) end local function newResource(kind, holder, key, ...) pending[#pending + 1] = { kind = kind, holder = holder, key = key, requestParams = {...} } end local function getResourceFromThreadIfAvailable() local data, resource for name,kind in pairs(resourceKinds) do local channel = love.thread.getChannel(CHANNEL_PREFIX .. kind.resourceKey) data = channel:pop() if data then resource = kind.postProcess and kind.postProcess(data, resourceBeingLoaded) or data resourceBeingLoaded.holder[resourceBeingLoaded.key] = resource loader.loadedCount = loader.loadedCount + 1 callbacks.oneLoaded(resourceBeingLoaded.kind, resourceBeingLoaded.holder, resourceBeingLoaded.key) resourceBeingLoaded = nil end end end local function requestNewResourceToThread() resourceBeingLoaded = shift(pending) local requestKey = resourceKinds[resourceBeingLoaded.kind].requestKey local channel = love.thread.getChannel(CHANNEL_PREFIX .. requestKey) channel:push(resourceBeingLoaded.requestParams) end local function endThreadIfAllLoaded() if not resourceBeingLoaded and #pending == 0 then love.thread.getChannel(CHANNEL_PREFIX .. "is_done"):push(true) callbacks.allLoaded() end end ----------------------------------------------------- function loader.newImage(holder, key, path) newResource('image', holder, key, path) end function loader.newFont(holder, key, path, size) newResource('font', holder, key, path, size) end function loader.newBMFont(holder, key, path, glyphsPath) newResource('font', holder, key, path, glyphsPath) end function loader.newSource(holder, key, path, sourceType) local kind = (sourceType == 'static' and 'staticSource' or 'streamSource') newResource(kind, holder, key, path) end function loader.newSoundData(holder, key, pathOrDecoder) newResource('soundData', holder, key, pathOrDecoder) end function loader.newImageData(holder, key, path) newResource('imageData', holder, key, path) end function loader.newCompressedData(holder, key, path) newResource('compressedData', holder, key, path) end function loader.start(allLoadedCallback, oneLoadedCallback) callbacks.allLoaded = allLoadedCallback or function() end callbacks.oneLoaded = oneLoadedCallback or function() end local thread = love.thread.newThread(pathToThisFile) loader.loadedCount = 0 loader.resourceCount = #pending thread:start(true) loader.thread = thread end function loader.update() if loader.thread then if loader.thread:isRunning() then if resourceBeingLoaded then getResourceFromThreadIfAvailable() elseif #pending > 0 then requestNewResourceToThread() else endThreadIfAllLoaded() loader.thread = nil end else local errorMessage = loader.thread:getError() assert(not errorMessage, errorMessage) end end end return loader end
mit
caioso/DynASM
dasm_arm.lua
60
34483
------------------------------------------------------------------------------ -- DynASM ARM module. -- -- Copyright (C) 2005-2014 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM module", version = "1.3.0", vernum = 10300, release = "2011-05-05", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex = bit.ror, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", "IMM12", "IMM16", "IMML8", "IMML12", "IMMV8", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { sp = "r13", lr = "r14", pc = "r15", } -- Int. register name -> ext. name. local map_reg_rev = { r13 = "sp", r14 = "lr", r15 = "pc", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, ror = 3, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ -- Template strings for ARM instructions. local map_op = { -- Basic data processing instructions. and_3 = "e0000000DNPs", eor_3 = "e0200000DNPs", sub_3 = "e0400000DNPs", rsb_3 = "e0600000DNPs", add_3 = "e0800000DNPs", adc_3 = "e0a00000DNPs", sbc_3 = "e0c00000DNPs", rsc_3 = "e0e00000DNPs", tst_2 = "e1100000NP", teq_2 = "e1300000NP", cmp_2 = "e1500000NP", cmn_2 = "e1700000NP", orr_3 = "e1800000DNPs", mov_2 = "e1a00000DPs", bic_3 = "e1c00000DNPs", mvn_2 = "e1e00000DPs", and_4 = "e0000000DNMps", eor_4 = "e0200000DNMps", sub_4 = "e0400000DNMps", rsb_4 = "e0600000DNMps", add_4 = "e0800000DNMps", adc_4 = "e0a00000DNMps", sbc_4 = "e0c00000DNMps", rsc_4 = "e0e00000DNMps", tst_3 = "e1100000NMp", teq_3 = "e1300000NMp", cmp_3 = "e1500000NMp", cmn_3 = "e1700000NMp", orr_4 = "e1800000DNMps", mov_3 = "e1a00000DMps", bic_4 = "e1c00000DNMps", mvn_3 = "e1e00000DMps", lsl_3 = "e1a00000DMws", lsr_3 = "e1a00020DMws", asr_3 = "e1a00040DMws", ror_3 = "e1a00060DMws", rrx_2 = "e1a00060DMs", -- Multiply and multiply-accumulate. mul_3 = "e0000090NMSs", mla_4 = "e0200090NMSDs", umaal_4 = "e0400090DNMSs", -- v6 mls_4 = "e0600090DNMSs", -- v6T2 umull_4 = "e0800090DNMSs", umlal_4 = "e0a00090DNMSs", smull_4 = "e0c00090DNMSs", smlal_4 = "e0e00090DNMSs", -- Halfword multiply and multiply-accumulate. smlabb_4 = "e1000080NMSD", -- v5TE smlatb_4 = "e10000a0NMSD", -- v5TE smlabt_4 = "e10000c0NMSD", -- v5TE smlatt_4 = "e10000e0NMSD", -- v5TE smlawb_4 = "e1200080NMSD", -- v5TE smulwb_3 = "e12000a0NMS", -- v5TE smlawt_4 = "e12000c0NMSD", -- v5TE smulwt_3 = "e12000e0NMS", -- v5TE smlalbb_4 = "e1400080NMSD", -- v5TE smlaltb_4 = "e14000a0NMSD", -- v5TE smlalbt_4 = "e14000c0NMSD", -- v5TE smlaltt_4 = "e14000e0NMSD", -- v5TE smulbb_3 = "e1600080NMS", -- v5TE smultb_3 = "e16000a0NMS", -- v5TE smulbt_3 = "e16000c0NMS", -- v5TE smultt_3 = "e16000e0NMS", -- v5TE -- Miscellaneous data processing instructions. clz_2 = "e16f0f10DM", -- v5T rev_2 = "e6bf0f30DM", -- v6 rev16_2 = "e6bf0fb0DM", -- v6 revsh_2 = "e6ff0fb0DM", -- v6 sel_3 = "e6800fb0DNM", -- v6 usad8_3 = "e780f010NMS", -- v6 usada8_4 = "e7800010NMSD", -- v6 rbit_2 = "e6ff0f30DM", -- v6T2 movw_2 = "e3000000DW", -- v6T2 movt_2 = "e3400000DW", -- v6T2 -- Note: the X encodes width-1, not width. sbfx_4 = "e7a00050DMvX", -- v6T2 ubfx_4 = "e7e00050DMvX", -- v6T2 -- Note: the X encodes the msb field, not the width. bfc_3 = "e7c0001fDvX", -- v6T2 bfi_4 = "e7c00010DMvX", -- v6T2 -- Packing and unpacking instructions. pkhbt_3 = "e6800010DNM", pkhbt_4 = "e6800010DNMv", -- v6 pkhtb_3 = "e6800050DNM", pkhtb_4 = "e6800050DNMv", -- v6 sxtab_3 = "e6a00070DNM", sxtab_4 = "e6a00070DNMv", -- v6 sxtab16_3 = "e6800070DNM", sxtab16_4 = "e6800070DNMv", -- v6 sxtah_3 = "e6b00070DNM", sxtah_4 = "e6b00070DNMv", -- v6 sxtb_2 = "e6af0070DM", sxtb_3 = "e6af0070DMv", -- v6 sxtb16_2 = "e68f0070DM", sxtb16_3 = "e68f0070DMv", -- v6 sxth_2 = "e6bf0070DM", sxth_3 = "e6bf0070DMv", -- v6 uxtab_3 = "e6e00070DNM", uxtab_4 = "e6e00070DNMv", -- v6 uxtab16_3 = "e6c00070DNM", uxtab16_4 = "e6c00070DNMv", -- v6 uxtah_3 = "e6f00070DNM", uxtah_4 = "e6f00070DNMv", -- v6 uxtb_2 = "e6ef0070DM", uxtb_3 = "e6ef0070DMv", -- v6 uxtb16_2 = "e6cf0070DM", uxtb16_3 = "e6cf0070DMv", -- v6 uxth_2 = "e6ff0070DM", uxth_3 = "e6ff0070DMv", -- v6 -- Saturating instructions. qadd_3 = "e1000050DMN", -- v5TE qsub_3 = "e1200050DMN", -- v5TE qdadd_3 = "e1400050DMN", -- v5TE qdsub_3 = "e1600050DMN", -- v5TE -- Note: the X for ssat* encodes sat_imm-1, not sat_imm. ssat_3 = "e6a00010DXM", ssat_4 = "e6a00010DXMp", -- v6 usat_3 = "e6e00010DXM", usat_4 = "e6e00010DXMp", -- v6 ssat16_3 = "e6a00f30DXM", -- v6 usat16_3 = "e6e00f30DXM", -- v6 -- Parallel addition and subtraction. sadd16_3 = "e6100f10DNM", -- v6 sasx_3 = "e6100f30DNM", -- v6 ssax_3 = "e6100f50DNM", -- v6 ssub16_3 = "e6100f70DNM", -- v6 sadd8_3 = "e6100f90DNM", -- v6 ssub8_3 = "e6100ff0DNM", -- v6 qadd16_3 = "e6200f10DNM", -- v6 qasx_3 = "e6200f30DNM", -- v6 qsax_3 = "e6200f50DNM", -- v6 qsub16_3 = "e6200f70DNM", -- v6 qadd8_3 = "e6200f90DNM", -- v6 qsub8_3 = "e6200ff0DNM", -- v6 shadd16_3 = "e6300f10DNM", -- v6 shasx_3 = "e6300f30DNM", -- v6 shsax_3 = "e6300f50DNM", -- v6 shsub16_3 = "e6300f70DNM", -- v6 shadd8_3 = "e6300f90DNM", -- v6 shsub8_3 = "e6300ff0DNM", -- v6 uadd16_3 = "e6500f10DNM", -- v6 uasx_3 = "e6500f30DNM", -- v6 usax_3 = "e6500f50DNM", -- v6 usub16_3 = "e6500f70DNM", -- v6 uadd8_3 = "e6500f90DNM", -- v6 usub8_3 = "e6500ff0DNM", -- v6 uqadd16_3 = "e6600f10DNM", -- v6 uqasx_3 = "e6600f30DNM", -- v6 uqsax_3 = "e6600f50DNM", -- v6 uqsub16_3 = "e6600f70DNM", -- v6 uqadd8_3 = "e6600f90DNM", -- v6 uqsub8_3 = "e6600ff0DNM", -- v6 uhadd16_3 = "e6700f10DNM", -- v6 uhasx_3 = "e6700f30DNM", -- v6 uhsax_3 = "e6700f50DNM", -- v6 uhsub16_3 = "e6700f70DNM", -- v6 uhadd8_3 = "e6700f90DNM", -- v6 uhsub8_3 = "e6700ff0DNM", -- v6 -- Load/store instructions. str_2 = "e4000000DL", str_3 = "e4000000DL", str_4 = "e4000000DL", strb_2 = "e4400000DL", strb_3 = "e4400000DL", strb_4 = "e4400000DL", ldr_2 = "e4100000DL", ldr_3 = "e4100000DL", ldr_4 = "e4100000DL", ldrb_2 = "e4500000DL", ldrb_3 = "e4500000DL", ldrb_4 = "e4500000DL", strh_2 = "e00000b0DL", strh_3 = "e00000b0DL", ldrh_2 = "e01000b0DL", ldrh_3 = "e01000b0DL", ldrd_2 = "e00000d0DL", ldrd_3 = "e00000d0DL", -- v5TE ldrsb_2 = "e01000d0DL", ldrsb_3 = "e01000d0DL", strd_2 = "e00000f0DL", strd_3 = "e00000f0DL", -- v5TE ldrsh_2 = "e01000f0DL", ldrsh_3 = "e01000f0DL", ldm_2 = "e8900000oR", ldmia_2 = "e8900000oR", ldmfd_2 = "e8900000oR", ldmda_2 = "e8100000oR", ldmfa_2 = "e8100000oR", ldmdb_2 = "e9100000oR", ldmea_2 = "e9100000oR", ldmib_2 = "e9900000oR", ldmed_2 = "e9900000oR", stm_2 = "e8800000oR", stmia_2 = "e8800000oR", stmfd_2 = "e8800000oR", stmda_2 = "e8000000oR", stmfa_2 = "e8000000oR", stmdb_2 = "e9000000oR", stmea_2 = "e9000000oR", stmib_2 = "e9800000oR", stmed_2 = "e9800000oR", pop_1 = "e8bd0000R", push_1 = "e92d0000R", -- Branch instructions. b_1 = "ea000000B", bl_1 = "eb000000B", blx_1 = "e12fff30C", bx_1 = "e12fff10M", -- Miscellaneous instructions. nop_0 = "e1a00000", mrs_1 = "e10f0000D", bkpt_1 = "e1200070K", -- v5T svc_1 = "ef000000T", swi_1 = "ef000000T", ud_0 = "e7f001f0", -- VFP instructions. ["vadd.f32_3"] = "ee300a00dnm", ["vadd.f64_3"] = "ee300b00Gdnm", ["vsub.f32_3"] = "ee300a40dnm", ["vsub.f64_3"] = "ee300b40Gdnm", ["vmul.f32_3"] = "ee200a00dnm", ["vmul.f64_3"] = "ee200b00Gdnm", ["vnmul.f32_3"] = "ee200a40dnm", ["vnmul.f64_3"] = "ee200b40Gdnm", ["vmla.f32_3"] = "ee000a00dnm", ["vmla.f64_3"] = "ee000b00Gdnm", ["vmls.f32_3"] = "ee000a40dnm", ["vmls.f64_3"] = "ee000b40Gdnm", ["vnmla.f32_3"] = "ee100a40dnm", ["vnmla.f64_3"] = "ee100b40Gdnm", ["vnmls.f32_3"] = "ee100a00dnm", ["vnmls.f64_3"] = "ee100b00Gdnm", ["vdiv.f32_3"] = "ee800a00dnm", ["vdiv.f64_3"] = "ee800b00Gdnm", ["vabs.f32_2"] = "eeb00ac0dm", ["vabs.f64_2"] = "eeb00bc0Gdm", ["vneg.f32_2"] = "eeb10a40dm", ["vneg.f64_2"] = "eeb10b40Gdm", ["vsqrt.f32_2"] = "eeb10ac0dm", ["vsqrt.f64_2"] = "eeb10bc0Gdm", ["vcmp.f32_2"] = "eeb40a40dm", ["vcmp.f64_2"] = "eeb40b40Gdm", ["vcmpe.f32_2"] = "eeb40ac0dm", ["vcmpe.f64_2"] = "eeb40bc0Gdm", ["vcmpz.f32_1"] = "eeb50a40d", ["vcmpz.f64_1"] = "eeb50b40Gd", ["vcmpze.f32_1"] = "eeb50ac0d", ["vcmpze.f64_1"] = "eeb50bc0Gd", vldr_2 = "ed100a00dl|ed100b00Gdl", vstr_2 = "ed000a00dl|ed000b00Gdl", vldm_2 = "ec900a00or", vldmia_2 = "ec900a00or", vldmdb_2 = "ed100a00or", vpop_1 = "ecbd0a00r", vstm_2 = "ec800a00or", vstmia_2 = "ec800a00or", vstmdb_2 = "ed000a00or", vpush_1 = "ed2d0a00r", ["vmov.f32_2"] = "eeb00a40dm|eeb00a00dY", -- #imm is VFPv3 only ["vmov.f64_2"] = "eeb00b40Gdm|eeb00b00GdY", -- #imm is VFPv3 only vmov_2 = "ee100a10Dn|ee000a10nD", vmov_3 = "ec500a10DNm|ec400a10mDN|ec500b10GDNm|ec400b10GmDN", vmrs_0 = "eef1fa10", vmrs_1 = "eef10a10D", vmsr_1 = "eee10a10D", ["vcvt.s32.f32_2"] = "eebd0ac0dm", ["vcvt.s32.f64_2"] = "eebd0bc0dGm", ["vcvt.u32.f32_2"] = "eebc0ac0dm", ["vcvt.u32.f64_2"] = "eebc0bc0dGm", ["vcvtr.s32.f32_2"] = "eebd0a40dm", ["vcvtr.s32.f64_2"] = "eebd0b40dGm", ["vcvtr.u32.f32_2"] = "eebc0a40dm", ["vcvtr.u32.f64_2"] = "eebc0b40dGm", ["vcvt.f32.s32_2"] = "eeb80ac0dm", ["vcvt.f64.s32_2"] = "eeb80bc0GdFm", ["vcvt.f32.u32_2"] = "eeb80a40dm", ["vcvt.f64.u32_2"] = "eeb80b40GdFm", ["vcvt.f32.f64_2"] = "eeb70bc0dGm", ["vcvt.f64.f32_2"] = "eeb70ac0GdFm", -- VFPv4 only: ["vfma.f32_3"] = "eea00a00dnm", ["vfma.f64_3"] = "eea00b00Gdnm", ["vfms.f32_3"] = "eea00a40dnm", ["vfms.f64_3"] = "eea00b40Gdnm", ["vfnma.f32_3"] = "ee900a40dnm", ["vfnma.f64_3"] = "ee900b40Gdnm", ["vfnms.f32_3"] = "ee900a00dnm", ["vfnms.f64_3"] = "ee900b00Gdnm", -- NYI: Advanced SIMD instructions. -- NYI: I have no need for these instructions right now: -- swp, swpb, strex, ldrex, strexd, ldrexd, strexb, ldrexb, strexh, ldrexh -- msr, nopv6, yield, wfe, wfi, sev, dbg, bxj, smc, srs, rfe -- cps, setend, pli, pld, pldw, clrex, dsb, dmb, isb -- stc, ldc, mcr, mcr2, mrc, mrc2, mcrr, mcrr2, mrrc, mrrc2, cdp, cdp2 } -- Add mnemonics for "s" variants. do local t = {} for k,v in pairs(map_op) do if sub(v, -1) == "s" then local v2 = sub(v, 1, 2)..char(byte(v, 3)+1)..sub(v, 4, -2) t[sub(k, 1, -3).."s"..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r1?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r(1?[0-9])$") if r then r = tonumber(r) if r <= 15 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_gpr_pm(expr) local pm, expr2 = match(expr, "^([+-]?)(.*)$") return parse_gpr(expr2), (pm == "-") end local function parse_vr(expr, tp) local t, r = match(expr, "^([sd])([0-9]+)$") if t == tp then r = tonumber(r) if r <= 31 then if t == "s" then return shr(r, 1), band(r, 1) end return band(r, 15), shr(r, 4) end end werror("bad register name `"..expr.."'") end local function parse_reglist(reglist) reglist = match(reglist, "^{%s*([^}]*)}$") if not reglist then werror("register list expected") end local rr = 0 for p in gmatch(reglist..",", "%s*([^,]*),") do local rbit = shl(1, parse_gpr(gsub(p, "%s+$", ""))) if band(rr, rbit) ~= 0 then werror("duplicate register `"..p.."'") end rr = rr + rbit end return rr end local function parse_vrlist(reglist) local ta, ra, tb, rb = match(reglist, "^{%s*([sd])([0-9]+)%s*%-%s*([sd])([0-9]+)%s*}$") ra, rb = tonumber(ra), tonumber(rb) if ta and ta == tb and ra and rb and ra <= 31 and rb <= 31 and ra <= rb then local nr = rb+1 - ra if ta == "s" then return shl(shr(ra,1),12)+shl(band(ra,1),22) + nr else return shl(band(ra,15),12)+shl(shr(ra,4),22) + nr*2 + 0x100 end end werror("register list expected") end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) local n = tonumber(imm) if n then local m = band(n) for i=0,-15,-1 do if shr(m, 8) == 0 then return m + shl(band(i, 15), 8) end m = ror(m, 2) end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm16(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then if shr(n, 16) == 0 then return band(n, 0x0fff) + shl(band(n, 0xf000), 4) end werror("out of range immediate `"..imm.."'") else waction("IMM16", 32*16, imm) return 0 end end local function parse_imm_load(imm, ext) local n = tonumber(imm) if n then if ext then if n >= -255 and n <= 255 then local up = 0x00800000 if n < 0 then n = -n; up = 0 end return shl(band(n, 0xf0), 4) + band(n, 0x0f) + up end else if n >= -4095 and n <= 4095 then if n >= 0 then return n+0x00800000 end return -n end end werror("out of range immediate `"..imm.."'") else waction(ext and "IMML8" or "IMML12", 32768 + shl(ext and 8 or 12, 5), imm) return 0 end end local function parse_shift(shift, gprok) if shift == "rrx" then return 3 * 32 else local s, s2 = match(shift, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end if sub(s2, 1, 1) == "#" then return parse_imm(s2, 5, 7, 0, false) + shl(s, 5) else if not gprok then werror("expected immediate shift operand") end return shl(parse_gpr(s2), 8) + shl(s, 5) + 16 end end end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end local function parse_load(params, nparams, n, op) local oplo = band(op, 255) local ext, ldrd = (oplo ~= 0), (oplo == 208) local d if (ldrd or oplo == 240) then d = band(shr(op, 12), 15) if band(d, 1) ~= 0 then werror("odd destination register") end end local pn = params[n] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") local p2 = params[n+1] if not p1 then if not p2 then if match(pn, "^[<>=%-]") or match(pn, "^extern%s+") then local mode, n, s = parse_label(pn, false) waction("REL_"..mode, n + (ext and 0x1800 or 0x0800), s, 1) return op + 15 * 65536 + 0x01000000 + (ext and 0x00400000 or 0) end local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12), format(tp.ctypefmt, tailr)) return op + shl(d, 16) + 0x01000000 + (ext and 0x00400000 or 0) end end end werror("expected address operand") end if wb == "!" then op = op + 0x00200000 end if p2 then if wb == "!" then werror("bad use of '!'") end local p3 = params[n+2] op = op + shl(parse_gpr(p1), 16) local imm = match(p2, "^#(.*)$") if imm then local m = parse_imm_load(imm, ext) if p3 then werror("too many parameters") end op = op + m + (ext and 0x00400000 or 0) else local m, neg = parse_gpr_pm(p2) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 then op = op + parse_shift(p3) end end else local p1a, p2 = match(p1, "^([^,%s]*)%s*(.*)$") op = op + shl(parse_gpr(p1a), 16) + 0x01000000 if p2 ~= "" then local imm = match(p2, "^,%s*#(.*)$") if imm then local m = parse_imm_load(imm, ext) op = op + m + (ext and 0x00400000 or 0) else local p2a, p3 = match(p2, "^,%s*([^,%s]*)%s*,?%s*(.*)$") local m, neg = parse_gpr_pm(p2a) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 ~= "" then if ext then werror("too many parameters") end op = op + parse_shift(p3) end end else if wb == "!" then werror("bad use of '!'") end op = op + (ext and 0x00c00000 or 0x00800000) end end return op end local function parse_vload(q) local reg, imm = match(q, "^%[%s*([^,%s]*)%s*(.*)%]$") if reg then local d = shl(parse_gpr(reg), 16) if imm == "" then return d end imm = match(imm, "^,%s*#(.*)$") if imm then local n = tonumber(imm) if n then if n >= -1020 and n <= 1020 and n%4 == 0 then return d + (n >= 0 and n/4+0x00800000 or -n/4) end werror("out of range immediate `"..imm.."'") else waction("IMMV8", 32768 + 32*8, imm) return d end end else if match(q, "^[<>=%-]") or match(q, "^extern%s+") then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n + 0x2800, s, 1) return 15 * 65536 end local reg, tailr = match(q, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction("IMMV8", 32768 + 32*8, format(tp.ctypefmt, tailr)) return shl(d, 16) end end end werror("expected address operand") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(sub(template, 1, 8), 16) local n = 1 local vr = "s" -- Process each character. for p in gmatch(sub(template, 9), ".") do local q = params[n] if p == "D" then op = op + shl(parse_gpr(q), 12); n = n + 1 elseif p == "N" then op = op + shl(parse_gpr(q), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(q), 8); n = n + 1 elseif p == "M" then op = op + parse_gpr(q); n = n + 1 elseif p == "d" then local r,h = parse_vr(q, vr); op = op+shl(r,12)+shl(h,22); n = n + 1 elseif p == "n" then local r,h = parse_vr(q, vr); op = op+shl(r,16)+shl(h,7); n = n + 1 elseif p == "m" then local r,h = parse_vr(q, vr); op = op+r+shl(h,5); n = n + 1 elseif p == "P" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm12(imm) + 0x02000000 else op = op + parse_gpr(q) end n = n + 1 elseif p == "p" then op = op + parse_shift(q, true); n = n + 1 elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "l" then op = op + parse_vload(q) elseif p == "B" then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) elseif p == "C" then -- blx gpr vs. blx label. if match(q, "^([%w_]+):(r1?[0-9])$") or match(q, "^r(1?[0-9])$") then op = op + parse_gpr(q) else if op < 0xe0000000 then werror("unconditional instruction") end local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) op = 0xfa000000 end elseif p == "F" then vr = "s" elseif p == "G" then vr = "d" elseif p == "o" then local r, wb = match(q, "^([^!]*)(!?)$") op = op + shl(parse_gpr(r), 16) + (wb == "!" and 0x00200000 or 0) n = n + 1 elseif p == "R" then op = op + parse_reglist(q); n = n + 1 elseif p == "r" then op = op + parse_vrlist(q); n = n + 1 elseif p == "W" then op = op + parse_imm16(q); n = n + 1 elseif p == "v" then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 elseif p == "w" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 else op = op + shl(parse_gpr(q), 8) + 16 end elseif p == "X" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "Y" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 8) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xf0), 12) + band(imm, 0x0f) elseif p == "K" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 16) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xfff0), 4) + band(imm, 0x000f) elseif p == "T" then op = op + parse_imm(q, 24, 0, 0, false); n = n + 1 elseif p == "s" then -- Ignored. else assert(false) end end wputpos(pos, op) end map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions. if secpos+3 > maxsecpos then wflush() end local pos = wpos() local apos, spos = #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil end error(err, 0) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = function(t, k) local v = map_coreop[k] if v then return v end local k1, cc, k2 = match(k, "^(.-)(..)([._].*)$") local cv = map_cond[cc] if cv then local v = rawget(t, k1..k2) if type(v) == "string" then local scv = format("%x", cv) return gsub(scv..sub(v, 2), "|e", "|"..scv) end end end }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
Choumiko/Factorio-Stdlib
spec/event/gui_spec.lua
1
11188
require 'stdlib/event/gui' require 'spec/defines' local test_function = {f=function(x) _G.someVariable = x end, g=function(x) _G.someVariable = x end} local function_a = function(arg) test_function.f(arg.tick) end local function_b = function(arg) test_function.f(arg.player_index) end local function_c = function() return true end local function_d = function(arg) test_function.g(arg.tick) end local function_e = function(arg) test_function.g(arg.player_index) end local function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end describe('Gui', function() before_each(function() _G.game = {tick = 1} _G.script = {on_event = function(_, _) return end} end) after_each(function() Event._registry = {} Event.Gui._registry = {} Event.Gui._dispatch = {} end) --[[ ----.register tests --]] it('.register should fail if a nil/false event id is passed', function() assert.has.errors(function() Event.Gui.register( false, "test_pattern", function_a ) end) assert.has.errors(function() Event.Gui.register( nil, "test_pattern", function_a ) end) end) it('.register should fail if a non-string gui_element_pattern is passed', function() assert.has.errors(function() Event.Gui.register( 1, false, function_a ) end) assert.has.errors(function() Event.Gui.register( 1, nil, function_a ) end) assert.has.errors(function() Event.Gui.register( 1, 5, function_a ) end) assert.has.errors(function() Event.Gui.register( 1, {4}, function_a ) end) end) it('.register should register a handler for a given pattern', function() Event.Gui.register( 1, "test_pattern", function_a ) assert.is_not_nil( Event.Gui._registry[1] ) assert.equals( function_a, Event.Gui._registry[1]["test_pattern"] ) end) it('.register should replace a handler when given a new one for a given pattern', function() Event.Gui.register( 1, "test_pattern", function_a ) Event.Gui.register( 1, "test_pattern", function_b ) assert.is_not_nil( Event.Gui._registry[1] ) assert.equals( function_b, Event.Gui._registry[1]["test_pattern"] ) end) it('.register should remove handler if nil is passed as a handler', function() Event.Gui.register( 1, "test_pattern", function_a ) Event.Gui.register( 1, "test_pattern", nil) assert.is_nil( Event.Gui._registry[1] ) end) it('.register should keep all existing patterns when a new one is registered', function() Event.Gui.register( 1, "test_pattern", function_a ) Event.Gui.register( 1, "test_pattern2", function_b ) Event.Gui.register( 1, "test_pattern3", function_c) assert.is_not_nil( Event.Gui._registry[1] ) assert.equals( function_c, Event.Gui._registry[1]["test_pattern3"] ) assert.equals( function_b, Event.Gui._registry[1]["test_pattern2"] ) assert.equals( function_a, Event.Gui._registry[1]["test_pattern"] ) end) it('.register should keep all existing patterns when a one is removed', function() Event.Gui.register( 1, "test_pattern", function_a ) Event.Gui.register( 1, "test_pattern2", function_b ) Event.Gui.register( 1, "test_pattern3", function_c ) Event.Gui.register( 1, "test_pattern2", nil) assert.is_not_nil( Event.Gui._registry[1] ) assert.equals( function_c, Event.Gui._registry[1]["test_pattern3"] ) assert.is_nil( Event.Gui._registry[1]["test_pattern2"] ) assert.equals( function_a, Event.Gui._registry[1]["test_pattern"] ) end) it('.register should pass the event Event.register for final registration', function() local s = spy.on(Event, "register") Event.Gui.register( 1, "test_pattern", function_a ) assert.spy(s).was_called() assert.spy(s).was_called_with(1, Event.Gui.dispatch) end) it('.register should return itself', function() assert.equals( Event.Gui, Event.Gui.register( 1, "test_pattern", function_a ) ) assert.equals( Event.Gui, Event.Gui.register( 1, "test_pattern2", function_b ).register( 1, "test_pattern3", function_c ) ) assert.equals( function_a, Event.Gui._registry[1]["test_pattern"] ) assert.equals( function_b, Event.Gui._registry[1]["test_pattern2"] ) assert.equals( function_c, Event.Gui._registry[1]["test_pattern3"] ) end) --[[ ----.dispath methods of use --]] it('.dispath should fail if a nil/false event id is passed', function() assert.has.errors(function() Event.Gui.dispath( false ) end) assert.has.errors(function() Event.Gui.dispath( nil ) end) end) it('.dispatch should call all registered handlers for matching patterns', function() Event.Gui.register( 1, "test_pattern", function_a ) Event.Gui.register( 1, "test_pattern1", function_b ) Event.Gui.register( 1, "_pa", function_d ) Event.Gui.register( 1, "12", function_e ) local event = {name = 1, tick = 9001, element={name="test_pattern12",valid=true}, player_index = 1} local s = spy.on(test_function, "f") local s2 = spy.on(test_function, "g") Event.Gui.dispatch(event) assert.spy(s).was_called_with(9001) assert.spy(s).was_called_with(1) assert.spy(s2).was_called_with(9001) assert.spy(s2).was_called_with(1) end) it('.dispatch should called once per event', function() Event.Gui.register( 1, "test_pattern", function_a ) Event.Gui.register( 1, "test_pattern1", function_a ) Event.Gui.register( 1, "test_pattern12", function_a ) Event.Gui.register( 1, "test_pattern123", function_a ) Event.Gui.register( 1, "test_pattern1234", function_a ) Event.Gui.register( 1, "test_pattern4", function_d ) Event.Gui.register( 1, "test_pattern5", function_d ) Event.Gui.register( 1, "test_pattern6", function_d ) Event.Gui.register( 1, "test_pattern7", function_d ) local event = {name = 1, tick = 9001, element={name="test_pattern1234",valid=true}, player_index = 1} --local s = spy.on(Event.Gui, "dispatch") local s2 = spy.on(test_function, "f") Event.dispatch(event) -- assert.spy(s).was_called(1) --This is failing to spy on Event.Gui.dispatch? assert.spy(s2).was_called(5) --Backup plan. multiple Event.Gui.dispatch calls results in 135 calls here. end) it('.dispatch should not call handlers for non-matching patterns', function() Event.Gui.register( 1, "test-pattern", function_a ) Event.Gui.register( 1, "%asd$", function_a ) Event.Gui.register( 1, "\"", function_a ) Event.Gui.register( 1, "123", function_a ) local event = {name = 1, tick = 9001, element={name="test_pattern12",valid=true}, player_index = 1} local s = spy.on(test_function, "f") Event.Gui.dispatch(event) assert.spy(s).was_not_called() end) it('.dispatch should print an error to connected players if a handler throws an error', function() _G.game.players = { { name = 'test_player', valid = true, connected = true, print = function() end } } require('stdlib/table') _G.game.connected_players = table.filter(_G.game.players, function(p) return p.connected end) local s = spy.on(_G.game.players[1], "print") Event.Gui.register( 1, "test_pattern", function() error("should error") end) assert.is_not_nil( Event.Gui._registry[1]["test_pattern"] ) Event.Gui.dispatch({name = 1, tick = 9001, element={name="test_pattern",valid=true}, player_index = 1}) assert.spy(s).was_called() end) --[[ ----.remove methods of use --]] it('.remove should fail if a nil/false event id is passed', function() assert.has.errors(function() Event.Gui.remove( false, "test_pattern" ) end) assert.has.errors(function() Event.Gui.remove( nil, "test_pattern" ) end) end) it('.remove should fail if a non-string gui_element_pattern is passed', function() assert.has.errors(function() Event.Gui.remove( 1, false, "test_pattern" ) end) assert.has.errors(function() Event.Gui.remove( 1, nil, "test_pattern" ) end) assert.has.errors(function() Event.Gui.remove( 1, 5, "test_pattern" ) end) assert.has.errors(function() Event.Gui.remove( 1, {4}, "test_pattern" ) end) end) it('.remove should remove only the handler of given pattern', function() Event.Gui.register( 1, "test_pattern", function_a ) Event.Gui.register( 1, "test_pattern2", function_b ) Event.Gui.register( 1, "test_pattern3", function_c ) Event.Gui.remove( 1, "test_pattern2" ) assert.is_true( tablelength(Event.Gui._registry[1]) == 2) assert.equals( function_a, Event.Gui._registry[1]["test_pattern"] ) assert.equals( function_c, Event.Gui._registry[1]["test_pattern3"] ) assert.is_nil( Event.Gui._registry[1]["test_pattern2"] ) end) it('.on_click should return itself', function() assert.equals(Gui, Gui.on_click("test_pattern", function() end)) assert.equals(Gui, Gui.on_click("test_pattern", function() end).on_click("test_pattern", function() end)) end) it('.on_click should pass the event to Event.Gui.register for registration', function() local s = spy.on(Event.Gui, "register") Gui.on_click( "test_pattern", function_a ) assert.spy(s).was_called() assert.spy(s).was_called_with(defines.events.on_gui_click, "test_pattern", function_a) end) it('.on_checked_state_changed should pass the event to Event.Gui.register for registration', function() local s = spy.on(Event.Gui, "register") Gui.on_checked_state_changed( "test_pattern", function_a ) assert.spy(s).was_called() assert.spy(s).was_called_with(defines.events.on_gui_checked_state_changed, "test_pattern", function_a) end) it('.on_text_changed should pass the event to Event.Gui.register for registration', function() local s = spy.on(Event.Gui, "register") Gui.on_text_changed( "test_pattern", function_a ) assert.spy(s).was_called() assert.spy(s).was_called_with(defines.events.on_gui_text_changed, "test_pattern", function_a) end) it('.on_elem_changed should pass the event to Event.Gui.register for registration', function() local s = spy.on(Event.Gui, "register") Gui.on_elem_changed( "test_pattern", function_a ) assert.spy(s).was_called() assert.spy(s).was_called_with(defines.events.on_gui_elem_changed, "test_pattern", function_a) end) it('.on_selection_state_changed should pass the event to Event.Gui.register for registration', function() local s = spy.on(Event.Gui, "register") Gui.on_selection_state_changed( "test_pattern", function_a ) assert.spy(s).was_called() assert.spy(s).was_called_with(defines.events.on_gui_selection_state_changed, "test_pattern", function_a) end) end)
isc
melinath/Brent
lua/objectives.lua
1
8497
local events = modular.require("events") local maps = modular.require("maps") local utils = modular.require("utils") local _ = wesnoth.textdomain("wesnoth-Brent") --! Container for the base objective class and its subclasses. objectives = {} objectives.base = utils.class:subclass({ --! The base class for objectives. This can be extended by calling --! ``objectives.base:subclass(cfg)``, where ``cfg`` is a table defining --! overriding behavior for the subclass. Instances of subclasses are meant --! to be used to populate a quest's objective tables. --! Attributes !-- --! The displayed description of the objective. It must be set at some --! point. description = nil, --! A table of objectives which must be completed before this objective. It --! is up to the authors of custom objectives to honor this list when --! registering events. prerequisites = {}, --! Methods !-- should_display = function(self) --! Returns ``true`` if the objective should be displayed and ``false`` --! otherwise. By default, returns ``true``. return true end, prerequisites_met = function(self, quest) --! Returns ``true`` if the objective's prerequisites have been met and --! ``false`` otherwise. for i, prerequisite in ipairs(self.prerequisites) do if not prerequisite:conditions_met(quest) then return false end end return true end, conditions_met = function(self, quest) --! Returns ``true`` if the objective's conditions have been met and --! ``false`` otherwise. By default, returns ``true``. return true end, get_status_text = function(self, quest) --! Returns some sort of text representation of the status of the --! objective. By default, returns "Complete" if ``self.conditions_met`` --! returns ``true`` and an empty string otherwise. if self:conditions_met(quest) then return _("Complete") end return "" end, get_map_events = function(self, quest) --! A table mapping map ids to {event_name, function} tuples. --! If the current map matches one of the map ids, the defined --! functions will be registered at the given event names. The --! functions should be related to this objective - for --! example, setting up the objective, or preventing the --! player from continuing until the objective has been met. --! The special value "*" can be used to match all map ids. --! Events should also call ``self:on_completion(quest)`` if --! they complete the objective's goals. See the kill_count --! objective for an example implementation. return {} end, _register_event = function(self, quest, event_name, func) events.register(event_name, function() if quest.status == 'active' and self:prerequisites_met(quest) and not self:conditions_met(quest) then func(self) end end) end, register_events = function(self, quest) --! This function will be run during preload to register events with --! the events framework. By default, registers the given map_events --! if and only if the conditions of the objective have *not* been met. if quest.status == "active" and not self:conditions_met(quest) then local map_events = self:get_map_events(quest) if maps.current ~= nil and map_events[maps.current.id] then for i=1, #map_events[maps.current.id] do local event_name, func = table.unpack(map_events[maps.current.id][i]) self:_register_event(quest, event_name, func) end end if map_events["*"] then for i=1, #map_events["*"] do local event_name, func = table.unpack(map_events["*"][i]) self:_register_event(quest, event_name, func) end end end end, on_completion = function(self, quest) --! Hook which should be run when the objective is considered --! completed. By default, displays a message and calls --! ``quest:objective_completed(self)``. wesnoth.fire("print", { green = 255, text = markup.concat(_("Objective completed: "), self.description), size = 20, duration = 200 }) quest:objective_completed(self) end, }) --! Base class for notes. Always return ``false`` for conditions_met. objectives.note = objectives.base:subclass({ conditions_met = function(self, quest) return false end }) --! Base class for objectives intended to be manually marked complete. objectives.manual = objectives.base:subclass({ variable_name = 'manual', conditions_met = function(self, quest) return quest:get_var(self.variable_name) end, mark_complete = function(self, quest) quest:set_var(self.variable_name, 1) self:on_completion(quest) end, }) --! Base class for objectives which involve getting a certain count of things. objectives.count = objectives.base:subclass({ --! The total count which must be reached to satisfy the objective. total_count = nil, --! Wesnoth variable which is used to store the count for this objective. variable_name = nil, --! Integer by which to increment the count. increment_by = 1, get_count = function(self, quest) --! Returns the current count for this objective, as stored in the --! quest's variables as ``self.variable_name``. This may be higher --! than the total count. return quest:get_var(self.variable_name) or 0 end, increment = function(self, quest) local count = self:get_count(quest) quest:set_var(self.variable_name, count + self.increment_by) end, conditions_met = function(self, quest) return self:get_count(quest) >= self.total_count end, get_status_text = function(self, quest) if self.total_count == 1 then return objectives.base.get_status_text(self, quest) else local current_count = math.min(self:get_count(quest), self.total_count) return string.format("%d/%d", current_count, self.total_count) end end, }) --! Base class for quests which involve killing a certain number of things. objectives.kill_count = objectives.count:subclass({ variable_name = 'kill_count', --! Mapping of map IDs to filters for the kill event. The filters which can be --! provided are SUF keyed in as "filter" and "filter_second". The special string --! "*" can be used to match all map IDs. --! --! Example: map_filters = {["*"] = {filter = {side = 1}}} map_filters = {}, get_map_events = function(self, quest) local map_events = {} for map_id, filters in pairs(self.map_filters) do map_events[map_id] = {{"die", function() local filter, filter_second = filters["filter"], filters["filter_second"] local c = wesnoth.current.event_context local should_increment = true if filter ~= nil then local unit = wesnoth.get_unit(c.x1, c.y1) if not wesnoth.match_unit(unit, filter) then should_increment = false end end if should_increment and filter_second ~= nil then local second_unit = wesnoth.get_unit(c.x2, c.y2) if not wesnoth.match_unit(second_unit, filter_second) then should_increment = false end end if should_increment then self:increment(quest) end if self:conditions_met(quest) then self:on_completion(quest) end end}} end return map_events end, }) --! Base class for objectives which involve going to a location on a certain --! map. objectives.visit_location = objectives.base:subclass({ variable_name = 'location_visited', --! Mapping of map IDs to filters for the moveto event. "filter" (an SUF) --! and "filter_location" are currently supported. The special string "*" --! can be used to match all map IDs. --! --! Example: map_filters = {"*" = {"filter" = {"side" = 1}}} map_filters = {}, conditions_met = function(self, quest) return quest:get_var(self.variable_name) end, mark_visited = function(self, quest) quest:set_var(self.variable_name, true) end, get_map_events = function(self, quest) local map_events = {} for map_id, filters in pairs(self.map_filters) do map_events[map_id] = {{"moveto", function() local c = wesnoth.current.event_context local filter, filter_location = filters["filter"], filters["filter_location"] local matched = true if filter_location ~= nil then if not wesnoth.match_location(c.x1, c.x2, filter_location) then matched = false end end if filter ~= nil then local unit = wesnoth.get_unit(c.x1, c.y1) if not wesnoth.match_unit(unit, filter) then matched = false end end if matched then self:mark_visited(quest) self:on_completion(quest) end end}} end return map_events end, }) return objectives
gpl-2.0
tltneon/NutScript
plugins/stamina/sh_plugin.lua
2
2096
PLUGIN.name = "Stamina" PLUGIN.author = "Chessnut" PLUGIN.desc = "Adds a stamina system to limit running." if (SERVER) then function PLUGIN:PostPlayerLoadout(client) client:setLocalVar("stm", 100) local uniqueID = "nutStam"..client:SteamID() local offset = 0 local velocity local length2D = 0 local runSpeed = client:GetRunSpeed() - 5 timer.Create(uniqueID, 0.25, 0, function() if (IsValid(client)) then local character = client:getChar() if (client:GetMoveType() != MOVETYPE_NOCLIP and character) then velocity = client:GetVelocity() length2D = velocity:Length2D() runSpeed = nut.config.get("runSpeed") + character:getAttrib("stm", 0) if (client:WaterLevel() > 1) then runSpeed = runSpeed * 0.775 end if (client:KeyDown(IN_SPEED) and length2D >= (runSpeed - 10)) then offset = -2 + (character:getAttrib("end", 0) / 60) elseif (offset > 0.5) then offset = 1 else offset = 1.75 end if (client:Crouching()) then offset = offset + 1 end local current = client:getLocalVar("stm", 0) local value = math.Clamp(current + offset, 0, 100) if (current != value) then client:setLocalVar("stm", value) if (value == 0 and !client:getNetVar("brth", false)) then client:SetRunSpeed(nut.config.get("walkSpeed")) client:setNetVar("brth", true) --character:updateAttrib("end", 0.1) --character:updateAttrib("stm", 0.01) hook.Run("PlayerStaminaLost", client) elseif (value >= 50 and client:getNetVar("brth", false)) then client:SetRunSpeed(runSpeed) client:setNetVar("brth", nil) end end end else timer.Remove(uniqueID) end end) end local playerMeta = FindMetaTable("Player") function playerMeta:restoreStamina(amount) local current = self:getLocalVar("stm", 0) local value = math.Clamp(current + amount, 0, 100) self:setLocalVar("stm", value) end else nut.bar.add(function() return LocalPlayer():getLocalVar("stm", 0) / 100 end, Color(200, 200, 40), nil, "stm") end
mit