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
virtualopensystems/snabbswitch
src/lib/protocol/tcp.lua
5
4120
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local header = require("lib.protocol.header") local ipsum = require("lib.checksum").ipsum local tcp_header_t = ffi.typeof[[ struct { uint16_t src_port; uint16_t dst_port; uint32_t seq; uint32_t ack; uint16_t off_flags; //data offset:4 reserved:3 NS:1 CWR:1 ECE:1 URG:1 ACK:1 PSH:1 RST:1 SYN:1 FIN:1 uint16_t window_size; uint16_t checksum; uint16_t pad; } __attribute__((packed)) ]] local tcp = subClass(header) -- Class variables tcp._name = "tcp" tcp._header_type = tcp_header_t tcp._header_ptr_type = ffi.typeof("$*", tcp_header_t) tcp._ulp = { method = nil } -- Class methods function tcp:new (config) local o tcp:superClass().new(self) o:src_port(config.src_port) o:dst_port(config.dst_port) o:seq_num(config.seq) o:ack_num(config.ack) o:window_size(config.window_size) o:header().pad = 0 o:offset(config.offset or 0) o:ns(config.ns or 0) o:cwr(config.cwr or 0) o:ece(config.ece or 0) o:urg(config.urg or 0) o:ack(config.ack or 0) o:psh(config.psh or 0) o:rst(config.rst or 0) o:syn(config.syn or 0) o:fin(config.fin or 0) o:checksum() return o end -- Instance methods function tcp:src_port (port) local h = self:header() if port ~= nil then h.src_port = C.htons(port) end return C.ntohs(h.src_port) end function tcp:dst_port (port) local h = self:header() if port ~= nil then h.dst_port = C.htons(port) end return C.ntohs(h.dst_port) end function tcp:seq_num (seq) local h = self:header() if seq ~= nil then h.seq = C.htonl(seq) end return C.ntohl(h.seq) end function tcp:ack_num (ack) local h = self:header() if ack ~= nil then h.ack = C.htonl(ack) end return C.ntohl(h.ack) end function tcp:offset (offset) -- ensure reserved bits are 0 lib.bitfield(16, self:header(), 'off_flags', 4, 3, 0) return lib.bitfield(16, self:header(), 'off_flags', 0, 4, offset) end -- set all flags at once function tcp:flags (flags) return lib.bitfield(16, self:header(), 'off_flags', 7, 9, flags) end function tcp:ns (ns) return lib.bitfield(16, self:header(), 'off_flags', 7, 1, ns) end function tcp:cwr (cwr) return lib.bitfield(16, self:header(), 'off_flags', 8, 1, cwr) end function tcp:ece (ece) return lib.bitfield(16, self:header(), 'off_flags', 9, 1, ece) end function tcp:urg (urg) return lib.bitfield(16, self:header(), 'off_flags', 10, 1, urg) end function tcp:ack (ack) return lib.bitfield(16, self:header(), 'off_flags', 11, 1, ack) end function tcp:psh (psh) return lib.bitfield(16, self:header(), 'off_flags', 12, 1, psh) end function tcp:rst (rst) return lib.bitfield(16, self:header(), 'off_flags', 13, 1, rst) end function tcp:syn (syn) return lib.bitfield(16, self:header(), 'off_flags', 14, 1, syn) end function tcp:fin (fin) return lib.bitfield(16, self:header(), 'off_flags', 15, 1, fin) end function tcp:window_size (window_size) local h = self:header() if window_size ~= nil then h.window_size = C.htons(window_size) end return C.ntohs(h.window_size) end function tcp:checksum (payload, length, ip) local h = self:header() if payload then local csum = 0 if ip then -- Checksum IP pseudo-header local ph = ip:pseudo_header(length + self:sizeof(), 6) csum = ipsum(ffi.cast("uint8_t *", ph), ffi.sizeof(ph), 0) end -- Add TCP header h.checksum = 0 csum = ipsum(ffi.cast("uint8_t *", h), self:sizeof(), bit.bnot(csum)) -- Add TCP payload h.checksum = C.htons(ipsum(payload, length, bit.bnot(csum))) end return C.ntohs(h.checksum) end -- override the default equality method function tcp:eq (other) --compare significant fields return (self:src_port() == other:src_port()) and (self:dst_port() == other:dst_port()) and (self:seq_num() == other:seq_num()) and (self:ack_num() == other:ack_num()) end return tcp
apache-2.0
b03605079/darkstar
scripts/zones/Windurst_Walls/npcs/Chomomo.lua
38
1404
----------------------------------- -- Area: Windurst Walls -- NPC: Chomomo -- Type: Standard NPC -- @pos -1.262 -11 290.224 239 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,8) == false) then player:startEvent(0x01f3); else player:startEvent(0x0145); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x01f3) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",8,true); end end;
gpl-3.0
larsnorbergofficial/DiabolicUI
data/auras.lua
2
6166
local _, Engine = ... -- This database will contain lists of categorized Auras -- for CC, dispellers and so on. -- Note: -- In some cases the spellID of the spell casting the effect is listed, -- while what we would want is the spellID of the applied aura/effect on the target. -- Will need to start a public initiative on discord to help people test this out, probably. -- Using this page for dimishing returns in Legion: http://dr-wow.com/ local auras = { -- Diminishing Returns dr = { -- Seconds after last application before vulnerable again. reset = 18, resetKnockback = 10, -- Part of the normal duration on the [i]th application. duration = { 1, .5, .25, 0 }, durationTaunt = { 1, .65, .42, .27, 0 }, durationKnockback = { 1, 0 } }, -- Crowd Control cc = { disorient = { [207167] = true, -- Death Knight - Blinding Sleet [207685] = true, -- Demon Hunter - Sigil of Misery [ 33786] = true, -- Druid - Cyclone [186387] = true, -- Hunter - Bursting Shot [213691] = true, -- Hunter - Scatter Shot [ 31661] = true, -- Mage - Dragon's Breath [198909] = true, -- Monk - Song of Chi-Ji [202274] = true, -- Monk - Incendiary Brew [105421] = true, -- Paladin - Blinding Light [ 605] = true, -- Priest - Dominate Mind [ 8122] = true, -- Priest - Psychic Scream [ 87204] = true, -- Priest - Sin and Punishment (131556?) (Vampiric Touch Dispel) [ 2094] = true, -- Rogue - Blind [ 5246] = true, -- Warrior - Intimidating Shout [ 5782] = true, -- Warlock - Fear [118699] = true, -- Warlock - Fear (new) [ 5484] = true, -- Warlock - Howl of Terror [115268] = true, -- Warlock - Mesmerize (Shivarra) [ 6358] = true, -- Warlock - Seduction (Succubus) }, incapacitate = { [ 99] = true, -- Druid - Incapacitating Roar [236025] = true, -- Druid - Enraged Maim [209790] = true, -- Hunter - Freezing Arrow [ 3355] = true, -- Hunter - Freezing Trap [ 19386] = true, -- Hunter - Wyvern Sting [ 118] = true, -- Mage - Polymorph [ 28271] = true, -- Mage - Polymorph (Turtle) [ 28272] = true, -- Mage - Polymorph (Pig) [ 61305] = true, -- Mage - Polymorph (Black Cat) [ 61721] = true, -- Mage - Polymorph (Rabbit) [ 61780] = true, -- Mage - Polymorph (Turkey) [126819] = true, -- Mage - Polymorph (Porcupine) [161353] = true, -- Mage - Polymorph (Polar Cub) [161354] = true, -- Mage - Polymorph (Monkey) [161355] = true, -- Mage - Polymorph (Penguin) [161372] = true, -- Mage - Polymorph (Peacock) [ 82691] = true, -- Mage - Ring of Frost [115078] = true, -- Monk - Paralysis [ 20066] = true, -- Paladin - Repentance [200196] = true, -- Priest - Holy Word: Chastise [ 9484] = true, -- Priest - Shackle Undead [ 1776] = true, -- Rogue - Gouge [ 6770] = true, -- Rogue - Sap [ 51514] = true, -- Shaman - Hex [210873] = true, -- Shaman - Hex (Compy) [211004] = true, -- Shaman - Hex (Spider) [211010] = true, -- Shaman - Hex (Snake) [211015] = true, -- Shaman - Hex (Cockroach) [ 710] = true, -- Warlock - Banish [ 6789] = true, -- Warlock - Mortal Coil [107079] = true -- Pandarian - Quaking Palm }, knockback = { }, root = { }, silence = { }, stun = { [108194] = true, -- Death Knight - Asphyxiate [221562] = true, -- Death Knight - Asphyxiate? [ 91800] = true, -- Death Knight - Gnaw [179057] = true, -- Demon Hunter - Chaos Nova [211881] = true, -- Demon Hunter - Fel Eruption [205630] = true, -- Demon Hunter - Illidan's Grasp [168881] = true, -- Druid - Maim (5 combo points) [168880] = true, -- Druid - Maim [168879] = true, -- Druid - Maim [168878] = true, -- Druid - Maim [168877] = true, -- Druid - Maim [ 5211] = true, -- Druid - Mighty Bash [163505] = true, -- Druid - Rake [117526] = true, -- Hunter - Binding Shot [ 24394] = true, -- Hunter - Intimidation (Pet) [117418] = true, -- Monk - Fists of Fury [119381] = true, -- Monk - Leg Sweep [ 853] = true, -- Paladin - Hammer of Justice [200200] = true, -- Priest - Holy Word: Chastise [226943] = true, -- Priest - Mind Bomb [199804] = true, -- Rogue - Between the Eyes [ 1833] = true, -- Rogue - Cheap Shot [ 408] = true, -- Rogue - Kidney Shot [204399] = true, -- Shaman - Earthfury (no DR?) [118905] = true, -- Shaman - Static Charge (Capacitor Totem) [ 89766] = true, -- Warlock - Axe Toss (Felguard) [ 22703] = true, -- Warlock - Infernal Awakening (Infernal) [ 30283] = true, -- Warlock - Shadowfury [132168] = true, -- Warrior - Shockwave [132169] = true, -- Warrior - Storm Bolt [ 20549] = true -- Tauren - War Stomp }, }, harm = {}, help = {}, zone = { [64373] = true -- Armistice (Argent Tournament Zone Buff) }, -- Loss of Control -- This will be auto-generated below, just defining them here for semantics. loc = {} } do -- Loss of Control Display Priorities (lower value = higher priority) -- *Mostly intended for nameplates, commented out things we want filtered out local locPrio = { disorient = 3, incapacitate = 5, --knockback = 2, --root = 1, --silence = 4, stun = 6 } -- CC Display Priorities (lower value = higher priority) -- *Mostly intended for unitframes local ccPrio = { disorient = 3, incapacitate = 5, knockback = 2, root = 1, silence = 4, stun = 6 } -- Merge CC categories to allow aura.cc[spellID] local categories = {} -- Avoid modifying the table while iterating for categoryName in pairs(auras.cc) do categories[#categories+1] = categoryName end for i=1,#categories do local categoryName = categories[i] for spellID in pairs(auras.cc[categoryName]) do -- Using priorities here instead of true/nil, -- to allow modules to filter auras based on category. auras.cc[spellID] = ccPrio[categoryName] auras.loc[spellID] = locPrio[categoryName] end end end Engine:NewStaticConfig("Data: Auras", auras)
mit
lyn0328/FrameSynchro
Trunk/Client/src/framework/network.lua
2
7679
--[[ Copyright (c) 2011-2014 chukong-inc.com 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 network = {} --[[-- 检查地 WIFI 网络是否可用 提示: WIFI 网络可用不代表可以访问互联网。 @return boolean 网络是否可用 ]] function network.isLocalWiFiAvailable() return cc.Network:isLocalWiFiAvailable() end --[[-- 检查互联网连接是否可用 通常,这里接口返回 3G 网络的状态,具体情况与设备和操作系统有关。 @return boolean 网络是否可用 ]] function network.isInternetConnectionAvailable() return cc.Network:isInternetConnectionAvailable() end --[[-- 检查是否可以解析指定的主机名 ~~~ lua if network.isHostNameReachable("www.google.com") then -- 域名可以解析 end ~~~ 注意: 该接口会阻塞程序,因此在调用该接口时应该提醒用户应用程序在一段时间内会失去响应。 @return boolean 主机名是否可以解析 ]] function network.isHostNameReachable(hostname) if type(hostname) ~= "string" then printError("network.isHostNameReachable() - invalid hostname %s", tostring(hostname)) return false end return cc.Network:isHostNameReachable(hostname) end --[[-- 返回互联网连接状态值 状态值有三种: - kCCNetworkStatusNotReachable: 无法访问互联网 - kCCNetworkStatusReachableViaWiFi: 通过 WIFI - kCCNetworkStatusReachableViaWWAN: 通过 3G 网络 @return string 互联网连接状态值 ]] function network.getInternetConnectionStatus() return cc.Network:getInternetConnectionStatus() end --[[-- 创建异步 HTTP 请求,并返回 cc.HTTPRequest 对象。 ~~~ lua function onRequestFinished(event) local ok = (event.name == "completed") local request = event.request if not ok then -- 请求失败,显示错误代码和错误消息 print(request:getErrorCode(), request:getErrorMessage()) return end local code = request:getResponseStatusCode() if code ~= 200 then -- 请求结束,但没有返回 200 响应代码 print(code) return end -- 请求成功,显示服务端返回的内容 local response = request:getResponseString() print(response) end -- 创建一个请求,并以 POST 方式发送数据到服务端 local url = "http://www.mycompany.com/request.php" local request = network.createHTTPRequest(onRequestFinished, url, "POST") request:addPOSTValue("KEY", "VALUE") -- 开始请求。当请求完成时会调用 callback() 函数 request:start() ~~~ @return HTTPRequest 结果 ]] function network.createHTTPRequest(callback, url, method) if not method then method = "GET" end if string.upper(tostring(method)) == "GET" then method = cc.kCCHTTPRequestMethodGET else method = cc.kCCHTTPRequestMethodPOST end return cc.HTTPRequest:createWithUrl(callback, url, method) end --[[-- --- Upload a file through a HTTPRequest instance. -- @author zrong(zengrong.net) -- Creation: 2014-04-14 -- @param callback As same as the first parameter of network.createHTTPRequest. -- @param url As same as the second parameter of network.createHTTPRequest. -- @param datas Includes following values: -- fileFiledName(The input label name that type is file); -- filePath(A absolute path for a file) -- contentType(Optional, the file's contentType, default is application/octet-stream) -- extra(Optional, the key-value table that transmit to form) -- for example: ~~~ lua network.uploadFile(function(evt) if evt.name == "completed" then local request = evt.request printf("REQUEST getResponseStatusCode() = %d", request:getResponseStatusCode()) printf("REQUEST getResponseHeadersString() =\n%s", request:getResponseHeadersString()) printf("REQUEST getResponseDataLength() = %d", request:getResponseDataLength()) printf("REQUEST getResponseString() =\n%s", request:getResponseString()) end end, "http://127.0.0.1/upload.php", { fileFieldName="filepath", filePath=device.writablePath.."screen.jpg", contentType="Image/jpeg", extra={ {"act", "upload"}, {"submit", "upload"}, } } ) ~~~ ]] function network.uploadFile(callback, url, datas) assert(datas or datas.fileFieldName or datas.filePath, "Need file datas!") local request = network.createHTTPRequest(callback, url, "POST") local fileFieldName = datas.fileFieldName local filePath = datas.filePath local contentType = datas.contentType if contentType then request:addFormFile(fileFieldName, filePath, contentType) else request:addFormFile(fileFieldName, filePath) end if datas.extra then for i in ipairs(datas.extra) do local data = datas.extra[i] request:addFormContents(data[1], data[2]) end end request:start() return request end local function parseTrueFalse(t) t = string.lower(tostring(t)) if t == "yes" or t == "true" then return true end return false end function network.makeCookieString(cookie) local arr = {} for name, value in pairs(cookie) do if type(value) == "table" then value = tostring(value.value) else value = tostring(value) end arr[#arr + 1] = tostring(name) .. "=" .. string.urlencode(value) end return table.concat(arr, "; ") end function network.parseCookie(cookieString) local cookie = {} local arr = string.split(cookieString, "\n") for _, item in ipairs(arr) do item = string.trim(item) if item ~= "" then local parts = string.split(item, "\t") -- ".amazon.com" represents the domain name of the Web server that created the cookie and will be able to read the cookie in the future -- TRUE indicates that all machines within the given domain can access the cookie -- "/" denotes the path within the domain for which the variable is valid -- "FALSE" indicates that the connection is not secure -- "2082787601" represents the expiration date in UNIX time (number of seconds since January 1, 1970 00:00:00 GMT) -- "ubid-main" is the name of the cookie -- "002-2904428-3375661" is the value of the cookie local c = { domain = parts[1], access = parseTrueFalse(parts[2]), path = parts[3], secure = parseTrueFalse(parts[4]), expire = checkint(parts[5]), name = parts[6], value = string.urldecode(parts[7]), } cookie[c.name] = c end end return cookie end return network
gpl-3.0
Anubhav652/GTW-RPG
[resources]/GTWtrain/data.lua
1
10099
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- --[[ Resource settings, all settings goes here ]]-- Settings = { max_distance_to_spawn = 2000, -- Nearest distance to other trains update_sync_time = 100, -- Time between each sync update slow_speed = 3, -- Definition of slow speed station_stop_time_ms = 11000, -- Time to stop at stations max_track_distance = 180, -- How far away from the tracks can a player be before a train is created min_track_distance = 90, -- How close to the tracks can nay player be before a train is spawned debug_level = 0, -- How many debug messages should display in server console } --[[ All train data are stored in this table ]]-- Trains = { cars = {{ }}, -- Array of carriages attached to the train blips = {{ }}, is_running = { }, -- Boolean indicating if train is moving or not target_speed = { }, -- The speed the train is trying to reach engineer = { }, sync_timer = { }, is_leaving = { }, horn_cooldown = { }, } --[[ Spawn points along the tracks stoptype[0=drive, 1=station, 2=hold] direction[0=counterclockwise, 1=clockwise, 2=both] type[0=train, 1=tram] x, y, z, maxSpeed(kmh) ]]-- coords = { {1,2,0, -1942,174,27, 10}, -- STATION {0,0,0, -1934,238,25, 20}, {0,2,0, -1920,276,20, 40}, {0,2,0, -1861,327,9, 90}, {0,2,0, -1801,367,2, 100}, {0,2,0, -1726,421,8, 110}, {0,2,0, -1663,467,19, 120}, {0,2,0, -1572,533,34, 130}, {0,2,0, -1380,672,36, 130}, {0,2,0, -1228,783,36, 130}, {0,2,0, -1109,869,36, 130}, {0,2,0, -1006,944,36, 130}, {0,2,0, -860,1050,36, 120}, {0,2,0, -712,1152,32, 110}, {0,2,0, -589,1190,28, 110}, {0,2,0, -463,1217,31, 110}, {0,2,0, -298,1256,30, 110}, {0,2,0, -205,1275,26, 100}, {0,2,0, -43,1292,19, 50}, {0,1,0, 90,1283,21, 20}, {1,2,0, 127,1274,24, 10}, -- STATION {0,0,0, 302,1213,24, 20}, {0,2,0, 477,1219,16, 60}, {0,2,0, 625,1298,13, 60}, {0,2,0, 717,1375,13, 40}, {0,1,0, 741,1492,11, 20}, {1,2,0, 743,1780,7, 10}, -- STATION {0,0,0, 741,1935,7, 20}, {0,2,0, 740,2054,10, 50}, {0,2,0, 738,2178,17, 70}, {0,2,0, 728,2295,20, 70}, {0,2,0, 731,2436,21, 70}, {0,2,0, 769,2543,22, 80}, {0,2,0, 834,2672,22, 80}, {0,2,0, 915,2749,21, 80}, {0,2,0, 1049,2738,16, 80}, {0,2,0, 1180,2643,13, 40}, {0,1,0, 1311,2632,12, 20}, {1,2,0, 1451,2632,12, 10}, -- STATION {0,0,0, 1581,2632,12, 20}, {0,2,0, 1639,2636,12, 30}, {0,2,0, 1779,2676,12, 50}, {0,2,0, 1915,2694,12, 60}, {0,2,0, 2008,2694,12, 60}, {0,2,0, 2151,2693,12, 50}, {0,2,0, 2311,2690,12, 60}, {0,2,0, 2462,2685,12, 70}, {0,2,0, 2533,2610,12, 60}, {0,2,0, 2550,2467,12, 50}, {0,2,0, 2552,2424,11, 60}, {0,2,0, 2552,2323,5, 70}, {0,2,0, 2584,2230,2, 80}, {0,2,0, 2722,2123,0, 40}, {0,1,0, 2782,1999,5, 20}, {1,2,0, 2780,1738,12, 10}, -- STATION {0,0,0, 2813,1603,12, 40}, {0,1,0, 2864,1438,12, 40}, {1,2,0, 2864,1258,12, 10}, -- STATION {0,0,0, 2772,1045,12, 20}, {0,2,0, 2764,975,12, 40}, {0,2,0, 2764,888,12, 70}, {0,2,0, 2764,768,12, 80}, {0,2,0, 2765,610,11, 80}, {0,2,0, 2765,392,9, 80}, {0,2,0, 2765,306,9, 70}, {0,2,0, 2798,190,15, 40}, {0,1,0, 2821,101,26, 20}, {1,2,0, 2827, 32,26, 10}, -- STATION {0,0,0, 2827,-94,35, 20}, {0,2,0, 2794,-192,29, 10}, {2,2,0, 2755,-262,21, 0}, -- END POINT {0,1,0, 2615,-295,15, 10}, {0,1,0, 2479,-277,19, 20}, {0,1,0, 2373,-279,22, 50}, {0,1,0, 2273,-336,39, 80}, {0,2,0, 2144,-357,57, 90}, {0,2,0, 2062,-370,65, 90}, {0,2,0, 1994,-473,72, 80}, {0,2,0, 2024,-563,73, 80}, {0,2,0, 2098,-629,64, 90}, {0,2,0, 2206,-712,45, 90}, {0,2,0, 2275,-813,33, 90}, {0,2,0, 2284,-929,28, 80}, {0,2,0, 2284,-1006,28, 70}, {0,2,0, 2284,-1075,28, 60}, {0,2,0, 2284,-1178,27, 50}, {0,2,0, 2284,-1305,25, 40}, {0,2,0, 2284,-1374,25, 40}, {0,2,0, 2277,-1466,24, 40}, {0,2,0, 2242,-1564,20, 40}, {0,2,0, 2212,-1641,17, 20}, {1,2,0, 2206,-1688,16, 10}, -- STATION, O {1,2,0, 2203,-1688,16, 10}, -- STATION, I {0,2,0, 2199,-1707,15, 20}, {0,2,0, 2198,-1848,15, 30}, {0,2,0, 2197,-1909,15, 40}, {0,2,0, 2173,-1947,15, 40}, {0,2,0, 2133,-1954,15, 50}, {0,2,0, 2031,-1954,15, 50}, {0,2,0, 1950,-1954,15, 40}, {0,1,0, 1895,-1954,15, 20}, {1,2,0, 1732,-1958,15, 10}, -- STATION {0,0,0, 1674,-1954,15, 20}, {0,2,0, 1588,-1954,15, 40}, {0,2,0, 1507,-1954,15, 80}, {0,2,0, 1366,-1939,9, 110}, {0,2,0, 1221,-1808,-3, 110}, {0,2,0, 1124,-1696,-3, 110}, {0,2,0, 984,-1537,-1, 70}, {0,2,0, 927,-1476,-1, 40}, {0,1,0, 872,-1421,0, 20}, {1,2,0, 790, -1345,-1, 10}, -- STATION {0,0,0, 763,-1321,0, 20}, {0,2,0, 694,-1265,2, 40}, {0,2,0, 612,-1204,5, 80}, {0,2,0, 524,-1148,10, 120}, {0,2,0, 437,-1103,14, 130}, {0,2,0, 335,-1062,19, 140}, {0,2,0, -9,-1018,22, 140}, {0,2,0, -149,-1027,12, 130}, {0,2,0, -286,-1133,29, 120}, {0,2,0, -396,-1249,43, 110}, {0,2,0, -502,-1236,43, 100}, {0,2,0, -566,-1186,43, 90}, {0,2,0, -665,-1124,50, 90}, {0,2,0, -772,-1154,64, 80}, {0,2,0, -818,-1231,73, 80}, {0,2,0, -829,-1290,80, 90}, {0,2,0, -865,-1448,97, 100}, {0,2,0, -961,-1498,89, 80}, {0,2,0, -1073,-1507,67, 40}, {0,1,0, -1166,-1518,44, 20}, {1,2,0, -1295,-1511,28, 10}, -- STATION {0,0,0, -1396,-1510,24, 20}, {0,2,0, -1506,-1504,20, 40}, {0,2,0, -1649,-1477,15, 90}, {0,2,0, -1816,-1345,15, 150}, {0,2,0, -1898,-1225,15, 150}, {0,2,0, -1965,-1074,21, 150}, {0,2,0, -1979,-823,27, 150}, {0,2,0, -1979,-763,27, 140}, {0,2,0, -1979,-714,27, 130}, {0,2,0, -1980,-669,27, 120}, {0,2,0, -1980,-629,27, 110}, {0,2,0, -1981,-571,27, 100}, {0,2,0, -1979,-497,27, 90}, {0,2,0, -1970,-400,27, 80}, {0,2,0, -1964,-327,27, 70}, {0,2,0, -1949,-210,27, 60}, {0,0,0, -1945,-116,27, 60}, {0,0,0, -1945,-79,27, 40}, {0,0,0, -1945,-21,27, 20}, {0,0,0, -1945,27,27, 10}, {2,2,0, -1945,84,27, 0}, -- END POINT -- Tram derail points {0,2,1, -2267,514,35, 40}, {0,2,1, -2367,505,30, 30}, {0,2,1, -2342,455,33, 40}, {0,2,1, -2274,383,34, 50}, {0,2,1, -2252,328,35, 50}, {0,2,1, -2252,264,35, 70}, {0,2,1, -2252,127,35, 70}, {0,2,1, -2254,36,35, 70}, {0,2,1, -2256,-13,35, 60}, {0,2,1, -2256,-47,35, 50}, {0,2,1, -2253,-65,35, 40}, {0,2,1, -2214,-71,35, 50}, {0,2,1, -2174,-69,35, 40}, {0,2,1, -2167,-23,35, 50}, {0,2,1, -2165,25,35, 40}, {0,2,1, -2126,30,35, 50}, {0,2,1, -2061,30,35, 50}, {0,2,1, -2013,30,33, 40}, {0,2,1, -2007,103,27, 60}, {0,2,1, -2007,223,28, 70}, {0,2,1, -2004,328,35, 70}, {0,2,1, -2004,413,35, 60}, {0,2,1, -2004,503,35, 50}, {0,2,1, -2003,545,35, 40}, {0,2,1, -1999,597,35, 30}, {0,2,1, -1912,603,35, 40}, {0,2,1, -1866,603,35, 50}, {0,2,1, -1809,603,35, 40}, {0,2,1, -1751,603,25, 40}, {0,2,1, -1713,633,25, 40}, {0,2,1, -1710,722,25, 40}, {0,2,1, -1638,728,14, 40}, {0,2,1, -1576,728,7, 30}, {0,2,1, -1549,733,7, 30}, {0,2,1, -1542,764,7, 40}, {0,2,1, -1538,807,7, 40}, {0,2,1, -1551,848,7, 30}, {0,2,1, -1630,848,8, 30}, {0,2,1, -1668,848,23, 30}, {0,2,1, -1701,848,25, 40}, {0,2,1, -1764,848,25, 40}, {0,2,1, -1844,848,34, 30}, {0,2,1, -1907,848,35, 40}, {0,2,1, -1966,848,44, 30}, {0,2,1, -2001,858,45, 40}, {0,2,1, -2000,913,45, 40}, {0,2,1, -1926,921,37, 50}, {0,2,1, -1882,921,35, 40}, {0,2,1, -1853,921,34, 30}, {0,2,1, -1823,921,26, 40}, {0,2,1, -1764,921,25, 50}, {0,2,1, -1695,921,25, 40}, {0,2,1, -1668,921,25, 30}, {0,2,1, -1624,921,9, 40}, {0,2,1, -1537,922,7, 40}, {0,2,1, -1549,981,7, 50}, {0,2,1, -1585,1081,7, 60}, {0,2,1, -1585,1157,7, 70}, {0,2,1, -1625,1237,7, 70}, {0,2,1, -1705,1317,7, 80}, {0,2,1, -1841,1375,7, 70}, {0,2,1, -1912,1319,7, 70}, {0,2,1, -1981,1307,7, 60}, {0,2,1, -2039,1307,7, 50}, {0,2,1, -2068,1277,9, 50}, {0,2,1, -2146,1274,24, 60}, {0,2,1, -2244,1272,40, 50}, {0,2,1, -2273,1226,48, 50}, {0,2,1, -2265,1119,73, 40}, {0,2,1, -2265,1057,83, 50}, {0,2,1, -2265,1015,84, 40}, {0,2,1, -2265,977,70, 50}, {0,2,1, -2265,920,66, 50}, {0,2,1, -2265,866,66, 40}, {0,2,1, -2265,824,52, 50}, {0,2,1, -2265,742,49, 60}, {0,2,1, -2265,683,49, 60}, {0,2,1, -2265,642,49, 50}, }
gpl-3.0
Radseq/otclient
modules/client_terminal/terminal.lua
6
10799
-- configs local LogColors = { [LogDebug] = 'pink', [LogInfo] = 'white', [LogWarning] = 'yellow', [LogError] = 'red' } local MaxLogLines = 128 local MaxHistory = 1000 local oldenv = getfenv(0) setfenv(0, _G) _G.commandEnv = runinsandbox('commands') setfenv(0, oldenv) -- private variables local terminalWindow local terminalButton local logLocked = false local commandTextEdit local terminalBuffer local commandHistory = { } local currentHistoryIndex = 0 local poped = false local oldPos local oldSize local firstShown = false local flushEvent local cachedLines = {} local disabled = false local allLines = {} -- private functions local function navigateCommand(step) if commandTextEdit:isMultiline() then return end local numCommands = #commandHistory if numCommands > 0 then currentHistoryIndex = math.min(math.max(currentHistoryIndex + step, 0), numCommands) if currentHistoryIndex > 0 then local command = commandHistory[numCommands - currentHistoryIndex + 1] commandTextEdit:setText(command) commandTextEdit:setCursorPos(-1) else commandTextEdit:clearText() end end end local function completeCommand() local cursorPos = commandTextEdit:getCursorPos() if cursorPos == 0 then return end local commandBegin = commandTextEdit:getText():sub(1, cursorPos) local possibleCommands = {} -- create a list containing all globals local allVars = table.copy(_G) table.merge(allVars, commandEnv) -- match commands for k,v in pairs(allVars) do if k:sub(1, cursorPos) == commandBegin then table.insert(possibleCommands, k) end end -- complete command with one match if #possibleCommands == 1 then commandTextEdit:setText(possibleCommands[1]) commandTextEdit:setCursorPos(-1) -- show command matches elseif #possibleCommands > 0 then print('>> ' .. commandBegin) -- expand command local expandedComplete = commandBegin local done = false while not done do cursorPos = #commandBegin+1 if #possibleCommands[1] < cursorPos then break end expandedComplete = commandBegin .. possibleCommands[1]:sub(cursorPos, cursorPos) for i,v in ipairs(possibleCommands) do if v:sub(1, #expandedComplete) ~= expandedComplete then done = true end end if not done then commandBegin = expandedComplete end end commandTextEdit:setText(commandBegin) commandTextEdit:setCursorPos(-1) for i,v in ipairs(possibleCommands) do print(v) end end end local function doCommand(textWidget) local currentCommand = textWidget:getText() executeCommand(currentCommand) textWidget:clearText() return true end local function addNewline(textWidget) if not textWidget:isOn() then textWidget:setOn(true) end textWidget:appendText('\n') end local function onCommandChange(textWidget, newText, oldText) local _, newLineCount = string.gsub(newText, '\n', '\n') textWidget:setHeight((newLineCount + 1) * textWidget.baseHeight) if newLineCount == 0 and textWidget:isOn() then textWidget:setOn(false) end end local function onLog(level, message, time) if disabled then return end -- avoid logging while reporting logs (would cause a infinite loop) if logLocked then return end logLocked = true addLine(message, LogColors[level]) logLocked = false end -- public functions function init() terminalWindow = g_ui.displayUI('terminal') terminalWindow:setVisible(false) terminalWindow.onDoubleClick = popWindow terminalButton = modules.client_topmenu.addLeftButton('terminalButton', tr('Terminal') .. ' (Ctrl + T)', '/images/topbuttons/terminal', toggle) g_keyboard.bindKeyDown('Ctrl+T', toggle) commandHistory = g_settings.getList('terminal-history') commandTextEdit = terminalWindow:getChildById('commandTextEdit') commandTextEdit:setHeight(commandTextEdit.baseHeight) connect(commandTextEdit, {onTextChange = onCommandChange}) g_keyboard.bindKeyPress('Up', function() navigateCommand(1) end, commandTextEdit) g_keyboard.bindKeyPress('Down', function() navigateCommand(-1) end, commandTextEdit) g_keyboard.bindKeyPress('Ctrl+C', function() if commandTextEdit:hasSelection() or not terminalSelectText:hasSelection() then return false end g_window.setClipboardText(terminalSelectText:getSelection()) return true end, commandTextEdit) g_keyboard.bindKeyDown('Tab', completeCommand, commandTextEdit) g_keyboard.bindKeyPress('Shift+Enter', addNewline, commandTextEdit) g_keyboard.bindKeyDown('Enter', doCommand, commandTextEdit) g_keyboard.bindKeyDown('Escape', hide, terminalWindow) terminalBuffer = terminalWindow:getChildById('terminalBuffer') terminalSelectText = terminalWindow:getChildById('terminalSelectText') terminalSelectText.onDoubleClick = popWindow terminalSelectText.onMouseWheel = function(a,b,c) terminalBuffer:onMouseWheel(b,c) end terminalBuffer.onScrollChange = function(self, value) terminalSelectText:setTextVirtualOffset(value) end g_logger.setOnLog(onLog) if not g_app.isRunning() then g_logger.fireOldMessages() elseif _G.terminalLines then for _,line in pairs(_G.terminalLines) do addLine(line.text, line.color) end end end function terminate() g_settings.setList('terminal-history', commandHistory) removeEvent(flushEvent) if poped then oldPos = terminalWindow:getPosition() oldSize = terminalWindow:getSize() end local settings = { size = oldSize, pos = oldPos, poped = poped } g_settings.setNode('terminal-window', settings) g_keyboard.unbindKeyDown('Ctrl+T') g_logger.setOnLog(nil) terminalWindow:destroy() terminalButton:destroy() commandEnv = nil _G.terminalLines = allLines end function hideButton() terminalButton:hide() end function popWindow() if poped then oldPos = terminalWindow:getPosition() oldSize = terminalWindow:getSize() terminalWindow:fill('parent') terminalWindow:setOn(false) terminalWindow:getChildById('bottomResizeBorder'):disable() terminalWindow:getChildById('rightResizeBorder'):disable() terminalWindow:getChildById('titleBar'):hide() terminalWindow:getChildById('terminalScroll'):setMarginTop(0) terminalWindow:getChildById('terminalScroll'):setMarginBottom(0) terminalWindow:getChildById('terminalScroll'):setMarginRight(0) poped = false else terminalWindow:breakAnchors() terminalWindow:setOn(true) local size = oldSize or { width = g_window.getWidth()/2.5, height = g_window.getHeight()/4 } terminalWindow:setSize(size) local pos = oldPos or { x = 0, y = g_window.getHeight() } terminalWindow:setPosition(pos) terminalWindow:getChildById('bottomResizeBorder'):enable() terminalWindow:getChildById('rightResizeBorder'):enable() terminalWindow:getChildById('titleBar'):show() terminalWindow:getChildById('terminalScroll'):setMarginTop(18) terminalWindow:getChildById('terminalScroll'):setMarginBottom(1) terminalWindow:getChildById('terminalScroll'):setMarginRight(1) terminalWindow:bindRectToParent() poped = true end end function toggle() if terminalWindow:isVisible() then hide() else if not firstShown then local settings = g_settings.getNode('terminal-window') if settings then if settings.size then oldSize = settings.size end if settings.pos then oldPos = settings.pos end if settings.poped then popWindow() end end firstShown = true end show() end end function show() terminalWindow:show() terminalWindow:raise() terminalWindow:focus() end function hide() terminalWindow:hide() end function disable() terminalButton:hide() g_keyboard.unbindKeyDown('Ctrl+T') disabled = true end function flushLines() local numLines = terminalBuffer:getChildCount() + #cachedLines local fulltext = terminalSelectText:getText() for _,line in pairs(cachedLines) do -- delete old lines if needed if numLines > MaxLogLines then local firstChild = terminalBuffer:getChildByIndex(1) if firstChild then local len = #firstChild:getText() firstChild:destroy() table.remove(allLines, 1) fulltext = string.sub(fulltext, len) end end local label = g_ui.createWidget('TerminalLabel', terminalBuffer) label:setId('terminalLabel' .. numLines) label:setText(line.text) label:setColor(line.color) table.insert(allLines, {text=line.text,color=line.color}) fulltext = fulltext .. '\n' .. line.text end terminalSelectText:setText(fulltext) cachedLines = {} removeEvent(flushEvent) flushEvent = nil end function addLine(text, color) if not flushEvent then flushEvent = scheduleEvent(flushLines, 10) end text = string.gsub(text, '\t', ' ') table.insert(cachedLines, {text=text, color=color}) end function executeCommand(command) if command == nil or #string.gsub(command, '\n', '') == 0 then return end -- add command line addLine("> " .. command, "#ffffff") -- reset current history index currentHistoryIndex = 0 -- add new command to history if #commandHistory == 0 or commandHistory[#commandHistory] ~= command then table.insert(commandHistory, command) if #commandHistory > MaxHistory then table.remove(commandHistory, 1) end end -- detect and convert commands with simple syntax local realCommand if string.sub(command, 1, 1) == '=' then realCommand = 'print(' .. string.sub(command,2) .. ')' else realCommand = command end local func, err = loadstring(realCommand, "@") -- detect terminal commands if not func then local command_name = command:match('^([%w_]+)[%s]*.*') if command_name then local args = string.split(command:match('^[%w_]+[%s]*(.*)'), ' ') if commandEnv[command_name] and type(commandEnv[command_name]) == 'function' then func = function() modules.client_terminal.commandEnv[command_name](unpack(args)) end elseif command_name == command then addLine('ERROR: command not found', 'red') return end end end -- check for syntax errors if not func then addLine('ERROR: incorrect lua syntax: ' .. err:sub(5), 'red') return end -- setup func env to commandEnv setfenv(func, commandEnv) -- execute the command local ok, ret = pcall(func) if ok then -- if the command returned a value, print it if ret then addLine(ret, 'white') end else addLine('ERROR: command failed: ' .. ret, 'red') end end function clear() terminalBuffer:destroyChildren() terminalSelectText:setText('') cachedLines = {} allLines = {} end
mit
TorstenC/esp8266-devkit
Espressif/examples/nodemcu-firmware/lua_examples/irsend.lua
88
1803
------------------------------------------------------------------------------ -- IR send module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("irsend.lua").nec(4, 0x00ff00ff) ------------------------------------------------------------------------------ local M do -- const local NEC_PULSE_US = 1000000 / 38000 local NEC_HDR_MARK = 9000 local NEC_HDR_SPACE = 4500 local NEC_BIT_MARK = 560 local NEC_ONE_SPACE = 1600 local NEC_ZERO_SPACE = 560 local NEC_RPT_SPACE = 2250 -- cache local gpio, bit = gpio, bit local mode, write = gpio.mode, gpio.write local waitus = tmr.delay local isset = bit.isset -- NB: poorman 38kHz PWM with 1/3 duty. Touch with care! ) local carrier = function(pin, c) c = c / NEC_PULSE_US while c > 0 do write(pin, 1) write(pin, 0) c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c * 1 c = c * 1 c = c * 1 c = c - 1 end end -- tsop signal simulator local pull = function(pin, c) write(pin, 0) waitus(c) write(pin, 1) end -- NB: tsop mode allows to directly connect pin -- inplace of TSOP input local nec = function(pin, code, tsop) local pulse = tsop and pull or carrier -- setup transmitter mode(pin, 1) write(pin, tsop and 1 or 0) -- header pulse(pin, NEC_HDR_MARK) waitus(NEC_HDR_SPACE) -- sequence, lsb first for i = 31, 0, -1 do pulse(pin, NEC_BIT_MARK) waitus(isset(code, i) and NEC_ONE_SPACE or NEC_ZERO_SPACE) end -- trailer pulse(pin, NEC_BIT_MARK) -- done transmitter --mode(pin, 0, tsop and 1 or 0) end -- expose M = { nec = nec, } end return M
gpl-3.0
Aquanim/Zero-K
effects/sumo.lua
7
3226
return { ["sumosmoke"] = { muzzlesmoke = { air = true, class = [[CSimpleParticleSystem]], count = 6, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.20 0.11 0.0 0.3 0.20 0.11 0.0 0.03 0 0 0 0.01]], directional = false, emitrot = 60, emitrotspread = 0, emitvector = [[0, -1, 0]], gravity = [[0, 0.3, 0]], numparticles = 1, particlelife = 8, particlelifespread = 10, particlesize = [[3 i-0.4]], particlesizespread = 1, particlespeed = [[4 i-1]], particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 0.8, sizemod = 1.0, texture = [[smokesmall]], }, }, }, ["sumoland"] = { dustcloud = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.7, colormap = [[0.52 0.41 0.21 1 0 0 0 0.01]], directional = false, emitrot = 90, emitrotspread = 10, emitvector = [[0, 1, 0]], gravity = [[0, 0.03, 0]], numparticles = 30, particlelife = 50, particlelifespread = 0, particlesize = 1, particlesizespread = 3, particlespeed = 6, particlespeedspread = 12, pos = [[0, -10, 0]], sizegrowth = 1.7, sizemod = 1, texture = [[smokesmall]], }, }, dirt = { air = true, class = [[CSimpleParticleSystem]], count = 30, ground = true, water = true, properties = { airdrag = 0.995, alwaysvisible = true, colormap = [[0.22 0.18 0.15 1 0.22 0.18 0.15 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 70, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 8, particlelife = 190, particlelifespread = 0, particlesize = [[1 r10]], particlesizespread = 0, particlespeed = 3, particlespeedspread = 4, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[debris2]], }, }, fanny = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 30, explosiongenerator = [[custom:FANNY]], pos = [[0, 0, 0]], }, }, }, }
gpl-2.0
thesrinivas/rakshak
rakshak-probe/userspace/elasticsearch-lua/tests/endpoints/SnapshotTest/StatusTest.lua
2
1640
-- Importing modules local Status = require "elasticsearch.endpoints.Snapshot.Status" local MockTransport = require "lib.MockTransport" local getmetatable = getmetatable -- Setting up environment local _ENV = lunit.TEST_CASE "tests.endpoints.SnapshotTest.StatusTest" -- Declaring local variables local endpoint local mockTransport = MockTransport:new() -- Testing the constructor function constructorTest() assert_function(Status.new) local o = Status:new() assert_not_nil(o) local mt = getmetatable(o) assert_table(mt) assert_equal(mt, mt.__index) end -- The setup function function setup() endpoint = Status:new{ transport = mockTransport } end -- Testing request function requestTest() mockTransport.method = "GET" mockTransport.uri = "/_snapshot/my_backup/_status" mockTransport.params = {} mockTransport.body = nil endpoint:setParams{ repository = "my_backup", } local _, err = endpoint:request() assert_nil(err) end -- Testing snapshot request function requestSnapshotTest() mockTransport.method = "GET" mockTransport.uri = "/_snapshot/my_backup/snapshot_1/_status" mockTransport.params = {} mockTransport.body = nil endpoint:setParams{ repository = "my_backup", snapshot = "snapshot_1" } local _, err = endpoint:request() assert_nil(err) end -- Testing error request function requestErrorTest() mockTransport.method = "PUT" mockTransport.params = {} mockTransport.body = nil local _, err = endpoint:request() assert_not_nil(err) endpoint:setParams{ snapshot = "snapshot_1" } local _, err = endpoint:request() assert_not_nil(err) end
gpl-2.0
b03605079/darkstar
scripts/zones/Spire_of_Vahzl/npcs/_0n0.lua
12
1483
----------------------------------- -- Area: Spire of Vahzl -- NPC: Web of Recollection ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(TradeBCNM(player,player:getZoneID(),trade,npc))then return; else player:messageSpecial(FAINT_SCRAPING); return 1; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(EventTriggerBCNM(player,npc))then return 1; else return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if(EventUpdateBCNM(player,csid,option))then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(EventFinishBCNM(player,csid,option))then return; end end;
gpl-3.0
stevedonovan/Penlight
lua/pl/List.lua
3
15792
--- Python-style list class. -- -- **Please Note**: methods that change the list will return the list. -- This is to allow for method chaining, but please note that `ls = ls:sort()` -- does not mean that a new copy of the list is made. In-place (mutable) methods -- are marked as returning 'the list' in this documentation. -- -- See the Guide for further @{02-arrays.md.Python_style_Lists|discussion} -- -- See <a href="http://www.python.org/doc/current/tut/tut.html">http://www.python.org/doc/current/tut/tut.html</a>, section 5.1 -- -- **Note**: The comments before some of the functions are from the Python docs -- and contain Python code. -- -- Written for Lua version Nick Trout 4.0; Redone for Lua 5.1, Steve Donovan. -- -- Dependencies: `pl.utils`, `pl.tablex`, `pl.class` -- @classmod pl.List -- @pragma nostrip local tinsert,tremove,concat,tsort = table.insert,table.remove,table.concat,table.sort local setmetatable, getmetatable,type,tostring,string = setmetatable,getmetatable,type,tostring,string local tablex = require 'pl.tablex' local filter,imap,imap2,reduce,transform,tremovevalues = tablex.filter,tablex.imap,tablex.imap2,tablex.reduce,tablex.transform,tablex.removevalues local tsub = tablex.sub local utils = require 'pl.utils' local class = require 'pl.class' local array_tostring,split,assert_arg,function_arg = utils.array_tostring,utils.split,utils.assert_arg,utils.function_arg local normalize_slice = tablex._normalize_slice -- metatable for our list and map objects has already been defined.. local Multimap = utils.stdmt.MultiMap local List = utils.stdmt.List local iter class(nil,nil,List) -- we want the result to be _covariant_, i.e. t must have type of obj if possible local function makelist (t,obj) local klass = List if obj then klass = getmetatable(obj) end return setmetatable(t,klass) end local function simple_table(t) return type(t) == 'table' and not getmetatable(t) and #t > 0 end function List._create (src) if simple_table(src) then return src end end function List:_init (src) if self == src then return end -- existing table used as self! if src then for v in iter(src) do tinsert(self,v) end end end --- Create a new list. Can optionally pass a table; -- passing another instance of List will cause a copy to be created; -- this will return a plain table with an appropriate metatable. -- we pass anything which isn't a simple table to iterate() to work out -- an appropriate iterator -- @see List.iterate -- @param[opt] t An optional list-like table -- @return a new List -- @usage ls = List(); ls = List {1,2,3,4} -- @function List.new List.new = List --- Make a copy of an existing list. -- The difference from a plain 'copy constructor' is that this returns -- the actual List subtype. function List:clone() local ls = makelist({},self) ls:extend(self) return ls end --- Add an item to the end of the list. -- @param i An item -- @return the list function List:append(i) tinsert(self,i) return self end List.push = tinsert --- Extend the list by appending all the items in the given list. -- equivalent to 'a[len(a):] = L'. -- @tparam List L Another List -- @return the list function List:extend(L) assert_arg(1,L,'table') for i = 1,#L do tinsert(self,L[i]) end return self end --- Insert an item at a given position. i is the index of the -- element before which to insert. -- @int i index of element before whichh to insert -- @param x A data item -- @return the list function List:insert(i, x) assert_arg(1,i,'number') tinsert(self,i,x) return self end --- Insert an item at the begining of the list. -- @param x a data item -- @return the list function List:put (x) return self:insert(1,x) end --- Remove an element given its index. -- (equivalent of Python's del s[i]) -- @int i the index -- @return the list function List:remove (i) assert_arg(1,i,'number') tremove(self,i) return self end --- Remove the first item from the list whose value is given. -- (This is called 'remove' in Python; renamed to avoid confusion -- with table.remove) -- Return nil if there is no such item. -- @param x A data value -- @return the list function List:remove_value(x) for i=1,#self do if self[i]==x then tremove(self,i) return self end end return self end --- Remove the item at the given position in the list, and return it. -- If no index is specified, a:pop() returns the last item in the list. -- The item is also removed from the list. -- @int[opt] i An index -- @return the item function List:pop(i) if not i then i = #self end assert_arg(1,i,'number') return tremove(self,i) end List.get = List.pop --- Return the index in the list of the first item whose value is given. -- Return nil if there is no such item. -- @function List:index -- @param x A data value -- @int[opt=1] idx where to start search -- @return the index, or nil if not found. local tfind = tablex.find List.index = tfind --- Does this list contain the value? -- @param x A data value -- @return true or false function List:contains(x) return tfind(self,x) and true or false end --- Return the number of times value appears in the list. -- @param x A data value -- @return number of times x appears function List:count(x) local cnt=0 for i=1,#self do if self[i]==x then cnt=cnt+1 end end return cnt end --- Sort the items of the list, in place. -- @func[opt='<'] cmp an optional comparison function -- @return the list function List:sort(cmp) if cmp then cmp = function_arg(1,cmp) end tsort(self,cmp) return self end --- Return a sorted copy of this list. -- @func[opt='<'] cmp an optional comparison function -- @return a new list function List:sorted(cmp) return List(self):sort(cmp) end --- Reverse the elements of the list, in place. -- @return the list function List:reverse() local t = self local n = #t for i = 1,n/2 do t[i],t[n] = t[n],t[i] n = n - 1 end return self end --- Return the minimum and the maximum value of the list. -- @return minimum value -- @return maximum value function List:minmax() local vmin,vmax = 1e70,-1e70 for i = 1,#self do local v = self[i] if v < vmin then vmin = v end if v > vmax then vmax = v end end return vmin,vmax end --- Emulate list slicing. like 'list[first:last]' in Python. -- If first or last are negative then they are relative to the end of the list -- eg. slice(-2) gives last 2 entries in a list, and -- slice(-4,-2) gives from -4th to -2nd -- @param first An index -- @param last An index -- @return a new List function List:slice(first,last) return tsub(self,first,last) end --- Empty the list. -- @return the list function List:clear() for i=1,#self do tremove(self) end return self end local eps = 1.0e-10 --- Emulate Python's range(x) function. -- Include it in List table for tidiness -- @int start A number -- @int[opt] finish A number greater than start; if absent, -- then start is 1 and finish is start -- @int[opt=1] incr an increment (may be less than 1) -- @return a List from start .. finish -- @usage List.range(0,3) == List{0,1,2,3} -- @usage List.range(4) = List{1,2,3,4} -- @usage List.range(5,1,-1) == List{5,4,3,2,1} function List.range(start,finish,incr) if not finish then finish = start start = 1 end if incr then assert_arg(3,incr,'number') if math.ceil(incr) ~= incr then finish = finish + eps end else incr = 1 end assert_arg(1,start,'number') assert_arg(2,finish,'number') local t = List() for i=start,finish,incr do tinsert(t,i) end return t end --- list:len() is the same as #list. function List:len() return #self end -- Extended operations -- --- Remove a subrange of elements. -- equivalent to 'del s[i1:i2]' in Python. -- @int i1 start of range -- @int i2 end of range -- @return the list function List:chop(i1,i2) return tremovevalues(self,i1,i2) end --- Insert a sublist into a list -- equivalent to 's[idx:idx] = list' in Python -- @int idx index -- @tparam List list list to insert -- @return the list -- @usage l = List{10,20}; l:splice(2,{21,22}); assert(l == List{10,21,22,20}) function List:splice(idx,list) assert_arg(1,idx,'number') idx = idx - 1 local i = 1 for v in iter(list) do tinsert(self,i+idx,v) i = i + 1 end return self end --- General slice assignment s[i1:i2] = seq. -- @int i1 start index -- @int i2 end index -- @tparam List seq a list -- @return the list function List:slice_assign(i1,i2,seq) assert_arg(1,i1,'number') assert_arg(1,i2,'number') i1,i2 = normalize_slice(self,i1,i2) if i2 >= i1 then self:chop(i1,i2) end self:splice(i1,seq) return self end --- Concatenation operator. -- @within metamethods -- @tparam List L another List -- @return a new list consisting of the list with the elements of the new list appended function List:__concat(L) assert_arg(1,L,'table') local ls = self:clone() ls:extend(L) return ls end --- Equality operator ==. True iff all elements of two lists are equal. -- @within metamethods -- @tparam List L another List -- @return true or false function List:__eq(L) if #self ~= #L then return false end for i = 1,#self do if self[i] ~= L[i] then return false end end return true end --- Join the elements of a list using a delimiter. -- This method uses tostring on all elements. -- @string[opt=''] delim a delimiter string, can be empty. -- @return a string function List:join (delim) delim = delim or '' assert_arg(1,delim,'string') return concat(array_tostring(self),delim) end --- Join a list of strings. <br> -- Uses `table.concat` directly. -- @function List:concat -- @string[opt=''] delim a delimiter -- @return a string List.concat = concat local function tostring_q(val) local s = tostring(val) if type(val) == 'string' then s = '"'..s..'"' end return s end --- How our list should be rendered as a string. Uses join(). -- @within metamethods -- @see List:join function List:__tostring() return '{'..self:join(',',tostring_q)..'}' end --- Call the function on each element of the list. -- @func fun a function or callable object -- @param ... optional values to pass to function function List:foreach (fun,...) fun = function_arg(1,fun) for i = 1,#self do fun(self[i],...) end end local function lookup_fun (obj,name) local f = obj[name] if not f then error(type(obj).." does not have method "..name,3) end return f end --- Call the named method on each element of the list. -- @string name the method name -- @param ... optional values to pass to function function List:foreachm (name,...) for i = 1,#self do local obj = self[i] local f = lookup_fun(obj,name) f(obj,...) end end --- Create a list of all elements which match a function. -- @func fun a boolean function -- @param[opt] arg optional argument to be passed as second argument of the predicate -- @return a new filtered list. function List:filter (fun,arg) return makelist(filter(self,fun,arg),self) end --- Split a string using a delimiter. -- @string s the string -- @string[opt] delim the delimiter (default spaces) -- @return a List of strings -- @see pl.utils.split function List.split (s,delim) assert_arg(1,s,'string') return makelist(split(s,delim)) end --- Apply a function to all elements. -- Any extra arguments will be passed to the function. -- @func fun a function of at least one argument -- @param ... arbitrary extra arguments. -- @return a new list: {f(x) for x in self} -- @usage List{'one','two'}:map(string.upper) == {'ONE','TWO'} -- @see pl.tablex.imap function List:map (fun,...) return makelist(imap(fun,self,...),self) end --- Apply a function to all elements, in-place. -- Any extra arguments are passed to the function. -- @func fun A function that takes at least one argument -- @param ... arbitrary extra arguments. -- @return the list. function List:transform (fun,...) transform(fun,self,...) return self end --- Apply a function to elements of two lists. -- Any extra arguments will be passed to the function -- @func fun a function of at least two arguments -- @tparam List ls another list -- @param ... arbitrary extra arguments. -- @return a new list: {f(x,y) for x in self, for x in arg1} -- @see pl.tablex.imap2 function List:map2 (fun,ls,...) return makelist(imap2(fun,self,ls,...),self) end --- apply a named method to all elements. -- Any extra arguments will be passed to the method. -- @string name name of method -- @param ... extra arguments -- @return a new list of the results -- @see pl.seq.mapmethod function List:mapm (name,...) local res = {} for i = 1,#self do local val = self[i] local fn = lookup_fun(val,name) res[i] = fn(val,...) end return makelist(res,self) end local function composite_call (method,f) return function(self,...) return self[method](self,f,...) end end function List.default_map_with(T) return function(self,name) local m if T then local f = lookup_fun(T,name) m = composite_call('map',f) else m = composite_call('mapn',name) end getmetatable(self)[name] = m -- and cache.. return m end end List.default_map = List.default_map_with --- 'reduce' a list using a binary function. -- @func fun a function of two arguments -- @return result of the function -- @see pl.tablex.reduce function List:reduce (fun) return reduce(fun,self) end --- Partition a list using a classifier function. -- The function may return nil, but this will be converted to the string key '<nil>'. -- @func fun a function of at least one argument -- @param ... will also be passed to the function -- @treturn MultiMap a table where the keys are the returned values, and the values are Lists -- of values where the function returned that key. -- @see pl.MultiMap function List:partition (fun,...) fun = function_arg(1,fun) local res = {} for i = 1,#self do local val = self[i] local klass = fun(val,...) if klass == nil then klass = '<nil>' end if not res[klass] then res[klass] = List() end res[klass]:append(val) end return setmetatable(res,Multimap) end --- return an iterator over all values. function List:iter () return iter(self) end --- Create an iterator over a seqence. -- This captures the Python concept of 'sequence'. -- For tables, iterates over all values with integer indices. -- @param seq a sequence; a string (over characters), a table, a file object (over lines) or an iterator function -- @usage for x in iterate {1,10,22,55} do io.write(x,',') end ==> 1,10,22,55 -- @usage for ch in iterate 'help' do do io.write(ch,' ') end ==> h e l p function List.iterate(seq) if type(seq) == 'string' then local idx = 0 local n = #seq local sub = string.sub return function () idx = idx + 1 if idx > n then return nil else return sub(seq,idx,idx) end end elseif type(seq) == 'table' then local idx = 0 local n = #seq return function() idx = idx + 1 if idx > n then return nil else return seq[idx] end end elseif type(seq) == 'function' then return seq elseif type(seq) == 'userdata' and io.type(seq) == 'file' then return seq:lines() end end iter = List.iterate return List
mit
b03605079/darkstar
scripts/globals/mobskills/Horrid_Roar_3.lua
6
1347
--------------------------------------------------- -- Horrid Roar (Tiamat, Jormungand, Vrtra, Ouryu) -- Dispels all buffs including food. Lowers Enmity. --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then return 1; elseif (mob:hasStatusEffect(EFFECT_INVINCIBLE)) then return 1; elseif (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then return 1; elseif(target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() == 1) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dispel = target:dispelAllStatusEffect(bit.bor(EFFECTFLAG_DISPELABLE, EFFECTFLAG_FOOD)); if(dispel == 0) then -- no effect skill:setMsg(MSG_NO_EFFECT); -- no effect else skill:setMsg(MSG_DISAPPEAR_NUM); end mob:lowerEnmity(target, 70); if (mob:getName() == "Jormungand" and mob:getHPP() <= 30 and mob:actionQueueAbility() == false) then mob:useMobAbility(1040); end return dispel; end
gpl-3.0
b03605079/darkstar
scripts/zones/Dynamis-Beaucedine/mobs/Angra_Mainyu.lua
19
2392
----------------------------------- -- Area: Dynamis Beaucedine -- NPC: Angra Mainyu -- Mega Boss ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) SpawnMob(17326082):updateEnmity(target); -- Fire_Pukis SpawnMob(17326083):updateEnmity(target); -- Poison_Pukis SpawnMob(17326084):updateEnmity(target); -- Wind_Pukis SpawnMob(17326085):updateEnmity(target); -- Petro_Pukis end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) if(GetMobAction(17326082) == 0 and GetMobAction(17326279) ~= 0) then SpawnMob(17326082):updateEnmity(target); end if(GetMobAction(17326083) == 0 and GetMobAction(17326468) ~= 0) then SpawnMob(17326083):updateEnmity(target); end if(GetMobAction(17326084) == 0 and GetMobAction(17326353) ~= 0) then SpawnMob(17326084):updateEnmity(target); end if(GetMobAction(17326085) == 0 and GetMobAction(17326207) ~= 0) then SpawnMob(17326085):updateEnmity(target); end end; -- Return the selected spell ID. function onMonsterMagicPrepare(mob, target) if(mob:getHPP() < 25) then return 244; -- Death else -- Can cast Blindga, Death, Graviga, Silencega, and Sleepga II. -- Casts Graviga every time before he teleports. rnd = math.random(); if (rnd < 0.2) then return 361; -- Blindga elseif (rnd < 0.4) then return 244; -- Death elseif (rnd < 0.6) then return 366; -- Graviga elseif (rnd < 0.8) then return 274; -- Sleepga II else return 359; -- Silencega end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:addTitle(DYNAMISBEAUCEDINE_INTERLOPER); -- Add title killer:setVar("DynaBeaucedine_Win",1); if(killer:hasKeyItem(HYDRA_CORPS_INSIGNIA) == false) then killer:addKeyItem(HYDRA_CORPS_INSIGNIA); killer:messageSpecial(KEYITEM_OBTAINED,HYDRA_CORPS_INSIGNIA); end end;
gpl-3.0
b03605079/darkstar
scripts/zones/Castle_Oztroja/npcs/Kaa_Toru_the_Just.lua
19
1579
----------------------------------- -- Area: Castle Oztroja -- NPC: Kaa Toru the Just -- Type: Mission NPC [ Windurst Mission 6-2 NPC ]~ -- @pos -100.188 -62.125 145.422 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(WINDURST) == SAINTLY_INVITATION and player:getVar("MissionStatus") == 2) then player:startEvent(0x002d,0,200); else player:startEvent(0x002e); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x002d) then player:delKeyItem(HOLY_ONES_INVITATION); player:addKeyItem(HOLY_ONES_OATH); player:messageSpecial(KEYITEM_OBTAINED,HOLY_ONES_OATH); player:addItem(13134); -- Ashura Necklace player:messageSpecial(ITEM_OBTAINED,13134); player:setVar("MissionStatus",3); end end;
gpl-3.0
ZigzagAK/nginx-resty-auto-healthcheck-config
lua/pointcuts/common.lua
1
2582
local _M = { _VERSION = "2.1.0" } local system = require "system" local ipairs, pairs = ipairs, pairs local pcall, xpcall = pcall, xpcall local traceback = debug.traceback local tinsert = table.insert local unpack = unpack local assert = assert local ngx_log = ngx.log local INFO, ERR = ngx.INFO, ngx.ERR -- setup in init() local MOD_TYPE --- @field #table lib lib = lib or {} function lib.fake(...) return ... end function lib.pcall(f, ...) local ok, result = pcall(function(...) return { f(...) } end, ...) if ok then return unpack(result) end return nil, result end function lib.xpcall(f, ...) local ok, result = xpcall(function(...) return { f(...) } end, function(err) ngx_log(ERR, err, "\n", traceback()) return err end, ...) if ok then return unpack(result) end return nil, result end function lib.foreach_v(t, f) for _,v in pairs(t) do f(v) end end function lib.foreach(t, f) for k,v in pairs(t) do f(k, v) end end function lib.foreachi(t, f) for i=1,#t do f(t[i], i) end end function lib.find_if(t, f) for k,v in pairs(t) do if f(k,v) then return k, v end end end function lib.find_if_i(t, f) local v for i=1,#t do v = t[i] if f(v, i) then return { v, i } end end end function lib.load_modules(path, opts) local modules = system.getmodules(path) local result = {} lib.foreachi(modules, function(m) local short_name, name = unpack(m) local mod, err = lib.xpcall(require, name) if not mod then opts.logfun(ERR, short_name, "error: ", err) else if opts.getfun then local fun = opts.getfun(mod) if fun then tinsert(result, { short_name, fun }) opts.logfun(INFO, short_name, "success") else package.loaded[name] = nil end else opts.logfun(INFO, short_name, "success") end end end) return result end function lib.process_modules(modules, logfun, logall) lib.foreachi(modules, function(mod) local name, fun = unpack(mod) local _,err = lib.xpcall(fun) if err then logfun(ERR, name, "error: ", err) elseif logall then logfun(INFO, name, "success") end end) end function lib.module_type() assert(MOD_TYPE, "MOD_TYPE is nil") return MOD_TYPE end function lib.path2lua_module(path) return path:gsub("^lua/", "") :gsub("^conf/conf.d/", "") :gsub("/", ".") end function _M.init(mod_type) assert(not MOD_TYPE, "MOD_TYPE already initialized") MOD_TYPE = mod_type end return _M
bsd-2-clause
b03605079/darkstar
scripts/zones/Metalworks/npcs/Mighty_Fist.lua
17
2528
----------------------------------- -- Area: Metalworks -- NPC: Mighty Fist -- Starts & Finishes Quest: The Darksmith (R) -- Involved in Quest: Dark Legacy -- @pos -47 2 -30 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(BASTOK,THE_DARKSMITH) ~= QUEST_AVAILABLE) then if(trade:hasItemQty(645,2) and trade:getItemCount() == 2) then player:startEvent(0x0236); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getVar("darkLegacyCS") == 1) then player:startEvent(0x02f0); elseif(player:hasKeyItem(DARKSTEEL_FORMULA)) then player:startEvent(0x02f2); elseif(player:getQuestStatus(BASTOK,THE_DARKSMITH) == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 3) then player:startEvent(0x0235); else Message = math.random(0,1); if(Message == 1) then player:startEvent(0x0230); else player:startEvent(0x0231); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0235) then player:addQuest(BASTOK,THE_DARKSMITH); elseif(csid == 0x0236) then TheDarksmith = player:getQuestStatus(BASTOK,THE_DARKSMITH); player:tradeComplete(); player:addGil(GIL_RATE*8000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*8000); if(TheDarksmith == QUEST_ACCEPTED) then player:addFame(BASTOK,BAS_FAME*30); player:completeQuest(BASTOK,THE_DARKSMITH); else player:addFame(BASTOK,BAS_FAME*5); end elseif(csid == 0x02f0) then player:setVar("darkLegacyCS",2); player:addKeyItem(LETTER_FROM_THE_DARKSTEEL_FORGE); player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_THE_DARKSTEEL_FORGE); end end;
gpl-3.0
b03605079/darkstar
scripts/globals/mobskills/Havoc_Spiral.lua
6
1098
--------------------------------------------- -- Havoc Spiral -- -- Description: Deals damage to players in an area of effect. Additional effect: Sleep -- Type: Physical -- 2-3 Shadows -- Range: Unknown -- Special weaponskill unique to Ark Angel MR. Deals ~100-300 damage. --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) -- TODO: Can skillchain? Unknown property. local numhits = 1; local accmod = 1; local dmgmod = 3; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_2_SHADOW); -- Witnessed 280 to a melee, 400 to a BRD, and 500 to a wyvern, so... target:delHP(dmg); MobStatusEffectMove(mob, target, EFFECT_SLEEP_I, 1, 0, math.random(30, 60)); return dmg; end;
gpl-3.0
b03605079/darkstar
scripts/zones/La_Theine_Plateau/npcs/Deaufrain.lua
17
2302
----------------------------------- -- Area: La Theine Plateau -- NPC: Deaufrain -- Involved in Mission: The Rescue Drill -- @pos -304 28 339 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(SANDORIA) == THE_RESCUE_DRILL) then local MissionStatus = player:getVar("MissionStatus"); if(MissionStatus == 3) then player:startEvent(0x0066); elseif(MissionStatus == 4) then player:showText(npc, RESCUE_DRILL + 4); elseif(MissionStatus == 8) then if(player:getVar("theRescueDrillRandomNPC") == 3) then player:startEvent(0x0071); else player:showText(npc, RESCUE_DRILL + 21); end elseif(MissionStatus == 9) then if(player:getVar("theRescueDrillRandomNPC") == 3) then player:showText(npc, RESCUE_DRILL + 25); else player:showText(npc, RESCUE_DRILL + 26); end elseif(MissionStatus >= 10) then player:showText(npc, RESCUE_DRILL + 30); else player:showText(npc, RESCUE_DRILL); end else player:showText(npc, RESCUE_DRILL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0066) then player:setVar("MissionStatus",4); elseif(csid == 0x0071) then if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16535); -- Bronze Sword else player:addItem(16535); player:messageSpecial(ITEM_OBTAINED, 16535); -- Bronze Sword player:setVar("MissionStatus",9); end end end;
gpl-3.0
Anubhav652/GTW-RPG
[resources]/GTWtraindriver/train_s.lua
1
9446
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Globally accessible tables local train_payment_timers = { } local td_payment = 50 --[[ Find and return the ID of nearest station ]]-- function find_nearest_station(plr, route) if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return 1 end local x,y,z = getElementPosition(plr) local ID,total_dist = 1,9999 for k=1, #train_routes[route] do local dist = getDistanceBetweenPoints3D(train_routes[route][k][1],train_routes[route][k][2],train_routes[route][k][3], x,y,z) if dist < total_dist then total_dist = dist ID = k end end return ID end --[[ Calculate the ID for next trainstation and inform the passengers ]]-- function create_new_train_station(plr, ID) -- There must be a route at this point if not plr or not getElementData(plr, "GTWtraindriver.currentRoute") then return end -- Did we reach the end of the line yet? if so then restart the same route if #train_routes[getElementData(plr, "GTWtraindriver.currentRoute")] < ID then ID = 1; setElementData(plr, "GTWtraindriver.currentstation", 1) end -- Get the coordinates of the next station from our table local x,y,z = train_routes[getElementData(plr, "GTWtraindriver.currentRoute")][ID][1], train_routes[getElementData(plr, "GTWtraindriver.currentRoute")][ID][2], train_routes[getElementData(plr, "GTWtraindriver.currentRoute")][ID][3] -- Tell the client to make a marker and a blip for the traindriver triggerClientEvent(plr, "GTWtraindriver.createtrainstation", plr, x,y,z) -- Get the train object and check for passengers in it local veh = getPedOccupiedVehicle(plr) if not veh then return end local passengers = getVehicleOccupants(veh) if not passengers then return end -- Alright, we got some passengers, let's tell them where we're going for k,pa in pairs(passengers) do setTimer(delayed_message, 10000, 1, "Next station: "..getZoneName(x,y,z).. " in "..getZoneName(x,y,z, true), pa, 55,200, 0) end -- Save the station ID setElementData(plr, "GTWtraindriver.currentstation", ID) end --[[ Drivers get's a route asigned while passengers has to pay when entering the train ]]-- function on_train_enter(plr, seat, jacked) -- Make sure the vehicle is a train if not train_vehicles[getElementModel(source)] then return end if getElementType(plr) ~= "player" then return end -- Start the payment timer for passengers entering the train if seat > 0 then driver = getVehicleOccupant(source, 0) if driver and getElementType(driver) == "player" and getPlayerTeam(driver) and getPlayerTeam(driver) == getTeamFromName( "Civilians" ) and getElementData(driver, "Occupation") == "Train Driver" then -- Initial payment pay_for_the_ride(driver, plr) -- Kill the timer if it exist and make a new one if isTimer( train_payment_timers[plr] ) then killTimer( train_payment_timers[plr] ) end train_payment_timers[plr] = setTimer(pay_for_the_ride, 30000, 0, driver, plr) end end -- Whoever entered the train is a traindriver if getPlayerTeam(plr) and getPlayerTeam(plr) == getTeamFromName("Civilians") and getElementData(plr, "Occupation") == "Train Driver" and seat == 0 and train_vehicles[getElementModel(source )] then -- Let him choose a route to drive triggerClientEvent(plr, "GTWtraindriver.selectRoute", plr) end end addEventHandler("onVehicleEnter", root, on_train_enter) --[[ A little hack for developers to manually change the route ID ]]-- function choose_route(plr, cmd) if not getPedOccupiedVehicle(plr) or not train_vehicles[ getElementModel(getPedOccupiedVehicle(plr))] then return end if getElementType(plr) ~= "player" then return end -- Make sure it's a traindriver inside a train requesting this if getPlayerTeam(plr) and getPlayerTeam(plr) == getTeamFromName("Civilians") and getElementData(plr, "Occupation") == "Train Driver" and getPedOccupiedVehicleSeat(plr) == 0 then -- Force selection of new route triggerClientEvent(plr, "GTWtraindriver.selectRoute", plr) end end addCommandHandler("route", choose_route) addCommandHandler("routes", choose_route) addCommandHandler("routelist", choose_route) addCommandHandler("routeslist", choose_route) --[[ A new route has been selected, load it's data ]]-- function start_new_route(route) setElementData(client, "GTWtraindriver.currentRoute", route) if not getElementData(client, "GTWtraindriver.currentstation") then local first_station = find_nearest_station(client, route) create_new_train_station(client, first_station) else create_new_train_station(client, getElementData(client, "GTWtraindriver.currentstation")) end exports.GTWtopbar:dm("Drive your train to the first station to start your route", client, 0, 255, 0) end addEvent("GTWtraindriver.selectRouteReceive", true) addEventHandler("GTWtraindriver.selectRouteReceive", root, start_new_route) --[[ Handles payments in trains ]]-- function pay_for_the_ride(driver, passenger, first) -- Make sure that both the driver and passenger are players if not driver or not isElement(driver) or getElementType(driver) ~= "player" then return end if not passenger or not isElement(passenger) or getElementType(passenger) ~= "player" then return end -- Make sure the passenger is still inside the train local veh = getPedOccupiedVehicle(driver) if getVehicleOccupant(veh, 0) == driver and getElementData(driver, "Occupation") == "Train Driver" then -- First payment are more expensive if first then takePlayerMoney( passenger, 25 ) givePlayerMoney( driver, 25 ) else takePlayerMoney( passenger, 5 ) givePlayerMoney( driver, 5 ) end else -- Throw the passenger out if he can't pay for the ride any more removePedFromVehicle ( passenger ) if isElement(train_payment_timers[passenger]) then killTimer(train_payment_timers[passenger]) end exports.GTWtopbar:dm( "You can't afford this train ride anymore!", passenger, 255, 0, 0 ) end end --[[ station the payment timer when a passenger exit the train ]]-- function vehicle_exit(plr, seat, jacked) if isTimer(train_payment_timers[plr]) then killTimer(train_payment_timers[plr]) end end addEventHandler("onVehicleExit", root, vehicle_exit) --[[ Calculate the next station ]]-- function calculate_next_station(td_payment) -- Make sure the player is driving a train if not isPedInVehicle(client) then return end if not train_vehicles[getElementModel(getPedOccupiedVehicle(client))] then return end -- Calculate the payment minus charges for damage local fine = math.floor(td_payment - (td_payment*(1-(getElementHealth(getPedOccupiedVehicle(client))/1000)))) -- Increase stats by 1 local playeraccount = getPlayerAccount(client) local train_stations = (getAccountData(playeraccount, "GTWdata_stats_train_stations") or 0) + 1 setAccountData(playeraccount, "GTWdata_stats_train_stations", train_stations) -- Pay the driver givePlayerMoney(client, (fine + math.floor(train_stations/2)) * (1 + math.floor(getElementData(client, "GTWvehicles.numberOfCars")/10 or 1))) -- Notify about the payment reduce if the train is damaged if math.floor(td_payment - fine) > 1 then takePlayerMoney(client, math.floor(td_payment - fine)) exports.GTWtopbar:dm("Removed $"..tostring(math.floor(td_payment - fine)).." due to damage on your train!", client, 255, 0, 0) end -- Get the next station on the list if #train_routes[getElementData(client, "GTWtraindriver.currentRoute")] == tonumber(getElementData(client, "GTWtraindriver.currentstation")) then setElementData( client, "GTWtraindriver.currentstation", 1) else setElementData(client, "GTWtraindriver.currentstation", tonumber( getElementData(client, "GTWtraindriver.currentstation" ))+1) end -- Force the client to create markers and blips for the next station create_new_train_station(client, tonumber(getElementData(client, "GTWtraindriver.currentstation"))) end addEvent("GTWtraindriver.paytrainDriver", true) addEventHandler("GTWtraindriver.paytrainDriver", resourceRoot, calculate_next_station) --[[ A little hack for developers to manually change the route ID ]]-- function set_manual_station(plr, cmd, ID) local is_staff = exports.GTWstaff:isStaff(plr) if not is_staff then return end setElementData(plr, "GTWtraindriver.currentstation", tonumber(ID) or 1) create_new_train_station(plr, tonumber(ID) or 1) end addCommandHandler("settrainstation", set_manual_station) --[[ Display a delayed message securely ]]-- function delayed_message(text, plr, r,g,b, color_coded) if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end if not getPlayerTeam(plr) or getPlayerTeam(plr) ~= getTeamFromName("Civilians") or getElementData(plr, "Occupation") ~= "Train Driver" then return end if not getPedOccupiedVehicle(plr) or not train_vehicles[getElementModel(getPedOccupiedVehicle(plr))] then return end exports.GTWtopbar:dm(text, plr, r,g,b, color_coded) end
gpl-3.0
b03605079/darkstar
scripts/zones/Grand_Palace_of_HuXzoi/npcs/HomePoint#1.lua
16
1210
----------------------------------- -- Area: Grand Palace of Hu'Xzoi -- NPC: HomePoint#3 -- @pos ----------------------------------- package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 88); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Aquanim/Zero-K
gamedata/modularcomms/weapons/aalaser.lua
6
1275
local name = "commweapon_aalaser" local weaponDef = { name = [[Anti-Air Laser]], areaOfEffect = 12, beamDecay = 0.736, beamTime = 1/30, beamttl = 15, canattackground = false, coreThickness = 0.5, craterBoost = 0, craterMult = 0, cylinderTargeting = 1, customParams = { is_unit_weapon = 1, slot = [[5]], light_color = [[0.2 1.2 1.2]], light_radius = 120, reaim_time = 1, }, damage = { default = 1.88, planes = 18.8, }, explosionGenerator = [[custom:flash_teal7]], fireStarter = 100, impactOnly = true, impulseFactor = 0, interceptedByShieldType = 1, laserFlareSize = 3.25, minIntensity = 1, noSelfDamage = true, range = 800, reloadtime = 0.1, rgbColor = [[0 1 1]], soundStart = [[weapon/laser/rapid_laser]], soundStartVolume = 4, thickness = 2.1650635094611, tolerance = 8192, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 2200, } return name, weaponDef
gpl-2.0
arychen/GlobalCall
feeds/luci/applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrd6.lua
68
16296
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require("luci.tools.webadmin") local fs = require "nixio.fs" local util = require "luci.util" local ip = require "luci.ip" local has_ipip = fs.glob("/etc/modules.d/[0-9]*-ipip")() m = Map("olsrd6", translate("OLSR Daemon"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) function m.on_parse() local has_defaults = false m.uci:foreach("olsrd6", "InterfaceDefaults", function(s) has_defaults = true return false end) if not has_defaults then m.uci:section("olsrd6", "InterfaceDefaults") end end function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end s = m:section(TypedSection, "olsrd6", translate("General settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("lquality", translate("Link Quality Settings")) s:tab("smartgw", translate("SmartGW"), not has_ipip and translate("Warning: kmod-ipip is not installed. Without kmod-ipip SmartGateway will not work, please install it.")) s:tab("advanced", translate("Advanced Settings")) poll = s:taboption("advanced", Value, "Pollrate", translate("Pollrate"), translate("Polling rate for OLSR sockets in seconds. Default is 0.05.")) poll.optional = true poll.datatype = "ufloat" poll.placeholder = "0.05" nicc = s:taboption("advanced", Value, "NicChgsPollInt", translate("Nic changes poll interval"), translate("Interval to poll network interfaces for configuration changes (in seconds). Default is \"2.5\".")) nicc.optional = true nicc.datatype = "ufloat" nicc.placeholder = "2.5" tos = s:taboption("advanced", Value, "TosValue", translate("TOS value"), translate("Type of service value for the IP header of control traffic. Default is \"16\".")) tos.optional = true tos.datatype = "uinteger" tos.placeholder = "16" fib = s:taboption("general", ListValue, "FIBMetric", translate("FIB metric"), translate ("FIBMetric controls the metric value of the host-routes OLSRd sets. ".. "\"flat\" means that the metric value is always 2. This is the preferred value ".. "because it helps the linux kernel routing to clean up older routes. ".. "\"correct\" uses the hopcount as the metric value. ".. "\"approx\" use the hopcount as the metric value too, but does only update the hopcount if the nexthop changes too. ".. "Default is \"flat\".")) fib:value("flat") fib:value("correct") fib:value("approx") lql = s:taboption("lquality", ListValue, "LinkQualityLevel", translate("LQ level"), translate("Link quality level switch between hopcount and cost-based (mostly ETX) routing.<br />".. "<b>0</b> = do not use link quality<br />".. "<b>2</b> = use link quality for MPR selection and routing<br />".. "Default is \"2\"")) lql:value("2") lql:value("0") lqage = s:taboption("lquality", Value, "LinkQualityAging", translate("LQ aging"), translate("Link quality aging factor (only for lq level 2). Tuning parameter for etx_float and etx_fpm, smaller values ".. "mean slower changes of ETX value. (allowed values are between 0.01 and 1.0)")) lqage.optional = true lqage:depends("LinkQualityLevel", "2") lqa = s:taboption("lquality", ListValue, "LinkQualityAlgorithm", translate("LQ algorithm"), translate("Link quality algorithm (only for lq level 2).<br />".. "<b>etx_float</b>: floating point ETX with exponential aging<br />".. "<b>etx_fpm</b> : same as etx_float, but with integer arithmetic<br />".. "<b>etx_ff</b> : ETX freifunk, an etx variant which use all OLSR traffic (instead of only hellos) for ETX calculation<br />".. "<b>etx_ffeth</b>: incompatible variant of etx_ff that allows ethernet links with ETX 0.1.<br />".. "Defaults to \"etx_ff\"")) lqa.optional = true lqa:value("etx_ff") lqa:value("etx_fpm") lqa:value("etx_float") lqa:value("etx_ffeth") lqa:depends("LinkQualityLevel", "2") lqa.optional = true lqfish = s:taboption("lquality", Flag, "LinkQualityFishEye", translate("LQ fisheye"), translate("Fisheye mechanism for TCs (checked means on). Default is \"on\"")) lqfish.default = "1" lqfish.optional = true hyst = s:taboption("lquality", Flag, "UseHysteresis", translate("Use hysteresis"), translate("Hysteresis for link sensing (only for hopcount metric). Hysteresis adds more robustness to the link sensing ".. "but delays neighbor registration. Defaults is \"yes\"")) hyst.default = "yes" hyst.enabled = "yes" hyst.disabled = "no" hyst:depends("LinkQualityLevel", "0") hyst.optional = true hyst.rmempty = true port = s:taboption("general", Value, "OlsrPort", translate("Port"), translate("The port OLSR uses. This should usually stay at the IANA assigned port 698. It can have a value between 1 and 65535.")) port.optional = true port.default = "698" port.rmempty = true mainip = s:taboption("general", Value, "MainIp", translate("Main IP"), translate("Sets the main IP (originator ip) of the router. This IP will NEVER change during the uptime of olsrd. ".. "Default is ::, which triggers usage of the IP of the first interface.")) mainip.optional = true mainip.rmempty = true mainip.datatype = "ipaddr" mainip.placeholder = "::" sgw = s:taboption("smartgw", Flag, "SmartGateway", translate("Enable"), translate("Enable SmartGateway. If it is disabled, then " .. "all other SmartGateway parameters are ignored. Default is \"no\".")) sgw.default="no" sgw.enabled="yes" sgw.disabled="no" sgw.rmempty = true sgwnat = s:taboption("smartgw", Flag, "SmartGatewayAllowNAT", translate("Allow gateways with NAT"), translate("Allow the selection of an outgoing ipv4 gateway with NAT")) sgwnat:depends("SmartGateway", "yes") sgwnat.default="yes" sgwnat.enabled="yes" sgwnat.disabled="no" sgwnat.optional = true sgwnat.rmempty = true sgwuplink = s:taboption("smartgw", ListValue, "SmartGatewayUplink", translate("Announce uplink"), translate("Which kind of uplink is exported to the other mesh nodes. " .. "An uplink is detected by looking for a local HNA6 ::ffff:0:0/96 or 2000::/3. Default setting is \"both\".")) sgwuplink:value("none") sgwuplink:value("ipv4") sgwuplink:value("ipv6") sgwuplink:value("both") sgwuplink:depends("SmartGateway", "yes") sgwuplink.default="both" sgwuplink.optional = true sgwuplink.rmempty = true sgwulnat = s:taboption("smartgw", Flag, "SmartGatewayUplinkNAT", translate("Uplink uses NAT"), translate("If this Node uses NAT for connections to the internet. " .. "Default is \"yes\".")) sgwulnat:depends("SmartGatewayUplink", "ipv4") sgwulnat:depends("SmartGatewayUplink", "both") sgwulnat.default="yes" sgwulnat.enabled="yes" sgwulnat.disabled="no" sgwnat.optional = true sgwnat.rmempty = true sgwspeed = s:taboption("smartgw", Value, "SmartGatewaySpeed", translate("Speed of the uplink"), translate("Specifies the speed of ".. "the uplink in kilobits/s. First parameter is upstream, second parameter is downstream. Default is \"128 1024\".")) sgwspeed:depends("SmartGatewayUplink", "ipv4") sgwspeed:depends("SmartGatewayUplink", "ipv6") sgwspeed:depends("SmartGatewayUplink", "both") sgwspeed.optional = true sgwspeed.rmempty = true sgwprefix = s:taboption("smartgw", Value, "SmartGatewayPrefix", translate("IPv6-Prefix of the uplink"), translate("This can be used " .. "to signal the external IPv6 prefix of the uplink to the clients. This might allow a client to change it's local IPv6 address to " .. "use the IPv6 gateway without any kind of address translation. The maximum prefix length is 64 bits. " .. "Default is \"::/0\" (no prefix).")) sgwprefix:depends("SmartGatewayUplink", "ipv6") sgwprefix:depends("SmartGatewayUplink", "both") sgwprefix.optional = true sgwprefix.rmempty = true willingness = s:taboption("advanced", ListValue, "Willingness", translate("Willingness"), translate("The fixed willingness to use. If not set willingness will be calculated dynamically based on battery/power status. Default is \"3\".")) for i=0,7 do willingness:value(i) end willingness.optional = true willingness.default = "3" natthr = s:taboption("advanced", Value, "NatThreshold", translate("NAT threshold"), translate("If the route to the current gateway is to be changed, the ETX value of this gateway is ".. "multiplied with this value before it is compared to the new one. ".. "The parameter can be a value between 0.1 and 1.0, but should be close to 1.0 if changed.<br />".. "<b>WARNING:</b> This parameter should not be used together with the etx_ffeth metric!<br />".. "Defaults to \"1.0\".")) for i=1,0.1,-0.1 do natthr:value(i) end natthr:depends("LinkQualityAlgorithm", "etx_ff") natthr:depends("LinkQualityAlgorithm", "etx_float") natthr:depends("LinkQualityAlgorithm", "etx_fpm") natthr.default = "1.0" natthr.optional = true natthr.write = write_float i = m:section(TypedSection, "InterfaceDefaults", translate("Interfaces Defaults")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float ifs = m:section(TypedSection, "Interface", translate("Interfaces")) ifs.addremove = true ifs.anonymous = true ifs.extedit = luci.dispatcher.build_url("admin/services/olsrd6/iface/%s") ifs.template = "cbi/tblsection" function ifs.create(...) local sid = TypedSection.create(...) luci.http.redirect(ifs.extedit % sid) end ign = ifs:option(Flag, "ignore", translate("Enable")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = ifs:option(DummyValue, "interface", translate("Network")) network.template = "cbi/network_netinfo" mode = ifs:option(DummyValue, "Mode", translate("Mode")) function mode.cfgvalue(...) return Value.cfgvalue(...) or m.uci:get_first("olsrd6", "InterfaceDefaults", "Mode", "mesh") end hello = ifs:option(DummyValue, "_hello", translate("Hello")) function hello.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "HelloInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloInterval", 5)) local v = tonumber(m.uci:get("olsrd6", section, "HelloValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloValidityTime", 40)) return "%.01fs / %.01fs" %{ i, v } end tc = ifs:option(DummyValue, "_tc", translate("TC")) function tc.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "TcInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcInterval", 2)) local v = tonumber(m.uci:get("olsrd6", section, "TcValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcValidityTime", 256)) return "%.01fs / %.01fs" %{ i, v } end mid = ifs:option(DummyValue, "_mid", translate("MID")) function mid.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "MidInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidInterval", 18)) local v = tonumber(m.uci:get("olsrd6", section, "MidValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidValidityTime", 324)) return "%.01fs / %.01fs" %{ i, v } end hna = ifs:option(DummyValue, "_hna", translate("HNA")) function hna.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "HnaInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaInterval", 18)) local v = tonumber(m.uci:get("olsrd6", section, "HnaValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaValidityTime", 108)) return "%.01fs / %.01fs" %{ i, v } end return m
gpl-2.0
b03605079/darkstar
scripts/zones/Upper_Jeuno/npcs/Laila.lua
16
2416
----------------------------------- -- Area: Upper Jeuno -- NPC: Laila -- Type: Job Quest Giver -- @zone: 244 -- @pos -54.045 -1 100.996 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local lakesideMin = player:getQuestStatus(JEUNO,LAKESIDE_MINUET); local lakeProg = player:getVar("Lakeside_Minuet_Progress"); if(lakesideMin == QUEST_AVAILABLE and player:getMainLvl() >= ADVANCED_JOB_LEVEL and ENABLE_WOTG == 1) then player:startEvent(0x277f); -- Start quest csid, asks for Key Item Stardust Pebble elseif(lakesideMin == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x2787); elseif(player:hasKeyItem(STARDUST_PEBBLE)) then player:startEvent(0x2786); -- Ends Quest elseif(lakeProg == 3) then player:startEvent(0x2781); elseif(lakesideMin == QUEST_ACCEPTED) then player:startEvent(0x2780) -- After accepting, reminder else player:startEvent(0x2788); -- Default end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x277f and option == 1) then player:addQuest(JEUNO,LAKESIDE_MINUET); elseif(csid == 0x2786) then player:setVar("Lakeside_Minuet_Progress",0); player:completeQuest(JEUNO,LAKESIDE_MINUET); player:addTitle(TROUPE_BRILIOTH_DANCER); player:unlockJob(19); player:messageSpecial(UNLOCK_DANCER); player:addFame(JEUNO, JEUNO_FAME*30); player:delKeyItem(STARDUST_PEBBLE); player:needToZone(true); end end;
gpl-3.0
cosmy1/Urho3D
bin/Data/LuaScripts/42_PBRMaterials.lua
11
8285
-- PBR materials example. -- This sample demonstrates: -- - Loading a scene that showcases physically based materials & shaders -- -- To use with deferred rendering, a PBR deferred renderpath should be chosen: -- CoreData/RenderPaths/PBRDeferred.xml or CoreData/RenderPaths/PBRDeferredHWDepth.xml require "LuaScripts/Utilities/Sample" local dynamicMaterial = nil local roughnessLabel = nil local metallicLabel = nil local ambientLabel = nil local zone = nil function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateUI() CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Subscribe to global events for camera movement SubscribeToEvents() end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use sliders to change Roughness and Metallic\n" .. "Hold RMB and use WASD keys and mouse to move") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- 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 CreateScene() scene_ = Scene() -- Load scene content prepared in the editor (XML format). GetFile() returns an open file from the resource system -- which scene.LoadXML() will read local file = cache:GetFile("Scenes/PBRExample.xml") scene_:LoadXML(file) -- In Lua the file returned by GetFile() needs to be deleted manually file:delete() local sphereWithDynamicMatNode = scene_:GetChild("SphereWithDynamicMat") local staticModel = sphereWithDynamicMatNode:GetComponent("StaticModel") dynamicMaterial = staticModel:GetMaterial(0) local zoneNode = scene_:GetChild("Zone") zone = zoneNode:GetComponent("Zone") -- Create the camera (not included in the scene file) cameraNode = scene_:CreateChild("Camera") cameraNode:CreateComponent("Camera") cameraNode.position = sphereWithDynamicMatNode.position + Vector3(2.0, 2.0, 2.0) cameraNode:LookAt(sphereWithDynamicMatNode.position) yaw = cameraNode.rotation:YawAngle() pitch = cameraNode.rotation:PitchAngle() end function CreateUI() -- Set up global UI style into the root UI element local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") ui.root.defaultStyle = style -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will -- control the camera, and when visible, it will interact with the UI local cursor = ui.root:CreateChild("Cursor") cursor:SetStyleAuto() ui.cursor = cursor -- Set starting position of the cursor at the rendering window center cursor:SetPosition(graphics.width / 2, graphics.height / 2) roughnessLabel = ui.root:CreateChild("Text") roughnessLabel:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) roughnessLabel:SetPosition(370, 50) roughnessLabel.textEffect = TE_SHADOW metallicLabel = ui.root:CreateChild("Text") metallicLabel:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) metallicLabel:SetPosition(370, 100) metallicLabel.textEffect = TE_SHADOW ambientLabel = ui.root:CreateChild("Text") ambientLabel:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) ambientLabel:SetPosition(370, 150) ambientLabel.textEffect = TE_SHADOW local roughnessSlider = ui.root:CreateChild("Slider") roughnessSlider:SetStyleAuto() roughnessSlider:SetPosition(50, 50) roughnessSlider:SetSize(300, 20) roughnessSlider.range = 1.0 -- 0 - 1 range SubscribeToEvent(roughnessSlider, "SliderChanged", "HandleRoughnessSliderChanged") roughnessSlider.value = 0.5 local metallicSlider = ui.root:CreateChild("Slider") metallicSlider:SetStyleAuto() metallicSlider:SetPosition(50, 100) metallicSlider:SetSize(300, 20) metallicSlider.range = 1.0 -- 0 - 1 range SubscribeToEvent(metallicSlider, "SliderChanged", "HandleMetallicSliderChanged") metallicSlider.value = 0.5 local ambientSlider = ui.root:CreateChild("Slider") ambientSlider:SetStyleAuto() ambientSlider:SetPosition(50, 150) ambientSlider:SetSize(300, 20) ambientSlider.range = 10.0 -- 0 - 10 range SubscribeToEvent(ambientSlider, "SliderChanged", "HandleAmbientSliderChanged") ambientSlider.value = zone.ambientColor.a end function HandleRoughnessSliderChanged(eventType, eventData) local newValue = eventData["Value"]:GetFloat() dynamicMaterial:SetShaderParameter("Roughness", Variant(newValue)) roughnessLabel.text = "Roughness: " .. newValue end function HandleMetallicSliderChanged(eventType, eventData) local newValue = eventData["Value"]:GetFloat() dynamicMaterial:SetShaderParameter("Metallic", Variant(newValue)) metallicLabel.text = "Metallic: " .. newValue end function HandleAmbientSliderChanged(eventType, eventData) local newValue = eventData["Value"]:GetFloat() local col = Color(0, 0, 0, newValue) zone.ambientColor = col ambientLabel.text = "Ambient HDR Scale: " .. zone.ambientColor.a end function SetupViewport() renderer.hdrRendering = true -- 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) -- Add post-processing effects appropriate with the example scene local effectRenderPath = viewport:GetRenderPath():Clone() effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/FXAA2.xml")) effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/GammaCorrection.xml")) effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/Tonemap.xml")) effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/AutoExposure.xml")) viewport.renderPath = effectRenderPath end function SubscribeToEvents() -- Subscribe HandleUpdate() function for camera motion SubscribeToEvent("Update", "HandleUpdate") 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 MoveCamera(timeStep) -- Right mouse button controls mouse cursor visibility: hide when pressed ui.cursor.visible = not input:GetMouseButtonDown(MOUSEB_RIGHT) -- Do not move if the UI has a focused element if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 10.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 -- Only move the camera when the cursor is hidden if not ui.cursor.visible then 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) end -- 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 end
mit
Aquanim/Zero-K
LuaRules/Gadgets/Include/Optics.lua
6
7100
-- -- Adapted from: -- https://gist.githubusercontent.com/frnsys/6014eed30c69c6722177/raw/ec32813a900348cbb3ab60205921d70c60286ce3/optics.py -- local PQ = VFS.Include("LuaRules/Gadgets/Include/PriorityQueue.lua") local function DistSq(p1, p2) return (p1.x - p2.x)^2 + (p1.z - p2.z)^2 end local TableEcho = Spring.Utilities.TableEcho local Optics = {} function Optics.new(incPoints, incNeighborMatrix, incMinPoints, incBenchmark) if not incBenchmark then incBenchmark = {} incBenchmark.Enter = function (name) end incBenchmark.Leave = function (name) end end local object = setmetatable({}, { __index = { points = incPoints or {}, neighborMatrix = incNeighborMatrix or {}, minPoints = incMinPoints, benchmark = incBenchmark, pointByfID = {}, unprocessed = {}, ordered = {}, -- get ready for a clustering run _Setup = function(self) self.benchmark:Enter("Optics:_Setup") local points, unprocessed = self.points, self.unprocessed --Spring.Echo("epsSq", self.epsSq, "minPoints", self.minPoints) for pIdx, point in pairs(points) do point.rd = nil point.cd = nil point.processed = nil unprocessed[point] = true self.pointByfID[point.fID] = point end --TableEcho(points, "_Setup points") self.benchmark:Leave("Optics:_Setup") end, -- distance from a point to its nth neighbor (n = minPoints - 1) _CoreDistance = function(self, point, neighbors) self.benchmark:Enter("Optics:_CoreDistance") if point.cd then self.benchmark:Leave("Optics:_CoreDistance") return point.cd end if #neighbors >= self.minPoints - 1 then --(minPoints - 1) because point is also part of minPoints local distTable = {} for i = 1, #neighbors do local neighbor = neighbors[i] distTable[#distTable + 1] = DistSq(point, neighbor) end table.sort(distTable) --TableEcho({point=point, neighbors=neighbors, distTable=distTable}, "_CoreDistance (#neighbors >= self.minPoints - 1)") point.cd = distTable[self.minPoints - 1] --return (minPoints - 1) farthest distance as CoreDistance self.benchmark:Leave("Optics:_CoreDistance") return point.cd end self.benchmark:Leave("Optics:_CoreDistance") return nil end, -- neighbors for a point within eps _Neighbors = function(self, pIdx) self.benchmark:Enter("Optics:_Neighbors") local neighbors = {} for pIdx2, _ in pairs(self.neighborMatrix[pIdx]) do neighbors[#neighbors + 1] = self.pointByfID[pIdx2] end --Spring.Echo("#neighbors", #neighbors) self.benchmark:Leave("Optics:_Neighbors") return neighbors end, -- mark a point as processed _Processed = function(self, point) --Spring.Echo("_Processed") point.processed = true self.unprocessed[point] = nil local ordered = self.ordered ordered[#ordered + 1] = point end, -- update seeds if a smaller reachability distance is found _Update = function(self, neighbors, point, seedsPQ) self.benchmark:Enter("Optics:_Update") for ni = 1, #neighbors do local n = neighbors[ni] if not n.processed then --Spring.Echo("newRD") local newRd = math.max(point.cd, DistSq(point, n)) if n.rd == nil then n.rd = newRd --this is a bug!!!! seedsPQ:push({newRd, n}) elseif newRd < n.rd then --this is a bug!!!! n.rd = newRd end end end self.benchmark:Leave("Optics:_Update") --return seedsPQ end, -- run the OPTICS algorithm Run = function(self) self:_Setup() local unprocessed = self.unprocessed --TableEcho(unprocessed, "unprocessed") self.benchmark:Enter("Optics:Run Main Body") while next(unprocessed) do self.benchmark:Enter("Optics:Run (while next(unprocessed) do)") --TableEcho({item=next(unprocessed)}, "next(unprocessed)") local point = next(unprocessed) -- mark p as processed self:_Processed(point) -- find p's neighbors local neighbors = self:_Neighbors(point.fID) --TableEcho({point=point, neighbors=neighbors}, "self:_Neighbors(point)") --TableEcho({point=point, neighborsNum=#neighbors}, "self:_Neighbors(point)") -- if p has a core_distance, i.e has min_cluster_size - 1 neighbors if self:_CoreDistance(point, neighbors) then self.benchmark:Enter("Optics:Run (self:_CoreDistance(point, neighbors))") --Spring.Echo("if self:_CoreDistance(point, neighbors) then") local seedsPQ = PQ.new( function(a,b) return a[1] < b[1] end ) --seedsPQ = self:_Update(neighbors, point, seedsPQ) self:_Update(neighbors, point, seedsPQ) while seedsPQ:peek() do self.benchmark:Enter("Optics:Run (while seedsPQ:peek() do)") -- seeds.sort(key=lambda n: n.rd) local n = seedsPQ:pop()[2] --because we don't need priority --TableEcho({n=n}, "seedsPQ:pop()") -- mark n as processed self:_Processed(n) -- find n's neighbors local nNeighbors = self:_Neighbors(n.fID) --TableEcho({n=n, nNeighbors=nNeighbors}, "seedsPQ:peek()") -- if p has a core_distance... if self:_CoreDistance(n, nNeighbors) then --seedsPQ = self:_Update(nNeighbors, n, seedsPQ) self:_Update(nNeighbors, n, seedsPQ) end self.benchmark:Leave("Optics:Run (while seedsPQ:peek() do)") end self.benchmark:Leave("Optics:Run (self:_CoreDistance(point, neighbors))") end self.benchmark:Leave("Optics:Run (while next(unprocessed) do)") end self.benchmark:Leave("Optics:Run Main Body") -- when all points have been processed -- return the ordered list --Spring.Echo("#ordered", #self.ordered) --TableEcho({ordered = self.ordered}, "ordered") return self.ordered end, -- ??? Clusterize = function(self, clusterThreshold) local clusters = {} local separators = {} local clusterThresholdSq = clusterThreshold^2 local ordered = self.ordered for i = 1, #ordered do local thisP = ordered[i] local thisRD = thisP.rd or math.huge -- use an upper limit to separate the clusters if thisRD > clusterThresholdSq then separators[#separators + 1] = i end end separators[#separators + 1] = #ordered + 1 --TableEcho(separators,"separators") for j = 1, #separators - 1 do local sepStart = separators[j] local sepEnd = separators[j + 1] print(sepEnd, sepStart, sepEnd - sepStart, self.minPoints) if sepEnd - sepStart >= self.minPoints then --Spring.Echo("sepEnd - sepStart >= self.minPoints") --self.ordered[start:end] local clPoints = {} for si = sepStart, sepEnd - 1 do clPoints[#clPoints + 1] = ordered[si].fID end -- TableEcho({clPoints=clPoints}, "clPoints") clusters[#clusters + 1] = {} clusters[#clusters].members = clPoints --Spring.Echo("#clPoints", #clPoints) end end --TableEcho({ordered=ordered}, "clusters") return clusters end, } }) return object end return Optics
gpl-2.0
b03605079/darkstar
scripts/zones/Port_Windurst/npcs/Pyo_Nzon.lua
36
2750
----------------------------------- -- Area: Port Windurst -- NPC: Pyo Nzon ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS); InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET); OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS); ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE); if (ThePromise == QUEST_COMPLETED) then Message = math.random(0,1) if (Message == 1) then player:startEvent(0x021b); else player:startEvent(0x020f); end elseif (ThePromise == QUEST_ACCEPTED) then player:startEvent(0x0205); elseif (CryingOverOnions == QUEST_COMPLETED) then player:startEvent(0x01fe); elseif (CryingOverOnions == QUEST_ACCEPTED) then player:startEvent(0x01f6); elseif (OnionRings == QUEST_COMPLETED) then player:startEvent(0x01bb); elseif (OnionRings == QUEST_ACCEPTED ) then player:startEvent(0x01b5); elseif (InspectorsGadget == QUEST_COMPLETED) then player:startEvent(0x01aa); elseif (InspectorsGadget == QUEST_ACCEPTED) then player:startEvent(0x01a2); elseif (KnowOnesOnions == QUEST_COMPLETED) then player:startEvent(0x0199); elseif (KnowOnesOnions == QUEST_ACCEPTED) then KnowOnesOnionsVar = player:getVar("KnowOnesOnions"); if (KnowOnesOnionsVar == 2) then player:startEvent(0x0198); else player:startEvent(0x018c); end elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then player:startEvent(0x017e); elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then player:startEvent(0x0177); else player:startEvent(0x016e); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Aquanim/Zero-K
effects/paris.lua
13
4272
-- paris_glow -- paris -- paris_gflash -- paris_sphere return { ["paris_glow"] = { glow = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 1, colormap = [[0 0 0 0.01 0.8 0.8 0.8 0.9 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 180, emitvector = [[-0, 1, 0]], gravity = [[0, 0.00, 0]], numparticles = 1, particlelife = 10, particlelifespread = 0, particlesize = 60, particlesizespread = 10, particlespeed = 1, particlespeedspread = 0, pos = [[0, 2, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[circularthingy]], }, }, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.5, flashsize = 100, ttl = 10, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, }, ["paris"] = { dustring = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:GEORGE]], pos = [[0, 0, 0]], }, }, gflash = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:PARIS_GFLASH]], pos = [[0, 0, 0]], }, }, glow = { air = true, class = [[CExpGenSpawner]], count = 0, ground = true, water = true, properties = { delay = [[0 i0.5]], explosiongenerator = [[custom:PARIS_GLOW]], pos = [[0, 0, 0]], }, }, shere = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:PARIS_SPHERE]], pos = [[0, 5, 0]], }, }, }, ["paris_gflash"] = { groundflash = { circlealpha = 0.5, circlegrowth = 60, flashalpha = 0, flashsize = 30, ttl = 20, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, }, ["paris_sphere"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.5, flashsize = 60, ttl = 60, color = { [1] = 0.80000001192093, [2] = 0.80000001192093, [3] = 1, }, }, pikez = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.15, color = [[1.0,1.0,0.8]], dir = [[-15 r30,-15 r30,-15 r30]], length = 40, width = 15, }, }, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.3, alwaysvisible = false, color = [[0.8,0.8,1]], expansionspeed = 58, ttl = 10, }, }, }, }
gpl-2.0
stevedonovan/Penlight
spec/permute_spec.lua
1
5731
local permute = require("pl.permute") local tcopy = require("pl.tablex").copy local utils = require("pl.utils") describe("pl.permute", function() describe("order_iter", function() it("returns all order combinations", function() local result = {} for list in permute.order_iter({"one", "two", "three"}) do result[#result+1] = tcopy(list) end assert.same({ [1] = { [1] = 'two', [2] = 'three', [3] = 'one' }, [2] = { [1] = 'three', [2] = 'two', [3] = 'one' }, [3] = { [1] = 'three', [2] = 'one', [3] = 'two' }, [4] = { [1] = 'one', [2] = 'three', [3] = 'two' }, [5] = { [1] = 'two', [2] = 'one', [3] = 'three' }, [6] = { [1] = 'one', [2] = 'two', [3] = 'three' } }, result) end) it("returns nil on empty list", function() local result = {} for list in permute.order_iter({}) do result[#result+1] = tcopy(list) end assert.equal(0, #result) end) end) describe("order_table", function() it("returns all order combinations", function() local result = permute.order_table({"one", "two", "three"}) assert.same({ [1] = { [1] = 'two', [2] = 'three', [3] = 'one' }, [2] = { [1] = 'three', [2] = 'two', [3] = 'one' }, [3] = { [1] = 'three', [2] = 'one', [3] = 'two' }, [4] = { [1] = 'one', [2] = 'three', [3] = 'two' }, [5] = { [1] = 'two', [2] = 'one', [3] = 'three' }, [6] = { [1] = 'one', [2] = 'two', [3] = 'three' } }, result) end) it("returns empty table on empty input list", function() local result = permute.order_table({}) assert.same({}, result) end) end) describe("list_iter", function() it("returns all combinations from sub-lists", function() local result = {} local strs = {"one", "two", "three"} local ints = { 1,2,3 } local bools = { true, false } for count, str, int, bool in permute.list_iter(strs, ints, bools) do result[#result+1] = {count, str, int, bool} end assert.same({ [1] = {1, 'one', 1, true }, [2] = {2, 'two', 1, true }, [3] = {3, 'three', 1, true }, [4] = {4, 'one', 2, true }, [5] = {5, 'two', 2, true }, [6] = {6, 'three', 2, true }, [7] = {7, 'one', 3, true }, [8] = {8, 'two', 3, true }, [9] = {9, 'three', 3, true }, [10] = {10, 'one', 1, false }, [11] = {11, 'two', 1, false }, [12] = {12, 'three', 1, false }, [13] = {13, 'one', 2, false }, [14] = {14, 'two', 2, false }, [15] = {15, 'three', 2, false }, [16] = {16, 'one', 3, false }, [17] = {17, 'two', 3, false }, [18] = {18, 'three', 3, false }, }, result) end) it("is nil-safe, given 'n' is set", function() local result = {} local bools = utils.pack(nil, true, false) local strs = utils.pack("one", "two", nil) for count, bool, str in permute.list_iter(bools, strs) do result[#result+1] = {count, bool, str} end assert.same({ [1] = {1, nil, 'one' }, [2] = {2, true, 'one' }, [3] = {3, false, 'one' }, [4] = {4, nil, 'two' }, [5] = {5, true, 'two' }, [6] = {6, false, 'two' }, [7] = {7, nil, nil }, [8] = {8, true, nil }, [9] = {9, false, nil }, }, result) end) it("returns nil on empty list", function() local count = 0 for list in permute.list_iter({}) do count = count + 1 end assert.equal(0, count) end) end) describe("list_table", function() it("returns all combinations from sub-lists", function() local strs = {"one", "two", "three"} local ints = { 1,2,3 } local bools = { true, false } assert.same({ [1] = {'one', 1, true, n = 3 }, [2] = {'two', 1, true, n = 3 }, [3] = {'three', 1, true, n = 3 }, [4] = {'one', 2, true, n = 3 }, [5] = {'two', 2, true, n = 3 }, [6] = {'three', 2, true, n = 3 }, [7] = {'one', 3, true, n = 3 }, [8] = {'two', 3, true, n = 3 }, [9] = {'three', 3, true, n = 3 }, [10] = {'one', 1, false, n = 3 }, [11] = {'two', 1, false, n = 3 }, [12] = {'three', 1, false, n = 3 }, [13] = {'one', 2, false, n = 3 }, [14] = {'two', 2, false, n = 3 }, [15] = {'three', 2, false, n = 3 }, [16] = {'one', 3, false, n = 3 }, [17] = {'two', 3, false, n = 3 }, [18] = {'three', 3, false, n = 3 }, }, permute.list_table(strs, ints, bools)) end) it("is nil-safe, given 'n' is set", function() local bools = utils.pack(nil, true, false) local strs = utils.pack("one", "two", nil) assert.same({ [1] = {nil, 'one', n = 2 }, [2] = {true, 'one', n = 2 }, [3] = {false, 'one', n = 2 }, [4] = {nil, 'two', n = 2 }, [5] = {true, 'two', n = 2 }, [6] = {false, 'two', n = 2 }, [7] = {nil, nil, n = 2 }, [8] = {true, nil, n = 2 }, [9] = {false, nil, n = 2 }, }, permute.list_table(bools, strs)) end) it("returns nil on empty list", function() assert.same({}, permute.list_table({})) end) end) end)
mit
b03605079/darkstar
scripts/zones/Al_Zahbi/Zone.lua
8
1315
----------------------------------- -- -- Zone: Al_Zahbi (48) -- ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; -- MOG HOUSE EXIT if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then position = math.random(1,5) + 37; player:setPos(position,0,-62,192); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
aliarshad2000/hunterbot
plugins/stats.lua
236
3989
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
Aquanim/Zero-K
LuaRules/Gadgets/start_unit_setup.lua
4
25586
function gadget:GetInfo() return { name = "StartSetup", desc = "Implements initial setup: start units, resources, and plop for construction", author = "Licho, CarRepairer, Google Frog, SirMaverick", date = "2008-2010", license = "GNU GPL, v2 or later", layer = -1, -- Before terraforming gadget (for facplop terraforming) enabled = true -- loaded by default? } end -- partially based on Spring's unit spawn gadget include("LuaRules/Configs/start_setup.lua") include("LuaRules/Configs/constants.lua") -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local spGetTeamInfo = Spring.GetTeamInfo local spGetPlayerInfo = Spring.GetPlayerInfo local spGetPlayerList = Spring.GetPlayerList local modOptions = Spring.GetModOptions() local DELAYED_AFK_SPAWN = false local COOP_MODE = false local playerChickens = Spring.Utilities.tobool(Spring.GetModOption("playerchickens", false, false)) local campaignBattleID = modOptions.singleplayercampaignbattleid local setAiStartPos = (modOptions.setaispawns == "1") local CAMPAIGN_SPAWN_DEBUG = (Spring.GetModOptions().campaign_spawn_debug == "1") local gaiateam = Spring.GetGaiaTeamID() local SAVE_FILE = "Gadgets/start_unit_setup.lua" local fixedStartPos = (modOptions.fixedstartpos == "1") local ordersToRemove local modStartMetal = START_METAL local modStartEnergy = START_ENERGY local modInnateMetal = INNATE_INC_METAL local modInnateEnergy = INNATE_INC_ENERGY local storageUnits = { { unitDefID = UnitDefNames["staticstorage"].id, storeAmount = UnitDefNames["staticstorage"].metalStorage } } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (gadgetHandler:IsSyncedCode()) then -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Functions shared between missions and non-missions local function CheckOrderRemoval() -- FIXME: maybe we can remove polling every frame and just remove the orders directly if not ordersToRemove then return end for unitID, factoryDefID in pairs(ordersToRemove) do local cmdID, _, cmdTag = Spring.GetUnitCurrentCommand(unitID) if cmdID == -factoryDefID then Spring.GiveOrderToUnit(unitID, CMD.REMOVE, cmdTag, CMD.OPT_ALT) end end ordersToRemove = nil end local function CheckFacplopUse(unitID, unitDefID, teamID, builderID) if ploppableDefs[unitDefID] and (select(5, Spring.GetUnitHealth(unitID)) < 0.1) and (builderID and Spring.GetUnitRulesParam(builderID, "facplop") == 1) then -- (select(5, Spring.GetUnitHealth(unitID)) < 0.1) to prevent ressurect from spending facplop. Spring.SetUnitRulesParam(builderID,"facplop",0, {inlos = true}) Spring.SetUnitRulesParam(unitID,"ploppee",1, {private = true}) ordersToRemove = ordersToRemove or {} ordersToRemove[builderID] = unitDefID -- Instantly complete factory local maxHealth = select(2,Spring.GetUnitHealth(unitID)) Spring.SetUnitHealth(unitID, {health = maxHealth, build = 1}) local x,y,z = Spring.GetUnitPosition(unitID) Spring.SpawnCEG("gate", x, y, z) -- Stats collection (acuelly not, see below) if GG.mod_stats_AddFactoryPlop then GG.mod_stats_AddFactoryPlop(teamID, unitDefID) end -- FIXME: temporary hack because I'm in a hurry -- proper way: get rid of all the useless shit in modstats, reenable and collect plop stats that way (see above) local str = "SPRINGIE:facplop," .. UnitDefs[unitDefID].name .. "," .. teamID .. "," .. select(6, Spring.GetTeamInfo(teamID, false)) .. "," local _, playerID, _, isAI = Spring.GetTeamInfo(teamID, false) if isAI then str = str .. "Nightwatch" -- existing account just in case infra explodes otherwise else str = str .. (Spring.GetPlayerInfo(playerID, false) or "ChanServ") -- ditto, different acc to differentiate end str = str .. ",END_PLOP" Spring.SendCommands("wbynum 255 " .. str) -- Spring.PlaySoundFile("sounds/misc/teleport2.wav", 10, x, y, z) -- FIXME: performance loss, possibly preload? end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Mission Handling if VFS.FileExists("mission.lua") then -- this is a mission, we just want to set starting storage (and enable facplopping) function gadget:Initialize() for _, teamID in ipairs(Spring.GetTeamList()) do Spring.SetTeamResource(teamID, "es", START_STORAGE + HIDDEN_STORAGE) Spring.SetTeamResource(teamID, "ms", START_STORAGE + HIDDEN_STORAGE) end end function GG.SetStartLocation() end function gadget:GameFrame(n) CheckOrderRemoval() end function GG.GiveFacplop(unitID) -- deprecated, use rulesparam directly Spring.SetUnitRulesParam(unitID, "facplop", 1, {inlos = true}) end function gadget:UnitCreated(unitID, unitDefID, teamID, builderID) CheckFacplopUse(unitID, unitDefID, teamID, builderID) end return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local gamestart = false --local createBeforeGameStart = {} -- no longer used local scheduledSpawn = {} local luaSetStartPositions = {} local playerSides = {} -- sides selected ingame from widget - per players local teamSides = {} -- sides selected ingame from widgets - per teams local playerIDsByName = {} local commChoice = {} --local prespawnedCommIDs = {} -- [teamID] = unitID GG.startUnits = {} -- WARNING: this is liable to break with new dyncomms (entries will likely not be an actual unitDefID) GG.CommanderSpawnLocation = {} local waitingForComm = {} GG.waitingForComm = waitingForComm -- overlaps with the rulesparam local commSpawnedTeam = {} local commSpawnedPlayer = {} -- allow gadget:Save (unsynced) to reach them local function UpdateSaveReferences() _G.waitingForComm = waitingForComm _G.scheduledSpawn = scheduledSpawn _G.playerSides = playerSides _G.teamSides = teamSides _G.commSpawnedTeam = commSpawnedTeam _G.commSpawnedPlayer = commSpawnedPlayer end UpdateSaveReferences() local loadGame = false -- was this loaded from a savegame? -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:UnitCreated(unitID, unitDefID, teamID, builderID) CheckFacplopUse(unitID, unitDefID, teamID, builderID) end local function InitUnsafe() end function gadget:Initialize() -- needed if you reload luarules local frame = Spring.GetGameFrame() if frame and frame > 0 then gamestart = true end InitUnsafe() local allUnits = Spring.GetAllUnits() for _, unitID in pairs(allUnits) do local udid = Spring.GetUnitDefID(unitID) if udid then gadget:UnitCreated(unitID, udid, Spring.GetUnitTeam(unitID)) end end end local function GetStartUnit(teamID, playerID, isAI) local teamInfo = teamID and select(7, Spring.GetTeamInfo(teamID, true)) if teamInfo and teamInfo.staticcomm then local commanderName = teamInfo.staticcomm local commanderLevel = teamInfo.staticcomm_level or 1 local commanderProfile = GG.ModularCommAPI.GetCommProfileInfo(commanderName) return commanderProfile.baseUnitDefID end local startUnit if isAI then -- AI that didn't pick comm type gets default comm return UnitDefNames[Spring.GetTeamRulesParam(teamID, "start_unit") or "dyntrainer_strike_base"].id end if (teamID and teamSides[teamID]) then startUnit = DEFAULT_UNIT end if (playerID and playerSides[playerID]) then startUnit = DEFAULT_UNIT end -- if a player-selected comm is available, use it playerID = playerID or (teamID and select(2, spGetTeamInfo(teamID, false)) ) if (playerID and commChoice[playerID]) then --Spring.Echo("Attempting to load alternate comm") local playerCommProfiles = GG.ModularCommAPI.GetPlayerCommProfiles(playerID, true) local altComm = playerCommProfiles[commChoice[playerID]] if altComm then startUnit = playerCommProfiles[commChoice[playerID]].baseUnitDefID end end if (not startUnit) and (not DELAYED_AFK_SPAWN) then startUnit = DEFAULT_UNIT end -- hack workaround for chicken --local luaAI = Spring.GetTeamLuaAI(teamID) --if luaAI and string.find(string.lower(luaAI), "chicken") then startUnit = nil end --if didn't pick a comm, wait for user to pick return (startUnit or nil) end local function GetFacingDirection(x, z, teamID) return (math.abs(Game.mapSizeX/2 - x) > math.abs(Game.mapSizeZ/2 - z)) and ((x>Game.mapSizeX/2) and "west" or "east") or ((z>Game.mapSizeZ/2) and "north" or "south") end local function getMiddleOfStartBox(teamID) local x = Game.mapSizeX / 2 local z = Game.mapSizeZ / 2 local boxID = Spring.GetTeamRulesParam(teamID, "start_box_id") if boxID then local startposList = GG.startBoxConfig[boxID] and GG.startBoxConfig[boxID].startpoints if startposList then local startpos = startposList[1] -- todo: distribute afkers over them all instead of always using the 1st x = startpos[1] z = startpos[2] end end return x, Spring.GetGroundHeight(x,z), z end local function GetStartPos(teamID, teamInfo, isAI) if luaSetStartPositions[teamID] then return luaSetStartPositions[teamID].x, luaSetStartPositions[teamID].y, luaSetStartPositions[teamID].z end if fixedStartPos then local x, y, z if teamInfo then x, z = tonumber(teamInfo.start_x), tonumber(teamInfo.start_z) end if x then y = Spring.GetGroundHeight(x, z) else x, y, z = Spring.GetTeamStartPosition(teamID) end return x, y, z end if not (Spring.GetTeamRulesParam(teamID, "valid_startpos") or isAI) then local x, y, z = getMiddleOfStartBox(teamID) return x, y, z end local x, y, z = Spring.GetTeamStartPosition(teamID) -- clamp invalid positions -- AIs can place them -- remove this once AIs are able to be filtered through AllowStartPosition local boxID = isAI and Spring.GetTeamRulesParam(teamID, "start_box_id") if boxID and not GG.CheckStartbox(boxID, x, z) then x,y,z = getMiddleOfStartBox(teamID) end return x, y, z end local function SpawnStartUnit(teamID, playerID, isAI, bonusSpawn, notAtTheStartOfTheGame) if not teamID then return end local _,_,_,_,_,allyTeamID,teamInfo = Spring.GetTeamInfo(teamID, true) if teamInfo and teamInfo.nocommander then waitingForComm[teamID] = nil return end local luaAI = Spring.GetTeamLuaAI(teamID) if luaAI and string.find(string.lower(luaAI), "chicken") then return false elseif playerChickens then -- allied to latest chicken team? no com for you local chickenTeamID = -1 for _,t in pairs(Spring.GetTeamList()) do local teamLuaAI = Spring.GetTeamLuaAI(t) if teamLuaAI and string.find(string.lower(teamLuaAI), "chicken") then chickenTeamID = t end end if (chickenTeamID > -1) and (Spring.AreTeamsAllied(teamID,chickenTeamID)) then --Spring.Echo("chicken_control detected no com for "..playerID) return false end end -- get start unit local startUnit = GetStartUnit(teamID, playerID, isAI) if ((COOP_MODE and playerID and commSpawnedPlayer[playerID]) or (not COOP_MODE and commSpawnedTeam[teamID])) and not bonusSpawn then return false end if startUnit then -- replace with shuffled position local x,y,z = GetStartPos(teamID, teamInfo, isAI) -- get facing direction local facing = GetFacingDirection(x, z, teamID) if CAMPAIGN_SPAWN_DEBUG then local _, aiName = Spring.GetAIInfo(teamID) Spring.MarkerAddPoint(x, y, z, "Commander " .. (aiName or "Player")) return -- Do not spawn commander end GG.startUnits[teamID] = startUnit GG.CommanderSpawnLocation[teamID] = {x = x, y = y, z = z, facing = facing} if GG.GalaxyCampaignHandler then facing = GG.GalaxyCampaignHandler.OverrideCommFacing(teamID) or facing end -- CREATE UNIT local unitID = GG.DropUnit(startUnit, x, y, z, facing, teamID, _, _, _, _, _, GG.ModularCommAPI.GetProfileIDByBaseDefID(startUnit), teamInfo and tonumber(teamInfo.static_level), true) if not unitID then return end if GG.GalaxyCampaignHandler then GG.GalaxyCampaignHandler.DeployRetinue(unitID, x, z, facing, teamID) end if Spring.GetGameFrame() <= 1 then Spring.SpawnCEG("gate", x, y, z) -- Spring.PlaySoundFile("sounds/misc/teleport2.wav", 10, x, y, z) -- performance loss end if not bonusSpawn then Spring.SetTeamRulesParam(teamID, "commSpawned", 1, {allied = true}) commSpawnedTeam[teamID] = true if playerID then Spring.SetGameRulesParam("commSpawnedPlayer"..playerID, 1, {allied = true}) commSpawnedPlayer[playerID] = true end waitingForComm[teamID] = nil end -- add facplop local teamLuaAI = Spring.GetTeamLuaAI(teamID) local udef = UnitDefs[Spring.GetUnitDefID(unitID)] local metal, metalStore = Spring.GetTeamResources(teamID, "metal") local energy, energyStore = Spring.GetTeamResources(teamID, "energy") Spring.SetTeamResource(teamID, "energy", teamInfo.start_energy or (modStartEnergy + energy)) Spring.SetTeamResource(teamID, "metal", teamInfo.start_metal or (modStartMetal + metal)) if GG.Overdrive then GG.Overdrive.AddInnateIncome(allyTeamID, modInnateMetal, modInnateEnergy) end if (udef.customParams.level and udef.name ~= "chickenbroodqueen") and ((not campaignBattleID) or GG.GalaxyCampaignHandler.HasFactoryPlop(teamID)) then Spring.SetUnitRulesParam(unitID, "facplop", 1, {inlos = true}) end local name = "noname" -- Backup for when player does not choose a commander and then resigns. if isAI then name = select(2, Spring.GetAIInfo(teamID)) else name = Spring.GetPlayerInfo(playerID, false) end Spring.SetUnitRulesParam(unitID, "commander_owner", name, {inlos = true}) return true end return false end local function StartUnitPicked(playerID, name) local _,_,spec,teamID = spGetPlayerInfo(playerID, false) if spec then return end teamSides[teamID] = name local startUnit = GetStartUnit(teamID, playerID) if startUnit then SendToUnsynced("CommSelection",playerID, startUnit) --activate an event called "CommSelection" that can be detected in unsynced part if UnitDefNames[startUnit] then Spring.SetTeamRulesParam(teamID, "commChoice", UnitDefNames[startUnit].id) else Spring.SetTeamRulesParam(teamID, "commChoice", startUnit) end end if gamestart then -- picked commander after game start, prep for orbital drop -- can't do it directly because that's an unsafe change local frame = Spring.GetGameFrame() + 3 if not scheduledSpawn[frame] then scheduledSpawn[frame] = {} end scheduledSpawn[frame][#scheduledSpawn[frame] + 1] = {teamID, playerID} --else --[[ if startPosition[teamID] then local oldCommID = prespawnedCommIDs[teamID] local pos = startPosition[teamID] local startUnit = GetStartUnit(teamID, playerID, isAI) if startUnit then local newCommID = Spring.CreateUnit(startUnit, pos.x, pos.y, pos.z , "s", 0) if oldCommID then local cmds = Spring.GetCommandQueue(oldCommID, -1) --//transfer command queue for i = 1, #cmds do local cmd = cmds[i] Spring.GiveOrderToUnit(newUnit, cmd.id, cmd.params, cmd.options.coded) end Spring.DestroyUnit(oldCommID, false, true) end prespawnedCommIDs[teamID] = newCommID end end ]] end GG.startUnits[teamID] = GetStartUnit(teamID) -- ctf compatibility end local function workAroundSpecsInTeamZero(playerlist, team) if team == 0 then local players = #playerlist local specs = 0 -- count specs for i=1,#playerlist do local _,_,spec = spGetPlayerInfo(playerlist[i], false) if spec then specs = specs + 1 end end if players == specs then return nil end end return playerlist end --[[ This function return true if everyone in the team resigned. This function is alternative to "isDead" from: "_,_,isDead,isAI = spGetTeamInfo(team, false)" because "isDead" failed to return true when human team resigned before GameStart() event. --]] local function IsTeamResigned(team) local playersInTeam = spGetPlayerList(team) for j=1,#playersInTeam do local spec = select(3,spGetPlayerInfo(playersInTeam[j], false)) if not spec then return false end end return true end local function GetPregameUnitStorage(teamID) local storage = 0 for i = 1, #storageUnits do storage = storage + Spring.GetTeamUnitDefCount(teamID, storageUnits[i].unitDefID) * storageUnits[i].storeAmount end return storage end function gadget:GameStart() if Spring.Utilities.tobool(Spring.GetGameRulesParam("loadedGame")) then return end gamestart = true -- check starting/innate resource modoptions if (modOptions.startmetal and tonumber(modOptions.startmetal) and tonumber(modOptions.startmetal) >= 0) then modStartMetal = modOptions.startmetal end if (modOptions.startenergy and tonumber(modOptions.startenergy) and tonumber(modOptions.startenergy) >= 0) then modStartEnergy = modOptions.startenergy end if (modOptions.startresdelta and tonumber(modOptions.startresdelta) and tonumber(modOptions.startresdelta) > 0) then local resdelta = math.random(0,modOptions.startresdelta) modStartMetal = modStartMetal + resdelta modStartEnergy = modStartEnergy + resdelta end if (modOptions.innatemetal and tonumber(modOptions.innatemetal) and tonumber(modOptions.innatemetal) >= 0) then modInnateMetal = modOptions.innatemetal end if (modOptions.innateenergy and tonumber(modOptions.innateenergy) and tonumber(modOptions.innateenergy) >= 0) then modInnateEnergy = modOptions.innateenergy end -- spawn units for teamNum,team in ipairs(Spring.GetTeamList()) do -- clear resources -- actual resources are set depending on spawned unit and setup if not loadGame then local pregameUnitStorage = (campaignBattleID and GetPregameUnitStorage(team)) or 0 Spring.SetTeamResource(team, "es", pregameUnitStorage + HIDDEN_STORAGE) Spring.SetTeamResource(team, "ms", pregameUnitStorage + HIDDEN_STORAGE) Spring.SetTeamResource(team, "energy", 0) Spring.SetTeamResource(team, "metal", 0) end --check if player resigned before game started local _,playerID,_,isAI = spGetTeamInfo(team, false) local deadPlayer = (not isAI) and IsTeamResigned(team) if team ~= gaiateam and not deadPlayer then local luaAI = Spring.GetTeamLuaAI(team) if DELAYED_AFK_SPAWN then if not (luaAI and string.find(string.lower(luaAI), "chicken")) then waitingForComm[team] = true end end if COOP_MODE then -- 1 start unit per player local playerlist = Spring.GetPlayerList(team, true) playerlist = workAroundSpecsInTeamZero(playerlist, team) if playerlist and (#playerlist > 0) then for i=1,#playerlist do local _,_,spec = spGetPlayerInfo(playerlist[i], false) if (not spec) then SpawnStartUnit(team, playerlist[i]) end end else -- AI etc. SpawnStartUnit(team, nil, true) end else -- no COOP_MODE if (playerID) then local _,_,spec,teamID = spGetPlayerInfo(playerID, false) if (teamID == team and not spec) then isAI = false else playerID = nil end end SpawnStartUnit(team, playerID, isAI) end -- extra comms local playerlist = Spring.GetPlayerList(team, true) playerlist = workAroundSpecsInTeamZero(playerlist, team) if playerlist then for i = 1, #playerlist do local customKeys = select(10, Spring.GetPlayerInfo(playerlist[i])) if customKeys and customKeys.extracomm then for j = 1, tonumber(customKeys.extracomm) do Spring.Echo("Spawing a commander") SpawnStartUnit(team, playerlist[i], false, true) end end end end end end end function gadget:RecvSkirmishAIMessage(aiTeam, dataStr) -- perhaps this should be a global relay mode somewhere instead local command = "ai_commander:"; if dataStr:find(command,1,true) then local name = dataStr:sub(command:len()+1); CallAsTeam(aiTeam, function() Spring.SendLuaRulesMsg(command..aiTeam..":"..name); end) end end local function SetStartLocation(teamID, x, z) luaSetStartPositions[teamID] = {x = x, y = Spring.GetGroundHeight(x,z), z = z} end GG.SetStartLocation = SetStartLocation function gadget:RecvLuaMsg(msg, playerID) if msg:find("faction:",1,true) then local side = msg:sub(9) playerSides[playerID] = side commChoice[playerID] = nil -- unselect existing custom comm, if any StartUnitPicked(playerID, side) elseif msg:find("customcomm:",1,true) then local name = msg:sub(12) commChoice[playerID] = name StartUnitPicked(playerID, name) elseif msg:find("ai_commander:",1,true) then local command = "ai_commander:"; local offset = msg:find(":",command:len()+1,true); local teamID = msg:sub(command:len()+1,offset-1); local name = msg:sub(offset+1); teamID = tonumber(teamID); local _,_,_,isAI = Spring.GetTeamInfo(teamID, false) if(isAI) then -- this is actually an AI local aiid, ainame, aihost = Spring.GetAIInfo(teamID) if (aihost == playerID) then -- it's actually controlled by the local host local unitDef = UnitDefNames[name]; if unitDef then -- the requested unit actually exists if aiCommanders[unitDef.id] then Spring.SetTeamRulesParam(teamID, "start_unit", name); end end end end elseif (msg:find("ai_start_pos:",1,true) and setAiStartPos) then local msg_table = Spring.Utilities.ExplodeString(':', msg) if msg_table then local teamID, x, z = tonumber(msg_table[2]), tonumber(msg_table[3]), tonumber(msg_table[4]) if teamID then local _,_,_,isAI = Spring.GetTeamInfo(teamID, false) if isAI and x and z then SetStartLocation(teamID, x, z) Spring.MarkerAddPoint(x, 0, z, "AI " .. teamID .. " start") end end end end end function gadget:GameFrame(n) CheckOrderRemoval() if n == (COMM_SELECT_TIMEOUT) then for team in pairs(waitingForComm) do local _,playerID = spGetTeamInfo(team, false) teamSides[team] = DEFAULT_UNIT_NAME --playerSides[playerID] = "basiccomm" scheduledSpawn[n] = scheduledSpawn[n] or {} scheduledSpawn[n][#scheduledSpawn[n] + 1] = {team, playerID} -- playerID is needed here so the player can't spawn coms 2 times in COOP_MODE mode end end if scheduledSpawn[n] then for _, spawnData in pairs(scheduledSpawn[n]) do local teamID, playerID = spawnData[1], spawnData[2] local canSpawn = SpawnStartUnit(teamID, playerID, false, false, true) if (canSpawn) then -- extra comms local customKeys = select(10, playerID) if playerID and customKeys and customKeys.extracomm then for j=1, tonumber(customKeys.extracomm) do SpawnStartUnit(teamID, playerID, false, true, true) end end end end scheduledSpawn[n] = nil end end function gadget:Shutdown() --Spring.Echo("<Start Unit Setup> Going to sleep...") end function gadget:Load(zip) if not (GG.SaveLoad and GG.SaveLoad.ReadFile) then Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Start Unit Setup failed to access save/load API") return end loadGame = true local data = GG.SaveLoad.ReadFile(zip, "Start Unit Setup", SAVE_FILE) or {} -- load data wholesale waitingForComm = data.waitingForComm or {} scheduledSpawn = data.scheduledSpawn or {} playerSides = data.playerSides or {} teamSides = data.teamSides or {} commSpawnedPlayer = data.commSpawnedPlayer or {} commSpawnedTeam = data.commSpawnedTeam or {} UpdateSaveReferences() end -------------------------------------------------------------------- -- unsynced code -------------------------------------------------------------------- else function gadget:Initialize() gadgetHandler:AddSyncAction('CommSelection',CommSelection) --Associate "CommSelected" event to "WrapToLuaUI". Reference: http://springrts.com/phpbb/viewtopic.php?f=23&t=24781 "Gadget and Widget Cross Communication" end function CommSelection(_,playerID, startUnit) if (Script.LuaUI('CommSelection')) then --if there is widgets subscribing to "CommSelection" function then: local isSpec = Spring.GetSpectatingState() --receiver player is spectator? local myAllyID = Spring.GetMyAllyTeamID() --receiver player's alliance? local _,_,_,_, eventAllyID = Spring.GetPlayerInfo(playerID, false) --source alliance? if isSpec or myAllyID == eventAllyID then Script.LuaUI.CommSelection(playerID, startUnit) --send to widgets as event end end end local MakeRealTable = Spring.Utilities.MakeRealTable function gadget:Save(zip) if VFS.FileExists("mission.lua") then -- nothing to do return end if not GG.SaveLoad then Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Start Unit Setup failed to access save/load API") return end local toSave = { waitingForComm = MakeRealTable(SYNCED.waitingForComm, "Start setup (waitingForComm)"), scheduledSpawn = MakeRealTable(SYNCED.scheduledSpawn, "Start setup (scheduledSpawn)"), playerSides = MakeRealTable(SYNCED.playerSides, "Start setup (playerSides)"), teamSides = MakeRealTable(SYNCED.teamSides, "Start setup (teamSides)"), commSpawnedPlayer = MakeRealTable(SYNCED.commSpawnedPlayer, "Start setup (commSpawnedPlayer)"), commSpawnedTeam = MakeRealTable(SYNCED.commSpawnedTeam, "Start setup (commSpawnedTeam)"), } GG.SaveLoad.WriteSaveData(zip, SAVE_FILE, toSave) end end
gpl-2.0
b03605079/darkstar
scripts/zones/Chamber_of_Oracles/npcs/Pedestal_of_Ice.lua
12
2252
----------------------------------- -- Area: Chamber of Oracles -- NPC: Pedestal of Ice -- Involved in Zilart Mission 7 -- @pos 199 -2 36 168 ------------------------------------- package.loaded["scripts/zones/Chamber_of_Oracles/TextIDs"] = nil; ------------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Chamber_of_Oracles/TextIDs"); ------------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ZilartStatus = player:getVar("ZilartStatus"); if(player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then if(player:hasKeyItem(ICE_FRAGMENT)) then player:delKeyItem(ICE_FRAGMENT); player:setVar("ZilartStatus",ZilartStatus + 8); player:messageSpecial(YOU_PLACE_THE,ICE_FRAGMENT); if(ZilartStatus == 255) then player:startEvent(0x0001); end elseif (ZilartStatus == 255) then -- Execute cutscene if the player is interrupted. player:startEvent(0x0001); else player:messageSpecial(IS_SET_IN_THE_PEDESTAL,ICE_FRAGMENT); end elseif(player:hasCompletedMission(ZILART,THE_CHAMBER_OF_ORACLES)) then player:messageSpecial(HAS_LOST_ITS_POWER,ICE_FRAGMENT); else player:messageSpecial(PLACED_INTO_THE_PEDESTAL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(csid == 0x0001) then player:addTitle(LIGHTWEAVER); player:setVar("ZilartStatus",2); player:addKeyItem(PRISMATIC_FRAGMENT); player:messageSpecial(KEYITEM_OBTAINED,PRISMATIC_FRAGMENT); player:completeMission(ZILART,THE_CHAMBER_OF_ORACLES); player:addMission(ZILART,RETURN_TO_DELKFUTTS_TOWER); end end;
gpl-3.0
thesrinivas/rakshak
rakshak-probe/userspace/elasticsearch-lua/tests/integration/SearchTest.lua
2
1206
-- Tests: -- search() -- -- Setting up environment local _ENV = lunit.TEST_CASE "tests.integration.SearchTest" function test() operations.bulkIndex(dataset) -- Simple query search local res = operations.searchQuery("type:PushEvent") assert_equal(103, res.hits.total) -- Simple body search local res = operations.searchBody{ query = { match = { type = "PushEvent" } } } assert_equal(103, res.hits.total) -- Aggregation search local res = operations.searchBody{ aggs = { maxActorId = { max = { field = "actor.id" } } } } assert_equal(10364741.0, res.aggregations.maxActorId.value) -- Regex Search local res = operations.searchBody{ query = { regexp = { type = { value = "pusheven." } } } } assert_equal(103, res.hits.total) -- Search template local res = operations.searchTemplate{ inline = { query = { match = { type = "{{query_string}}" } } }, params = { query_string = "PushEvent" } } assert_equal(103, res.hits.total) operations.bulkDeleteExistingDocuments(dataset) end
gpl-2.0
Aquanim/Zero-K
scripts/tankaa.lua
5
3020
include "constants.lua" include "trackControl.lua" include "pieceControl.lua" local base, turret, guns, aim = piece("base", "turret", "guns", "aim") local barrels = {piece("barrel1", "barrel2")} local flares = {piece("flare1", "flare2")} local a1, a2, neck = piece("a1", "a2", "neck") local currentGun = 1 local isAiming = false local disarmed = false local stuns = {false, false, false} local SIG_AIM = 1 local function RestoreAfterDelay() SetSignalMask (SIG_AIM) Sleep (5000) Turn (turret, y_axis, 0, 1) Turn ( guns, x_axis, 0, 1) WaitForTurn (turret, y_axis) WaitForTurn ( guns, x_axis) isAiming = false end local StopPieceTurn = GG.PieceControl.StopTurn function Stunned(stun_type) stuns[stun_type] = true disarmed = true Signal (SIG_AIM) StopPieceTurn(turret, y_axis) StopPieceTurn( guns, x_axis) end function Unstunned(stun_type) stuns[stun_type] = false if not stuns[1] and not stuns[2] and not stuns[3] then disarmed = false StartThread(RestoreAfterDelay) end end function script.StartMoving() StartThread(TrackControlStartMoving) end function script.StopMoving() TrackControlStopMoving() end function script.AimFromWeapon() return aim end function script.QueryWeapon() return flares[currentGun] end function script.AimWeapon(num, heading, pitch) Signal (SIG_AIM) SetSignalMask (SIG_AIM) isAiming = true while disarmed do Sleep (33) end local slowMult = (Spring.GetUnitRulesParam (unitID, "baseSpeedMult") or 1) Turn (turret, y_axis, heading, 10*slowMult) Turn ( guns, x_axis, -pitch, 10*slowMult) WaitForTurn (turret, y_axis) WaitForTurn ( guns, x_axis) StartThread (RestoreAfterDelay) return true end function script.FireWeapon() EmitSfx(flares[currentGun], 1024) local barrel = barrels[currentGun] Move (barrel, z_axis, -14) Move (barrel, z_axis, 0, 21) currentGun = 3 - currentGun end function script.Create() local trax = {piece("tracks1", "tracks2", "tracks3", "tracks4")} Show(trax[1]) -- in case current != 1 before luarules reload Hide(trax[2]) Hide(trax[3]) Hide(trax[4]) InitiailizeTrackControl({ wheels = { large = {piece('wheels1', 'wheels2', 'wheels3')}, small = {piece('wheels4', 'wheels5', 'wheels6')}, }, tracks = trax, signal = 2, smallSpeed = math.rad(360), smallAccel = math.rad(60), smallDecel = math.rad(120), largeSpeed = math.rad(540), largeAccel = math.rad(90), largeDecel = math.rad(180), trackPeriod = 50, }) StartThread (GG.Script.SmokeUnit, unitID, {base, turret, guns}) end local explodables = {a1, a2, neck, turret, barrels[1], barrels[2]} function script.Killed (recentDamage, maxHealth) local severity = recentDamage / maxHealth local brutal = severity > 0.5 local sfx = SFX local explodeFX = sfx.FALL + (brutal and (sfx.SMOKE + sfx.FIRE) or 0) local rand = math.random for i = 1, #explodables do if rand() < severity then Explode (explodables[i], explodeFX) end end if brutal then Explode(base, sfx.SHATTER) return 2 else return 1 end end
gpl-2.0
geoffleyland/rima
lua/tests/rima/types/number_t.lua
1
4691
-- Copyright (c) 2009-2012 Incremental IP Limited -- see LICENSE for license information local number_t = require("rima.types.number_t") local object = require("rima.lib.object") local undefined_t = require("rima.types.undefined_t") local interface = require("rima.interface") ------------------------------------------------------------------------------ return function(T) local E = interface.eval local R = interface.R local sum = interface.sum T:test(object.typeinfo(number_t:new()).number_t, "typeinfo(number_t:new()).number_t") T:test(object.typeinfo(number_t:new()).undefined_t, "typeinfo(number_t:new()).undefined_t") T:check_equal(object.typename(number_t:new()), "number_t", "typename(number_t:new()) == 'number_t'") T:expect_error(function() number_t:new(2, 1) end, "lower bound must be <= upper bound") T:expect_error(function() number_t:new(1.1, 2, true) end, "lower bound is not integer") T:expect_error(function() number_t:new(1, 2.1, true) end, "upper bound is not integer") T:check_equal(number_t:new(0, 1, true), "binary") T:check_equal(number_t:new(0, 1), "0 <= * <= 1, * real") T:check_equal(number_t:new(1, 100, true), "1 <= * <= 100, * integer") T:check_equal(number_t:new(0, 1, true):describe("a"), "a binary") T:check_equal(number_t:new(0, 1):describe("b"), "0 <= b <= 1, b real") T:check_equal(number_t:new(1, 100, true):describe("c"), "1 <= c <= 100, c integer") T:test(not number_t:new():includes("a string"), "number does not include string") T:test(number_t:new(0, 1):includes(0), "(0, 1) includes 0") T:test(number_t:new(0, 1):includes(1), "(0, 1) includes 2") T:test(number_t:new(0, 1):includes(0.5), "(0, 1) includes 0.5") T:test(not number_t:new(0, 1):includes(-0.1), "(0, 1) does not include -0.1") T:test(not number_t:new(0, 1):includes(2), "(0, 1) does not include 2") T:test(number_t:new(0, 1, true):includes(0), "(0, 1, int) includes 0") T:test(number_t:new(0, 1, true):includes(1), "(0, 1, int) includes 2") T:test(not number_t:new(0, 1, true):includes(0.5), "(0, 1, int) does not include 0.5") T:test(not number_t:new(0, 1, true):includes(-0.1), "(0, 1, int) does not include -0.1") T:test(not number_t:new(0, 1, true):includes(2), "(0, 1, int) does not include 2") T:test(not number_t:new(0, 1):includes(undefined_t:new()), "(0, 1) does not include undefined") T:test(number_t:new(0, 1):includes(number_t:new(0, 1)), "(0, 1) includes (0, 1)") T:test(number_t:new(0, 1):includes(number_t:new(0.1, 1)), "(0, 1) includes (0.1, 1)") T:test(not number_t:new(0, 1):includes(number_t:new(0, 1.1)), "(0, 1) does not include (0, 1.1)") T:test(number_t:new(0, 1):includes(number_t:new(0, 1, true)), "(0, 1) includes (0, 1, int)") T:test(not number_t:new(0, 1, true):includes(number_t:new(0, 1)), "(0, 1, int) does not include (0, 1)") T:check_equal(object.typename(number_t.free()), "number_t", "typename(number_t.free()) == 'number_t'") T:test(number_t.free():includes(number_t.free()), "free includes free") T:test(not number_t.free(1):includes(number_t.free()), "free(1) does not include free") T:check_equal(object.typename(number_t.positive()), "number_t", "typename(number_t.positive()) == 'number_t'") T:expect_ok(function() number_t.positive(3, 5) end) T:expect_error(function() number_t.positive(-3, 5) end, "bounds for positive variables must be positive") T:check_equal(object.typename(number_t.negative()), "number_t", "typename(number_t.negative()) == 'number_t'") T:expect_ok(function() number_t.negative(-3, -1) end) T:expect_error(function() number_t.negative(-3, 5) end, "bounds for negative variables must be negative") T:check_equal(object.typename(number_t.integer()), "number_t", "typename(number_t.integer()) == 'number_t'") T:expect_ok(function() number_t.integer(-5, 5) end) T:expect_error(function() number_t.integer(0.5, 5) end, "lower bound is not integer") T:expect_ok(function() number_t.binary() end) do local x = R"x" local S1 = { x = 1 } local S2 = { x = number_t:new() } T:expect_error(function() E(x.a, S1) end, "error indexing 'x' as 'x.a': can't index a number") T:expect_error(function() E(x.a, S2) end, "error indexing 'x' as 'x.a': can't index a number") end do local x = R"x" local S1 = { x = {1} } local S2 = { x = {number_t:new()} } local e = sum{x=x}(x.a) T:expect_error(function() E(e, S1) end, "error indexing 'x%[1%]' as 'x%[1%]%.a': can't index a number") T:expect_error(function() E(e, S2) end, "error indexing 'x%[1%]' as 'x%[1%]%.a': can't index a number") end end ------------------------------------------------------------------------------
mit
b03605079/darkstar
scripts/zones/RuAun_Gardens/npcs/HomePoint#2.lua
12
1249
----------------------------------- -- Area: RuAun_Gardens -- NPC: HomePoint#2 -- @pos -499 -42 167 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RuAun_Gardens/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 60); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Anubhav652/GTW-RPG
[resources]/GTWvehicles/vehicle_server.lua
1
12078
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- --[[ Bind the L key to toggle vehicle lights ]]-- function resource_load() local players = getElementsByType("player") for k,v in pairs(players) do bindKey(v, "l", "down", toggle_lights, "Lights on/off") end end addEventHandler("onResourceStart", resourceRoot, resource_load) function apply_key_binds() bindKey(source, "l", "down", toggle_lights, "Lights on/off") end addEventHandler("onPlayerJoin", root, apply_key_binds) --[[ Helper function for vehicle rental charges ]]-- function pay_vehicle_rent(plr, amount) paymentsCounter[plr] = (paymentsCounter[plr] or 0) + amount end --[[ Client want to spawn a vehicle ]]-- function spawn_vehicle(vehID, rot, price, extra, spawnx, spawny, spawnz) if isElement(client) and vehID and rot and price then local money = getPlayerMoney(client) if money >= price and getPlayerWantedLevel(client) == 0 and getElementInterior(client) == 0 then if isElement(vehicles[client]) then destroy_vehicle(client, true) end if vehID then if vehID == 592 or vehID == 577 or vehID == 553 then local playeraccount = getPlayerAccount(client) local pilot_progress = tonumber(getAccountData(playeraccount, "GTWdata_stats_pilot_progress")) or 0 if pilot_progress < 40 then exports.GTWtopbar:dm("Your pilot license doesn't allow large aircraft yet! (Must be above 40)", client, 255, 0, 0) return end end local x,y,z = getElementPosition(client) if spawnx and spawny and spawnz then x,y,z = spawnx,spawny,spawnz end vehicles[client] = createVehicle(vehID, x, y, z+1.5, 0, 0, rot) setElementHealth(vehicles[client], (getElementHealth(vehicles[client]))) setVehicleHandling(vehicles[client], "headLight ", "big") setVehicleHandling(vehicles[client], "tailLight", "big") -- Semi truck trailers if vehID == 403 or vehID == 514 or vehID == 515 then if extra ~= "" then if extra == "Fuel" then vehID = 584 end if extra == "Trailer 1" then vehID = 435 end if extra == "Trailer 2" then vehID = 450 end if extra == "Trailer 3" then vehID = 591 end trailers[client] = { } trailers[client][1] = createVehicle(vehID, x, y, z, 0, 0, rot) setElementHealth(trailers[client][1], (getElementHealth(trailers[client][1]))) --triggerClientEvent(root, "GTWvehicles.onStreamOut", root, trailers[client]) --attachTrailerToVehicle(vehicles[client], trailers[client]) setElementData(vehicles[client], "GTWvehicles.isTrailerTowingVehile", true) setElementData(vehicles[client], "GTWvehicles.attachedTrailer", trailers[client][1]) setElementData(trailers[client][1], "GTWvehicles.isTrailer", true) setElementData(trailers[client][1], "GTWvehicles.towingVehicle", vehicles[client]) attachElements(trailers[client][1], vehicles[client], 0, -10) setElementSyncer(trailers[client][1], client) setTimer(detachElements, 50, 1, trailers[client][1]) setTimer(attachTrailerToVehicle, 100, 1, vehicles[client], trailers[client][1]) -- Dual trailers if supported if vehID == 591 then local second_trailer = createVehicle(435, x, y, z, 0, 0, rot) local second_tower = createVehicle(515, x, y, z, 0, 0, rot) setElementHealth(second_trailer, (getElementHealth(second_trailer))) setElementHealth(second_tower, (getElementHealth(second_tower))) attachElements(second_tower, trailers[client][1], 0, 0, 0.5) setElementCollisionsEnabled(second_tower, false) setElementAlpha(second_tower, 0) attachElements(second_trailer, second_tower, 0, -10) setElementSyncer(second_trailer, client) setTimer(detachElements, 50, 1, second_trailer) setTimer(attachTrailerToVehicle, 100, 1, second_tower, second_trailer) -- Save element pointers for deletion setElementData(vehicles[client], "GTWvehicles.second_tower", second_tower) setElementData(trailers[client][1], "GTWvehicles.second_trailer", second_trailer) end end end -- Train cars if vehID == 537 or vehID == 538 or vehID == 449 then trailers[client] = { } setTrainDirection(vehicles[client], true) if vehID == 537 then vehID = 569 end if vehID == 538 then vehID = 570 end local carriage = nil local carriage2 = vehicles[client] local playeraccount = getPlayerAccount(client) --[[local train_stops = tonumber(getAccountData(playeraccount, "GTWdata_stats_train_stops")) or 0 local tram_stops = tonumber(getAccountData(playeraccount, "GTWdata_stats_tram_stops")) or 0]]-- local numberOfCarriages = tonumber(extra) or 2 -- Extra freight engines local engines = 1 if numberOfCarriages > 3 and (getElementModel(vehicles[client]) == 538 or getElementModel(vehicles[client]) == 537) then carriage = createVehicle(getElementModel(vehicles[client]), x, y, z, 0, 0, rot) setElementHealth(carriage, (getElementHealth(carriage))) triggerClientEvent(root, "GTWvehicles.onStreamOut", root, carriage) attachTrailerToVehicle(carriage2, carriage) carriage2 = carriage numberOfCarriages = numberOfCarriages - 1 engines = engines + 1 table.insert(trailers[client], carriage) setTimer(setTrainDirection, 1000, 1, carriage, not getTrainDirection(vehicles[client])) end -- Add train carriages for c=1, numberOfCarriages do carriage = createVehicle(vehID, x, y, z, 0, 0, rot) setElementHealth ( carriage, ( getElementHealth(carriage) ) * 4 ) if vehID == 569 then local container_array = {3566, 3568, 3569} local container = createObject(container_array[math.random(#container_array)], x,y,z, 0,0,0, true) setObjectScale(container, 0.8) attachElements(container, carriage, 0,0,0.8, 0,0,0) setElementData(carriage, "GTWvehicles.container", container) end triggerClientEvent(root, "GTWvehicles.onStreamOut", root, carriage) attachTrailerToVehicle(carriage2, carriage) table.insert(trailers[client], carriage) carriage2 = carriage end if numberOfCarriages < 1 then numberOfCarriages = 1 end setElementData(client, "GTWvehicles.numberOfCars", numberOfCarriages) setTimer(display_message, 350, 1, "Train set up: "..engines.." engines and: "..numberOfCarriages.." cars", client, 0, 255, 0) end setElementData(vehicles[client], "vehicleFuel", math.random(90,100)) setElementData(vehicles[client], "owner", getAccountName(getPlayerAccount(client))) setElementData(client, "currVeh", getElementModel(vehicles[client])) warpPedIntoVehicle(client, vehicles[client]) -- Start the rental price counter paymentsCounter[client] = price paymentsHolder[client] = setTimer(pay_vehicle_rent, 60000, 0, client, price) exports.GTWtopbar:dm("You will pay: "..price.."$/minute to use this vehicle", client, 255, 200, 0) end elseif getElementInterior(client) > 0 then exports.GTWtopbar:dm("Vehicles can not be used inside!", client, 255, 0, 0) elseif money < price then exports.GTWtopbar:dm("You don't have enought money to use this vehicle!", client, 255, 0, 0) end triggerClientEvent(client, "GTWvehicles.closeWindow", root) end end addEvent("GTWvehicles.spawnvehicle", true) addEventHandler("GTWvehicles.spawnvehicle", resourceRoot, spawn_vehicle) --[[ Set the color of the new vehicle ]]-- function set_vehicle_color(m_type) if isElement(vehicles[client]) then local p_text, free_fuel, r1,g1,b1, r2,g2,b2 = unpack(properties[m_type]) if p_text ~= "" then setVehiclePlateText(vehicles[client], p_text) end if free_fuel then setElementData(vehicles[client], "vehicleOccupation", true) -- Free fuel end if r1 and g1 and b1 and r2 and g2 and b2 and r1 > -1 then setVehicleColor(vehicles[client], r1,g1,b1, r2,g2,b2) if trailers[client] then for k,v in pairs(trailers[client]) do if isElement(v) then setVehicleColor(v, r1,g1,b1, r2,g2,b2) end end end end end end addEvent("GTWvehicles.colorvehicle", true) addEventHandler("GTWvehicles.colorvehicle", root, set_vehicle_color) --[[ Cleanup and destroy vehicle ]]-- function destroy_vehicle(plr, force_delete) if not force_delete then force_delete = false end if vehicles[plr] and isElement(vehicles[plr]) and (not getVehicleOccupant(vehicles[plr]) or force_delete) then -- Clean up second trailers for semi trucks if trailers[plr] and isElement(trailers[plr][1]) and getElementData(trailers[plr][1], "GTWvehicles.second_trailer") then destroyElement(getElementData(trailers[plr][1], "GTWvehicles.second_trailer")) end if getElementData(vehicles[plr], "GTWvehicles.second_tower") then destroyElement(getElementData(vehicles[plr], "GTWvehicles.second_tower")) end if getPedOccupiedVehicle(plr) and force_delete ~= true then return exports.GTWtopbar:dm("Exit your vehicle before removing it!", plr, 255, 0, 0) end if trailers[plr] and #trailers[plr] > 0 then for k,v in ipairs(trailers[plr]) do if isElement(v) then detachTrailerFromVehicle(v) if getElementData(v, "GTWvehicles.container") then destroyElement(getElementData(v, "GTWvehicles.container")) end destroyElement(v) end end end if isElement(vehicles[plr]) then for k,v in ipairs(getAttachedElements(vehicles[plr])) do destroyElement(v) end destroyElement(vehicles[plr]) end triggerEvent("GTWvehicles.onDestroyVehilce", plr, plr) setElementData(plr, "currVeh", 0) if isTimer(paymentsHolder[plr]) then killTimer(paymentsHolder[plr]) end takePlayerMoney(plr, paymentsCounter[plr] or 0) exports.GTWtopbar:dm("Rental cost was: "..tostring(paymentsCounter[plr] or 0).."$", plr, 0, 255, 0) else exports.GTWtopbar:dm("You don't have a vehicle to destroy!", plr, 255, 0, 0) end end function player_quit() destroy_vehicle(source, true) end function player_logout(playeraccount, _) destroy_vehicle(source, true) end addCommandHandler("djv", destroy_vehicle) addCommandHandler("rrv", destroy_vehicle) addEventHandler("onPlayerQuit", root, player_quit) addEventHandler("onPlayerLogout", root, player_logout) function removeTimer(thePlayer, seat, jacked) if isTimer(gearTimers[source]) then killTimer(gearTimers[source]) end end addEventHandler("onVehicleExit", getRootElement(), removeTimer) -- Remove/respawn broken vehicles and clean up function cleanUp() if isElement(source) and not getElementData(source, "owner") then setTimer(destroy_vehicle, 330000, 1, source) elseif isElement(source) and getElementData(source, "owner") then setTimer(respawn_vehicle, 330000, 1, source) end end addEventHandler("onVehicleExplode", getRootElement(), cleanUp) function respawn_vehicle(veh) if isElement(veh) then respawnVehicle(veh) end end -- Recursively destroys entire trains consisting of attached carriages or traielrs function destroyVehicleTrain(veh) if veh and isElement(veh) and getVehicleTowedByVehicle(veh) then destroyVehicleTrain(getVehicleTowedByVehicle(veh)) if veh and getVehicleTowedByVehicle(veh) and isElement(getVehicleTowedByVehicle(veh)) then destroyElement(getVehicleTowedByVehicle(veh)) end end end addEventHandler("onElementDestroy", getRootElement(), function() if getElementType(source) == "vehicle" then destroyVehicleTrain(source) end end)
gpl-3.0
b03605079/darkstar
scripts/globals/spells/luminohelix.lua
22
1719
-------------------------------------- -- Spell: Luminohelix -- Deals light damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --get helix acc/att merits local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT); --calculate raw damage local dmg = calculateMagicDamage(35,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); dmg = dmg + caster:getMod(MOD_HELIX_EFFECT); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,merit*3); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,merit*2); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); local dot = dmg; --add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); -- calculate Damage over time dot = target:magicDmgTaken(dot); utils.clamp(dot, 0, 99999); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); target:addStatusEffect(EFFECT_HELIX,dot,3,duration); return dmg; end;
gpl-3.0
node-wot/node-wot
lua_examples/yet-another-ds18b20.lua
79
1924
------------------------------------------------------------------------------ -- DS18B20 query module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("ds18b20.lua").read(4, function(r) for k, v in pairs(r) do print(k, v) end end) ------------------------------------------------------------------------------ local M do local bit = bit local format_addr = function(a) return ("%02x-%02x%02x%02x%02x%02x%02x"):format( a:byte(1), a:byte(7), a:byte(6), a:byte(5), a:byte(4), a:byte(3), a:byte(2) ) end local read = function(pin, cb, delay) local ow = require("ow") -- get list of relevant devices local d = { } ow.setup(pin) ow.reset_search(pin) while true do tmr.wdclr() local a = ow.search(pin) if not a then break end if ow.crc8(a) == 0 and (a:byte(1) == 0x10 or a:byte(1) == 0x28) then d[#d + 1] = a end end -- conversion command for all ow.reset(pin) ow.skip(pin) ow.write(pin, 0x44, 1) -- wait a bit tmr.alarm(0, delay or 100, 0, function() -- iterate over devices local r = { } for i = 1, #d do tmr.wdclr() -- read rom command ow.reset(pin) ow.select(pin, d[i]) ow.write(pin, 0xBE, 1) -- read data local x = ow.read_bytes(pin, 9) if ow.crc8(x) == 0 then local t = (x:byte(1) + x:byte(2) * 256) -- negatives? if bit.isset(t, 15) then t = 1 - bit.bxor(t, 0xffff) end -- NB: temperature in Celsius * 10^4 t = t * 625 -- NB: due 850000 means bad pullup. ignore if t ~= 850000 then r[format_addr(d[i])] = t end d[i] = nil end end cb(r) end) end -- expose M = { read = read, } end return M
mit
nasomi/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Ragyaya.lua
38
1043
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ragyaya -- Type: Standard NPC -- @zone: 94 -- @pos -95.376 -3 60.795 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0196); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
actboy168/YDWE
Development/Component/plugin/w3x2lni/script/gui/backend.lua
3
4020
local process = require 'bee.subprocess' local proto = require 'share.protocol' local lang = require 'share.lang' local backend = {} backend.message = '' backend.title = '' backend.progress = nil backend.report = {} local mt = {} mt.__index = mt function mt:unpack_out(bytes) while true do local res = proto.recv(self.proto_s, bytes) if not res then break end bytes = '' self.output[#self.output+1] = res end end function mt:update_out() if not self.out_rd then return end local n = process.peek(self.out_rd) if n == nil then self.out_rd:close() self.out_rd = nil return end if n == 0 or n == nil then return end local r = self.out_rd:read(n) if r then self:unpack_out(r) return end self.out_rd:close() self.out_rd = nil end function mt:update_err() if not self.err_rd then return end local n = process.peek(self.err_rd) if n == nil then self.err_rd:close() self.err_rd = nil return end if n == 0 then return end local r = self.err_rd:read(n) if r then self.error = self.error .. r return end self.err_rd:close() self.err_rd = nil end function mt:update_pipe() self:update_out() self:update_err() if not self.process:is_running() then self:unpack_out() if self.err_rd then self.error = self.error .. self.err_rd:read 'a' end self.exit_code = self.process:wait() self.process:kill() return true end return false end local function push_report(type, level, value, tip) local name = level .. type if not backend.report[name] then backend.report[name] = {} end table.insert(backend.report[name], {value, tip}) end function mt:update_message() while true do local msg = table.remove(self.output, 1) if not msg then break end local key, value = msg.type, msg.args if key == 'progress' then backend.progress = value * 100 elseif key == 'report' then push_report(value.type, value.level, value.content, value.tip) elseif key == 'title' then backend.title = value elseif key == 'text' then backend.message = value elseif key == 'exit' then backend.lastword = value end end end function mt:update() if self.exited then return end if not self.closed then self.closed = self:update_pipe() end if #self.output > 0 then self:update_message() end if #self.error > 0 then while #self.output > 0 do self:update_message() end self.output = {} if self.out_rd then self.out_rd:close() self.out_rd = nil end backend.message = lang.ui.FAILED end if self.closed then while #self.output > 0 do self:update_message() end self.exited = true return true end return false end function backend:init(application, currentdir) self.application = application self.currentdir = currentdir end function backend:clean() self.message = '' self.progress = nil self.report = {} self.lastword = nil end function backend:open(entry, commandline) local p = process.spawn { self.application:string(), '-E', '-e', ('package.cpath=[[%s]]'):format(package.cpath), entry, commandline, console = 'disable', stdout = true, stderr = true, cwd = self.currentdir:string(), } if not p then return end self:clean() return setmetatable({ process = p, out_rd = p.stdout, err_rd = p.stderr, output = {}, error = '', proto_s = {}, }, mt) end return backend
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Waters/npcs/Ajen-Myoojen.lua
38
1044
----------------------------------- -- Area: Windurst Waters -- NPC: Ajen-Myoojen -- Type: Standard NPC -- @zone: 238 -- @pos -44.542 -5.999 238.996 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x010e); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/West_Ronfaure/npcs/Stone_Monument.lua
32
1287
----------------------------------- -- Area: West Ronfaure -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos -183.734 -12.678 -395.722 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00001); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Samanj5/spam-is-alive
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
nasomi/darkstar
scripts/globals/mobskills/Emetic_Discharge.lua
44
2025
--------------------------------------------- -- Emetic Discharge -- Family: Bloodlapper and Brummbar -- Description: Transfers all ailments to target -- Type: Enfeebling -- Utsusemi/Blink absorb: 2-3 shadows -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local removables = {EFFECT_FLASH, EFFECT_BLINDNESS, EFFECT_ELEGY, EFFECT_REQUIEM, EFFECT_PARALYSIS, EFFECT_POISON, EFFECT_CURSE_I, EFFECT_CURSE_II, EFFECT_DISEASE, EFFECT_PLAGUE, EFFECT_WEIGHT, EFFECT_BIND, EFFECT_BIO, EFFECT_DIA, EFFECT_BURN, EFFECT_FROST, EFFECT_CHOKE, EFFECT_RASP, EFFECT_SHOCK, EFFECT_DROWN, EFFECT_STR_DOWN, EFFECT_DEX_DOWN, EFFECT_VIT_DOWN, EFFECT_AGI_DOWN, EFFECT_INT_DOWN, EFFECT_MND_DOWN, EFFECT_CHR_DOWN, EFFECT_ADDLE, EFFECT_SLOW, EFFECT_HELIX, EFFECT_ACCURACY_DOWN, EFFECT_ATTACK_DOWN, EFFECT_EVASION_DOWN, EFFECT_DEFENSE_DOWN, EFFECT_MAGIC_ACC_DOWN, EFFECT_MAGIC_ATK_DOWN, EFFECT_MAGIC_EVASION_DOWN, EFFECT_MAGIC_DEF_DOWN, EFFECT_MAX_TP_DOWN, EFFECT_MAX_MP_DOWN, EFFECT_MAX_HP_DOWN}; local dmg = utils.takeShadows(target, 1, math.random(2,3)); --removes 2-3 shadows --if removed more shadows than were up or there weren't any if (dmg > 0) then for i, effect in ipairs(removables) do if (mob:hasStatusEffect(effect)) then local statusEffect = mob:getStatusEffect(effect); target:addStatusEffect(effect, statusEffect:getPower(), statusEffect:getTickCount(), statusEffect:getDuration()); mob:delStatusEffect(effect); end; end; end; skill:setMsg(MSG_NO_EFFECT); -- no effect return 0; end;
gpl-3.0
keharriso/love-nuklear
example/overview.lua
1
3326
-- An overview of most of the supported widgets. local checkA = {value = false} local checkB = {value = true} local radio = {value = 'A'} local selectA = {value = false} local selectB = {value = true} local slider = {value = 0.2} local progress = {value = 1} local colorPicker = {value = '#ff0000'} local property = {value = 6} local edit = {value = 'Edit text'} local comboA = {value = 1, items = {'A', 'B', 'C'}} local scissorActive = false return function (ui) if ui:windowBegin('Overview', 100, 100, 600, 450, 'border', 'movable', 'title') then ui:menubarBegin() ui:layoutRow('dynamic', 30, 1) if ui:menuBegin('Menu', nil, 120, 90) then ui:layoutRow('dynamic', 40, 1) ui:menuItem('Item A') ui:menuItem('Item B') ui:menuItem('Item C') ui:menuEnd() end ui:menubarEnd() ui:layoutRow('dynamic', 375, 3) if ui:groupBegin('Group 1', 'border') then ui:layoutRow('dynamic', 30, 1) ui:label('Left label') ui:label('Centered label', 'centered') ui:label('Right label', 'right') ui:label('Colored label', 'left', '#ff0000') if ui:treePush('tab', 'Tree Tab') then if ui:treePush('node', 'Tree Node 1') then ui:label('Label 1') ui:treePop() end if ui:treePush('node', 'Tree Node 2') then ui:label('Label 2') ui:treePop() end ui:treePop() end ui:spacing(1) if ui:button('Button') then print('button pressed!') end ui:spacing(1) ui:checkbox('Checkbox A', checkA) ui:checkbox('Checkbox B', checkB) if ui:button('Scissor') then scissorActive = not scissorActive end ui:groupEnd() end if ui:groupBegin('Group 2', 'border') then ui:layoutRow('dynamic', 30, 1) ui:label('Radio buttons:') ui:layoutRow('dynamic', 30, 3) ui:radio('A', radio) ui:radio('B', radio) ui:radio('C', radio) ui:layoutRow('dynamic', 30, 1) ui:selectable('Selectable A', selectA) ui:selectable('Selectable B', selectB) ui:layoutRow('dynamic', 30, {.35, .65}) ui:label('Slider:') ui:slider(0, slider, 1, 0.05) ui:label('Progress:') ui:progress(progress, 10, true) ui:layoutRow('dynamic', 30, 2) ui:spacing(2) ui:label('Color picker:') ui:button(nil, colorPicker.value) ui:layoutRow('dynamic', 90, 1) ui:colorPicker(colorPicker) ui:groupEnd() end if ui:groupBegin('Group 3', 'border') then ui:layoutRow('dynamic', 30, 1) ui:property('Property', 0, property, 10, 0.25, 0.05) ui:spacing(1) ui:label('Edit:') ui:layoutRow('dynamic', 90, 1) ui:edit('box', edit) ui:layoutRow('dynamic', 5, 1) ui:spacing(1) ui:layoutRow('dynamic', 30, 1) ui:label('Combobox:') ui:combobox(comboA, comboA.items) ui:layoutRow('dynamic', 5, 1) ui:spacing(1) ui:layoutRow('dynamic', 30, 1) if ui:widgetIsHovered() then ui:tooltip('Test tooltip') end local x, y, w, h = ui:widgetBounds() if ui:contextualBegin(100, 100, x, y, w, h) then ui:layoutRow('dynamic', 30, 1) ui:contextualItem('Item A') ui:contextualItem('Item B') ui:contextualEnd() end ui:label('Contextual (Right click me)') ui:groupEnd() end end ui:windowEnd() if(scissorActive) then love.graphics.setScissor() love.graphics.clear() love.graphics.setScissor(130, 130, 500, 400) else love.graphics.setScissor() end end
mit
Metalab/loungelights
old/init.lua
1
3860
wifi.setmode(wifi.STATION) gpio.mode(1,gpio.OUTPUT) gpio.mode(2,gpio.OUTPUT) gpio.mode(0,gpio.OUTPUT) gpio.mode(8,gpio.OUTPUT) spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, spi.DATABITS_8, 0) wifi.sta.config("metalab", "") wifi.sta.connect() tmr.alarm(0, 1000, 1, function() if wifi.sta.status() == 5 then startMqttClient() tmr.stop(0) else print("Connect AP, Waiting...") end end) function startMqttClient() currentLights = {100,200,50,100,255} m = mqtt.Client("lights", 120, "lichter", "password") m:on("connect", function(con) print ("connected") end) m:on("offline", function(con) print ("offline") end) m:on("message", function(conn, topic, data) print(topic .. ":" ) if data ~= nil then print(data) currentLights = parseData(data,currentLights) if currentLights[1] == 0 then gpio.write(2,gpio.HIGH) end if currentLights[2] == 0 then gpio.write(8,gpio.HIGH) end if currentLights[1] > 0 then gpio.write(1,gpio.HIGH) end if currentLights[2] > 0 then gpio.write(0,gpio.HIGH) end pwm.setup(4,1000,currentLights[1]*4+3) pwm.setup(6,1000,currentLights[2]*4+3) pwm.start(4) pwm.start(6) spi.send(1,{currentLights[3],currentLights[4],currentLights[5]}) end end) -- IP-Adress of Mqtt Server (probably the IP-Adress of Slackomatic) -- You must send a message to /lights (or whatever other name you chose for the channel) to control the lights. -- The default port is 1883. -- The expected format is explained below. m:connect("10.20.30.186", 1883, 0, function(conn) print("connected") m:subscribe("/lights",0, function(conn) print("subscribe success") end) m:publish("/lights","Lights ready. Read the comments in the Lua-Code if you don't know what to do.",0,0, function(conn) print("sent") end) end) end -- The expected string format is: w,a,r,g,b where w = white, a = amber, r = red, g = green, b = blue. -- If left out variable remains at current value. -- Example: 123,,,255, means: white = 123, a,r and b are left unchanged and g = 255 = max. -- Which exact characters are used for separation doesn't matter. 123,,,255, is to interpreted the same as as 123:::255: for instance. -- Values are to in [0,255]. Larger Values will be assumed to be 255 = max. -- A way to send "delta" values that define a new color by adding an offset to the current color should be implemented BY YOU, -- because frankly, I don't give a damn. It might be a practical way to implement the red alert or some other annoying shit. -- "Deltas" (i.e. "offsets") are recognized by the sign (+ or -) at their beginning. -- Example: 100,+3,,-4,0 means: w = 100, a = a+3, r unchanged, g = g-4, b = 0. function parseData(data,current) leng = string.len(data) color = 1 num = "" vals = {} for i = 1, leng, 1 do if color > 5 then break end ch = string.sub(data,i,i) if tonumber(ch) ~= nil then num = num..ch else if num == "" then vals[color] = current[color] color = color + 1 else number = tonumber(num) if number > 255 then number = 255 end vals[color] = number num = "" color = color + 1 end end end number = tonumber(num) if number > 255 then number = 255 end vals[5] = number return vals end
gpl-3.0
nasomi/darkstar
scripts/globals/spells/bluemagic/infrasonics.lua
18
1442
----------------------------------------- -- Spell: Infrasonics -- Lowers the evasion of enemies within a fan-shaped area originating from the caster -- Spell cost: 42 MP -- Monster Type: Lizards -- Spell Type: Magical (Ice) -- Blue Magic Points: 4 -- Stat Bonus: INT+1 -- Level: 65 -- Casting Time: 5 seconds -- Recast Time: 120 seconds -- Magic Bursts on: Induration, Distortion, Darkness -- Combos: None ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_EVASION_DOWN; local dINT = caster:getStat(MOD_MND) - target:getStat(MOD_MND); local resist = applyResistance(caster,spell,target,dINT,BLUE_SKILL); local duration = 60 * resist; local power = 20; if (resist > 0.5) then -- Do it! if (target:addStatusEffect(typeEffect,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end; return typeEffect; end;
gpl-3.0
znek/xupnpd
src/ui/api_v2.lua
2
2025
function ui_api_v_2_call(args,data,ip,url,methtod) methtod = string.upper(methtod) route = string.split(url, '/') res = nil if methtod == "GET" then if route[1] == 'playlist' then res = {} local d=util.dir(cfg.playlists_path) if d then table.sort(d) for i,j in ipairs(d) do if string.find(j,'.+%.m3u$') then local fname=util.urlencode(j) table.insert (res,{ name = j, id = string.gsub(j, ".m3u", '') } ) --http.send(string.format('<tr><td><a href=\'/ui/show?fname=%s&%s\'>%s</a> [<a href=\'/ui/remove?fname=%s&%s\'>x</a>]</td></tr>\n',fname,'',j,fname,'')) end end end end if route[1] =='status' then res = {} res['uuid'] = http_vars.uuid res['description'] = http_vars.description res['uptime'] = http_vars.uptime() res['fname'] = http_vars.fname res['port'] = http_vars.port res['name'] = http_vars.name res['version'] = http_vars.version res['manufacturer_url'] = http_vars.manufacturer_url res['manufacturer'] = http_vars.manufacturer res['interface'] = http_vars.interface res['url'] = http_vars.url end end if methtod == "DELETE" then if route[1] == "playlist" then res = {success = false} if route[2] then local real_name=util.urldecode( route[2] ) .. ".m3u" local path=cfg.playlists_path if args.feed=='1' then path=cfg.feeds_path end if os.remove(path..real_name) then core.sendevent('reload') res.success = true else res = nil end end end end if res then http_send_headers(200,'json') http.send(json.encode(res)) else http_send_headers(404) http.send(json.encode(url)) end end
gpl-2.0
minaevmike/rspamd
src/plugins/lua/mid.lua
1
3181
--[[ Copyright (c) 2016, Alexander Moisseev <moiseev@mezonplus.ru> 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. ]]-- --[[ MID plugin - suppress INVALID_MSGID and MISSING_MID for messages originating from listed valid DKIM domains with missed or known proprietary Message-IDs ]]-- local rspamd_logger = require "rspamd_logger" local rspamd_regexp = require "rspamd_regexp" local settings = { url = '', symbol_known_mid = 'KNOWN_MID', symbol_known_no_mid = 'KNOWN_NO_MID', symbol_invalid_msgid = 'INVALID_MSGID', symbol_missing_mid = 'MISSING_MID', symbol_dkim_allow = 'R_DKIM_ALLOW', csymbol_invalid_msgid_allowed = 'INVALID_MSGID_ALLOWED', csymbol_missing_mid_allowed = 'MISSING_MID_ALLOWED', } local map = {} local function known_mid_cb(task) local re = {} local header = task:get_header('Message-Id') local das = task:get_symbol(settings['symbol_dkim_allow']) if das and das[1] and das[1]['options'] then for _,dkim_domain in ipairs(das[1]['options']) do local v = map:get_key(dkim_domain) if v then if v == '' then if not header then task:insert_result(settings['symbol_known_no_mid'], 1, dkim_domain) return end else re[dkim_domain] = rspamd_regexp.create_cached(v) if header and re[dkim_domain] and re[dkim_domain]:match(header) then task:insert_result(settings['symbol_known_mid'], 1, dkim_domain) return end end end end end end local opts = rspamd_config:get_all_opt('mid') if opts then for k,v in pairs(opts) do settings[k] = v end if settings['url'] and #settings['url'] > 0 then map = rspamd_config:add_map ({ url = settings['url'], type = 'map', description = 'Message-IDs map' }) local id = rspamd_config:register_symbol({ name = 'KNOWN_MID_CALLBACK', type = 'callback', callback = known_mid_cb }) rspamd_config:register_symbol({ name = settings['symbol_known_mid'], parent = id, type = 'virtual' }) rspamd_config:register_symbol({ name = settings['symbol_known_no_mid'], parent = id, type = 'virtual' }) rspamd_config:add_composite(settings['csymbol_invalid_msgid_allowed'], settings['symbol_known_mid'] .. ' & ' .. settings['symbol_invalid_msgid']) rspamd_config:add_composite(settings['csymbol_missing_mid_allowed'], settings['symbol_known_no_mid'] .. ' & ' .. settings['symbol_missing_mid']) rspamd_config:register_dependency(id, settings['symbol_dkim_allow']) else rspamd_logger.infox(rspamd_config, 'url is not specified, disabling module') end end
apache-2.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_system/leds.lua
83
3272
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("system", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Configuration"), translate("Customizes the behaviour of the device <abbr title=\"Light Emitting Diode\">LED</abbr>s if possible.")) local sysfs_path = "/sys/class/leds/" local leds = {} local fs = require "nixio.fs" local util = require "nixio.util" if fs.access(sysfs_path) then leds = util.consume((fs.dir(sysfs_path))) end if #leds == 0 then return m end s = m:section(TypedSection, "led", "") s.anonymous = true s.addremove = true function s.parse(self, ...) TypedSection.parse(self, ...) os.execute("/etc/init.d/led enable") end s:option(Value, "name", translate("Name")) sysfs = s:option(ListValue, "sysfs", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Name")) for k, v in ipairs(leds) do sysfs:value(v) end s:option(Flag, "default", translate("Default state")).rmempty = false trigger = s:option(ListValue, "trigger", translate("Trigger")) local triggers = fs.readfile(sysfs_path .. leds[1] .. "/trigger") for t in triggers:gmatch("[%w-]+") do trigger:value(t, translate(t:gsub("-", ""))) end delayon = s:option(Value, "delayon", translate ("On-State Delay")) delayon:depends("trigger", "timer") delayoff = s:option(Value, "delayoff", translate ("Off-State Delay")) delayoff:depends("trigger", "timer") dev = s:option(ListValue, "_net_dev", translate("Device")) dev.rmempty = true dev:value("") dev:depends("trigger", "netdev") function dev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function dev.write(self, section, value) m.uci:set("system", section, "dev", value) end function dev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end for k, v in pairs(luci.sys.net.devices()) do if v ~= "lo" then dev:value(v) end end mode = s:option(MultiValue, "mode", translate("Trigger Mode")) mode.rmempty = true mode:depends("trigger", "netdev") mode:value("link", translate("Link On")) mode:value("tx", translate("Transmit")) mode:value("rx", translate("Receive")) usbdev = s:option(ListValue, "_usb_dev", translate("USB Device")) usbdev:depends("trigger", "usbdev") usbdev.rmempty = true usbdev:value("") function usbdev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function usbdev.write(self, section, value) m.uci:set("system", section, "dev", value) end function usbdev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end for p in nixio.fs.glob("/sys/bus/usb/devices/[0-9]*/manufacturer") do local id = p:match("%d+-%d+") local mf = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/manufacturer") or "?" local pr = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/product") or "?" usbdev:value(id, "%s (%s - %s)" %{ id, mf, pr }) end return m
gpl-2.0
EnjoyHacking/nn
Euclidean.lua
24
5711
local Euclidean, parent = torch.class('nn.Euclidean', 'nn.Module') function Euclidean:__init(inputSize,outputSize) parent.__init(self) self.weight = torch.Tensor(inputSize,outputSize) self.gradWeight = torch.Tensor(inputSize,outputSize) -- state self.gradInput:resize(inputSize) self.output:resize(outputSize) self.fastBackward = true self:reset() end function Euclidean:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(1)) end if nn.oldSeed then for i=1,self.weight:size(2) do self.weight:select(2, i):apply(function() return torch.uniform(-stdv, stdv) end) end else self.weight:uniform(-stdv, stdv) end end local function view(res, src, ...) local args = {...} if src:isContiguous() then res:view(src, table.unpack(args)) else res:reshape(src, table.unpack(args)) end end function Euclidean:updateOutput(input) -- lazy initialize buffers self._input = self._input or input.new() self._weight = self._weight or self.weight.new() self._expand = self._expand or self.output.new() self._expand2 = self._expand2 or self.output.new() self._repeat = self._repeat or self.output.new() self._repeat2 = self._repeat2 or self.output.new() local inputSize, outputSize = self.weight:size(1), self.weight:size(2) -- y_j = || w_j - x || = || x - w_j || if input:dim() == 1 then view(self._input, input, inputSize, 1) self._expand:expandAs(self._input, self.weight) self._repeat:resizeAs(self._expand):copy(self._expand) self._repeat:add(-1, self.weight) self.output:norm(self._repeat, 2, 1) self.output:resize(outputSize) elseif input:dim() == 2 then local batchSize = input:size(1) view(self._input, input, batchSize, inputSize, 1) self._expand:expand(self._input, batchSize, inputSize, outputSize) -- make the expanded tensor contiguous (requires lots of memory) self._repeat:resizeAs(self._expand):copy(self._expand) self._weight:view(self.weight, 1, inputSize, outputSize) self._expand2:expandAs(self._weight, self._repeat) if torch.type(input) == 'torch.CudaTensor' then -- requires lots of memory, but minimizes cudaMallocs and loops self._repeat2:resizeAs(self._expand2):copy(self._expand2) self._repeat:add(-1, self._repeat2) else self._repeat:add(-1, self._expand2) end self.output:norm(self._repeat, 2, 2) self.output:resize(batchSize, outputSize) else error"1D or 2D input expected" end return self.output end function Euclidean:updateGradInput(input, gradOutput) if not self.gradInput then return end self._div = self._div or input.new() self._output = self._output or self.output.new() self._gradOutput = self._gradOutput or input.new() self._expand3 = self._expand3 or input.new() if not self.fastBackward then self:updateOutput(input) end local inputSize, outputSize = self.weight:size(1), self.weight:size(2) --[[ dy_j -2 * (w_j - x) x - w_j ---- = --------------- = ------- dx 2 || w_j - x || y_j --]] -- to prevent div by zero (NaN) bugs self._output:resizeAs(self.output):copy(self.output):add(0.0000001) view(self._gradOutput, gradOutput, gradOutput:size()) self._div:cdiv(gradOutput, self._output) if input:dim() == 1 then self._div:resize(1, outputSize) self._expand3:expandAs(self._div, self.weight) if torch.type(input) == 'torch.CudaTensor' then self._repeat2:resizeAs(self._expand3):copy(self._expand3) self._repeat2:cmul(self._repeat) else self._repeat2:cmul(self._repeat, self._expand3) end self.gradInput:sum(self._repeat2, 2) self.gradInput:resizeAs(input) elseif input:dim() == 2 then local batchSize = input:size(1) self._div:resize(batchSize, 1, outputSize) self._expand3:expand(self._div, batchSize, inputSize, outputSize) if torch.type(input) == 'torch.CudaTensor' then self._repeat2:resizeAs(self._expand3):copy(self._expand3) self._repeat2:cmul(self._repeat) else self._repeat2:cmul(self._repeat, self._expand3) end self.gradInput:sum(self._repeat2, 3) self.gradInput:resizeAs(input) else error"1D or 2D input expected" end return self.gradInput end function Euclidean:accGradParameters(input, gradOutput, scale) local inputSize, outputSize = self.weight:size(1), self.weight:size(2) scale = scale or 1 --[[ dy_j 2 * (w_j - x) w_j - x ---- = --------------- = ------- dw_j 2 || w_j - x || y_j --]] -- assumes a preceding call to updateGradInput if input:dim() == 1 then self.gradWeight:add(-scale, self._repeat2) elseif input:dim() == 2 then self._sum = self._sum or input.new() self._sum:sum(self._repeat2, 1) self._sum:resize(inputSize, outputSize) self.gradWeight:add(-scale, self._sum) else error"1D or 2D input expected" end end function Euclidean:type(type, tensorCache) if type then -- prevent premature memory allocations self._input = nil self._output = nil self._gradOutput = nil self._weight = nil self._div = nil self._sum = nil self._expand = nil self._expand2 = nil self._expand3 = nil self._repeat = nil self._repeat2 = nil end return parent.type(self, type, tensorCache) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Saluhwa.lua
34
1475
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Saluhwa -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,SALUHWA_SHOP_DIALOG); stock = {0x3002,605, -- Mapple Shield (Available when AC is in the city) 0x3003,1815, -- Elm Shield (Available when AC is in the city) 0x3004,4980, -- Mahogany Shield (Available when AC is in the city) 0x3005,15600, -- Oak Shield (Available when AC is in the city) 0x3007,64791} -- Round Shield (Available when AC is in the city) showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
shangjiyu/luci-with-extra
build/luadoc/luadoc/taglet/standard/tags.lua
32
5542
------------------------------------------------------------------------------- -- 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, tonumber = assert, type, tostring, tonumber module "luadoc.taglet.standard.tags" ------------------------------------------------------------------------------- local function author (tag, block, text) block[tag] = block[tag] or {} if not text then luadoc.logger:warn("author `name' not defined [["..text.."]]: skipping") return end table.insert (block[tag], text) end ------------------------------------------------------------------------------- -- Set the class of a comment block. Classes can be "module", "function", -- "table". The first two classes are automatic, extracted from the source code local function class (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function cstyle (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function sort (tag, block, text) block[tag] = tonumber(text) or 0 end ------------------------------------------------------------------------------- local function copyright (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function description (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function field (tag, block, text) if block["class"] ~= "table" then luadoc.logger:warn("documenting `field' for block that is not a `table'") end block[tag] = block[tag] or {} local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") assert(name, "field name not defined") table.insert(block[tag], name) block[tag][name] = desc end ------------------------------------------------------------------------------- -- Set the name of the comment block. If the block already has a name, issue -- an error and do not change the previous value local function name (tag, block, text) if block[tag] and block[tag] ~= text then luadoc.logger:error(string.format("block name conflict: `%s' -> `%s'", block[tag], text)) end block[tag] = text end ------------------------------------------------------------------------------- -- Processes a parameter documentation. -- @param tag String with the name of the tag (it must be "param" always). -- @param block Table with previous information about the block. -- @param text String with the current line being processed. local function param (tag, block, text) block[tag] = block[tag] or {} -- TODO: make this pattern more flexible, accepting empty descriptions local _, _, name, desc = string.find(text, "^([_%w%.]+)%s+(.*)") if not name then luadoc.logger:warn("parameter `name' not defined [["..text.."]]: skipping") return end local i = table.foreachi(block[tag], function (i, v) if v == name then return i end end) if i == nil then luadoc.logger:warn(string.format("documenting undefined parameter `%s'", name)) table.insert(block[tag], name) end block[tag][name] = desc end ------------------------------------------------------------------------------- local function release (tag, block, text) block[tag] = text end ------------------------------------------------------------------------------- local function ret (tag, block, text) tag = "ret" if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- -- @see ret local function see (tag, block, text) -- see is always an array block[tag] = block[tag] or {} -- remove trailing "." text = string.gsub(text, "(.*)%.$", "%1") local s = util.split("%s*,%s*", text) table.foreachi(s, function (_, v) table.insert(block[tag], v) end) end ------------------------------------------------------------------------------- -- @see ret local function usage (tag, block, text) if type(block[tag]) == "string" then block[tag] = { block[tag], text } elseif type(block[tag]) == "table" then table.insert(block[tag], text) else block[tag] = text end end ------------------------------------------------------------------------------- local handlers = {} handlers["author"] = author handlers["class"] = class handlers["cstyle"] = cstyle handlers["copyright"] = copyright handlers["description"] = description handlers["field"] = field handlers["name"] = name handlers["param"] = param handlers["release"] = release handlers["return"] = ret handlers["see"] = see handlers["sort"] = sort handlers["usage"] = usage ------------------------------------------------------------------------------- function handle (tag, block, text) if not handlers[tag] then luadoc.logger:error(string.format("undefined handler for tag `%s'", tag)) return end if text then text = text:gsub("`([^\n]-)`", "<code>%1</code>") text = text:gsub("`(.-)`", "<pre>%1</pre>") end -- assert(handlers[tag], string.format("undefined handler for tag `%s'", tag)) return handlers[tag](tag, block, text) end
apache-2.0
nasomi/darkstar
scripts/zones/Woh_Gates/Zone.lua
34
1270
----------------------------------- -- -- Zone: Woh Gates -- ----------------------------------- package.loaded["scripts/zones/Woh_Gates/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Woh_Gates/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(479,0,139,140); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Southern_San_dOria/npcs/Helbort.lua
17
2420
----------------------------------- -- Area: Southern San d'Oria -- NPC: Helbort -- Starts and Finished Quest: A purchase of Arms -- @zone 230 -- @pos 71 -1 65 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) quest_fas = player:getQuestStatus(SANDORIA,FATHER_AND_SON); -- 1st Quest in Series quest_poa = player:getQuestStatus(SANDORIA,A_PURCHASE_OF_ARMS); -- 2nd Quest in Series if (player:getFameLevel(SANDORIA) >= 2 and quest_fas == QUEST_COMPLETED and quest_poa == QUEST_AVAILABLE) then player:startEvent(0x0252); -- Start quest A Purchase of Arms elseif (quest_poa == QUEST_ACCEPTED and player:hasKeyItem(WEAPONS_RECEIPT) == true) then player:startEvent(0x025f); -- Finish A Purchase of Arms quest else player:startEvent(0x0251); -- Standard Dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0252 and option == 0) then player:addQuest(SANDORIA, A_PURCHASE_OF_ARMS); player:addKeyItem(WEAPONS_ORDER); player:messageSpecial(KEYITEM_OBTAINED,WEAPONS_ORDER); elseif (csid == 0x025f) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17090); -- Elm Staff else player:addTitle(ARMS_TRADER); player:delKeyItem(WEAPONS_RECEIPT); player:addItem(17090); player:messageSpecial(ITEM_OBTAINED,17090); -- Elm Staff player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA, A_PURCHASE_OF_ARMS); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5ct.lua
17
2441
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: _5ct (Magical Gizmo) #5 -- Involved In Mission: The Horutoto Ruins Experiment ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- The Magical Gizmo Number, this number will be compared to the random -- value created by the mission The Horutoto Ruins Experiment, when you -- reach the Gizmo Door and have the cutscene local magical_gizmo_no = 5; -- of the 6 -- Check if we are on Windurst Mission 1-1 if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 2) then -- Check if we found the correct Magical Gizmo or not if (player:getVar("MissionStatus_rv") == magical_gizmo_no) then player:startEvent(0x0038); else if (player:getVar("MissionStatus_op5") == 2) then -- We've already examined this player:messageSpecial(EXAMINED_RECEPTACLE); else -- Opened the wrong one player:startEvent(0x0039); end end end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); -- If we just finished the cutscene for Windurst Mission 1-1 -- The cutscene that we opened the correct Magical Gizmo if (csid == 0x0038) then player:setVar("MissionStatus",3); player:setVar("MissionStatus_rv", 0); player:addKeyItem(CRACKED_MANA_ORBS); player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS); elseif (csid == 0x0039) then -- Opened the wrong one player:setVar("MissionStatus_op5", 2); -- Give the message that thsi orb is not broken player:messageSpecial(NOT_BROKEN_ORB); end end;
gpl-3.0
coolflyreg/gs
3rd/skynet-mingw/test/testredis2.lua
82
1043
local skynet = require "skynet" local redis = require "redis" local db function add1(key, count) local t = {} for i = 1, count do t[2*i -1] = "key" ..i t[2*i] = "value" .. i end db:hmset(key, table.unpack(t)) end function add2(key, count) local t = {} for i = 1, count do t[2*i -1] = "key" ..i t[2*i] = "value" .. i end table.insert(t, 1, key) db:hmset(t) end function __init__() db = redis.connect { host = "127.0.0.1", port = 6300, db = 0, auth = "foobared" } print("dbsize:", db:dbsize()) local ok, msg = xpcall(add1, debug.traceback, "test1", 250000) if not ok then print("add1 failed", msg) else print("add1 succeed") end local ok, msg = xpcall(add2, debug.traceback, "test2", 250000) if not ok then print("add2 failed", msg) else print("add2 succeed") end print("dbsize:", db:dbsize()) print("redistest launched") end skynet.start(__init__)
gpl-2.0
shangjiyu/luci-with-extra
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/network.lua
14
4221
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" m = Map("network", translate("Interfaces")) m.pageaction = false m:section(SimpleSection).template = "admin_network/iface_overview" if fs.access("/etc/init.d/dsl_control") then dsl = m:section(TypedSection, "dsl", translate("DSL")) dsl.anonymous = true annex = dsl:option(ListValue, "annex", translate("Annex")) annex:value("a", translate("Annex A + L + M (all)")) annex:value("b", translate("Annex B (all)")) annex:value("j", translate("Annex J (all)")) annex:value("m", translate("Annex M (all)")) annex:value("bdmt", translate("Annex B G.992.1")) annex:value("b2", translate("Annex B G.992.3")) annex:value("b2p", translate("Annex B G.992.5")) annex:value("at1", translate("ANSI T1.413")) annex:value("admt", translate("Annex A G.992.1")) annex:value("alite", translate("Annex A G.992.2")) annex:value("a2", translate("Annex A G.992.3")) annex:value("a2p", translate("Annex A G.992.5")) annex:value("l", translate("Annex L G.992.3 POTS 1")) annex:value("m2", translate("Annex M G.992.3")) annex:value("m2p", translate("Annex M G.992.5")) tone = dsl:option(ListValue, "tone", translate("Tone")) tone:value("", translate("auto")) tone:value("a", translate("A43C + J43 + A43")) tone:value("av", translate("A43C + J43 + A43 + V43")) tone:value("b", translate("B43 + B43C")) tone:value("bv", translate("B43 + B43C + V43")) xfer_mode = dsl:option(ListValue, "xfer_mode", translate("Encapsulation mode")) xfer_mode:value("atm", translate("ATM (Asynchronous Transfer Mode)")) xfer_mode:value("ptm", translate("PTM/EFM (Packet Transfer Mode)")) line_mode = dsl:option(ListValue, "line_mode", translate("DSL line mode")) line_mode:value("", translate("auto")) line_mode:value("adsl", translate("ADSL")) line_mode:value("vdsl", translate("VDSL")) firmware = dsl:option(Value, "firmware", translate("Firmware File")) m.pageaction = true end -- Show ATM bridge section if we have the capabilities if fs.access("/usr/sbin/br2684ctl") then atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"), translate("ATM bridges expose encapsulated ethernet in AAL5 " .. "connections as virtual Linux network interfaces which can " .. "be used in conjunction with DHCP or PPP to dial into the " .. "provider network.")) atm.addremove = true atm.anonymous = true atm.create = function(self, section) local sid = TypedSection.create(self, section) local max_unit = -1 m.uci:foreach("network", "atm-bridge", function(s) local u = tonumber(s.unit) if u ~= nil and u > max_unit then max_unit = u end end) m.uci:set("network", sid, "unit", max_unit + 1) m.uci:set("network", sid, "atmdev", 0) m.uci:set("network", sid, "encaps", "llc") m.uci:set("network", sid, "payload", "bridged") m.uci:set("network", sid, "vci", 35) m.uci:set("network", sid, "vpi", 8) return sid end atm:tab("general", translate("General Setup")) atm:tab("advanced", translate("Advanced Settings")) vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)")) vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)")) encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode")) encaps:value("llc", translate("LLC")) encaps:value("vc", translate("VC-Mux")) atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number")) unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number")) payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode")) payload:value("bridged", translate("bridged")) payload:value("routed", translate("routed")) m.pageaction = true end local network = require "luci.model.network" if network:has_ipv6() then local s = m:section(NamedSection, "globals", "globals", translate("Global network options")) local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix")) o.datatype = "ip6addr" o.rmempty = true m.pageaction = true end return m
apache-2.0
nasomi/darkstar
scripts/zones/Kazham/npcs/Mijeh_Sholpoilo.lua
15
1102
----------------------------------- -- Area: Kazham -- NPC: Mijeh Sholpoilo -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00A8); -- scent from Blue Rafflesias else player:startEvent(0x003F); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
dani-sj/danibot01
plugins/cpu.lua
244
1893
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!$ uptime') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!$ uptime", patterns = {"^!$ uptime", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
dmccuskey/dmc-states-mixin
dmc_corona/lib/dmc_lua/lua_patch.lua
44
7239
--====================================================================-- -- lua_patch.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 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 Patch --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --====================================================================-- --== Imports local Utils = {} -- make copying easier --====================================================================-- --== Setup, Constants local lua_patch_data = { string_format_active = false, table_pop_active = false, print_output_active = false } local PATCH_TABLE_POP = 'table-pop' local PATCH_STRING_FORMAT = 'string-format' local PATCH_PRINT_OUTPUT = 'print-output' local addTablePopPatch, removeTablePopPatch local addStringFormatPatch, removeStringFormatPatch local addPrintOutputPatch, removePrintOutputPatch local sfmt = string.format local tstr = tostring --====================================================================-- --== Support Functions --== Start: copy from lua_utils ==-- -- 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 --== End: copy from lua_utils ==-- local function addLuaPatch( input ) -- print( "Patch.addLuaPatch" ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT } else error( sfmt( "Lua Patch:: unknown patch type '%s'", type(input) ) ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then addTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then addStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then addPrintOutputPatch() else error( sfmt( "Lua Patch:: unknown patch name '%s'", tostring( patch ) ) ) end end end local function addAllLuaPatches() addLuaPatch( nil ) end local function removeLuaPatch( input ) -- print( "Patch.removeLuaPatch", input ) if type(input)=='table' then -- pass elseif type(input)=='string' then input = { input } elseif type(input)=='nil' then input = { PATCH_TABLE_POP, PATCH_STRING_FORMAT } else error( "Lua Patch:: unknown patch type '" .. type(input) .. "'" ) end for i, patch_name in ipairs( input ) do if patch_name == PATCH_TABLE_POP then removeTablePopPatch() elseif patch_name == PATCH_STRING_FORMAT then removeStringFormatPatch() elseif patch_name == PATCH_PRINT_OUTPUT then removePrintOutputPatch() else error( "Lua Patch:: unknown patch name '" .. tostring( patch ) .. "'" ) end end end local function removeAllLuaPatches() addAllLuaPatches( nil ) end --====================================================================-- --== Setup Patches --====================================================================-- --======================================================-- -- Python-style string formatting addStringFormatPatch = function() if lua_patch_data.string_format_active == false then print( "Lua Patch::activating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = Utils.stringFormatting lua_patch_data.string_format_active = true end end removeStringFormatPatch = function() if lua_patch_data.string_format_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_STRING_FORMAT .. "'" ) getmetatable("").__mod = nil lua_patch_data.string_format_active = false end end --======================================================-- -- Python-style table pop() method -- tablePop() -- local function tablePop( t, v ) assert( type(t)=='table', "Patch:tablePop, expected table arg for pop()") assert( v, "Patch:tablePop, expected key" ) local res = t[v] t[v] = nil return res end addTablePopPatch = function() if lua_patch_data.table_pop_active == false then print( "Lua Patch::activating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = tablePop lua_patch_data.table_pop_active = true end end removeTablePopPatch = function() if lua_patch_data.table_pop_active == true then print( "Lua Patch::deactivating patch '" .. PATCH_TABLE_POP .. "'" ) table.pop = nil lua_patch_data.table_pop_active = false end end --======================================================-- -- Print Output functions local function printNotice( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "NOTICE" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end local function printWarning( str, params ) params = params or {} if params.newline==nil then params.newline=true end --==-- local prefix = "WARNING" local nlstr = "\n\n" if not params.newline then nlstr='' end print( sfmt( "%s[%s] %s%s", nlstr, prefix, tstr(str), nlstr ) ) end addPrintOutputPatch = function() if lua_patch_data.print_output_active == false then _G.pnotice = printNotice _G.pwarn = printWarning lua_patch_data.print_output_active = true end end removePrintOutputPatch = function() if lua_patch_data.print_output_active == true then _G.pnotice = nil _G.pwarn = nil lua_patch_data.print_output_active = false end end --====================================================================-- --== Patch Facade --====================================================================-- return { PATCH_TABLE_POP=PATCH_TABLE_POP, PATCH_STRING_FORMAT=PATCH_STRING_FORMAT, PATCH_PRINT_OUTPUT=PATCH_PRINT_OUTPUT, addPatch = addLuaPatch, addAllPatches=addAllLuaPatches, removePatch=removeLuaPatch, removeAllPatches=removeAllLuaPatch, }
mit
shakfu/start-vm
config/artful/awesome/vicious/contrib/pop_all.lua
4
1430
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Boris Bolgradov <> -- -- This widget type depends on luasocket. -- -- Widget arguments are host, port, username and -- password, i.e.: -- {"mail.myhost.com", 110, "John", "132435"} --------------------------------------------------- -- {{{ Grab environment local tonumber = tonumber local setmetatable = setmetatable local sock_avail, socket = pcall(function() return require("socket") end) -- }}} -- POP: provides the count of new messages in a POP3 mailbox -- vicious.contrib.pop local pop_all = {} -- {{{ POP3 count widget type local function worker(format, warg) if not sock_avail or (not warg or #warg ~= 4) then return {"N/A"} end local host, port = warg[1], tonumber(warg[2]) local user, pass = warg[3], warg[4] local client = socket.tcp() client:settimeout(3) client:connect(host, port) client:receive("*l") client:send("USER " .. user .. "\r\n") client:receive("*l") client:send("PASS " .. pass .. "\r\n") client:receive("*l") client:send("STAT" .. "\r\n") local response = client:receive("*l") client:close() if response:find("%+OK") then response = response:match("%+OK (%d+)") end return {response} end -- }}} return setmetatable(pop_all, { __call = function(_, ...) return worker(...) end })
mit
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/timers/one_minute_timer.lua
1
13852
--[[ Botman - A collection of scripts for managing 7 Days to Die servers Copyright (C) 2020 Matthew Dwyer This copyright applies to the Lua source code in this Mudlet profile. Email smegzor@gmail.com URL http://botman.nz Source https://bitbucket.org/mhdwyer/botman --]] local debug function savePlayerData(steam) --dbug("savePlayerData " .. steam) fixMissingPlayer(steam) fixMissingIGPlayer(steam) -- update players table with x y z players[steam].lastAtHome = nil players[steam].protectPaused = nil players[steam].name = igplayers[steam].name players[steam].xPos = igplayers[steam].xPos players[steam].yPos = igplayers[steam].yPos players[steam].zPos = igplayers[steam].zPos players[steam].seen = botman.serverTime players[steam].playerKills = igplayers[steam].playerKills players[steam].deaths = igplayers[steam].deaths players[steam].zombies = igplayers[steam].zombies players[steam].score = igplayers[steam].score players[steam].ping = igplayers[steam].ping -- update the player record in the database updatePlayer(steam) end function everyMinute() local words, word, rday, rhour, rmin, k, v local diff, days, hours, restartTime, zombiePlayers, tempDate, playerList if not server.windowGMSG then -- fix a weird issue where the server table is not all there. In testing, after restoring the table the bot restarted itself which is what we're after here. loadServer() end windowMessage(server.windowDebug, "60 second timer\n") if not server.ServerMaxPlayerCount then -- missing ServerMaxPlayerCount so we need to re-read gg sendCommand("gg") end -- enable debug to see where the code is stopping. Any error will be after the last debug line. debug = false -- should be false unless testing if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end zombiePlayers = {} if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end if not server.delayReboot then if (botman.scheduledRestart == true) and botman.scheduledRestartPaused == false and tonumber(botman.playersOnline) > 0 and server.allowReboot == true then restartTime = botman.scheduledRestartTimestamp - os.time() if (restartTime > 60 and restartTime < 601) or (restartTime > 1139 and restartTime < 1201) or (restartTime > 1799 and restartTime < 1861) then message("say [" .. server.chatColour .. "]Rebooting in " .. os.date("%M minutes %S seconds",botman.scheduledRestartTimestamp - os.time()) .. ".[-]") end end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end for k, v in pairs(igplayers) do if not players[k].newPlayer then players[k].cash = players[k].cash + server.perMinutePayRate end if server.ServerMaxPlayerCount then if tonumber(v.afk - os.time()) < 200 and (botman.playersOnline >= server.ServerMaxPlayerCount or server.idleKickAnytime) and (accessLevel(k) > 2) and server.idleKick then message("pm " .. v.steam .. " [" .. server.warnColour .. "]You appear to be away from your keyboard. You will be kicked after " .. os.date("%M minutes %S seconds",v.afk - os.time()) .. " for being afk. If you move, talk, add or remove inventory you will not be kicked.[-]") end end if debug then dbug("steam " .. k .. " name " .. v.name) end -- save the igplayer to players savePlayerData(k) -- reload the player from the database so that we fill in any missing fields with default values loadPlayers(k) -- add or update the player record in the bots shared database insertBotsPlayer(k) if (v.killTimer == nil) then v.killTimer = 0 end v.killTimer = v.killTimer + 1 if (v.killTimer > 1) then -- clean up some tables, removing the player from them invTemp[k] = nil if (v.timeOnServer) then players[k].timeOnServer = players[k].timeOnServer + v.sessionPlaytime end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end if (os.time() - players[k].lastLogout) > 300 then players[k].relogCount = 0 end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end if (os.time() - players[k].lastLogout) < 60 then players[k].relogCount = tonumber(players[k].relogCount) + 1 else players[k].relogCount = tonumber(players[k].relogCount) - 1 if tonumber(players[k].relogCount) < 0 then players[k].relogCount = 0 end end lastHotspots[k] = nil players[k].lastLogout = os.time() if botman.dbConnected then conn:execute("DELETE FROM messageQueue WHERE recipient = " .. k) conn:execute("DELETE FROM gimmeQueue WHERE steam = " .. k) conn:execute("DELETE FROM commandQueue WHERE steam = " .. k) conn:execute("DELETE FROM playerQueue WHERE steam = " .. k) if accessLevel(k) < 3 then conn:execute("DELETE FROM memTracker WHERE steam = " .. k) end end -- the player's y coord is negative. Attempt to rescue them by sending them back to the surface. if tonumber(v.yPos) < 0 and accessLevel(k) > 2 then if not v.fallingRescue then v.fallingRescue = true sendCommand("tele " .. k .. " " .. v.xPosLastOK .. " -1 " .. v.zPosLastOK) else v.fallingRescue = nil kick(k, "You were kicked to fix you falling under the world. You can rejoin any time.") end end -- check how many claims they have placed sendCommand("llp " .. k .. " parseable") -- flag this ingame player record for deletion zombiePlayers[k] = {} if botman.botsConnected then -- update player in bots db connBots:execute("UPDATE players SET ip = '" .. players[k].ip .. "', name = '" .. escape(stripCommas(players[k].name)) .. "', online = 0 WHERE steam = " .. k .. " AND botID = " .. server.botID) end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end for k, v in pairs(zombiePlayers) do if debug then dbug("Removing zombie player " .. players[k].name .. "\n") end igplayers[k] = nil end --if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end --updateSlots() if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end -- check players table for problems and remove for k, v in pairs(players) do if (k ~= v.steam) or v.id == "-1" then players[k] = nil end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end if tonumber(botman.playersOnline) == 0 and botman.scheduledRestart and server.allowReboot and not botman.serverRebooting then irc_chat(server.ircMain, "A reboot is scheduled and nobody is on so the server is rebooting now.") botman.scheduledRestart = false botman.scheduledRestartTimestamp = os.time() botman.scheduledRestartPaused = false botman.scheduledRestartForced = false if (botman.rebootTimerID ~= nil) then killTimer(botman.rebootTimerID) end if (rebootTimerDelayID ~= nil) then killTimer(rebootTimerDelayID) end botman.rebootTimerID = nil rebootTimerDelayID = nil if not botMaintenance.lastSA then botMaintenance.lastSA = os.time() saveBotMaintenance() sendCommand("sa") else if (os.time() - botMaintenance.lastSA) > 30 then botMaintenance.lastSA = os.time() saveBotMaintenance() sendCommand("sa") end end server.delayReboot = false finishReboot() end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end if server.uptime then if (tonumber(botman.playersOnline) == 0 and tonumber(server.uptime) < 0) and (scheduledReboot ~= true) and server.allowReboot and not botman.serverRebooting then botman.rebootTimerID = tempTimer( 60, [[startReboot()]] ) scheduledReboot = true end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end -- report excessive falling blocks if tonumber(server.dropMiningWarningThreshold) > 0 then for k,v in pairs(fallingBlocks) do if tonumber(v.count) > tonumber(server.dropMiningWarningThreshold) then irc_chat(server.ircAlerts, v.count .. " blocks fell off the world in region " .. k .. " ( " .. v.x .. " " .. v.y .. " " .. v.z .. " )") alertAdmins(v.count .. " blocks fell off the world in region " .. k .. " ( " .. v.x .. " " .. v.y .. " " .. v.z .. " )", "warn") playerList = "" -- players near the falling blocks for a, b in pairs(igplayers) do dist = distancexz(v.x, v.z, b.xPos, b.zPos) if tonumber(dist) < 300 then if playerList == "" then playerList = b.name .. " (" .. string.format("%d", dist) .. ")" else playerList = playerList .. ", " .. b.name .. " (" .. string.format("%d", dist) .. ")" end end end if playerList ~= "" then irc_chat(server.ircAlerts, "Players near falling blocks and (distance): " .. playerList) alertAdmins("Players near falling blocks and (distance): " .. playerList, "warn") end end end end -- reset the fallingBlocks table fallingBlocks = {} if (server.scanZombies or server.scanEntities) and not server.lagged then if not server.useAllocsWebAPI then sendCommand("le") end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end -- save some server fields if botman.dbConnected then conn:execute("UPDATE server SET lottery = " .. server.lottery .. ", date = '" .. server.dateTest .. "', ircBotName = '" .. server.ircBotName .. "'") end if server.useAllocsWebAPI then if (botman.resendAdminList or tablelength(staffList) == 0) then if not botman.noAdminsDefined then sendCommand("admin list") end botman.resendAdminList = false end if botman.resendBanList then sendCommand("ban list") botman.resendBanList = false end if botman.resendGG then sendCommand("gg") botman.resendGG = false end if type(modVersions) ~= "table" then modVersions = {} end if botman.resendVersion or tablelength(modVersions) == 0 then sendCommand("version") botman.resendVersion = false end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end updateSlots() if debug then dbug("debug everyMinute end") end end function oneMinuteTimer() local k, v, days, hours, minutes, tempDate -- enable debug to see where the code is stopping. Any error will be after the last debug line. debug = false if botman.APICheckTimestamp then if (os.time() - botman.APICheckTimestamp) > 180 and not botman.APICheckPassed and server.allowBotRestarts then restartBot() end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end fixMissingStuff() if tonumber(server.uptime) == 0 then if server.botman and not server.stompy then sendCommand("bm-uptime") end if not server.botman and server.stompy then sendCommand("bc-time") end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end tempDate = os.date("%Y-%m-%d", os.time()) if botman.botDate == nil then botman.botDate = os.date("%Y-%m-%d", os.time()) botman.botTime = os.date("%H:%M:%S", os.time()) end -- if the bot's local date has changed, run NewBotDay if tempDate ~= botman.botDate then newBotDay() end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end botman.botDate = os.date("%Y-%m-%d", os.time()) botman.botTime = os.date("%H:%M:%S", os.time()) if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end if botman.botOffline then return end botHeartbeat() if botman.botDisabled then return end if server.useAllocsWebAPI and botman.APIOffline then sendCommand("APICheck") end if tonumber(botman.playersOnline) ~= 0 then sendCommand("gt") end if customOneMinuteTimer ~= nil then -- read the note on overriding bot code in custom/custom_functions.lua if customOneMinuteTimer() then return end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end if tablelength(players) == 0 then gatherServerData() return end if tonumber(botman.playersOnline) > 0 then if server.botman then sendCommand("bm-listplayerbed") sendCommand("bm-listplayerfriends") sendCommand("bm-anticheat report") end if tonumber(botman.playersOnline) < 25 then if server.stompy then sendCommand("bc-lp /online /filter=steamid,friends,bedroll,pack,walked,ip,level,crafted,vendor,playtime,session") end removeClaims() end if tonumber(server.maxPrisonTime) > 0 then -- check for players to release from prison for k,v in pairs(igplayers) do if tonumber(players[k].prisonReleaseTime) < os.time() and players[k].prisoner and tonumber(players[k].prisonReleaseTime) > 0 then gmsg(server.commandPrefix .. "release " .. k) else if players[k].prisoner then if players[k].prisonReleaseTime - os.time() < 86164 then days, hours, minutes = timeRemaining(players[k].prisonReleaseTime) message("pm " .. k .. " [" .. server.chatColour .. "]You will be released in about " .. days .. " days " .. hours .. " hours and " .. minutes .. " minutes.[-]") end end end end end end if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end -- build list of players that are online for the panel panelWho() -- check for timed events due to run runTimedEvents() if (debug) then dbug("debug one minute timer line " .. debugger.getinfo(1).currentline) end everyMinute() if debug then dbug("debug one minute timer end") end end
gpl-3.0
OrenjiAkira/lua-html
lib/lux/portable.lua
1
2748
--[[ -- -- Copyright (c) 2013-2016 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- This module allows for portable programming in Lua. -- It currently support versions 5.1 through 5.3. local portable = {} local lambda = require 'lux.functional' local lua_major, lua_minor = (function (a,b) return tonumber(a), tonumber(b) end) (_VERSION:match "(%d+)%.(%d+)") assert(lua_major >= 5 and lua_minor >= 1) -- for sanity local env_stack = {} local push = table.insert local pop = table.remove local function getEnv () if lua_minor <= 1 then return getfenv() else return _ENV end end local function setEnv (env) if lua_minor <= 1 then setfenv(0, env) else _ENV = env end end portable.getEnv = getEnv portable.setEnv = setEnv function portable.isVersion(major, minor) return major == lua_major and minor == lua_minor end function portable.minVersion(major, minor) return major <= lua_major and minor <= lua_minor end function portable.pushEnvironment (env) push(env_stack, getEnv()) setEnv(env) end function portable.popEnvironment () setEnv(pop(env_stack)) end if lua_minor <= 1 then table.unpack = unpack table.pack = function (...) return { n = select('#', ...), ... } end end --- Re-loads a funcion with the given env and an optional chunk name. -- It is important to note that the reloaded funcion loses its closure. -- @function loadWithEnv -- @param f The original function -- @param env The new environment -- @param[opt] source The reloaded funciton chunk name if lua_minor <= 1 then function portable.loadWithEnv(f, env, source) local loaded, err = loadstring(string.dump(f, source)) if not loaded then return nil, err end return setfenv(loaded, env) end else function portable.loadWithEnv(f, env, source) return load(string.dump(f), source, 'b', env) end end return portable
mit
kenyh0926/DBProxy
lib/active-transactions.lua
4
2681
--[[ $%BEGINLICENSE%$ Copyright (c) 2008, 2009, 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%$ --]] --[[ print the statements of all transactions as soon as one of them aborted for now we know about: * Lock wait timeout exceeded * Deadlock found when trying to get lock --]] if not proxy.global.trxs then proxy.global.trxs = { } end function read_query(packet) if packet:byte() ~= proxy.COM_QUERY then return end if not proxy.global.trxs[proxy.connection.server.thread_id] then proxy.global.trxs[proxy.connection.server.thread_id] = { } end proxy.queries:append(1, packet, { resultset_is_needed = true }) local t = proxy.global.trxs[proxy.connection.server.thread_id] t[#t + 1] = packet:sub(2) return proxy.PROXY_SEND_QUERY end function read_query_result(inj) local res = inj.resultset local flags = res.flags if res.query_status == proxy.MYSQLD_PACKET_ERR then local err_code = res.raw:byte(2) + (res.raw:byte(3) * 256) local err_sqlstate = res.raw:sub(5, 9) local err_msg = res.raw:sub(10) -- print("-- error-packet: " .. err_code) if err_code == 1205 or -- Lock wait timeout exceeded err_code == 1213 then -- Deadlock found when trying to get lock print(("[%d] received a ERR(%d, %s), dumping all active transactions"):format( proxy.connection.server.thread_id, err_code, err_msg)) for thread_id, statements in pairs(proxy.global.trxs) do for stmt_id, statement in ipairs(statements) do print((" [%d].%d: %s"):format(thread_id, stmt_id, statement)) end end end end -- we are done, free the statement list if not flags.in_trans then proxy.global.trxs[proxy.connection.server.thread_id] = nil end end function disconnect_client() proxy.global.trxs[proxy.connection.server.thread_id] = nil end
gpl-2.0
pmyadlowsky/mash
darkice.lua
1
2641
Mash.darkice = {} Mash.darkice.cmd = "darkice -v 10" Mash.darkice.client = "mashice" Mash.darkice.config = function(config, streams) local count = 0 local path = os.tmpname() file = io.open(path, "w") file:write("[general]\n") file:write("duration = 0\n") file:write("bufferSecs = 3\n") file:write("reconnect = yes\n") file:write("\n") file:write("[input]\n") file:write("device = jack\n") file:write("sampleRate = " .. Mash.samplerate() .. "\n") file:write("bitsPerSample = 16\n") file:write("channel = " .. config.channels .. "\n") file:write("jackClientName = " .. Mash.darkice.client .. "\n") for i, spec in ipairs(streams) do file:write("\n") file:write("[icecast2-" .. count .. "]\n") count = count + 1 if spec.type == "vorbis" then file:write("bitrateMode = vbr\n") file:write("format = vorbis\n") file:write("quality = " .. spec.quality .. "\n") elseif spec.type == "mp3" then file:write("bitrateMode = cbr\n") file:write("format = mp3\n") file:write("bitrate = " .. spec.bitrate .. "\n") end file:write("server = " .. config.host .. "\n") file:write("port = " .. config.port .. "\n") file:write("password = " .. config.password .. "\n") file:write("mountPoint = " .. spec.mount .. "\n") file:write("name = " .. config.name .. "\n") if config.description ~= nil then file:write("description = " .. config.description .. "\n") end if config.url ~= nil then file:write("url = " .. config.url .. "\n") end if config.genre ~= nil then file:write("genre = " .. config.genre .. "\n") end file:write("public = yes\n") end file:close() return path end Mash.client_present = function(client) local i, cname, pat pat = "^" .. client .. ":" for i, cname in ipairs(Mash.jack_ports()) do if string.find(cname, pat) then return(true) end end return(false) end function beep(duration, freq) Mash.darkice.connect() Mash.gen("sine", {duration=duration, freq=freq}):play() end Mash.darkice.connect = function(config_file) if (not Mash.client_present(Mash.darkice.client)) then Mash.fork(Mash.darkice.cmd .. " -c " .. config_file .. " &", 2) else print("mashice running") end Mash.feed(Mash.darkice.client .. ":left", Mash.darkice.client .. ":right") end ice_cfg = Mash.darkice.config( { channels = 2, host = "127.0.0.1", port = 8000, password = "hackme", name = "MASH-FM", description = "this is a description", url = "http://wtju.net/", genre = "Everything+" }, {{ type = "vorbis", quality = 0.6, mount = "vorbis.ogg"}, { type = "mp3", bitrate = 256, mount = "mp3.mp3" } } ) Mash.darkice.connect(ice_cfg)
gpl-3.0
mlem/wesnoth
data/ai/micro_ais/cas/ca_forest_animals_tusker_attack.lua
26
2575
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local function get_tuskers(cfg) local tuskers = AH.get_units_with_moves { side = wesnoth.current.side, type = cfg.tusker_type } return tuskers end local function get_adjacent_enemies(cfg) local adjacent_enemies = wesnoth.get_units { { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } }, { "filter_adjacent", { side = wesnoth.current.side, type = cfg.tusklet_type } } } return adjacent_enemies end local ca_forest_animals_tusker_attack = {} function ca_forest_animals_tusker_attack:evaluation(ai, cfg) -- Check whether there is an enemy next to a tusklet and attack it ("protective parents" AI) if (not cfg.tusker_type) or (not cfg.tusklet_type) then return 0 end if (not get_tuskers(cfg)[1]) then return 0 end if (not get_adjacent_enemies(cfg)[1]) then return 0 end return cfg.ca_score end function ca_forest_animals_tusker_attack:execution(ai, cfg) local tuskers = get_tuskers(cfg) local adjacent_enemies = get_adjacent_enemies(cfg) -- Find the closest enemy to any tusker local min_dist, attacker, target = 9e99 for _,tusker in ipairs(tuskers) do for _,enemy in ipairs(adjacent_enemies) do local dist = H.distance_between(tusker.x, tusker.y, enemy.x, enemy.y) if (dist < min_dist) then min_dist, attacker, target = dist, tusker, enemy end end end -- The tusker moves as close to enemy as possible -- Closeness to tusklets is secondary criterion local adj_tusklets = wesnoth.get_units { side = wesnoth.current.side, type = cfg.tusklet_type, { "filter_adjacent", { id = target.id } } } local best_hex = AH.find_best_move(attacker, function(x, y) local rating = - H.distance_between(x, y, target.x, target.y) for _,tusklet in ipairs(adj_tusklets) do if (H.distance_between(x, y, tusklet.x, tusklet.y) == 1) then rating = rating + 0.1 end end return rating end) AH.movefull_stopunit(ai, attacker, best_hex) if (not attacker) or (not attacker.valid) then return end if (not target) or (not target.valid) then return end local dist = H.distance_between(attacker.x, attacker.y, target.x, target.y) if (dist == 1) then AH.checked_attack(ai, attacker, target) else AH.checked_stopunit_attacks(ai, attacker) end end return ca_forest_animals_tusker_attack
gpl-2.0
shakfu/start-vm
config/base/awesome/vicious/contrib/batpmu.lua
18
2390
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> --------------------------------------------------- -- {{{ Grab environment local tonumber = tonumber local io = { open = io.open } local setmetatable = setmetatable local math = { min = math.min, floor = math.floor } local string = { find = string.find, match = string.match, format = string.format } -- }}} -- Batpmu: provides state, charge and remaining time for a requested battery using PMU -- vicious.contrib.batpmu local batpmu = {} -- {{{ Battery widget type local function worker(format, batid) local battery_state = { ["full"] = "↯", ["unknown"] = "⌁", ["00000013"] = "+", ["00000011"] = "-" } -- Get /proc/pmu/battery* state local f = io.open("/proc/pmu/" .. batid) -- Handler for incompetent users if not f then return {battery_state["unknown"], 0, "N/A"} end local statefile = f:read("*all") f:close() -- Get /proc/pmu/info data local f = io.open("/proc/pmu/info") local infofile = f:read("*all") f:close() -- Check if the battery is present if infofile == nil or string.find(infofile, "Battery count[%s]+:[%s]0") then return {battery_state["unknown"], 0, "N/A"} end -- Get capacity and charge information local capacity = string.match(statefile, "max_charge[%s]+:[%s]([%d]+).*") local remaining = string.match(statefile, "charge[%s]+:[%s]([%d]+).*") -- Calculate percentage local percent = math.min(math.floor(remaining / capacity * 100), 100) -- Get timer information local timer = string.match(statefile, "time rem%.[%s]+:[%s]([%d]+).*") if timer == "0" then return {battery_state["full"], percent, "N/A"} end -- Get state information local state = string.match(statefile, "flags[%s]+:[%s]([%d]+).*") local state = battery_state[state] or battery_state["unknown"] -- Calculate remaining (charging or discharging) time local hoursleft = math.floor(tonumber(timer) / 3600) local minutesleft = math.floor((tonumber(timer) / 60) % 60) local time = string.format("%02d:%02d", hoursleft, minutesleft) return {state, percent, time} end -- }}} return setmetatable(batpmu, { __call = function(_, ...) return worker(...) end })
mit
nasomi/darkstar
scripts/zones/Apollyon/mobs/Dark_Elemental.lua
16
2431
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger"); local correctelement=false; switch (elementalday): caseof { [1] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [2] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [8] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Waters/npcs/Rukuku.lua
36
1417
----------------------------------- -- Area: Windurst Waters -- NPC: Rukuku -- Involved in Quest: Making the Grade -- Working 100% -- @zone = 238 -- @pos = 130 -6 160 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then player:startEvent(0x01c2); -- During Making the GRADE else player:startEvent(0x01aa); -- Standard conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
coolflyreg/gs
3rd/skynet-mingw/lualib/mysql.lua
6
15787
-- Copyright (C) 2012 Yichun Zhang (agentzh) -- Copyright (C) 2014 Chang Feng -- This file is modified version from https://github.com/openresty/lua-resty-mysql -- The license is under the BSD license. -- Modified by Cloud Wu (remove bit32 for lua 5.3) local socketchannel = require "socketchannel" local mysqlaux = require "mysqlaux.c" local crypt = require "crypt" local sub = string.sub local strgsub = string.gsub local strformat = string.format local strbyte = string.byte local strchar = string.char local strrep = string.rep local strunpack = string.unpack local strpack = string.pack local sha1= crypt.sha1 local setmetatable = setmetatable local error = error local tonumber = tonumber local new_tab = function (narr, nrec) return {} end local _M = { _VERSION = '0.13' } -- constants local STATE_CONNECTED = 1 local STATE_COMMAND_SENT = 2 local COM_QUERY = 0x03 local SERVER_MORE_RESULTS_EXISTS = 8 -- 16MB - 1, the default max allowed packet size used by libmysqlclient local FULL_PACKET_SIZE = 16777215 local mt = { __index = _M } -- mysql field value type converters local converters = new_tab(0, 8) for i = 0x01, 0x05 do -- tiny, short, long, float, double converters[i] = tonumber end converters[0x08] = tonumber -- long long converters[0x09] = tonumber -- int24 converters[0x0d] = tonumber -- year converters[0xf6] = tonumber -- newdecimal local function _get_byte2(data, i) return strunpack("<I2",data,i) end local function _get_byte3(data, i) return strunpack("<I3",data,i) end local function _get_byte4(data, i) return strunpack("<I4",data,i) end local function _get_byte8(data, i) return strunpack("<I8",data,i) end local function _set_byte2(n) return strpack("<I2", n) end local function _set_byte3(n) return strpack("<I3", n) end local function _set_byte4(n) return strpack("<I4", n) end local function _from_cstring(data, i) return strunpack("z", data, i) end local function _dumphex(bytes) return strgsub(bytes, ".", function(x) return strformat("%02x ", strbyte(x)) end) end local function _compute_token(password, scramble) if password == "" then return "" end --_dumphex(scramble) local stage1 = sha1(password) --print("stage1:", _dumphex(stage1) ) local stage2 = sha1(stage1) local stage3 = sha1(scramble .. stage2) local i = 0 return strgsub(stage3,".", function(x) i = i + 1 -- ~ is xor in lua 5.3 return strchar(strbyte(x) ~ strbyte(stage1, i)) end) end local function _compose_packet(self, req, size) self.packet_no = self.packet_no + 1 local packet = _set_byte3(size) .. strchar(self.packet_no) .. req return packet end local function _send_packet(self, req, size) local sock = self.sock self.packet_no = self.packet_no + 1 local packet = _set_byte3(size) .. strchar(self.packet_no) .. req return socket.write(self.sock,packet) end local function _recv_packet(self,sock) local data = sock:read( 4) if not data then return nil, nil, "failed to receive packet header: " end local len, pos = _get_byte3(data, 1) if len == 0 then return nil, nil, "empty packet" end if len > self._max_packet_size then return nil, nil, "packet size too big: " .. len end local num = strbyte(data, pos) self.packet_no = num data = sock:read(len) if not data then return nil, nil, "failed to read packet content: " end local field_count = strbyte(data, 1) local typ if field_count == 0x00 then typ = "OK" elseif field_count == 0xff then typ = "ERR" elseif field_count == 0xfe then typ = "EOF" elseif field_count <= 250 then typ = "DATA" end return data, typ end local function _from_length_coded_bin(data, pos) local first = strbyte(data, pos) if not first then return nil, pos end if first >= 0 and first <= 250 then return first, pos + 1 end if first == 251 then return nil, pos + 1 end if first == 252 then pos = pos + 1 return _get_byte2(data, pos) end if first == 253 then pos = pos + 1 return _get_byte3(data, pos) end if first == 254 then pos = pos + 1 return _get_byte8(data, pos) end return false, pos + 1 end local function _from_length_coded_str(data, pos) local len len, pos = _from_length_coded_bin(data, pos) if len == nil then return nil, pos end return sub(data, pos, pos + len - 1), pos + len end local function _parse_ok_packet(packet) local res = new_tab(0, 5) local pos res.affected_rows, pos = _from_length_coded_bin(packet, 2) res.insert_id, pos = _from_length_coded_bin(packet, pos) res.server_status, pos = _get_byte2(packet, pos) res.warning_count, pos = _get_byte2(packet, pos) local message = sub(packet, pos) if message and message ~= "" then res.message = message end return res end local function _parse_eof_packet(packet) local pos = 2 local warning_count, pos = _get_byte2(packet, pos) local status_flags = _get_byte2(packet, pos) return warning_count, status_flags end local function _parse_err_packet(packet) local errno, pos = _get_byte2(packet, 2) local marker = sub(packet, pos, pos) local sqlstate if marker == '#' then -- with sqlstate pos = pos + 1 sqlstate = sub(packet, pos, pos + 5 - 1) pos = pos + 5 end local message = sub(packet, pos) return errno, message, sqlstate end local function _parse_result_set_header_packet(packet) local field_count, pos = _from_length_coded_bin(packet, 1) local extra extra = _from_length_coded_bin(packet, pos) return field_count, extra end local function _parse_field_packet(data) local col = new_tab(0, 2) local catalog, db, table, orig_table, orig_name, charsetnr, length local pos catalog, pos = _from_length_coded_str(data, 1) db, pos = _from_length_coded_str(data, pos) table, pos = _from_length_coded_str(data, pos) orig_table, pos = _from_length_coded_str(data, pos) col.name, pos = _from_length_coded_str(data, pos) orig_name, pos = _from_length_coded_str(data, pos) pos = pos + 1 -- ignore the filler charsetnr, pos = _get_byte2(data, pos) length, pos = _get_byte4(data, pos) col.type = strbyte(data, pos) --[[ pos = pos + 1 col.flags, pos = _get_byte2(data, pos) col.decimals = strbyte(data, pos) pos = pos + 1 local default = sub(data, pos + 2) if default and default ~= "" then col.default = default end --]] return col end local function _parse_row_data_packet(data, cols, compact) local pos = 1 local ncols = #cols local row if compact then row = new_tab(ncols, 0) else row = new_tab(0, ncols) end for i = 1, ncols do local value value, pos = _from_length_coded_str(data, pos) local col = cols[i] local typ = col.type local name = col.name if value ~= nil then local conv = converters[typ] if conv then value = conv(value) end end if compact then row[i] = value else row[name] = value end end return row end local function _recv_field_packet(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end if typ ~= 'DATA' then return nil, "bad field packet type: " .. typ end -- typ == 'DATA' return _parse_field_packet(packet) end local function _recv_decode_packet_resp(self) return function(sock) -- don't return more than 2 results return true, (_recv_packet(self,sock)) end end local function _recv_auth_resp(self) return function(sock) local packet, typ, err = _recv_packet(self,sock) if not packet then --print("recv auth resp : failed to receive the result packet") error ("failed to receive the result packet"..err) --return nil,err end if typ == 'ERR' then local errno, msg, sqlstate = _parse_err_packet(packet) error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) --return nil, errno,msg, sqlstate end if typ == 'EOF' then error "old pre-4.1 authentication protocol not supported" end if typ ~= 'OK' then error "bad packet type: " end return true, true end end local function _mysql_login(self,user,password,database,on_connect) return function(sockchannel) local packet, typ, err = sockchannel:response( _recv_decode_packet_resp(self) ) --local aat={} if not packet then error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end self.protocol_ver = strbyte(packet) local server_ver, pos = _from_cstring(packet, 2) if not server_ver then error "bad handshake initialization packet: bad server version" end self._server_ver = server_ver local thread_id, pos = _get_byte4(packet, pos) local scramble1 = sub(packet, pos, pos + 8 - 1) if not scramble1 then error "1st part of scramble not found" end pos = pos + 9 -- skip filler -- two lower bytes self._server_capabilities, pos = _get_byte2(packet, pos) self._server_lang = strbyte(packet, pos) pos = pos + 1 self._server_status, pos = _get_byte2(packet, pos) local more_capabilities more_capabilities, pos = _get_byte2(packet, pos) self._server_capabilities = self._server_capabilities|more_capabilities<<16 local len = 21 - 8 - 1 pos = pos + 1 + 10 local scramble_part2 = sub(packet, pos, pos + len - 1) if not scramble_part2 then error "2nd part of scramble not found" end local scramble = scramble1..scramble_part2 local token = _compute_token(password, scramble) local client_flags = 260047; local req = strpack("<I4I4c24zs1z", client_flags, self._max_packet_size, strrep("\0", 24), -- TODO: add support for charset encoding user, token, database) local packet_len = #req local authpacket=_compose_packet(self,req,packet_len) sockchannel:request(authpacket,_recv_auth_resp(self)) if on_connect then on_connect(self) end end end local function _compose_query(self, query) self.packet_no = -1 local cmd_packet = strchar(COM_QUERY) .. query local packet_len = 1 + #query local querypacket = _compose_packet(self, cmd_packet, packet_len) return querypacket end local function read_result(self, sock) local packet, typ, err = _recv_packet(self, sock) if not packet then return nil, err --error( err ) end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end if typ == 'OK' then local res = _parse_ok_packet(packet) if res and res.server_status&SERVER_MORE_RESULTS_EXISTS ~= 0 then return res, "again" end return res end if typ ~= 'DATA' then return nil, "packet type " .. typ .. " not supported" --error( "packet type " .. typ .. " not supported" ) end -- typ == 'DATA' local field_count, extra = _parse_result_set_header_packet(packet) local cols = new_tab(field_count, 0) for i = 1, field_count do local col, err, errno, sqlstate = _recv_field_packet(self, sock) if not col then return nil, err, errno, sqlstate --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate)) end cols[i] = col end local packet, typ, err = _recv_packet(self, sock) if not packet then --error( err) return nil, err end if typ ~= 'EOF' then --error ( "unexpected packet type " .. typ .. " while eof packet is ".. "expected" ) return nil, "unexpected packet type " .. typ .. " while eof packet is ".. "expected" end -- typ == 'EOF' local compact = self.compact local rows = new_tab( 4, 0) local i = 0 while true do packet, typ, err = _recv_packet(self, sock) if not packet then --error (err) return nil, err end if typ == 'EOF' then local warning_count, status_flags = _parse_eof_packet(packet) if status_flags&SERVER_MORE_RESULTS_EXISTS ~= 0 then return rows, "again" end break end -- if typ ~= 'DATA' then -- return nil, 'bad row packet type: ' .. typ -- end -- typ == 'DATA' local row = _parse_row_data_packet(packet, cols, compact) i = i + 1 rows[i] = row end return rows end local function _query_resp(self) return function(sock) local res, err, errno, sqlstate = read_result(self,sock) if not res then local badresult ={} badresult.badresult = true badresult.err = err badresult.errno = errno badresult.sqlstate = sqlstate return true , badresult end if err ~= "again" then return true, res end local mulitresultset = {res} mulitresultset.mulitresultset = true local i =2 while err =="again" do res, err, errno, sqlstate = read_result(self,sock) if not res then return true, mulitresultset end mulitresultset[i]=res i=i+1 end return true, mulitresultset end end function _M.connect(opts) local self = setmetatable( {}, mt) local max_packet_size = opts.max_packet_size if not max_packet_size then max_packet_size = 1024 * 1024 -- default 1 MB end self._max_packet_size = max_packet_size self.compact = opts.compact_arrays local database = opts.database or "" local user = opts.user or "" local password = opts.password or "" local channel = socketchannel.channel { host = opts.host, port = opts.port or 3306, auth = _mysql_login(self,user,password,database,opts.on_connect), } self.sockchannel = channel -- try connect first only once channel:connect(true) return self end function _M.disconnect(self) self.sockchannel:close() setmetatable(self, nil) end function _M.query(self, query) local querypacket = _compose_query(self, query) local sockchannel = self.sockchannel if not self.query_resp then self.query_resp = _query_resp(self) end return sockchannel:request( querypacket, self.query_resp ) end function _M.server_ver(self) return self._server_ver end function _M.quote_sql_str( str) return mysqlaux.quote_sql_str(str) end function _M.set_compact_arrays(self, value) self.compact = value end return _M
gpl-2.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27001103.lua
1
1287
--BT1-088 Frieza, Hellish Terror local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZAS_ARMY,CHARACTER_FRIEZA,SPECIAL_TRAIT_FRIEZA_CLAN) ds.AddPlayProcedure(c,COLOR_YELLOW,2,2) --evolve ds.EnableEvolve(c,aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_FRIEZA),COLOR_YELLOW,2,1) --double strike ds.EnableDoubleStrike(c) --switch position ds.AddSingleAutoPlay(c,0,nil,scard.postg,scard.posop,DS_EFFECT_FLAG_CARD_CHOOSE,ds.evoplcon) end scard.dragon_ball_super_card=true scard.combo_cost=1 function scard.posfilter(c) return c:IsActive() and c:IsHasSkill(DS_SKILL_BLOCKER) end function scard.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(DS_LOCATION_BATTLE) and chkc:IsControler(1-tp) and ds.BattleAreaFilter(scard.posfilter)(chkc) end if chk==0 then return true end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) local ct=Duel.GetMatchingGroupCount(ds.BattleAreaFilter(scard.posfilter),tp,0,DS_LOCATION_BATTLE,nil) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOREST) Duel.SelectTarget(tp,ds.BattleAreaFilter(scard.posfilter),tp,0,DS_LOCATION_BATTLE,ct,ct,nil) end scard.posop=ds.ChooseSwitchPositionOperation(DS_POS_FACEUP_REST)
gpl-3.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/modules/base/luasrc/model/uci.lua
86
10653
--[[ LuCI - UCI model Description: Generalized UCI model FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 os = require "os" local uci = require "uci" local util = require "luci.util" local table = require "table" local setmetatable, rawget, rawset = setmetatable, rawget, rawset local require, getmetatable = require, getmetatable local error, pairs, ipairs = error, pairs, ipairs local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack --- LuCI UCI model library. -- The typical workflow for UCI is: Get a cursor instance from the -- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.), -- save the changes to the staging area via Cursor.save and finally -- Cursor.commit the data to the actual config files. -- LuCI then needs to Cursor.apply the changes so deamons etc. are -- reloaded. -- @cstyle instance module "luci.model.uci" --- Create a new UCI-Cursor. -- @class function -- @name cursor -- @return UCI-Cursor cursor = uci.cursor APIVERSION = uci.APIVERSION --- Create a new Cursor initialized to the state directory. -- @return UCI cursor function cursor_state() return cursor(nil, "/var/state") end inst = cursor() inst_state = cursor_state() local Cursor = getmetatable(inst) --- Applies UCI configuration changes -- @param configlist List of UCI configurations -- @param command Don't apply only return the command function Cursor.apply(self, configlist, command) configlist = self:_affected(configlist) if command then return { "/sbin/luci-reload", unpack(configlist) } else return os.execute("/sbin/luci-reload %s >/dev/null 2>&1" % table.concat(configlist, " ")) end end --- Delete all sections of a given type that match certain criteria. -- @param config UCI config -- @param type UCI section type -- @param comparator Function that will be called for each section and -- returns a boolean whether to delete the current section (optional) function Cursor.delete_all(self, config, stype, comparator) local del = {} if type(comparator) == "table" then local tbl = comparator comparator = function(section) for k, v in pairs(tbl) do if section[k] ~= v then return false end end return true end end local function helper (section) if not comparator or comparator(section) then del[#del+1] = section[".name"] end end self:foreach(config, stype, helper) for i, j in ipairs(del) do self:delete(config, j) end end --- Create a new section and initialize it with data. -- @param config UCI config -- @param type UCI section type -- @param name UCI section name (optional) -- @param values Table of key - value pairs to initialize the section with -- @return Name of created section function Cursor.section(self, config, type, name, values) local stat = true if name then stat = self:set(config, name, type) else name = self:add(config, type) stat = name and true end if stat and values then stat = self:tset(config, name, values) end return stat and name end --- Updated the data of a section using data from a table. -- @param config UCI config -- @param section UCI section name (optional) -- @param values Table of key - value pairs to update the section with function Cursor.tset(self, config, section, values) local stat = true for k, v in pairs(values) do if k:sub(1, 1) ~= "." then stat = stat and self:set(config, section, k, v) end end return stat end --- Get a boolean option and return it's value as true or false. -- @param config UCI config -- @param section UCI section name -- @param option UCI option -- @return Boolean function Cursor.get_bool(self, ...) local val = self:get(...) return ( val == "1" or val == "true" or val == "yes" or val == "on" ) end --- Get an option or list and return values as table. -- @param config UCI config -- @param section UCI section name -- @param option UCI option -- @return UCI value function Cursor.get_list(self, config, section, option) if config and section and option then local val = self:get(config, section, option) return ( type(val) == "table" and val or { val } ) end return nil end --- Get the given option from the first section with the given type. -- @param config UCI config -- @param type UCI section type -- @param option UCI option (optional) -- @param default Default value (optional) -- @return UCI value function Cursor.get_first(self, conf, stype, opt, def) local rv = def self:foreach(conf, stype, function(s) local val = not opt and s['.name'] or s[opt] if type(def) == "number" then val = tonumber(val) elseif type(def) == "boolean" then val = (val == "1" or val == "true" or val == "yes" or val == "on") end if val ~= nil then rv = val return false end end) return rv end --- Set given values as list. -- @param config UCI config -- @param section UCI section name -- @param option UCI option -- @param value UCI value -- @return Boolean whether operation succeeded function Cursor.set_list(self, config, section, option, value) if config and section and option then return self:set( config, section, option, ( type(value) == "table" and value or { value } ) ) end return false end -- Return a list of initscripts affected by configuration changes. function Cursor._affected(self, configlist) configlist = type(configlist) == "table" and configlist or {configlist} local c = cursor() c:load("ucitrack") -- Resolve dependencies local reloadlist = {} local function _resolve_deps(name) local reload = {name} local deps = {} c:foreach("ucitrack", name, function(section) if section.affects then for i, aff in ipairs(section.affects) do deps[#deps+1] = aff end end end) for i, dep in ipairs(deps) do for j, add in ipairs(_resolve_deps(dep)) do reload[#reload+1] = add end end return reload end -- Collect initscripts for j, config in ipairs(configlist) do for i, e in ipairs(_resolve_deps(config)) do if not util.contains(reloadlist, e) then reloadlist[#reloadlist+1] = e end end end return reloadlist end --- Create a sub-state of this cursor. The sub-state is tied to the parent -- curser, means it the parent unloads or loads configs, the sub state will -- do so as well. -- @return UCI state cursor tied to the parent cursor function Cursor.substate(self) Cursor._substates = Cursor._substates or { } Cursor._substates[self] = Cursor._substates[self] or cursor_state() return Cursor._substates[self] end local _load = Cursor.load function Cursor.load(self, ...) if Cursor._substates and Cursor._substates[self] then _load(Cursor._substates[self], ...) end return _load(self, ...) end local _unload = Cursor.unload function Cursor.unload(self, ...) if Cursor._substates and Cursor._substates[self] then _unload(Cursor._substates[self], ...) end return _unload(self, ...) end --- Add an anonymous section. -- @class function -- @name Cursor.add -- @param config UCI config -- @param type UCI section type -- @return Name of created section --- Get a table of saved but uncommitted changes. -- @class function -- @name Cursor.changes -- @param config UCI config -- @return Table of changes -- @see Cursor.save --- Commit saved changes. -- @class function -- @name Cursor.commit -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.revert -- @see Cursor.save --- Deletes a section or an option. -- @class function -- @name Cursor.delete -- @param config UCI config -- @param section UCI section name -- @param option UCI option (optional) -- @return Boolean whether operation succeeded --- Call a function for every section of a certain type. -- @class function -- @name Cursor.foreach -- @param config UCI config -- @param type UCI section type -- @param callback Function to be called -- @return Boolean whether operation succeeded --- Get a section type or an option -- @class function -- @name Cursor.get -- @param config UCI config -- @param section UCI section name -- @param option UCI option (optional) -- @return UCI value --- Get all sections of a config or all values of a section. -- @class function -- @name Cursor.get_all -- @param config UCI config -- @param section UCI section name (optional) -- @return Table of UCI sections or table of UCI values --- Manually load a config. -- @class function -- @name Cursor.load -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.save -- @see Cursor.unload --- Revert saved but uncommitted changes. -- @class function -- @name Cursor.revert -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.commit -- @see Cursor.save --- Saves changes made to a config to make them committable. -- @class function -- @name Cursor.save -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.load -- @see Cursor.unload --- Set a value or create a named section. -- @class function -- @name Cursor.set -- @param config UCI config -- @param section UCI section name -- @param option UCI option or UCI section type -- @param value UCI value or nil if you want to create a section -- @return Boolean whether operation succeeded --- Get the configuration directory. -- @class function -- @name Cursor.get_confdir -- @return Configuration directory --- Get the directory for uncomitted changes. -- @class function -- @name Cursor.get_savedir -- @return Save directory --- Set the configuration directory. -- @class function -- @name Cursor.set_confdir -- @param directory UCI configuration directory -- @return Boolean whether operation succeeded --- Set the directory for uncommited changes. -- @class function -- @name Cursor.set_savedir -- @param directory UCI changes directory -- @return Boolean whether operation succeeded --- Discard changes made to a config. -- @class function -- @name Cursor.unload -- @param config UCI config -- @return Boolean whether operation succeeded -- @see Cursor.load -- @see Cursor.save
gpl-2.0
nasomi/darkstar
scripts/globals/spells/bewitching_etude.lua
18
1619
----------------------------------------- -- Spell: Bewitching Etude -- Static CHR Boost, BRD 62 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 0; if (sLvl+iLvl <= 416) then power = 12; elseif ((sLvl+iLvl >= 417) and (sLvl+iLvl <= 445)) then power = 13; elseif ((sLvl+iLvl >= 446) and (sLvl+iLvl <= 474)) then power = 14; elseif (sLvl+iLvl >= 475) then power = 15; end local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_ETUDE,power,10,duration,caster:getID(), MOD_CHR, 2)) then spell:setMsg(75); end return EFFECT_ETUDE; end;
gpl-3.0
nasomi/darkstar
scripts/globals/spells/bluemagic/asuran_claws.lua
28
1798
----------------------------------------- -- Spell: Asuran Claws -- Delivers a sixfold attack. Accuracy varies with TP -- Spell cost: 81 MP -- Monster Type: Beasts -- Spell Type: Physical (Blunt) -- Blue Magic Points: 2 -- Stat Bonus: AGI +3 -- Level: 70 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Skillchain Element(s): Fire (Primary) and Lightning (Secondary) - (can open Scission, Detonation, Liquefaction, or Fusion; can close Liquefaction, Impaction, or Fusion) -- Combos: Counter ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ACC; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_IMPACTION; params.numhits = 6; params.multiplier = 1.0; params.tp150 = 1.05; params.tp300 = 1.1; params.azuretp = 1.2; params.duppercap = 21; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
actboy168/YDWE
Development/Component/plugin/w3x2lni/script/core/map-builder/load.lua
3
2739
local lang = require 'lang' local w2l local function search_staticfile(map, callback) local function search_tbl(tbl) for _, v in pairs(tbl) do if type(v) == 'table' then search_tbl(v) elseif type(v) == 'string' then callback(v) end end end search_tbl(w2l.info) end local function search_listfile(map, callback) local buf = map:get '(listfile)' if buf then local start = 1 while true do local pos = buf:find('\r\n', start) if not pos then callback(buf:sub(start)) break end callback(buf:sub(start, pos-1)) start = pos + 2 end end end local function search_imp(map, callback) local buf = map:get 'war3map.imp' if buf then local _, count, index = ('ll'):unpack(buf) local name for i = 1, count do _, name, index = ('c1z'):unpack(buf, index) callback(name) if not map:has(name) then local name = 'war3mapimported\\' .. name callback(name) end end end end local searchers = { search_listfile, search_staticfile, search_imp, } local function search_mpq(map) local total = map:number_of_files() local count = 0 local clock = os.clock() local mark = {} local files = {} for i, searcher in ipairs(searchers) do pcall(searcher, map, function (name) local lname = name:lower() if mark[lname] then return end mark[lname] = true if not map:has(name) then return end files[name] = map:get(name) count = count + 1 if os.clock() - clock > 0.1 then clock = os.clock() w2l.messager.text(lang.script.LOAD_MAP_FILE:format(count, total)) w2l.progress(count / total) end end) end return files end local function search_dir(map) local list = map:list_file() local total = #list local clock = os.clock() local count = 0 local files = {} for i, name in ipairs(list) do files[name] = map:get(name) count = count + 1 if os.clock() - clock > 0.1 then clock = os.clock() w2l.messager.text(lang.script.LOAD_MAP_FILE:format(count, total)) w2l.progress(count / total) end end return files end return function (w2l_, map) w2l = w2l_ if map:get_type() == 'mpq' then return search_mpq(map) else return search_dir(map) end end
gpl-3.0
RhenaudTheLukark/CreateYourFrisk
Assets/Mods/Examples/Lua/Encounters/04 - Animation.lua
2
1894
-- An animation demo with a rotating Sans head. -- music = "shine_on_you_crazy_diamond" --Always OGG. Extension is added automatically. Remove the first two lines for custom music. encountertext = "It's an animation!" --Modify as necessary. It will only be read out in the action select screen. nextwaves = {"bullettest_chaserorb"} wavetimer = 4.0 arenasize = {155, 130} autolinebreak = true enemies = { "sans" } enemypositions = { {0, 0} } -- A custom list with attacks to choose from. Actual selection happens in EnemyDialogueEnding(). Put here in case you want to use it. possible_attacks = {"bullettest_bouncy", "bullettest_chaserorb", "bullettest_touhou"} function EncounterStarting() --Include the animation Lua file. It's important you do this in EncounterStarting, because you can't create sprites before the game's done loading. --Be careful that you use different variable names as you have here, because the encounter's will be overwritten otherwise! --You can also use that to your benefit if you want to share a bunch of variables with multiple encounters. require "Animations/sans_anim" end function Update() --By calling the AnimateSans() function on the animation Lua file, we can create some movement! AnimateSans() end function EnemyDialogueEnding() -- Good location to fill the 'nextwaves' table with the attacks you want to have simultaneously. -- This example line below takes a random attack from 'possible_attacks'. nextwaves = { possible_attacks[math.random(#possible_attacks)] } end function DefenseEnding() --This built-in function fires after the defense round ends. encountertext = RandomEncounterText() --This built-in function gets a random encounter text from a random enemy. end function HandleSpare() State("ENEMYDIALOGUE") end function HandleItem(ItemID) BattleDialog({"Selected item " .. ItemID .. "."}) end
gpl-3.0
RhenaudTheLukark/CreateYourFrisk
Assets/Mods/Examples 2/Lua/Encounters/04 - Animation.lua
2
1894
-- An animation demo with a rotating Sans head. -- music = "shine_on_you_crazy_diamond" --Always OGG. Extension is added automatically. Remove the first two lines for custom music. encountertext = "It's an animation!" --Modify as necessary. It will only be read out in the action select screen. nextwaves = {"bullettest_chaserorb"} wavetimer = 4.0 arenasize = {155, 130} autolinebreak = true enemies = { "sans" } enemypositions = { {0, 0} } -- A custom list with attacks to choose from. Actual selection happens in EnemyDialogueEnding(). Put here in case you want to use it. possible_attacks = {"bullettest_bouncy", "bullettest_chaserorb", "bullettest_touhou"} function EncounterStarting() --Include the animation Lua file. It's important you do this in EncounterStarting, because you can't create sprites before the game's done loading. --Be careful that you use different variable names as you have here, because the encounter's will be overwritten otherwise! --You can also use that to your benefit if you want to share a bunch of variables with multiple encounters. require "Animations/sans_anim" end function Update() --By calling the AnimateSans() function on the animation Lua file, we can create some movement! AnimateSans() end function EnemyDialogueEnding() -- Good location to fill the 'nextwaves' table with the attacks you want to have simultaneously. -- This example line below takes a random attack from 'possible_attacks'. nextwaves = { possible_attacks[math.random(#possible_attacks)] } end function DefenseEnding() --This built-in function fires after the defense round ends. encountertext = RandomEncounterText() --This built-in function gets a random encounter text from a random enemy. end function HandleSpare() State("ENEMYDIALOGUE") end function HandleItem(ItemID) BattleDialog({"Selected item " .. ItemID .. "."}) end
gpl-3.0
nasomi/darkstar
scripts/globals/items/derfland_pear.lua
35
1212
----------------------------------------- -- ID: 4352 -- Item: derfland_pear -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -3 -- Intelligence 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4352); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Upper_Jeuno/npcs/Laila.lua
18
3782
----------------------------------- -- Area: Upper Jeuno -- NPC: Laila -- Type: Job Quest Giver -- @zone: 244 -- @pos -54.045 -1 100.996 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local lakesideMin = player:getQuestStatus(JEUNO,LAKESIDE_MINUET); local lakeProg = player:getVar("Lakeside_Minuet_Progress"); if (lakesideMin == QUEST_AVAILABLE and player:getMainLvl() >= ADVANCED_JOB_LEVEL and ENABLE_WOTG == 1) then player:startEvent(0x277f); -- Start quest csid, asks for Key Item Stardust Pebble elseif (lakesideMin == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x2787); elseif (player:hasKeyItem(STARDUST_PEBBLE)) then player:startEvent(0x2786); -- Ends Quest elseif (lakeProg == 3) then player:startEvent(0x2781); elseif (lakesideMin == QUEST_ACCEPTED) then player:startEvent(0x2780) -- After accepting, reminder elseif ((player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_AVAILABLE or (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED and player:hasItem(19203)==false)) and player:getMainJob()==JOB_DNC and player:getMainLvl()>=40) then player:startEvent(0x2791); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED and player:getVar("QuestStatus_DNC_AF1")==5 and player:seenKeyItem(THE_ESSENCE_OF_DANCE) and player:getMainJob()==JOB_DNC) then player:startEvent(0x2795); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED) then player:startEvent(0x2796); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_ROAD_TO_DIVADOM) == QUEST_AVAILABLE and player:getMainJob()==JOB_DNC) then player:startEvent(0x2798); else player:startEvent(0x2788); -- Default end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x277f and option == 1) then player:addQuest(JEUNO,LAKESIDE_MINUET); elseif (csid == 0x2786) then player:setVar("Lakeside_Minuet_Progress",0); player:completeQuest(JEUNO,LAKESIDE_MINUET); player:addTitle(TROUPE_BRILIOTH_DANCER); player:unlockJob(19); player:messageSpecial(UNLOCK_DANCER); player:addFame(JEUNO, JEUNO_FAME*30); player:delKeyItem(STARDUST_PEBBLE); player:needToZone(true); elseif (csid==0x2791) then if (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED) then player:delQuest(JEUNO,THE_UNFINISHED_WALTZ); player:delKeyItem(THE_ESSENCE_OF_DANCE); end player:addQuest(JEUNO,THE_UNFINISHED_WALTZ); player:setVar("QuestStatus_DNC_AF1", 1); elseif (csid==0x2795) then player:setVar("QuestStatus_DNC_AF1", 0); player:addItem(19203); -- war hoop player:messageSpecial(ITEM_OBTAINED,19203); player:completeQuest(JEUNO,THE_UNFINISHED_WALTZ); end end;
gpl-3.0
mlem/wesnoth
data/ai/micro_ais/cas/ca_hunter.lua
26
8246
local H = wesnoth.require "lua/helper.lua" local W = H.set_wml_action_metatable {} local AH = wesnoth.require "ai/lua/ai_helper.lua" local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua" local function hunter_attack_weakest_adj_enemy(ai, hunter) -- Attack the enemy with the fewest hitpoints adjacent to 'hunter', if there is one -- Returns status of the attack: -- 'attacked': if a unit was attacked -- 'killed': if a unit was killed -- 'no_attack': if no unit was attacked if (hunter.attacks_left == 0) then return 'no_attack' end local min_hp, target = 9e99 for xa,ya in H.adjacent_tiles(hunter.x, hunter.y) do local enemy = wesnoth.get_unit(xa, ya) if enemy and wesnoth.is_enemy(enemy.side, wesnoth.current.side) then if (enemy.hitpoints < min_hp) then min_hp, target = enemy.hitpoints, enemy end end end if target then AH.checked_attack(ai, hunter, target) if target and target.valid then return 'attacked' else return 'killed' end end return 'no_attack' end local function get_hunter(cfg) local filter = cfg.filter or { id = cfg.id } local hunter = AH.get_units_with_moves { side = wesnoth.current.side, { "and", filter } }[1] return hunter end local ca_hunter = {} function ca_hunter:evaluation(ai, cfg) if get_hunter(cfg) then return cfg.ca_score end return 0 end function ca_hunter:execution(ai, cfg) -- Hunter does a random wander in area given by @cfg.hunting_ground until it finds -- and kills an enemy unit, then retreats to position given by @cfg.home_x/y -- for @cfg.rest_turns turns, or until fully healed local hunter = get_hunter(cfg) local hunter_vars = MAIUV.get_mai_unit_variables(hunter, cfg.ai_id) -- If hunting_status is not set for the hunter -> default behavior -> random wander if (not hunter_vars.hunting_status) then -- Hunter gets a new goal if none exist or on any move with 10% random chance local rand = math.random(10) if (not hunter_vars.goal_x) or (rand == 1) then -- 'locs' includes border hexes, but that does not matter here locs = AH.get_passable_locations((cfg.filter_location or {}), hunter) local rand = math.random(#locs) hunter_vars.goal_x, hunter_vars.goal_y = locs[rand][1], locs[rand][2] MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end local reach_map = AH.get_reachable_unocc(hunter) -- Now find the one of these hexes that is closest to the goal local max_rating, best_hex = -9e99 reach_map:iter( function(x, y, v) -- Distance from goal is first rating local rating = - H.distance_between(x, y, hunter_vars.goal_x, hunter_vars.goal_y) -- Huge rating bonus if this is next to an enemy local enemy_hp = 500 for xa,ya in H.adjacent_tiles(x, y) do local enemy = wesnoth.get_unit(xa, ya) if enemy and wesnoth.is_enemy(enemy.side, wesnoth.current.side) then if (enemy.hitpoints < enemy_hp) then enemy_hp = enemy.hitpoints end end end rating = rating + 500 - enemy_hp -- prefer attack on weakest enemy if (rating > max_rating) then max_rating, best_hex = rating, { x, y } end end) if (best_hex[1] ~= hunter.x) or (best_hex[2] ~= hunter.y) then AH.checked_move(ai, hunter, best_hex[1], best_hex[2]) -- partial move only if (not hunter) or (not hunter.valid) then return end else -- If hunter did not move, we need to stop it (also delete the goal) AH.checked_stopunit_moves(ai, hunter) if (not hunter) or (not hunter.valid) then return end hunter_vars.goal_x, hunter_vars.goal_y = nil, nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end -- If this gets the hunter to the goal, we delete the goal if (hunter.x == hunter_vars.goal_x) and (hunter.y == hunter_vars.goal_y) then hunter_vars.goal_x, hunter_vars.goal_y = nil, nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end -- Finally, if the hunter ended up next to enemies, attack the weakest of those local attack_status = hunter_attack_weakest_adj_enemy(ai, hunter) -- If the enemy was killed, hunter returns home if hunter and hunter.valid and (attack_status == 'killed') then hunter_vars.goal_x, hunter_vars.goal_y = nil, nil hunter_vars.hunting_status = 'returning' MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) if cfg.show_messages then W.message { speaker = hunter.id, message = 'Now that I have eaten, I will go back home.' } end end return end -- If we got here, this means the hunter is either returning, or resting if (hunter_vars.hunting_status == 'returning') then goto_x, goto_y = wesnoth.find_vacant_tile(cfg.home_x, cfg.home_y) local next_hop = AH.next_hop(hunter, goto_x, goto_y) if next_hop then AH.movefull_stopunit(ai, hunter, next_hop) if (not hunter) or (not hunter.valid) then return end -- If there's an enemy on the 'home' hex and we got right next to it, attack that enemy if (H.distance_between(cfg.home_x, cfg.home_y, next_hop[1], next_hop[2]) == 1) then local enemy = wesnoth.get_unit(cfg.home_x, cfg.home_y) if enemy and wesnoth.is_enemy(enemy.side, hunter.side) then if cfg.show_messages then W.message { speaker = hunter.id, message = 'Get out of my home!' } end AH.checked_attack(ai, hunter, enemy) if (not hunter) or (not hunter.valid) then return end end end end -- We also attack the weakest adjacent enemy, if still possible hunter_attack_weakest_adj_enemy(ai, hunter) if (not hunter) or (not hunter.valid) then return end -- If the hunter got home, start the resting counter if (hunter.x == cfg.home_x) and (hunter.y == cfg.home_y) then hunter_vars.hunting_status = 'resting' hunter_vars.resting_until = wesnoth.current.turn + (cfg.rest_turns or 3) MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) if cfg.show_messages then W.message { speaker = hunter.id, message = 'I made it home - resting now until the end of Turn ' .. hunter_vars.resting_until .. ' or until fully healed.' } end end return end -- If we got here, the only remaining action should be resting if (hunter_vars.hunting_status == 'resting') then AH.checked_stopunit_moves(ai, hunter) if (not hunter) or (not hunter.valid) then return end -- We also attack the weakest adjacent enemy hunter_attack_weakest_adj_enemy(ai, hunter) if (not hunter) or (not hunter.valid) then return end -- If this is the last turn of resting, we remove the status and turn variable if (hunter.hitpoints >= hunter.max_hitpoints) and (hunter_vars.resting_until <= wesnoth.current.turn) then hunter_vars.hunting_status = nil hunter_vars.resting_until = nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) if cfg.show_messages then W.message { speaker = hunter.id, message = 'I am done resting. It is time to go hunting again next turn.' } end end return end -- In principle we should never get here, but just in case something got changed in WML: -- Reset variable, so that hunter goes hunting on next turn hunter_vars.hunting_status = nil MAIUV.set_mai_unit_variables(hunter, cfg.ai_id, hunter_vars) end return ca_hunter
gpl-2.0
nasomi/darkstar
scripts/globals/abilities/chaos_roll.lua
9
3293
----------------------------------- -- Ability: Chaos Roll -- Enhances attack for party members within area of effect -- Optimal Job: Dark Knight -- Lucky Number: 4 -- Unlucky Number: 8 -- Level: 14 -- -- Die Roll |No DRK |With DRK -- -------- -------- ----------- -- 1 |6% |16% -- 2 |8% |18% -- 3 |9% |19% -- 4 |25% |35% -- 5 |11% |21% -- 6 |13% |23% -- 7 |16% |26% -- 8 |3% |13% -- 9 |17% |27% -- 10 |19% |29% -- 11 |31% |41% -- Bust |-10% |-10% ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else player:setLocalVar("DRK_roll_bonus", 0); -- reset the variable for job bonus - this is only called on the first roll and only once return 0,0; end end; ----------------------------------- -- onUseAbilityRoll ----------------------------------- function onUseAbilityRoll(caster,target,ability,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {6, 8, 9, 25, 11, 13, 16, 3, 17, 19, 31, 10} local effectpower = effectpowers[total]; local jobBonus = caster:getLocalVar("DRK_roll_bonus"); if (total < 12) then if (jobBonus == 0) then -- this happens on the first roll only, and only for the roller if (caster:hasPartyJob(JOB_DRK) or math.random(0, 99) < caster:getMod(MOD_JOB_BONUS_CHANCE)) then jobBonus = 1; -- enables job boost -- print("first roll w/ bonus") else jobBonus = 2; -- setting this to 2 so it doesn't allow for another attempt to apply the job bonus with the modifier upon double-up. -- print("first roll") end end if (jobBonus == 1) then effectpower = effectpower + 10; -- print("activate job bonus"); end if (target:getID() == caster:getID()) then -- only need to set the variable for the caster, and just once. caster:setLocalVar("DRK_roll_bonus", jobBonus); end -- print(caster:getLocalVar("DRK_roll_bonus")); end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_CHAOS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_ATTP) == false) then ability:setMsg(423); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/prized_seafood_stewpot.lua
36
1865
----------------------------------------- -- ID: 5240 -- Item: Prized Seafood Stewpot -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 100 -- MP +20 -- Dexterity 2 -- Vitality 2 -- Agility 2 -- Mind 2 -- HP Recovered while healing 9 -- MP Recovered while healing 3 -- Accuracy 7 -- Evasion 7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5240); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 100); target:addMod(MOD_MP, 20); target:addMod(MOD_DEX, 2); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, 2); target:addMod(MOD_MND, 2); target:addMod(MOD_HPHEAL, 9); target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_ACC, 7); target:addMod(MOD_EVA, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 100); target:delMod(MOD_MP, 20); target:delMod(MOD_DEX, 2); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, 2); target:delMod(MOD_MND, 2); target:delMod(MOD_HPHEAL, 9); target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_ACC, 7); target:delMod(MOD_EVA, 7); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Signpost.lua
19
1356
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Signpost ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getID() == 17261155) then player:messageSpecial(SIGN_5); elseif (npc:getID() == 17261156) then player:messageSpecial(SIGN_4); elseif (npc:getID() == 17261157) then player:messageSpecial(SIGN_3); elseif (npc:getID() == 17261158) then player:messageSpecial(SIGN_2); elseif (npc:getID() == 17261159) or (npc:getID() == 17261160) or (npc:getID() == 17261161) then player:messageSpecial(SIGN_1); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID: %u",csid); --print("RESULT: %u",option); end;
gpl-3.0
srush/OpenNMT
onmt/utils/Logger.lua
3
2371
--[[ Logger is a class used for maintaining logs in a log file. --]] local Logger = torch.class('Logger') --[[ Construct a Logger object. Parameters: * `logPath` - the path to log file. If left blank, then output log to stdout. * `mute` - whether or not suppress outputs to stdout. [false] Example: logging = onmt.utils.Logger.new("./log.txt") logging:info('%s is an extension of OpenNMT.', 'Im2Text') logging:shutDown() ]] function Logger:__init(logPath, mute) logPath = logPath or '' mute = mute or false self.mute = mute local openMode = 'w' local f = io.open(logPath, 'r') if f then f:close() local input = nil while not input do print('Logging file exits. Overwrite(o)? Append(a)? Abort(q)?') input = io.read() if input == 'o' or input == 'O' then openMode = 'w' elseif input == 'a' or input == 'A' then openMode = 'a' elseif input == 'q' or input == 'Q' then os.exit() else openMode = 'a' end end end if string.len(logPath) > 0 then self.logFile = io.open(logPath, openMode) else self.logFile = nil self.mute = false end end --[[ Log a message at a specified level. Parameters: * `message` - the message to log. * `level` - the desired message level. ['INFO'] ]] function Logger:log(message, level) level = level or 'INFO' local timeStamp = os.date('%x %X') local msgFormatted = string.format('[%s %s] %s', timeStamp, level, message) if not self.mute then print (msgFormatted) end if self.logFile then self.logFile:write(msgFormatted .. '\n') self.logFile:flush() end end --[[ Log a message at 'INFO' level. Parameters: * `message` - the message to log. Supports formatting string. ]] function Logger:info(...) self:log(string.format(...), 'INFO') end --[[ Log a message at 'WARNING' level. Parameters: * `message` - the message to log. Supports formatting string. ]] function Logger:warning(...) self:log(string.format(...), 'WARNING') end --[[ Log a message at 'ERROR' level. Parameters: * `message` - the message to log. Supports formatting string. ]] function Logger:error(...) self:log(string.format(...), 'ERROR') end --[[ Deconstructor. Close the log file. ]] function Logger:shutDown() if self.logFile then self.logFile:close() end end return Logger
mit
nasomi/darkstar
scripts/globals/mobskills/Radiant_Breath.lua
17
1040
--------------------------------------------- -- Radiant Breath -- -- Description: Deals light damage to enemies within a fan-shaped area of effect originating from the caster. Additional effect: Slow and Silence. -- Type: Magical (Light) -- -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffectOne = EFFECT_SLOW; local typeEffectTwo = EFFECT_SILENCE; MobStatusEffectMove(mob, target, typeEffectOne, 128, 0, 120); MobStatusEffectMove(mob, target, typeEffectTwo, 1, 0, 120); local dmgmod = MobBreathMove(mob, target, 0.2, 0.75, ELE_LIGHT, 700); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_LIGHT,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
fegimanam/zus
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
haka-security/haka
modules/protocol/http/http_utils.lua
5
6141
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local class = require('class') local module = {} module.uri = {} module.cookies = {} local _unreserved = table.dict({string.byte("-"), string.byte("."), string.byte("_"), string.byte("~")}) local str = string.char local function uri_safe_decode(uri) local uri = string.gsub(uri, '%%(%x%x)', function(p) local val = tonumber(p, 16) if (val > 47 and val < 58) or (val > 64 and val < 91) or (val > 96 and val < 123) or (table.contains(_unreserved, val)) then return str(val) else return '%' .. string.upper(p) end end) return uri end local function uri_safe_decode_split(tab) for k, v in pairs(tab) do if type(v) == 'table' then uri_safe_decode_split(v) else tab[k] = uri_safe_decode(v) end end end local _prefixes = {{'^%.%./', ''}, {'^%./', ''}, {'^/%.%./', '/'}, {'^/%.%.$', '/'}, {'^/%./', '/'}, {'^/%.$', '/'}} local function remove_dot_segments(path) local output = {} local slash = '' local nb = 0 if path:sub(1,1) == '/' then slash = '/' end while path ~= '' do local index = 0 for _, prefix in ipairs(_prefixes) do path, nb = path:gsub(prefix[1], prefix[2]) if nb > 0 then if index == 2 or index == 3 then table.remove(output, #output) end break end index = index + 1 end if nb == 0 then if path:sub(1,1) == '/' then path = path:sub(2) end local left, right = path:match('([^/]*)([/]?.*)') table.insert(output, left) path = right end end return slash .. table.concat(output, '/') end -- Uri splitter object local HttpUriSplit = class.class('HttpUriSplit') function HttpUriSplit.method:__init(uri) assert(uri, "uri parameter required") local splitted_uri = {} local core_uri local query, fragment, path, authority -- uri = core_uri [ ?query ] [ #fragment ] core_uri, query, fragment = string.match(uri, '([^#?]*)[%?]*([^#]*)[#]*(.*)') -- query (+ split params) if query and query ~= '' then self.query = query local args = {} string.gsub(self.query, '([^=&]+)(=?([^&?]*))&?', function(p, q, r) args[p] = r or true return '' end) self.args = args end -- fragment if fragment and fragment ~= '' then self.fragment = fragment end -- scheme local temp = string.gsub(core_uri, '^(%a*)://', function(p) if p ~= '' then self.scheme = p end return '' end) -- authority and path authority, path = string.match(temp, '([^/]*)([/]*.*)$') if (path and path ~= '') then self.path = path end -- authority = [ userinfo @ ] host [ : port ] if authority and authority ~= '' then self.authority = authority -- userinfo authority = string.gsub(authority, "^([^@]*)@", function(p) if p ~= '' then self.userinfo = p end return '' end) -- port authority = string.gsub(authority, ":([^:][%d]+)$", function(p) if p ~= '' then self.port = p end return '' end) -- host if authority ~= '' then self.host = authority end -- userinfo = user : password (deprecated usage) if self.userinfo then local user, pass = string.match(self.userinfo, '(.*):(.*)') if user and user ~= '' then self.user = user self.pass = pass end end end end function HttpUriSplit.method:__tostring() local uri = {} -- authority components local auth = {} -- host if self.host then -- userinfo if self.user and self.pass then table.insert(auth, self.user) table.insert(auth, ':') table.insert(auth, self.pass) table.insert(auth, '@') end table.insert(auth, self.host) --port if self.port then table.insert(auth, ':') table.insert(auth, self.port) end end -- scheme and authority if #auth > 0 then if self.scheme then table.insert(uri, self.scheme) table.insert(uri, '://') table.insert(uri, table.concat(auth)) else table.insert(uri, table.concat(auth)) end end -- path if self.path then table.insert(uri, self.path) end -- query if self.query then local query = {} for k, v in pairs(self.args) do local q = {} table.insert(q, k) table.insert(q, v) table.insert(query, table.concat(q, '=')) end if #query > 0 then table.insert(uri, '?') table.insert(uri, table.concat(query, '&')) end end -- fragment if self.fragment then table.insert(uri, '#') table.insert(uri, self.fragment) end return table.concat(uri) end function HttpUriSplit.method:normalize() assert(self) -- decode percent-encoded octets of unresserved chars -- capitalize letters in escape sequences uri_safe_decode_split(self) -- use http as default scheme if not self.scheme and self.authority then self.scheme = 'http' end -- scheme and host are not case sensitive if self.scheme then self.scheme = string.lower(self.scheme) end if self.host then self.host = string.lower(self.host) end -- remove default port if self.port and self.port == '80' then self.port = nil end -- add '/' to path if self.scheme == 'http' and (not self.path or self.path == '') then self.path = '/' end -- normalize path according to rfc 3986 if self.path then self.path = remove_dot_segments(self.path) end return self end function module.uri.split(uri) return HttpUriSplit:new(uri) end function module.uri.normalize(uri) local splitted_uri = HttpUriSplit:new(uri) splitted_uri:normalize() return tostring(splitted_uri) end -- Cookie slitter object local HttpCookiesSplit = class.class('HttpCookiesSplit') function HttpCookiesSplit.method:__init(cookie_line) if cookie_line then string.gsub(cookie_line, '([^=;]+)=([^;]*);?', function(p, q) self[p] = q return '' end) end end function HttpCookiesSplit.method:__tostring() assert(self) local cookie = {} for k, v in pairs(self) do local ck = {} table.insert(ck, k) table.insert(ck, v) table.insert(cookie, table.concat(ck, '=')) end return table.concat(cookie, ';') end function module.cookies.split(cookie_line) return HttpCookiesSplit:new(cookie_line) end return module
mpl-2.0
nasomi/darkstar
scripts/zones/Kazham/npcs/Dheo_Nbolo.lua
15
1097
----------------------------------- -- Area: Kazham -- NPC: Dheo Nbolo -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00B5); -- scent from Blue Rafflesias else player:startEvent(0x005B); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/baked_popoto.lua
35
1283
----------------------------------------- -- ID: 4436 -- Item: Baked Popoto -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Dexterity -1 -- Vitality 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4436); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, -1); target:addMod(MOD_VIT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, -1); target:delMod(MOD_VIT, 2); end;
gpl-3.0
nasomi/darkstar
scripts/zones/RuAun_Gardens/npcs/qm4.lua
16
1444
----------------------------------- -- Area: Ru'Aun Gardens -- NPC: ??? (Suzaku's Spawn) -- Allows players to spawn the HNM Suzaku with a Gem of the South and a Summerstone. -- @pos -514 -70 -264 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/zones/RuAun_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade Gem of the South and Summerstone if (GetMobAction(17309983) == 0 and trade:hasItemQty(1420,1) and trade:hasItemQty(1421,1) and trade:getItemCount() == 2) then player:tradeComplete(); SpawnMob(17309983,300):updateClaim(player); -- Spawn Suzaku player:showText(npc,SKY_GOD_OFFSET + 7); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(SKY_GOD_OFFSET + 3); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
coolflyreg/gs
3rd/skynet-mingw/examples/watchdog.lua
53
1286
local skynet = require "skynet" local netpack = require "netpack" local CMD = {} local SOCKET = {} local gate local agent = {} function SOCKET.open(fd, addr) skynet.error("New client from : " .. addr) agent[fd] = skynet.newservice("agent") skynet.call(agent[fd], "lua", "start", { gate = gate, client = fd, watchdog = skynet.self() }) end local function close_agent(fd) local a = agent[fd] agent[fd] = nil if a then skynet.call(gate, "lua", "kick", fd) -- disconnect never return skynet.send(a, "lua", "disconnect") end end function SOCKET.close(fd) print("socket close",fd) close_agent(fd) end function SOCKET.error(fd, msg) print("socket error",fd, msg) close_agent(fd) end function SOCKET.warning(fd, size) -- size K bytes havn't send out in fd print("socket warning", fd, size) end function SOCKET.data(fd, msg) end function CMD.start(conf) skynet.call(gate, "lua", "open" , conf) end function CMD.close(fd) close_agent(fd) end skynet.start(function() skynet.dispatch("lua", function(session, source, cmd, subcmd, ...) if cmd == "socket" then local f = SOCKET[subcmd] f(...) -- socket api don't need return else local f = assert(CMD[cmd]) skynet.ret(skynet.pack(f(subcmd, ...))) end end) gate = skynet.newservice("gate") end)
gpl-2.0
ngeiswei/ardour
share/scripts/store_recall_mixer.lua
4
17372
ardour { ["type"] = "EditorAction", name = "Mixer Store", author = "Ardour Team", description = [[ Stores the current Mixer state as a file that can be read and recalled arbitrarily. Supports: processor settings, grouping, mute, solo, gain, trim, pan and processor ordering, plus re-adding certain deleted plugins. ]] } function factory() return function() local invalidate = {} local path = ARDOUR.LuaAPI.build_filename(Session:path(), "export", "params.lua") function mismatch_dialog(mismatch_str, checkbox_str) --string.format("Track didn't match ID: %d, but did match track in session: %s", 999, 'track') local dialog = { { type = "label", colspan = 5, title = mismatch_str }, { type = "checkbox", col=1, colspan = 1, key = "use", default = true, title = checkbox_str }, } local mismatch_return = LuaDialog.Dialog("", dialog):run() if mismatch_return then return mismatch_return['use'] else return false end end function get_processor_by_name(track, name) local i = 0 local proc = track:nth_processor(i) repeat if(proc:display_name() == name) then return proc else i = i + 1 end proc = track:nth_processor(i) until proc:isnil() end function new_plugin(name) for x = 0, 6 do local plugin = ARDOUR.LuaAPI.new_plugin(Session, name, x, "") if not(plugin:isnil()) then return plugin end end end function group_by_id(id) local id = tonumber(id) for g in Session:route_groups():iter() do local group_id = tonumber(g:to_stateful():id():to_s()) if group_id == id then return g end end end function group_by_name(name) for g in Session:route_groups():iter() do if g:name() == name then return g end end end function route_groupid_interrogate(t) local group = false for g in Session:route_groups():iter() do for r in g:route_list():iter() do if r:name() == t:name() then group = g:to_stateful():id():to_s() end end end return group end function route_group_interrogate(t) for g in Session:route_groups():iter() do for r in g:route_list():iter() do if r:name() == t:name() then return g end end end end function empty_last_store() --empty current file from last run local file = io.open(path, "w") file:write("") file:close() end function mark_tracks(selected) empty_last_store() local route_string = [[instance = { route_id = %d, route_name = '%s', gain_control = %f, trim_control = %f, pan_control = %s, muted = %s, soloed = %s, order = {%s}, cache = {%s}, group = %s, group_name = '%s' }]] local group_string = [[instance = { group_id = %s, name = '%s', routes = {%s}, }]] local processor_string = [[instance = { plugin_id = %d, display_name = '%s', owned_by_route_name = '%s', owned_by_route_id = %d, parameters = {%s}, active = %s, }]] local group_route_string = " [%d] = %s," local proc_order_string = " [%d] = %d," local proc_cache_string = " [%d] = '%s'," local params_string = " [%d] = %f," --ensure easy-to-read formatting doesn't make it through local route_string = string.gsub(route_string, "[\n\t]", "") local group_string = string.gsub(group_string, "[\n\t]", "") local processor_string = string.gsub(processor_string, "[\n\t]", "") local sel = Editor:get_selection () local groups_to_write = {} local i = 0 local tracks = Session:get_routes() if selected then tracks = sel.tracks:routelist() end for r in tracks:iter() do local group = route_group_interrogate(r) if group then local already_there = false for _, v in pairs(groups_to_write) do if group == v then already_there = true end end if not(already_there) then groups_to_write[#groups_to_write + 1] = group end end end for _, g in pairs(groups_to_write) do local tmp_str = "" for t in g:route_list():iter() do tmp_str = tmp_str .. string.format(group_route_string, i, t:to_stateful():id():to_s()) i = i + 1 end local group_str = string.format( group_string, g:to_stateful():id():to_s(), g:name(), tmp_str ) file = io.open(path, "a") file:write(group_str, "\r\n") file:close() end for r in tracks:iter() do if r:is_monitor () or r:is_auditioner () then goto nextroute end -- skip special routes local order = ARDOUR.ProcessorList() local x = 0 repeat local proc = r:nth_processor(x) if not proc:isnil() then order:push_back(proc) end x = x + 1 until proc:isnil() local route_group = route_group_interrogate(r) if route_group then route_group = route_group:name() else route_group = "" end local rid = r:to_stateful():id():to_s() local pan = r:pan_azimuth_control() if pan:isnil() then pan = false else pan = pan:get_value() end --sometimes a route doesn't have pan, like the master. local order_nmbr = 0 local tmp_order_str, tmp_cache_str = "", "" for p in order:iter() do local pid = p:to_stateful():id():to_s() if not(string.find(p:display_name(), "latcomp")) then tmp_order_str = tmp_order_str .. string.format(proc_order_string, order_nmbr, pid) tmp_cache_str = tmp_cache_str .. string.format(proc_cache_string, pid, p:display_name()) end order_nmbr = order_nmbr + 1 end local route_str = string.format( route_string, rid, r:name(), r:gain_control():get_value(), r:trim_control():get_value(), tostring(pan), r:muted(), r:soloed(), tmp_order_str, tmp_cache_str, route_groupid_interrogate(r), route_group ) file = io.open(path, "a") file:write(route_str, "\n") file:close() local i = 0 while true do local params = {} local proc = r:nth_plugin (i) if proc:isnil () then break end local active = proc:active() local id = proc:to_stateful():id():to_s() local plug = proc:to_insert ():plugin (0) local n = 0 -- count control-ports for j = 0, plug:parameter_count () - 1 do -- iterate over all plugin parameters if plug:parameter_is_control (j) then local label = plug:parameter_label (j) if plug:parameter_is_input (j) and label ~= "hidden" and label:sub (1,1) ~= "#" then local _, _, pd = ARDOUR.LuaAPI.plugin_automation(proc, n) local val = ARDOUR.LuaAPI.get_processor_param(proc, j, true) --print(r:name(), "->", proc:display_name(), label, val) params[n] = val end n = n + 1 end end i = i + 1 local tmp_params_str = "" for k, v in pairs(params) do tmp_params_str = tmp_params_str .. string.format(params_string, k, v) end local proc_str = string.format( processor_string, id, proc:display_name(), r:name(), r:to_stateful():id():to_s(), tmp_params_str, active ) file = io.open(path, "a") file:write(proc_str, "\n") file:close() end ::nextroute:: end end function recall(debug, dry_run) local file = io.open(path, "r") assert(file, "File not found!") local bypass_routes = {} local i = 0 for l in file:lines() do --print(i, l) local exec_line = dry_run["dothis-"..i] local skip_line = false if not(exec_line == nil) and not(exec_line) then skip_line = true end local plugin, route, group = false, false, false local f = load(l) if debug then print(i, string.sub(l, 0, 29), f) end if f then f() end if instance["route_id"] then route = true end if instance["plugin_id"] then plugin = true end if instance["group_id"] then group = true end if group then if skip_line then goto nextline end local g_id = instance["group_id"] local routes = instance["routes"] local name = instance["name"] local group = group_by_id(g_id) if not(group) then local group = Session:new_route_group(name) for _, v in pairs(routes) do local rt = Session:route_by_id(PBD.ID(v)) if rt:isnil() then rt = Session:route_by_name(name) end if not(rt:isnil()) then group:add(rt) end end end end if route then local substitution = tonumber(dry_run["destination-"..i]) if skip_line or (substitution == 0) then bypass_routes[#bypass_routes + 1] = instance["route_id"] goto nextline end local old_order = ARDOUR.ProcessorList() local route_id = instance["route_id"] local r_id = PBD.ID(instance["route_id"]) local muted, soloed = instance["muted"], instance["soloed"] local order = instance["order"] local cache = instance["cache"] local group = instance["group"] local group_name = instance["group_name"] local name = instance["route_name"] local gc, tc, pc = instance["gain_control"], instance["trim_control"], instance["pan_control"] if not(substitution == instance["route_id"]) then print('SUBSTITUTION FOR: ', name, substitution, Session:route_by_id(PBD.ID(substitution)):name()) --bypass_routes[#bypass_routes + 1] = route_id was_subbed = true r_id = PBD.ID(substitution) end local rt = Session:route_by_id(r_id) if rt:isnil() then rt = Session:route_by_name(name) end if rt:isnil() then goto nextline end local cur_group_id = route_groupid_interrogate(rt) if not(group) and (cur_group_id) then local g = group_by_id(cur_group_id) if g then g:remove(rt) end end local rt_group = group_by_name(group_name) if rt_group then rt_group:add(rt) end well_known = {'PRE', 'Trim', 'EQ', 'Comp', 'Fader', 'POST'} for k, v in pairs(order) do local proc = Session:processor_by_id(PBD.ID(1)) if not(was_subbed) then proc = Session:processor_by_id(PBD.ID(v)) end if proc:isnil() then for id, name in pairs(cache) do if v == id then proc = new_plugin(name) for _, control in pairs(well_known) do if name == control then proc = get_processor_by_name(rt, control) invalidate[v] = proc:to_stateful():id():to_s() goto nextproc end end if not(proc) then goto nextproc end if not(proc:isnil()) then rt:add_processor_by_index(proc, 0, nil, true) invalidate[v] = proc:to_stateful():id():to_s() end end end end ::nextproc:: if proc and not(proc:isnil()) then old_order:push_back(proc) end end rt:reorder_processors(old_order, nil) if muted then rt:mute_control():set_value(1, 1) else rt:mute_control():set_value(0, 1) end if soloed then rt:solo_control():set_value(1, 1) else rt:solo_control():set_value(0, 1) end rt:gain_control():set_value(gc, 1) rt:trim_control():set_value(tc, 1) if pc ~= false then rt:pan_azimuth_control():set_value(pc, 1) end end if plugin then if skip_line then goto nextline end --if the plugin is owned by a route --we decided not to use, skip it for _, v in pairs(bypass_routes) do if instance["owned_by_route_id"] == v then goto nextline end end local enable = {} local params = instance["parameters"] local p_id = instance["plugin_id"] local act = instance["active"] for k, v in pairs(invalidate) do --invalidate any deleted plugin's id if p_id == k then p_id = v end end local proc = Session:processor_by_id(PBD.ID(p_id)) if proc:isnil() then goto nextline end local plug = proc:to_insert():plugin(0) for k, v in pairs(params) do local label = plug:parameter_label(k) if string.find(label, "Assign") or string.find(label, "Enable") then --@ToDo: Check Plugin type == LADSPA or VST? enable[k] = v --queue any assignments/enables for after the initial parameter recalling to duck the 'in-on-change' feature end ARDOUR.LuaAPI.set_processor_param(proc, k, v) end for k, v in pairs(enable) do ARDOUR.LuaAPI.set_processor_param(proc, k, v) end if act then proc:activate() else proc:deactivate() end end ::nextline:: i = i + 1 end end function dry_run(debug) --returns a dialog-able table of --everything we do (logically) --in the recall function local route_values = {['----'] = "0"} for r in Session:get_routes():iter() do route_values[r:name()] = r:to_stateful():id():to_s() end local i = 0 local dry_table = { {type = "label", align = "left", key = "col-0-title" , col = 0, colspan = 1, title = 'Source Settings:'}, {type = "label", align = "left", key = "col-0-title" , col = 1, colspan = 1, title = 'Actions:'}, {type = "label", align = "left", key = "col-2-title" , col = 2, colspan = 1, title = 'Destination:'}, {type = "label", align = "left", key = "col-2-title" , col = 3, colspan = 1, title = 'Do this?'}, } local file = io.open(path, "r") assert(file, "File not found!") for l in file:lines() do local do_plugin, do_route, do_group = false, false, false local f = load(l) if debug then print(i, string.sub(l, 0, 29), f) end if f then f() end if instance["route_id"] then do_route = true end if instance["plugin_id"] then do_plugin = true end if instance["group_id"] then do_group = true end if do_group then local group_id = instance["group_id"] local group_name = instance["name"] local dlg_title, action_title = "", "" local group_ptr = group_by_id(group_id) if not(group_ptr) then new_group = Session:new_route_group(group_name) dlg_title = string.format("Cannot Find: (Group) %s.", group_name, new_group:name()) action_title = "will create and use settings" else dlg_title = string.format("Found by ID: (Group) %s.", group_ptr:name()) action_title = "will use group settings" end table.insert(dry_table, { type = "label", align = "left", key = "group-"..i , col = 0, colspan = 1, title = dlg_title }) table.insert(dry_table, { type = "label", align = "left", key = "group-"..i , col = 1, colspan = 1, title = action_title }) table.insert(dry_table, { type = "checkbox", col=3, colspan = 1, key = "dothis-"..i, default = true, title = "line:"..i }) end if do_route then local route_id = instance["route_id"] local route_name = instance["route_name"] local dlg_title = "" local route_ptr = Session:route_by_id(PBD.ID(route_id)) if route_ptr:isnil() then route_ptr = Session:route_by_name(route_name) if not(route_ptr:isnil()) then dlg_title = string.format("Found by Name: (Rotue) %s", route_ptr:name()) action_title = "will use route settings" else dlg_title = string.format("Cannot Find: (Route) %s", route_name) action_title = "will be ignored" end else dlg_title = string.format("Found by ID: (Route) %s", route_ptr:name()) action_title = "will use route settings" end if route_ptr:isnil() then name = route_name else name = route_ptr:name() end table.insert(dry_table, { type = "label", align = "left", key = "route-"..i , col = 0, colspan = 1, title = dlg_title }) table.insert(dry_table, { type = "label", align = "left", key = "action-"..i , col = 1, colspan = 1, title = action_title }) table.insert(dry_table, { type = "dropdown", align = "left", key = "destination-"..i, col = 2, colspan = 1, title = "", values = route_values, default = name or "----" }) table.insert(dry_table, { type = "checkbox", col=3, colspan = 1, key = "dothis-"..i, default = true, title = "line"..i }) end i = i + 1 end return dry_table end local dialog_options = { { type = "label", colspan = 5, title = "" }, { type = "radio", col = 1, colspan = 7, key = "select", title = "", values ={ ["Store"] = "store", ["Recall"] = "recall" }, default = "Store"}, { type = "label", colspan = 5, title = "" }, } local store_options = { { type = "label", colspan = 5, title = "" }, { type = "checkbox", col=1, colspan = 1, key = "selected", default = false, title = "Selected tracks only"}, { type = "entry", col=2, colspan = 10, key = "filename", default = "params", title = "Store name" }, { type = "label", colspan = 5, title = "" }, } local recall_options = { { type = "label", colspan = 5, title = "" }, { type = "file", col =1, colspan = 10, key = "file", title = "Select a File", path = ARDOUR.LuaAPI.build_filename(Session:path(), "export", "params.lua") }, { type = "label", colspan = 5, title = "" }, } local rv = LuaDialog.Dialog("Mixer Store:", dialog_options):run() if rv then local choice = rv["select"] if choice == "store" then local srv = LuaDialog.Dialog("Mixer Store:", store_options):run() if srv then empty_last_store() --ensures that params.lua will exist for the recall dialog path = ARDOUR.LuaAPI.build_filename(Session:path(), "export", srv["filename"] .. ".lua") mark_tracks(srv['selected']) end end if choice == "recall" then local rrv = LuaDialog.Dialog("Mixer Store:", recall_options):run() if rrv then if rrv['file'] ~= path then path = rrv['file'] end --recall(true) local dry_return = LuaDialog.Dialog("Mixer Store:", dry_run(true)):run() if dry_return then recall(true, dry_return) end end end end end end
gpl-2.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-radvd/luasrc/model/cbi/radvd/interface.lua
78
7996
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - Interface %q", "?"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "interface" then luci.http.redirect(m.redirect) return end m.uci:foreach("radvd", "interface", function(s) if s['.name'] == sid and s.interface then m.title = translatef("Radvd - Interface %q", s.interface) return false end end) s = m:section(NamedSection, sid, "interface", translate("Interface Configuration")) s.addremove = false s:tab("general", translate("General")) s:tab("timing", translate("Timing")) s:tab("mobile", translate("Mobile IPv6")) -- -- General -- o = s:taboption("general", Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:taboption("general", Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:taboption("general", DynamicList, "client", translate("Clients"), translate("Restrict communication to specified clients, leave empty to use multicast")) o.rmempty = true o.datatype = "ip6addr" o.placeholder = "any" function o.cfgvalue(...) local v = Value.cfgvalue(...) local l = { } for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:taboption("general", Flag, "AdvSendAdvert", translate("Enable advertisements"), translate("Enables router advertisements and solicitations")) o.rmempty = false function o.write(self, section, value) if value == "1" then m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "IgnoreIfMissing", 1) end m.uci:set("radvd", section, "AdvSendAdvert", value) end o = s:taboption("general", Flag, "UnicastOnly", translate("Unicast only"), translate("Indicates that the underlying link is not broadcast capable, prevents unsolicited advertisements from being sent")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvManagedFlag", translate("Managed flag"), translate("Enables the additional stateful administered autoconfiguration protocol (RFC2462)")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvOtherConfigFlag", translate("Configuration flag"), translate("Enables the autoconfiguration of additional, non address information (RFC2462)")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvSourceLLAddress", translate("Source link-layer address"), translate("Includes the link-layer address of the outgoing interface in the RA")) o.rmempty = false o.default = "1" o:depends("AdvSendAdvert", "1") o = s:taboption("general", Value, "AdvLinkMTU", translate("Link MTU"), translate("Advertises the given link MTU in the RA if specified. 0 disables MTU advertisements")) o.datatype = "uinteger" o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("general", Value, "AdvCurHopLimit", translate("Current hop limit"), translate("Advertises the default Hop Count value for outgoing unicast packets in the RA. 0 disables hopcount advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 64 o:depends("AdvSendAdvert", "1") o = s:taboption("general", ListValue, "AdvDefaultPreference", translate("Default preference"), translate("Advertises the default router preference")) o.optional = false o.default = "medium" o:value("low", translate("low")) o:value("medium", translate("medium")) o:value("high", translate("high")) o:depends("AdvSendAdvert", "1") -- -- Timing -- o = s:taboption("timing", Value, "MinRtrAdvInterval", translate("Minimum advertisement interval"), translate("The minimum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 198 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "MaxRtrAdvInterval", translate("Maximum advertisement interval"), translate("The maximum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 600 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "MinDelayBetweenRAs", translate("Minimum advertisement delay"), translate("The minimum time allowed between sending multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 3 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvReachableTime", translate("Reachable time"), translate("Advertises assumed reachability time in milliseconds of neighbours in the RA if specified. 0 disables reachability advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvRetransTimer", translate("Retransmit timer"), translate("Advertises wait time in milliseconds between Neighbor Solicitation messages in the RA if specified. 0 disables retransmit advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvDefaultLifetime", translate("Default lifetime"), translate("Advertises the lifetime of the default router in seconds. 0 indicates that the node is no default router")) o.datatype = "uinteger" o.optional = false o.placeholder = 1800 o:depends("AdvSendAdvert", "1") -- -- Mobile -- o = s:taboption("mobile", Flag, "AdvHomeAgentFlag", translate("Advertise Home Agent flag"), translate("Advertises Mobile IPv6 Home Agent capability (RFC3775)")) o:depends("AdvSendAdvert", "1") o = s:taboption("mobile", Flag, "AdvIntervalOpt", translate("Mobile IPv6 interval option"), translate("Include Mobile IPv6 Advertisement Interval option to RA")) o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Flag, "AdvHomeAgentInfo", translate("Home Agent information"), translate("Include Home Agent Information in the RA")) o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Flag, "AdvMobRtrSupportFlag", translate("Mobile IPv6 router registration"), translate("Advertises Mobile Router registration capability (NEMO Basic)")) o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Value, "HomeAgentLifetime", translate("Home Agent lifetime"), translate("Advertises the time in seconds the router is offering Mobile IPv6 Home Agent services")) o.datatype = "uinteger" o.optional = false o.placeholder = 1800 o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Value, "HomeAgentPreference", translate("Home Agent preference"), translate("The preference for the Home Agent sending this RA")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) return m
gpl-2.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/settings.lua
1
9204
-- In this file you can set up all the properties and settings for your game mode. ENABLE_HERO_RESPAWN = true -- Should the heroes automatically respawn on a timer or stay dead until manually respawned UNIVERSAL_SHOP_MODE = false -- Should the main shop contain Secret Shop items as well as regular items ALLOW_SAME_HERO_SELECTION = true -- Should we let people select the same hero as each other HERO_SELECTION_TIME = 5 -- How long should we let people select their hero? PRE_GAME_TIME = 0 -- How long after people select their heroes should the horn blow and the game start? POST_GAME_TIME = 8 if IsInToolsMode() then POST_GAME_TIME = 8000 end -- How long should we let people look at the scoreboard before closing the server automatically? TREE_REGROW_TIME = 60.0 -- How long should it take individual trees to respawn after being cut down/destroyed? ALLY_SELECTION_TIME = 10 ALLY_DISPLAY_TIME = 3 GOLD_PER_TICK = 0 -- How much gold should players get per tick? GOLD_TICK_TIME = 1000 -- How long should we wait in seconds between gold ticks? RECOMMENDED_BUILDS_DISABLED = true -- Should we disable the recommened builds for heroes CAMERA_DISTANCE_OVERRIDE = -1 -- How far out should we allow the camera to go? Use -1 for the default (1134) while still allowing for panorama camera distance changes MINIMAP_ICON_SIZE = 1 -- What icon size should we use for our heroes? MINIMAP_CREEP_ICON_SIZE = 1 -- What icon size should we use for creeps? MINIMAP_RUNE_ICON_SIZE = 1 -- What icon size should we use for runes? RUNE_SPAWN_TIME = 120 -- How long in seconds should we wait between rune spawns? CUSTOM_BUYBACK_COST_ENABLED = false -- Should we use a custom buyback cost setting? CUSTOM_BUYBACK_COOLDOWN_ENABLED = false -- Should we use a custom buyback time? BUYBACK_ENABLED = false -- Should we allow people to buyback when they die? DISABLE_FOG_OF_WAR_ENTIRELY = true -- Should we disable fog of war entirely for both teams? USE_UNSEEN_FOG_OF_WAR = false -- Should we make unseen and fogged areas of the map completely black until uncovered by each team? -- Note: DISABLE_FOG_OF_WAR_ENTIRELY must be false for USE_UNSEEN_FOG_OF_WAR to work USE_STANDARD_DOTA_BOT_THINKING = false -- Should we have bots act like they would in Dota? (This requires 3 lanes, normal items, etc) USE_STANDARD_HERO_GOLD_BOUNTY = false -- Should we give gold for hero kills the same as in Dota, or allow those values to be changed? USE_CUSTOM_TOP_BAR_VALUES = false -- Should we do customized top bar values or use the default kill count per team? TOP_BAR_VISIBLE = false -- Should we display the top bar score/count at all? SHOW_KILLS_ON_TOPBAR = false -- Should we display kills only on the top bar? (No denies, suicides, kills by neutrals) Requires USE_CUSTOM_TOP_BAR_VALUES ENABLE_TOWER_BACKDOOR_PROTECTION = false-- Should we enable backdoor protection for our towers? REMOVE_ILLUSIONS_ON_DEATH = false -- Should we remove all illusions if the main hero dies? DISABLE_GOLD_SOUNDS = false -- Should we disable the gold sound when players get gold? END_GAME_ON_KILLS = false -- Should the game end after a certain number of kills? KILLS_TO_END_GAME_FOR_TEAM = 50 -- How many kills for a team should signify an end of game? USE_CUSTOM_HERO_LEVELS = true -- Should we allow heroes to have custom levels? MAX_LEVEL = 50 -- What level should we let heroes get to? USE_CUSTOM_XP_VALUES = true -- Should we use custom XP values to level up heroes, or the default Dota numbers? -- Fill this table up with the required XP per level if you want to change it XP_PER_LEVEL_TABLE = {} for i=1,MAX_LEVEL do XP_PER_LEVEL_TABLE[i] = (i-1) * 100 end ENABLE_FIRST_BLOOD = false -- Should we enable first blood for the first kill in this game? HIDE_KILL_BANNERS = true -- Should we hide the kill banners that show when a player is killed? LOSE_GOLD_ON_DEATH = true -- Should we have players lose the normal amount of dota gold on death? SHOW_ONLY_PLAYER_INVENTORY = false -- Should we only allow players to see their own inventory even when selecting other units? DISABLE_STASH_PURCHASING = false -- Should we prevent players from being able to buy items into their stash when not at a shop? DISABLE_ANNOUNCER = false -- Should we disable the announcer from working in the game? FORCE_PICKED_HERO = nil--"npc_dota_hero_wisp" -- What hero should we force all players to spawn as? (e.g. "npc_dota_hero_axe"). Use nil to allow players to pick their own hero. FIXED_RESPAWN_TIME = 3 -- What time should we use for a fixed respawn timer? Use -1 to keep the default dota behavior. FOUNTAIN_CONSTANT_MANA_REGEN = -1 -- What should we use for the constant fountain mana regen? Use -1 to keep the default dota behavior. FOUNTAIN_PERCENTAGE_MANA_REGEN = -1 -- What should we use for the percentage fountain mana regen? Use -1 to keep the default dota behavior. FOUNTAIN_PERCENTAGE_HEALTH_REGEN = -1 -- What should we use for the percentage fountain health regen? Use -1 to keep the default dota behavior. MAXIMUM_ATTACK_SPEED = 600 -- What should we use for the maximum attack speed? MINIMUM_ATTACK_SPEED = 20 -- What should we use for the minimum attack speed? GAME_END_DELAY = 1 -- How long should we wait after the game winner is set to display the victory banner and End Screen? Use -1 to keep the default (about 10 seconds) VICTORY_MESSAGE_DURATION = 3 -- How long should we wait after the victory message displays to show the End Screen? Use STARTING_GOLD = 500 -- How much starting gold should we give to each player? DISABLE_DAY_NIGHT_CYCLE = true -- Should we disable the day night cycle from naturally occurring? (Manual adjustment still possible) DISABLE_KILLING_SPREE_ANNOUNCER = true -- Shuold we disable the killing spree announcer? DISABLE_STICKY_ITEM = true -- Should we disable the sticky item button in the quick buy area? SKIP_TEAM_SETUP = false -- Should we skip the team setup entirely? ENABLE_AUTO_LAUNCH = false -- Should we automatically have the game complete team setup after AUTO_LAUNCH_DELAY seconds? AUTO_LAUNCH_DELAY = 5 -- How long should the default team selection launch timer be? The default for custom games is 30. Setting to 0 will skip team selection. LOCK_TEAM_SETUP = false -- Should we lock the teams initially? Note that the host can still unlock the teams -- NOTE: You always need at least 2 non-bounty type runes to be able to spawn or your game will crash! ENABLED_RUNES = {} -- Which runes should be enabled to spawn in our game mode? ENABLED_RUNES[DOTA_RUNE_DOUBLEDAMAGE] = true ENABLED_RUNES[DOTA_RUNE_HASTE] = true ENABLED_RUNES[DOTA_RUNE_ILLUSION] = true ENABLED_RUNES[DOTA_RUNE_INVISIBILITY] = true ENABLED_RUNES[DOTA_RUNE_REGENERATION] = true ENABLED_RUNES[DOTA_RUNE_BOUNTY] = true ENABLED_RUNES[DOTA_RUNE_ARCANE] = true MAX_NUMBER_OF_TEAMS = 4 -- How many potential teams can be in this game mode? USE_CUSTOM_TEAM_COLORS = true -- Should we use custom team colors? USE_CUSTOM_TEAM_COLORS_FOR_PLAYERS = true -- Should we use custom team colors to color the players/minimap? TEAM_COLORS = {} -- If USE_CUSTOM_TEAM_COLORS is set, use these colors. TEAM_COLORS[DOTA_TEAM_GOODGUYS] = { 61, 210, 150 } -- Teal TEAM_COLORS[DOTA_TEAM_BADGUYS] = { 243, 201, 9 } -- Yellow TEAM_COLORS[DOTA_TEAM_CUSTOM_1] = { 197, 77, 168 } -- Pink TEAM_COLORS[DOTA_TEAM_CUSTOM_2] = { 255, 108, 0 } -- Orange TEAM_COLORS[DOTA_TEAM_CUSTOM_3] = { 52, 85, 255 } -- Blue TEAM_COLORS[DOTA_TEAM_CUSTOM_4] = { 101, 212, 19 } -- Green TEAM_COLORS[DOTA_TEAM_CUSTOM_5] = { 129, 83, 54 } -- Brown TEAM_COLORS[DOTA_TEAM_CUSTOM_6] = { 27, 192, 216 } -- Cyan TEAM_COLORS[DOTA_TEAM_CUSTOM_7] = { 199, 228, 13 } -- Olive TEAM_COLORS[DOTA_TEAM_CUSTOM_8] = { 140, 42, 244 } -- Purple USE_AUTOMATIC_PLAYERS_PER_TEAM = false -- Should we set the number of players to 10 / MAX_NUMBER_OF_TEAMS? CUSTOM_TEAM_PLAYER_COUNT = {} -- If we're not automatically setting the number of players per team, use this table CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_GOODGUYS] = 1 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_BADGUYS] = 1 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_1] = 1 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_2] = 1 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_3] = 0 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_4] = 0 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_5] = 0 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_6] = 0 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_7] = 0 CUSTOM_TEAM_PLAYER_COUNT[DOTA_TEAM_CUSTOM_8] = 0
mit
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/flower_cyan_9.meta.lua
18
1947
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 80, light_colors = { "0 190 171 255", "6 190 39 255", "153 229 80 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/flower_cyan_4.meta.lua
18
1947
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 80, light_colors = { "0 190 171 255", "6 190 39 255", "153 229 80 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nico57c/love2d-lualib
Tools/Object.lua
1
1060
-- Tools/Object.lua module("Ncr7.tObject", package.seeall) New = {} function New._object(class, o, metatable) local o = o or {} o._global=_G if(nil~=metatable) then setmetatable(o, table.merge(metatable,{ __index = class } ) ) else setmetatable(o, { __index = class }) end return o end New._mt = {} function New._mt.__index(table, key) --local class = _G[key] local class = key return type(class.initialize) == 'function' and class.initialize or function() return New._object(class) end end setmetatable(New,New._mt) function deepcopy(o, seen) seen = seen or {} if o == nil then return nil end if seen[o] then return seen[o] end local no if type(o) == 'table' then no = {} seen[o] = no for k, v in next, o, nil do no[deepcopy(k, seen)] = deepcopy(v, seen) end setmetatable(no, deepcopy(getmetatable(o), seen)) else -- number, string, boolean, etc no = o end return no end function getGlobal() return _G end function setGobal(global) _G = global end function _NULL_() end
mit
nasomi/darkstar
scripts/globals/mobskills/Prishe_Item_2.lua
53
1486
--------------------------------------------- -- Prishe Item 2 --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/zones/Empyreal_Paradox/TextIDs"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (target:hasStatusEffect(EFFECT_PHYSICAL_SHIELD) or target:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then return 1; elseif (mob:hasStatusEffect(EFFECT_PLAGUE) or mob:hasStatusEffect(EFFECT_CURSE_I) or mob:hasStatusEffect(EFFECT_MUTE)) then return 0; elseif (math.random() < 0.25) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) skill:setMsg(0); if (mob:hasStatusEffect(EFFECT_PLAGUE) or mob:hasStatusEffect(EFFECT_CURSE_I) or mob:hasStatusEffect(EFFECT_MUTE)) then -- use Remedy! mob:messageText(mob, PRISHE_TEXT + 12, false); mob:delStatusEffect(EFFECT_PLAGUE); mob:delStatusEffect(EFFECT_CURSE_I); mob:delStatusEffect(EFFECT_MUTE); elseif (math.random() < 0.5) then -- Carnal Incense! mob:messageText(mob, PRISHE_TEXT + 10, false); mob:addStatusEffect(EFFECT_PHYSICAL_SHIELD, 0, 0, 30); else -- Spiritual Incense! mob:messageText(mob, PRISHE_TEXT + 11, false); mob:addStatusEffect(EFFECT_MAGIC_SHIELD, 0, 0, 30); end return 0; end;
gpl-3.0