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
Flourish-Team/Flourish
Premake/source/binmodules/luasocket/test/urltest.lua
12
19140
local socket = require("socket") socket.url = require("socket.url") dofile("testsupport.lua") local check_build_url = function(parsed) local built = socket.url.build(parsed) if built ~= parsed.url then print("built is different from expected") print(built) print(expected) os.exit() end end local check_protect = function(parsed, path, unsafe) local built = socket.url.build_path(parsed, unsafe) if built ~= path then print(built, path) print("path composition failed.") os.exit() end end local check_invert = function(url) local parsed = socket.url.parse(url) parsed.path = socket.url.build_path(socket.url.parse_path(parsed.path)) local rebuilt = socket.url.build(parsed) if rebuilt ~= url then print(url, rebuilt) print("original and rebuilt are different") os.exit() end end local check_parse_path = function(path, expect) local parsed = socket.url.parse_path(path) for i = 1, math.max(#parsed, #expect) do if parsed[i] ~= expect[i] then print(path) os.exit() end end if expect.is_directory ~= parsed.is_directory then print(path) print("is_directory mismatch") os.exit() end if expect.is_absolute ~= parsed.is_absolute then print(path) print("is_absolute mismatch") os.exit() end local built = socket.url.build_path(expect) if built ~= path then print(built, path) print("path composition failed.") os.exit() end end local check_absolute_url = function(base, relative, absolute) local res = socket.url.absolute(base, relative) if res ~= absolute then io.write("absolute: In test for '", relative, "' expected '", absolute, "' but got '", res, "'\n") os.exit() end end local check_parse_url = function(gaba) local url = gaba.url gaba.url = nil local parsed = socket.url.parse(url) for i, v in pairs(gaba) do if v ~= parsed[i] then io.write("parse: In test for '", url, "' expected ", i, " = '", v, "' but got '", tostring(parsed[i]), "'\n") for i,v in pairs(parsed) do print(i,v) end os.exit() end end for i, v in pairs(parsed) do if v ~= gaba[i] then io.write("parse: In test for '", url, "' expected ", i, " = '", tostring(gaba[i]), "' but got '", v, "'\n") for i,v in pairs(parsed) do print(i,v) end os.exit() end end end print("testing URL parsing") check_parse_url{ url = "scheme://user:pass$%?#wd@host:port/path;params?query#fragment", scheme = "scheme", authority = "user:pass$%?#wd@host:port", host = "host", port = "port", userinfo = "user:pass$%?#wd", password = "pass$%?#wd", user = "user", path = "/path", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://user:pass?#wd@host:port/path;params?query#fragment", scheme = "scheme", authority = "user:pass?#wd@host:port", host = "host", port = "port", userinfo = "user:pass?#wd", password = "pass?#wd", user = "user", path = "/path", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://user:pass-wd@host:port/path;params?query#fragment", scheme = "scheme", authority = "user:pass-wd@host:port", host = "host", port = "port", userinfo = "user:pass-wd", password = "pass-wd", user = "user", path = "/path", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://user:pass#wd@host:port/path;params?query#fragment", scheme = "scheme", authority = "user:pass#wd@host:port", host = "host", port = "port", userinfo = "user:pass#wd", password = "pass#wd", user = "user", path = "/path", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://user:pass#wd@host:port/path;params?query", scheme = "scheme", authority = "user:pass#wd@host:port", host = "host", port = "port", userinfo = "user:pass#wd", password = "pass#wd", user = "user", path = "/path", params = "params", query = "query", } check_parse_url{ url = "scheme://userinfo@host:port/path;params?query#fragment", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://user:password@host:port/path;params?query#fragment", scheme = "scheme", authority = "user:password@host:port", host = "host", port = "port", userinfo = "user:password", user = "user", password = "password", path = "/path", params = "params", query = "query", fragment = "fragment", } check_parse_url{ url = "scheme://userinfo@host:port/path;params?query#", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", params = "params", query = "query", fragment = "" } check_parse_url{ url = "scheme://userinfo@host:port/path;params?#fragment", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", params = "params", query = "", fragment = "fragment" } check_parse_url{ url = "scheme://userinfo@host:port/path;params#fragment", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", params = "params", fragment = "fragment" } check_parse_url{ url = "scheme://userinfo@host:port/path;?query#fragment", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", params = "", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://userinfo@host:port/path?query#fragment", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://userinfo@host:port/;params?query#fragment", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://userinfo@host:port", scheme = "scheme", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", } check_parse_url{ url = "//userinfo@host:port/path;params?query#fragment", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "//userinfo@host:port/path", authority = "userinfo@host:port", host = "host", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", } check_parse_url{ url = "//userinfo@host/path", authority = "userinfo@host", host = "host", userinfo = "userinfo", user = "userinfo", path = "/path", } check_parse_url{ url = "//user:password@host/path", authority = "user:password@host", host = "host", userinfo = "user:password", password = "password", user = "user", path = "/path", } check_parse_url{ url = "//user:@host/path", authority = "user:@host", host = "host", userinfo = "user:", password = "", user = "user", path = "/path", } check_parse_url{ url = "//user@host:port/path", authority = "user@host:port", host = "host", userinfo = "user", user = "user", port = "port", path = "/path", } check_parse_url{ url = "//host:port/path", authority = "host:port", port = "port", host = "host", path = "/path", } check_parse_url{ url = "//host/path", authority = "host", host = "host", path = "/path", } check_parse_url{ url = "//host", authority = "host", host = "host", } check_parse_url{ url = "/path", path = "/path", } check_parse_url{ url = "path", path = "path", } -- IPv6 tests check_parse_url{ url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html", scheme = "http", host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210", authority = "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80", port = "80", path = "/index.html" } check_parse_url{ url = "http://[1080:0:0:0:8:800:200C:417A]/index.html", scheme = "http", host = "1080:0:0:0:8:800:200C:417A", authority = "[1080:0:0:0:8:800:200C:417A]", path = "/index.html" } check_parse_url{ url = "http://[3ffe:2a00:100:7031::1]", scheme = "http", host = "3ffe:2a00:100:7031::1", authority = "[3ffe:2a00:100:7031::1]", } check_parse_url{ url = "http://[1080::8:800:200C:417A]/foo", scheme = "http", host = "1080::8:800:200C:417A", authority = "[1080::8:800:200C:417A]", path = "/foo" } check_parse_url{ url = "http://[::192.9.5.5]/ipng", scheme = "http", host = "::192.9.5.5", authority = "[::192.9.5.5]", path = "/ipng" } check_parse_url{ url = "http://[::FFFF:129.144.52.38]:80/index.html", scheme = "http", host = "::FFFF:129.144.52.38", port = "80", authority = "[::FFFF:129.144.52.38]:80", path = "/index.html" } check_parse_url{ url = "http://[2010:836B:4179::836B:4179]", scheme = "http", host = "2010:836B:4179::836B:4179", authority = "[2010:836B:4179::836B:4179]", } check_parse_url{ url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment", authority = "userinfo@[::FFFF:129.144.52.38]:port", host = "::FFFF:129.144.52.38", port = "port", userinfo = "userinfo", user = "userinfo", path = "/path", params = "params", query = "query", fragment = "fragment" } check_parse_url{ url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment", scheme = "scheme", authority = "user:password@[::192.9.5.5]:port", host = "::192.9.5.5", port = "port", userinfo = "user:password", user = "user", password = "password", path = "/path", params = "params", query = "query", fragment = "fragment" } print("testing URL building") check_build_url { url = "scheme://user:password@host:port/path;params?query#fragment", scheme = "scheme", host = "host", port = "port", user = "user", password = "password", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url{ url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment", host = "::FFFF:129.144.52.38", port = "port", user = "userinfo", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url{ url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment", scheme = "scheme", host = "::192.9.5.5", port = "port", user = "user", password = "password", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url { url = "scheme://user:password@host/path;params?query#fragment", scheme = "scheme", host = "host", user = "user", password = "password", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url { url = "scheme://user@host/path;params?query#fragment", scheme = "scheme", host = "host", user = "user", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url { url = "scheme://host/path;params?query#fragment", scheme = "scheme", host = "host", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url { url = "scheme://host/path;params#fragment", scheme = "scheme", host = "host", path = "/path", params = "params", fragment = "fragment" } check_build_url { url = "scheme://host/path#fragment", scheme = "scheme", host = "host", path = "/path", fragment = "fragment" } check_build_url { url = "scheme://host/path", scheme = "scheme", host = "host", path = "/path", } check_build_url { url = "//host/path", host = "host", path = "/path", } check_build_url { url = "/path", path = "/path", } check_build_url { url = "scheme://user:password@host:port/path;params?query#fragment", scheme = "scheme", host = "host", port = "port", user = "user", userinfo = "not used", password = "password", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url { url = "scheme://user:password@host:port/path;params?query#fragment", scheme = "scheme", host = "host", port = "port", user = "user", userinfo = "not used", authority = "not used", password = "password", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url { url = "scheme://user:password@host:port/path;params?query#fragment", scheme = "scheme", host = "host", port = "port", userinfo = "user:password", authority = "not used", path = "/path", params = "params", query = "query", fragment = "fragment" } check_build_url { url = "scheme://user:password@host:port/path;params?query#fragment", scheme = "scheme", authority = "user:password@host:port", path = "/path", params = "params", query = "query", fragment = "fragment" } -- standard RFC tests print("testing absolute resolution") check_absolute_url("http://a/b/c/d;p?q#f", "g:h", "g:h") check_absolute_url("http://a/b/c/d;p?q#f", "g", "http://a/b/c/g") check_absolute_url("http://a/b/c/d;p?q#f", "./g", "http://a/b/c/g") check_absolute_url("http://a/b/c/d;p?q#f", "g/", "http://a/b/c/g/") check_absolute_url("http://a/b/c/d;p?q#f", "/g", "http://a/g") check_absolute_url("http://a/b/c/d;p?q#f", "//g", "http://g") check_absolute_url("http://a/b/c/d;p?q#f", "?y", "http://a/b/c/d;p?y") check_absolute_url("http://a/b/c/d;p?q#f", "g?y", "http://a/b/c/g?y") check_absolute_url("http://a/b/c/d;p?q#f", "g?y/./x", "http://a/b/c/g?y/./x") check_absolute_url("http://a/b/c/d;p?q#f", "#s", "http://a/b/c/d;p?q#s") check_absolute_url("http://a/b/c/d;p?q#f", "g#s", "http://a/b/c/g#s") check_absolute_url("http://a/b/c/d;p?q#f", "g#s/./x", "http://a/b/c/g#s/./x") check_absolute_url("http://a/b/c/d;p?q#f", "g?y#s", "http://a/b/c/g?y#s") check_absolute_url("http://a/b/c/d;p?q#f", ";x", "http://a/b/c/d;x") check_absolute_url("http://a/b/c/d;p?q#f", "g;x", "http://a/b/c/g;x") check_absolute_url("http://a/b/c/d;p?q#f", "g;x?y#s", "http://a/b/c/g;x?y#s") check_absolute_url("http://a/b/c/d;p?q#f", ".", "http://a/b/c/") check_absolute_url("http://a/b/c/d;p?q#f", "./", "http://a/b/c/") check_absolute_url("http://a/b/c/d;p?q#f", "..", "http://a/b/") check_absolute_url("http://a/b/c/d;p?q#f", "../", "http://a/b/") check_absolute_url("http://a/b/c/d;p?q#f", "../g", "http://a/b/g") check_absolute_url("http://a/b/c/d;p?q#f", "../..", "http://a/") check_absolute_url("http://a/b/c/d;p?q#f", "../../", "http://a/") check_absolute_url("http://a/b/c/d;p?q#f", "../../g", "http://a/g") check_absolute_url("http://a/b/c/d;p?q#f", "", "http://a/b/c/d;p?q#f") check_absolute_url("http://a/b/c/d;p?q#f", "/./g", "http://a/./g") check_absolute_url("http://a/b/c/d;p?q#f", "/../g", "http://a/../g") check_absolute_url("http://a/b/c/d;p?q#f", "g.", "http://a/b/c/g.") check_absolute_url("http://a/b/c/d;p?q#f", ".g", "http://a/b/c/.g") check_absolute_url("http://a/b/c/d;p?q#f", "g..", "http://a/b/c/g..") check_absolute_url("http://a/b/c/d;p?q#f", "..g", "http://a/b/c/..g") check_absolute_url("http://a/b/c/d;p?q#f", "./../g", "http://a/b/g") check_absolute_url("http://a/b/c/d;p?q#f", "./g/.", "http://a/b/c/g/") check_absolute_url("http://a/b/c/d;p?q#f", "g/./h", "http://a/b/c/g/h") check_absolute_url("http://a/b/c/d;p?q#f", "g/../h", "http://a/b/c/h") -- extra tests check_absolute_url("//a/b/c/d;p?q#f", "d/e/f", "//a/b/c/d/e/f") check_absolute_url("/a/b/c/d;p?q#f", "d/e/f", "/a/b/c/d/e/f") check_absolute_url("a/b/c/d", "d/e/f", "a/b/c/d/e/f") check_absolute_url("a/b/c/d/../", "d/e/f", "a/b/c/d/e/f") check_absolute_url("http://velox.telemar.com.br", "/dashboard/index.html", "http://velox.telemar.com.br/dashboard/index.html") print("testing path parsing and composition") check_parse_path("/eu/tu/ele", { "eu", "tu", "ele"; is_absolute = 1 }) check_parse_path("/eu/", { "eu"; is_absolute = 1, is_directory = 1 }) check_parse_path("eu/tu/ele/nos/vos/eles/", { "eu", "tu", "ele", "nos", "vos", "eles"; is_directory = 1}) check_parse_path("/", { is_absolute = 1, is_directory = 1}) check_parse_path("", { }) check_parse_path("eu%01/%02tu/e%03l%04e/nos/vos%05/e%12les/", { "eu\1", "\2tu", "e\3l\4e", "nos", "vos\5", "e\18les"; is_directory = 1}) check_parse_path("eu/tu", { "eu", "tu" }) print("testing path protection") check_protect({ "eu", "-_.!~*'():@&=+$,", "tu" }, "eu/-_.!~*'():@&=+$,/tu") check_protect({ "eu ", "~diego" }, "eu%20/~diego") check_protect({ "/eu>", "<diego?" }, "%2Feu%3E/%3Cdiego%3F") check_protect({ "\\eu]", "[diego`" }, "%5Ceu%5D/%5Bdiego%60") check_protect({ "{eu}", "|diego\127" }, "%7Beu%7D/%7Cdiego%7F") check_protect({ "eu ", "~diego" }, "eu /~diego", 1) check_protect({ "/eu>", "<diego?" }, "/eu>/<diego?", 1) check_protect({ "\\eu]", "[diego`" }, "\\eu]/[diego`", 1) check_protect({ "{eu}", "|diego\127" }, "{eu}/|diego\127", 1) print("testing inversion") check_invert("http:") check_invert("a/b/c/d.html") check_invert("//net_loc") check_invert("http:a/b/d/c.html") check_invert("//net_loc/a/b/d/c.html") check_invert("http://net_loc/a/b/d/c.html") check_invert("//who:isit@net_loc") check_invert("http://he:man@boo.bar/a/b/c/i.html;type=moo?this=that#mark") check_invert("/b/c/d#fragment") check_invert("/b/c/d;param#fragment") check_invert("/b/c/d;param?query#fragment") check_invert("/b/c/d?query") check_invert("/b/c/d;param?query") check_invert("http://he:man@[::192.168.1.1]/a/b/c/i.html;type=moo?this=that#mark") print("the library passed all tests")
mit
KayMD/Illarion-Content
triggerfield/elstree_air_661.lua
4
1186
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (799,422,0,'triggerfield.elstree_air_661'); -- INSERT INTO triggerfields VALUES (799,423,0,'triggerfield.elstree_air_661'); -- INSERT INTO triggerfields VALUES (798,422,0,'triggerfield.elstree_air_661'); -- INSERT INTO triggerfields VALUES (798,423,0,'triggerfield.elstree_air_661'); local elementDrop = require("content.elementDrop") local M = {} function M.MoveToField(char) -- pure air will be created elementDrop.chanceForElementDrop(char, {successItemID = 2551}) end return M
agpl-3.0
KayMD/Illarion-Content
item/id_316_sand.lua
3
1447
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local M = {} local id_382_ceilingtrowel = require("gm.items.id_382_ceilingtrowel") -- UPDATE items SET itm_script='item.id_316_sand' WHERE itm_id = 316; local deleteIt function M.MoveItemBeforeMove(User, SourceItem, TargetItem) deleteIt=false; local GroundItem = world:getItemOnField(TargetItem.pos) if (GroundItem.id==10) then local removePos = TargetItem.pos world:erase(GroundItem,1) deleteIt=true world:gfx(45,TargetItem.pos) -- In case the portal is on a gm set spawnpoint, we remove the spawnpoint id_382_ceilingtrowel.saveRemovePosition(removePos) end return true end function M.MoveItemAfterMove(User, SourceItem, TargetItem) if deleteIt then world:erase(TargetItem,1) end end return M
agpl-3.0
Sweet-kid/Algorithm-Implementations
Derivative/Lua/Yonaba/derivative_test.lua
26
1356
-- Tests for derivative.lua local drv = require 'derivative' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end local function fuzzyEqual(a, b, eps) local eps = eps or 1e-4 return (math.abs(a - b) < eps) end run('Testing left derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.left(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.left(f, 5), 3 * 5 * 5)) end) run('Testing right derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.right(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.right(f, 5), 3 * 5 * 5)) end) run('Testing mid derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.mid(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.mid(f, 5), 3 * 5 * 5)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
litnimax/luci
modules/base/luasrc/sys/iptparser.lua
60
10704
--[[ Iptables parser and query library (c) 2008-2009 Jo-Philipp Wich <xm@leipzig.freifunk.net> (c) 2008-2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local luci = {} luci.util = require "luci.util" luci.sys = require "luci.sys" luci.ip = require "luci.ip" local tonumber, ipairs, table = tonumber, ipairs, table --- LuCI iptables parser and query library -- @cstyle instance module("luci.sys.iptparser") --- Create a new iptables parser object. -- @class function -- @name IptParser -- @param family Number specifying the address family. 4 for IPv4, 6 for IPv6 -- @return IptParser instance IptParser = luci.util.class() function IptParser.__init__( self, family ) self._family = (tonumber(family) == 6) and 6 or 4 self._rules = { } self._chains = { } if self._family == 4 then self._nulladdr = "0.0.0.0/0" self._tables = { "filter", "nat", "mangle", "raw" } self._command = "iptables -t %s --line-numbers -nxvL" else self._nulladdr = "::/0" self._tables = { "filter", "mangle", "raw" } self._command = "ip6tables -t %s --line-numbers -nxvL" end self:_parse_rules() end --- Find all firewall rules that match the given criteria. Expects a table with -- search criteria as only argument. If args is nil or an empty table then all -- rules will be returned. -- -- The following keys in the args table are recognized: -- <ul> -- <li> table - Match rules that are located within the given table -- <li> chain - Match rules that are located within the given chain -- <li> target - Match rules with the given target -- <li> protocol - Match rules that match the given protocol, rules with -- protocol "all" are always matched -- <li> source - Match rules with the given source, rules with source -- "0.0.0.0/0" (::/0) are always matched -- <li> destination - Match rules with the given destination, rules with -- destination "0.0.0.0/0" (::/0) are always matched -- <li> inputif - Match rules with the given input interface, rules -- with input interface "*" (=all) are always matched -- <li> outputif - Match rules with the given output interface, rules -- with output interface "*" (=all) are always matched -- <li> flags - Match rules that match the given flags, current -- supported values are "-f" (--fragment) -- and "!f" (! --fragment) -- <li> options - Match rules containing all given options -- </ul> -- The return value is a list of tables representing the matched rules. -- Each rule table contains the following fields: -- <ul> -- <li> index - The index number of the rule -- <li> table - The table where the rule is located, can be one -- of "filter", "nat" or "mangle" -- <li> chain - The chain where the rule is located, e.g. "INPUT" -- or "postrouting_wan" -- <li> target - The rule target, e.g. "REJECT" or "DROP" -- <li> protocol The matching protocols, e.g. "all" or "tcp" -- <li> flags - Special rule options ("--", "-f" or "!f") -- <li> inputif - Input interface of the rule, e.g. "eth0.0" -- or "*" for all interfaces -- <li> outputif - Output interface of the rule,e.g. "eth0.0" -- or "*" for all interfaces -- <li> source - The source ip range, e.g. "0.0.0.0/0" (::/0) -- <li> destination - The destination ip range, e.g. "0.0.0.0/0" (::/0) -- <li> options - A list of specific options of the rule, -- e.g. { "reject-with", "tcp-reset" } -- <li> packets - The number of packets matched by the rule -- <li> bytes - The number of total bytes matched by the rule -- </ul> -- Example: -- <pre> -- ip = luci.sys.iptparser.IptParser() -- result = ip.find( { -- target="REJECT", -- protocol="tcp", -- options={ "reject-with", "tcp-reset" } -- } ) -- </pre> -- This will match all rules with target "-j REJECT", -- protocol "-p tcp" (or "-p all") -- and the option "--reject-with tcp-reset". -- @params args Table containing the search arguments (optional) -- @return Table of matching rule tables function IptParser.find( self, args ) local args = args or { } local rv = { } args.source = args.source and self:_parse_addr(args.source) args.destination = args.destination and self:_parse_addr(args.destination) for i, rule in ipairs(self._rules) do local match = true -- match table if not ( not args.table or args.table:lower() == rule.table ) then match = false end -- match chain if not ( match == true and ( not args.chain or args.chain == rule.chain ) ) then match = false end -- match target if not ( match == true and ( not args.target or args.target == rule.target ) ) then match = false end -- match protocol if not ( match == true and ( not args.protocol or rule.protocol == "all" or args.protocol:lower() == rule.protocol ) ) then match = false end -- match source if not ( match == true and ( not args.source or rule.source == self._nulladdr or self:_parse_addr(rule.source):contains(args.source) ) ) then match = false end -- match destination if not ( match == true and ( not args.destination or rule.destination == self._nulladdr or self:_parse_addr(rule.destination):contains(args.destination) ) ) then match = false end -- match input interface if not ( match == true and ( not args.inputif or rule.inputif == "*" or args.inputif == rule.inputif ) ) then match = false end -- match output interface if not ( match == true and ( not args.outputif or rule.outputif == "*" or args.outputif == rule.outputif ) ) then match = false end -- match flags (the "opt" column) if not ( match == true and ( not args.flags or rule.flags == args.flags ) ) then match = false end -- match specific options if not ( match == true and ( not args.options or self:_match_options( rule.options, args.options ) ) ) then match = false end -- insert match if match == true then rv[#rv+1] = rule end end return rv end --- Rebuild the internal lookup table, for example when rules have changed -- through external commands. -- @return nothing function IptParser.resync( self ) self._rules = { } self._chain = nil self:_parse_rules() end --- Find the names of all tables. -- @return Table of table names. function IptParser.tables( self ) return self._tables end --- Find the names of all chains within the given table name. -- @param table String containing the table name -- @return Table of chain names in the order they occur. function IptParser.chains( self, table ) local lookup = { } local chains = { } for _, r in ipairs(self:find({table=table})) do if not lookup[r.chain] then lookup[r.chain] = true chains[#chains+1] = r.chain end end return chains end --- Return the given firewall chain within the given table name. -- @param table String containing the table name -- @param chain String containing the chain name -- @return Table containing the fields "policy", "packets", "bytes" -- and "rules". The "rules" field is a table of rule tables. function IptParser.chain( self, table, chain ) return self._chains[table:lower()] and self._chains[table:lower()][chain] end --- Test whether the given target points to a custom chain. -- @param target String containing the target action -- @return Boolean indicating whether target is a custom chain. function IptParser.is_custom_target( self, target ) for _, r in ipairs(self._rules) do if r.chain == target then return true end end return false end -- [internal] Parse address according to family. function IptParser._parse_addr( self, addr ) if self._family == 4 then return luci.ip.IPv4(addr) else return luci.ip.IPv6(addr) end end -- [internal] Parse iptables output from all tables. function IptParser._parse_rules( self ) for i, tbl in ipairs(self._tables) do self._chains[tbl] = { } for i, rule in ipairs(luci.util.execl(self._command % tbl)) do if rule:find( "^Chain " ) == 1 then local crefs local cname, cpol, cpkt, cbytes = rule:match( "^Chain ([^%s]*) %(policy (%w+) " .. "(%d+) packets, (%d+) bytes%)" ) if not cname then cname, crefs = rule:match( "^Chain ([^%s]*) %((%d+) references%)" ) end self._chain = cname self._chains[tbl][cname] = { policy = cpol, packets = tonumber(cpkt or 0), bytes = tonumber(cbytes or 0), references = tonumber(crefs or 0), rules = { } } else if rule:find("%d") == 1 then local rule_parts = luci.util.split( rule, "%s+", nil, true ) local rule_details = { } -- cope with rules that have no target assigned if rule:match("^%d+%s+%d+%s+%d+%s%s") then table.insert(rule_parts, 4, nil) end -- ip6tables opt column is usually zero-width if self._family == 6 then table.insert(rule_parts, 6, "--") end rule_details["table"] = tbl rule_details["chain"] = self._chain rule_details["index"] = tonumber(rule_parts[1]) rule_details["packets"] = tonumber(rule_parts[2]) rule_details["bytes"] = tonumber(rule_parts[3]) rule_details["target"] = rule_parts[4] rule_details["protocol"] = rule_parts[5] rule_details["flags"] = rule_parts[6] rule_details["inputif"] = rule_parts[7] rule_details["outputif"] = rule_parts[8] rule_details["source"] = rule_parts[9] rule_details["destination"] = rule_parts[10] rule_details["options"] = { } for i = 11, #rule_parts do if #rule_parts[i] > 0 then rule_details["options"][i-10] = rule_parts[i] end end self._rules[#self._rules+1] = rule_details self._chains[tbl][self._chain].rules[ #self._chains[tbl][self._chain].rules + 1 ] = rule_details end end end end self._chain = nil end -- [internal] Return true if optlist1 contains all elements of optlist 2. -- Return false in all other cases. function IptParser._match_options( self, o1, o2 ) -- construct a hashtable of first options list to speed up lookups local oh = { } for i, opt in ipairs( o1 ) do oh[opt] = true end -- iterate over second options list -- each string in o2 must be also present in o1 -- if o2 contains a string which is not found in o1 then return false for i, opt in ipairs( o2 ) do if not oh[opt] then return false end end return true end
apache-2.0
mt246/mt246
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- 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 = '' 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 pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end 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..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
nobie/sesame_fw
feeds/luci/applications/luci-diag-devinfo/dist/usr/lib/lua/luci/model/cbi/luci_diag/smap_devinfo_mini.lua
141
1031
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson 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$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug) luci.controller.luci_diag.smap_common.action_links(m, true) return m
gpl-2.0
Flourish-Team/Flourish
Premake/source/modules/vstudio/tests/cs2005/test_compiler_props.lua
10
1424
-- -- tests/actions/vstudio/cs2005/test_compiler_props.lua -- Test the compiler flags of a Visual Studio 2005+ C# project. -- Copyright (c) 2012-2013 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_cs2005_compiler_props") local dn2005 = p.vstudio.dotnetbase local project = p.project -- -- Setup and teardown -- local wks, prj function suite.setup() p.action.set("vs2005") wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") dn2005.compilerProps(cfg) end -- -- Check handling of defines. -- function suite.defineConstants_onDefines() defines { "DEBUG", "TRACE" } prepare() test.capture [[ <DefineConstants>DEBUG;TRACE</DefineConstants> ]] end -- -- Check handling of the Unsafe flag. -- function suite.allowUnsafeBlocks_onUnsafeFlag() clr "Unsafe" prepare() test.capture [[ <DefineConstants></DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> ]] end -- -- Check handling of FatalWarnings flag. -- function suite.treatWarningsAsErrors_onFatalWarningsFlag() flags { "FatalWarnings" } prepare() test.capture [[ <DefineConstants></DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> ]] end
mit
drogers141/mac-hammerspoon
util.lua
1
8456
-- General language and low level application utilities -- see test.lua if questions util = {} --------------------------------------------------------------- -- CONFIG --------------------------------------------------------------- -- read local configuration stored in json -- module - code module -- returns value associated with that key -- so far only necessary to store strings util.get_config = function(module, key) local conf_file = hs.fs.currentDir() .. "/config.json" --print("conf_file: "..conf_file) local f = assert(io.open(conf_file, 'r')) local json_str = f:read("*a") f:close() local config_val = nil if json_str then local config = hs.json.decode(json_str) --print(module..": "..key.." = "..config[module][key]) config_val = config[module][key] end return config_val end ------------------------------------------------------------------------------- -- TABLE UTILS -- In general assume table is a dictionary data structure for these ------------------------------------------------------------------------------- -- util.merge(t1, t2, ..) -> table -- Params are tables -- Returns a copy of the merging of all tables taken from left to right -- ie - adds keys and values in each new table to the merge -- and overwrites any keys with new values if there are equal keys util.merge = function(...) local merged = {} for i, t in ipairs{...} do for k, v in pairs(t) do merged[k] = v end end return merged end -- tables have equal values for equal keys -- recursive to handle nested tables -- but pretty naive - only for tables that are values -- see tests for expected examples util.equals = function(t1, t2) if type(t1) ~= type(t2) then return false elseif type(t1) ~= "table" then return t1 == t2 end for k,v in pairs(t1) do if not util.equals(t1[k], t2[k]) then return false end end for k,v in pairs(t2) do if not util.equals(t1[k], t2[k]) then return false end end return true end -- returns reverse copy of l -- which is a table that is a list -- does not mutate l util.reverse = function(l) local rev = {} for i, v in pairs(l) do table.insert(rev, 1, v) end return rev end -- returns set of the keys for a table -- t - table assumed to be a dictionary function util.keys(t) local keyset = {} local i = 0 for k, v in pairs(t) do i = i + 1 keyset[i]=k end return keyset end -- *** str and print are for more limited usage -- one line string repr of simple key value table -- ie rects or sizes - no nested stuff function util.str(t) local s = "" for k, v in pairs(t) do s = s .. k .. "=" .. v .. ", " end if s and string.len(s) > 2 then s = "{" .. string.sub(s, 1, string.len(s)-2) .. "}" return s end end -- print table to stdout in one line -- t - table - assume you can easily print keys and values util.print = function(r) print(util.str(r)) end ------------------------------------------------------------------------------- -- OS INTERACTION UTILS -- logging, directory stuff, audio, etc ------------------------------------------------------------------------------- -- UPDATE: for macOS Sierra -- new unified logging system breaks syslog -- rather than play with the new system for my stuff will replicate -- system logging in ~/log util.logfile = util.get_config('util', 'logfile') -- log a string to util.logfile -- params -- s - string to log -- t - optional tag - defaults to "[dr-hammerspoon]" util.syslog = function(s, t) local tag = t or "[dr-hammerspoon]" local out = assert(io.open(util.logfile,'a')) local timestamp = os.date('%Y-%m-%d %H:%M:%S') out:write(timestamp.." "..tag.." "..s.."\n") out:close() end -- log string s to file f in append mode util.log = function(s, f) local out = assert(io.open(f,'a')) out:write(s) out:close() end -- returns table of absolute paths of files under dirpath -- as returned by ls if dirpath is a directory -- otherwise returns nil function util.dir(dirpath) -- remove possible trailing slash if string.sub(dirpath, string.len(dirpath),string.len(dirpath)) == "/" then dirpath = string.sub(dirpath, 1, string.len(dirpath) - 1) end local cmd = '[[ -d "' .. dirpath .. '" ]] && ls "' .. dirpath .. '"' print(cmd) local f = assert(io.popen(cmd)) local ret = {} for l in f:lines() do ret[#ret+1] = dirpath .. "/" .. l end if #ret == 0 then ret = nil end return ret end -- increment or decrement default audio output device volume -- delta - positive or negative - percentage to raise or lower volume --function util.volume_adjust(delta) -- local ad = audiodevice.defaultoutputdevice() -- local maybe_new_vol = ad:volume() + delta -- local new_vol = math.max(0, math.min(100, maybe_new_vol)) -- ad:setvolume(new_vol) --end -- noarg calls for key binding -- increment or decrement volume by 3 percent --util.volume_up = fnutils.partial(util.volume_adjust, 3) --util.volume_down = fnutils.partial(util.volume_adjust, -3) ------------------------------------------------------------------------------- -- WINDOW AND SCREEN UTILS ------------------------------------------------------------------------------- -- "visible" windows in mru order -- note this replaces window.orderedwindows() -- currently need to filter out windows that are not "standard" in some apps -- e.g. - if an iTerm terminal is in focus, 2 title-less windows -- with the same frame as the screen will be displayed util.orderedwindows = function() return hs.fnutils.filter(hs.window.orderedWindows(), function(w) return w:isStandard() end) end -- get the frame rect from a window or a screen object as a table that can be -- serialized and recreate a rect - ie dogfooded util.get_frame_rect = function(o) return {x=o:frame().x, y=o:frame().y, w=o:frame().w, h=o:frame().h} end -- table for a window userdata object -- id, application title, frame, window title util.windowtable = function(w) return {id=w:id(), apptitle=w:application():title(), frame=util.get_frame_rect(w), title=w:title()} end -- table for a screen userdata object - frame, -- frames with and without dock and menu util.screentable = function(s) return {frame=util.get_frame_rect(s), fullFrame=s:fullFrame().table} end -- get a window from current ordered standard windows by id -- id - number util.windowbyid = function(id) for i, w in pairs(util.orderedwindows()) do if w:id() == id then return w end end end -- identify screen based on resolution -- arbitrarily deciding on id here -- so need to add any new screens util.screens = { -- laptop s1 = {h = 900, w = 1440, x = 0, y = 0}, -- Dell 26 inch s2= {h = 1200, w = 1920, x = 0, y = 0}, -- work - Nixeus 27 inch s3 = {h = 1440, w = 2560, x = 0, y = 0}, -- Dell 34 inch ultra wide s4 = {h = 1440, w = 3440, x = 0, y = 0} } -- rect - hs.geometry.rect -- returns a screen_id string if found, or nil util.get_screen_id = function(rect) for i, r in pairs(util.screens) do if rect:equals(r) then return i end end end --------------------------------------------------------------- -- OTHER --------------------------------------------------------------- -- returns list of lines in multiline string s -- splits on \n, removes \n from lines function util.splitlines(s) local retlist = {} for l in string.gmatch(s, "[^\n]+") do retlist[#retlist+1] = l end return retlist end -- width is determined by longest line in text --function util.textgrid(title, text) -- local win = textgrid.create() ---- win:protect() -- -- local textlines = util.splitlines(text) -- local lenmap = fnutils.map(textlines, string.len) -- local maxlen = math.max(table.unpack(lenmap)) -- local size = {w = math.max(40, maxlen + 2), -- h = math.max(10, #textlines + 2)} -- -- local pos = 1 -- i.e. line currently at top of log textgrid -- -- local fg = "00FF00" -- local bg = "222222" -- -- win:settitle(title) -- win:resize(size) -- -- win:setbg(bg) -- win:setfg(fg) -- win:clear() -- -- for linenum = pos, math.min(pos + size.h, #textlines) do -- local line = textlines[linenum] -- for i = 1, math.min(#line, size.w) do -- local c = line:sub(i,i) -- win:setchar(c, i, linenum - pos + 1) -- end -- end -- -- win:show() -- win:focus() -- -- return win --end return util
mit
pdxmeshnet/mnigs
src/cjdnstools/contrib/lua/cjdns/addrcalc.lua
19
1888
-- Cjdns address conversion functions -- Translated from Cjdns C code to lua code by Alex <alex@portlandmeshnet.org> --- @module cjdns.addrcalc local addrcalc = {} local bit32 = require("bit32") local sha2 = require("sha2") function addrcalc.Base32_decode(input) local numForAscii = { 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,99,99,99,99,99,99, 99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99, 21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99, 99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99, 21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99, } local output = {} local outputIndex = 0 local inputIndex = 0 local nextByte = 0 local bits = 0 while inputIndex < string.len(input) do i = string.byte(input,inputIndex+1) if bit32.band(i,0x80) ~= 0 then error("Bad base32 decode input character " .. i) end b = numForAscii[i+1] inputIndex = inputIndex + 1 if b > 31 then error("Bad base32 decode input character " .. i) end nextByte = bit32.bor(nextByte, bit32.lshift(b, bits)) bits = bits + 5 if bits >= 8 then output[outputIndex+1] = bit32.band(nextByte, 0xff) outputIndex = outputIndex + 1 bits = bits - 8 nextByte = bit32.rshift(nextByte, 8) end end if bits >= 5 or nextByte ~= 0 then error("Bad base32 decode input, bits is " .. bits .. " and nextByte is " .. nextByte); end return string.char(unpack(output)); end function addrcalc.pkey2ipv6(k) if string.sub(k,-2) ~= ".k" then error("Invalid key") end kdata = addrcalc.Base32_decode(string.sub(k,1,-3)) hash = sha2.sha512(kdata) hash = sha2.sha512hex(hash) addr = string.sub(hash,1,4) for i = 2,8 do addr = addr .. ":" .. string.sub(hash,i*4-3,i*4) end return addr end return addrcalc
mit
gajop/Zero-K
scripts/corcrw.lua
5
8485
include 'constants.lua' include 'letsNotFailAtTrig.lua' -- by MergeNine -- shortcuts local GetUnitPosition = Spring.GetUnitPosition local SpawnCEG = Spring.SpawnCEG local GetGroundHeight = Spring.GetGroundHeight --pieces local Base = piece "Base" local RearTurretSeat = piece "RearTurretSeat" local RearTurret = piece "RearTurret" local RearGun = piece "RearGun" local RearFlashPoint = piece "RearFlashPoint" local LeftTurretSeat = piece "LeftTurretSeat" local LeftTurret = piece "LeftTurret" local LeftGun = piece "LeftGun" local LeftFlashPoint = piece "LeftFlashPoint" local RightTurretSeat = piece "RightTurretSeat" local RightTurret = piece "RightTurret" local RightGun = piece "RightGun" local RightFlashPoint = piece "RightFlashPoint" local subpoint, emit = piece("subpoint", "emit") local jetleft, jetright, jetrear = piece('jetleft', 'jetright', 'jetrear') local subemit = {} for i=0,4 do subemit[i] = piece("subemit"..i) end local gunpoints = { [1] = {aim = RightTurretSeat, rot = RightTurret, pitch = RightGun, fire = RightFlashPoint}, [2] = {aim = LeftTurretSeat, rot = LeftTurret, pitch = LeftGun, fire = LeftFlashPoint}, [3] = {aim = subpoint, pitch = subpoint, fire = subpoint}, [4] = {aim = RearTurretSeat, rot = RearTurret, pitch = RearGun, fire = RearFlashPoint}, [5] = {aim = Base, pitch = Base, fire = Base}, [6] = {aim = Base, pitch = Base, fire = Base}, } gunpoints[2].radial = {0.67289841175079, -0.29416278004646, 0.67873126268387} gunpoints[2].right = {0.6971772313118, -0.030258473008871, -0.71625995635986} gunpoints[2].normal = {0.23123440146446, 0.95516616106033, 0.18472272157669} gunpoints[1].radial = {-0.67857336997986, -0.29443317651749, 0.67293930053711} gunpoints[1].right = {0.70172995328903, 0.036489851772785, 0.71150785684586} gunpoints[1].normal = {-0.23404698073864, 0.95503199100494, 0.18185153603554} gunpoints[4].radial = {0.0040571023710072, -0.25233194231987, -0.96763223409653} gunpoints[4].right = {-0.99998968839645, 0.0029705890920013, 0.0034227864816785} gunpoints[4].normal = {0.0020107594318688, 0.96760839223862, -0.25231730937958} --signals local signals = { [1] = 2, [2] = 4, [4] = 8, tilt = 1, particle = { -- unused [1] = 16, [2] = 32, [4] = 64, } } local restoreDelay = 3000 local attacking = 0 --local blockAim = {false, false, false, false} local turretSpeed = 8 --local tiltAngle = math.rad(30) local isLanded = true local SPECIAL_FIRE_COUNT = 75 local SLOWDOWN_FACTOR = 0.75 local UNIT_SPEED = UnitDefNames["corcrw"].speed*SLOWDOWN_FACTOR/30 local sound_index = 0 function script.Activate() isLanded = false end function script.Deactivate() isLanded = true end local function EmitDust() while true do if not (isLanded or Spring.GetUnitIsStunned(unitID) or Spring.GetUnitIsCloaked(unitID)) then local x, _, z = GetUnitPosition(unitID) local y = GetGroundHeight(x, z) + 30 SpawnCEG("krowdust", x, y, z, 0, 0, 0, 1, 1) end Sleep(33) end end --[[ local function SetDGunCMD() local cmd = Spring.FindUnitCmdDesc(unitID, CMD.DGUN) local desc = { name = "Cluster Bomb", tooltip = "Drop a huge number of bombs in a circle under the Krow", type = CMDTYPE.ICON_MAP, } if cmd then Spring.EditUnitCmdDesc(unitID, cmd, desc) end end ]]-- local function updateVectors(num) Turn(gunpoints[num].rot,y_axis,0) Turn(gunpoints[num].pitch,x_axis,0) Turn(gunpoints[num].pitch,x_axis,math.rad(-90)) Sleep(400) local _, _, _, x, y, z = Spring.UnitScript.GetPiecePosDir(gunpoints[num].pitch) gunpoints[num].radial = hat({x, y, z}) Turn(gunpoints[num].rot,y_axis,math.rad(90)) Turn(gunpoints[num].pitch,x_axis,math.rad(90)) Sleep(400) local _, _, _, x, y, z = Spring.UnitScript.GetPiecePosDir(gunpoints[num].pitch) gunpoints[num].right = hat({x, y, z}) gunpoints[num].normal = cross(gunpoints[num].radial,gunpoints[num].right) Turn(gunpoints[num].rot,y_axis,0) Turn(gunpoints[num].pitch,x_axis,0) Spring.Echo("gunpoints[" .. num .. "].radial = {" .. gunpoints[num].radial[1] .. ", " .. gunpoints[num].radial[2] .. ", " .. gunpoints[num].radial[3] .. "}") Spring.Echo("gunpoints[" .. num .. "].right = {" .. gunpoints[num].right[1] .. ", " .. gunpoints[num].right[2] .. ", " .. gunpoints[num].right[3] .. "}") Spring.Echo("gunpoints[" .. num .. "].normal = {" .. gunpoints[num].normal[1] .. ", " .. gunpoints[num].normal[2] .. ", " .. gunpoints[num].normal[3] .. "}") end local function updateAllVectors() updateVectors(1) updateVectors(2) updateVectors(4) -- idk why they must be swapped gunpoints[1].normal,gunpoints[2].normal = gunpoints[2].normal,gunpoints[1].normal gunpoints[1].radial,gunpoints[2].radial = gunpoints[2].radial,gunpoints[1].radial gunpoints[1].right,gunpoints[2].right = gunpoints[2].right,gunpoints[1].right end function script.Create() --Turn(Base,y_axis, math.pi) --Spring.MoveCtrl.SetGunshipMoveTypeData(unitID,"turnRate",0) --set starting positions for turrets Turn(RightTurretSeat,x_axis,math.rad(17)) -- 17 Turn(RightTurretSeat,z_axis,math.rad(2)) -- 2 Turn(RightTurretSeat,y_axis,math.rad(-45)) -- -45 Turn(LeftTurretSeat,x_axis,math.rad(17)) -- 17 Turn(LeftTurretSeat,z_axis,math.rad(-2)) -- -2 Turn(LeftTurretSeat,y_axis,math.rad(45)) -- 45 Turn(RearTurretSeat,y_axis,math.rad(180)) Turn(RearTurretSeat,x_axis,math.rad(14.5)) for i=0,4 do Turn(subemit[i], x_axis, math.rad(90)) end --StartThread(updateAllVectors) Turn(jetleft, x_axis, math.rad(90)) Turn(jetright, x_axis, math.rad(90)) Turn(jetrear, x_axis, math.rad(90)) --Move(LeftTurretSeat,x_axis,-2) --Move(LeftTurretSeat,y_axis,-1.1) --Move(LeftTurretSeat,z_axis,17) --SetDGunCMD() StartThread(EmitDust) end --[[ function TiltBody(heading) Signal(signals.tilt) SetSignalMask(signals.tilt) if(attacking) then --calculate tilt amount for z angle and x angle local amountz = -math.sin(heading) local amountx = math.cos(heading) --Turn(Base,x_axis, amountx * tiltAngle,1) --Turn(Base,z_axis, amountz * tiltAngle,1) WaitForTurn (Base, x_axis) WaitForTurn (Base, z_axis) end end --]] local function RestoreAfterDelay() Sleep(restoreDelay) attacking = false --Turn(Base,x_axis, math.rad(0),1) --default tilt --WaitForTurn (Base, x_axis) --Turn(Base,z_axis, math.rad(0),1) --default tilt --WaitForTurn (Base, z_axis) --Signal(tiltSignal) end function script.QueryWeapon(num) return gunpoints[num].fire end function script.AimFromWeapon(num) return gunpoints[num].aim end local function ClusterBombThread() local slowState = 1 - (Spring.GetUnitRulesParam(unitID,"slowState") or 0) local sleepTime = 70/slowState for i = 1, SPECIAL_FIRE_COUNT do EmitSfx(subemit[0], FIRE_W5) Sleep(sleepTime) end Sleep(330) Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 1) GG.UpdateUnitAttributes(unitID) end function ClusterBomb() StartThread(ClusterBombThread) Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", SLOWDOWN_FACTOR) GG.UpdateUnitAttributes(unitID) --local vx, vy, vz = Spring.GetUnitVelocity(unitID) --local hSpeed = math.sqrt(vx^2 + vz^2) --if hSpeed > UNIT_SPEED then -- Spring.SetUnitVelocity(unitID, vx*UNIT_SPEED/hSpeed, vy, vz*UNIT_SPEED/hSpeed) --end end function script.AimWeapon(num, heading, pitch) if num >= 5 then return false elseif num == 3 then --EmitSfx(Base, 2048 + 2) return false end Signal(signals[num]) SetSignalMask(signals[num]) attacking = true --StartThread(TiltBody, heading) local theta, phi = getTheActuallyCorrectHeadingAndPitch(heading, pitch, gunpoints[num].normal, gunpoints[num].radial, gunpoints[num].right) Turn(gunpoints[num].rot, y_axis, theta, turretSpeed) Turn(gunpoints[num].pitch, x_axis, phi,turretSpeed) WaitForTurn (gunpoints[num].pitch, x_axis) WaitForTurn (gunpoints[num].rot, y_axis) StartThread(RestoreAfterDelay) return true end function script.FireWeapon(num) --Sleep(1000) if num ~= 3 then EmitSfx(gunpoints[num].fire, 1024) else --ClusterBomb() end end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .5 or ((Spring.GetUnitMoveTypeData(unitID).aircraftState or "") == "crashing") then Explode(Base, sfxNone) Explode(RightTurret, sfxNone) Explode(LeftTurret, sfxNone) Explode(RearTurret, sfxNone) return 1 else Explode(Base, sfxShatter) Explode(RightTurret, sfxExplode) Explode(LeftTurret, sfxExplode) Explode(RearTurret, sfxExplode) return 2 end end
gpl-2.0
Minefix/MineFix
mods/nether/mapgen.lua
4
7181
-- Parameters local NETHER_DEPTH = -5000 local TCAVE = 0.6 local BLEND = 128 -- Stuff local yblmax = NETHER_DEPTH - BLEND * 2 -- Initialize noise object and localise noise buffer local nobj_cave = nil local nbuf_cave -- Content ids local c_air = minetest.get_content_id("air") local c_stone_with_coal = minetest.get_content_id("default:stone_with_coal") local c_stone_with_iron = minetest.get_content_id("default:stone_with_iron") local c_stone_with_diamond = minetest.get_content_id("default:stone_with_diamond") local c_stone_with_gold = minetest.get_content_id("default:stone_with_gold") local c_stone_with_copper = minetest.get_content_id("default:stone_with_copper") local c_gravel = minetest.get_content_id("default:gravel") local c_dirt = minetest.get_content_id("default:dirt") local c_sand = minetest.get_content_id("default:sand") local c_cobble = minetest.get_content_id("default:cobblestone") local c_mossycobble = minetest.get_content_id("default:cobblestone_mossy") local c_stair_cobble = minetest.get_content_id("stairs:stair_cobblestone") local c_lava_source = minetest.get_content_id("default:lava_source") local c_lava_flowing = minetest.get_content_id("default:lava_flowing") local c_water_source = minetest.get_content_id("default:water_source") local c_water_flowing = minetest.get_content_id("default:water_flowing") local c_glowstone = minetest.get_content_id("nether:glowstone") local c_sand_soul = minetest.get_content_id("nether:sand_soul") local c_netherbrick = minetest.get_content_id("nether:brick") local c_netherrack = minetest.get_content_id("nether:rack") local np_cave = { offset = 0, scale = 1, spread = {x = 384, y = 128, z = 384}, -- squashed 3:1 seed = 59033, octaves = 5, persist = 0.7 } -- On-generated function minetest.register_on_generated(function(minp, maxp, seed) if minp.y > NETHER_DEPTH then return end local t1 = os.clock() local x1 = maxp.x local y1 = maxp.y local z1 = maxp.z local x0 = minp.x local y0 = minp.y local z0 = minp.z local vm, emin, emax = minetest.get_mapgen_object("voxelmanip") local area = VoxelArea:new{MinEdge = emin, MaxEdge = emax} local data = vm:get_data() local x11 = emax.x -- Limits of mapchunk plus mapblock shell local y11 = emax.y local z11 = emax.z local x00 = emin.x local y00 = emin.y local z00 = emin.z local ystride = x1 - x0 + 1 local zstride = ystride * ystride local chulens = {x = ystride, y = ystride, z = ystride} local minposxyz = {x = x0, y = y0, z = z0} nobj_cave = nobj_cave or minetest.get_perlin_map(np_cave, chulens) local nvals_cave = nobj_cave:get3dMap_flat(minposxyz, nbuf_cave) for y = y00, y11 do -- Y loop first to minimise tcave calculations local tcave local in_chunk_y = false if y >= y0 and y <= y1 then if y > yblmax then tcave = TCAVE + ((y - yblmax) / BLEND) ^ 2 else tcave = TCAVE end in_chunk_y = true end for z = z00, z11 do local vi = area:index(x00, y, z) -- Initial voxelmanip index local ni local in_chunk_yz = in_chunk_y and z >= z0 and z <= z1 for x = x00, x11 do if in_chunk_yz and x == x0 then -- Initial noisemap index ni = (z - z0) * zstride + (y - y0) * ystride + 1 end local in_chunk_yzx = in_chunk_yz and x >= x0 and x <= x1 -- In mapchunk local id = data[vi] -- Existing node -- Cave air, cave liquids and dungeons are overgenerated, -- convert these throughout mapchunk plus shell if id == c_air or -- Air and liquids to air id == c_lava_source or id == c_lava_flowing or id == c_water_source or id == c_water_flowing then data[vi] = c_air -- Dungeons are preserved so we don't need -- to check for cavern in the shell elseif id == c_cobble or -- Dungeons (preserved) to netherbrick id == c_mossycobble or id == c_stair_cobble then data[vi] = c_netherbrick end if in_chunk_yzx then -- In mapchunk if nvals_cave[ni] > tcave then -- Only excavate cavern in mapchunk data[vi] = c_air elseif id == c_stone_with_gold or -- Precious ores to glowstone id == c_stone_with_diamond then data[vi] = c_glowstone elseif id == c_gravel or -- Blob ore to nethersand id == c_dirt or id == c_sand then data[vi] = c_sand_soul else -- All else to netherstone data[vi] = c_netherrack end ni = ni + 1 -- Only increment noise index in mapchunk end vi = vi + 1 end end end vm:set_data(data) vm:set_lighting({day = 0, night = 0}) vm:calc_lighting() vm:update_liquids() vm:write_to_map() local chugent = math.ceil((os.clock() - t1) * 1000) print ("[nether] generate chunk " .. chugent .. " ms") end) function make_portal(pos) local p1, p2 = is_portal(pos) if not p1 or not p2 then return false end for d = 1, 2 do for y = p1.y + 1, p2.y - 1 do local p if p1.z == p2.z then p = {x = p1.x + d, y = y, z = p1.z} else p = {x = p1.x, y = y, z = p1.z + d} end if minetest.get_node(p).name ~= "air" then return false end end end local param2 if p1.z == p2.z then param2 = 0 else param2 = 1 end local target = {x = p1.x, y = p1.y, z = p1.z} target.x = target.x + 1 if target.y < NETHER_DEPTH then target.y = find_surface_target_y(target.x, target.z, -16) else local start_y = NETHER_DEPTH - math.random(500, 1500) -- Search start target.y = find_nether_target_y(target.x, target.z, start_y) end for d = 0, 3 do for y = p1.y, p2.y do local p = {} if param2 == 0 then p = {x = p1.x + d, y = y, z = p1.z} else p = {x = p1.x, y = y, z = p1.z + d} end if minetest.get_node(p).name == "air" then minetest.set_node(p, {name = "nether:portal", param2 = param2}) end local meta = minetest.get_meta(p) meta:set_string("p1", minetest.pos_to_string(p1)) meta:set_string("p2", minetest.pos_to_string(p2)) meta:set_string("target", minetest.pos_to_string(target)) end end return true end function find_nether_target_y(target_x, target_z, start_y) local nobj_cave_point = minetest.get_perlin(np_cave) local air = 0 -- Consecutive air nodes found for y = start_y, start_y - 4096, -1 do local nval_cave = nobj_cave_point:get3d({x = target_x, y = y, z = target_z}) if nval_cave > TCAVE then -- Cavern air = air + 1 else -- Not cavern, check if 4 nodes of space above if air >= 4 then -- Check volume for non-natural nodes local minp = {x = target_x - 1, y = y - 1, z = target_z - 2} local maxp = {x = target_x + 2, y = y + 3, z = target_z + 2} if volume_is_natural(minp, maxp) then return y + 2 else -- Restart search a little lower find_nether_target_y(target_x, target_z, y - 16) end else -- Not enough space, reset air to zero air = 0 end end end return start_y -- Fallback end function find_surface_target_y(target_x, target_z, start_y) for y = start_y, start_y - 256, -16 do -- Check volume for non-natural nodes local minp = {x = target_x - 1, y = y - 1, z = target_z - 2} local maxp = {x = target_x + 2, y = y + 3, z = target_z + 2} if volume_is_natural(minp, maxp) then return y end end return y -- Fallback end
agpl-3.0
pixeltailgames/gm-mediaplayer
lua/mediaplayer/utils.lua
1
5617
if SERVER then AddCSLuaFile() end local file = file local math = math local urllib = url local ceil = math.ceil local floor = math.floor local Round = math.Round local log = math.log local pow = math.pow local format = string.format local tostring = tostring local IsValid = IsValid local utils = {} --- -- Ceil the given number to the largest power of two. -- function utils.CeilPower2(n) return pow(2, ceil(log(n) / log(2))) end --- -- Method for easily grabbing a value from a table without checking that each -- fragment exists. -- -- @param tbl Table -- @param key e.g. "json.key.fragments" -- function utils.TableLookup( tbl, key ) local fragments = string.Split(key, '.') local value = tbl for _, fragment in ipairs(fragments) do value = value[fragment] if not value then return nil end end return value end --- -- Formats the number of seconds to a string. -- e.g. 3612 => 24:12 -- function utils.FormatSeconds(sec) sec = Round(sec) local hours = floor(sec / 3600) local minutes = floor((sec % 3600) / 60) local seconds = sec % 60 if minutes < 10 then minutes = "0" .. tostring(minutes) end if seconds < 10 then seconds = "0" .. tostring(seconds) end if hours > 0 then return format("%s:%s:%s", hours, minutes, seconds) else return format("%s:%s", minutes, seconds) end end -- https://github.com/xfbs/PiL3/blob/master/18MathLibrary/shuffle.lua function utils.Shuffle(list) -- make and fill array of indices local indices = {} for i = 1, #list do indices[#indices+1] = i end -- create shuffled list local shuffled = {} for i = 1, #list do -- get a random index local index = math.random(#indices) -- get the value local value = list[indices[index]] -- remove it from the list so it won't be used again table.remove(indices, index) -- insert into shuffled array shuffled[#shuffled+1] = value end return shuffled end function utils.Retry( func, success, error, maxAttempts ) maxAttempts = maxAttempts or 3 local attempts = 1 local function callback( value ) if value then success( value ) elseif attempts < maxAttempts then attempts = attempts + 1 func( callback ) else error() end end func( callback ) end local function setTimeout( func, wait ) local timerID = tostring( func ) timer.Create( timerID, wait, 1, func ) timer.Start( timerID ) return timerID end local function clearTimeout( timerID ) if timer.Exists( timerID ) then timer.Destroy( timerID ) end end -- based on underscore.js' _.throttle function function utils.Throttle( func, wait, options ) wait = wait or 1 options = options or {} local timeout, args, result local previous local function later() previous = (options.leading == false) and 0 or RealTime() timeout = nil result = func( unpack(args) ) if not timeout then args = nil end end local function throttled(...) local now = RealTime() if not previous then previous = now end local remaining = wait - (now - previous) args = {...} if remaining <= 0 or remaining > wait then if timeout then clearTimeout(timeout) timeout = nil end previous = now result = func( unpack(args) ) if not timeout then args = nil end elseif not timeout and options.trailing ~= false then timeout = setTimeout(later, remaining) end return result end return throttled end if CLIENT then local CeilPower2 = utils.CeilPower2 local SetDrawColor = surface.SetDrawColor local SetMaterial = surface.SetMaterial local DrawTexturedRect = surface.DrawTexturedRect local DrawRect = surface.DrawRect local color_white = color_white function utils.DrawHTMLPanel( panel, w, h ) if not (IsValid( panel ) and w and h) then return end panel:UpdateHTMLTexture() local pw, ph = panel:GetSize() -- Convert to scalar w = w / pw h = h / ph -- Fix for non-power-of-two html panel size pw = CeilPower2(pw) ph = CeilPower2(ph) SetDrawColor( color_white ) local mat = panel:GetHTMLMaterial() if mat then SetMaterial( mat ) DrawTexturedRect( 0, 0, w * pw, h * ph ) else DrawRect( 0, 0, w * pw, h * ph ) end end function utils.ParseHHMMSS( time ) local tbl = {} -- insert fragments in reverse for fragment, _ in string.gmatch(time, ":?(%d+)") do table.insert(tbl, 1, tonumber(fragment) or 0) end if #tbl == 0 then return nil end local seconds = 0 for i = 1, #tbl do seconds = seconds + tbl[i] * math.max(60 ^ (i-1), 1) end return seconds end --- -- Attempts to play uri from stream or local file and returns channel in -- callback. -- function utils.LoadStreamChannel( uri, options, callback ) local isLocalFile = false -- Play uri from a local file if: -- 1. Windows OS and path contains drive letter -- 2. Linux or OS X and path starts with a single '/' -- -- We can't check this using file.Exists since GMod only allows checking -- within the GMod directory. However, sound.PlayFile will still load -- a file from any directory. if ( system.IsWindows() and uri:find("^%w:/") ) or ( not system.IsWindows() and uri:find("^/[^/]") ) then isLocalFile = true local success, decoded = pcall(urllib.unescape, uri) if success then uri = decoded end end local playFunc = isLocalFile and sound.PlayFile or sound.PlayURL playFunc( uri, options or "noplay", function( channel ) if IsValid( channel ) then callback( channel ) else callback( nil ) end end ) end end _G.MediaPlayerUtils = utils
mit
Flourish-Team/Flourish
Premake/source/modules/gmake/tests/workspace/test_default_config.lua
13
1465
-- -- tests/actions/make/test_default_config.lua -- Validate generation of default configuration block for makefiles. -- Copyright (c) 2012-2015 Jason Perkins and the Premake project -- local suite = test.declare("make_default_config") local p = premake -- -- Setup/teardown -- local wks, prj function suite.setup() wks = test.createWorkspace() end local function prepare() prj = test.getproject(wks, 1) p.make.defaultconfig(prj) end -- -- Verify the handling of the default setup: Debug and Release, no platforms. -- function suite.defaultsToFirstBuildCfg_onNoPlatforms() prepare() test.capture [[ ifndef config config=debug endif ]] end -- -- Verify handling of build config/platform combination. -- function suite.defaultsToFirstPairing_onPlatforms() platforms { "Win32", "Win64" } prepare() test.capture [[ ifndef config config=debug_win32 endif ]] end -- -- If the project excludes a workspace build cfg, it should be skipped -- over as the default config as well. -- function suite.usesFirstValidPairing_onExcludedConfig() platforms { "Win32", "Win64" } removeconfigurations { "Debug" } prepare() test.capture [[ ifndef config config=release_win32 endif ]] end -- -- Verify handling of defaultplatform -- function suite.defaultsToSpecifiedPlatform() platforms { "Win32", "Win64" } defaultplatform "Win64" prepare() test.capture [[ ifndef config config=debug_win64 endif ]] end
mit
jayman39tx/naev
dat/missions/flf/flf_pre01.lua
2
14459
--[[ -- This is the first "prelude" mission leading to the FLF campaign. The player takes a FLF agent onboard, then either turns him in to the Dvaered or delivers him to a hidden FLF base. -- stack variable flfbase_intro: -- 1 - The player has turned in the FLF agent or rescued the Dvaered crew. Conditional for dv_antiflf02 -- 2 - The player has rescued the FLF agent. Conditional for flf_pre02 -- 3 - The player has found the FLF base for the Dvaered, or has betrayed the FLF after rescuing the agent. Conditional for dv_antiflf03 --]] -- localization stuff, translators would work here include("fleethelper.lua") title = {} text = {} turnintitle = {} turnintext = {} osd_desc = {} title[1] = _("Gregar joins the party") text[1] = _([[A haggard-looking man emerges from the airlock. He says, "Thank goodness you're here. My name is Gregar, I'm with the Frontier Liberation Front. I mean you no harm." He licks his lips in hesitation before continuing. "I have come under attack from a Dvaered patrol. I wasn't violating any laws, and we're not even in Dvaered territory! Anyway, my ship is unable to fly." You help Gregar to your cockpit and install him in a vacant seat. He is obviously very tired, but he forces himself to speak. "Listen, I was on my way back from a mission when those Dvaered bastards jumped me. I know this is a lot to ask, but I have little choice seeing how my ship is a lost cause. Can you take me the rest of the way? It's not far. We have a secret base in the %s system. Fly there and contact my comrades. They will take you the rest of the way." With that, Gregar nods off, leaving you to decide what to do next. Gregar wants you to find his friends, but harboring a known terrorist, let alone helping him, might not be looked kindly upon by the authorities...]]) title[2] = _("Gregar puts an end to hostilities") text[2] = _([["Wha- hey! What's going on!" You were too busy dodging incoming fire, rebalancing your shields and generally trying to kill your attackers before they kill you to notice that Gregar, your passenger, has roused from his slumber. Clearly the noise and the rocking have jolted him awake. You snap at him not to distract you from this fight, but he desperately interrupts. "These guys are my contacts, my friends! I was supposed to meet them here! Oh crap, this is not good. I didn't realize I'd be out this long! Look, I need to use your comm array right now. Trust me!" Before you have a chance to ask him what he thinks he's doing, Gregar begins tuning your communications array, and soon finds the frequency he wants. "FLF sentinel formation, this is Lt. Gregar Fletcher, authorization code six-six-niner-four-seven-Gamma-Foxtrot! Cease fire, I repeat, cease fire!" He then turns to you. "Same to you. Stop shooting. This is a misunderstanding, they're not your enemies."]]) title[3] = "" text[3] = _([[You are skeptical at first, but a few seconds later it becomes apparent that the FLF fighters have indeed ceased firing. Then, there is an incoming comm from the lead ship. "This is FLF sentinel Alpha. Lt. Fletcher, authorization code verified. Why are you with that civilian? Where is your ship? And why didn't you contact us right away?" "Apologies, Alpha. It's a long story. For now, let me just tell you that you can trust the pilot of this ship. He has kindly helped me out of a desperate situation, and without him I probably would never have returned alive. Request you escort us to Sindbad." "Copy that Lt. Fletcher." Alpha then addresses you. "Please follow us. We will guide you to our base. Stay close. Sensor range is lousy in these parts, and if you get separated from us, we won't be able to find you again, and you won't be able to find us or our base." With that, Alpha breaks the connection. It seems you have little choice but to do as he says if you ever want to take Gregar to his destination.]]) title[4] = _("Gregar leaves the party") text[4] = _([[You and Gregar step out of your airlock and onto Sindbad Station. You are greeted by a group of five or six FLF soldiers. They seem relieved to see Gregar, but they clearly regard you with mistrust. You are taken to meet with a senior officer of the base. Gregar doesn't come with you, as he seems to have urgent matters to attend to - away from prying ears like your own. "All right, Mr. %s," the officer begins. "I don't know who you are or what you think you're doing here, but you shouldn't kid yourself. The only reason why you are in my office and not in a holding cell is because one of my trusted colleagues is vouching for you." The officer leans a little closer to you and pins you with a level stare. "I don't think you're a Dvaered spy. The Dvaered don't have the wit to pull off decent espionage. But you shouldn't get any ideas of running to the Dvaered and blabbing about our presence here. They're neither a trusting nor a grateful sort, so they'd probably just arrest you and torture you for what you know. So, I trust you understand that your discretion is in both our interests."]]) title[5] = "" text[5] = _([[The moment of tension passes, and the officer leans back in his chair. "That threat delivered, I should at least extend my gratitude for helping one of ours in his time of need, though you had no reason to do so. That's why I will allow you to move freely on this station, at least to some extent, and I will allow you to leave when you please, as well as to return if you see the need. Who knows, maybe if you hit it off with the personnel stationed here, we might even come to consider you a friend." You exchange a few more polite words with the officer, then leave his office. As you head back to your ship, you consider your position. You have gained access to a center of FLF activity. Should you want to make an enemy of House Dvaered, perhaps this would be a good place to start...]]) comm_msg = _("Nothing personal, mate, but we're expecting someone and you ain't him. No witnesses!") contacttitle = _("You have lost contact with your escorts!") contacttext = _([[Your escorts have disappeared from your sensor grid. Unfortunately, it seems you have no way of telling where they went. You have failed to reach the FLF's hidden base.]]) turnintitle[1] = _("An opportunity to uphold the law") turnintext[1] = _([[You have arrived at a Dvaered controlled world, and you are harboring a FLF fugitive on your ship. Fortunately, Gregar is still asleep. You could choose to alert the authorities and turn him in, and possibly collect a reward. Would you like to do so?]]) turnintitle[2] = _("Another criminal caught") turnintext[2] = _([[It doesn't take Dvaered security long to arrive at your landing bay. They board your ship, seize Gregar and take him away before he even comprehends what's going on. "You have served House Dvaered adequately, citizen," the stone-faced captain of the security detail tells you. "In recognition of your service, we may allow you to participate in other operations regarding the FLF terrorists. If you have further questions, direct them to our public liaison." The officer turns and leaves without waiting for an answer, and without rewarding you in any tangible way. You wonder if you should scout out this liaison, in hopes of at least getting something out of this whole situation.]]) misn_title = _("Deal with the FLF agent") osd_desc[1] = _("Take Gregar, the FLF agent to the %s system and make contact with the FLF") osd_desc[2] = _("Alternatively, turn Gregar in to the nearest Dvaered base") osd_adddesc = _("Follow the FLF ships to their secret base. Do not lose them!") misn_desc = _("You have taken onboard a member of the FLF. You must either take him where he wants to go, or turn him in to the Dvaered.") function create() missys = {system.get(var.peek("flfbase_sysname"))} if not misn.claim(missys) then abort() -- TODO: This claim should be in the event that starts this mission! end misn.accept() -- The player chose to accept this mission by boarding the FLF ship flfdead = false -- Flag to check if the player destroyed the FLF sentinels basefound = false -- Flag to keep track if the player has seen the base destsysname = var.peek("flfbase_sysname") destsys = system.get(destsysname) tk.msg(title[1], text[1]:format(destsysname)) misn.osdCreate(misn_title, {osd_desc[1]:format(destsysname), osd_desc[2]}) misn.setDesc(misn_desc) misn.setTitle(misn_title) misn.markerAdd(system.get(destsysname), "low") gregar = misn.cargoAdd("Gregar", 0) hook.enter("enter") hook.land("land") end -- Handle the FLF encounter, Gregar's intervention, and ultimately the search for the base. function enter() if system.cur() == destsys and not flfdead and not basefound then -- Collect information needed for course calculations local spread = 45 -- max degrees off-course for waypoints local basepos = vec2.new(-8700,-3000) -- NOTE: Should be identical to the location in asset.xml! local jumppos = jump.pos( system.cur(), "Behar" ) -- Calculate course local dist = vec2.dist(basepos, jumppos) -- The distance from the jump point to the base local course = basepos - jumppos -- The vector from the jump point to the base local cx, cy = course:get() -- Cartesian coordinates of the course local courseangle = math.atan2(cy, cx) -- Angle of the course in polar coordinates -- Generate new angles deviating off the courseangle local angle2 = courseangle + (rnd.rnd() - 0.5) * 2 * spread * 2 * math.pi / 360 local angle1 = courseangle + (rnd.rnd() - 0.5) * 2 * spread * 2 * math.pi / 360 -- Set FLF base waypoints -- Base is at -8700,-3000 -- Waypoints deviate off the course by at most spread degrees waypoint2 = jumppos + vec2.new(dist / 3 * math.cos(angle2), dist / 3 * math.sin(angle2)) waypoint1 = jumppos + course * 1 / 3 + vec2.new(dist / 3 * math.cos(angle1), dist / 3 * math.sin(angle1)) waypoint0 = basepos -- The base will not be spawned until the player is close to this waypoint. pilot.toggleSpawn(false) pilot.clear() -- Add FLF ships that are to guide the player to the FLF base (but only after a battle!) fleetFLF = addShips( "FLF Vendetta", "flf_norun", jumppos, 3 ) faction.get("FLF"):modPlayerSingle(-200) hook.timer(2000, "commFLF") hook.timer(25000, "wakeUpGregarYouLazyBugger") end end -- There are two cases we need to check here: landing on the FLF base and landing on a Dvaered world. function land() -- Case FLF base if planet.cur():name() == "Sindbad" then tk.msg(title[4], text[4]:format(player.name())) tk.msg(title[4], text[5]) var.push("flfbase_intro", 2) var.pop("flfbase_flfshipkilled") misn.cargoJet(gregar) misn.finish(true) -- Case Dvaered planet elseif planet.cur():faction():name() == "Dvaered" and not basefound then if tk.yesno(turnintitle[1], turnintext[1]) then tk.msg(turnintitle[2], turnintext[2]) faction.get("Dvaered"):modPlayerSingle(5) var.push("flfbase_intro", 1) var.pop("flfbase_flfshipkilled") misn.cargoJet(gregar) misn.finish(true) end end end function commFLF() fleetFLF[1]:comm(comm_msg) end -- Gregar wakes up and calls off the FLF attackers. They agree to guide you to their hidden base. -- If the player has destroyed the FLF ships, nothing happens and a flag is set. In this case, the player can only do the Dvaered side of the mini-campaign. function wakeUpGregarYouLazyBugger() flfdead = true -- Prevents failure if ALL the ships are dead. for i, j in ipairs(fleetFLF) do if j:exists() then j:setInvincible(true) j:setFriendly() j:setHealth(100,100) j:changeAI("flf_norun") j:setHilight(true) flfdead = false end end if not flfdead then tk.msg(title[2], text[2]) tk.msg(title[2], text[3]) faction.get("FLF"):modPlayerSingle(105) -- Small buffer to ensure it doesn't go negative again right away. misn.osdCreate(misn_title, {osd_desc[1]:format(destsysname), osd_adddesc, osd_desc[2]}) misn.osdActive(2) hook.timer(2000, "annai") OORT = hook.timer(10000, "outOfRange") end end -- Fly the FLF ships through their waypoints function annai() local poss = {} poss[1] = vec2.new(0,70) poss[2] = vec2.new(50, -50) poss[3] = vec2.new(-50, -50) for i, j in ipairs(fleetFLF) do if j:exists() then j:control() j:goto(player.pos()) -- NOT the player pilot, or the task may not pop properly. j:goto(waypoint2, false) j:goto(waypoint1, false) j:goto(waypoint0 + poss[i]) end end spawner = hook.timer(1000, "spawnbase") end -- Part of the escort script function spawnbase() local mindist = 2000 -- definitely OOR. for i, j in ipairs(fleetFLF) do if j:exists() then mindist = math.min(mindist, vec2.dist(j:pos(), waypoint0)) end end if mindist < 1000 then diff.apply("FLF_base") -- Safety measure to ensure the player can land. base = planet.get("Sindbad") base:landOverride() basefound = true hook.rm(OORT) else spawner = hook.timer(1000, "spawnbase") end end -- Check if the player is still with his escorts function outOfRange() local mindist = 2000 -- definitely OOR. for i, j in ipairs(fleetFLF) do if j:exists() then mindist = math.min(mindist, vec2.dist(j:pos(), player.pilot():pos())) end end if mindist < 1000 then OORT = hook.timer(2000, "outOfRange") else -- TODO: handle mission failure due to distance to escorts tk.msg(contacttitle, contacttext) for i, j in ipairs(fleetFLF) do if j:exists() then j:rm() end end hook.rm(spawner) end end function abort() var.pop("flfbase_flfshipkilled") misn.finish(false) end
gpl-3.0
kmfreeminer/km-freeminer-mods
mods/default/functions.lua
2
14294
--{{{ Sounds function default.node_sound_defaults(table) table = table or {} table.footstep = table.footstep or {name="", gain=1.0} table.dug = table.dug or {name="default_dug_node", gain=0.25} table.place = table.place or {name="default_place_node_hard", gain=1.0} return table end function default.node_sound_stone_defaults(table) table = table or {} table.footstep = table.footstep or {name="default_hard_footstep", gain=0.5} table.dug = table.dug or {name="default_hard_footstep", gain=1.0} default.node_sound_defaults(table) return table end function default.node_sound_dirt_defaults(table) table = table or {} table.footstep = table.footstep or {name="default_dirt_footstep", gain=1.0} table.dug = table.dug or {name="default_dirt_footstep", gain=1.5} table.place = table.place or {name="default_place_node", gain=1.0} default.node_sound_defaults(table) return table end function default.node_sound_sand_defaults(table) table = table or {} table.footstep = table.footstep or {name="default_sand_footstep", gain=0.2} table.dug = table.dug or {name="default_sand_footstep", gain=0.4} table.place = table.place or {name="default_place_node", gain=1.0} default.node_sound_defaults(table) return table end function default.node_sound_wood_defaults(table) table = table or {} table.footstep = table.footstep or {name="default_wood_footstep", gain=0.5} table.dug = table.dug or {name="default_wood_footstep", gain=1.0} default.node_sound_defaults(table) return table end function default.node_sound_leaves_defaults(table) table = table or {} table.footstep = table.footstep or {name="default_grass_footstep", gain=0.35} table.dug = table.dug or {name="default_grass_footstep", gain=0.7} table.dig = table.dig or {name="default_dig_crumbly", gain=0.4} table.place = table.place or {name="default_place_node", gain=1.0} default.node_sound_defaults(table) return table end function default.node_sound_glass_defaults(table) table = table or {} table.footstep = table.footstep or {name="default_glass_footstep", gain=0.5} table.dug = table.dug or {name="default_break_glass", gain=1.0} default.node_sound_defaults(table) return table end --}}} --{{{ Lavacooling ABM minetest.register_abm({ nodenames = {"default:lava_source", "default:lava_flowing"}, neighbors = {"group:water"}, interval = 3, chance = 3, action = function(pos, node, active_object_count, active_object_count_wider) core.freeze_melt(pos, -1); minetest.sound_play("default_cool_lava", { pos = pos, max_hear_distance = 16, gain = 0.25 }) end, }) minetest.register_abm({ nodenames = {"default:lava_source", "default:lava_flowing"}, interval = 100, chance = 10, action = function(pos, node, active_object_count, active_object_count_wider) -- bad place: to not freeze lava in caves if not pos.y or pos.y < -100 then return end -- skip springs if node.param2 >= 128 then return end local light = core.get_node_light({x=pos.x,y=pos.y+1, z=pos.z}, 0.5) if not light or light < default.LIGHT_MAX then return end core.freeze_melt(pos, -1); end, }) --}}} --{{{ Papyrus and cactus growing minetest.register_abm({ nodenames = {"default:cactus"}, neighbors = {"group:sand"}, interval = 50, chance = 20, action = function(pos, node) pos.y = pos.y-1 local name = minetest.get_node(pos).name if minetest.get_item_group(name, "sand") ~= 0 then pos.y = pos.y+1 local height = 0 while minetest.get_node(pos).name == "default:cactus" and height < 4 do height = height+1 pos.y = pos.y+1 end if height < 4 then if minetest.get_node(pos).name == "air" then minetest.set_node(pos, {name="default:cactus"}) end end end end, }) minetest.register_abm({ nodenames = {"default:papyrus"}, neighbors = {"default:dirt", "default:dirt_with_grass"}, interval = 50, chance = 20, action = function(pos, node) pos.y = pos.y-1 local name = minetest.get_node(pos).name if name == "default:dirt" or name == "default:dirt_with_grass" then if minetest.find_node_near(pos, 3, {"group:water"}) == nil then return end pos.y = pos.y+1 local height = 0 while minetest.get_node(pos).name == "default:papyrus" and height < 4 do height = height+1 pos.y = pos.y+1 end if height < 4 then if minetest.get_node(pos).name == "air" then minetest.set_node(pos, {name="default:papyrus"}) end end end end, }) --}}} --{{{ Leafdecay default.leafdecay_trunk_cache = {} default.leafdecay_enable_cache = true -- Spread the load of finding trunks default.leafdecay_trunk_find_allow_accumulator = 0 minetest.register_globalstep(function(dtime) local finds_per_second = 5000 default.leafdecay_trunk_find_allow_accumulator = math.floor(dtime * finds_per_second) end) default.after_place_leaves = function(pos, placer, itemstack, pointed_thing) local node = minetest.get_node(pos) node.param2 = 1 minetest.set_node(pos, node) end minetest.register_abm({ nodenames = {"group:leafdecay"}, neighbors = {"air", "group:liquid"}, -- A low interval and a high inverse chance spreads the load interval = 10, chance = 3, action = function(p0, node, _, _) --print("leafdecay ABM at "..p0.x..", "..p0.y..", "..p0.z..")") local do_preserve = false local d = minetest.registered_nodes[node.name].groups.leafdecay if not d or d == 0 then --print("not groups.leafdecay") return end local n0 = minetest.get_node(p0) if n0.param2 ~= 0 then --print("param2 ~= 0") return end local p0_hash = nil if default.leafdecay_enable_cache then p0_hash = minetest.hash_node_position(p0) local trunkp = default.leafdecay_trunk_cache[p0_hash] if trunkp then local n = minetest.get_node(trunkp) local reg = minetest.registered_nodes[n.name] -- Assume ignore is a trunk, to make the thing -- work at the border of the active area if n.name == "ignore" or (reg and reg.groups.tree and reg.groups.tree ~= 0) then --print("cached trunk still exists") return end --print("cached trunk is invalid") -- Cache is invalid table.remove(default.leafdecay_trunk_cache, p0_hash) end end if default.leafdecay_trunk_find_allow_accumulator <= 0 then return end default.leafdecay_trunk_find_allow_accumulator = default.leafdecay_trunk_find_allow_accumulator - 1 -- Assume ignore is a trunk, to make the thing -- work at the border of the active area local p1 = minetest.find_node_near(p0, d, {"ignore", "group:tree"}) if p1 then do_preserve = true if default.leafdecay_enable_cache then --print("caching trunk") -- Cache the trunk default.leafdecay_trunk_cache[p0_hash] = p1 end end if not do_preserve then -- Drop stuff other than the node itself local itemstacks = minetest.get_node_drops(n0.name) for _, itemname in ipairs(itemstacks) do if minetest.get_item_group(n0.name, "leafdecay_drop") ~= 0 or itemname ~= n0.name then local p_drop = { x = p0.x - 0.5 + math.random(), y = p0.y - 0.5 + math.random(), z = p0.z - 0.5 + math.random(), } minetest.add_item(p_drop, itemname) end end -- Remove node minetest.remove_node(p0) nodeupdate(p0) end end }) --}}} --{{{ Grass growing on well-lit dirt if not default.weather then minetest.register_abm({ nodenames = {"default:dirt"}, interval = 2, chance = 200, action = function(pos, node) local above = {x = pos.x, y = pos.y + 1, z = pos.z} local name = minetest.get_node(above).name local nodedef = minetest.registered_nodes[name] if nodedef and (nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none" and (minetest.get_node_light(above) or 0) >= 13 then if name == "default:snow" or name == "default:snowblock" then minetest.set_node(pos, {name = "default:dirt_with_snow"}) else minetest.set_node(pos, {name = "default:dirt_with_grass"}) end end end }) -- Grass and dry grass removed in darkness minetest.register_abm({ nodenames = {"default:dirt_with_grass", "default:dirt_with_dry_grass"}, interval = 2, chance = 20, action = function(pos, node) local above = {x = pos.x, y = pos.y + 1, z = pos.z} local name = minetest.get_node(above).name local nodedef = minetest.registered_nodes[name] if name ~= "ignore" and nodedef and not ( (nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none" ) then minetest.set_node(pos, {name = "default:dirt"}) end end }) end --}}} --{{{ Moss growth on cobble near water minetest.register_abm({ nodenames = {"default:cobble"}, neighbors = {"group:water"}, interval = 17, chance = 200, neighbors_range = 2, --catch_up = false, action = function(pos, node) minetest.set_node(pos, {name = "default:mossycobble"}) end }) --}}} --{{{ Modname getting and stripping function default.get_modname (name) if name:sub(1,1) ~= ":" then return name:sub(1, name:find(":") - 1) else return name:sub(2, name:find(":") - 1) end end function default.strip_modname (name) if name:sub(1,1) ~= ":" then return name:sub(name:find(":") + 1) else return name:sub(name:find(":", 2) + 1) end end --}}} --{{{ Cyrillic lower string.CYRILLIC_LOWER = { ["А"] = "а", ["Б"] = "б", ["В"] = "в", ["Г"] = "г", ["Д"] = "д", ["Е"] = "е", ["Ё"] = "ё", ["Ж"] = "ж", ["З"] = "з", ["И"] = "и", ["Й"] = "й", ["К"] = "к", ["Л"] = "л", ["М"] = "м", ["Н"] = "н", ["О"] = "о", ["П"] = "п", ["Р"] = "р", ["С"] = "с", ["Т"] = "т", ["У"] = "у", ["Ф"] = "ф", ["Х"] = "х", ["Ц"] = "ц", ["Ч"] = "ч", ["Ш"] = "ш", ["Щ"] = "щ", ["Ъ"] = "ъ", ["Ы"] = "ы", ["Ь"] = "ь", ["Э"] = "э", ["Ю"] = "ю", ["Я"] = "я", } function string.lower_cyr (str) for upper, lower in pairs(string.CYRILLIC_LOWER) do str = str:gsub(upper, lower) end return str end --}}} --{{{ Cyrillic string index fix function string.cyr_index (s, index) local new_index = index local step_index = index local function increase_index() new_index = new_index + 1 end repeat step_index = new_index new_index = index local sub = s:sub(1, step_index) for upper, lower in pairs(string.CYRILLIC_LOWER) do sub:gsub(upper, increase_index) sub:gsub(lower, increase_index) end until step_index == new_index return step_index end --}}} --{{{ string: Find nearest function string.find_nearest(s, pattern, index, range) local i = s:cyr_index(index) local before = s:sub(1, i - 1) local after = s:sub(i + 1) if range then before = before:sub(before:cyr_index(index - range)) after = after:sub(1, after:cyr_index(range)) end local first_before = before:reverse():find(pattern) local first_after = after:find(pattern) if first_before == nil and first_after ~= nil then return i + first_after elseif first_before ~=nil and first_after == nil then return i - first_before elseif first_before ~= nil and first_after ~= nil then if first_before < first_after then return i - first_before else return i + first_after end else return end end --}}} --{{{ Child attachments function default.get_attached(parent, bone, position, rotation) local result = {} for _, entity in pairs(minetest.luaentities) do local object = entity.object local o_parent, o_bone, o_pos, o_rot = object:get_attach() if o_parent ~= nil and o_parent == parent and (bone == nil or o_bone == bone) and (position == nil or vector.equals(o_pos, position)) and (rotation == nil or vector.equals(o_rot, rotation)) then table.insert(result, object) end end return result end --}}} --{{{ Delete table elemet function table.delete(t, value, all) if value == nil then return end local all = all or false for k,v in pairs(table) do if v == value then t[k] = nil if not all then return true end end end return true end --}}}
gpl-3.0
gajop/Zero-K
LuaUI/Configs/icontypes.lua
2
21107
-- $Id: icontypes.lua 4585 2009-05-09 11:15:01Z google frog $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: icontypes.lua -- brief: icontypes definitions -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --This file is used by engine, it's just placed here so LuaUI can access it too -------------------------------------------------------------------------------- local icontypes = { default = { size=1.3, radiusadjust=1, }, none = { size=0, radiusadjust=0, }, -- commanders commander0 = { bitmap='icons/armcommander.dds', size=1.9, }, commander1 = { bitmap='icons/armcommander.dds', size=2, }, commander2 = { bitmap='icons/armcommander.dds', size=2.2, }, commander3 = { bitmap='icons/armcommander.dds', size=2.4, }, commander4 = { bitmap='icons/armcommander.dds', size=2.6, }, commander5 = { bitmap='icons/armcommander.dds', size=2.8, }, corcommander = { bitmap='icons/corcommander.dds', size=2, }, krogoth = { bitmap='icons/krogoth.dds', size=3, }, air = { bitmap='icons/air.dds', size=1.2, }, sea = { bitmap='icons/sea.dds', size=1.5, }, building = { bitmap='icons/building.dds', radiusadjust=1, size=0.8, }, -------------------------------------------------------------------------------- -- LEGACY -------------------------------------------------------------------------------- kbot = { bitmap='icons/bomb.dds', size=1.5, }, assaultkbot = { bitmap='icons/t3generic.dds', size=1.8, }, tank = { bitmap='icons/tank.dds', size=1.5, }, heavytank = { bitmap='icons/riot.dds', size=2.0, }, --long-range missiles such as Merls and Dominators - use cruisemissile now lrm = { bitmap='icons/lrm.dds', size=1.8, }, scout = { bitmap='icons/scout.dds', size=1.5, }, fixedarty = { bitmap='icons/fixedarty.dds', size=1.8, }, mobilearty = { bitmap='icons/mobilearty.dds', size=1.8, }, fixedaa = { bitmap='icons/fixedaa.dds', size=1.8, }, mobileaa = { bitmap='icons/mobileaa.dds', size=1.8, }, --kamikaze! bomb = { bitmap='icons/bomb.dds', size=1.6, }, -------------------------------------------------------------------------------- -- CURRENT ICONS -------------------------------------------------------------------------------- --kbots kbotjammer = { bitmap='icons/kbotjammer.dds', size=2.0, }, kbotshield = { bitmap='icons/kbotshield.dds', size=1.8, }, kbotradar = { bitmap='icons/kbotradar.dds', size=1.8, }, kbotraider = { bitmap='icons/kbotraider.dds', size=1.8, }, kbotscythe = { bitmap='icons/kbotscythe.dds', size=1.8, }, kbotassault = { bitmap='icons/kbotassault.dds', size=2, }, kbotskirm = { bitmap='icons/kbotskirm.dds', size=1.8, }, kbotriot = { bitmap='icons/kbotriot.dds', size=1.8, }, kbotarty = { bitmap='icons/kbotarty.dds', size=1.8, }, kbotlrarty = { bitmap='icons/kbotlrarty.dds', size=1.8, }, kbotlrm = { bitmap='icons/kbotlrm.dds', size=1.8, }, kbotaa = { bitmap='icons/kbotaa.dds', size=1.8, }, kbotscout = { bitmap='icons/kbotscout.dds', size=1.8, }, --puppy kbotbomb = { bitmap='icons/kbotbomb.dds', size=1.8, }, --vehicles vehicleshield = { bitmap='icons/vehicleshield.dds', size=1.8, }, vehiclejammer = { bitmap='icons/vehiclejammer.dds', size=1.8, }, vehicleradar = { bitmap='icons/vehicleradar.dds', size=1.8, }, vehiclegeneric = { bitmap='icons/vehiclegeneric.dds', size=1.8, }, vehiclescout = { bitmap='icons/vehiclescout.dds', size=1.8, }, vehicleraider = { bitmap='icons/vehicleraider.dds', size=1.8, }, vehicleassault = { bitmap='icons/vehicleassault.dds', size=1.8, }, vehicleskirm = { bitmap='icons/vehicleskirm.dds', size=1.8, }, vehiclesupport = { bitmap='icons/vehiclesupport.dds', size=1.8, }, vehicleaa = { bitmap='icons/vehicleaa.dds', size=1.8, }, vehicleriot = { bitmap='icons/vehicleriot.dds', size=1.8, }, vehiclearty = { bitmap='icons/vehiclearty.dds', size=1.8, }, vehiclespecial = { bitmap='icons/vehiclespecial.png', size=2.1, }, vehiclelrarty = { bitmap='icons/vehiclelrarty.dds', size=2.2, }, vehicleaa = { bitmap='icons/vehicleaa.dds', size=1.8, }, --walkers walkerjammer = { bitmap='icons/walkerjammer.dds', size=2, }, walkershield = { bitmap='icons/walkershield.dds', size=2, }, walkerraider = { bitmap='icons/walkerraider.dds', size=1.6, }, walkerassault = { bitmap='icons/walkerassault.dds', size=1.7, }, walkerskirm = { bitmap='icons/walkerskirm.dds', size=1.7, }, walkerriot = { bitmap='icons/walkerriot.dds', size=1.6, }, walkerarty = { bitmap='icons/walkerarty.dds', size=1.6, }, walkerlrarty = { bitmap='icons/walkerlrarty.dds', size=2, }, walkeraa = { bitmap='icons/walkeraa.dds', size=1.6, }, walkerscout = { bitmap='icons/walkerscout.dds', size=2, }, --roach walkerbomb = { bitmap='icons/walkerbomb.png', distance=0.5, size=1.8, }, walkersupport = { bitmap='icons/walkersupport.png', size=2, }, -- amphibious amphraider = { bitmap='icons/amphraider.png', size=1.9, }, amphtorpraider = { bitmap='icons/amphtorpraider.png', size=1.9, }, amphskirm = { bitmap='icons/amphskirm.png', size=1.8, }, amphassault = { bitmap='icons/amphassault.png', size=2.6, }, amphaa = { bitmap='icons/amphaa.png', size=1.8, }, amphtorpriot = { bitmap='icons/amphtorpriot.png', size=2.2, }, amphtorpassault = { bitmap='icons/amphtorpriot.png', size=2.6, }, amphtransport = { bitmap='icons/amphtransport.png', size=2.2, }, --t2 vehicles (aka tanks) tankantinuke = { bitmap='icons/tankantinuke.dds', size=2.8, }, tankassault = { bitmap='icons/tankassault.dds', size=2.0, }, tankskirm = { bitmap='icons/tankskirm.dds', size=2.3, }, tankriot = { bitmap='icons/tankriot.dds', size=2.0, }, tankraider = { bitmap='icons/tankraider.dds', size=2.0, }, tankarty = { bitmap='icons/tankarty.dds', size=2.0, }, tanklrarty = { bitmap='icons/tanklrarty.dds', size=2.2, }, tanklrm = { bitmap='icons/tanklrm.dds', size=2.0, }, tankaa = { bitmap='icons/tankaa.dds', size=2.0, }, tankscout = { bitmap='icons/tankscout.dds', size=2.0, }, --hover hoverraider = { bitmap='icons/hoverraider.dds', size=1.8, }, hoverassault = { bitmap='icons/hoverassault.dds', size=1.8, }, hoverskirm = { bitmap='icons/hoverskirm.dds', size=1.8, }, hoverspecial = { bitmap='icons/hoverspecial.png', size=1.8, }, hoverriot = { bitmap='icons/hoverriot.dds', size=1.8, }, hoverarty = { bitmap='icons/hoverarty.dds', size=1.8, }, hoveraa = { bitmap='icons/hoveraa.dds', size=1.8, }, hovertransport = { bitmap='icons/hovertransport.dds', size=1.8, }, --spider spiderantinuke = { bitmap='icons/spiderantinuke.dds', size=2.8, }, spidergeneric = { bitmap='icons/spidergeneric.dds', size=1.8, }, spiderscout = { bitmap='icons/spiderscout.dds', distance=0.75, size=1.8, }, spiderraider = { bitmap='icons/spiderraider.dds', size=1.8, }, spiderskirm = { bitmap='icons/spiderskirm.dds', size=1.8, }, spiderriot = { bitmap='icons/spiderriot.dds', size=1.8, }, spiderriotspecial = { bitmap='icons/spiderriotspecial.png', size=1.8, }, spiderassault = { bitmap='icons/spiderassault.dds', size=1.8, }, spiderarty = { bitmap='icons/spiderarty.dds', size=1.8, }, spideraa = { bitmap='icons/spideraa.dds', size=1.8, }, spidersupport = { bitmap='icons/spidersupport.dds', size=2.4, }, --tick spiderbomb = { bitmap='icons/spiderbomb.dds', distance=0.5, size=1.8, }, --jumper jumpjetgeneric = { bitmap='icons/jumpjetgeneric.dds', size=1.8, }, jumpjetaa = { bitmap='icons/jumpjetaa.dds', size=1.8, }, jumpjetassault = { bitmap='icons/jumpjetassault.dds', size=1.8, }, --skuttle jumpjetbomb = { bitmap='icons/jumpjetbomb.dds', distance=0.5, size=1.8, }, jumpjetraider = { bitmap='icons/jumpjetraider.dds', size=1.8, }, jumpjetriot = { bitmap='icons/jumpjetriot.dds', size=1.8, }, kbotwideriot = { bitmap='icons/kbotwideriot.png', size=2, }, -- fatbots (jumpers that don't jump) fatbotarty = { bitmap='icons/fatbotarty.png', size=2.1, }, fatbotsupport = { bitmap='icons/fatbotsupport.png', size=1.8, }, --striders (aka tier 3) t3riot = { bitmap='icons/t3riot.dds', size=2.6, }, t3generic = { bitmap='icons/t3generic.dds', size=2.9, }, t3genericbig = { bitmap='icons/t3generic.dds', size=3, }, t3special = { bitmap='icons/t3special.png', size=2.7, }, t3arty = { bitmap='icons/t3arty.dds', size=2.7, }, t3skirm = { bitmap='icons/t3skirm.dds', size=2.7, }, t3spiderriot = { bitmap='icons/t3spiderriot.png', size=2.4, }, t3spidergeneric = { bitmap='icons/t3spidergeneric.png', size=2.7, }, t3jumpjetriot = { bitmap='icons/t3jumpjetriot.png', size=2.4, }, --icon for construction units and field engineers builder = { bitmap='icons/builder.dds', size=1.8, }, amphbuilder = { bitmap='icons/amphbuilder.png', size=1.8, }, hoverbuilder = { bitmap='icons/hoverbuilder.png', size=1.8, }, jumpjetbuilder = { bitmap='icons/jumpjetbuilder.png', size=1.8, }, kbotbuilder = { bitmap='icons/kbotbuilder.png', size=1.8, }, shipbuilder = { bitmap='icons/shipbuilder.png', size=1.8, }, spiderbuilder = { bitmap='icons/spiderbuilder.png', size=1.8, }, tankbuilder = { bitmap='icons/tankbuilder.png', size=1.8, }, vehiclebuilder = { bitmap='icons/vehiclebuilder.png', size=1.8, }, walkerbuilder = { bitmap='icons/walkerbuilder.png', size=1.8, }, builderair = { bitmap='icons/builderair.dds', size=1.8, }, t3builder = { bitmap='icons/t3builder.dds', size=2, }, staticbuilder = { bitmap='icons/staticbuilder.dds', size=1, }, t3hub = { bitmap='icons/t3hub.dds', size=2.4, }, --defense defenseshield = { bitmap='icons/defenseshield.dds', size=2.0, }, defense = { bitmap='icons/defense.dds', size=2.0, }, defensetorp = { bitmap='icons/defensetorp.png', size=2.0, }, defenseskirm = { bitmap='icons/defenseskirm.dds', size=2.0, }, defenseheavy = { bitmap='icons/defenseheavy.dds', size=2.0, }, defenseriot = { bitmap='icons/defenseriot.dds', size=2.0, }, defensesupport = { bitmap='icons/defensesupport.png', size=2.0, }, defenseraider = { bitmap='icons/defenseraider.dds', size=2.0, }, defenseaa = { bitmap='icons/defenseaa.dds', size=2.0, }, defenseskirmaa = { bitmap='icons/defenseskirmaa.png', size=2.0, }, defensespecial = { bitmap='icons/defensespecial.dds', size=2.0, }, staticjammer = { bitmap='icons/staticjammer.dds', size=2.0, }, staticshield = { bitmap='icons/staticshield.dds', size=2.0, }, statictransport = { bitmap='icons/statictransport.png', size=1.4, }, staticaa = { bitmap='icons/staticaa.dds', size=2.0, }, staticskirmaa = { bitmap='icons/staticskirmaa.png', size=2.0, }, staticarty = { bitmap='icons/staticarty.dds', size=2.2, }, staticbomb = { bitmap='icons/staticbomb.dds', size=2.0, }, heavysam = { bitmap='icons/heavysam.dds', size=2.2, }, --covers LRPC ships as well as statics lrpc = { bitmap='icons/lrpc.dds', size=2.4, }, radar = { bitmap='icons/radar.dds', size=2, }, advradar = { bitmap='icons/radar.dds', size=2.8, }, sonar = { bitmap='icons/sonar.dds', size=2, }, --now only covers snipers sniper = { bitmap='icons/sniper.dds', size=2.4, }, --Pole Bot stealth = { bitmap='icons/sniper.dds', size=1.6, }, --clogger icon clogger = { bitmap='icons/clogger.dds', size=2, }, --Annihilator fixedtachyon = { bitmap='icons/fixedtachyon.dds', size=2, }, -- DDM staticassaultriot = { bitmap='icons/staticassaultriot.png', size=2, }, --Penetrator mobiletachyon = { bitmap='icons/mobiletachyon.dds', size=2.3, }, --plane icons scoutplane = { bitmap='icons/scoutplane.dds', size=1.7, }, radarplane = { bitmap='icons/radarplane.dds', size=2.0, }, fighter = { bitmap='icons/fighter.dds', size=1.5, }, stealthfighter = { bitmap='icons/stealthfighter.dds', size=1.7, }, bomber = { bitmap='icons/bomber.dds', size=1.8, }, bombernuke = { bitmap='icons/bombernuke.dds', size=2.5, }, bomberriot = { bitmap='icons/bomberriot.dds', size=2.1, }, bomberassault = { bitmap='icons/bomberassault.dds', size=2.1, }, bomberspecial = { bitmap='icons/bomberspecial.dds', size=2.1, }, bomberraider = { bitmap='icons/bomberraider.dds', size=2.1, }, smallgunship = { bitmap='icons/gunship.png', size=1.4, }, gunship = { bitmap='icons/gunship.png', size=2, }, gunshipaa = { bitmap='icons/gunshipaa.png', size=2, }, gunshipears = { bitmap='icons/gunshipears.png', size=2, }, heavygunship = { bitmap='icons/heavygunship.dds', size=2.4, }, heavygunshipears = { bitmap='icons/heavygunshipears.png', size=2.4, }, supergunship = { bitmap='icons/supergunship.dds', size=2.8, }, gunshipscout = { bitmap='icons/gunshipscout.png', size=1.5, }, gunshipspecial = { bitmap='icons/gunshipspecial.png', size=1.5, }, gunshipraider = { bitmap='icons/gunshipraider.png', size=2, }, gunshipskirm = { bitmap='icons/gunshipskirm.png', size=2, }, gunshipriot = { bitmap='icons/gunshipriot.png', size=4, }, gunshipassault = { bitmap='icons/gunshipassault.png', size=2.4, }, gunshiparty = { bitmap='icons/gunshiparty.png', size=2.4, }, gunshiptransport = { bitmap='icons/gunshiptransport.png', size=2, }, gunshiptransport_large = { bitmap='icons/gunshiptransport.png', size=3.2, }, heavygunshipskirm = { bitmap='icons/heavygunshipskirm.png', size=2.4, }, heavygunshiptransport = { bitmap='icons/heavygunshiptransport.png', size=2.4, }, heavygunshipassault = { bitmap='icons/heavygunshipassault.png', size=2.4, }, nebula = { bitmap='icons/nebula.dds', size=4, }, airtransport = { bitmap='icons/airtransport.dds', size=2.3, }, airtransportbig = { bitmap='icons/airtransport.dds', size=3, }, airbomb = { bitmap='icons/airbomb.dds', distance=0.5, size=1.6, }, --spec ops t3builder = { bitmap='icons/t3builder.dds', size=1.8, }, --nanos staticbuilder = { bitmap='icons/staticbuilder.dds', size=1.8, }, --ship icons scoutboat = { bitmap='icons/scoutboat.dds', size=2.2, }, corvette = { bitmap='icons/corvette.dds', size=2.8, }, hunter = { bitmap='icons/hunter.dds', size=2.8, }, vanquisher = { bitmap='icons/vanquisher.dds', size=3.2, }, destroyer = { bitmap='icons/destroyer.dds', size=3.2, }, aaship = { bitmap='icons/aaship.dds', size=2.9, }, enforcer = { bitmap='icons/enforcer.dds', size=3.2, }, submarine = { bitmap='icons/submarine.dds', size=3.0, }, snipersub = { bitmap='icons/snipersub.dds', size=3.5, }, missilesub = { bitmap='icons/missilesub.dds', size=4, }, battleship = { bitmap='icons/battleship.dds', size=4, }, carrier = { bitmap='icons/carrier.dds', size=4, }, shiptransport = { bitmap='icons/shiptransport.dds', size=2.5, }, --icon for energy buildings of various tiers, including pylon energy_med = { bitmap='icons/energy_med.png', size=2.1, }, energywind = { bitmap='icons/energywind.dds', size=1.8, }, energysolar = { bitmap='icons/energysolar.dds', size=2, }, energyfus = { bitmap='icons/energyfus.dds', size=2, }, energysuperfus = { bitmap='icons/energysuperfus.dds', size=3.2, }, energygeo = { bitmap='icons/geo1.png', size=2, }, energymohogeo = { bitmap='icons/geo2.png', size=2.4, }, pylon = { bitmap='icons/pylon.dds', size=1.8, }, --icon for cruise missiles such as Detonator and Catalyst cruisemissile = { bitmap='icons/cruisemissile.dds', size=2.5, }, cruisemissilesmall = { bitmap='icons/cruisemissile.dds', size=1, }, --icon for nuclear missile silos nuke = { bitmap='icons/nuke.dds', size=3.0, }, --icon for ABM platforms, both static and mobile antinuke = { bitmap='icons/antinuke.dds', size=3.0, }, --Starlight/Zenith mahlazer = { bitmap='icons/mahlazer.dds', size=3.0, }, special = { bitmap='icons/special.dds', size=1.6, }, shield = { bitmap='icons/shield.dds', size=1.6, }, mex = { bitmap='icons/mex.dds', size = 1.1, }, storage = { bitmap='icons/storage.dds', size = 1, }, power = { bitmap='icons/power.dds', size=1, radiusadjust=1, }, --landmines mine = { bitmap='icons/mine.dds', distance=0.75, size=1.4, }, --facs factory = { bitmap='icons/factory.dds', size=2.6, radiusadjust=1, }, fact3 = { bitmap='icons/fact3.dds', size=2.6, radiusadjust=0, }, factank = { bitmap='icons/factank.dds', size=2.6, radiusadjust=0, }, facair = { bitmap='icons/facair.dds', size=2.6, radiusadjust=0, }, facgunship = { bitmap='icons/facgunship.dds', size=2.6, radiusadjust=0, }, facvehicle = { bitmap='icons/facvehicle.dds', size=2.6, radiusadjust=0, }, fackbot = { bitmap='icons/fackbot.dds', size=2.6, radiusadjust=0, }, facwalker = { bitmap='icons/facwalker.dds', size=2.6, radiusadjust=0, }, facspider = { bitmap='icons/facspider.png', size=2.6, radiusadjust=0, }, facjumpjet = { bitmap='icons/facjumpjet.png', size=2.6, radiusadjust=0, }, facamph = { bitmap='icons/facamph.png', size=2.6, radiusadjust=0, }, facship = { bitmap='icons/facship.dds', size=2.6, radiusadjust=0, }, fachover = { bitmap='icons/fachover.dds', size=2.6, radiusadjust=0, }, --chicken chicken = { --bitmap='icons/chicken.dds', bitmap='icons/kbotraider.dds', size=1.4, }, chickena = { --bitmap='icons/chickena.dds', bitmap='icons/walkerassault.dds', size=1.7, }, chickenc = { --bitmap='icons/chickenc.dds', bitmap='icons/spiderassault.dds', size=1.8, }, chickenf = { --bitmap='icons/chickenf.dds', bitmap='icons/fighter.dds', size=2.2, }, chickens = { --bitmap='icons/chickens.dds', bitmap='icons/kbotskirm.dds', size=1.5, }, chickenr = { --bitmap='icons/chickenr.dds', bitmap='icons/kbotarty.dds', size=1.6, }, chickendodo = { --bitmap='icons/chickendodo.dds', bitmap='icons/kbotbomb.dds', size=1.4, }, chickenleaper = { --bitmap='icons/chickenleaper.dds', bitmap='icons/jumpjetraider.dds', size=1.8, }, --chicken mini queen chickenminiq = { bitmap='icons/chickenq.dds', size=3.5, }, --chicken queen chickenq = { bitmap='icons/chickenq.dds', size=5.0, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return icontypes -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
L1L1/cardpeek
dot_cardpeek_dir/scripts/etc/gsm-mobile-country-codes.lua
16
7787
-- from ITU Recommendation E.218 (05/04) GSM_MCC = { [202] = "Greece" [204] = "Netherlands (Kingdom of the)" [206] = "Belgium" [208] = "France" [212] = "Monaco (Principality of)" [213] = "Andorra (Principality of)" [214] = "Spain" [216] = "Hungary (Republic of)" [218] = "Bosnia and Herzegovina" [219] = "Croatia (Republic of)" [220] = "Serbia and Montenegro" [222] = "Italy" [225] = "Vatican City State" [226] = "Romania" [228] = "Switzerland (Confederation of)" [230] = "Czech Republic" [231] = "Slovak Republic" [232] = "Austria" [234] = "United Kingdom of Great Britain and Northern Ireland" [235] = "United Kingdom of Great Britain and Northern Ireland" [238] = "Denmark" [240] = "Sweden" [242] = "Norway" [244] = "Finland" [246] = "Lithuania (Republic of)" [247] = "Latvia (Republic of)" [248] = "Estonia (Republic of)" [250] = "Russian Federation" [255] = "Ukraine" [257] = "Belarus (Republic of)" [259] = "Moldova (Republic of)" [260] = "Poland (Republic of)" [262] = "Germany (Federal Republic of)" [266] = "Gibraltar" [268] = "Portugal" [270] = "Luxembourg" [272] = "Ireland" [274] = "Iceland" [276] = "Albania (Republic of)" [278] = "Malta" [280] = "Cyprus (Republic of)" [282] = "Georgia" [283] = "Armenia (Republic of)" [284] = "Bulgaria (Republic of)" [286] = "Turkey" [288] = "Faroe Islands" [290] = "Greenland (Denmark)" [292] = "San Marino (Republic of)" [293] = "Slovenia (Republic of)" [294] = "The Former Yugoslav Republic of Macedonia" [295] = "Liechtenstein (Principality of)" [302] = "Canada" [308] = "Saint Pierre and Miquelon (Collectivité territoriale de la République française)" [310] = "United States of America" [311] = "United States of America" [312] = "United States of America" [313] = "United States of America" [314] = "United States of America" [315] = "United States of America" [316] = "United States of America" [330] = "Puerto Rico" [332] = "United States Virgin Islands" [334] = "Mexico" [338] = "Jamaica" [340] = "Martinique (French Department of)" [340] = "Guadeloupe (French Department of)" [342] = "Barbados" [344] = "Antigua and Barbuda" [346] = "Cayman Islands" [348] = "British Virgin Islands" [350] = "Bermuda" [352] = "Grenada" [354] = "Montserrat" [356] = "Saint Kitts and Nevis" [358] = "Saint Lucia" [360] = "Saint Vincent and the Grenadines" [362] = "Netherlands Antilles" [363] = "Aruba" [364] = "Bahamas (Commonwealth of the)" [365] = "Anguilla" [366] = "Dominica (Commonwealth of)" [368] = "Cuba" [370] = "Dominican Republic" [372] = "Haiti (Republic of)" [374] = "Trinidad and Tobago" [376] = "Turks and Caicos Islands" [400] = "Azerbaijani Republic" [401] = "Kazakstan (Republic of)" [402] = "Bhutan (Kingdom of)" [404] = "India (Republic of)" [405] = "India (Republic of)" [410] = "Pakistan (Islamic Republic of)" [412] = "Afghanistan" [413] = "Sri Lanka (Democratic Socialist Republic of)" [414] = "Myanmar (Union of)" [415] = "Lebanon" [416] = "Jordan (Hashemite Kingdom of)" [417] = "Syrian Arab Republic" [418] = "Iraq (Republic of)" [419] = "Kuwait (State of)" [420] = "Saudi Arabia (Kingdom of)" [421] = "Yemen (Republic of)" [422] = "Oman (Sultanate of)" [424] = "United Arab Emirates" [425] = "Israel (State of)" [426] = "Bahrain (Kingdom of)" [427] = "Qatar (State of)" [428] = "Mongolia" [429] = "Nepal" [430] = "United Arab Emirates (Note 2)" [431] = "United Arab Emirates (Note 2)" [432] = "Iran (Islamic Republic of)" [434] = "Uzbekistan (Republic of)" [436] = "Tajikistan (Republic of)" [437] = "Kyrgyz Republic" [438] = "Turkmenistan" [440] = "Japan" [441] = "Japan" [450] = "Korea (Republic of)" [452] = "Viet Nam (Socialist Republic of)" [454] = "Hongkong, China" [455] = "Macao, China" [456] = "Cambodia (Kingdom of)" [457] = "Lao People's Democratic Republic" [460] = "China (People's Republic of)" [461] = "China (People's Republic of)" [466] = "Taiwan, China" [467] = "Democratic People's Republic of Korea" [470] = "Bangladesh (People's Republic of) " [472] = "Maldives (Republic of)" [502] = "Malaysia" [505] = "Australia" [510] = "Indonesia (Republic of)" [514] = "Democratic Republic of Timor-Leste" [515] = "Philippines (Republic of the)" [520] = "Thailand" [525] = "Singapore (Republic of)" [528] = "Brunei Darussalam" [530] = "New Zealand" [534] = "Northern Mariana Islands (Commonwealth of the)" [535] = "Guam" [536] = "Nauru (Republic of)" [537] = "Papua New Guinea" [539] = "Tonga (Kingdom of)" [540] = "Solomon Islands" [541] = "Vanuatu (Republic of)" [542] = "Fiji (Republic of)" [543] = "Wallis and Futuna (Territoire français d'outremer)" [544] = "American Samoa" [545] = "Kiribati (Republic of)" [546] = "New Caledonia (Territoire français d'outre-mer)" [547] = "French Polynesia (Territoire français d'outre-mer)" [548] = "Cook Islands" [549] = "Samoa (Independent State of)" [550] = "Micronesia (Federated States of)" [551] = "Marshall Islands (Republic of the)" [552] = "Palau (Republic of)" [602] = "Egypt (Arab Republic of)" [603] = "Algeria (People's Democratic Republic of)" [604] = "Morocco (Kingdom of)" [605] = "Tunisia" [606] = "Libya (Socialist People's Libyan Arab Jamahiriya)" [607] = "Gambia (Republic of the)" [608] = "Senegal (Republic of)" [609] = "Mauritania (Islamic Republic of)" [610] = "Mali (Republic of)" [611] = "Guinea (Republic of)" [612] = "Côte d'Ivoire (Republic of)" [613] = "Burkina Faso" [614] = "Niger (Republic of the)" [615] = "Togolese Republic" [616] = "Benin (Republic of)" [617] = "Mauritius (Republic of)" [618] = "Liberia (Republic of)" [619] = "Sierra Leone" [620] = "Ghana " [621] = "Nigeria (Federal Republic of)" [622] = "Chad (Republic of)" [623] = "Central African Republic" [624] = "Cameroon (Republic of)" [625] = "Cape Verde (Republic of)" [626] = "Sao Tome and Principe (Democratic Republic of)" [627] = "Equatorial Guinea (Republic of)" [628] = "Gabonese Republic" [629] = "Congo (Republic of the)" [630] = "Democratic Republic of the Congo" [631] = "Angola (Republic of)" [632] = "Guinea-Bissau (Republic of)" [633] = "Seychelles (Republic of)" [634] = "Sudan (Republic of the)" [635] = "Rwandese Republic" [636] = "Ethiopia (Federal Democratic Republic of)" [637] = "Somali Democratic Republic" [638] = "Djibouti (Republic of)" [639] = "Kenya (Republic of)" [640] = "Tanzania (United Republic of)" [641] = "Uganda (Republic of)" [642] = "Burundi (Republic of)" [643] = "Mozambique (Republic of)" [645] = "Zambia (Republic of)" [646] = "Madagascar (Republic of)" [647] = "Reunion (French Department of)" [648] = "Zimbabwe (Republic of)" [649] = "Namibia (Republic of)" [650] = "Malawi " [651] = "Lesotho (Kingdom of)" [652] = "Botswana (Republic of)" [653] = "Swaziland (Kingdom of)" [654] = "Comoros (Union of the)" [655] = "South Africa (Republic of)" [657] = "Eritrea" [702] = "Belize" [704] = "Guatemala (Republic of)" [706] = "El Salvador (Republic of)" [708] = "Honduras (Republic of)" [710] = "Nicaragua" [712] = "Costa Rica" [714] = "Panama (Republic of)" [716] = "Peru" [722] = "Argentine Republic" [724] = "Brazil (Federative Republic of)" [730] = "Chile" [732] = "Colombia (Republic of)" [734] = "Venezuela (Bolivarian Republic of)" [736] = "Bolivia (Republic of)" [738] = "Guyana" [740] = "Ecuador" [742] = "French Guiana (French Department of)" [744] = "Paraguay (Republic of)" [746] = "Suriname (Republic of)" [748] = "Uruguay (Eastern Republic of)" }
gpl-3.0
trappi-stone/Factorio-Stdlib
spec/config/config_spec.lua
1
16396
require 'spec/setup/defines' require 'stdlib/config/config' --[[ the table to be duplicated for all tests. ]]-- _G.config_template = { a = true, b = false, c = "", d = 100, e = {}, f = nil, g = { a = true, b = false, c = "", d = 100, e = {}, f = nil, g = { a = true, b = false, c = "", d = 100, e = {}, f = nil, g = { a = true, b = false, c = "", d = 100, e = {}, f = nil, g = { a = true, b = false, c = "", d = 100, e = {}, f = nil, g = {} } } } } } --[[ the table to be check for corruption. ]]-- _G.config_template2 = table.deepcopy(_G.config_template) describe('Config', function() describe('.new', function() before_each( function() _G.config_table = table.deepcopy(_G.config_template) assert.same(_G.config_template, _G.config_template2) assert.same(_G.config_template, _G.config_table) end) it('Creates a new Config passing different parameters', function() assert.no.errors(function() Config.new({}) end) assert.no.errors(function() Config.new(_G.config_table) end) assert.has.errors(function() Config.new(true) end) assert.has.errors(function() Config.new(false) end) assert.has.errors(function() Config.new(nil) end) assert.has.errors(function() Config.new("") end) assert.has.errors(function() Config.new("{}") end) assert.has.errors(function() Config.new(Config.new({})) end) end) end) describe('.get', function() before_each( function() _G.config_table = table.deepcopy(_G.config_template) assert.same(_G.config_template, _G.config_template2) assert.same(_G.config_template, _G.config_table) end) it('Reserved characters', function() local cfg = Config.new(_G.config_table); local reservedCharacters = '`~!@#$%^&*+=|;:/\\\'",?()[]{}<>' reservedCharacters:gsub(".", function(c) assert.has.errors(function() cfg.get("g" .. c .. "g") end) end) end) it('Round 1/3: Getting data from valid paths without errors', function() local cfg = Config.new(_G.config_table); assert.no.errors(function() cfg.get("a") end) assert.no.errors(function() cfg.get("b") end) assert.no.errors(function() cfg.get("c") end) assert.no.errors(function() cfg.get("d") end) assert.no.errors(function() cfg.get("e") end) assert.no.errors(function() cfg.get("f") end) assert.no.errors(function() cfg.get("g") end) assert.no.errors(function() cfg.get("g.a") end) assert.no.errors(function() cfg.get("g.g.a") end) assert.no.errors(function() cfg.get("g.g.g.a") end) assert.no.errors(function() cfg.get("g.g.g.g.a") end) end) it('Round 2/3: Verifying data from valid paths', function() local cfg = Config.new(_G.config_table); assert.same(_G.config_template.a, cfg.get("a")) assert.same(_G.config_template.b, cfg.get("b")) assert.same(_G.config_template.c, cfg.get("c")) assert.same(_G.config_template.d, cfg.get("d")) assert.same(_G.config_template.e, cfg.get("e")) assert.same(_G.config_template.f, cfg.get("f")) assert.same(_G.config_template.g, cfg.get("g")) assert.same(_G.config_template.g.a, cfg.get("g.a")) assert.same(_G.config_template.g.g.a, cfg.get("g.g.a")) assert.same(_G.config_template.g.g.g.a, cfg.get("g.g.g.a")) assert.same(_G.config_template.g.g.g.g.a, cfg.get("g.g.g.g.a")) end) it('Round 3/3: Getting data from invalid paths', function() local cfg = Config.new(_G.config_table); assert.has.errors(function() cfg.get(true) end) assert.has.errors(function() cfg.get(false) end) assert.has.errors(function() cfg.get(nil) end) assert.has.errors(function() cfg.get({}) end) assert.has.errors(function() cfg.get("") end) assert.no.errors(function() cfg.get("a.a") end) assert.no.errors(function() cfg.get("b.a") end) assert.no.errors(function() cfg.get("c.a") end) assert.no.errors(function() cfg.get("d.a") end) assert.no.errors(function() cfg.get("e.a") end) assert.no.errors(function() cfg.get("f.a") end) assert.no.errors(function() cfg.get("g.z") end) assert.same(nil, cfg.get("a.a")) assert.same(nil, cfg.get("b.a")) assert.same(nil, cfg.get("c.a")) assert.same(nil, cfg.get("d.a")) assert.same(nil, cfg.get("e.a")) assert.same(nil, cfg.get("f.a")) assert.same(nil, cfg.get("g.z")) end) end) describe('.set', function() before_each( function() _G.config_table = table.deepcopy(_G.config_template) assert.same(_G.config_template, _G.config_template2) assert.same(_G.config_template, _G.config_table) end) it('Reserved characters', function() local cfg = Config.new(_G.config_table); local reservedCharacters = '`~!@#$%^&*+=|;:/\\\'",?()[]{}<>' reservedCharacters:gsub(".", function(c) assert.has.errors(function() cfg.set("g" .. c .. "g") end) end) end) it('Round 1/3: Setting data from valid paths without errors', function() local cfg = Config.new(_G.config_table); assert.no.errors(function() cfg.set("g.g.g.g.a", 1337) end) assert.no.errors(function() cfg.set("g.g.g.a", 1337) end) assert.no.errors(function() cfg.set("g.g.a", 1337) end) assert.no.errors(function() cfg.set("g.a", 1337) end) assert.no.errors(function() cfg.set("g.g", 1337) end) assert.no.errors(function() cfg.set("g", 1337) end) end) it('Round 2/3: Verifying data from valid paths', function() local cfg = Config.new(_G.config_table); local tempNum = 1000 tempNum = tempNum + 1 assert.same(1, cfg.set("a", tempNum)) assert.same(tempNum, _G.config_table.a) tempNum = tempNum + 1 assert.same(1, cfg.set("b", tempNum)) assert.same(tempNum, _G.config_table.b) tempNum = tempNum + 1 assert.same(1, cfg.set("c", tempNum)) assert.same(tempNum, _G.config_table.c) tempNum = tempNum + 1 assert.same(1, cfg.set("d", tempNum)) assert.same(tempNum, _G.config_table.d) tempNum = tempNum + 1 assert.same(1, cfg.set("e", tempNum)) assert.same(tempNum, _G.config_table.e) tempNum = tempNum + 1 assert.same(1, cfg.set("f", tempNum)) assert.same(tempNum, _G.config_table.f) tempNum = tempNum + 1 assert.same(1, cfg.set("g", tempNum)) assert.same(tempNum, _G.config_table.g) assert.same(1, cfg.set("g.a", nil)) assert.same(nil, _G.config_table.g.a) tempNum = tempNum + 1 assert.same(1, cfg.set("g.g.a", tempNum)) assert.same(tempNum, _G.config_table.g.g.a) tempNum = tempNum + 1 assert.same(1, cfg.set("g.g.g.a", tempNum)) assert.same(tempNum, _G.config_table.g.g.g.a) tempNum = tempNum + 1 assert.same(1, cfg.set("g.g.g.g.a", tempNum)) assert.same(tempNum, _G.config_table.g.g.g.g.a) end) it('Round 3/3: Setting data from invalid paths', function() local cfg = Config.new(_G.config_table); local config_table2 = table.deepcopy(_G.config_template) assert.has.errors(function() cfg.set(true) end) assert.has.errors(function() cfg.set(false) end) assert.has.errors(function() cfg.set(nil) end) assert.has.errors(function() cfg.set({}) end) assert.has.errors(function() cfg.set("") end) config_table2.a={a=1337} assert.no.errors(function() cfg.set("a.a", 1337) end) assert.same(config_table2, _G.config_table) config_table2.b={a=1337} assert.no.errors(function() cfg.set("b.a", 1337) end) assert.same(config_table2, _G.config_table) config_table2.c={a=1337} assert.no.errors(function() cfg.set("c.a", 1337) end) assert.same(config_table2, _G.config_table) config_table2.d={a=1337} assert.no.errors(function() cfg.set("d.a", 1337) end) assert.same(config_table2, _G.config_table) config_table2.e={a=1337} assert.no.errors(function() cfg.set("e.a", 1337) end) assert.same(config_table2, _G.config_table) config_table2.f={a=1337} assert.no.errors(function() cfg.set("f.a", 1337) end) assert.same(config_table2, _G.config_table) config_table2.g.z=1337 assert.no.errors(function() cfg.set("g.z", 1337) end) assert.same(config_table2, _G.config_table) end) end) describe('.delete', function() before_each( function() _G.config_table = table.deepcopy(_G.config_template) assert.same(_G.config_template, _G.config_template2) assert.same(_G.config_template, _G.config_table) end) it('Reserved characters', function() local cfg = Config.new(_G.config_table); local reservedCharacters = '`~!@#$%^&*+=|;:/\\\'",?()[]{}<>' reservedCharacters:gsub(".", function(c) assert.has.errors(function() cfg.delete("g" .. c .. "g") end) end) end) it('Round 1/3: Deleting data from valid paths without errors', function() local cfg = Config.new(_G.config_table); assert.no.errors(function() cfg.delete("g.g.g.g.g") end) assert.no.errors(function() cfg.delete("g.g.g.a") end) assert.no.errors(function() cfg.delete("g.g.a") end) assert.no.errors(function() cfg.delete("g.a") end) assert.no.errors(function() cfg.delete("a") end) assert.no.errors(function() cfg.delete("b") end) assert.no.errors(function() cfg.delete("c") end) assert.no.errors(function() cfg.delete("d") end) assert.no.errors(function() cfg.delete("e") end) assert.no.errors(function() cfg.delete("f") end) assert.no.errors(function() cfg.delete("g") end) end) it('Round 2/3: Verifying data from valid paths', function() local cfg = Config.new(_G.config_table); assert.same(1, cfg.delete("g.g.g.g.g")) assert.same(nil, _G.config_table.g.g.g.g.g) ---------------------------------------- assert.same(1, cfg.delete("g.g.g.a")) assert.same(nil, _G.config_table.g.g.g.a) assert.same(_G.config_template.g.g.g.b, _G.config_table.g.g.g.b) --Make sure we didn't delete too much assert.same(1, cfg.delete("g.g.a")) assert.same(nil, _G.config_table.g.g.a) assert.same(1, cfg.delete("g.a")) assert.same(nil, _G.config_table.g.a) assert.same(1, cfg.delete("a")) assert.same(nil, _G.config_table.a) assert.same(1, cfg.delete("b")) assert.same(nil, _G.config_table.b) assert.same(1, cfg.delete("c")) assert.same(nil, _G.config_table.c) assert.same(1, cfg.delete("d")) assert.same(nil, _G.config_table.d) assert.same(1, cfg.delete("e")) assert.same(nil, _G.config_table.e) assert.same(0, cfg.delete("f")) assert.same(nil, _G.config_table.f) assert.same(1, cfg.delete("g")) assert.same(nil, _G.config_table.g) end) it('Round 3/3: Deleting data from invalid paths', function() local cfg = Config.new(_G.config_table); assert.has.errors(function() cfg.delete(true) end) assert.has.errors(function() cfg.delete(false) end) assert.has.errors(function() cfg.delete(nil) end) assert.has.errors(function() cfg.delete({}) end) assert.has.errors(function() cfg.delete("") end) assert.same(0, cfg.delete("a.a")) assert.same(_G.config_template, _G.config_table) assert.same(0, cfg.delete("b.a")) assert.same(_G.config_template, _G.config_table) assert.same(0, cfg.delete("c.a")) assert.same(_G.config_template, _G.config_table) assert.same(0, cfg.delete("d.a")) assert.same(_G.config_template, _G.config_table) assert.same(0, cfg.delete("e.a")) assert.same(_G.config_template, _G.config_table) assert.same(0, cfg.delete("f.a")) assert.same(_G.config_template, _G.config_table) assert.same(0, cfg.delete("g.z")) assert.same(_G.config_template, _G.config_table) end) end) describe('.is_set', function() before_each( function() _G.config_table = table.deepcopy(_G.config_template) assert.same(_G.config_template, _G.config_template2) assert.same(_G.config_template, _G.config_table) end) it('Reserved characters', function() local cfg = Config.new(_G.config_table); local reservedCharacters = '`~!@#$%^&*+=|;:/\\\'",?()[]{}<>' reservedCharacters:gsub(".", function(c) assert.has.errors(function() cfg.is_set("g" .. c .. "g") end) end) end) it('Round 1/3: is_set from valid paths without errors?', function() local cfg = Config.new(_G.config_table); assert.no.errors(function() cfg.is_set("a") end) assert.no.errors(function() cfg.is_set("b") end) assert.no.errors(function() cfg.is_set("c") end) assert.no.errors(function() cfg.is_set("d") end) assert.no.errors(function() cfg.is_set("e") end) assert.no.errors(function() cfg.is_set("f") end) assert.no.errors(function() cfg.is_set("g") end) assert.no.errors(function() cfg.is_set("g.a") end) assert.no.errors(function() cfg.is_set("g.g.a") end) assert.no.errors(function() cfg.is_set("g.g.g.a") end) assert.no.errors(function() cfg.is_set("g.g.g.g.a") end) end) it('Round 2/3: Verifying is_set from valid paths', function() local cfg = Config.new(_G.config_table); assert.is_true(cfg.is_set("a")) assert.is_true(cfg.is_set("b")) assert.is_true(cfg.is_set("c")) assert.is_true(cfg.is_set("d")) assert.is_true(cfg.is_set("e")) assert.is_false(cfg.is_set("f")) assert.is_true(cfg.is_set("g")) assert.is_true(cfg.is_set("g.a")) assert.is_true(cfg.is_set("g.g.a")) assert.is_true(cfg.is_set("g.g.g.a")) assert.is_true(cfg.is_set("g.g.g.g.a")) end) it('Round 3/3: Verifying is_set from invalid paths', function() local cfg = Config.new(_G.config_table); assert.is_false(cfg.is_set("a.a")) assert.is_false(cfg.is_set("b.a")) assert.is_false(cfg.is_set("c.a")) assert.is_false(cfg.is_set("d.a")) assert.is_false(cfg.is_set("e.a")) assert.is_false(cfg.is_set("f.a")) assert.is_false(cfg.is_set("g.z")) end) end) end)
isc
wxguidesigner/wxGUIDesigner
build/premake/4.3/premake4.lua
2
2754
-- -- Premake 4.x build configuration script -- -- -- Define the project. Put the release configuration first so it will be the -- default when folks build using the makefile. That way they don't have to -- worry about the /scripts argument and all that. -- solution "Premake4" configurations { "Release", "Debug" } location ( _OPTIONS["to"] ) project "Premake4" targetname "premake4" language "C" kind "ConsoleApp" flags { "No64BitChecks", "ExtraWarnings", "StaticRuntime" } includedirs { "src/host/lua-5.1.4/src" } files { "*.txt", "**.lua", "src/**.h", "src/**.c", } excludes { "src/premake.lua", "src/host/lua-5.1.4/src/lua.c", "src/host/lua-5.1.4/src/luac.c", "src/host/lua-5.1.4/src/print.c", "src/host/lua-5.1.4/**.lua", "src/host/lua-5.1.4/etc/*.c" } configuration "Debug" targetdir "bin/debug" defines "_DEBUG" flags { "Symbols" } configuration "Release" targetdir "bin/release" defines "NDEBUG" flags { "OptimizeSize" } configuration "vs*" defines { "_CRT_SECURE_NO_WARNINGS" } configuration "linux" defines { "LUA_USE_POSIX", "LUA_USE_DLOPEN" } links { "m", "dl" } configuration "macosx" defines { "LUA_USE_MACOSX" } configuration { "macosx", "gmake" } buildoptions { "-mmacosx-version-min=10.1" } linkoptions { "-lstdc++-static", "-mmacosx-version-min=10.1" } configuration { "not windows", "not solaris" } linkoptions { "-rdynamic" } configuration { "solaris" } linkoptions { "-Wl,--export-dynamic" } -- -- A more thorough cleanup. -- if _ACTION == "clean" then os.rmdir("bin") os.rmdir("build") end -- -- Use the --to=path option to control where the project files get generated. I use -- this to create project files for each supported toolset, each in their own folder, -- in preparation for deployment. -- newoption { trigger = "to", value = "path", description = "Set the output location for the generated files" } -- -- Use the embed action to convert all of the Lua scripts into C strings, which -- can then be built into the executable. Always embed the scripts before creating -- a release build. -- dofile("scripts/embed.lua") newaction { trigger = "embed", description = "Embed scripts in scripts.c; required before release builds", execute = doembed } -- -- Use the release action to prepare source and binary packages for a new release. -- This action isn't complete yet; a release still requires some manual work. -- dofile("scripts/release.lua") newaction { trigger = "release", description = "Prepare a new release (incomplete)", execute = dorelease }
gpl-3.0
davidBelanger/nn
View.lua
41
2232
local View, parent = torch.class('nn.View', 'nn.Module') function View:__init(...) parent.__init(self) if select('#', ...) == 1 and torch.typename(select(1, ...)) == 'torch.LongStorage' then self.size = select(1, ...) else self.size = torch.LongStorage({...}) end self.numElements = 1 local inferdim = false for i = 1,#self.size do local szi = self.size[i] if szi >= 0 then self.numElements = self.numElements * self.size[i] else assert(szi == -1, 'size should be positive or -1') assert(not inferdim, 'only one dimension can be at -1') inferdim = true end end self.output = nil self.gradInput = nil self.numInputDims = nil end function View:setNumInputDims(numInputDims) self.numInputDims = numInputDims return self end local function batchsize(input, size, numInputDims, numElements) local ind = input:nDimension() local isz = input:size() local maxdim = numInputDims and numInputDims or ind local ine = 1 for i=ind,ind-maxdim+1,-1 do ine = ine * isz[i] end if ine % numElements ~= 0 then error(string.format( 'input view (%s) and desired view (%s) do not match', table.concat(input:size():totable(), 'x'), table.concat(size:totable(), 'x'))) end -- the remainder is either the batch... local bsz = ine / numElements -- ... or the missing size dim for i=1,size:size() do if size[i] == -1 then bsz = 1 break end end -- for dim over maxdim, it is definitively the batch for i=ind-maxdim,1,-1 do bsz = bsz * isz[i] end -- special card if bsz == 1 and (not numInputDims or input:nDimension() <= numInputDims) then return end return bsz end function View:updateOutput(input) local bsz = batchsize(input, self.size, self.numInputDims, self.numElements) if bsz then self.output = input:view(bsz, table.unpack(self.size:totable())) else self.output = input:view(self.size) end return self.output end function View:updateGradInput(input, gradOutput) self.gradInput = gradOutput:view(input:size()) return self.gradInput end
bsd-3-clause
miralireza2/gpf
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
Mistranger/OpenRA
mods/cnc/maps/nod07a/nod07a-AI.lua
7
6191
--[[ Copyright 2007-2017 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackPaths = { { AttackPath1 }, { AttackPath2 } } GDIBase = { GDICYard, GDIPyle, GDIWeap, GDIHQ, GDIProc, GDINuke1, GDINuke2, GDINuke3, GDIBuilding1, GDIBuilding2, GDIBuilding3, GDIBuilding4, GDIBuilding5, GDIBuilding6, GDIBuilding7, GDIBuilding8 } InfantryAttackGroup = { } InfantryGroupSize = 4 InfantryProductionCooldown = DateTime.Minutes(3) InfantryProductionTypes = { "e1", "e1", "e2" } HarvesterProductionType = { "harv" } VehicleAttackGroup = { } VehicleGroupSize = 4 VehicleProductionCooldown = DateTime.Minutes(4) VehicleProductionTypes = { "jeep", "jeep", "mtnk", "mtnk", "mtnk" } StartingCash = 4000 BaseProc = { type = "proc", pos = CPos.New(22, 51), cost = 1500, exists = true } BaseNuke1 = { type = "nuke", pos = CPos.New(16, 56), cost = 500, exists = true } BaseNuke2 = { type = "nuke", pos = CPos.New(18, 57), cost = 500, exists = true } BaseNuke3 = { type = "nuke", pos = CPos.New(27, 51), cost = 500, exists = true } InfantryProduction = { type = "pyle", pos = CPos.New(18, 54), cost = 500, exists = true } VehicleProduction = { type = "weap", pos = CPos.New(27, 55), cost = 2000, exists = true } BaseBuildings = { BaseProc, BaseNuke1, BaseNuke2, BaseNuke3, InfantryProduction, VehicleProduction } BuildBase = function(cyard) Utils.Do(BaseBuildings, function(building) if not building.exists and not cyardIsBuilding then BuildBuilding(building, cyard) return end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end BuildBuilding = function(building, cyard) cyardIsBuilding = true Trigger.AfterDelay(Actor.BuildTime(building.type), function() cyardIsBuilding = false if cyard.IsDead or cyard.Owner ~= enemy then return end local actor = Actor.Create(building.type, true, { Owner = enemy, Location = building.pos }) enemy.Cash = enemy.Cash - building.cost building.exists = true if actor.Type == 'pyle' or actor.Type == 'hand' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(actor) end) elseif actor.Type == 'weap' or actor.Type == 'afld' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(actor) end) end Trigger.OnKilled(actor, function() building.exists = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end) end CheckForHarvester = function() local harv = enemy.GetActorsByType("harv") return #harv > 0 end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function(enemy) local lazyUnits = enemy.GetGroundAttackers() Utils.Do(lazyUnits, function(unit) IdleHunt(unit) end) end ProduceHarvester = function(building) if not buildingHarvester then buildingHarvester = true building.Build(HarvesterProductionType, function() buildingHarvester = false end) end end ProduceInfantry = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(InfantryProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) InfantryAttackGroup[#InfantryAttackGroup + 1] = unit[1] if #InfantryAttackGroup >= InfantryGroupSize then SendUnits(InfantryAttackGroup, Path) InfantryAttackGroup = { } Trigger.AfterDelay(InfantryProductionCooldown, function() ProduceInfantry(building) end) else Trigger.AfterDelay(delay, function() ProduceInfantry(building) end) end end) end ProduceVehicle = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then ProduceHarvester(building) Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(VehicleProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) VehicleAttackGroup[#VehicleAttackGroup + 1] = unit[1] if #VehicleAttackGroup >= VehicleGroupSize then SendUnits(VehicleAttackGroup, Path) VehicleAttackGroup = { } Trigger.AfterDelay(VehicleProductionCooldown, function() ProduceVehicle(building) end) else Trigger.AfterDelay(delay, function() ProduceVehicle(building) end) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end) end StartAI = function(cyard) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) enemy.Cash = StartingCash BuildBase(cyard) end Trigger.OnAllKilledOrCaptured(GDIBase, function() IdlingUnits(enemy) end) Trigger.OnKilled(GDIProc, function(building) BaseProc.exists = false end) Trigger.OnKilled(GDINuke1, function(building) BaseNuke1.exists = false end) Trigger.OnKilled(GDINuke2, function(building) BaseNuke2.exists = false end) Trigger.OnKilled(GDINuke3, function(building) BaseNuke3.exists = false end) Trigger.OnKilled(GDIPyle, function(building) InfantryProduction.exists = false end) Trigger.OnKilled(GDIWeap, function(building) VehicleProduction.exists = false end)
gpl-3.0
gajop/Zero-K
units/armraven.lua
2
6208
unitDef = { unitname = [[armraven]], name = [[Catapult]], description = [[Heavy Saturation Artillery Strider]], acceleration = 0.1092, brakeRate = 0.1942, buildCostEnergy = 3500, buildCostMetal = 3500, builder = false, buildPic = [[ARMRAVEN.png]], buildTime = 3500, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[65 65 65]], collisionVolumeTest = 1, collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { description_de = [[Schwerer Raketen-Artillerie Läufer]], description_fr = [[Mechwarrior Lance-Roquette Lourd]], description_pl = [[Ciężka Artyleria Rakietowa]], helptext = [[The Catapult is an MLRS strider. It can launch a volley of rockets that guarantees the destruction of almost anything in the target area, then quickly retreat behind friendly forces.]], helptext_de = [[Das Catapult ist ein Läufer mit Mehrfachraketenwerfer-Artilleriesystem. Es kann eine Salve von Raketen starten, was die Zerstörung von fast allem im Zielgebiet garantieren kann. Infolgedessen kann es sich schnell in freundliches Gebiet hinter den Fronteinheiten zurückziehen.]], helptext_fr = [[Le Catapult est le plus fragile des Mechwarriors. Il est cependant trcs rapide et tire un nombre incalculable de roquettes r grande distance grâce r ses deux batteries lance missiles embarquées. Une seule salve peut tapisser une large zone, et rares sont les survivant.]], helptext_pl = [[Catapult wystrzeliwuje seriÄ?rakiet, która jest w stanie zniszczyÄ?prawie wszystko w wyznaczonym obszarze. Podczas przeładowywania może schowaÄ?siÄ?wśród innych jednostek.]], }, explodeAs = [[ATOMIC_BLASTSML]], footprintX = 4, footprintZ = 4, iconType = [[t3arty]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, mass = 659, maxDamage = 4000, maxSlope = 36, maxVelocity = 1.8, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[KBOT4]], moveState = 0, noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB]], objectName = [[catapult.s3o]], script = [[armraven.cob]], seismicSignature = 4, selfDestructAs = [[ATOMIC_BLASTSML]], side = [[CORE]], sightDistance = 660, smoothAnim = true, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 36, turnRate = 990, upright = true, workerTime = 0, weapons = { { def = [[ROCKET]], badTargetCategory = [[GUNSHIP]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]], }, }, weaponDefs = { ROCKET = { name = [[Long-Range Rocket Battery]], areaOfEffect = 128, avoidFeature = false, avoidGround = false, burst = 20, burstrate = 0.1, cegTag = [[RAVENTRAIL]], craterBoost = 1, craterMult = 2, customParams = { light_camera_height = 2500, light_color = [[0.35 0.17 0.04]], light_radius = 400, }, damage = { default = 220.5, planes = 220.5, subs = 11, }, dance = 20, edgeEffectiveness = 0.5, explosionGenerator = [[custom:MEDMISSILE_EXPLOSION]], fireStarter = 100, flightTime = 8, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[hobbes.s3o]], noSelfDamage = true, projectiles = 2, range = 1450, reloadtime = 30, smokeTrail = false, soundHit = [[weapon/missile/rapid_rocket_hit]], soundHitVolume = 5, soundStart = [[weapon/missile/rapid_rocket_fire]], soundStartVolume = 5, startVelocity = 100, tolerance = 512, trajectoryHeight = 1, turnRate = 2500, turret = true, weaponAcceleration = 100, weaponTimer = 6, weaponType = [[MissileLauncher]], weaponVelocity = 250, wobble = 7000, }, }, featureDefs = { DEAD = { description = [[Wreckage - Catapult]], blocking = true, category = [[corpses]], damage = 4000, energy = 0, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, height = [[40]], hitdensity = [[100]], metal = 1400, object = [[catapult_wreck.s3o]], reclaimable = true, reclaimTime = 1400, }, HEAP = { description = [[Debris - Catapult]], blocking = false, category = [[heaps]], damage = 4000, energy = 0, footprintX = 3, footprintZ = 3, height = [[4]], hitdensity = [[100]], metal = 700, object = [[debris3x3b.s3o]], reclaimable = true, reclaimTime = 700, }, }, } return lowerkeys({ armraven = unitDef })
gpl-2.0
KayMD/Illarion-Content
content/_gods/ushara.lua
3
1956
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local class = require('base.class') local baseelder = require("content._gods.baseelder") local common = require('base.common') local M = {} M.Ushara = class( baseelder.BaseElder, function(self, ...) self:_init(...) end ) function M.Ushara:_init(ordinal, elderOrdinal) baseelder.BaseElder._init(self, ordinal, elderOrdinal) -- call the base class constructor self.nameDe = "Ushara" self.nameEn = "Ushara" self.descriptionDe = "die Göttin der Erde" self.descriptionEn = "Goddess of earth" self.devotionItems = { {id = 2552, number = 1}, -- pure earth {id = 207, number = 1}, -- battle staff {id = 55, number = 1}, -- green robe } self.sacrificeItems = { -- array of tables defining groups of items for sacrificing { -- FIXME id_set = common.setFromList({ -- set of item IDs 2552, -- pure earth 2782, -- wand of earth }), minimal_quality = 0, -- int in 1..9 - if present, item quality has to be greater or equal minimal_durability = 0, -- int in 0..99 - if present, item durability has to be greater or equal value_multiplier = 1, -- float -- the monetary value gets multiplied by this }, } end return M
agpl-3.0
KayMD/Illarion-Content
quest/hummi_olaficht_605.lua
3
3346
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (605, 'quest.hummi_olaficht_605'); local common = require("base.common") local M = {} local GERMAN = Player.german local ENGLISH = Player.english -- Insert the quest title here, in both languages local Title = {} Title[GERMAN] = "Finde Frizza in Cadomyr" Title[ENGLISH] = "Find Frizza in Cadomyr" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do local Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Finde Frizza beim Marktplatz in Cadomyr and sprich mit ihr." Description[ENGLISH][1] = "Find Frizza at the market in Cadomyr and talk to her." Description[GERMAN][2] = "Da kannst nun mit Frizza sprechen. Frage nach 'Hilfe' wenn du nicht weißt, wonach du fragen sollst!\nDu kannst auch zurück zu Hummi gehen, um deine Belohnung abzuholen und später nochmals vorbei kommen. Frizza hat nämlich auch mindestens eine Aufgabe für dich." Description[ENGLISH][2] = "You can talk with Frizza now. Ask for 'help' if you do not know what to say!\nYou can also go back to Hummi to collect your reward and come back later. Frizza also has at least one task for you." Description[GERMAN][3] = "Hast du bereits nach den beiden anderen NPCs die Hummi erwähnt hat gefragt und sie auch besucht? Elesil and Iradona? Wenn nein, dann solltest du das jetzt tun. Wenn ja, dann hat Hummi einen zusätzlichen Auftrag für dich." Description[ENGLISH][3] = "Have you already asked for and visited the two other NPCs, Elesil and Iradona, that Hummi mentions? If not, you should do it now. If you have already visited them, Hummi has an additional task for you." -- Insert the position of the quest start here (probably the position of an NPC or item) local Start = {681, 311, 0} -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there local QuestTarget = {} QuestTarget[1] = {position(117, 599, 0)} -- Frizza QuestTarget[2] = {position(681, 311, 0)} -- Hummi -- Insert the quest status which is reached at the end of the quest local FINAL_QUEST_STATUS = 3 function M.QuestTitle(user) return common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function M.QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return common.GetNLS(user, german, english) end function M.QuestStart() return Start end function M.QuestTargets(user, status) return QuestTarget[status] end function M.QuestFinalStatus() return FINAL_QUEST_STATUS end return M
agpl-3.0
casseveritt/premake
tests/test_string.lua
84
1550
-- -- tests/test_string.lua -- Automated test suite for the new string functions. -- Copyright (c) 2008 Jason Perkins and the Premake project -- T.string = { } -- -- string.endswith() tests -- function T.string.endswith_ReturnsTrue_OnMatch() test.istrue(string.endswith("Abcdef", "def")) end function T.string.endswith_ReturnsFalse_OnMismatch() test.isfalse(string.endswith("Abcedf", "efg")) end function T.string.endswith_ReturnsFalse_OnLongerNeedle() test.isfalse(string.endswith("Abc", "Abcdef")) end function T.string.endswith_ReturnsFalse_OnNilHaystack() test.isfalse(string.endswith(nil, "ghi")) end function T.string.endswith_ReturnsFalse_OnNilNeedle() test.isfalse(string.endswith("Abc", nil)) end function T.string.endswith_ReturnsTrue_OnExactMatch() test.istrue(string.endswith("/", "/")) end -- -- string.explode() tests -- function T.string.explode_ReturnsParts_OnValidCall() test.isequal({"aaa","bbb","ccc"}, string.explode("aaa/bbb/ccc", "/", true)) end -- -- string.startswith() tests -- function T.string.startswith_OnMatch() test.istrue(string.startswith("Abcdef", "Abc")) end function T.string.startswith_OnMismatch() test.isfalse(string.startswith("Abcdef", "ghi")) end function T.string.startswith_OnLongerNeedle() test.isfalse(string.startswith("Abc", "Abcdef")) end function T.string.startswith_OnEmptyHaystack() test.isfalse(string.startswith("", "Abc")) end function T.string.startswith_OnEmptyNeedle() test.istrue(string.startswith("Abcdef", "")) end
bsd-3-clause
KayMD/Illarion-Content
craft/final/roasting.lua
3
2288
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local crafts = require("craft.base.crafts") local M = {} local roasting = crafts.Craft:new{ craftEN = "Roasting", craftDE = "Braten", handTool = 2495, leadSkill = Character.cookingAndBaking, sfx = 7, sfxDuration = 27, } roasting:addTool(304) -- smoke oven roasting:addTool(305) -- smoke oven local product local catId catId = roasting:addCategory("Meat", "Fleisch") -- Ham product = roasting:addProduct(catId, 306, 1) product:addIngredient(307) -- pork -- Smoked chicken product = roasting:addProduct(catId, 3709, 1) product:addIngredient(1151) -- chicken meat -- Smoked rabbit product = roasting:addProduct(catId, 3710, 1) product:addIngredient(553) -- rabbit meat -- Grilled lamb product = roasting:addProduct(catId, 3713, 1) product:addIngredient(2934) -- lamb meat -- Grilled venison product = roasting:addProduct(catId, 3714, 1) product:addIngredient(552) -- deer meat -- Grilled steak product = roasting:addProduct(catId, 3606, 1) product:addIngredient(2940) -- raw steak catId = roasting:addCategory("Fish", "Fisch") -- Smoked rose fish product = roasting:addProduct(catId, 3915, 1) product:addIngredient(1210) -- rose fish -- Smoked salmon product = roasting:addProduct(catId, 3916, 1) product:addIngredient(355) -- salmon -- Smoked horse mackerel product = roasting:addProduct(catId, 3914, 1) product:addIngredient(1209) -- horse mackerel -- Smoked trout product = roasting:addProduct(catId, 455, 1) product:addIngredient(73) -- trout M.roasting = roasting return M
agpl-3.0
gajop/Zero-K
scripts/cordoom.lua
7
5402
include "constants.lua" --pieces local base = piece "Base" local shellbase = piece "ShellBase" local shell_1 = piece "Shell_1" local shell_2 = piece "Shell_2" -- guns local cannonbase = piece "CannonBase" local cannon = piece "Cannon" local flare1 = piece "flare1" local heatraybase = piece "HeatrayBase" local heatray = piece "Heatray" local flare2 = piece "flare2" local flare3 = piece "flare3" local spGetUnitRulesParam = Spring.GetUnitRulesParam local smokePiece = { shell_1, shell_2, cannonbase, heatray } --variables local heat = false local on = false --signals local aim = 2 local aim2 = 4 local open = 8 local close = 16 local closeInterrupt = 32 local mainPitch = 0.5 local mainHeading = 0.8 local shellSpeed = 0.7 local position = 0 local tauOn16 = tau/16 local tauOn8 = tau/8 local function Open() Signal(close) --kill the closing animation if it is in process SetSignalMask(open) --set the signal to kill the opening animation while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end Spring.SetUnitArmored(unitID,false) -- Open Main Shell Move(shell_1, x_axis, 0, shellSpeed) Move(shell_2, x_axis, 0, shellSpeed) WaitForMove(shell_1, x_axis) while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end -- Unsquish heatray Move(shellbase, y_axis, 0, 3) Move(heatraybase, y_axis, 0, 1.5) WaitForMove(shellbase, y_axis) WaitForMove(heatraybase, y_axis) while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end -- Unstow Guns Turn(cannonbase, x_axis, 0, mainPitch) Move(heatray,z_axis, 0, 4) WaitForTurn(cannonbase, x_axis) WaitForMove(heatray, z_axis) if spGetUnitRulesParam(unitID, "lowpower") == 1 then return end -- Ready Cannon Head Move(cannon, z_axis, 0, 10) WaitForMove(cannon, z_axis) while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end on = true end local function FinalCloseInterrupt() SetSignalMask(closeInterrupt) while true do if spGetUnitRulesParam(unitID, "lowpower") == 1 then Move(shell_1,x_axis, 15, 0.000000001) Move(shell_2,x_axis, -15, 0.000000001) StartThread(Close) return end Sleep(500) end end --closing animation of the factory function Close() Signal(aim) Signal(aim2) Signal(closeInterrupt) Signal(open) --kill the opening animation if it is in process SetSignalMask(close) --set the signal to kill the closing animation while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end -- Prepare both guns to be stowed. Move(cannon, z_axis, -10, 10) Turn(heatray, x_axis, 0, 2) WaitForTurn(heatray, x_axis) WaitForMove(cannon, z_axis) while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end -- Stow Guns Turn(cannonbase, x_axis, 1.57, mainPitch) Move(heatray,z_axis, -10, 4) WaitForTurn(cannonbase, x_axis) WaitForMove(heatray, z_axis) while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end -- Squish Heatray area Turn(shellbase, y_axis, tauOn8*position, mainHeading/4) Turn(heatraybase, y_axis, tauOn8*position, 1) WaitForTurn(shellbase, y_axis) WaitForTurn(heatraybase, y_axis) while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end Move(shellbase, y_axis, -12.6, 3) Move(heatraybase, y_axis, -6.3, 1.5) WaitForMove(shellbase,y_axis) WaitForMove(heatraybase,y_axis) while spGetUnitRulesParam(unitID, "lowpower") == 1 do Sleep(500) end -- Close Main Shell Move(shell_1,x_axis, 5, shellSpeed) Move(shell_2,x_axis, -5, shellSpeed) StartThread(FinalCloseInterrupt) WaitForMove(shell_1,x_axis) WaitForMove(shell_2,x_axis) Signal(closeInterrupt) -- Set Armour Spring.SetUnitArmored(unitID,true) end function script.Activate () StartThread(Open) end function script.Deactivate () on = false StartThread(Close) end function script.Create() StartThread(SmokeUnit, smokePiece) end local aimFromSet = {cannonbase, heatraybase} function script.AimFromWeapon(num) return aimFromSet[num] end function script.AimWeapon(num, heading, pitch) if (not on) or (spGetUnitRulesParam(unitID, "lowpower") == 1) then return false end if num == 1 then Signal(aim) SetSignalMask(aim) position = math.floor((heading + tauOn16)/tauOn8)%8 Turn(shellbase, y_axis, heading, mainHeading) Turn(cannonbase, x_axis, -pitch, mainPitch) WaitForTurn (shellbase, y_axis) WaitForTurn (cannonbase, x_axis) return (spGetUnitRulesParam(unitID, "lowpower") == 0) --checks for sufficient energy in grid elseif num == 2 then Signal(aim2) SetSignalMask(aim2) Turn(heatraybase, y_axis, heading, 3) Turn(heatray, x_axis, -pitch, 2) WaitForTurn (heatraybase, y_axis) WaitForTurn (heatray, x_axis) return (spGetUnitRulesParam(unitID, "lowpower") == 0) end end function script.QueryWeapon(num) if num == 1 then return flare1 elseif num == 2 then if heat then return flare2 else return flare3 end end end function script.FireWeapon(num) if num == 1 then EmitSfx(flare1, 1024) Move(cannon, z_axis, -24) Move(cannon, z_axis, 0, 10) Sleep(20) Hide(flare1) elseif num == 2 then heat = not heat end end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= .25) then return 1 -- corpsetype elseif (severity <= .5) then return 1 -- corpsetype else return 2 -- corpsetype end end
gpl-2.0
gajop/Zero-K
units/armspy.lua
2
6167
unitDef = { unitname = [[armspy]], name = [[Infiltrator]], description = [[Cloaked Scout/Anti-Heavy]], acceleration = 0.3, activateWhenBuilt = true, brakeRate = 0.3, buildCostEnergy = 280, buildCostMetal = 280, buildPic = [[armspy.png]], buildTime = 280, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], cloakCost = 4, cloakCostMoving = 12, corpse = [[DEAD]], customParams = { description_bp = [[Espi?o invisível a radar]], description_de = [[Spion, Anti-Heavy]], description_fi = [[N?kym?t?n vakoilija]], description_fr = [[Espion, contre les unités lourdes]], description_pl = [[Szpieg]], helptext = [[The Infiltrator is useful in two ways. Firstly it is an excellent scout, and very difficult to detect. It can penetrate deep into enemy lines. It also has the capacity to shoot a paralyzing bolt that will freeze any one target, good against heavy enemies and enemy infrastructure.]], helptext_bp = [[O Infiltrador é útil de várias formas. Pode ser um batedor invisível e indetectável por radar para espiar o inimigo, ou detona-lo como uma bomba de PEM contra o inimigo.]], helptext_de = [[Der Infiltrator ist für zwei Dinge nützlich. Erstens ist er ein exzellenter Aufklärer und sehr schwer zu entdecken. Er kann sich tief hinter die feindlichen Linien begeben. Außerdem besitzt er die Eigentschaft einen paralysierenden Bolzen abzuschießen, der jedes Ziel einfriert, was gegen schwere Einheiten und feindliche Infrastruktur sehr nützlich ist.]], helptext_fi = [[Tutkassakin n?kym?t?n Infiltrator pystyy piileksim??n vihollisen alueella tulematta havaituksi ker?ten hy?dyllist? informaatiota t?m?n toiminnasta. Laukaisee tuhoutuessaan EMP-pommin.]], helptext_fr = [[L'infiltrator est une unité légère invisible. Il peut typiquement être utilisé comme un éclaireur permettant d'espionner la base enemie sans se faire repérer. Il peut aussi libérer une décharge EMP de très haute puissance pour paralyser une cible unique, utile contre les unités lourdes et l'infrastructure. En cas d'échec le temps de recharge très long signifie la perte certaine de cette unité.]], helptext_pl = [[Infiltrator jest uzyteczny w dwojaki sposób. Przede wszystkim jest doskonalym zwiadowca, który dzieki maskowaniu i mozliwosci wspinania sie po dowolnym terenie jest bardzo trudny do wykrycia. Ponadto moze wystrzelic wiazke EMP, która sparalizuje pojedyncza jednostke lub budynek na dlugi okres czasu.]], }, explodeAs = [[BIG_UNITEX]], fireState = 0, footprintX = 2, footprintZ = 2, iconType = [[walkerscout]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, initCloaked = true, maxDamage = 270, maxSlope = 36, maxVelocity = 2.55, maxWaterDepth = 22, minCloakDistance = 60, movementClass = [[TKBOT3]], moveState = 0, noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK TURRET]], objectName = [[infiltrator.s3o]], script = [[armspy.lua]], seismicSignature = 16, selfDestructAs = [[BIG_UNITEX]], sightDistance = 550, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ChickenTrackPointyShort]], trackWidth = 45, turnRate = 1800, weapons = { { def = [[spy]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]], }, }, weaponDefs = { spy = { name = [[Electro-Stunner]], areaOfEffect = 8, collideFriendly = false, craterBoost = 0, craterMult = 0, customParams = { light_color = [[1.85 1.85 0.45]], light_radius = 300, }, damage = { default = 8000.1, }, duration = 8, explosionGenerator = [[custom:YELLOW_LIGHTNINGPLOSION]], fireStarter = 0, heightMod = 1, impactOnly = true, impulseBoost = 0, impulseFactor = 0, intensity = 12, interceptedByShieldType = 1, paralyzer = true, paralyzeTime = 30, range = 100, reloadtime = 35, rgbColor = [[1 1 0.25]], soundStart = [[weapon/LightningBolt]], soundTrigger = true, targetborder = 1, texture1 = [[lightning]], thickness = 10, tolerance = 10000, turret = true, weaponType = [[LightningCannon]], weaponVelocity = 450, }, }, featureDefs = { DEAD = { description = [[Wreckage - Infiltrator]], blocking = true, damage = 270, energy = 0, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, metal = 112, object = [[Infiltrator_wreck.s3o]], reclaimable = true, reclaimTime = 112, }, HEAP = { description = [[Debris - Infiltrator]], blocking = false, damage = 270, energy = 0, footprintX = 2, footprintZ = 2, metal = 56, object = [[debris2x2a.s3o]], reclaimable = true, reclaimTime = 56, }, }, } return lowerkeys({ armspy = unitDef })
gpl-2.0
Flourish-Team/Flourish
Premake/source/src/base/http.lua
17
1300
-- -- http.lua -- Additions to the http namespace. -- Copyright (c) 2008-2014 Jason Perkins and the Premake project -- if http == nil then return end --- -- Simple progress bar on stdout for curl downloads. --- function http.reportProgress(total, current) local width = 70 local progress = math.floor(current * width / total) if progress == width then io.write(string.rep(' ', width + 2) .. '\r') else io.write('[' .. string.rep('=', progress) .. string.rep(' ', width - progress) .. ']\r') end end --- -- Correctly escape parameters for use in a url. --- function http.escapeUrlParam(param) local url_encodings = { [' '] = '%%20', ['!'] = '%%21', ['"'] = '%%22', ['#'] = '%%23', ['$'] = '%%24', ['&'] = '%%26', ['\''] = '%%27', ['('] = '%%28', [')'] = '%%29', ['*'] = '%%2A', ['+'] = '%%2B', ['-'] = '%%2D', ['.'] = '%%2E', ['/'] = '%%2F', [':'] = '%%3A', [';'] = '%%3B', ['<'] = '%%3C', ['='] = '%%3D', ['>'] = '%%3E', ['?'] = '%%3F', ['@'] = '%%40', ['['] = '%%5B', ['\\'] = '%%5C', [']'] = '%%5D', ['^'] = '%%5E', ['_'] = '%%5F', ['`'] = '%%60' } param = param:gsub('%%', '%%25') for k,v in pairs(url_encodings) do param = param:gsub('%' .. k, v) end return param end
mit
casseveritt/premake
tests/actions/make/test_makesettings.lua
57
1055
-- -- tests/actions/make/test_makesettings.lua -- Tests makesettings lists in generated makefiles. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.make_settings = { } local suite = T.make_settings local make = premake.make local sln, prj, cfg function suite.setup() _ACTION = "gmake" sln = solution("MySolution") configurations { "Debug", "Release" } makesettings { "SOLUTION_LEVEL_SETTINGS" } project("MyProject") makesettings { "PROJECT_LEVEL_SETTINGS" } configuration { "Debug" } makesettings { "DEBUG_LEVEL_SETTINGS" } configuration { "Release" } makesettings { "RELEASE_LEVEL_SETTINGS" } premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) cfg = premake.getconfig(prj, "Debug") end function suite.writesProjectSettings() make.settings(prj, premake.gcc) test.capture [[ SOLUTION_LEVEL_SETTINGS PROJECT_LEVEL_SETTINGS ]] end function suite.writesConfigSettings() make.settings(cfg, premake.gcc) test.capture [[ DEBUG_LEVEL_SETTINGS ]] end
bsd-3-clause
AnsonSmith/kong
kong/cli/utils/utils.lua
13
3172
--[[ Kong CLI utilities - Logging - Luarocks helpers ]] local ansicolors = require "ansicolors" local constants = require "kong.constants" local Object = require "classic" local lpath = require "luarocks.path" local IO = require "kong.tools.io" -- -- Colors -- local colors = {} for _, v in ipairs({"red", "green", "yellow", "blue"}) do colors[v] = function(str) return ansicolors("%{"..v.."}"..str.."%{reset}") end end local function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end -- -- Logging -- local Logger = Object:extend() function Logger:new(silent) self.silent = silent end function Logger:print(str) if not self.silent then print(trim(str)) end end function Logger:info(str) self:print(colors.blue("[INFO] ")..str) end function Logger:success(str) self:print(colors.green("[OK] ")..str) end function Logger:warn(str) self:print(colors.yellow("[WARN] ")..str) end function Logger:error(str) self:print(colors.red("[ERR] ")..str) end function Logger:error_exit(str) self:error(str) os.exit(1) end local logger = Logger() -- -- Luarocks -- local function get_kong_infos() return { name = constants.NAME, version = constants.ROCK_VERSION } end local function get_luarocks_dir() local cfg = require "luarocks.cfg" local search = require "luarocks.search" local infos = get_kong_infos() local tree_map = {} local results = {} for _, tree in ipairs(cfg.rocks_trees) do local rocks_dir = lpath.rocks_dir(tree) tree_map[rocks_dir] = tree search.manifest_search(results, rocks_dir, search.make_query(infos.name:lower(), infos.version)) end local version for k, _ in pairs(results.kong) do version = k end return tree_map[results.kong[version][1].repo] end local function get_luarocks_config_dir() local repo = get_luarocks_dir() local infos = get_kong_infos() return lpath.conf_dir(infos.name:lower(), infos.version, repo) end local function get_luarocks_install_dir() local repo = get_luarocks_dir() local infos = get_kong_infos() return lpath.install_dir(infos.name:lower(), infos.version, repo) end local function get_kong_config_path(args_config) local config_path = args_config -- Use the rock's config if no config at default location if not IO.file_exists(config_path) then logger:warn("No configuration at: "..config_path.." using default config instead.") config_path = IO.path:join(get_luarocks_config_dir(), "kong.yml") end -- Make sure the configuration file really exists if not IO.file_exists(config_path) then logger:warn("No configuration at: "..config_path) logger:error_exit("Could not find a configuration file.") end return config_path end -- Checks if a port is open on localhost -- @param `port` The port to check -- @return `open` True if open, false otherwise local function is_port_open(port) local _, code = IO.os_execute("nc -w 5 -z 127.0.0.1 "..tostring(port)) return code == 0 end return { colors = colors, logger = logger, get_kong_infos = get_kong_infos, get_kong_config_path = get_kong_config_path, get_luarocks_install_dir = get_luarocks_install_dir, is_port_open = is_port_open }
apache-2.0
INPStarfall/Starfall
lua/starfall/sfderma.lua
2
23083
-- Starfall Derma -- This is for easily creating derma ui in the style of the Starfall Editor -- Any derma added should not have anything to do with SF.Editor table apart from design elements e.g. colours, icons -- Starfall Frame local PANEL = {} PANEL.windows = {} function PANEL:Init () self.windows[ #self.windows + 1 ] = self self.lockParent = nil self.lockChildren = {} self.locked = false local frame = self self:ShowCloseButton( false ) self:SetDraggable( true ) self:SetSizable( true ) self:SetScreenLock( true ) self:SetDeleteOnClose( false ) self:MakePopup() self:SetVisible( false ) self:SetMinHeight( 315 ) self.components = {} self._PerformLayout = self.PerformLayout function self:PerformLayout ( ... ) local w, h = self:GetSize() if w < 105 + self.components[ "buttonHolder" ]:GetWide() then w = 105 + self.components[ "buttonHolder" ]:GetWide() end self:SetSize( w, h ) self:_PerformLayout( ... ) end -- Button Holder local buttonHolder = vgui.Create( "DPanel", self ) buttonHolder.buttons = {} buttonHolder.Paint = function () end buttonHolder:SetHeight( 22 ) local spacing = 3 function buttonHolder:PerformLayout ( ... ) local wide = 0 for k, v in pairs( self.buttons ) do wide = wide + v.button:GetWide() + spacing end self:SetWide( wide ) self:SetPos( frame:GetWide() - 5 - self:GetWide(), 5 ) local pos = self:GetWide() + spacing for k, v in pairs( self.buttons ) do pos = pos - spacing - v.button:GetWide() v.button:SetPos( pos, 0 ) end end function buttonHolder:addButton ( name, button ) self.buttons[ #self.buttons + 1 ] = { name = name, button = button } button:PerformLayout() self:PerformLayout() end function buttonHolder:getButton ( buttonName ) for k, v in pairs( self.buttons ) do if v.name == buttonName then return v.button end end end function buttonHolder:removeButton ( button ) if button == nil then return end for k, v in pairs( self.buttons ) do if v.button == button or v.name == button then v.button:Remove() self.buttons[ k ] = nil end end end self:AddComponent( "buttonHolder", buttonHolder ) -- End Button Holder local buttonClose = vgui.Create( "StarfallButton", buttonHolder ) buttonClose:SetText( "Close" ) function buttonClose:DoClick () frame:close() end buttonHolder:addButton( "Close", buttonClose ) local buttonLock = vgui.Create( "StarfallButton", buttonHolder ) buttonLock:SetText( "Unlocked" ) function buttonLock:DoClick () if self.active then self.active = false self:SetText( "Unlocked" ) frame.locked = false else if frame.lockParent then self.active = true self:SetText( "Locked" ) frame.locked = true end end end buttonHolder:addButton( "Lock", buttonLock ) end function PANEL:Think () -- Overwriting default think function, mostly copied from default function local mousex = math.Clamp( gui.MouseX(), 1, ScrW() - 1 ) local mousey = math.Clamp( gui.MouseY(), 1, ScrH() - 1 ) self.Dragged = false self.Resized = false if self.Dragging and not self.locked then self.Dragged = true local x = mousex - self.Dragging[ 1 ] local y = mousey - self.Dragging[ 2 ] -- Lock to screen bounds if screenlock is enabled if self:GetScreenLock() then x = math.Clamp( x, 0, ScrW() - self:GetWide() ) y = math.Clamp( y, 0, ScrH() - self:GetTall() ) end -- Edge snapping local minChildX = ScrW() local minX = 0 for k, v in pairs( self.lockChildren ) do if v.locked then if v:GetPos() < minChildX then minChildX = v:GetPos() minX = v:GetWide() end end end if minChildX > x then minX = 0 end local maxChildX = 0 local maxX = 0 for k, v in pairs( self.lockChildren ) do if v.locked then if v:GetPos() + v:GetWide() > maxChildX then maxChildX = v:GetPos() + v:GetWide() maxX = v:GetWide() end end end if maxChildX < x + self:GetWide() then maxX = 0 end if x < 10 and x > -10 then x = 0 elseif x + self:GetWide() > ScrW() - 10 and x + self:GetWide() < ScrW() + 10 then x = ScrW() - self:GetWide() elseif x < minX + 10 and x > minX - 10 then x = minX elseif x + self:GetWide() > ScrW() - maxX - 10 and x + self:GetWide() < ScrW() - maxX + 10 then x = ScrW() - maxX - self:GetWide() end if y < 10 then y = 0 elseif y + self:GetTall() > ScrH() - 10 then y = ScrH() - self:GetTall() end for k, v in pairs( self.windows ) do if v == self or not v:IsVisible() or table.HasValue( self.lockChildren, v ) and v.locked then goto skip end local vx, vy = v:GetPos() local snapped = false self.lockParent = nil v:removeLockChild( self ) -- Not very easy to read but it works if y >= vy and y <= vy + v:GetTall() or y + self:GetTall() >= vy and y + self:GetTall() <= vy + v:GetTall() or y <= vy and y + self:GetTall() >= vy + v:GetTall() then if x > vx - 10 and x < vx + 10 then x = vx self:lock( v ) snapped = true elseif x > vx + v:GetWide() - 10 and x < vx + v:GetWide() + 10 then x = vx + v:GetWide() self:lock( v ) snapped = true elseif x + self:GetWide() > vx - 10 and x + self:GetWide() < vx + 10 then x = vx - self:GetWide() self:lock( v ) snapped = true elseif x + self:GetWide() > vx + v:GetWide() - 10 and x + self:GetWide() < vx + v:GetWide() + 10 then x = vx + v:GetWide() - self:GetWide() self:lock( v ) snapped = true end end if x >= vx and x <= vx + v:GetWide() or x + self:GetWide() >= vx and x + self:GetWide() <= vx + v:GetWide() or x <= vx and x + self:GetWide() >= vx + v:GetWide() then if y > vy - 10 and y < vy + 10 then y = vy self:lock( v ) snapped = true elseif y > vy + v:GetTall() - 10 and y < vy + v:GetTall() + 10 then y = vy + v:GetTall() self:lock( v ) snapped = true elseif y + self:GetTall() > vy - 10 and y + self:GetTall() < vy + 10 then y = vy - self:GetTall() self:lock( v ) snapped = true elseif y + self:GetTall() > vy + v:GetTall() - 10 and y + self:GetTall() < vy + v:GetTall() + 10 then y = vy + v:GetTall() - self:GetTall() self:lock( v ) snapped = true end end if snapped then break end ::skip:: end local dx, dy = self:GetPos() dx = x - dx dy = y - dy self:SetPos( x, y ) self:moveLockChildren( dx, dy ) end if self.Sizing then self.Resized = true local x = self.Sizing[ 1 ] and mousex - self.Sizing[ 1 ] or self:GetWide() local y = self.Sizing[ 2 ] and mousey - self.Sizing[ 2 ] or self:GetTall() local px, py = self:GetPos() if x < self.m_iMinWidth then x = self.m_iMinWidth elseif x > ScrW() - px and self:GetScreenLock() then x = ScrW() - px end if y < self.m_iMinHeight then y = self.m_iMinHeight elseif y > ScrH() - py and self:GetScreenLock() then y = ScrH() - py end for k, v in pairs( self.windows ) do if v == self or not v:IsVisible() then goto skip end local vx, vy = v:GetPos() -- Not very easy to read but it works if py >= vy and py <= vy + v:GetTall() or py + y >= vy and py + y <= vy + v:GetTall() or py <= vy and py + y >= vy + v:GetTall() then if px + x > vx - 10 and px + x < vx + 10 then x = vx - px elseif px + x > vx + v:GetWide() - 10 and px + x < vx + v:GetWide() + 10 then x = vx + v:GetWide() - px end end if px >= vx and px <= vx + v:GetWide() or px + x >= vx and px + x <= vx + v:GetWide() or px <= vx and px + x >= vx + v:GetWide() then if py + y > vy - 10 and py + y < vy + 10 then y = vy - py elseif py + y > vy + v:GetTall() - 10 and py + y < vy + v:GetTall() + 10 then y = vy + v:GetTall() - py end end ::skip:: end self:SetSize( x, y ) end if self.Hovered and self.m_bSizable and mousex > ( self.x + self:GetWide() - 20 ) and mousey > ( self.y + self:GetTall() - 20 ) then self:SetCursor( "sizenwse" ) elseif self.Hovered and self.m_bSizable and mousex > ( self.x + self:GetWide() - 5 ) then self:SetCursor( "sizewe" ) elseif self.Hovered and self.m_bSizable and mousey > ( self.y + self:GetTall() - 5 ) then self:SetCursor( "sizens" ) elseif self.Hovered and self:GetDraggable() and mousey < ( self.y + 24 ) and not self.locked then self:SetCursor( "sizeall" ) else self:SetCursor( "arrow" ) end -- Don't allow the frame to go higher than 0 if self.y < 0 then self:SetPos( self.x, 0 ) end self:OnThink() self.Dragged = nil self.Resized = nil end function PANEL:OnThink () end function PANEL:OnMousePressed () -- Pretty much copied from default function again if self.m_bSizable then if gui.MouseX() > ( self.x + self:GetWide() - 20 ) and gui.MouseY() > ( self.y + self:GetTall() - 20 ) then self.Sizing = { gui.MouseX() - self:GetWide(), gui.MouseY() - self:GetTall() } self:MouseCapture( true ) return end if gui.MouseX() > ( self.x + self:GetWide() - 5 ) then self.Sizing = { gui.MouseX() - self:GetWide(), nil } self:MouseCapture( true ) return end if gui.MouseY() > ( self.y + self:GetTall() - 5 ) then self.Sizing = { nil, gui.MouseY() - self:GetTall() } self:MouseCapture( true ) return end end if self:GetDraggable() and gui.MouseY() < ( self.y + 24 ) then self.Dragging = { gui.MouseX() - self.x, gui.MouseY() - self.y } self:MouseCapture( true ) return end end function PANEL:AddComponent ( name, component ) self.components[ name ] = component end function PANEL:addLockChild ( frame ) if table.HasValue( self.lockChildren, frame ) then return end self.lockChildren[ #self.lockChildren + 1 ] = frame end function PANEL:removeLockChild ( frame ) if not table.HasValue( self.lockChildren, frame ) then return end table.RemoveByValue( self.lockChildren, frame ) end function PANEL:setLockParent ( frame ) self.lockParent = frame end function PANEL:lock ( frame ) self:setLockParent( frame ) frame:addLockChild( self ) end function PANEL:moveLockChildren ( x, y ) for k, v in pairs( self.lockChildren ) do if v.locked then local vx, vy = v:GetPos() v:SetPos( vx + x, vy + y ) v:moveLockChildren( x, y ) end end end PANEL.Paint = function ( panel, w, h ) draw.RoundedBox( 0, 0, 0, w, h, SF.Editor.colors.dark ) end function PANEL:open () for k, v in pairs( self.lockChildren ) do if v.locked then v:open() end end self:SetVisible( true ) self:SetKeyBoardInputEnabled( true ) self:MakePopup() self:InvalidateLayout( true ) self:OnOpen() end function PANEL:close () for k, v in pairs( self.lockChildren ) do if v.locked then v:close() end end self:OnClose() self:SetKeyBoardInputEnabled( false ) self:Close() end function PANEL:OnOpen () end function PANEL:OnClose () end vgui.Register( "StarfallFrame", PANEL, "DFrame" ) -- End Starfall Frame -------------------------------------------------------------- -------------------------------------------------------------- -- Starfall Button PANEL = {} function PANEL:Init () self:SetText( "" ) self:SetSize( 22, 22 ) end function PANEL:SetIcon ( icon ) self.icon = SF.Editor.icons[ icon ] end function PANEL:PerformLayout () if self:GetText() ~= "" then self:SizeToContentsX() self:SetWide( self:GetWide() + 14 ) end end PANEL.Paint = function ( button, w, h ) if button.Hovered or button.active then draw.RoundedBox( 0, 0, 0, w, h, button.backgroundHoverCol or SF.Editor.colors.med ) else draw.RoundedBox( 0, 0, 0, w, h, button.backgroundCol or SF.Editor.colors.meddark ) end if button.icon then surface.SetDrawColor( SF.Editor.colors.medlight ) surface.SetMaterial( button.icon ) surface.DrawTexturedRect( 2, 2, w - 4, h - 4 ) end end function PANEL:UpdateColours ( skin ) return self:SetTextStyleColor( self.labelCol or SF.Editor.colors.light ) end function PANEL:SetHoverColor ( col ) self.backgroundHoverCol = col end function PANEL:SetColor ( col ) self.backgroundCol = col end function PANEL:SetLabelColor ( col ) self.labelCol = col end function PANEL:DoClick () end vgui.Register( "StarfallButton", PANEL, "DButton" ) -- End Starfall Button -------------------------------------------------------------- -------------------------------------------------------------- -- Starfall Panel PANEL = {} function PANEL:Init () self.m_bgColor = SF.Editor.colors.light end PANEL.Paint = function ( panel, w, h ) draw.RoundedBox( 0, 0, 0, w, h, panel.m_bgColor ) end vgui.Register( "StarfallPanel", PANEL, "DPanel" ) -- End Starfall Panel -------------------------------------------------------------- -------------------------------------------------------------- -- Tab Holder PANEL = {} function PANEL:Init () self:SetTall( 22 ) self.offsetTabs = 0 self.tabs = {} local parent = self self.offsetRight = vgui.Create( "StarfallButton", self ) self.offsetRight:SetVisible( false ) self.offsetRight:SetSize( 22, 22 ) self.offsetRight:SetIcon( "arrowr" ) function self.offsetRight:PerformLayout () local wide = 0 if parent.offsetLeft:IsVisible() then wide = parent.offsetLeft:GetWide() + 2 end for i = parent.offsetTabs + 1, #parent.tabs do if wide + parent.tabs[ i ]:GetWide() > parent:GetWide() - self:GetWide() - 2 then break else wide = wide + parent.tabs[ i ]:GetWide() + 2 end end self:SetPos( wide, 0 ) end function self.offsetRight:DoClick () parent.offsetTabs = parent.offsetTabs + 1 if parent.offsetTabs > #parent.tabs - 1 then parent.offsetTabs = #parent.tabs - 1 end parent:InvalidateLayout() end self.offsetLeft = vgui.Create( "StarfallButton", self ) self.offsetLeft:SetVisible( false ) self.offsetLeft:SetSize( 22, 22 ) self.offsetLeft:SetIcon( "arrowl" ) function self.offsetLeft:DoClick () parent.offsetTabs = parent.offsetTabs - 1 if parent.offsetTabs < 0 then parent.offsetTabs = 0 end parent:InvalidateLayout() end self.menuoptions = {} self.menuoptions[ #self.menuoptions + 1 ] = { "Close", function () if not self.targetTab then return end self:removeTab( self.targetTab ) self.targetTab = nil end } self.menuoptions[ #self.menuoptions + 1 ] = { "Close Other Tabs", function () if not self.targetTab then return end local n = 1 while #self.tabs ~= 1 do v = self.tabs[ n ] if v ~= self.targetTab then self:removeTab( v ) else n = 2 end end self.targetTab = nil end } end PANEL.Paint = function () end function PANEL:PerformLayout () local parent = self:GetParent() self:SetWide( parent:GetWide() - 10 ) self.offsetRight:PerformLayout() self.offsetLeft:PerformLayout() local offset = 0 if self.offsetLeft:IsVisible() then offset = self.offsetLeft:GetWide() + 2 end for i = 1, self.offsetTabs do offset = offset - self.tabs[ i ]:GetWide() - 2 end local bool = false for k, v in pairs( self.tabs ) do v:SetPos( offset, 0 ) if offset < 0 then v:SetVisible( false ) elseif offset + v:GetWide() > self:GetWide() - self.offsetRight:GetWide() - 2 then v:SetVisible( false ) bool = true else v:SetVisible( true ) end offset = offset + v:GetWide() + 2 end if bool then self.offsetRight:SetVisible( true ) else self.offsetRight:SetVisible( false ) end if self.offsetTabs > 0 then self.offsetLeft:SetVisible( true ) else self.offsetLeft:SetVisible( false ) end end function PANEL:addTab ( text ) local panel = self local tab = vgui.Create( "StarfallButton", self ) tab:SetText( text ) tab.isTab = true function tab:DoClick () panel:selectTab( self ) end function tab:DoRightClick () panel.targetTab = self local menu = vgui.Create( "DMenu", panel:GetParent() ) for k, v in pairs( panel.menuoptions ) do local option, func = v[ 1 ], v[ 2 ] if func == "SPACER" then menu:AddSpacer() else menu:AddOption( option, func ) end end menu:Open() end function tab:DoMiddleClick () panel:removeTab( self ) end self.tabs[ #self.tabs + 1 ] = tab return tab end function PANEL:removeTab ( tab ) local tabIndex if type( tab ) == "number" then tabIndex = tab tab = self.tabs[ tab ] else tabIndex = self:getTabIndex( tab ) end table.remove( self.tabs, tabIndex ) tab:Remove() self:OnRemoveTab( tabIndex ) end function PANEL:getActiveTab () for k,v in pairs( self.tabs ) do if v.active then return v end end end function PANEL:getTabIndex ( tab ) return table.KeyFromValue( self.tabs, tab ) end function PANEL:selectTab ( tab ) if type( tab ) == "number" then tab = self.tabs[ tab ] end if tab == nil then return end if self:getActiveTab() == tab then return end for k,v in pairs( self.tabs ) do v.active = false end tab.active = true if self:getTabIndex( tab ) <= self.offsetTabs then self.offsetTabs = self:getTabIndex( tab ) - 1 elseif not tab:IsVisible() then while not tab:IsVisible() do self.offsetTabs = self.offsetTabs + 1 self:PerformLayout() end end end function PANEL:OnRemoveTab ( tabIndex ) end vgui.Register( "StarfallTabHolder", PANEL, "DPanel" ) -- End Tab Holder -------------------------------------------------------------- -------------------------------------------------------------- -- File Tree local invalid_filename_chars = { ["*"] = "", ["?"] = "", [">"] = "", ["<"] = "", ["|"] = "", ["\\"] = "", ['"'] = "", } PANEL = {} function PANEL:Init () end function PANEL:setup ( folder ) self.folder = folder self.Root = self.RootNode:AddFolder( folder, folder, "DATA", true ) self.Root:SetExpanded( true ) end function PANEL:reloadTree () self.Root:Remove() self:setup( self.folder ) end function PANEL:DoRightClick ( node ) self:openMenu( node ) end function PANEL:openMenu ( node ) local menu if node:GetFileName() then menu = "file" elseif node:GetFolder() then menu = "folder" end self.menu = vgui.Create( "DMenu", self:GetParent() ) if menu == "file" then self.menu:AddOption( "Open", function () self:OnNodeSelected( node ) end ) self.menu:AddSpacer() self.menu:AddOption( "Rename", function () Derma_StringRequestNoBlur( "Rename file", "", string.StripExtension( node:GetText() ), function ( text ) if text == "" then return end text = string.gsub( text, ".", invalid_filename_chars ) local saveFile = string.GetPathFromFilename( node:GetFileName() ) .. text .. ".txt" local contents = file.Read( node:GetFileName() ) file.Delete( node:GetFileName() ) file.Write( saveFile, contents ) SF.AddNotify( LocalPlayer(), "File renamed as " .. saveFile .. ".", NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end ) end ) self.menu:AddSpacer() self.menu:AddOption( "Delete", function () Derma_Query( "Are you sure you want to delete this file?", "Delete file", "Delete", function () file.Delete( node:GetFileName() ) SF.AddNotify( LocalPlayer(), "File deleted: " .. node:GetFileName(), NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end, "Cancel" ) end ) elseif menu == "folder" then self.menu:AddOption( "New file", function () Derma_StringRequestNoBlur( "New file", "", "", function ( text ) if text == "" then return end text = string.gsub( text, ".", invalid_filename_chars ) local saveFile = node:GetFolder().."/"..text..".txt" file.Write( saveFile, "" ) SF.AddNotify( LocalPlayer(), "New file: " .. saveFile, NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end ) end ) self.menu:AddSpacer() self.menu:AddOption( "New folder", function () Derma_StringRequestNoBlur( "New folder", "", "", function ( text ) if text == "" then return end text = string.gsub( text, ".", invalid_filename_chars ) local saveFile = node:GetFolder().."/"..text file.CreateDir( saveFile ) SF.AddNotify( LocalPlayer(), "New folder: " .. saveFile, NOTIFY_GENERIC, 7, NOTIFYSOUND_DRIP3 ) self:reloadTree() end ) end ) end self.menu:Open() end derma.DefineControl( "StarfallFileTree", "", PANEL, "DTree" ) -- End File Tree -------------------------------------------------------------- -------------------------------------------------------------- -- File Browser PANEL = {} function PANEL:Init () self:Dock( FILL ) self:DockMargin( 0, 5, 0, 0 ) self.Paint = function () end local tree = vgui.Create( "StarfallFileTree", self ) tree:Dock( FILL ) self.tree = tree local searchBox = vgui.Create( "DTextEntry", self ) searchBox:Dock( TOP ) searchBox:SetValue( "Search..." ) searchBox._OnGetFocus = searchBox.OnGetFocus function searchBox:OnGetFocus () if self:GetValue() == "Search..." then self:SetValue( "" ) end searchBox:_OnGetFocus() end searchBox._OnLoseFocus = searchBox.OnLoseFocus function searchBox:OnLoseFocus () if self:GetValue() == "" then self:SetText( "Search..." ) end searchBox:_OnLoseFocus() end function searchBox:OnChange () if self:GetValue() == "" then tree:reloadTree() return end tree.Root.ChildNodes:Clear() local function containsFile ( dir, search ) local files, folders = file.Find( dir .. "/*", "DATA" ) for k, file in pairs( files ) do if string.find( string.lower( file ), string.lower( search ) ) then return true end end for k, folder in pairs( folders ) do if containsFile( dir .. "/" .. folder, search ) then return true end end return false end local function addFiles ( search, dir, node ) local allFiles, allFolders = file.Find( dir .. "/*", "DATA" ) for k, v in pairs( allFolders ) do if containsFile( dir .. "/" .. v, search ) then local newNode = node:AddNode( v ) newNode:SetExpanded( true ) addFiles( search, dir .. "/" .. v, newNode ) end end for k, v in pairs( allFiles ) do if string.find( string.lower( v ), string.lower( search ) ) then node:AddNode( v, "icon16/page_white.png" ) end end end addFiles( self:GetValue():PatternSafe(), "starfall", tree.Root ) tree.Root:SetExpanded( true ) end self.searchBox = searchBox end function PANEL:getComponents () return self.searchBox, self.tree end derma.DefineControl( "StarfallFileBrowser", "", PANEL, "DPanel" ) -- End File Browser
bsd-3-clause
pixeltailgames/gm-mediaplayer
lua/mediaplayer/sh_services.lua
1
2498
MediaPlayer.Services = {} function MediaPlayer.RegisterService( service ) local base if service.Base then base = MediaPlayer.Services[service.Base] elseif MediaPlayer.Services.base then base = MediaPlayer.Services.base end -- Inherit base service setmetatable( service, { __index = base } ) -- Create base class for service baseclass.Set( "mp_service_" .. service.Id, service ) -- Store service MediaPlayer.Services[ service.Id ] = service if MediaPlayer.DEBUG then print( "MediaPlayer.RegisterService", service.Name ) end end function MediaPlayer.GetValidServiceNames( whitelist ) local tbl = {} for _, service in pairs(MediaPlayer.Services) do if not rawget(service, "Abstract") then if whitelist then if table.HasValue( whitelist, service.Id ) then table.insert( tbl, service.Name ) end else table.insert( tbl, service.Name ) end end end return tbl end function MediaPlayer.GetSupportedServiceIDs() local tbl = {} for _, service in pairs(MediaPlayer.Services) do if not rawget(service, "Abstract") then table.insert( tbl, service.Id ) end end return tbl end function MediaPlayer.ValidUrl( url ) for id, service in pairs(MediaPlayer.Services) do if service:Match( url ) then return true end end return false end function MediaPlayer.GetMediaForUrl( url, webpageFallback ) local service for id, s in pairs(MediaPlayer.Services) do if s:Match( url ) then service = s break end end if not service then if webpageFallback then service = MediaPlayer.Services.www else service = MediaPlayer.Services.base end end return service:New( url ) end -- Load services do local path = "services/" local fullpath = "mediaplayer/" .. path local services = { "base", -- MUST LOAD FIRST! -- Browser "browser", -- base "youtube", "googledrive", "twitch", "twitchstream", "vimeo", -- HTML Resources "resource", -- base "image", "html5_video", "webpage", -- IGModAudioChannel "audiofile", "shoutcast", "soundcloud" } for _, name in ipairs(services) do local clfile = path .. name .. "/cl_init.lua" local svfile = path .. name .. "/init.lua" local shfile = fullpath .. name .. ".lua" if file.Exists(shfile, "LUA") then clfile = shfile svfile = shfile end SERVICE = {} if SERVER then AddCSLuaFile(clfile) include(svfile) else include(clfile) end MediaPlayer.RegisterService( SERVICE ) SERVICE = nil end end
mit
gajop/Zero-K
lups/ParticleClasses/Jet.lua
14
6334
-- $Id: Jet.lua 3171 2008-11-06 09:06:29Z det $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local Jet = {} Jet.__index = Jet local jitShader local tex --//screencopy local timerUniform ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function Jet.GetInfo() return { name = "Jet", backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = 4, --// extreme simply z-ordering :x --// gfx requirement fbo = true, shader = true, distortion= true, ms = -1, intel = -1, } end Jet.Default = { layer = 4, life = math.huge, repeatEffect = true, emitVector = {0,0,-1}, pos = {0,0,0}, --// not used width = 4, length = 50, distortion = 0.02, animSpeed = 1, texture1 = "bitmaps/GPL/Lups/perlin_noise.jpg", --// noise texture texture2 = ":c:bitmaps/GPL/Lups/jet.bmp", --// jitter shape } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local spGetGameSeconds = Spring.GetGameSeconds local glUseShader = gl.UseShader local glUniform = gl.Uniform local glTexture = gl.Texture local glCallList = gl.CallList function Jet:BeginDrawDistortion() glUseShader(jitShader) glUniform(timerUniform, spGetGameSeconds()) end function Jet:EndDrawDistortion() glUseShader(0) glTexture(1,false) glTexture(2,false) end function Jet:DrawDistortion() glTexture(1,self.texture1) glTexture(2,self.texture2) glCallList(self.dList) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- used if repeatEffect=true; function Jet:ReInitialize() self.dieGameFrame = self.dieGameFrame + self.life end function Jet.Initialize() jitShader = gl.CreateShader({ vertex = [[ uniform float timer; varying float distortion; varying vec4 texCoords; const vec4 centerPos = vec4(0.0,0.0,0.0,1.0); // gl_vertex.xy := width/length // gl_vertex.zw := texcoord // gl_MultiTexCoord0.x := (quad_width) / (quad_length) (used to normalize the texcoord dimensions) // gl_MultiTexCoord0.y := distortion strength // gl_MultiTexCoord0.z := animation speed // gl_MultiTexCoord1 := emit vector void main() { texCoords.st = gl_Vertex.pq; texCoords.pq = gl_Vertex.pq; texCoords.p *= gl_MultiTexCoord0.x; texCoords.pq += timer*gl_MultiTexCoord0.z; gl_Position = gl_ModelViewMatrix * centerPos; vec3 dir3 = vec3(gl_ModelViewMatrix * gl_MultiTexCoord1) - gl_Position.xyz; vec3 v = normalize( dir3 ); vec3 w = normalize( -vec3(gl_Position) ); vec3 u = normalize( cross(w,v) ); gl_Position.xyz += gl_Vertex.x*v + gl_Vertex.y*u; gl_Position = gl_ProjectionMatrix * gl_Position; distortion = gl_MultiTexCoord0.y; } ]], fragment = [[ uniform sampler2D noiseMap; uniform sampler2D mask; varying float distortion; varying vec4 texCoords; void main(void) { float opac = texture2D(mask,texCoords.st).r; vec2 noiseVec = (texture2D(noiseMap, texCoords.pq).st - 0.5) * distortion * opac; gl_FragColor = vec4(noiseVec.xy,0.0,gl_FragCoord.z); } ]], uniformInt = { noiseMap = 1, mask = 2, }, uniform = { timer = 0, } }) if (jitShader == nil) then print(PRIO_MAJOR,"LUPS->Jet: shader error: "..gl.GetShaderLog()) return false end timerUniform = gl.GetUniformLocation(jitShader, 'timer') end function Jet:Finalize() if (gl.DeleteShader) then gl.DeleteShader(jitShader) end end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local glMultiTexCoord = gl.MultiTexCoord local glVertex = gl.Vertex local glCreateList = gl.CreateList local glDeleteList = gl.DeleteList local glBeginEnd = gl.BeginEnd local GL_QUADS = GL.QUADS local function BeginEndDrawList(self) local ev = self.emitVector glMultiTexCoord(0,self.width/self.length,self.distortion,0.2*self.animSpeed) glMultiTexCoord(1,ev[1],ev[2],ev[3],1) --// xy = width/length ; zw = texcoord local w = self.width local l = self.length glVertex(-l,-w, 1,0) glVertex(0, -w, 1,1) glVertex(0, w, 0,1) glVertex(-l, w, 0,0) end function Jet:CreateParticle() self.dList = glCreateList(glBeginEnd,GL_QUADS, BeginEndDrawList,self) --// used for visibility check self.radius = self.length self.dieGameFrame = thisGameFrame + self.life end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local MergeTable = MergeTable local setmetatable = setmetatable function Jet.Create(Options) local newObject = MergeTable(Options, Jet.Default) setmetatable(newObject,Jet) -- make handle lookup newObject:CreateParticle() return newObject end function Jet:Destroy() --gl.DeleteTexture(self.texture1) --gl.DeleteTexture(self.texture2) glDeleteList(self.dList) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return Jet
gpl-2.0
ifoxhz/iFox
third-party/LuaJIT-2.0.3/src/jit/vmdef.lua
56
6676
-- This is a generated file. DO NOT EDIT! module(...) bcnames = "ISLT ISGE ISLE ISGT ISEQV ISNEV ISEQS ISNES ISEQN ISNEN ISEQP ISNEP ISTC ISFC IST ISF MOV NOT UNM LEN ADDVN SUBVN MULVN DIVVN MODVN ADDNV SUBNV MULNV DIVNV MODNV ADDVV SUBVV MULVV DIVVV MODVV POW CAT KSTR KCDATAKSHORTKNUM KPRI KNIL UGET USETV USETS USETN USETP UCLO FNEW TNEW TDUP GGET GSET TGETV TGETS TGETB TSETV TSETS TSETB TSETM CALLM CALL CALLMTCALLT ITERC ITERN VARG ISNEXTRETM RET RET0 RET1 FORI JFORI FORL IFORL JFORL ITERL IITERLJITERLLOOP ILOOP JLOOP JMP FUNCF IFUNCFJFUNCFFUNCV IFUNCVJFUNCVFUNCC FUNCCW" irnames = "LT GE LE GT ULT UGE ULE UGT EQ NE ABC RETF NOP BASE PVAL GCSTEPHIOP LOOP USE PHI RENAMEKPRI KINT KGC KPTR KKPTR KNULL KNUM KINT64KSLOT BNOT BSWAP BAND BOR BXOR BSHL BSHR BSAR BROL BROR ADD SUB MUL DIV MOD POW NEG ABS ATAN2 LDEXP MIN MAX FPMATHADDOV SUBOV MULOV AREF HREFK HREF NEWREFUREFO UREFC FREF STRREFALOAD HLOAD ULOAD FLOAD XLOAD SLOAD VLOAD ASTOREHSTOREUSTOREFSTOREXSTORESNEW XSNEW TNEW TDUP CNEW CNEWI TBAR OBAR XBAR CONV TOBIT TOSTR STRTO CALLN CALLL CALLS CALLXSCARG " irfpm = { [0]="floor", "ceil", "trunc", "sqrt", "exp", "exp2", "log", "log2", "log10", "sin", "cos", "tan", "other", } irfield = { [0]="str.len", "func.env", "func.pc", "tab.meta", "tab.array", "tab.node", "tab.asize", "tab.hmask", "tab.nomm", "udata.meta", "udata.udtype", "udata.file", "cdata.ctypeid", "cdata.ptr", "cdata.int", "cdata.int64", "cdata.int64_4", } ircall = { [0]="lj_str_cmp", "lj_str_new", "lj_strscan_num", "lj_str_fromint", "lj_str_fromnum", "lj_tab_new1", "lj_tab_dup", "lj_tab_newkey", "lj_tab_len", "lj_gc_step_jit", "lj_gc_barrieruv", "lj_mem_newgco", "lj_math_random_step", "lj_vm_modi", "sinh", "cosh", "tanh", "fputc", "fwrite", "fflush", "lj_vm_floor", "lj_vm_ceil", "lj_vm_trunc", "sqrt", "exp", "lj_vm_exp2", "log", "lj_vm_log2", "log10", "sin", "cos", "tan", "lj_vm_powi", "pow", "atan2", "ldexp", "lj_vm_tobit", "softfp_add", "softfp_sub", "softfp_mul", "softfp_div", "softfp_cmp", "softfp_i2d", "softfp_d2i", "softfp_ui2d", "softfp_f2d", "softfp_d2ui", "softfp_d2f", "softfp_i2f", "softfp_ui2f", "softfp_f2i", "softfp_f2ui", "fp64_l2d", "fp64_ul2d", "fp64_l2f", "fp64_ul2f", "fp64_d2l", "fp64_d2ul", "fp64_f2l", "fp64_f2ul", "lj_carith_divi64", "lj_carith_divu64", "lj_carith_modi64", "lj_carith_modu64", "lj_carith_powi64", "lj_carith_powu64", "lj_cdata_setfin", "strlen", "memcpy", "memset", "lj_vm_errno", "lj_carith_mul64", } traceerr = { [0]="error thrown or hook called during recording", "trace too long", "trace too deep", "too many snapshots", "blacklisted", "NYI: bytecode %d", "leaving loop in root trace", "inner loop in root trace", "loop unroll limit reached", "bad argument type", "JIT compilation disabled for function", "call unroll limit reached", "down-recursion, restarting", "NYI: C function %p", "NYI: FastFunc %s", "NYI: unsupported variant of FastFunc %s", "NYI: return to lower frame", "store with nil or NaN key", "missing metamethod", "looping index lookup", "NYI: mixed sparse/dense table", "symbol not in cache", "NYI: unsupported C type conversion", "NYI: unsupported C function type", "guard would always fail", "too many PHIs", "persistent type instability", "failed to allocate mcode memory", "machine code too long", "hit mcode limit (retrying)", "too many spill slots", "inconsistent register allocation", "NYI: cannot assemble IR instruction %d", "NYI: PHI shuffling too complex", "NYI: register coalescing too complex", } ffnames = { [0]="Lua", "C", "assert", "type", "next", "pairs", "ipairs_aux", "ipairs", "getmetatable", "setmetatable", "getfenv", "setfenv", "rawget", "rawset", "rawequal", "unpack", "select", "tonumber", "tostring", "error", "pcall", "xpcall", "loadfile", "load", "loadstring", "dofile", "gcinfo", "collectgarbage", "newproxy", "print", "coroutine.status", "coroutine.running", "coroutine.create", "coroutine.yield", "coroutine.resume", "coroutine.wrap_aux", "coroutine.wrap", "math.abs", "math.floor", "math.ceil", "math.sqrt", "math.log10", "math.exp", "math.sin", "math.cos", "math.tan", "math.asin", "math.acos", "math.atan", "math.sinh", "math.cosh", "math.tanh", "math.frexp", "math.modf", "math.deg", "math.rad", "math.log", "math.atan2", "math.pow", "math.fmod", "math.ldexp", "math.min", "math.max", "math.random", "math.randomseed", "bit.tobit", "bit.bnot", "bit.bswap", "bit.lshift", "bit.rshift", "bit.arshift", "bit.rol", "bit.ror", "bit.band", "bit.bor", "bit.bxor", "bit.tohex", "string.len", "string.byte", "string.char", "string.sub", "string.rep", "string.reverse", "string.lower", "string.upper", "string.dump", "string.find", "string.match", "string.gmatch_aux", "string.gmatch", "string.gsub", "string.format", "table.foreachi", "table.foreach", "table.getn", "table.maxn", "table.insert", "table.remove", "table.concat", "table.sort", "io.method.close", "io.method.read", "io.method.write", "io.method.flush", "io.method.seek", "io.method.setvbuf", "io.method.lines", "io.method.__gc", "io.method.__tostring", "io.open", "io.popen", "io.tmpfile", "io.close", "io.read", "io.write", "io.flush", "io.input", "io.output", "io.lines", "io.type", "os.execute", "os.remove", "os.rename", "os.tmpname", "os.getenv", "os.exit", "os.clock", "os.date", "os.time", "os.difftime", "os.setlocale", "debug.getregistry", "debug.getmetatable", "debug.setmetatable", "debug.getfenv", "debug.setfenv", "debug.getinfo", "debug.getlocal", "debug.setlocal", "debug.getupvalue", "debug.setupvalue", "debug.upvalueid", "debug.upvaluejoin", "debug.sethook", "debug.gethook", "debug.debug", "debug.traceback", "jit.on", "jit.off", "jit.flush", "jit.status", "jit.attach", "jit.util.funcinfo", "jit.util.funcbc", "jit.util.funck", "jit.util.funcuvname", "jit.util.traceinfo", "jit.util.traceir", "jit.util.tracek", "jit.util.tracesnap", "jit.util.tracemc", "jit.util.traceexitstub", "jit.util.ircalladdr", "jit.opt.start", "ffi.meta.__index", "ffi.meta.__newindex", "ffi.meta.__eq", "ffi.meta.__len", "ffi.meta.__lt", "ffi.meta.__le", "ffi.meta.__concat", "ffi.meta.__call", "ffi.meta.__add", "ffi.meta.__sub", "ffi.meta.__mul", "ffi.meta.__div", "ffi.meta.__mod", "ffi.meta.__pow", "ffi.meta.__unm", "ffi.meta.__tostring", "ffi.meta.__pairs", "ffi.meta.__ipairs", "ffi.clib.__index", "ffi.clib.__newindex", "ffi.clib.__gc", "ffi.callback.free", "ffi.callback.set", "ffi.cdef", "ffi.new", "ffi.cast", "ffi.typeof", "ffi.istype", "ffi.sizeof", "ffi.alignof", "ffi.offsetof", "ffi.errno", "ffi.string", "ffi.copy", "ffi.fill", "ffi.abi", "ffi.metatype", "ffi.gc", "ffi.load", }
gpl-3.0
gajop/Zero-K
LuaUI/Widgets/chili/Headers/util.lua
3
8121
--//============================================================================= function IsTweakMode() return widgetHandler.tweakMode end --//============================================================================= function unpack4(t) if t then return t[1], t[2], t[3], t[4] else return 1, 2, 3, 4 end end function clamp(min,max,num) if (num<min) then return min elseif (num>max) then return max end return num end function ExpandRect(rect,margin) return { rect[1] - margin[1], --//left rect[2] - margin[2], --//top rect[3] + margin[1] + margin[3], --//width rect[4] + margin[2] + margin[4], --//height } end function InRect(rect,x,y) return x>=rect[1] and y>=rect[2] and x<=rect[1]+rect[3] and y<=rect[2]+rect[4] end function ProcessRelativeCoord(code, total) local num = tonumber(code) if (type(code) == "string") then local percent = tonumber(code:sub(1,-2)) or 0 if (percent<0) then percent = 0 elseif (percent>100) then percent = 100 end return math.floor(total * percent/100) elseif (num)and((1/num)<0) then return math.floor(total + num) else return math.floor(num or 0) end end function IsRelativeCoord(code) local num = tonumber(code) if (type(code) == "string") then return true elseif (num)and((1/num)<0) then return true else return false end end function IsRelativeCoordType(code) local num = tonumber(code) if (type(code) == "string") then return "relative" elseif (num)and((1/num)<0) then return "negative" else return "default" end end --//============================================================================= function IsObject(v) return ((type(v)=="metatable")or(type(v)=="userdata")) and(v.classname) end function IsNumber(v) return (type(v)=="number") end function isnumber(v) return (type(v)=="number") end function istable(v) return (type(v)=="table") end function isstring(v) return (type(v)=="string") end function isindexable(v) local t = type(v) return (t=="table")or(t=="metatable")or(t=="userdata") end function isfunc(v) return (type(v)=="function") end --//============================================================================= local curScissor = {1,1,1e9,1e9} local stack = {curScissor} local stackN = 1 function PushScissor(x,y,w,h) local right = x+w local bottom = y+h if (right > curScissor[3]) then right = curScissor[3] end if (bottom > curScissor[4]) then bottom = curScissor[4] end if (x < curScissor[1]) then x = curScissor[1] end if (y < curScissor[2]) then y = curScissor[2] end curScissor = {x,y,right,bottom} stackN = stackN + 1 stack[stackN] = curScissor local width = right - x local height = bottom - y if (width < 0) or (height < 0) then --// scissor is null space -> don't render at all return false end gl.Scissor(x,y,width,height) end function PopScissor() stack[stackN] = nil stackN = stackN - 1 curScissor = stack[stackN] if (stackN == 1) then gl.Scissor(false) else local x,y, right,bottom = unpack4(curScissor) local w = right - x local h = bottom - y if w >= 0 and h >= 0 then gl.Scissor(x,y,w,h) end end end --//============================================================================= function AreRectsOverlapping(rect1,rect2) return (rect1[1] <= rect2[1] + rect2[3]) and (rect1[1] + rect1[3] >= rect2[1]) and (rect1[2] <= rect2[2] + rect2[4]) and (rect1[2] + rect1[4] >= rect2[2]) end --//============================================================================= local oldPrint = print function print(...) oldPrint(...) io.flush() end --//============================================================================= function _ParseColorArgs(r,g,b,a) local t = type(r) if (t == "table") then return r else return {r,g,b,a} end end --//============================================================================= function string:findlast(str) local i local j = 0 repeat i = j j = self:find(str,i+1,true) until (not j) return i end function string:GetExt() local i = self:findlast('.') if (i) then return self:sub(i) end end --//============================================================================= local type = type local pairs = pairs function table:clear() for i,_ in pairs(self) do self[i] = nil end end function table:map(fun) local newTable = {} for key, value in pairs(self) do newTable[key] = fun(key, value) end return newTable end function table:shallowcopy() local newTable = {} for k, v in pairs(self) do newTable[k] = v end return newTable end function table:arrayshallowcopy() local newArray = {} for i=1, #self do newArray[i] = self[i] end return newTable end function table:arrayappend(t) for i=1, #t do self[#self+1] = t[i] end end function table:arraymap(fun) for i=1, #self do newTable[i] = fun(self[i]) end end function table:fold(fun, state) for key, value in pairs(self) do fun(state, key, value) end end function table:arrayreduce(fun) local state = self[1] for i=2, #self do state = fun(state , self[i]) end return state end -- removes and returns element from array -- array, T element -> T element function table:arrayremovefirst(element) for i=1, #self do if self[i] == element then return self:remove(i) end end end function table:ifind(element) for i=1, #self do if self[i] == element then return i end end return false end function table:sum() local r = 0 for i=1, #self do r = r + self[i] end return r end function table:merge(table2) for i,v in pairs(table2) do if (type(v)=='table') then local sv = type(self[i]) if (sv == 'table')or(sv == 'nil') then if (sv == 'nil') then self[i] = {} end table.merge(self[i],v) end elseif (self[i] == nil) then self[i] = v end end end function table:iequal(table2) for i,v in pairs(self) do if (table2[i] ~= v) then return false end end for i,v in pairs(table2) do if (self[i] ~= v) then return false end end return true end function table:iequal(table2) local length = #self if (length ~= #table2) then return false end for i=1,length do if (self[i] ~= table2[i]) then return false end end return true end function table:size() local cnt = 0 for _ in pairs(self) do cnt = cnt + 1 end return cnt end --//============================================================================= local weak_meta = {__mode='v'} function CreateWeakTable() local m = {} setmetatable(m, weak_meta) return m end --//============================================================================= function math.round(num,idp) if (not idp) then return math.floor(num+.5) else return ("%." .. idp .. "f"):format(num) --local mult = 10^(idp or 0) --return math.floor(num * mult + 0.5) / mult end end --//============================================================================= function InvertColor(c) return {1 - c[1], 1 - c[2], 1 - c[3], c[4]} end function math.mix(x, y, a) return y * a + x * (1 - a) end function mulColor(c, s) return {s * c[1], s * c[2], s * c[3], c[4]} end function mulColors(c1, c2) return {c1[1] * c2[1], c1[2] * c2[2], c1[3] * c2[3], c1[4] * c2[4]} end function mixColors(c1, c2, a) return { math.mix(c1[1], c2[1], a), math.mix(c1[2], c2[2], a), math.mix(c1[3], c2[3], a), math.mix(c1[4], c2[4], a) } end function color2incolor(r,g,b,a) if type(r) == 'table' then r,g,b,a = unpack4(r) end local inColor = '\255\255\255\255' if r then inColor = string.char(255, r*255, g*255, b*255) end return inColor end function incolor2color(inColor) local a = 255 local r,g,b = inColor:sub(2,4):byte(1,3) return r/255, g/255, b/255, a/255 end --//=============================================================================
gpl-2.0
KayMD/Illarion-Content
npc/base/patrol.lua
2
8187
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- base script for patrolling npcs or monsters local waypoints = require("npc.base.waypoints") local doors = require("base.doors") local M = {} -- functions for subscription: -- AbortRoute(guard) -- CharacterNear(guard,char) -- ** defaults ** local PatrolPointer = {}; -- local WpPointer = {}; -- pointers for the PatrolList local RandomPatrolChooser = {}; -- define if the patrols are randomly chosen. Can be changed in other scripts. local WpDone = {}; -- count how many waypoints (as destination) have been visited local WpMax = {}; -- save how many waypoints have to be visited in this patrol local NextWp = {}; -- save the next waypoint (the guard is walking to) local CurWp = {}; -- save the current waypoint (the guard is walking away from) local WpTry = {}; -- save how many times the route was aborted and choose a solution local PatrolInitDone = {}; local firstStartPatrol --[[ PatrolList must contain lists with positions at first, then they are replaced with the respective waypoints @ index base of every list must contain a list: [1] boolean true if waypoints are randomly chosen [2] integer number of waypoints to be chosen before patrol ends. 0=list.length ]] local PatrolList = {}; local ChooseNewPatrol local ChooseNewWp local GetWpFromPos local SetNewWp local AbortRoute local OpenDoor local CloseDoor local GetDoorItem local CharacterNear -- replace position data in PatrolList with waypoints and delete those which have no respective waypoint function M.PatrolInit(guard) if PatrolInitDone[guard.id]~=nil then return; end PatrolInitDone[guard.id] = 1; PatrolPointer[guard.id] = 0; WpPointer[guard.id] = 0; RandomPatrolChooser[guard.id] = true; WpDone[guard.id] = 0; WpMax[guard.id] = 0; NextWp[guard.id] = nil; CurWp[guard.id] = nil; WpTry[guard.id] = 0; local nospace = true; for _,patrol in pairs(PatrolList) do nospace = true; for j,pos in ipairs(patrol) do local wp = GetWpFromPos(pos); if wp==nil then nospace = false; patrol[j] = -1; else patrol[j] = wp; end end -- fill in the spaces, if not all positions could be assigned to a wp if not nospace then local free for j,pos in ipairs(patrol) do if pos==-1 then if not free then free = j; end elseif free then patrol[free] = pos; free = free + 1; patrol[j] = nil; end end end end end --[[ starts the patrol and initializes the PatrolList and WaypointList @return boolean if the patrol has been started ]] function M.StartPatrol(guard) if firstStartPatrol==nil then firstStartPatrol = 1; waypoints.Init(); M.PatrolInit(); end PatrolPointer[guard.id] = 0; WpTry[guard.id] = 0; ChooseNewPatrol(guard); NextWp[guard.id] = GetWpFromPos(guard.pos); if not NextWp[guard.id] then NextWp[guard.id] = PatrolList[PatrolPointer[guard.id]][WpPointer[guard.id]]; guard:forceWarp(NextWp[guard.id].pos); end if not NextWp[guard.id] then return false; end guard.waypoints:clear(); SetNewWp(guard); guard:setOnRoute(true); return true; end --[[ choose a new patrol. Sequential and random (see RandomPatrolChooser) is supported. ]] function ChooseNewPatrol(guard) guard.waypoints:clear(); WpPointer[guard.id] = 0; WpDone[guard.id] = 0; local l = #PatrolList; if RandomPatrolChooser[guard.id] then PatrolPointer[guard.id] = math.random(1,l); else PatrolPointer[guard.id] = PatrolPointer[guard.id] + 1; if PatrolPointer[guard.id]>l then PatrolPointer[guard.id] = 1; end end if PatrolList[PatrolPointer[guard.id]].base[2] ~= 0 then WpMax[guard.id] = PatrolList[PatrolPointer[guard.id]].base[2]; else WpMax[guard.id] = #PatrolList[PatrolPointer[guard.id]]; end ChooseNewWp(guard); end -- choose a new waypoint as destination, sequentially or randomly function ChooseNewWp(guard) local l = #PatrolList[PatrolPointer[guard.id]]; if PatrolList[PatrolPointer[guard.id]].base[1] then WpPointer[guard.id] = math.random(1,l); else WpPointer[guard.id] = WpPointer[guard.id] + 1; if WpPointer[guard.id]>l then WpPointer[guard.id] = 1; end end end -- get the respective waypoint or nil if noone exists function GetWpFromPos(pos) local index = waypoints.PosToIndex(pos); --[[ broken, probably beyond repair for _,area in pairs(WaypointList) do if area[index] then return area[index]; end end ]] return nil; end --[[ choose and set a new (temporary) waypoint. NextWp has to be set (which is actually the current waypoint) ]] function SetNewWp(guard) if (guard.pos == PatrolList[PatrolPointer[guard.id]][WpPointer[guard.id]].pos) then WpDone[guard.id] = WpDone[guard.id] + 1; if WpDone[guard.id]>=WpMax[guard.id] then ChooseNewPatrol(guard); else ChooseNewWp(guard); end end local last = CurWp[guard.id]; CurWp[guard.id] = NextWp[guard.id]; local w = false; NextWp[guard.id],w = CurWp[guard.id]:getNextWaypoint(PatrolList[PatrolPointer[guard.id]][WpPointer[guard.id]],last); OpenDoor(guard); guard.waypoints:addWaypoint(NextWp[guard.id].pos); if w then guard:warp(NextWp[guard.id].pos); end end --[[ continues patrol when route is aborted (set new wp, warp or restart patrol) should be called in the respective function of the monster/npc OR in base_guard.lua ]] function AbortRoute(guard) if (guard.pos == NextWp[guard.id].pos) then WpTry[guard.id] = 0; guard.waypoints:clear(); CloseDoor(guard); SetNewWp(guard); guard:setOnRoute(true); elseif WpTry[guard.id]==0 then WpTry[guard.id] = 1; guard:setOnRoute(true); elseif WpTry[guard.id]==1 then guard:warp(NextWp[guard.id].pos); WpTry[guard.id] = 2; AbortRoute(guard); elseif WpTry[guard.id]==2 then guard:forceWarp(NextWp[guard.id].pos); WpTry[guard.id] = 3; AbortRoute(guard); else M.StartPatrol(guard); end end -- open the door of curWp function OpenDoor(guard) local door = CurWp[guard.id].data.door; if door and (door.toPos == NextWp[guard.id].pos) then local item = GetDoorItem(door.pos); doors.OpenDoor(item); end end -- close the door of NextWp function CloseDoor(guard) local door = NextWp[guard.id].data.door; if door and (door.toPos == CurWp[guard.id].pos) then local item = world:getItemOnField(door.pos); doors.CloseDoor(item); end end -- get the door item, works only if it is on top function GetDoorItem(Posi) local item = world:getItemOnField(Posi); if (doors.CheckOpenDoor(item.id) or doors.CheckClosedDoor(item.id)) then return item; end; return nil; end; function CharacterNear(guard,char) if (NextWp[guard.id].pos == char.pos) then AbortRoute(guard); end end return M
agpl-3.0
jayman39tx/naev
dat/scripts/proximity.lua
17
4314
-- Poll for player proximity to a point in space. -- argument trigger: a table containing: -- location: The location, OR -- anchor: the pilot to use as the anchor for the trigger area -- radius: The radius around the location or anchor -- focus: The pilot that's polled for. If omitted, defaults to the player. -- funcname: The name of the function to be called when the player is in proximity. -- -- Example usage: hook.timer(500, "proximity", {location = vec2.new(0, 0), radius = 500, funcname = "function"}) -- Example usage: hook.timer(500, "proximity", {anchor = mypilot, radius = 500, funcname = "function"}) -- Example usage: hook.timer(500, "proximity", {anchor = mypilot, radius = 500, funcname = "function", focus = theirpilot}) function proximity( trigger ) if trigger.focus == nil then trigger.focus = player.pilot() end _proximity(trigger) end -- This variant assumes a proximity hook between two ships, and trigger when the anchor ship scans the focus ship (fuzzy detection doesn't trigger). -- argument trigger: a table containing: -- anchor: The pilot to use as the anchor for the trigger area. If omitted, defaults to the player. -- focus: The pilot that's polled for. -- funcname: The name of the function to be called when the player is in proximity. -- -- Example usage: hook.timer(500, "proximityScan", {focus = theirpilot, funcname = "function"}) -- Triggers when theirpilot is detected by the player -- Example usage: hook.timer(500, "proximityScan", {anchor = theirpilot, focus = mypilot, funcname = "function"}) -- Triggers when mypilot is detected by theirpilot function proximityScan( trigger ) if trigger.anchor == nil then trigger.anchor = player.pilot() end _proximityScan(trigger) end function _proximity( trigger ) if trigger.location ~= nil then if vec2.dist(trigger.focus:pos(), trigger.location) <= trigger.radius then _G[trigger.funcname]() return end elseif trigger.anchor ~= nil then if trigger.anchor:exists() and trigger.focus:exists() and vec2.dist(trigger.focus:pos(), trigger.anchor:pos()) <= trigger.radius then _G[trigger.funcname]() return end end -- Check global proxmitiy table if __proximity_tbl == nil then __proximity_tbl = {} __proximity_tbl["__save"] = true __proximity_tbl["id"] = 0 end -- Assign ID if necessary if trigger.__id == nil then __proximity_tbl["id"] = __proximity_tbl["id"]+1 trigger.__id = __proximity_tbl["id"] __proximity_tbl[ trigger.__id ] = trigger end -- First time hook is set if trigger.hook_tbl == nil then trigger.hook_tbl = {} hook.enter("proximityCancel", trigger) end -- Set new timer hook local hook_id = hook.timer(500, "_proximity", trigger) trigger.hook_tbl[1] = hook_id end function _proximityScan( trigger ) if trigger.focus ~= nil and trigger.anchor:exists() and trigger.focus:exists() then seen, scanned = trigger.anchor:inrange(trigger.focus) if scanned then _G[trigger.funcname]() return end end -- Check global proxmitiy table if __proximity_tbl == nil then __proximity_tbl = {} __proximity_tbl["__save"] = true __proximity_tbl["id"] = 0 end -- Assign ID if necessary if trigger.__id == nil then __proximity_tbl["id"] = __proximity_tbl["id"]+1 trigger.__id = __proximity_tbl["id"] __proximity_tbl[ trigger.__id ] = trigger end -- First time hook is set if trigger.hook_tbl == nil then trigger.hook_tbl = {} hook.enter("proximityCancel", trigger) end -- Set new timer hook local hook_id = hook.timer(500, "_proximityScan", trigger) trigger.hook_tbl[1] = hook_id end -- Make sure the proximity timer shuts itself off on land or jumpout. function proximityCancel( trigger ) if trigger ~= nil then hook.rm( trigger.hook_tbl[1] ) __proximity_tbl[ trigger.__id ] = nil end end -- Make sure the proximity timer shuts itself off on land or jumpout. function proximityCancel( trigger ) if trigger ~= nil then hook.rm( trigger.hook_tbl[1] ) __proximity_tbl[ trigger.__id ] = nil end end
gpl-3.0
Mutos/NAEV-StarsOfCall
dat/scripts/proximity.lua
17
4314
-- Poll for player proximity to a point in space. -- argument trigger: a table containing: -- location: The location, OR -- anchor: the pilot to use as the anchor for the trigger area -- radius: The radius around the location or anchor -- focus: The pilot that's polled for. If omitted, defaults to the player. -- funcname: The name of the function to be called when the player is in proximity. -- -- Example usage: hook.timer(500, "proximity", {location = vec2.new(0, 0), radius = 500, funcname = "function"}) -- Example usage: hook.timer(500, "proximity", {anchor = mypilot, radius = 500, funcname = "function"}) -- Example usage: hook.timer(500, "proximity", {anchor = mypilot, radius = 500, funcname = "function", focus = theirpilot}) function proximity( trigger ) if trigger.focus == nil then trigger.focus = player.pilot() end _proximity(trigger) end -- This variant assumes a proximity hook between two ships, and trigger when the anchor ship scans the focus ship (fuzzy detection doesn't trigger). -- argument trigger: a table containing: -- anchor: The pilot to use as the anchor for the trigger area. If omitted, defaults to the player. -- focus: The pilot that's polled for. -- funcname: The name of the function to be called when the player is in proximity. -- -- Example usage: hook.timer(500, "proximityScan", {focus = theirpilot, funcname = "function"}) -- Triggers when theirpilot is detected by the player -- Example usage: hook.timer(500, "proximityScan", {anchor = theirpilot, focus = mypilot, funcname = "function"}) -- Triggers when mypilot is detected by theirpilot function proximityScan( trigger ) if trigger.anchor == nil then trigger.anchor = player.pilot() end _proximityScan(trigger) end function _proximity( trigger ) if trigger.location ~= nil then if vec2.dist(trigger.focus:pos(), trigger.location) <= trigger.radius then _G[trigger.funcname]() return end elseif trigger.anchor ~= nil then if trigger.anchor:exists() and trigger.focus:exists() and vec2.dist(trigger.focus:pos(), trigger.anchor:pos()) <= trigger.radius then _G[trigger.funcname]() return end end -- Check global proxmitiy table if __proximity_tbl == nil then __proximity_tbl = {} __proximity_tbl["__save"] = true __proximity_tbl["id"] = 0 end -- Assign ID if necessary if trigger.__id == nil then __proximity_tbl["id"] = __proximity_tbl["id"]+1 trigger.__id = __proximity_tbl["id"] __proximity_tbl[ trigger.__id ] = trigger end -- First time hook is set if trigger.hook_tbl == nil then trigger.hook_tbl = {} hook.enter("proximityCancel", trigger) end -- Set new timer hook local hook_id = hook.timer(500, "_proximity", trigger) trigger.hook_tbl[1] = hook_id end function _proximityScan( trigger ) if trigger.focus ~= nil and trigger.anchor:exists() and trigger.focus:exists() then seen, scanned = trigger.anchor:inrange(trigger.focus) if scanned then _G[trigger.funcname]() return end end -- Check global proxmitiy table if __proximity_tbl == nil then __proximity_tbl = {} __proximity_tbl["__save"] = true __proximity_tbl["id"] = 0 end -- Assign ID if necessary if trigger.__id == nil then __proximity_tbl["id"] = __proximity_tbl["id"]+1 trigger.__id = __proximity_tbl["id"] __proximity_tbl[ trigger.__id ] = trigger end -- First time hook is set if trigger.hook_tbl == nil then trigger.hook_tbl = {} hook.enter("proximityCancel", trigger) end -- Set new timer hook local hook_id = hook.timer(500, "_proximityScan", trigger) trigger.hook_tbl[1] = hook_id end -- Make sure the proximity timer shuts itself off on land or jumpout. function proximityCancel( trigger ) if trigger ~= nil then hook.rm( trigger.hook_tbl[1] ) __proximity_tbl[ trigger.__id ] = nil end end -- Make sure the proximity timer shuts itself off on land or jumpout. function proximityCancel( trigger ) if trigger ~= nil then hook.rm( trigger.hook_tbl[1] ) __proximity_tbl[ trigger.__id ] = nil end end
gpl-3.0
DeterGent-Legion/MeGa_SaTaN
plugins/linkpv.lua
66
30275
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, '') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, '') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'linkpv' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, 'Group link for ('..string.gsub(msg.to.print_name, "_", " ")..'):\n'..group_link) end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 50 then return "Wrong number,range is [2-50]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { usage = { "linkpv: Send Link In Private Chat.", }, patterns = { "^([Ll]inkpv)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
danteinforno/wesnoth
join.lua
27
3343
-- join.lua -- -- Try to join a game called "Test" local function plugin() local function log(text) std_print("join: " .. text) end local counter = 0 local events, context, info local helper = wesnoth.require("lua/helper.lua") local function find_test_game(info) local g = info.game_list() if g then local gamelist = helper.get_child(g, "gamelist") if gamelist then for i = 1, #gamelist do local t = gamelist[i] if t[1] == "game" then local game = t[2] if game.scenario == "Test" then return game.id end end end end end return nil end local function idle_text(text) counter = counter + 1 if counter >= 100 then counter = 0 log("idling " .. text) end end log("hello world") repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for titlescreen or lobby") until info.name == "titlescreen" or info.name == "Multiplayer Lobby" while info.name == "titlescreen" do context.play_multiplayer({}) log("playing multiplayer...") events, context, info = coroutine.yield() end repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for lobby") until info.name == "Multiplayer Lobby" events, context, info = coroutine.yield() context.chat({message = "waiting for test game to join..."}) local test_game = nil repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for test game") for i,v in ipairs(events) do if v[1] == "chat" then std_print("chat:", v[2].message) end end test_game = find_test_game(info) until test_game log("found a test game, joining... id = " .. test_game) context.chat({message = "found test game"}) context.select_game({id = test_game}) events, context, info = coroutine.yield() context.join({}) events, context, info = coroutine.yield() repeat if context.join then context.join({}) else std_print("did not find join...") end events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for leader select dialog") until info.name == "Dialog" or info.name == "Multiplayer Wait" if info.name == "Dialog" then log("got a leader select dialog...") context.set_result({result = 0}) events, context, info = coroutine.yield() repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for mp wait") until info.name == "Multiplayer Wait" end log("got to multiplayer wait...") context.chat({message = "ready"}) repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for game") until info.name == "Game" log("got to a game context...") repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for not game") until info.name ~= "Game" log("left a game context...") repeat context.quit({}) log("quitting a " .. info.name .. " context...") events, context, info = coroutine.yield() until info.name == "titlescreen" context.exit({code = 0}) coroutine.yield() end return plugin
gpl-2.0
miralireza2/gpf
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
N3X15/spacebuild
lua/entities/base_sb_planet1/init.lua
1
11089
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include('shared.lua') function ENT:Initialize() self.BaseClass.Initialize(self) self:PhysicsInit(SOLID_NONE) self:SetMoveType(MOVETYPE_NONE) self:SetSolid(SOLID_NONE) -- TODO: Move this shit to sbenvironment. self.sbenvironment.temperature2 = 0 self.sbenvironment.sunburn = false self.sbenvironment.unstable = false self.sbenvironment.color = {} self.sbenvironment.bloom = {} self:SetNotSolid(true) self:DrawShadow(false) if CAF then self.caf = self.caf or {} self.caf.custom = self.caf.custom or {} self.caf.custom.canreceivedamage = false self.caf.custom.canreceiveheatdamage = false end end function ENT:GetSunburn() return self.sbenvironment.sunburn end function ENT:Unstable() if self.sbenvironment.unstable then if (math.random(1, 20) < 2) then --self:GetParent():Fire("invalue", "shake", "0") --self:GetParent():Fire("invalue", "rumble", "0") end end end function ENT:GetUnstable() return self.sbenvironment.unstable end local function Extract_Bit(bit, field) if not bit or not field then return false end local retval = 0 if ((field <= 7) and (bit <= 4)) then if (field >= 4) then field = field - 4 if (bit == 4) then return true end end if (field >= 2) then field = field - 2 if (bit == 2) then return true end end if (field >= 1) then field = field - 1 if (bit == 1) then return true end end end return false end function ENT:SetFlags(flags) if not flags or type(flags) ~= "number" then return end self.sbenvironment.habitat = Extract_Bit(1, flags) self.sbenvironment.unstable = Extract_Bit(2, flags) self.sbenvironment.sunburn = Extract_Bit(3, flags) end -- Simulates greenhouse gasses. function ENT:_GreenhousifyTemperature(t) -- Old delta-based temperature: -- T+((T*((C1-C2)/100))/2) --return t + ((t * ((self:GetCO2Percentage() - self.sbenvironment.air.co2per) / 100)) / 2) -- Simplified: -- T+(T*(C/200)) return t + (t * (self:GetCO2Percentage() / 200)) end function ENT:GetTemperature(ent) if not ent then return end local entpos = ent:GetPos() local trace = {} local lit = false local SunAngle2 = SunAngle local SunAngle if table.Count(TrueSun) > 0 then for k, v in pairs(TrueSun) do SunAngle = (entpos - v) SunAngle:Normalize() local startpos = (entpos - (SunAngle * 4096)) trace.start = startpos trace.endpos = entpos -- + Vector(0,0,30) local tr = util.TraceLine(trace) if (tr.Hit) then if (tr.Entity == ent) then if (ent:IsPlayer()) then if self.sbenvironment.sunburn then if (ent:Health() > 0) then ent:TakeDamage(5, 0) ent:EmitSound("HL2Player.BurnPain") end end end lit = true else --lit = false end else lit = true end end end local startpos = (entpos - (SunAngle2 * 4096)) trace.start = startpos trace.endpos = entpos -- + Vector(0,0,30) local tr = util.TraceLine(trace) if (tr.Hit) then if (tr.Entity == ent) then if (ent:IsPlayer()) then if self.sbenvironment.sunburn then if (ent:Health() > 0) then ent:TakeDamage(5, 0) ent:EmitSound("HL2Player.BurnPain") end end end lit = true else --lit = false end else lit = true end if lit then if self.sbenvironment.temperature2 then --return self.sbenvironment.temperature2 + ((self.sbenvironment.temperature2 * ((self:GetCO2Percentage() - self.sbenvironment.air.co2per) / 100)) / 2) return self:_GreenhousifyTemperature(self.sbenvironment.temperature2) end end if not self.sbenvironment.temperature then return 0 end --return self.sbenvironment.temperature + ((self.sbenvironment.temperature * ((self:GetCO2Percentage() - self.sbenvironment.air.co2per) / 100)) / 2) return self:_GreenhousifyTemperature(self.sbenvironment.temperature) end function ENT:GetPriority() return 1 end function ENT:CreateEnvironment(radius, gravity, atmosphere, temperature, temperature2, flags) self:SetFlags(flags) local o2 = 0 local co2 = 0 local n = 0 local h = 0 local pressure = atmosphere --set Radius if one is given if radius and type(radius) == "number" then if radius < 0 then radius = 0 end self.sbenvironment.size = radius end --set temperature2 if given if self.sbenvironment.habitat then --Based on values for earth o2 = 21 co2 = 0.45 n = 78 h = 0.55 else --Based on values for Venus o2 = 0 co2 = 96.5 n = 3.5 h = 0 end if temperature2 and type(temperature2) == "number" then self.sbenvironment.temperature2 = temperature2 end self.BaseClass.CreateEnvironment(self, gravity, atmosphere, pressure, temperature, o2, co2, n, h, "Planet " .. tostring(self:GetEnvironmentID())) end function ENT:UpdateEnvironment(radius, gravity, atmosphere, pressure, temperature, o2, co2, n, h, temperature2, flags) if radius and type(radius) == "number" then self:SetFlags(flags) self:UpdateSize(self.sbenvironment.size, radius) end --set temperature2 if given if temperature2 and type(temperature2) == "number" then self.sbenvironment.temperature2 = temperature2 end self.BaseClass.UpdateEnvironment(self, gravity, atmosphere, pressure, temperature, o2, co2, n) end function ENT:IsPlanet() return true end function ENT:CanTool() return false end function ENT:GravGunPunt() return false end function ENT:GravGunPickupAllowed() return false end function ENT:Think() self:Unstable() self:NextThink(CurTime() + 1) return true end local function SendBloom(ent) for k, ply in pairs(player.GetAll()) do umsg.Start("AddPlanet", ply) --umsg.Entity( ent ) --planet.num umsg.Short(ent:EntIndex()) umsg.Angle(ent:GetPos()) --planet.num umsg.Float(ent.sbenvironment.size) umsg.Bool(false) if table.Count(ent.sbenvironment.bloom) > 0 then umsg.Bool(true) umsg.Short(ent.sbenvironment.bloom.Col_r) umsg.Short(ent.sbenvironment.bloom.Col_g) umsg.Short(ent.sbenvironment.bloom.Col_b) umsg.Float(ent.sbenvironment.bloom.SizeX) umsg.Float(ent.sbenvironment.bloom.SizeY) umsg.Float(ent.sbenvironment.bloom.Passes) umsg.Float(ent.sbenvironment.bloom.Darken) umsg.Float(ent.sbenvironment.bloom.Multiply) umsg.Float(ent.sbenvironment.bloom.Color) else umsg.Bool(false) end umsg.End() end end local function SendColor(ent) for k, ply in pairs(player.GetAll()) do umsg.Start("AddPlanet", ply) --umsg.Entity( ent ) umsg.Short(ent:EntIndex()) umsg.Angle(ent:GetPos()) --planet.num umsg.Float(ent.sbenvironment.size) if table.Count(ent.sbenvironment.color) > 0 then umsg.Bool(true) umsg.Short(ent.sbenvironment.color.AddColor_r) umsg.Short(ent.sbenvironment.color.AddColor_g) umsg.Short(ent.sbenvironment.color.AddColor_b) umsg.Short(ent.sbenvironment.color.MulColor_r) umsg.Short(ent.sbenvironment.color.MulColor_g) umsg.Short(ent.sbenvironment.color.MulColor_b) umsg.Float(ent.sbenvironment.color.Brightness) umsg.Float(ent.sbenvironment.color.Contrast) umsg.Float(ent.sbenvironment.color.Color) else umsg.Bool(false) end umsg.Bool(false) umsg.End() end end function ENT:BloomEffect(Col_r, Col_g, Col_b, SizeX, SizeY, Passes, Darken, Multiply, Color) if SB_DEBUG then Msg("Col_r/b/g: " .. tostring(Col_r) .. "/" .. tostring(Col_b) .. "/" .. tostring(Col_g) .. "\n") Msg("SizeX/Y: " .. tostring(SizeX) .. "/" .. tostring(SizeY) .. "\n") Msg("Passes: " .. tostring(Passes) .. "\n") Msg("Darken: " .. tostring(Darken) .. "\n") Msg("Multiply: " .. tostring(Multiply) .. "\n") Msg("Color: " .. tostring(Color) .. "\n") end if Col_r then self.sbenvironment.bloom.Col_r = Col_r end if Col_g then self.sbenvironment.bloom.Col_g = Col_g end if Col_b then self.sbenvironment.bloom.Col_b = Col_b end if SizeX then self.sbenvironment.bloom.SizeX = SizeX end if SizeY then self.sbenvironment.bloom.SizeY = SizeY end if Passes then self.sbenvironment.bloom.Passes = Passes end if Darken then self.sbenvironment.bloom.Darken = Darken end if Multiply then self.sbenvironment.bloom.Multiply = Multiply end if Color then self.sbenvironment.bloom.Color = Color end Msg("Sending bloom update\n") SendBloom(self) end function ENT:ColorEffect(AddColor_r, AddColor_g, AddColor_b, MulColor_r, MulColor_g, MulColor_b, Brightness, Contrast, Color) if SB_DEBUG then Msg("AddColor_r/b/g: " .. tostring(AddColor_r) .. "/" .. tostring(AddColor_b) .. "/" .. tostring(AddColor_g) .. "\n") Msg("AddColor_r/b/g: " .. tostring(MulColor_r) .. "/" .. tostring(MulColor_b) .. "/" .. tostring(MulColor_g) .. "\n") Msg("Brightness: " .. tostring(Brightness) .. "\n") Msg("Contrast: " .. tostring(Contrast) .. "\n") Msg("Color: " .. tostring(Color) .. "\n") end if AddColor_r then self.sbenvironment.color.AddColor_r = AddColor_r end if AddColor_g then self.sbenvironment.color.AddColor_g = AddColor_g end if AddColor_b then self.sbenvironment.color.AddColor_b = AddColor_b end if MulColor_r then self.sbenvironment.color.MulColor_r = MulColor_r end if MulColor_g then self.sbenvironment.color.MulColor_g = MulColor_g end if MulColor_b then self.sbenvironment.color.MulColor_b = MulColor_b end if Brightness then self.sbenvironment.color.Brightness = Brightness end if Contrast then self.sbenvironment.color.Contrast = Contrast end if Color then self.sbenvironment.color.Color = Color end --Msg("Sending color update\n") SendColor(self) end
apache-2.0
gajop/Zero-K
LuaRules/Gadgets/CAI/UnitListHandler.lua
7
7249
--[[ Handles Lists of Units * Create as a list of unit with some functions. * Can get total unit cost, a random unit, units in area etc.. * Elements can have custom data. == CreateUnitList(losCheckAllyTeamID) losCheckAllyTeamID is the point of view that the return functions should take regarding LOS. A non-cheating AI would always create a unit list with its allyTeamID to ensure that the UnitList does not cheat. === Functions === == GetUnitPosition(unitID) -> {x, y, z} or false Returns the position of the unitID obeying LOS and radar. == GetNearestUnit(x, z, condition) -> unitID Returns the nearest unit in the list which satisfies the condition. The condition is a function of the form condition(unitID, x, z, customData, cost). == HasUnitMoved(unitID, range) -> boolean Returns true if the unit is range away from where it was when HasUnitMoved was last called. == IsPositionNearUnit(x, z, radius, condition) -> boolean Returns true if there is a unit from the list satisfying the conditions within the radius around the point. The condition is the same as in GetNearestUnit. == OverwriteUnitData(unitID, newData) == GetUnitData(unitID) -> table == SetUnitDataValue(unitID, key, value) Functions which get and set the custom data attachable to units in the list. == AddUnit(unitID, static, cost, newData) Adds a unit to the list. - static tells the list whether the unit can move. - cost is just treated as a number. - newData is a table of information to attach to the unit. == RemoveUnit(unitID) -> boolean Remove a unit from the list == GetUnitCost(unitID) -> cost == GetTotalCost() -> cost == ValidUnitID(unitID) -> boolean Returns true if the unit is in the list. == Iterator() -> unitID, cost, customData Provides a way to iterate over units in the list. It is not safe to remove units while iterating over them. To use do this: for unitID, cost, customData in unitList.Iterator() do ... end --]] local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitLosState = Spring.GetUnitLosState local UnitListHandler = {} local function DisSQ(x1,z1,x2,z2) return (x1 - x2)^2 + (z1 - z2)^2 end local function InternalGetUnitPosition(data, losCheckAllyTeamID) if data.static then if data.x then return data.x, data.y, data.z else local x,y,z = spGetUnitPosition(data.unitID) data.x = x data.y = y data.z = z return x, y, z end end if losCheckAllyTeamID then local los = spGetUnitLosState(data.unitID, losCheckAllyTeamID, false) if los and (los.los or los.radar) and los.typed then local x,y,z = spGetUnitPosition(data.unitID) return x, y, z end else local x,y,z = spGetUnitPosition(data.unitID) return x, y, z end return false end function UnitListHandler.CreateUnitList(losCheckAllyTeamID) local unitMap = {} local unitList = {} local unitCount = 0 local totalCost = 0 -- Indiviual Unit Position Functions function GetUnitPosition(unitID) if unitMap[unitID] then local index = unitMap[unitID] return InternalGetUnitPosition(unitList[index], losCheckAllyTeamID) end end function HasUnitMoved(unitID, range) if not unitMap[unitID] then return false end local index = unitMap[unitID] local data = unitList[index] if data.static then return false end local x,_,z = InternalGetUnitPosition(data, losCheckAllyTeamID) if x then if not data.oldX then data.oldX = x data.oldZ = z return true end if DisSQ(x,z,data.oldX,data.oldZ) > range^2 then data.oldX = x data.oldZ = z return true end return false end return true end -- Position checks over all units in the list function GetNearestUnit(x,z,condition) local minDisSq = false local closeID = false local closeX = false local closeZ = false for i = 1, unitCount do local data = unitList[i] local ux,_,uz = InternalGetUnitPosition(data, losCheckAllyTeamID) if ux and condition and condition(data.unitID, ux, uz, data.customData, data.cost) then local thisDisSq = DisSQ(x,z,ux,uz) if not minDisSq or minDisSq > thisDisSq then minDisSq = thisDisSq closeID = data.unitID closeX = x closeZ = z end end end return closeID, closeX, closeZ end function IsPositionNearUnit(x, z, radius, condition) local radiusSq = radius^2 for i = 1, unitCount do local data = unitList[i] local ux,_,uz = InternalGetUnitPosition(data, losCheckAllyTeamID) if ux and condition and condition(data.unitID, ux, uz, data.customData, data.cost) then local thisDisSq = DisSQ(x,z,ux,uz) if thisDisSq < radiusSq then return true end end end return false end -- Unit cust data handling function OverwriteUnitData(unitID, newData) if unitMap[unitID] then local index = unitMap[unitID] unitList[index].customData = newData end end function GetUnitData(unitID) -- returns a table but don't edit it! if unitMap[unitID] then local index = unitMap[unitID] return unitList[index].customData or {} end end function SetUnitDataValue(unitID, key, value) if unitMap[unitID] then local index = unitMap[unitID] if not unitList[index].customData then unitList[index].customData = {} end unitList[index].customData[key] = value end end -- Unit addition and removal handling function AddUnit(unitID, static, cost, newData) if unitMap[unitID] then if newData then OverwriteUnitData(unitID, newData) end return false end cost = cost or 0 -- Add unit to list unitCount = unitCount + 1 unitList[unitCount] = { unitID = unitID, static = static, cost = cost, customData = newData, } unitMap[unitID] = unitCount totalCost = totalCost + cost return true end function RemoveUnit(unitID) if unitMap[unitID] then local index = unitMap[unitID] totalCost = totalCost - unitList[index].cost -- Copy the end of the list to this index unitList[index] = unitList[unitCount] unitMap[unitList[index].unitID] = index -- Remove the end of the list unitList[unitCount] = nil unitCount = unitCount - 1 unitMap[unitID] = nil return true end return false end function ValidUnitID(unitID) return (unitMap[unitID] and true) or false end -- Cost Handling function GetUnitCost(unitID) if unitMap[unitID] then local index = unitMap[unitID] return unitList[index].cost end end function GetTotalCost() return totalCost end -- To use Iterator, write "for unitID, data in unitList.Iterator() do" function Iterator() local i = 0 return function () i = i + 1 if i <= unitCount then return unitList[i].unitID, unitList[i].cost, unitList[i].customData end end end local newUnitList = { GetUnitPosition = GetUnitPosition, GetNearestUnit = GetNearestUnit, HasUnitMoved = HasUnitMoved, IsPositionNearUnit = IsPositionNearUnit, OverwriteUnitData = OverwriteUnitData, GetUnitData = GetUnitData, SetUnitDataValue = SetUnitDataValue, AddUnit = AddUnit, RemoveUnit = RemoveUnit, GetUnitCost = GetUnitCost, GetTotalCost = GetTotalCost, ValidUnitID = ValidUnitID, Iterator = Iterator, } return newUnitList end return UnitListHandler
gpl-2.0
Sweet-kid/Algorithm-Implementations
Breadth_First_Search/Lua/Yonaba/bfs_test.lua
26
2339
-- Tests for bfs.lua local BFS = require 'bfs' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function same(t, p, comp) for k,v in ipairs(t) do if not comp(v, p[k]) then return false end end return true end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Testing linear graph', function() local comp = function(a, b) return a.value == b end local ln_handler = require 'handlers.linear_handler' ln_handler.init(-2,5) local bfs = BFS(ln_handler) local start, goal = ln_handler.getNode(0), ln_handler.getNode(5) assert(same(bfs:findPath(start, goal), {0,1,2,3,4,5}, comp)) start, goal = ln_handler.getNode(-2), ln_handler.getNode(2) assert(same(bfs:findPath(start, goal), {-2,-1,0,1,2}, comp)) end) run('Testing grid graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local gm_handler = require 'handlers.gridmap_handler' local bfs = BFS(gm_handler) local map = {{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}} gm_handler.init(map) gm_handler.diagonal = false local start, goal = gm_handler.getNode(1,1), gm_handler.getNode(5,3) assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{1,3},{2,3},{3,3},{4,3},{5,3}}, comp)) gm_handler.diagonal = true assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{2,3},{3,3},{4,3},{5,3}}, comp)) end) run('Testing point graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local pg_handler = require 'handlers.point_graph_handler' local bfs = BFS(pg_handler) pg_handler.addNode('a') pg_handler.addNode('b') pg_handler.addNode('c') pg_handler.addNode('d') pg_handler.addEdge('a', 'b') pg_handler.addEdge('a', 'c') pg_handler.addEdge('b', 'd') local comp = function(a, b) return a.name == b end local start, goal = pg_handler.getNode('a'), pg_handler.getNode('d') assert(same(bfs:findPath(start, goal), {'a','b','d'}, comp)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
KayMD/Illarion-Content
monster/race_90_black_imp/id_903_shadow_dancer.lua
3
1215
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local monstermagic = require("monster.base.monstermagic") local blackImps = require("monster.race_90_black_imp.base") local magic = monstermagic() magic.addWarping{probability = 0.05, usage = magic.ONLY_NEAR_ENEMY} magic.addSummon{probability = 0.055, monsters = {592, 982, 594, 622, 623}} -- Angry chicken, Crazy Chicken, and beetles magic.addSummon{probability = 0.010, monsters = {981, 983}} -- beetles magic.addSummon{probability = 0.0001, monsters = {984}} -- bonescraper beetle local M = blackImps.generateCallbacks() return magic.addCallbacks(M)
agpl-3.0
casseveritt/premake
src/actions/make/make_csharp.lua
18
8352
-- -- make_csharp.lua -- Generate a C# project makefile. -- Copyright (c) 2002-2009 Jason Perkins and the Premake project -- -- -- Given a .resx resource file, builds the path to corresponding .resource -- file, matching the behavior and naming of Visual Studio. -- local function getresourcefilename(cfg, fname) if path.getextension(fname) == ".resx" then local name = cfg.buildtarget.basename .. "." local dir = path.getdirectory(fname) if dir ~= "." then name = name .. path.translate(dir, ".") .. "." end return "$(OBJDIR)/" .. _MAKE.esc(name .. path.getbasename(fname)) .. ".resources" else return fname end end -- -- Main function -- function premake.make_csharp(prj) local csc = premake.dotnet -- Do some processing up front: build a list of configuration-dependent libraries. -- Libraries that are built to a location other than $(TARGETDIR) will need to -- be copied so they can be found at runtime. local cfglibs = { } local cfgpairs = { } local anycfg for cfg in premake.eachconfig(prj) do anycfg = cfg cfglibs[cfg] = premake.getlinks(cfg, "siblings", "fullpath") cfgpairs[cfg] = { } for _, fname in ipairs(cfglibs[cfg]) do if path.getdirectory(fname) ~= cfg.buildtarget.directory then cfgpairs[cfg]["$(TARGETDIR)/" .. _MAKE.esc(path.getname(fname))] = _MAKE.esc(fname) end end end -- sort the files into categories, based on their build action local sources = {} local embedded = { } local copypairs = { } for fcfg in premake.project.eachfile(prj) do local action = csc.getbuildaction(fcfg) if action == "Compile" then table.insert(sources, fcfg.name) elseif action == "EmbeddedResource" then table.insert(embedded, fcfg.name) elseif action == "Content" then copypairs["$(TARGETDIR)/" .. _MAKE.esc(path.getname(fcfg.name))] = _MAKE.esc(fcfg.name) elseif path.getname(fcfg.name):lower() == "app.config" then copypairs["$(TARGET).config"] = _MAKE.esc(fcfg.name) end end -- Any assemblies that are on the library search paths should be copied -- to $(TARGETDIR) so they can be found at runtime local paths = table.translate(prj.libdirs, function(v) return path.join(prj.basedir, v) end) paths = table.join({prj.basedir}, paths) for _, libname in ipairs(premake.getlinks(prj, "system", "fullpath")) do local libdir = os.pathsearch(libname..".dll", unpack(paths)) if (libdir) then local target = "$(TARGETDIR)/" .. _MAKE.esc(path.getname(libname)) local source = path.getrelative(prj.basedir, path.join(libdir, libname))..".dll" copypairs[target] = _MAKE.esc(source) end end -- end of preprocessing -- -- set up the environment _p('# %s project makefile autogenerated by Premake', premake.action.current().shortname) _p('') _p('ifndef config') _p(' config=%s', _MAKE.esc(prj.configurations[1]:lower())) _p('endif') _p('') _p('ifndef verbose') _p(' SILENT = @') _p('endif') _p('') _p('ifndef CSC') _p(' CSC=%s', csc.getcompilervar(prj)) _p('endif') _p('') _p('ifndef RESGEN') _p(' RESGEN=resgen') _p('endif') _p('') -- Platforms aren't support for .NET projects, but I need the ability to match -- the buildcfg:platform identifiers with a block of settings. So enumerate the -- pairs the same way I do for C/C++ projects, but always use the generic settings local platforms = premake.filterplatforms(prj.solution, premake[_OPTIONS.cc].platforms) table.insert(platforms, 1, "") -- write the configuration blocks for cfg in premake.eachconfig(prj) do premake.gmake_cs_config(cfg, csc, cfglibs) end -- set project level values _p('# To maintain compatibility with VS.NET, these values must be set at the project level') _p('TARGET := $(TARGETDIR)/%s', _MAKE.esc(prj.buildtarget.name)) _p('FLAGS += /t:%s %s', csc.getkind(prj):lower(), table.implode(_MAKE.esc(prj.libdirs), "/lib:", "", " ")) _p('REFERENCES += %s', table.implode(_MAKE.esc(premake.getlinks(prj, "system", "basename")), "/r:", ".dll", " ")) _p('') -- list source files _p('SOURCES := \\') for _, fname in ipairs(sources) do _p('\t%s \\', _MAKE.esc(path.translate(fname))) end _p('') _p('EMBEDFILES := \\') for _, fname in ipairs(embedded) do _p('\t%s \\', getresourcefilename(prj, fname)) end _p('') _p('COPYFILES += \\') for target, source in pairs(cfgpairs[anycfg]) do _p('\t%s \\', target) end for target, source in pairs(copypairs) do _p('\t%s \\', target) end _p('') -- identify the shell type _p('SHELLTYPE := msdos') _p('ifeq (,$(ComSpec)$(COMSPEC))') _p(' SHELLTYPE := posix') _p('endif') _p('ifeq (/bin,$(findstring /bin,$(SHELL)))') _p(' SHELLTYPE := posix') _p('endif') _p('') -- main build rule(s) _p('.PHONY: clean prebuild prelink') _p('') _p('all: $(TARGETDIR) $(OBJDIR) prebuild $(EMBEDFILES) $(COPYFILES) prelink $(TARGET)') _p('') _p('$(TARGET): $(SOURCES) $(EMBEDFILES) $(DEPENDS)') _p('\t$(SILENT) $(CSC) /nologo /out:$@ $(FLAGS) $(REFERENCES) $(SOURCES) $(patsubst %%,/resource:%%,$(EMBEDFILES))') _p('\t$(POSTBUILDCMDS)') _p('') -- Create destination directories. Can't use $@ for this because it loses the -- escaping, causing issues with spaces and parenthesis _p('$(TARGETDIR):') premake.make_mkdirrule("$(TARGETDIR)") _p('$(OBJDIR):') premake.make_mkdirrule("$(OBJDIR)") -- clean target _p('clean:') _p('\t@echo Cleaning %s', prj.name) _p('ifeq (posix,$(SHELLTYPE))') _p('\t$(SILENT) rm -f $(TARGETDIR)/%s.* $(COPYFILES)', prj.buildtarget.basename) _p('\t$(SILENT) rm -rf $(OBJDIR)') _p('else') _p('\t$(SILENT) if exist $(subst /,\\\\,$(TARGETDIR)/%s.*) del $(subst /,\\\\,$(TARGETDIR)/%s.*)', prj.buildtarget.basename, prj.buildtarget.basename) for target, source in pairs(cfgpairs[anycfg]) do _p('\t$(SILENT) if exist $(subst /,\\\\,%s) del $(subst /,\\\\,%s)', target, target) end for target, source in pairs(copypairs) do _p('\t$(SILENT) if exist $(subst /,\\\\,%s) del $(subst /,\\\\,%s)', target, target) end _p('\t$(SILENT) if exist $(subst /,\\\\,$(OBJDIR)) rmdir /s /q $(subst /,\\\\,$(OBJDIR))') _p('endif') _p('') -- custom build step targets _p('prebuild:') _p('\t$(PREBUILDCMDS)') _p('') _p('prelink:') _p('\t$(PRELINKCMDS)') _p('') -- per-file rules _p('# Per-configuration copied file rules') for cfg in premake.eachconfig(prj) do _p('ifneq (,$(findstring %s,$(config)))', _MAKE.esc(cfg.name:lower())) for target, source in pairs(cfgpairs[cfg]) do premake.make_copyrule(source, target) end _p('endif') _p('') end _p('# Copied file rules') for target, source in pairs(copypairs) do premake.make_copyrule(source, target) end _p('# Embedded file rules') for _, fname in ipairs(embedded) do if path.getextension(fname) == ".resx" then _p('%s: %s', getresourcefilename(prj, fname), _MAKE.esc(fname)) _p('\t$(SILENT) $(RESGEN) $^ $@') end _p('') end end -- -- Write a block of configuration settings. -- function premake.gmake_cs_config(cfg, csc, cfglibs) _p('ifneq (,$(findstring %s,$(config)))', _MAKE.esc(cfg.name:lower())) _p(' TARGETDIR := %s', _MAKE.esc(cfg.buildtarget.directory)) _p(' OBJDIR := %s', _MAKE.esc(cfg.objectsdir)) _p(' DEPENDS := %s', table.concat(_MAKE.esc(premake.getlinks(cfg, "dependencies", "fullpath")), " ")) _p(' REFERENCES := %s', table.implode(_MAKE.esc(cfglibs[cfg]), "/r:", "", " ")) _p(' FLAGS += %s %s', table.implode(cfg.defines, "/d:", "", " "), table.concat(table.join(csc.getflags(cfg), cfg.buildoptions), " ")) _p(' define PREBUILDCMDS') if #cfg.prebuildcommands > 0 then _p('\t@echo Running pre-build commands') _p('\t%s', table.implode(cfg.prebuildcommands, "", "", "\n\t")) end _p(' endef') _p(' define PRELINKCMDS') if #cfg.prelinkcommands > 0 then _p('\t@echo Running pre-link commands') _p('\t%s', table.implode(cfg.prelinkcommands, "", "", "\n\t")) end _p(' endef') _p(' define POSTBUILDCMDS') if #cfg.postbuildcommands > 0 then _p('\t@echo Running post-build commands') _p('\t%s', table.implode(cfg.postbuildcommands, "", "", "\n\t")) end _p(' endef') _p('endif') _p('') end
bsd-3-clause
gajop/Zero-K
units/amphassault.lua
2
7171
unitDef = { unitname = [[amphassault]], name = [[Grizzly]], description = [[Heavy Amphibious Assault Walker]], acceleration = 0.1, brakeRate = 0.1, buildCostEnergy = 2000, buildCostMetal = 2000, buildPic = [[amphassault.png]], buildTime = 2000, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND SINK]], collisionVolumeOffsets = [[0 0 0]], --collisionVolumeScales = [[70 70 70]], --collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { amph_regen = 40, amph_submerged_at = 40, sink_on_emp = 0, floattoggle = [[1]], description_pl = [[Ciezki amfibijny bot szturmowy]], helptext = [[The Grizzly is a classic assault unit - relatively slow, clumsy and next to unstoppable. Its weapon is a high power laser beam with high range and damage, ineffective against swarmers and fast aircraft but not much else. While its weapon cannot fire underwater, the Grizzly can float to surface in order to shoot.]], helptext_pl = [[Grizzly to klasyczna jednostka szturmowa - dosc wolna i niezdarna, lecz prawie niepowstrzymana. Jego bronia jest laser o duzym zasiegu i obrazeniach, ktory ma problemy wlasciwie tylko z szybkimi jednostkom atakujacym w grupach i lotnictwem. Grizzly moze sie wynurzyc do strzalu, ale nie moze strzelac pod woda.]], aimposoffset = [[0 30 0]], midposoffset = [[0 6 0]], modelradius = [[35]], }, explodeAs = [[BIG_UNIT]], footprintX = 4, footprintZ = 4, iconType = [[amphassault]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 9000, maxSlope = 36, maxVelocity = 1.6, minCloakDistance = 75, movementClass = [[AKBOT4]], noChaseCategory = [[TERRAFORM FIXEDWING SUB]], objectName = [[amphassault.s3o]], script = [[amphassault.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNIT]], sfxtypes = { explosiongenerators = { [[custom:watercannon_muzzle]], }, }, sightDistance = 660, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 66, turnRate = 500, upright = false, weapons = { { def = [[LASER]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[FAKE_LASER]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { LASER = { name = [[High-Energy Laserbeam]], areaOfEffect = 14, beamTime = 0.8, beamttl = 1, coreThickness = 0.5, craterBoost = 0, craterMult = 0, customParams = { statsprojectiles = 1, statsdamage = 1500, light_color = [[0.25 0.25 0.75]], light_radius = 180, }, damage = { default = 302.8, subs = 15, }, explosionGenerator = [[custom:flash1bluedark]], fireTolerance = 8192, -- 45 degrees fireStarter = 90, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 10.4, minIntensity = 1, noSelfDamage = true, projectiles = 5, range = 600, reloadtime = 6, rgbColor = [[0 0 1]], scrollSpeed = 5, soundStart = [[weapon/laser/heavy_laser3]], soundStartVolume = 3, sweepfire = false, texture1 = [[largelaserdark]], texture2 = [[flaredark]], texture3 = [[flaredark]], texture4 = [[smallflaredark]], thickness = 10.4024486300101, tileLength = 300, tolerance = 10000, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 2250, }, FAKE_LASER = { name = [[Fake High-Energy Laserbeam]], areaOfEffect = 14, beamTime = 0.8, beamttl = 1, coreThickness = 0.5, craterBoost = 0, craterMult = 0, damage = { default = 300, subs = 15, }, explosionGenerator = [[custom:flash1bluedark]], fireStarter = 90, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 10.4, minIntensity = 1, noSelfDamage = true, projectiles = 5, range = 550, reloadtime = 6, rgbColor = [[0 0 1]], scrollSpeed = 5, soundStart = [[weapon/laser/heavy_laser3]], soundStartVolume = 3, sweepfire = false, texture1 = [[largelaserdark]], texture2 = [[flaredark]], texture3 = [[flaredark]], texture4 = [[smallflaredark]], thickness = 10.4024486300101, tileLength = 300, tolerance = 10000, turret = true, waterWeapon = true, weaponType = [[BeamLaser]], weaponVelocity = 2250, }, }, featureDefs = { DEAD = { description = [[Wreckage - Grizzly]], blocking = true, damage = 9000, energy = 0, featureDead = [[HEAP]], footprintX = 4, footprintZ = 4, metal = 800, object = [[amphassault_wreck.s3o]], reclaimable = true, reclaimTime = 800, }, HEAP = { description = [[Debris - Grizzly]], blocking = false, damage = 9000, energy = 0, footprintX = 4, footprintZ = 4, metal = 400, object = [[debris4x4c.s3o]], reclaimable = true, reclaimTime = 400, }, }, } return lowerkeys({ amphassault = unitDef })
gpl-2.0
jayman39tx/naev
dat/ai/tpl/scout.lua
5
2375
include("dat/ai/include/basic.lua") -- Variables planet_dist = 1500 -- distance to keep from planets enemy_dist = 800 -- distance to keep from enemies -- Required control rate control_rate = 2 -- Required "control" function function control () task = ai.taskname() if task == nil or task == "idle" then enemy = ai.getenemy() -- There is an enemy if enemy ~= nil then if ai.dist(enemy) < enemy_dist or ai.haslockon() then ai.pushtask("runaway", enemy) return end end -- nothing to do so check if we are too far form the planet (if there is one) if mem.approach == nil then local planet = ai.rndplanet() if planet ~= nil then mem.approach = planet:pos() end end planet = mem.approach if planet ~= nil then if ai.dist(planet) > planet_dist then ai.pushtask("approach") return end end -- Go idle if no task if task == nil then ai.pushtask("idle") return end -- Check if we are near enough elseif task == "approach" then planet = mem.approach if ai.dist( planet ) < planet_dist + ai.minbrakedist() then ai.poptask() ai.pushtask("idle") return end -- Check if we need to run more elseif task == "runaway" then enemy = ai.target() if ai.dist(enemy) > enemy_dist and ai.haslockon() == false then ai.poptask() return end end end -- Required "attacked" function function attacked ( attacker ) task = ai.taskname() -- Start running away if task ~= "runaway" then ai.pushtask("runaway", attacker) elseif task == "runaway" then if ai.target() ~= attacker then -- Runaway from the new guy ai.poptask() ai.pushtask("runaway", attacker) end end end -- Required "create" function function create () end -- Effectively does nothing function idle () if ai.isstopped() == false then ai.brake() end end -- Approaches the target function approach () target = mem.approach dir = ai.face(target) dist = ai.dist(target) -- See if should accel or brake if dist > planet_dist then ai.accel() else ai.poptask() ai.pushtask("idle") end end
gpl-3.0
KayMD/Illarion-Content
monster/base/quests.lua
4
15012
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --Generic 'Kill X monsters' quests by Estralis Seborian local common = require("base.common") local M = {} --TEMPLATE TO ADD A QUEST TO function iniQuests() --local id=NUMBER; --ID of the quest --germanTitle[id]="GERMAN TITLE"; --Title of the quest in german --englishTitle[id]="ENGLISH TITLE"; --Title of the quest in english --NPCName[id]="Miggs"; --This is the name of the NPC who gives out the quest --statusId[id]=NUMBER; --the queststatus as used by the NPC --germanRace[id]="stinkige Gullimumien"; --free description of the foes in german --englishRace[id]="smelly sewer mummies"; --free description of the foes in english --table.insert(questList[MONSTERID],id); --Insert the quest into the quest list of the monster race that has to be slain. You can add multiple monsters this way. --minimumQueststatus[id]=NUMBER1; --quest is only active with this queststatus and above. Each monster slain adds +1. Use a value > 0! --maximumQueststatus[id]=NUMBER2; --quest is finished if this queststatus is reached, no kill are counted anymore. Difference between NUMBER1 and NUMBER2 is the number of monsters that have to be slain --questLocation[id]=position(X,Y,Z); --a position around which the monsters have to be slain, e.g. centre of a dungeon or forest --radius[id]=RADIUS; --in this radius around the questlocation, kills are counted valid --Comment: If you want an NPC to give out multiple quests, you can do it like this: --Quest 1: To accept quest 1, set queststatus to 1 with the NPC. Use queststatus 1->11 to count 10 monsters. If the quest is finished, set queststatus to 12 with the NPC. --Quest 2: To accept quest 2, set queststatus to 13 with the NPC. Use queststatus 13->18 to count 5 monsters. If the quest is finished, set queststatus to 19 with the NPC. --Quest 3: To accept quest 3, set queststatus to 20 with the NPC. Use queststatus 20->21 to count 1 monster. If the quest is finished, set queststatus to 22 with the NPC. local quests = {} local questsByMonsterId = {} local questsByMonsterGroupId = {} local questsByRaceId = {} local function _isNumber(value) return type(value) == "number" end local function _isTable(value) return type(value) == "table" end local function _isFunction(value) return type(value) == "function" end local function _isString(value) return type(value) == "string" end local function registerQuest(quest, monsterIds, groupIds, raceIds) if not _isTable(quest) then error("Tried to insert a illegal structure as quest: Not a table") end if not _isFunction(quest.check) or not _isFunction(quest.execute) then error("Tried to insert a illegal structure as quest: Required check and execute functions not present") end table.insert(quests, quest) local index = #quests if monsterIds ~= nil then if _isTable(monsterIds) then for _, id in pairs(monsterIds) do local numberId = tonumber(id) if questsByMonsterId[numberId] == nil then questsByMonsterId[numberId] = {} end table.insert(questsByMonsterId[numberId], index) end else error("The list of monster IDs is expected to be a table of IDs.") end end if groupIds ~= nil then if _isTable(groupIds) then for _, id in pairs(groupIds) do local numberId = tonumber(id) if questsByMonsterGroupId[numberId] == nil then questsByMonsterGroupId[numberId] = {} end table.insert(questsByMonsterGroupId[numberId], index) end else error("The list of group IDs is expected to be a table of IDs.") end end if raceIds ~= nil then if _isTable(raceIds) then for _, id in pairs(raceIds) do local numberId = tonumber(id) if questsByRaceId[numberId] == nil then questsByRaceId[numberId] = {} end table.insert(questsByRaceId[numberId], index) end else error("The list of race IDs is expected to be a table of IDs.") end end end function M.addQuest(params) if not _isTable(params) then error("Quest data for the quest to add is missing.") end local questId if not _isNumber(params.questId) then error("The quest ID is required to be a number. It is the ID of the quest progress.") else questId = tonumber(params.questId) end local checkQuest if _isFunction(params.check) then checkQuest = params.check else local questLocations if _isTable(params.location) then questLocations = {params.location} elseif _isTable(params.locations) then questLocations = params.locations else error("One or multiple locations for the quests are required.") end for _, location in pairs(questLocations) do if not _isTable(location) then error("Location is not properly stored in a table.") end if location.position == nil or not _isNumber(location.radius) then error("Each location definition requires a position and a radius to be valid.") end end local minimalStatus, maximalStatus if _isTable(params.queststatus) then if _isNumber(params.queststatus.from) and _isNumber(params.queststatus.to) then minimalStatus = tonumber(params.queststatus.from) maximalStatus = tonumber(params.queststatus.to) elseif _isNumber(params.queststatus.min) and _isNumber(params.queststatus.max) then minimalStatus = tonumber(params.queststatus.min) maximalStatus = tonumber(params.queststatus.max) elseif _isNumber(params.queststatus[1]) and _isNumber(params.queststatus[2]) then minimalStatus = tonumber(params.queststatus[1]) maximalStatus = tonumber(params.queststatus[2]) else error("Failed to read the quest status range.") end elseif _isNumber(params.queststatus) then minimalStatus = tonumber(params.queststatus) maximalStatus = tonumber(params.queststatus) else error("Failed to read the required queststatus parameter.") end if minimalStatus > maximalStatus or minimalStatus < 0 then error("Quest status values are out of range.") end checkQuest = function(player, monster) if not player:isInRange(monster, 12) then -- Monster is too far away. Something went wrong return false end for _, location in pairs(questLocations) do if player:isInRangeToPosition(location.position, location.radius) then local currentStatus = player:getQuestProgress(questId); return currentStatus >= minimalStatus and currentStatus < maximalStatus end end return false end end local executeQuest if _isFunction(params.execute) then executeQuest = params.execute else executeQuest = function(player, monster) local currentStatus = player:getQuestProgress(questId); player:setQuestProgress(questId, currentStatus + 1) end end local reportQuest if _isFunction(params.report) then reportQuest = params.report else local minimalStatus, maximalStatus if _isTable(params.queststatus) then if _isNumber(params.queststatus.from) and _isNumber(params.queststatus.to) then minimalStatus = tonumber(params.queststatus.from) maximalStatus = tonumber(params.queststatus.to) elseif _isNumber(params.queststatus.min) and _isNumber(params.queststatus.max) then minimalStatus = tonumber(params.queststatus.min) maximalStatus = tonumber(params.queststatus.max) elseif _isNumber(params.queststatus[1]) and _isNumber(params.queststatus[2]) then minimalStatus = tonumber(params.queststatus[1]) maximalStatus = tonumber(params.queststatus[2]) else error("Failed to read the quest status range.") end elseif _isNumber(params.queststatus) then minimalStatus = tonumber(params.queststatus) maximalStatus = tonumber(params.queststatus) else error("Failed to read the required queststatus parameter.") end if minimalStatus > maximalStatus or minimalStatus < 0 then error("Quest status values are out of range.") end local titleGerman, titleEnglish if _isTable(params.questTitle) then if _isString(params.questTitle.german) and _isString(params.questTitle.english) then titleGerman = params.questTitle.german titleEnglish = params.questTitle.english elseif _isString(params.questTitle[Player.german]) and _isString(params.questTitle[Player.english]) then titleGerman = params.questTitle[Player.german] titleEnglish = params.questTitle[Player.english] end elseif _isString(params.questTitle) then titleGerman = params.questTitle titleEnglish = params.questTitle else error("Failed to read the required title of the quest.") end local monsterNameGerman, monsterNameEnglish if _isTable(params.monsterName) then local germanParams = params.monsterName.german or params.monsterName[Player.german] local englishParams = params.monsterName.english or params.monsterName[Player.english] if _isString(germanParams) then monsterNameGerman = germanParams else error("Failed to read the german part of the monster name.") end if _isString(englishParams) then monsterNameEnglish = englishParams else error("Failed to read the english part of the monster name.") end elseif _isString(params.monsterName) then monsterNameGerman = params.monsterName monsterNameEnglish = params.monsterName else error("Failed to read the required name of the monster.") end local npcName if _isString(params.npcName) then npcName = params.npcName else error("Failed to read the required NPC name.") end local totalCount = maximalStatus - minimalStatus reportQuest = function(player, monster) local currentStatus = player:getQuestProgress(questId); if currentStatus >= maximalStatus then --quest finished local germanFormat, englishFormat if maximalStatus == minimalStatus + 1 then -- only a single monster to beat germanFormat = "[Queststatus] %s: Du hast %s besiegt. Kehre zu %s zurück, um deine Belohnung zu erhalten." englishFormat = "[Quest status] %s: You have slain %s. Return to %s to claim your reward." else germanFormat = "[Queststatus] %s: Du hast genug %s besiegt. Kehre zu %s zurück, um deine Belohnung zu erhalten." englishFormat = "[Quest status] %s: You have slain enough %s. Return to %s to claim your reward." end common.InformNLS(player, germanFormat:format(titleGerman, monsterNameGerman, npcName), englishFormat:format(titleEnglish, monsterNameEnglish, npcName)); else --quest not finished local germanFormat = "[Queststatus] %s: Du hast %d von %d %s besiegt." local englishFormat = "[Quest status] %s: You have slain %d of %d %s." local doneCount = currentStatus - minimalStatus common.InformNLS(player, germanFormat:format(titleGerman, doneCount, totalCount, monsterNameGerman), englishFormat:format(titleEnglish, doneCount, totalCount, monsterNameEnglish)); end end end local quest = {} function quest.check(player, monster) return checkQuest(player, monster) end function quest.execute(player, monster) executeQuest(player, monster) reportQuest(player, monster) end registerQuest(quest, params.monsterIds, params.monsterGroupIds, params.raceIds) end function M.checkQuest(player, monster) local monsterId = monster:getMonsterType() local monsterGroupId = math.floor((monsterId - 1) / 10) local raceId = monster:getRace() local possibleQuests = {} if questsByMonsterId[monsterId] ~= nil then for _, questId in pairs(questsByMonsterId[monsterId]) do possibleQuests[questId] = true end end if questsByMonsterGroupId[monsterGroupId] ~= nil then for _, questId in pairs(questsByMonsterGroupId[monsterGroupId]) do possibleQuests[questId] = true end end if questsByRaceId[raceId] ~= nil then for _, questId in pairs(questsByRaceId[raceId]) do possibleQuests[questId] = true end end -- All candidates are assembled. Now check the ones that execute. local checkedQuests = {} for questId, _ in pairs(possibleQuests) do local quest = quests[questId] if quest.check(player, monster) then table.insert(checkedQuests, quest) end end for _, quest in pairs(checkedQuests) do quest.execute(player, monster) end end return M
agpl-3.0
hossein101/Darkhand
bot/darkhandbot.lua
1
10014
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin" }, sudo_users = {194573293,144132967},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Darkhand - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/hossein101/Darkhand Admins @DaRkHaNd0098 ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
nobie/sesame_fw
feeds/luci/applications/luci-statistics/dist/usr/lib/lua/luci/model/cbi/luci_statistics/email.lua
78
1934
--[[ Luci configuration model for statistics - collectd email plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("E-Mail Plugin Configuration"), translate( "The email plugin creates a unix socket which can be used " .. "to transmit email-statistics to a running collectd daemon. " .. "This plugin is primarily intended to be used in conjunction " .. "with Mail::SpamAssasin::Plugin::Collectd but can be used in " .. "other ways as well." )) -- collectd_email config section s = m:section( NamedSection, "collectd_email", "luci_statistics" ) -- collectd_email.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_email.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile", translate("Socket file") ) socketfile.default = "/var/run/collect-email.sock" socketfile:depends( "enable", 1 ) -- collectd_email.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup", translate("Socket group") ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_email.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) -- collectd_email.maxconns (MaxConns) maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") ) maxconns.default = 5 maxconns.isinteger = true maxconns.rmempty = true maxconns.optional = true maxconns:depends( "enable", 1 ) return m
gpl-2.0
litnimax/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua
78
1934
--[[ Luci configuration model for statistics - collectd email plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("E-Mail Plugin Configuration"), translate( "The email plugin creates a unix socket which can be used " .. "to transmit email-statistics to a running collectd daemon. " .. "This plugin is primarily intended to be used in conjunction " .. "with Mail::SpamAssasin::Plugin::Collectd but can be used in " .. "other ways as well." )) -- collectd_email config section s = m:section( NamedSection, "collectd_email", "luci_statistics" ) -- collectd_email.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_email.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile", translate("Socket file") ) socketfile.default = "/var/run/collect-email.sock" socketfile:depends( "enable", 1 ) -- collectd_email.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup", translate("Socket group") ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_email.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) -- collectd_email.maxconns (MaxConns) maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") ) maxconns.default = 5 maxconns.isinteger = true maxconns.rmempty = true maxconns.optional = true maxconns:depends( "enable", 1 ) return m
apache-2.0
gajop/Zero-K
units/armkam.lua
1
6213
unitDef = { unitname = [[armkam]], name = [[Banshee]], description = [[Raider Gunship]], acceleration = 0.18, brakeRate = 0.2, buildCostEnergy = 220, buildCostMetal = 220, builder = false, buildPic = [[ARMKAM.png]], buildTime = 220, canAttack = true, canFly = true, canGuard = true, canMove = true, canPatrol = true, canStop = true, canSubmerge = false, category = [[GUNSHIP]], collide = true, corpse = [[DEAD]], cruiseAlt = 100, customParams = { airstrafecontrol = [[1]], description_bp = [[Aeronave agressora]], description_fr = [[ADAV Pilleur]], description_de = [[Plünder Kampfhubschrauber]], description_pl = [[Lekki statek powietrzny]], helptext = [[The Banshee is a light gunship. Its high speed and decent damage makes it excellent for quickly taking out enemy economy or inaccurate units like assaults. However, it flies close to the ground and has a short range, meaning even other raiders can engage it on an equal footing. Like any raider, the Banshee should avoid riots and static defense.]], helptext_bp = [[Banshee é a aeronave agressora leve de Nova. Tem uma resist?ncia decente mas causa pouco dano. Funciona bem contra poderio anti-aério pouco resistente, sendo capaz de destruílo e ent?o atacar o resto do inimigo com impunidade por algum tempo, mas funciona mal contra poderio anti-aéreo pesado como metralhadoras anti-aéreas. Pode facilmente acertar unidades móveis e constitui defesa excelente contra inimigos que n?o incluem unidades anti-aéreas em seus grupos de ataque.]], helptext_fr = [[Le Banshee est un ADAV l?ger, un blindage l?ger et peu de d?g?ts en font la hantise des d?buts de conflits. Envoy? dans une base non pr?par?e ou contre une arm?e sans d?fense Anti Air, son attaque rapide est bien souvent fatale.]], helptext_de = [[Der Banshee ist ein leichter Kampfhubschrauber. Er besitzt nur wenig Ausdauer und macht wenig DPS. Er ist gut für direkte Attacken auf die Verteidiger (z.B. um Luftabwehr auszuschalten). Er trifft bewegte Einheiten sehr gut und erweist sich auch bei Verteidigung gegen Gegner ohne Luftabwehr als sehr nützlich.]], helptext_pl = [[Banshee ma bardzo duza predkosc i dosc dobre obrazenia, co pozwala na szybkie najazdy w celu zniszczenia budynkow ekonomicznych przeciwnika lub niecelnych jednostek, na przyklad szturmowych. Pulap lotu Banshee jest jednak na tyle niski, ze moze zostac ostrzelana nawet przez jednostki o krotszym zasiegu.]], modelradius = [[18]], }, explodeAs = [[GUNSHIPEX]], floater = true, footprintX = 2, footprintZ = 2, hoverAttack = true, iconType = [[gunshipraider]], idleAutoHeal = 10, idleTime = 150, maxDamage = 860, maxVelocity = 6.5, minCloakDistance = 75, noChaseCategory = [[TERRAFORM SUB]], objectName = [[banshee.s3o]], script = [[armkam.lua]], seismicSignature = 0, selfDestructAs = [[GUNSHIPEX]], sfxtypes = { explosiongenerators = { [[custom:VINDIBACK]], }, }, sightDistance = 500, turnRate = 693, weapons = { { def = [[LASER]], mainDir = [[0 0 1]], maxAngleDif = 90, onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { LASER = { name = [[Light Laserbeam]], areaOfEffect = 8, avoidFeature = false, beamTime = 0.12, collideFriendly = false, coreThickness = 0.3, craterBoost = 0, craterMult = 0, --cylinderTargeting = 1, customparams = { stats_hide_damage = 1, -- continuous laser stats_hide_reload = 1, light_color = [[1 0.25 0.25]], light_radius = 175, }, damage = { default = 6.83, -- 6.15 subs = 0.315, }, explosionGenerator = [[custom:flash1red]], --heightMod = 0.5, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, largeBeamLaser = true, laserFlareSize = 2, minIntensity = 1, noSelfDamage = true, range = 240, reloadtime = 0.11, rgbColor = [[1 0 0]], soundStart = [[weapon/laser/laser_burn9]], sweepfire = false, texture1 = [[largelaser]], texture2 = [[flare]], texture3 = [[flare]], texture4 = [[smallflare]], thickness = 2, tolerance = 2000, turret = true, weaponType = [[BeamLaser]], }, }, featureDefs = { DEAD = { description = [[Wreckage - Banshee]], blocking = true, damage = 860, energy = 0, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, metal = 88, object = [[banshee_dead.s3o]], reclaimable = true, reclaimTime = 88, }, HEAP = { description = [[Debris - Banshee]], blocking = false, damage = 860, energy = 0, footprintX = 2, footprintZ = 2, metal = 44, object = [[debris2x2a.s3o]], reclaimable = true, reclaimTime = 44, }, }, } return lowerkeys({ armkam = unitDef })
gpl-2.0
KayMD/Illarion-Content
triggerfield/galmair_bridges_660.lua
2
7563
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (498,201,0,'triggerfield.galmair_bridges2_660'); -- INSERT INTO triggerfields VALUES (497,201,0,'triggerfield.galmair_bridges2_660'); -- INSERT INTO triggerfields VALUES (496,207,0,'triggerfield.galmair_bridges2_660'); local common = require("base.common") local factions = require("base.factions") local deathaftertime = require("lte.deathaftertime") local longterm_cooldown = require("lte.longterm_cooldown") local character = require("base.character") local M = {} local monster = {} ---monster, numbers are archers -> excluded currently monster[1]={1,2,3,4,5}; --human monster[2]={11,12,13,14}; --dwarf 15 monster[3]={21,22,23,24}; --halfling 25 monster[4]={31,32,33,34}; --elf 35 monster[5]={41,42,43,45}; --orc 44 monster[6]={51,52,53,54,55}; -- lizard monster[7]={91,92,93,95,791,792}; -- troll 94,802,795,796 monster[8]={101,102,103,104,106,151,152,171,172,173}; -- mummy monster[9]={111,112,113,114,115}; --skeleton monster[10]={573,574,576,577,578}; --rats 575 monster[11]={891,892,893,901,902,903}; --Imp monster[12]={782,783}; --golden skeleton 784 monster[13]={301,303,304,305,306}; --golem monster[14]={851,852,853,861,862,863,871,872,873,881,882,883}; --hellhound monster[15]={62,63,64,65,66}; -- drow 61,65 monster[16]={201,202,203,204}; --demon skeleton 205 local shutup local luckybunch function M.setAmbush(ambushName, ambushState) if ambushState ~= true then ambushState = false end ScriptVars:set(ambushName,tostring(ambushState)) ScriptVars:save() end function M.isAmbush(ambushName) local foundValue, value = ScriptVars:find(ambushName) if value == "true" then return true else return false end end function M.setLastAmbush(ambushName) local currentTime = common.GetCurrentTimestamp() local scriptVar = ambushName.."Last" ScriptVars:set(scriptVar,tostring(currentTime)) ScriptVars:save() end function M.getTimeSinceLastAmbush(ambushName) local currentTime = common.GetCurrentTimestamp() local scriptVar = ambushName.."Last" local foundValue, value = ScriptVars:find(scriptVar) local lastTime = tonumber(value) if common.IsNilOrEmpty(lastTime) then lastTime = 0 end return currentTime - lastTime end function M.triggerAmbush(char, monsterPositions) if char:getType() ~= Character.player then --Monsters will be ingored return false end if char:getQuestProgress(660) ~= 0 then --lte check return false end local chance if factions.getMembership(char) == 3 then --set chance for Galmairians and non-Galmairians chance = 20 else chance = 5 end local fighter = false if (char:getSkill(Character.punctureWeapons)>=40) or (char:getSkill(Character.distanceWeapons)>=40) or (char:getSkill(Character.slashingWeapons)>=40) or (char:getSkill(Character.concussionWeapons)>=40) or (char:getSkill(Character.wrestling)>=40) then --check if we have a fighter fighter = true end if math.random(1,100)< chance and char:increaseAttrib("hitpoints",0)>8000 then --Chance of 1% and Hitpoints above 8000 if factions.getMembership(char) ~= 3 and (char:getSkill(Character.parry)<=30) or factions.getMembership(char) ~= 3 and not fighter then --Newbie and non-fighter protection for non-Galmairian return false end local level if (char:getSkill(Character.parry)<=80) then --check of skills of fighter level = math.random(1,11) --selection of lower monsters for average fighter else level = math.random(1,16) --selection of all monsters for good fighter end local enemy for i=1, #monsterPositions do enemy = monster[level][math.random(1,#monster[level])] world:gfx(41,monsterPositions[i]) world:createMonster(enemy,monsterPositions[i],0); end char:inform("Oh nein, ein Hinterhalt!", "Oh no, an ambush!") --message for player char:setQuestProgress(660,math.random(300,600)) --lte set return true else return false end end function M.fightAmbush(char) local luckybunch = false local hero = world:getPlayersInRangeOf(char.pos, 20); --lets see if there is a player around for i,player in ipairs(hero) do if factions.getMembership(player) == 3 then --check if galmairians are there luckybunch = true --if non-galmairians are together with galmairians end end if luckybunch then local monsters = world:getMonstersInRangeOf(char.pos, 35); --get all monster in player range for i,mon in ipairs(monsters) do character.DeathAfterTime(mon,math.random(5,10),0,33,true) --kill all monsters end end for i,player in ipairs(hero) do if factions.getMembership(player) == 3 then --check if galmairians are there player:inform("Bevor du auch noch reagieren kannst, schießen Pfeile an dir vorbei und töten deine Widersacher. Du blickst in die Richtung von wo die Pfeile kamen und siehst die Wachen von Galmair dir mit ihren Armbrüsten zuwinken. Gut, dass du dem Don deine Steuern zahlst und er dich beschützt!","Even before you are able to react, arrows shoot around you and take down your enemies. You look to the direction the arrows originated from and see guards of Galmair waving to you with their crossbows. Good, you have paid your taxes to the Don and he protects you!") --praise the don message for the player elseif luckybunch then -- glamairians are here...lucky you player:inform("Bevor du auch noch reagieren kannst, schießen Pfeile an dir vorbei und töten deine Widersacher. Du blickst in die Richtung von wo die Pfeile kamen und siehst die Wachen von Galmair euch mit ihren Armbrüsten zuwinken. Gut, dass du jemanden dabei hattest, der dem Don Steuern zahlst und daher beschützt wird vom Don!", "Even before you are able to react, arrows shoot around you and take down your enemies. You look to the direction the arrows originated from and see guards of Galmair waving to you with their crossbows. Good, you have someone with you who has paid taxes to the Don and is thus protected by the Don!") --wäähh wrong faction but together with friends message for the player else -- no galmairians are here...bad luck player:inform("Du wirfst einen Blick zurück zur Stadt von Galmair und siehst die Wachen dort wie sie dich und dein Schicksal beobachten. Was, wenn du nur dem Don deine Steuern zahlen würdest?", "You look back to the town of Galmair and see guards watching your fate. What if you had only paid your taxes to the Don?") --wäähh wrong faction message for the player end player:setQuestProgress(660,math.random(300,600)) --lte set for all players around end end return M
agpl-3.0
wangtianhang/UnityLuaTest
UnityLuaTest/Luajit/jit/p.lua
55
9135
---------------------------------------------------------------------------- -- LuaJIT profiler. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module is a simple command line interface to the built-in -- low-overhead profiler of LuaJIT. -- -- The lower-level API of the profiler is accessible via the "jit.profile" -- module or the luaJIT_profile_* C API. -- -- Example usage: -- -- luajit -jp myapp.lua -- luajit -jp=s myapp.lua -- luajit -jp=-s myapp.lua -- luajit -jp=vl myapp.lua -- luajit -jp=G,profile.txt myapp.lua -- -- The following dump features are available: -- -- f Stack dump: function name, otherwise module:line. Default mode. -- F Stack dump: ditto, but always prepend module. -- l Stack dump: module:line. -- <number> stack dump depth (callee < caller). Default: 1. -- -<number> Inverse stack dump depth (caller > callee). -- s Split stack dump after first stack level. Implies abs(depth) >= 2. -- p Show full path for module names. -- v Show VM states. Can be combined with stack dumps, e.g. vf or fv. -- z Show zones. Can be combined with stack dumps, e.g. zf or fz. -- r Show raw sample counts. Default: show percentages. -- a Annotate excerpts from source code files. -- A Annotate complete source code files. -- G Produce raw output suitable for graphical tools (e.g. flame graphs). -- m<number> Minimum sample percentage to be shown. Default: 3. -- i<number> Sampling interval in milliseconds. Default: 10. -- ---------------------------------------------------------------------------- -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local profile = require("jit.profile") local vmdef = require("jit.vmdef") local math = math local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor local sort, format = table.sort, string.format local stdout = io.stdout local zone -- Load jit.zone module on demand. -- Output file handle. local out ------------------------------------------------------------------------------ local prof_ud local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth local prof_ann, prof_count1, prof_count2, prof_samples local map_vmmode = { N = "Compiled", I = "Interpreted", C = "C code", G = "Garbage Collector", J = "JIT Compiler", } -- Profiler callback. local function prof_cb(th, samples, vmmode) prof_samples = prof_samples + samples local key_stack, key_stack2, key_state -- Collect keys for sample. if prof_states then if prof_states == "v" then key_state = map_vmmode[vmmode] or vmmode else key_state = zone:get() or "(none)" end end if prof_fmt then key_stack = profile.dumpstack(th, prof_fmt, prof_depth) key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x) return vmdef.ffnames[tonumber(x)] end) if prof_split == 2 then local k1, k2 = key_stack:match("(.-) [<>] (.*)") if k2 then key_stack, key_stack2 = k1, k2 end elseif prof_split == 3 then key_stack2 = profile.dumpstack(th, "l", 1) end end -- Order keys. local k1, k2 if prof_split == 1 then if key_state then k1 = key_state if key_stack then k2 = key_stack end end elseif key_stack then k1 = key_stack if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end end -- Coalesce samples in one or two levels. if k1 then local t1 = prof_count1 t1[k1] = (t1[k1] or 0) + samples if k2 then local t2 = prof_count2 local t3 = t2[k1] if not t3 then t3 = {}; t2[k1] = t3 end t3[k2] = (t3[k2] or 0) + samples end end end ------------------------------------------------------------------------------ -- Show top N list. local function prof_top(count1, count2, samples, indent) local t, n = {}, 0 for k in pairs(count1) do n = n + 1 t[n] = k end sort(t, function(a, b) return count1[a] > count1[b] end) for i=1,n do local k = t[i] local v = count1[k] local pct = floor(v*100/samples + 0.5) if pct < prof_min then break end if not prof_raw then out:write(format("%s%2d%% %s\n", indent, pct, k)) elseif prof_raw == "r" then out:write(format("%s%5d %s\n", indent, v, k)) else out:write(format("%s %d\n", k, v)) end if count2 then local r = count2[k] if r then prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or (prof_depth < 0 and " -> " or " <- ")) end end end end -- Annotate source code local function prof_annotate(count1, samples) local files = {} local ms = 0 for k, v in pairs(count1) do local pct = floor(v*100/samples + 0.5) ms = math.max(ms, v) if pct >= prof_min then local file, line = k:match("^(.*):(%d+)$") if not file then file = k; line = 0 end local fl = files[file] if not fl then fl = {}; files[file] = fl; files[#files+1] = file end line = tonumber(line) fl[line] = prof_raw and v or pct end end sort(files) local fmtv, fmtn = " %3d%% | %s\n", " | %s\n" if prof_raw then local n = math.max(5, math.ceil(math.log10(ms))) fmtv = "%"..n.."d | %s\n" fmtn = (" "):rep(n).." | %s\n" end local ann = prof_ann for _, file in ipairs(files) do local f0 = file:byte() if f0 == 40 or f0 == 91 then out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file)) break end local fp, err = io.open(file) if not fp then out:write(format("====== ERROR: %s: %s\n", file, err)) break end out:write(format("\n====== %s ======\n", file)) local fl = files[file] local n, show = 1, false if ann ~= 0 then for i=1,ann do if fl[i] then show = true; out:write("@@ 1 @@\n"); break end end end for line in fp:lines() do if line:byte() == 27 then out:write("[Cannot annotate bytecode file]\n") break end local v = fl[n] if ann ~= 0 then local v2 = fl[n+ann] if show then if v2 then show = n+ann elseif v then show = n elseif show+ann < n then show = false end elseif v2 then show = n+ann out:write(format("@@ %d @@\n", n)) end if not show then goto next end end if v then out:write(format(fmtv, v, line)) else out:write(format(fmtn, line)) end ::next:: n = n + 1 end fp:close() end end ------------------------------------------------------------------------------ -- Finish profiling and dump result. local function prof_finish() if prof_ud then profile.stop() local samples = prof_samples if samples == 0 then if prof_raw ~= true then out:write("[No samples collected]\n") end return end if prof_ann then prof_annotate(prof_count1, samples) else prof_top(prof_count1, prof_count2, samples, "") end prof_count1 = nil prof_count2 = nil prof_ud = nil end end -- Start profiling. local function prof_start(mode) local interval = "" mode = mode:gsub("i%d*", function(s) interval = s; return "" end) prof_min = 3 mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end) prof_depth = 1 mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end) local m = {} for c in mode:gmatch(".") do m[c] = c end prof_states = m.z or m.v if prof_states == "z" then zone = require("jit.zone") end local scope = m.l or m.f or m.F or (prof_states and "" or "f") local flags = (m.p or "") prof_raw = m.r if m.s then prof_split = 2 if prof_depth == -1 or m["-"] then prof_depth = -2 elseif prof_depth == 1 then prof_depth = 2 end elseif mode:find("[fF].*l") then scope = "l" prof_split = 3 else prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0 end prof_ann = m.A and 0 or (m.a and 3) if prof_ann then scope = "l" prof_fmt = "pl" prof_split = 0 prof_depth = 1 elseif m.G and scope ~= "" then prof_fmt = flags..scope.."Z;" prof_depth = -100 prof_raw = true prof_min = 0 elseif scope == "" then prof_fmt = false else local sc = prof_split == 3 and m.f or m.F or scope prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ") end prof_count1 = {} prof_count2 = {} prof_samples = 0 profile.start(scope:lower()..interval, prof_cb) prof_ud = newproxy(true) getmetatable(prof_ud).__gc = prof_finish end ------------------------------------------------------------------------------ local function start(mode, outfile) if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stdout end prof_start(mode or "f") end -- Public module functions. return { start = start, -- For -j command line option. stop = prof_finish }
mit
nobie/sesame_fw
feeds/luci/libs/httpclient/luasrc/httpclient.lua
41
9111
--[[ LuCI - Lua Development Framework Copyright 2009 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$ ]]-- require "nixio.util" local nixio = require "nixio" local ltn12 = require "luci.ltn12" local util = require "luci.util" local table = require "table" local http = require "luci.http.protocol" local date = require "luci.http.protocol.date" local type, pairs, ipairs, tonumber = type, pairs, ipairs, tonumber local unpack = unpack module "luci.httpclient" function chunksource(sock, buffer) buffer = buffer or "" return function() local output local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n") while not count and #buffer <= 1024 do local newblock, code = sock:recv(1024 - #buffer) if not newblock then return nil, code end buffer = buffer .. newblock _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n") end count = tonumber(count, 16) if not count then return nil, -1, "invalid encoding" elseif count == 0 then return nil elseif count + 2 <= #buffer - endp then output = buffer:sub(endp+1, endp+count) buffer = buffer:sub(endp+count+3) return output else output = buffer:sub(endp+1, endp+count) buffer = "" if count - #output > 0 then local remain, code = sock:recvall(count-#output) if not remain then return nil, code end output = output .. remain count, code = sock:recvall(2) else count, code = sock:recvall(count+2-#buffer+endp) end if not count then return nil, code end return output end end end function request_to_buffer(uri, options) local source, code, msg = request_to_source(uri, options) local output = {} if not source then return nil, code, msg end source, code = ltn12.pump.all(source, (ltn12.sink.table(output))) if not source then return nil, code end return table.concat(output) end function request_to_source(uri, options) local status, response, buffer, sock = request_raw(uri, options) if not status then return status, response, buffer elseif status ~= 200 and status ~= 206 then return nil, status, buffer end if response.headers["Transfer-Encoding"] == "chunked" then return chunksource(sock, buffer) else return ltn12.source.cat(ltn12.source.string(buffer), sock:blocksource()) end end -- -- GET HTTP-resource -- function request_raw(uri, options) options = options or {} local pr, auth, host, port, path if uri:find("@") then pr, auth, host, port, path = uri:match("(%w+)://(.+)@([%w-.]+):?([0-9]*)(.*)") else pr, host, port, path = uri:match("(%w+)://([%w-.]+):?([0-9]*)(.*)") end if not host then return nil, -1, "unable to parse URI" end if pr ~= "http" and pr ~= "https" then return nil, -2, "protocol not supported" end port = #port > 0 and port or (pr == "https" and 443 or 80) path = #path > 0 and path or "/" options.depth = options.depth or 10 local headers = options.headers or {} local protocol = options.protocol or "HTTP/1.1" headers["User-Agent"] = headers["User-Agent"] or "LuCI httpclient 0.1" if headers.Connection == nil then headers.Connection = "close" end if auth and not headers.Authorization then headers.Authorization = "Basic " .. nixio.bin.b64encode(auth) end local sock, code, msg = nixio.connect(host, port) if not sock then return nil, code, msg end sock:setsockopt("socket", "sndtimeo", options.sndtimeo or 15) sock:setsockopt("socket", "rcvtimeo", options.rcvtimeo or 15) if pr == "https" then local tls = options.tls_context or nixio.tls() sock = tls:create(sock) local stat, code, error = sock:connect() if not stat then return stat, code, error end end -- Pre assemble fixes if protocol == "HTTP/1.1" then headers.Host = headers.Host or host end if type(options.body) == "table" then options.body = http.urlencode_params(options.body) end if type(options.body) == "string" then headers["Content-Length"] = headers["Content-Length"] or #options.body headers["Content-Type"] = headers["Content-Type"] or "application/x-www-form-urlencoded" options.method = options.method or "POST" end if type(options.body) == "function" then options.method = options.method or "POST" end -- Assemble message local message = {(options.method or "GET") .. " " .. path .. " " .. protocol} for k, v in pairs(headers) do if type(v) == "string" or type(v) == "number" then message[#message+1] = k .. ": " .. v elseif type(v) == "table" then for i, j in ipairs(v) do message[#message+1] = k .. ": " .. j end end end if options.cookies then for _, c in ipairs(options.cookies) do local cdo = c.flags.domain local cpa = c.flags.path if (cdo == host or cdo == "."..host or host:sub(-#cdo) == cdo) and (cpa == path or cpa == "/" or cpa .. "/" == path:sub(#cpa+1)) and (not c.flags.secure or pr == "https") then message[#message+1] = "Cookie: " .. c.key .. "=" .. c.value end end end message[#message+1] = "" message[#message+1] = "" -- Send request sock:sendall(table.concat(message, "\r\n")) if type(options.body) == "string" then sock:sendall(options.body) elseif type(options.body) == "function" then local res = {options.body(sock)} if not res[1] then sock:close() return unpack(res) end end -- Create source and fetch response local linesrc = sock:linesource() local line, code, error = linesrc() if not line then sock:close() return nil, code, error end local protocol, status, msg = line:match("^([%w./]+) ([0-9]+) (.*)") if not protocol then sock:close() return nil, -3, "invalid response magic: " .. line end local response = { status = line, headers = {}, code = 0, cookies = {}, uri = uri } line = linesrc() while line and line ~= "" do local key, val = line:match("^([%w-]+)%s?:%s?(.*)") if key and key ~= "Status" then if type(response.headers[key]) == "string" then response.headers[key] = {response.headers[key], val} elseif type(response.headers[key]) == "table" then response.headers[key][#response.headers[key]+1] = val else response.headers[key] = val end end line = linesrc() end if not line then sock:close() return nil, -4, "protocol error" end -- Parse cookies if response.headers["Set-Cookie"] then local cookies = response.headers["Set-Cookie"] for _, c in ipairs(type(cookies) == "table" and cookies or {cookies}) do local cobj = cookie_parse(c) cobj.flags.path = cobj.flags.path or path:match("(/.*)/?[^/]*") if not cobj.flags.domain or cobj.flags.domain == "" then cobj.flags.domain = host response.cookies[#response.cookies+1] = cobj else local hprt, cprt = {}, {} -- Split hostnames and save them in reverse order for part in host:gmatch("[^.]*") do table.insert(hprt, 1, part) end for part in cobj.flags.domain:gmatch("[^.]*") do table.insert(cprt, 1, part) end local valid = true for i, part in ipairs(cprt) do -- If parts are different and no wildcard if hprt[i] ~= part and #part ~= 0 then valid = false break -- Wildcard on invalid position elseif hprt[i] ~= part and #part == 0 then if i ~= #cprt or (#hprt ~= i and #hprt+1 ~= i) then valid = false break end end end -- No TLD cookies if valid and #cprt > 1 and #cprt[2] > 0 then response.cookies[#response.cookies+1] = cobj end end end end -- Follow response.code = tonumber(status) if response.code and options.depth > 0 then if response.code == 301 or response.code == 302 or response.code == 307 and response.headers.Location then local nuri = response.headers.Location or response.headers.location if not nuri then return nil, -5, "invalid reference" end if not nuri:find("https?://") then nuri = pr .. "://" .. host .. ":" .. port .. nuri end options.depth = options.depth - 1 if options.headers then options.headers.Host = nil end sock:close() return request_raw(nuri, options) end end return response.code, response, linesrc(true), sock end function cookie_parse(cookiestr) local key, val, flags = cookiestr:match("%s?([^=;]+)=?([^;]*)(.*)") if not key then return nil end local cookie = {key = key, value = val, flags = {}} for fkey, fval in flags:gmatch(";%s?([^=;]+)=?([^;]*)") do fkey = fkey:lower() if fkey == "expires" then fval = date.to_unix(fval:gsub("%-", " ")) end cookie.flags[fkey] = fval end return cookie end function cookie_create(cookie) local cookiedata = {cookie.key .. "=" .. cookie.value} for k, v in pairs(cookie.flags) do if k == "expires" then v = date.to_http(v):gsub(", (%w+) (%w+) (%w+) ", ", %1-%2-%3 ") end cookiedata[#cookiedata+1] = k .. ((#v > 0) and ("=" .. v) or "") end return table.concat(cookiedata, "; ") end
gpl-2.0
nobie/sesame_fw
feeds/luci/applications/luci-vnstat/luasrc/model/cbi/vnstat.lua
90
2019
--[[ LuCI - Lua Configuration Interface Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" local nw = require "luci.model.network" local dbdir, line for line in io.lines("/etc/vnstat.conf") do dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']") if dbdir then break end end dbdir = dbdir or "/var/lib/vnstat" m = Map("vnstat", translate("VnStat"), translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s).")) m.submit = translate("Restart VnStat") m.reset = false nw.init(luci.model.uci.cursor_state()) local ifaces = { } local enabled = { } local iface if fs.access(dbdir) then for iface in fs.dir(dbdir) do if iface:sub(1,1) ~= '.' then ifaces[iface] = iface enabled[iface] = iface end end end for _, iface in ipairs(sys.net.devices()) do ifaces[iface] = iface end local s = m:section(TypedSection, "vnstat") s.anonymous = true s.addremove = false mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces")) mon_ifaces.template = "cbi/network_ifacelist" mon_ifaces.widget = "checkbox" mon_ifaces.cast = "table" mon_ifaces.noinactive = true mon_ifaces.nocreate = true function mon_ifaces.write(self, section, val) local i local s = { } if val then for _, i in ipairs(type(val) == "table" and val or { val }) do s[i] = true end end for i, _ in pairs(ifaces) do if not s[i] then fs.unlink(dbdir .. "/" .. i) fs.unlink(dbdir .. "/." .. i) end end if next(s) then m.uci:set_list("vnstat", section, "interface", utl.keys(s)) else m.uci:delete("vnstat", section, "interface") end end mon_ifaces.remove = mon_ifaces.write return m
gpl-2.0
Flourish-Team/Flourish
Premake/source/tests/base/test_include.lua
16
1678
-- -- tests/base/test_include.lua -- Test the include() function, for including external scripts -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("include") -- -- Setup and teardown -- function suite.teardown() -- clear the list of included files after each run io._includedFiles = { } end -- -- Tests -- function suite.include_findsPremakeFile_onFolderNameOnly() include (_TESTS_DIR .. "/folder") test.isequal("ok", p.captured()) end function suite.include_onExactFilename() include (_TESTS_DIR .. "/folder/premake5.lua") test.isequal("ok", p.captured()) end function suite.include_runsOnlyOnce_onMultipleIncludes() include (_TESTS_DIR .. "/folder/premake5.lua") include (_TESTS_DIR .. "/folder/premake5.lua") test.isequal("ok", p.captured()) end function suite.include_runsOnlyOnce_onMultipleIncludesWithDifferentPaths() include (_TESTS_DIR .. "/folder/premake5.lua") include (_TESTS_DIR .. "/../tests/folder/premake5.lua") test.isequal("ok", p.captured()) end function suite.includeexternal_runs() includeexternal (_TESTS_DIR .. "/folder/premake5.lua") test.isequal("ok", p.captured()) end function suite.includeexternal_runsAfterInclude() include (_TESTS_DIR .. "/folder/premake5.lua") includeexternal (_TESTS_DIR .. "/folder/premake5.lua") test.isequal("okok", p.captured()) end function suite.includeexternal_runsTwiceAfterInclude() include (_TESTS_DIR .. "/folder/premake5.lua") includeexternal (_TESTS_DIR .. "/folder/premake5.lua") includeexternal (_TESTS_DIR .. "/folder/premake5.lua") test.isequal("okokok", p.captured()) end
mit
tehran980/TeleSeed
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
gajop/Zero-K
scripts/factoryplane.lua
16
4552
include "constants.lua" local spGetUnitTeam = Spring.GetUnitTeam --pieces local base = piece "base" local bay = piece "bay" local narm1 = piece "narm1" local nano1 = piece "nano1" local emit1 = piece "emit1" local arm1b = piece "arm1b" local arm1 = piece "arm1" local arm1top = piece "arm1top" local arm1bot = piece "arm1bot" local pow1 = piece "pow1" local pow2 = piece "pow2" local plate = piece "plate" local nano2 = piece "nano2" local emit2 = piece "emit2" local door1 = piece "door1" local door2 = piece "door2" local fuelpad = piece "fuelpad" local padbase = piece "padbase" local pad1 = piece "pad1" local pad2 = piece "pad2" local pad3 = piece "pad3" local build = piece "build" local land = piece "land" --local vars local nanoPieces = {emit1,emit2} local nanoIdx = 1 local smokePiece = { piece "bay", piece "pad1", piece "fuelpad" } --opening animation local function Open() Signal(2) --kill the closing animation if it is in process --SetSignalMask(1) --set the signal to kill the opening animation Move(bay, 1, -18, 15) Turn(narm1, 1, 1.85, 0.75) Turn(nano1, 1, -1.309, 0.35) Turn(door1, 2, -0.611, 0.35) Sleep(600) Move(arm1b, 1, -11, 5) Turn(pow1, 3, -1.571, 0.8) WaitForTurn(door1, 2) Turn(door2, 2, 1.571, 0.9) Turn(arm1, 1, 1.3, 0.35) Turn(arm1top, 1, -0.873, 0.4) Turn(arm1bot, 1, 1.31, 0.5) Sleep(200) Turn(pow2, 1, 1.571, 1) WaitForTurn(door2, 2) Turn(narm1, 1, 1.466, 0.15) Move(plate, 3, 8.47, 3.2) Turn(door1, 2, 0, 0.15) Turn(nano2, 2, 0.698, 0.35) Sleep(500) Turn(arm1, 1, 0.524, 0.2) Sleep(150) -- SetUnitValue(COB.YARD_OPEN, 1) --Tobi said its not necessary SetUnitValue(COB.BUGGER_OFF, 1) SetUnitValue(COB.INBUILDSTANCE, 1) end --closing animation of the factory local function Close() Signal(1) --kill the opening animation if it is in process SetSignalMask(2) --set the signal to kill the closing animation -- SetUnitValue(COB.YARD_OPEN, 0) SetUnitValue(COB.BUGGER_OFF, 0) SetUnitValue(COB.INBUILDSTANCE, 0) Turn(narm1, 1, 1.85, 0.25) Sleep(800) Turn(arm1, 1, 1, 0.45) Move(plate, 3, 0, 3.2) Turn(door1, 2, -0.611, 0.15) Turn(nano2, 2, 0, 0.35) WaitForMove(plate, 3) Turn(arm1top, 1, 0, 0.4) Turn(arm1bot, 1, 0, 0.5) Turn(pow2, 1, 0, 1) Sleep(200) Turn(arm1, 1, 0, 0.3) Turn(door2, 2, 0, 0.9) WaitForTurn(door2, 2) Move(arm1b, 1, 0, 5) Turn(pow1, 3, 0, 1) Sleep(600) Turn(narm1, 1, 0, 0.75) Turn(nano1, 1, 0, 0.35) Turn(door1, 2, 0, 0.35) WaitForTurn(door1, 2) Move(bay, 1, 0, 11) WaitForMove(bay,1) end function padchange() while true do Sleep(1200) Hide(pad1) Show(pad2) Sleep(1200) Hide(pad2) Show(pad3) Sleep(1200) Hide(pad3) Show(pad2) Sleep(1200) Hide(pad2) Show(pad1) end end function script.Create() StartThread(SmokeUnit, smokePiece) Spring.SetUnitNanoPieces(unitID, nanoPieces) local buildprogress = select(5, Spring.GetUnitHealth(unitID)) while buildprogress < 1 do Sleep(250) buildprogress = select(5, Spring.GetUnitHealth(unitID)) end StartThread(padchange) end function script.QueryBuildInfo() return build end function script.QueryNanoPiece() if (nanoIdx == 2) then nanoIdx = 1 else nanoIdx = nanoIdx + 1 end local nano = nanoPieces[nanoIdx] --// send to LUPS GG.LUPS.QueryNanoPiece(unitID,unitDefID,spGetUnitTeam(unitID),nano) return nano end function script.QueryLandingPads() return { land } end function script.Activate () StartThread(Open) --animation needs its own thread because Sleep and WaitForTurn will not work otherwise end function script.Deactivate () StartThread(Close) end --death and wrecks function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= .25) then Explode(pad1, SFX.EXPLODE) Explode(fuelpad, SFX.EXPLODE_ON_HIT) Explode(nano1, SFX.EXPLODE_ON_HIT) Explode(nano2, SFX.EXPLODE_ON_HIT) Explode(door1, SFX.EXPLODE_ON_HIT) Explode(door2, SFX.EXPLODE_ON_HIT) return 1 -- corpsetype elseif (severity <= .5) then Explode(base, SFX.SHATTER) Explode(pad1, SFX.EXPLODE) Explode(fuelpad, SFX.EXPLODE_ON_HIT) Explode(nano1, SFX.EXPLODE_ON_HIT) Explode(nano2, SFX.EXPLODE_ON_HIT) Explode(door1, SFX.EXPLODE_ON_HIT) Explode(door2, SFX.EXPLODE_ON_HIT) return 1 -- corpsetype else Explode(base, SFX.SHATTER) Explode(bay, SFX.SHATTER) Explode(door1, SFX.SHATTER) Explode(door2, SFX.SHATTER) Explode(fuelpad, SFX.SHATTER) Explode(pad1, SFX.EXPLODE) Explode(nano1, SFX.EXPLODE_ON_HIT) Explode(nano2, SFX.EXPLODE_ON_HIT) return 2 -- corpsetype end end
gpl-2.0
kkitsune/GoblinEngine
engine/libs/bgfx/bgfx/scripts/genie.lua
4
8682
-- -- Copyright 2010-2016 Branimir Karadzic. All rights reserved. -- License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause -- newoption { trigger = "with-amalgamated", description = "Enable amalgamated build.", } newoption { trigger = "with-ovr", description = "Enable OculusVR integration.", } newoption { trigger = "with-sdl", description = "Enable SDL entry.", } newoption { trigger = "with-glfw", description = "Enable GLFW entry.", } newoption { trigger = "with-profiler", description = "Enable build with intrusive profiler.", } newoption { trigger = "with-scintilla", description = "Enable building with Scintilla editor.", } newoption { trigger = "with-shared-lib", description = "Enable building shared library.", } newoption { trigger = "with-tools", description = "Enable building tools.", } newoption { trigger = "with-examples", description = "Enable building examples.", } solution "bgfx" configurations { "Debug", "Release", } if _ACTION == "xcode4" then platforms { "Universal", } else platforms { "x32", "x64", -- "Xbox360", "Native", -- for targets where bitness is not specified } end language "C++" startproject "example-00-helloworld" MODULE_DIR = path.getabsolute("../") BGFX_DIR = path.getabsolute("..") BX_DIR = os.getenv("BX_DIR") local BGFX_BUILD_DIR = path.join(BGFX_DIR, ".build") local BGFX_THIRD_PARTY_DIR = path.join(BGFX_DIR, "3rdparty") if not BX_DIR then BX_DIR = path.getabsolute(path.join(BGFX_DIR, "../bx")) end if not os.isdir(BX_DIR) then print("bx not found at " .. BX_DIR) print("For more info see: https://bkaradzic.github.io/bgfx/build.html") os.exit() end defines { "BX_CONFIG_ENABLE_MSVC_LEVEL4_WARNINGS=1" } dofile (path.join(BX_DIR, "scripts/toolchain.lua")) if not toolchain(BGFX_BUILD_DIR, BGFX_THIRD_PARTY_DIR) then return -- no action specified end function copyLib() end if _OPTIONS["with-sdl"] then if os.is("windows") then if not os.getenv("SDL2_DIR") then print("Set SDL2_DIR enviroment variable.") end end end if _OPTIONS["with-profiler"] then defines { "ENTRY_CONFIG_PROFILER=1", "BGFX_CONFIG_PROFILER_REMOTERY=1", "_WINSOCKAPI_" } end function exampleProject(_name) project ("example-" .. _name) uuid (os.uuid("example-" .. _name)) kind "WindowedApp" configuration {} debugdir (path.join(BGFX_DIR, "examples/runtime")) includedirs { path.join(BX_DIR, "include"), path.join(BGFX_DIR, "include"), path.join(BGFX_DIR, "3rdparty"), path.join(BGFX_DIR, "examples/common"), } files { path.join(BGFX_DIR, "examples", _name, "**.c"), path.join(BGFX_DIR, "examples", _name, "**.cpp"), path.join(BGFX_DIR, "examples", _name, "**.h"), } removefiles { path.join(BGFX_DIR, "examples", _name, "**.bin.h"), } links { "bgfx", "example-common", } if _OPTIONS["with-sdl"] then defines { "ENTRY_CONFIG_USE_SDL=1" } links { "SDL2" } configuration { "osx" } libdirs { "$(SDL2_DIR)/lib" } configuration {} end if _OPTIONS["with-glfw"] then defines { "ENTRY_CONFIG_USE_GLFW=1" } links { "glfw3" } configuration { "linux or freebsd" } links { "Xrandr", "Xinerama", "Xi", "Xxf86vm", "Xcursor", } configuration { "osx" } linkoptions { "-framework CoreVideo", "-framework IOKit", } configuration {} end if _OPTIONS["with-ovr"] then configuration { "x32" } libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/Win32/Release", _ACTION) } configuration { "x64" } libdirs { path.join("$(OVR_DIR)/LibOVR/Lib/Windows/x64/Release", _ACTION) } configuration { "x32 or x64" } links { "libovr" } configuration {} end configuration { "vs*", "x32 or x64" } linkoptions { "/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll } links { -- this is needed only for testing with GLES2/3 on Windows with VS2008 "DelayImp", } configuration { "vs201*", "x32 or x64" } linkoptions { -- this is needed only for testing with GLES2/3 on Windows with VS201x "/DELAYLOAD:\"libEGL.dll\"", "/DELAYLOAD:\"libGLESv2.dll\"", } configuration { "mingw*" } targetextension ".exe" links { "gdi32", "psapi", } configuration { "vs20*", "x32 or x64" } links { "gdi32", "psapi", } configuration { "durango" } links { "d3d11_x", "d3d12_x", "combase", "kernelx", } configuration { "winphone8* or winstore8*" } removelinks { "DelayImp", "gdi32", "psapi" } links { "d3d11", "dxgi" } linkoptions { "/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata } -- WinRT targets need their own output directories or build files stomp over each other configuration { "x32", "winphone8* or winstore8*" } targetdir (path.join(BGFX_BUILD_DIR, "win32_" .. _ACTION, "bin", _name)) objdir (path.join(BGFX_BUILD_DIR, "win32_" .. _ACTION, "obj", _name)) configuration { "x64", "winphone8* or winstore8*" } targetdir (path.join(BGFX_BUILD_DIR, "win64_" .. _ACTION, "bin", _name)) objdir (path.join(BGFX_BUILD_DIR, "win64_" .. _ACTION, "obj", _name)) configuration { "ARM", "winphone8* or winstore8*" } targetdir (path.join(BGFX_BUILD_DIR, "arm_" .. _ACTION, "bin", _name)) objdir (path.join(BGFX_BUILD_DIR, "arm_" .. _ACTION, "obj", _name)) configuration { "mingw-clang" } kind "ConsoleApp" configuration { "android*" } kind "ConsoleApp" targetextension ".so" linkoptions { "-shared", } links { "EGL", "GLESv2", } configuration { "nacl*" } kind "ConsoleApp" targetextension ".nexe" links { "ppapi", "ppapi_gles2", "pthread", } configuration { "pnacl" } kind "ConsoleApp" targetextension ".pexe" links { "ppapi", "ppapi_gles2", "pthread", } configuration { "asmjs" } kind "ConsoleApp" targetextension ".bc" configuration { "linux-* or freebsd", "not linux-steamlink" } links { "X11", "GL", "pthread", } configuration { "linux-steamlink" } links { "EGL", "GLESv2", "SDL2", "pthread", } configuration { "rpi" } links { "X11", "GLESv2", "EGL", "bcm_host", "vcos", "vchiq_arm", "pthread", } configuration { "osx" } linkoptions { "-framework Cocoa", "-framework QuartzCore", "-framework OpenGL", "-weak_framework Metal", } configuration { "ios* or tvos*" } kind "ConsoleApp" linkoptions { "-framework CoreFoundation", "-framework Foundation", "-framework OpenGLES", "-framework UIKit", "-framework QuartzCore", "-weak_framework Metal", } configuration { "xcode4", "ios" } kind "WindowedApp" files { path.join(BGFX_DIR, "examples/runtime/iOS-Info.plist"), } configuration { "xcode4", "tvos" } kind "WindowedApp" files { path.join(BGFX_DIR, "examples/runtime/tvOS-Info.plist"), } configuration { "qnx*" } targetextension "" links { "EGL", "GLESv2", } configuration {} strip() end dofile "bgfx.lua" group "libs" bgfxProject("", "StaticLib", {}) if _OPTIONS["with-examples"] or _OPTIONS["with-tools"] then group "examples" dofile "example-common.lua" end if _OPTIONS["with-examples"] then group "examples" exampleProject("00-helloworld") exampleProject("01-cubes") exampleProject("02-metaballs") exampleProject("03-raymarch") exampleProject("04-mesh") exampleProject("05-instancing") exampleProject("06-bump") exampleProject("07-callback") exampleProject("08-update") exampleProject("09-hdr") exampleProject("10-font") exampleProject("11-fontsdf") exampleProject("12-lod") exampleProject("13-stencil") exampleProject("14-shadowvolumes") exampleProject("15-shadowmaps-simple") exampleProject("16-shadowmaps") exampleProject("17-drawstress") exampleProject("18-ibl") exampleProject("19-oit") exampleProject("20-nanovg") exampleProject("21-deferred") exampleProject("22-windows") exampleProject("23-vectordisplay") exampleProject("24-nbody") exampleProject("26-occlusion") exampleProject("27-terrain") exampleProject("28-wireframe") exampleProject("29-debugdraw") exampleProject("30-picking") exampleProject("31-rsm") -- C99 source doesn't compile under WinRT settings if not premake.vstudio.iswinrt() then exampleProject("25-c99") end end if _OPTIONS["with-shared-lib"] then group "libs" bgfxProject("-shared-lib", "SharedLib", {}) end if _OPTIONS["with-tools"] then group "tools" dofile "shaderc.lua" dofile "texturec.lua" dofile "texturev.lua" dofile "geometryc.lua" end
mit
shahabsaf1/EMC-Project
plugins/sudo.lua
14
1877
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, '!cpu') 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 = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
KayMD/Illarion-Content
item/id_1208_sandpit.lua
1
1057
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_1208_sandpit' WHERE itm_id=1208; local sanddigging = require("craft.gathering.sanddigging") local skillTransfer = require("base.skillTransfer") local M = {} function M.UseItem(User, SourceItem, ltstate) if skillTransfer.skillTransferInformMining(User) then return end sanddigging.StartGathering(User, SourceItem, ltstate) end return M
agpl-3.0
nobie/sesame_fw
feeds/luci/modules/freifunk/luasrc/model/cbi/freifunk/basics.lua
74
3518
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Manuel Munz <freifunk at somakoma de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]] local fs = require "luci.fs" local util = require "luci.util" local uci = require "luci.model.uci".cursor() local profiles = "/etc/config/profile_" m = Map("freifunk", translate ("Community")) c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router.")) community = c:option(ListValue, "name", translate ("Community")) community.rmempty = false local list = { } local list = fs.glob(profiles .. "*") for k,v in ipairs(list) do local name = uci:get_first(v, "community", "name") or "?" local n = string.gsub(v, profiles, "") community:value(n, name) end n = Map("system", translate("Basic system settings")) function n.on_after_commit(self) luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics")) end b = n:section(TypedSection, "system") b.anonymous = true hn = b:option(Value, "hostname", translate("Hostname")) hn.rmempty = false hn.datatype = "hostname" loc = b:option(Value, "location", translate("Location")) loc.rmempty = false loc.datatype = "minlength(1)" lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345") lat.datatype = "float" lat.rmempty = false lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345") lon.datatype = "float" lon.rmempty = false --[[ Opens an OpenStreetMap iframe or popup Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js ]]-- local class = util.class local ff = uci:get("freifunk", "community", "name") or "" local co = "profile_" .. ff local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52 local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10 local zoom = 12 if ( deflat == 52 and deflon == 10 ) then zoom = 4 end OpenStreetMapLonLat = luci.util.class(AbstractValue) function OpenStreetMapLonLat.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/osmll_value" self.latfield = nil self.lonfield = nil self.centerlat = "" self.centerlon = "" self.zoom = "0" self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100" self.height = "600" self.popup = false self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap self.hidetext="X" -- text on button, that hides OSMap end osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet.")) osm.latfield = "latitude" osm.lonfield = "longitude" osm.centerlat = uci:get_first("system", "system", "latitude") or deflat osm.centerlon = uci:get_first("system", "system", "longitude") or deflon osm.zoom = zoom osm.width = "100%" osm.height = "600" osm.popup = false osm.displaytext=translate("Show OpenStreetMap") osm.hidetext=translate("Hide OpenStreetMap") return m, n
gpl-2.0
kiarash14/BumperTG
plugins/media.lua
376
1679
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
iainmerrick/Urho3D
Source/ThirdParty/toluapp/src/bin/lua/template_class.lua
41
1829
_global_templates = {} classTemplateClass = { name = '', body = '', parents = {}, args = {}, -- the template arguments } classTemplateClass.__index = classTemplateClass function classTemplateClass:throw(types, local_scope) --if table.getn(types) ~= table.getn(self.args) then -- error("#invalid parameter count") --end -- replace for i =1 , types.n do local Il = split_c_tokens(types[i], " ") if table.getn(Il) ~= table.getn(self.args) then error("#invalid parameter count for "..types[i]) end local bI = self.body local pI = {} for j = 1,self.args.n do --Tl[j] = findtype(Tl[j]) or Tl[j] bI = string.gsub(bI, "([^_%w])"..self.args[j].."([^_%w])", "%1"..Il[j].."%2") if self.parents then for i=1,table.getn(self.parents) do pI[i] = string.gsub(self.parents[i], "([^_%w]?)"..self.args[j].."([^_%w]?)", "%1"..Il[j].."%2") end end end --local append = "<"..string.gsub(types[i], "%s+", ",")..">" local append = "<"..concat(Il, 1, table.getn(Il), ",")..">" append = string.gsub(append, "%s*,%s*", ",") append = string.gsub(append, ">>", "> >") for i=1,table.getn(pI) do --pI[i] = string.gsub(pI[i], ">>", "> >") pI[i] = resolve_template_types(pI[i]) end bI = string.gsub(bI, ">>", "> >") local n = self.name if local_scope then n = self.local_name end Class(n..append, pI, bI) end end function TemplateClass(name, parents, body, parameters) local o = { parents = parents, body = body, args = parameters, } local oname = string.gsub(name, "@.*$", "") oname = getnamespace(classContainer.curr)..oname o.name = oname o.local_name = name setmetatable(o, classTemplateClass) if _global_templates[oname] then warning("Duplicate declaration of template "..oname) else _global_templates[oname] = o end return o end
mit
KayMD/Illarion-Content
content/oldSlimeFeeding.lua
2
9889
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- This handles everything needed to control the quest of feeding the Old Slime in Runewick. local factions = require("base.factions") local scheduledFunction = require("scheduled.scheduledFunction") local lookat = require("base.lookat") local M = {} local oldSlimeId = 616 local blockedLever = 434 local normalLever = 435 local leverPosition = position(895, 774, 0) local teleportPlatform = position(894, 775, 0) local refuseFeedingField = position(894, 779, 0) local acceptFeedingField = position(887, 775, 0) local caveEntrance = position(890, 770, 0) local rewardPosition = position(893, 776, 0) local feedingInProgress = false local slimeDietItems = { {itemId = 159, amount = 15}, --[[toad stool]] {itemId = 52, amount = 3}, --[[bucket of water]] {itemId = 447, amount = 3}, --[[ruby powder]] {itemId = 21, amount = 9}, --[[coal]] {itemId = 152, amount = 3}, --[[life root]] {itemId = 2529, amount = 10}, --[[honey comb]] {itemId = 252, amount = 7}, --[[raw obsidian]] {itemId = 15, amount = 25}, --[[apple]] {itemId = 157, amount = 26}, --[[rotten tree bark]] {itemId = 762, amount = 3}, --[[gold crak herb]] {itemId = 314, amount = 10}, --[[potash]] {itemId = 456, amount = 11}, --[[snowball]] {itemId = 133, amount = 25}, --[[sun herb]] {itemId = 450, amount = 4}, --[[ameythst powder]] {itemId = 1149, amount = 10}, --[[eggs]] {itemId = 160, amount = 15}, --[[red head]] {itemId = 259, amount = 15}, --[[grain]] {itemId = 140, amount = 60}, --[[donf blade]] {itemId = 726, amount = 20}, --[[coarse sand]] {itemId = 767, amount = 10}, --[[water blossom]] {itemId = 451, amount = 3}, --[[topaz powder]] {itemId = 138, amount = 3}, --[[night angels blossom]] {itemId = 256, amount = 5}, --[[raw smaragd]] {itemId = 26, amount = 15} --[[clay]] } local rewardList = { {itemId = 164, amount = 1, quality = 333, data = nil}, --[[empty bottle]] {itemId = 59, amount = 1, quality = 333, data = {potionEffectId = 59555555, filledWith = "potion", descriptionDe = "Idiotenheilmittel. Idiot's treatment", descriptionEn = "Idiotenheilmittel. Idiot's treatment"}}, --[[potion, increase int]] {itemId = 126, amount = 1, quality = 666, data = nil}, --[[sickel]] {itemId = 3077, amount = 25, quality = 333, data = nil}, --[[silver coin]] {itemId = 1318, amount = 1, quality = 333, data = nil}, --[[bottle of Elven wine]] {itemId = 446, amount = 2, quality = 333, data = nil}, --[[sapphire powder]] {itemId = 449, amount = 2, quality = 333, data = nil}, --[[obsidian powder]] {itemId = 452, amount = 2, quality = 333, data = nil}, --[[diamond powder]] {itemId = 83, amount = 1, quality = 555, data = nil}, --[[topaz amulet]] {itemId = 254, amount = 5, quality = 333, data = nil}, --[[raw diamond]] {itemId = 3076, amount = 2678, quality = 333, data = nil}, --[[copper coins]] {itemId = 829, amount = 1, quality = 666, data = nil}, --[[yellow hat with feather]] {itemId = 2588, amount = 27, quality = 333, data = nil}, --[[bricks]] {itemId = 200, amount = 22, quality = 333, data = nil}, --[[tomato]] {itemId = 2668, amount = 1, quality = 444, data = nil} --[[poisoned simple dagger]] } function M.setSignText(signSlimeFeeding) local day = world:getTime("day") local itemId = slimeDietItems[day]["itemId"] local amount = slimeDietItems[day]["amount"] lookat.SetSpecialName(signSlimeFeeding, "Regeln für das Füttern des alten Schleims", "Rules for feeding the old slime") lookat.SetSpecialDescription(signSlimeFeeding,"Heutiges Futter: "..world:getItemName(itemId,Player.german)..", Anzahl: "..amount.." // Beachten: Nur Gegenstandsteleporter nutzen; pro Person nur einmal im Monat füttern (Überfressungsprävention); nur vorgegebenes Futter verwenden (Nährstoffversorgungssicherstellung); niemals sollen zwei Personen gleichzeitig füttern (Unentscheidbarkeitssyndromverhinderung); KEINE FÜTTERUNG IM MAS!", "Today's feeding: "..world:getItemName(itemId,Player.english)..", amount: "..amount.." // Keep in mind: Use only the object teleporter; every person may feed the slime only once a month (prevention of overeating); use only the food allowed on the current day (securing of nutrient supply); two people should never ever feed simultaneously (prevention of undecidability syndrome); NO FEEDING DURING MAS!") end local function newMonth(user) local questStatus = user:getQuestProgress(450) local year = math.floor(questStatus/100) local month = questStatus - (year*100) if questStatus == 0 or month < world:getTime("month") or year < world:getTime("year") then return true end return false end local function checkFeeding(user) local feeding if world:isItemOnField(teleportPlatform) then feeding = world:getItemOnField(teleportPlatform) if feeding.id == 432 or feeding.id == 433 then -- items used to mark the field. Do not remove them. return false, nil end else return false, nil end local day = world:getTime("day") local neededId = slimeDietItems[day]["itemId"] local neededAmount = slimeDietItems[day]["amount"] if feeding.id == neededId and feeding.number == neededAmount and feedingInProgress == false and newMonth(user) then return true, feeding else return false, feeding end end -- Called from the reload script (also used by the function useLever) function M.resetLever() if world:isItemOnField(leverPosition) then local lever = world:getItemOnField(leverPosition) lever.id = normalLever world:changeItem(lever) end end -- Called from lever item script function M.useLever(user, sourceItem) if sourceItem.id == blockedLever then user:inform("Der Hebel scheint blockiert. Du kannst ihn nicht bewegen.", "The lever seems blocked. You cannot move it.") return end local feedingAccepted, feedingItem = checkFeeding(user) if not feedingAccepted then if feedingItem then M.refuseItem(feedingItem) end else world:gfx(45, feedingItem.pos) world:gfx(46, acceptFeedingField) world:createItemFromItem(feedingItem, acceptFeedingField,true) world:erase(feedingItem, feedingItem.number) if factions.isRunewickCitizen(user) then factions.setRankpoints(user, factions.getRankpoints(user)+3) end user:setQuestProgress(450, world:getTime("year")*100 + world:getTime("month")) feedingInProgress = true local oldSlime = world:createMonster(oldSlimeId, position(1,1,0), 0) oldSlime:warp(caveEntrance) -- hack to show model, to work around a client issue oldSlime:talk(Character.say, "#me fließt aus der Höhlennische und beginnt sich in Richtung des Futters zu bewegen.", "#me flows out from the small hole and starts to move towards the feed.") oldSlime.movepoints = oldSlime.movepoints - 50 oldSlime.waypoints:addWaypoint(acceptFeedingField) oldSlime:setOnRoute(true) end sourceItem.id = blockedLever world:changeItem(sourceItem) scheduledFunction.registerFunction(2, function() M.resetLever() end) end -- Called from triggerfield script function M.warpCharacterAway(user) if user:getType() == Character.player or user:getMonsterType() ~= oldSlimeId then world:gfx(45,user.pos) user:warp(refuseFeedingField) world:gfx(46,refuseFeedingField) end end -- Called from triggerfield script (also by useLever function in this script) function M.refuseItem(refusedItem) world:gfx(45,refusedItem.pos) world:gfx(46,refuseFeedingField) world:createItemFromItem(refusedItem,refuseFeedingField,true) world:erase(refusedItem,refusedItem.number) end -- Called from monster script of old slime function M.oldSlimeAbortRoute(oldSlime) if oldSlime.pos == acceptFeedingField then if world:isItemOnField(acceptFeedingField) then oldSlime:talk(Character.say, "#mes schleimige Masse gleitet über das Futter und absorbiert es. Sein Körper wabbelt kurz ein Objekt tritt aus diesem raus, welches über die Ansperrung kataplutiert.", "#me's slimy mass flows over the feed and absorbs it. Its body wobbles for a short period of time and an object emerges from it, which is catapulted over the boundary.") local feeding = world:getItemOnField(acceptFeedingField) world:erase(feeding, feeding.number) local reward = rewardList[math.random(1, #rewardList)] world:createItemFromId(reward.itemId, reward.amount, rewardPosition, true, reward.quality, reward.data) oldSlime.movepoints = oldSlime.movepoints -50 end oldSlime.waypoints:addWaypoint(caveEntrance) oldSlime:setOnRoute(true) elseif oldSlime.pos == caveEntrance then oldSlime:talk(Character.say, "#me fließt in die Höhlennische zurück.", "#me flows back into the small hole.") oldSlime:increaseAttrib("hitpoints", -10000) feedingInProgress = false end end return M
agpl-3.0
nobie/sesame_fw
feeds/luci/modules/niu/luasrc/model/cbi/niu/wireless/bridge.lua
51
2481
local uci = require "luci.model.uci" local cursor = uci.cursor() if not cursor:get("wireless", "bridge") then cursor:section("wireless", "wifi-iface", "bridge", {device = "_", doth = "1", _niu = "1", mode = "sta", wds = "1"}) cursor:save("wireless") end local function deviceroute(self) cursor:unload("wireless") local d = cursor:get("wireless", "bridge", "device") if d ~= "none" then local nc = uci.cursor(nil, "") cursor:delete_all("wireless", "wifi-iface", function(s) return s.device == d and s._niu ~= "1" end) if nc:get("wireless", "bridge", "network") ~= cursor:get("wireless", "bridge", "network") then cursor:delete("wireless", "bridge", "network") end cursor:set("wireless", d, "disabled", 0) cursor:foreach("dhcp", "dhcp", function(s) if s.interface == "lan" and s.ignore ~= "1" then cursor:set("dhcp", s[".name"], "ignore", "1") end end) self:set_route("scan", "bridge", "bridgelan") else if cursor:get("wireless", "bridge", "network") then cursor:delete("wireless", "bridge", "network") cursor:foreach("dhcp", "dhcp", function(s) if s.interface == "lan" and s.ignore == "1" then cursor:set("dhcp", s[".name"], "ignore", "0") end end) self:set_route("lan") end end cursor:save("dhcp") cursor:save("wireless") end local d = Delegator() d.allow_finish = true d.allow_back = true d.allow_cancel = true d:add("device", "niu/wireless/brdevice") d:add("deviceroute", deviceroute) d:set("scan", "niu/network/wlanwanscan") d:set("bridge", "niu/network/wlanwan") d:set("bridgelan", "niu/network/lan1") d:set("lan", "niu/network/lan1") function d.on_cancel() cursor:revert("network") cursor:revert("wireless") cursor:revert("dhcp") end function d.on_done() if uci.inst_state:get("network", "lan", "ipaddr") ~= cursor:get("network", "lan", "ipaddr") then local cs = uci.cursor_state() cs:set("network", "lan", "_ipchanged", "1") cs:save("network") end if cursor:get("network", "lan", "proto") == "dhcp" then local emergv4 = cursor:get("network", "lan", "_emergv4") if emergv4 then if cursor:get("network", "lan_ea") then cursor:set("network", "lan_ea", "ipaddr", emergv4) else cursor:section("network", "alias", "lan_ea", { ipaddr = emergv4, netmask = "255.255.255.0", network = "lan" }) end else cursor:delete("network", "lan_ea") end end cursor:commit("network") cursor:commit("wireless") cursor:commit("dhcp") end return d
gpl-2.0
adel8268adelad/Bot-thebest
plugins/gif.lua
15
1758
do local BASE_URL = 'http://api.giphy.com/v1' local API_KEY = 'dc6zaTOxFJmzC' -- public beta key local function get_image(response) local images = json:decode(response).data if #images == 0 then return nil end -- No images local i = math.random(#images) local image = images[i] -- A random one if image.images.downsized then return image.images.downsized.url end if image.images.original then return image.original.url end return nil end local function get_random_top() local url = BASE_URL.."/gifs/trending?api_key="..API_KEY local response, code = http.request(url) if code ~= 200 then return nil end return get_image(response) end local function search(text) text = URL.escape(text) local url = BASE_URL.."/gifs/search?q="..text.."&api_key="..API_KEY local response, code = http.request(url) if code ~= 200 then return nil end return get_image(response) end local function run(msg, matches) local gif_url = nil -- If no search data, a random trending GIF will be sent if matches[1] == "gif" or matches[1] == "giphy" then gif_url = get_random_top() else gif_url = search(matches[1]) end if not gif_url then return "خطا گیف مورد نظر پیدا نشد" end local receiver = get_receiver(msg) print("GIF URL"..gif_url) send_document_from_url(receiver, gif_url) end return { description = "GIFs from telegram with Giphy API", usage = { "!gif (term): Search and sends GIF from Giphy. If no param, sends a trending GIF.", "!giphy (term): Search and sends GIF from Giphy. If no param, sends a trending GIF." }, patterns = { "^[!/#](gif)$", "^[!/#](gif) (.*)", "^[!/#](giphy) (.*)", "^[!/#](giphy)$" }, run = run } end
agpl-3.0
coral-framework/coral
modules/co/compiler/module/componentBaseHeader.lua
1
2310
local function template( writer, c, t ) c.header( writer, c, "Base class generated for component '", t.fullName, "'" ) writer( [[ #ifndef _]], t.fullNameUpperUnderline, [[_BASE_H_ #define _]], t.fullNameUpperUnderline, [[_BASE_H_ ]] ) local headers = t.includedHeaders for i = 1, #headers do writer( "#include <", headers[i], ">\n" ) end for fullName, type in pairs( t.forwardDeclTypes ) do writer( "#include <", type.headerName, ">\n" ) end writer( "#include <co/reserved/ComponentBase.h>\n\n" ) c.utils.openNamespaces( writer, c.moduleName ) writer( "\n" ) local facets = t.facets local receptacles = t.receptacles for i, itf in ipairs( facets ) do writer( [[ //! ]], t.fullName, [[ has a facet named ']], itf.name, [[', of type ]], itf.type.fullName, ".\n", [[ class ]], t.name , [[_]], itf.type.fullNameUnderline, [[ : public ]], itf.type.cppName, "\n", [[ { public: virtual co::IInterface* getInterface(); virtual co::IPort* getFacet(); }; ]] ) end writer( [[ /*! Inherit from this class to implement the component ']], t.fullName, [['. */ class ]], t.name, [[_Base : public co::ComponentBase]] ) if #facets > 0 then for i, itf in ipairs( facets ) do writer( ",\n\tpublic ", t.name, "_", itf.type.fullNameUnderline ) end end writer( [[ { public: ]], t.name, [[_Base(); virtual ~]], t.name, [[_Base(); // co::IService Methods: co::IObject* getProvider(); void serviceRetain(); void serviceRelease(); // co::IObject Methods: co::IComponent* getComponent(); co::IService* getServiceAt( co::IPort* ); void setServiceAt( co::IPort*, co::IService* ); ]] ) if #receptacles > 0 then writer( "\nprotected:" ) for i, itf in ipairs( receptacles ) do writer( [[ //! Get the service at receptacle ']], itf.name, [[', of type ]], itf.type.fullName, ".\n", [[ virtual ]], itf.type.cppName, [[* ]], t.formatAccessor( "get", itf.name ), [[Service() = 0; //! Set the service at receptacle ']], itf.name, [[', of type ]], itf.type.fullName, ".\n", [[ virtual void ]], t.formatAccessor( "set", itf.name ), [[Service( ]], itf.type.cppName, [[* ]], itf.name, [[ ) = 0; ]] ) end end writer( "};\n\n" ) c.utils.closeNamespaces( writer, c.moduleName ) writer( [[ #endif // _]], t.fullNameUpperUnderline, [[_BASE_H_ ]] ) end return template
mit
pixeltailgames/gm-mediaplayer
lua/mediaplayer/services/youtube/init.lua
1
5331
AddCSLuaFile "shared.lua" include "shared.lua" local TableLookup = MediaPlayerUtils.TableLookup --- -- Helper function for converting ISO 8601 time strings; this is the formatting -- used for duration specified in the YouTube v3 API. -- -- http://stackoverflow.com/a/22149575/1490006 -- local function convertISO8601Time( duration ) local a = {} for part in string.gmatch(duration, "%d+") do table.insert(a, part) end if duration:find('M') and not (duration:find('H') or duration:find('S')) then a = {0, a[1], 0} end if duration:find('H') and not duration:find('M') then a = {a[1], 0, a[2]} end if duration:find('H') and not (duration:find('M') or duration:find('S')) then a = {a[1], 0, 0} end duration = 0 if #a == 3 then duration = duration + tonumber(a[1]) * 3600 duration = duration + tonumber(a[2]) * 60 duration = duration + tonumber(a[3]) end if #a == 2 then duration = duration + tonumber(a[1]) * 60 duration = duration + tonumber(a[2]) end if #a == 1 then duration = duration + tonumber(a[1]) end return duration end function SERVICE:GetMetadata( callback ) if self._metadata then callback( self._metadata ) return end local cache = MediaPlayer.Metadata:Query(self) if MediaPlayer.DEBUG then print("MediaPlayer.GetMetadata Cache results:") PrintTable(cache or {}) end if cache then local metadata = {} metadata.title = cache.title metadata.duration = tonumber(cache.duration) metadata.thumbnail = cache.thumbnail self:SetMetadata(metadata) if self:IsTimed() then MediaPlayer.Metadata:Save(self) end callback(self._metadata) else local videoId = self:GetYouTubeVideoId() local videoUrl = "https://www.youtube.com/watch?v="..videoId self:Fetch( videoUrl, -- On Success function( body, length, headers, code ) local status, metadata = pcall(self.ParseYTMetaDataFromHTML, self, body) -- html couldn't be parsed if not status or not metadata.title or not isnumber(metadata.duration) then -- Title is nil or Duration is nan if istable(metadata) then metadata = "title = "..type(metadata.title)..", duration = "..type(metadata.duration) end -- Misc error callback(false, "Failed to parse HTML Page for metadata: "..metadata) return end self:SetMetadata(metadata, true) if self:IsTimed() then MediaPlayer.Metadata:Save(self) end callback(self._metadata) end, -- On failure function( code ) callback(false, "Failed to load YouTube ["..tostring(code).."]") end, -- Headers { ["User-Agent"] = "Googlebot" } ) end end --- -- Get the value for an attribute from a html element -- local function ParseElementAttribute( element, attribute ) if not element then return end -- Find the desired attribute local output = string.match( element, attribute.."%s-=%s-%b\"\"" ) if not output then return end -- Remove the 'attribute=' part output = string.gsub( output, attribute.."%s-=%s-", "" ) -- Trim the quotes around the value string return string.sub( output, 2, -2 ) end --- -- Get the contents of a html element by removing tags -- Used as fallback for when title cannot be found -- local function ParseElementContent( element ) if not element then return end -- Trim start local output = string.gsub( element, "^%s-<%w->%s-", "" ) -- Trim end return string.gsub( output, "%s-</%w->%s-$", "" ) end -- Lua search patterns to find metadata from the html local patterns = { ["title"] = "<meta%sproperty=\"og:title\"%s-content=%b\"\">", ["title_fallback"] = "<title>.-</title>", ["thumb"] = "<meta%sproperty=\"og:image\"%s-content=%b\"\">", ["thumb_fallback"] = "<link%sitemprop=\"thumbnailUrl\"%s-href=%b\"\">", ["duration"] = "<meta%sitemprop%s-=%s-\"duration\"%s-content%s-=%s-%b\"\">", ["live"] = "<meta%sitemprop%s-=%s-\"isLiveBroadcast\"%s-content%s-=%s-%b\"\">", ["live_enddate"] = "<meta%sitemprop%s-=%s-\"endDate\"%s-content%s-=%s-%b\"\">" } --- -- Function to parse video metadata straight from the html instead of using the API -- function SERVICE:ParseYTMetaDataFromHTML( html ) --MetaData table to return when we're done local metadata = {} -- Fetch title and thumbnail, with fallbacks if needed metadata.title = ParseElementAttribute(string.match(html, patterns["title"]), "content") or ParseElementContent(string.match(html, patterns["title_fallback"])) -- Parse HTML entities in the title into symbols metadata.title = url.htmlentities_decode(metadata.title) metadata.thumbnail = ParseElementAttribute(string.match(html, patterns["thumb"]), "content") or ParseElementAttribute(string.match(html, patterns["thumb_fallback"]), "href") -- See if the video is an ongoing live broadcast -- Set duration to 0 if it is, otherwise use the actual duration local isLiveBroadcast = tobool(ParseElementAttribute(string.match(html, patterns["live"]), "content")) local broadcastEndDate = string.match(html, patterns["live_enddate"]) if isLiveBroadcast and not broadcastEndDate then -- Mark as live video metadata.duration = 0 else local durationISO8601 = ParseElementAttribute(string.match(html, patterns["duration"]), "content") if isstring(durationISO8601) then metadata.duration = math.max(1, convertISO8601Time(durationISO8601)) end end return metadata end
mit
cshore/packages
net/mwan3-luci/files/usr/lib/lua/luci/controller/mwan3.lua
12
11317
module("luci.controller.mwan3", package.seeall) sys = require "luci.sys" ut = require "luci.util" ip = "/usr/bin/ip -4 " function index() if not nixio.fs.access("/etc/config/mwan3") then return end entry({"admin", "network", "mwan"}, alias("admin", "network", "mwan", "overview"), _("Load Balancing"), 600) entry({"admin", "network", "mwan", "overview"}, alias("admin", "network", "mwan", "overview", "overview_interface"), _("Overview"), 10) entry({"admin", "network", "mwan", "overview", "overview_interface"}, template("mwan/overview_interface")) entry({"admin", "network", "mwan", "overview", "interface_status"}, call("interfaceStatus")) entry({"admin", "network", "mwan", "overview", "overview_detailed"}, template("mwan/overview_detailed")) entry({"admin", "network", "mwan", "overview", "detailed_status"}, call("detailedStatus")) entry({"admin", "network", "mwan", "configuration"}, alias("admin", "network", "mwan", "configuration", "interface"), _("Configuration"), 20) entry({"admin", "network", "mwan", "configuration", "interface"}, arcombine(cbi("mwan/interface"), cbi("mwan/interfaceconfig")), _("Interfaces"), 10).leaf = true entry({"admin", "network", "mwan", "configuration", "member"}, arcombine(cbi("mwan/member"), cbi("mwan/memberconfig")), _("Members"), 20).leaf = true entry({"admin", "network", "mwan", "configuration", "policy"}, arcombine(cbi("mwan/policy"), cbi("mwan/policyconfig")), _("Policies"), 30).leaf = true entry({"admin", "network", "mwan", "configuration", "rule"}, arcombine(cbi("mwan/rule"), cbi("mwan/ruleconfig")), _("Rules"), 40).leaf = true entry({"admin", "network", "mwan", "advanced"}, alias("admin", "network", "mwan", "advanced", "hotplugscript"), _("Advanced"), 100) entry({"admin", "network", "mwan", "advanced", "hotplugscript"}, form("mwan/advanced_hotplugscript")) entry({"admin", "network", "mwan", "advanced", "mwanconfig"}, form("mwan/advanced_mwanconfig")) entry({"admin", "network", "mwan", "advanced", "networkconfig"}, form("mwan/advanced_networkconfig")) entry({"admin", "network", "mwan", "advanced", "wirelessconfig"}, form("mwan/advanced_wirelessconfig")) entry({"admin", "network", "mwan", "advanced", "diagnostics"}, template("mwan/advanced_diagnostics")) entry({"admin", "network", "mwan", "advanced", "diagnostics_display"}, call("diagnosticsData"), nil).leaf = true entry({"admin", "network", "mwan", "advanced", "troubleshooting"}, template("mwan/advanced_troubleshooting")) entry({"admin", "network", "mwan", "advanced", "troubleshooting_display"}, call("troubleshootingData")) end function getInterfaceStatus(ruleNumber, interfaceName) if ut.trim(sys.exec("uci -p /var/state get mwan3." .. interfaceName .. ".enabled")) == "1" then if ut.trim(sys.exec(ip .. "route list table " .. ruleNumber)) ~= "" then if ut.trim(sys.exec("uci -p /var/state get mwan3." .. interfaceName .. ".track_ip")) ~= "" then return "online" else return "notMonitored" end else return "offline" end else return "notEnabled" end end function getInterfaceName() local ruleNumber, status = 0, "" uci.cursor():foreach("mwan3", "interface", function (section) ruleNumber = ruleNumber+1 status = status .. section[".name"] .. "[" .. getInterfaceStatus(ruleNumber, section[".name"]) .. "]" end ) return status end function interfaceStatus() local ntm = require "luci.model.network".init() local mArray = {} -- overview status local statusString = getInterfaceName() if statusString ~= "" then mArray.wans = {} wansid = {} for wanName, interfaceState in string.gfind(statusString, "([^%[]+)%[([^%]]+)%]") do local wanInterfaceName = ut.trim(sys.exec("uci -p /var/state get network." .. wanName .. ".ifname")) if wanInterfaceName == "" then wanInterfaceName = "X" end local wanDeviceLink = ntm:get_interface(wanInterfaceName) wanDeviceLink = wanDeviceLink and wanDeviceLink:get_network() wanDeviceLink = wanDeviceLink and wanDeviceLink:adminlink() or "#" wansid[wanName] = #mArray.wans + 1 mArray.wans[wansid[wanName]] = { name = wanName, link = wanDeviceLink, ifname = wanInterfaceName, status = interfaceState } end end -- overview status log local mwanLog = ut.trim(sys.exec("logread | grep mwan3 | tail -n 50 | sed 'x;1!H;$!d;x'")) if mwanLog ~= "" then mArray.mwanlog = { mwanLog } end luci.http.prepare_content("application/json") luci.http.write_json(mArray) end function detailedStatus() local mArray = {} -- detailed mwan status local detailStatusInfo = ut.trim(sys.exec("/usr/sbin/mwan3 status")) if detailStatusInfo ~= "" then mArray.mwandetail = { detailStatusInfo } end luci.http.prepare_content("application/json") luci.http.write_json(mArray) end function diagnosticsData(interface, tool, task) function getInterfaceNumber() local number = 0 uci.cursor():foreach("mwan3", "interface", function (section) number = number+1 if section[".name"] == interface then interfaceNumber = number end end ) end local mArray = {} local results = "" if tool == "service" then os.execute("/usr/sbin/mwan3 " .. task) if task == "restart" then results = "MWAN3 restarted" elseif task == "stop" then results = "MWAN3 stopped" else results = "MWAN3 started" end else local interfaceDevice = ut.trim(sys.exec("uci -p /var/state get network." .. interface .. ".ifname")) if interfaceDevice ~= "" then if tool == "ping" then local gateway = ut.trim(sys.exec("route -n | awk '{if ($8 == \"" .. interfaceDevice .. "\" && $1 == \"0.0.0.0\" && $3 == \"0.0.0.0\") print $2}'")) if gateway ~= "" then if task == "gateway" then local pingCommand = "ping -c 3 -W 2 -I " .. interfaceDevice .. " " .. gateway results = pingCommand .. "\n\n" .. sys.exec(pingCommand) else local tracked = ut.trim(sys.exec("uci -p /var/state get mwan3." .. interface .. ".track_ip")) if tracked ~= "" then for z in tracked:gmatch("[^ ]+") do local pingCommand = "ping -c 3 -W 2 -I " .. interfaceDevice .. " " .. z results = results .. pingCommand .. "\n\n" .. sys.exec(pingCommand) .. "\n\n" end else results = "No tracking IP addresses configured on " .. interface end end else results = "No default gateway for " .. interface .. " found. Default route does not exist or is configured incorrectly" end elseif tool == "rulechk" then getInterfaceNumber() local rule1 = sys.exec(ip .. "rule | grep $(echo $((" .. interfaceNumber .. " + 1000)))") local rule2 = sys.exec(ip .. "rule | grep $(echo $((" .. interfaceNumber .. " + 2000)))") if rule1 ~= "" and rule2 ~= "" then results = "All required interface IP rules found:\n\n" .. rule1 .. rule2 elseif rule1 ~= "" or rule2 ~= "" then results = "Missing 1 of the 2 required interface IP rules\n\n\nRules found:\n\n" .. rule1 .. rule2 else results = "Missing both of the required interface IP rules" end elseif tool == "routechk" then getInterfaceNumber() local routeTable = sys.exec(ip .. "route list table " .. interfaceNumber) if routeTable ~= "" then results = "Interface routing table " .. interfaceNumber .. " was found:\n\n" .. routeTable else results = "Missing required interface routing table " .. interfaceNumber end elseif tool == "hotplug" then if task == "ifup" then os.execute("/usr/sbin/mwan3 ifup " .. interface) results = "Hotplug ifup sent to interface " .. interface .. "..." else os.execute("/usr/sbin/mwan3 ifdown " .. interface) results = "Hotplug ifdown sent to interface " .. interface .. "..." end end else results = "Unable to perform diagnostic tests on " .. interface .. ". There is no physical or virtual device associated with this interface" end end if results ~= "" then results = ut.trim(results) mArray.diagnostics = { results } end luci.http.prepare_content("application/json") luci.http.write_json(mArray) end function troubleshootingData() local ver = require "luci.version" local mArray = {} -- software versions local wrtRelease = ut.trim(ver.distversion) if wrtRelease ~= "" then wrtRelease = "OpenWrt - " .. wrtRelease else wrtRelease = "OpenWrt - unknown" end local luciRelease = ut.trim(ver.luciversion) if luciRelease ~= "" then luciRelease = "\nLuCI - " .. luciRelease else luciRelease = "\nLuCI - unknown" end local mwanVersion = ut.trim(sys.exec("opkg info mwan3 | grep Version | awk '{print $2}'")) if mwanVersion ~= "" then mwanVersion = "\n\nmwan3 - " .. mwanVersion else mwanVersion = "\n\nmwan3 - unknown" end local mwanLuciVersion = ut.trim(sys.exec("opkg info luci-app-mwan3 | grep Version | awk '{print $2}'")) if mwanLuciVersion ~= "" then mwanLuciVersion = "\nmwan3-luci - " .. mwanLuciVersion else mwanLuciVersion = "\nmwan3-luci - unknown" end mArray.versions = { wrtRelease .. luciRelease .. mwanVersion .. mwanLuciVersion } -- mwan config local mwanConfig = ut.trim(sys.exec("cat /etc/config/mwan3")) if mwanConfig == "" then mwanConfig = "No data found" end mArray.mwanconfig = { mwanConfig } -- network config local networkConfig = ut.trim(sys.exec("cat /etc/config/network | sed -e 's/.*username.*/ USERNAME HIDDEN/' -e 's/.*password.*/ PASSWORD HIDDEN/'")) if networkConfig == "" then networkConfig = "No data found" end mArray.netconfig = { networkConfig } -- wireless config local wirelessConfig = ut.trim(sys.exec("cat /etc/config/wireless | sed -e 's/.*username.*/ USERNAME HIDDEN/' -e 's/.*password.*/ PASSWORD HIDDEN/' -e 's/.*key.*/ KEY HIDDEN/'")) if wirelessConfig == "" then wirelessConfig = "No data found" end mArray.wificonfig = { wirelessConfig } -- ifconfig local ifconfig = ut.trim(sys.exec("ifconfig")) if ifconfig == "" then ifconfig = "No data found" end mArray.ifconfig = { ifconfig } -- route -n local routeShow = ut.trim(sys.exec("route -n")) if routeShow == "" then routeShow = "No data found" end mArray.routeshow = { routeShow } -- ip rule show local ipRuleShow = ut.trim(sys.exec(ip .. "rule show")) if ipRuleShow == "" then ipRuleShow = "No data found" end mArray.iprule = { ipRuleShow } -- ip route list table 1-250 local routeList, routeString = ut.trim(sys.exec(ip .. "rule | sed 's/://g' | awk '$1>=2001 && $1<=2250' | awk '{print $NF}'")), "" if routeList ~= "" then for line in routeList:gmatch("[^\r\n]+") do routeString = routeString .. line .. "\n" .. sys.exec(ip .. "route list table " .. line) end routeString = ut.trim(routeString) else routeString = "No data found" end mArray.routelist = { routeString } -- default firewall output policy local firewallOut = ut.trim(sys.exec("uci -p /var/state get firewall.@defaults[0].output")) if firewallOut == "" then firewallOut = "No data found" end mArray.firewallout = { firewallOut } -- iptables local iptables = ut.trim(sys.exec("iptables -L -t mangle -v -n")) if iptables == "" then iptables = "No data found" end mArray.iptables = { iptables } luci.http.prepare_content("application/json") luci.http.write_json(mArray) end
gpl-2.0
nobie/sesame_fw
feeds/luci/applications/luci-coovachilli/luasrc/model/cbi/coovachilli_network.lua
79
1639
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.ip") m = Map("coovachilli") -- tun s1 = m:section(TypedSection, "tun") s1.anonymous = true s1:option( Flag, "usetap" ) s1:option( Value, "tundev" ).optional = true s1:option( Value, "txqlen" ).optional = true net = s1:option( Value, "net" ) for _, route in ipairs(luci.sys.net.routes()) do if route.device ~= "lo" and route.dest:prefix() < 32 then net:value( route.dest:string() ) end end s1:option( Value, "dynip" ).optional = true s1:option( Value, "statip" ).optional = true s1:option( Value, "dns1" ).optional = true s1:option( Value, "dns2" ).optional = true s1:option( Value, "domain" ).optional = true s1:option( Value, "ipup" ).optional = true s1:option( Value, "ipdown" ).optional = true s1:option( Value, "conup" ).optional = true s1:option( Value, "condown" ).optional = true -- dhcp config s2 = m:section(TypedSection, "dhcp") s2.anonymous = true dif = s2:option( Value, "dhcpif" ) for _, nif in ipairs(luci.sys.net.devices()) do if nif ~= "lo" then dif:value(nif) end end s2:option( Value, "dhcpmac" ).optional = true s2:option( Value, "lease" ).optional = true s2:option( Value, "dhcpstart" ).optional = true s2:option( Value, "dhcpend" ).optional = true s2:option( Flag, "eapolenable" ) return m
gpl-2.0
nobie/sesame_fw
feeds/luci/applications/luci-coovachilli/dist/usr/lib/lua/luci/model/cbi/coovachilli_network.lua
79
1639
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.ip") m = Map("coovachilli") -- tun s1 = m:section(TypedSection, "tun") s1.anonymous = true s1:option( Flag, "usetap" ) s1:option( Value, "tundev" ).optional = true s1:option( Value, "txqlen" ).optional = true net = s1:option( Value, "net" ) for _, route in ipairs(luci.sys.net.routes()) do if route.device ~= "lo" and route.dest:prefix() < 32 then net:value( route.dest:string() ) end end s1:option( Value, "dynip" ).optional = true s1:option( Value, "statip" ).optional = true s1:option( Value, "dns1" ).optional = true s1:option( Value, "dns2" ).optional = true s1:option( Value, "domain" ).optional = true s1:option( Value, "ipup" ).optional = true s1:option( Value, "ipdown" ).optional = true s1:option( Value, "conup" ).optional = true s1:option( Value, "condown" ).optional = true -- dhcp config s2 = m:section(TypedSection, "dhcp") s2.anonymous = true dif = s2:option( Value, "dhcpif" ) for _, nif in ipairs(luci.sys.net.devices()) do if nif ~= "lo" then dif:value(nif) end end s2:option( Value, "dhcpmac" ).optional = true s2:option( Value, "lease" ).optional = true s2:option( Value, "dhcpstart" ).optional = true s2:option( Value, "dhcpend" ).optional = true s2:option( Flag, "eapolenable" ) return m
gpl-2.0
nanobox-io/tag
deps/cauterize/lib/group.lua
2
1570
-- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*- -- vim: ts=4 sw=4 ft=lua noet ---------------------------------------------------------------------- -- @author Daniel Barney <daniel@pagodabox.com> -- @copyright 2015, Pagoda Box, Inc. -- @doc -- -- @end -- Created : 19 May 2015 by Daniel Barney <daniel@pagodabox.com> ---------------------------------------------------------------------- local Pid = require('./pid') local Group = {} local groups = {} -- map a key with a pid so that the pid can be looked up later from -- from the key function Group.join(pid,name) local process = Pid.lookup(pid) if process then local group = groups[name] if not group then group = {} groups[name] = group end group[pid] = true process._groups[name] = true else error('unable to register a dead pid') end end function Group.leave(pid,name) local process = Pid.lookup(pid) if process then local group = groups[name] if group then group[pid] = nil process._groups[name] = nil end end end function Group.get(name) local group = groups[name] members = {} if group then local count = 1 for pid in pairs(group) do members[count] = pid count = count + 1 end end return members end -- clean up any mapping when the process exits function Group.clean(pid) local process = Pid.lookup(pid) if process then for name,_ in pairs(process._groups) do groups[name][pid] = nil end end end function Group.empty() groups = {} end return Group
mit
nobie/sesame_fw
feeds/luci/applications/luci-asterisk/dist/usr/lib/lua/luci/model/cbi/asterisk/trunk_sip.lua
80
2561
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require("luci.asterisk") -- -- SIP trunk info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Trunk Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Trunk %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "trunks") ) end return form -- -- SIP trunk config -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Trunk") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "peer", qualify = "yes", } back = peer:option(DummyValue, "_overview", "Back to trunk overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks") sipdomain = peer:option(Value, "host", "SIP Domain") sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy") outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port") register = peer:option(Flag, "register", "Register with peer") register.enabled = "yes" register.disabled = "no" regext = peer:option(Value, "registerextension", "Extension to register (optional)") regext:depends({register="1"}) didval = peer:option(ListValue, "_did", "Number of assigned DID numbers") didval:value("", "(none)") for i=1,24 do didval:value(i) end dialplan = peer:option(ListValue, "context", "Dialplan Context") dialplan:value(arg[1] .. "_inbound", "(default)") cbimap.uci:foreach("asterisk", "dialplan", function(s) dialplan:value(s['.name']) end) return cbimap end
gpl-2.0
arya5123/tell
setrank.lua
1
8916
do local Dev = 98962756 --put your id here(BOT OWNER ID) local function setrank(msg, name, value) -- setrank function local hash = nil if msg.to.type == 'chat' then hash = 'rank:'..msg.to.id..':variables' end if hash then redis:hset(hash, name, value) return send_msg('chat#id'..msg.to.id, 'مقام کاربر ('..name..') به '..value..' تغییر داده شد ', ok_cb, true) end end local function res_user_callback(extra, success, result) -- /info <username> function if success == 1 then if result.username then Username = '@'..result.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.id..'\n\n' local hash = 'rank:'..extra.chat2..':variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(Dev) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.id, extra.chat2) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.id, extra.chat2) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'TeleAgent Team' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, extra.user..' نام کاربری مورد نظر یافت نشد.', ok_cb, false) end end local function action_by_id(extra, success, result) -- /info <ID> function if success == 1 then if result.username then Username = '@'..result.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.id..'\n\n' local hash = 'rank:'..extra.chat2..':variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(Dev) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.id, extra.chat2) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.id, extra.chat2) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'TeleAgent Team' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, 'ایدی شخص مورد نظر در سیستم ثبت نشده است.\nاز دستور زیر استفاده کنید\n/info @username', ok_cb, false) end end local function action_by_reply(extra, success, result)-- (reply) /info function if result.from.username then Username = '@'..result.from.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.from.id..'\n\n' local hash = 'rank:'..result.to.id..':variables' local value = redis:hget(hash, result.from.id) if not value then if result.from.id == tonumber(Dev) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.from.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.from.id, result.to.id) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.from.id, result.to.id) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local user_info = {} local uhash = 'user:'..result.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.from.id..':'..result.to.id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'TeleAgent Team' send_msg(extra.receiver, text, ok_cb, true) end local function action_by_reply2(extra, success, result) local value = extra.value setrank(result, result.from.id, value) end local function run(msg, matches) if matches[1]:lower() == 'setrank' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) if not is_sudo(msg) then return "Only for Sudo" end local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then local value = string.sub(matches[2], 1, 1000) msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value}) else local name = string.sub(matches[2], 1, 50) local value = string.sub(matches[3], 1, 1000) local text = setrank(msg, name, value) return text end end if matches[1]:lower() == 'آیدی' and not matches[2] then local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply}) else if msg.from.username then Username = '@'..msg.from.username else Username = 'ندارد' end local text = 'نام : '..(msg.from.first_name or 'ندارد')..'\n' local text = text..'فامیل : '..(msg.from.last_name or 'ندارد')..'\n' local text = text..'یوزر : '..Username..'\n' local text = text..'ایدی کاربری : '..msg.from.id..'\n\n' local hash = 'rank:'..msg.to.id..':variables' if hash then local value = redis:hget(hash, msg.from.id) if not value then if msg.from.id == tonumber(Dev) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_sudo(msg) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner(msg) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod(msg) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n' end end local uhash = 'user:'..msg.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' if msg.to.type == 'chat' then text = text..'نام گروه : '..msg.to.title..'\n' text = text..'ایدی گروه : '..msg.to.id end text = text..'\n\nTeleAgent Team' return send_msg(receiver, text, ok_cb, true) end end if matches[1]:lower() == 'info' and matches[2] then local user = matches[2] local chat2 = msg.to.id local receiver = get_receiver(msg) if string.match(user, '^%d+$') then user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2}) elseif string.match(user, '^@.+$') then username = string.gsub(user, '@', '') msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2}) end end end return { description = 'Know your information or the info of a chat members.', usage = { '!info: Return your info and the chat info if you are in one.', '(Reply)!info: Return info of replied user if used by reply.', '!info <id>: Return the info\'s of the <id>.', '!info @<user_name>: Return the member @<user_name> information from the current chat.', '!setrank <userid> <rank>: change members rank.', '(Reply)!setrank <rank>: change members rank.', }, patterns = { "^(آیدی)$", "^(آیدی) (.*)$", "^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$", "^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$", }, run = run } end
gpl-2.0
mardraze/prosody-modules
mod_carbons_adhoc/mod_carbons_adhoc.lua
32
1256
-- Implement a Adhoc command which will show a user -- the status of carbons generation in regard to his clients -- -- Copyright (C) 2012 Michael Holzt -- -- This file is MIT/X11 licensed. local st = require "util.stanza"; local jid_bare = require "util.jid".bare; local adhoc_new = module:require "adhoc".new; local xmlns_carbons_v2 = "urn:xmpp:carbons:2"; local xmlns_carbons_v1 = "urn:xmpp:carbons:1"; local xmlns_carbons_v0 = "urn:xmpp:carbons:0"; local bare_sessions = bare_sessions; local function adhoc_status(self, data, state) local result; local bare_jid = jid_bare(data.from); local user_sessions = bare_sessions[bare_jid]; local result = ""; user_sessions = user_sessions and user_sessions.sessions; for _, session in pairs(user_sessions) do if session.full_jid then result = result .. session.full_jid .. ": " .. ( (session.want_carbons == xmlns_carbons_v2 and "v2" ) or (session.want_carbons == xmlns_carbons_v1 and "v1" ) or (session.want_carbons == xmlns_carbons_v0 and "v0" ) or "none" ) .. "\n"; end end return { info = result, status = "completed" }; end local status_desc = adhoc_new("Carbons: Get Status", "mod_carbons_adhoc#status", adhoc_status); module:add_item("adhoc", status_desc);
mit
drogers141/mac-hammerspoon
winops.lua
1
2488
-- Operations on windows that make use of lower level utils -- among the functions here are those intended to be bound to keys winops = {} local winutil = dofile(package.searchpath("winutil", package.path)) local fn = hs.fnutils ----------------------------------------------------------- -- Window Movement and Resizing ----------------------------------------------------------- local function move_win(mvec) local w = hs.window.focusedWindow() winutil.move_win(w, mvec) end local function resize_win(mvec) local w = hs.window.focusedWindow() winutil.resize_win(w, mvec) end -- move window right 5 percent of screen winops.move_win_right_5 = fn.partial(move_win, {x=5, y=0}) --function winops.move_win_right_5() -- move_win({x=5, y=0}) --end -- move window left 5 percent of screen winops.move_win_left_5 = fn.partial(move_win, {x=-5, y=0}) -- move window up 5 percent of screen winops.move_win_up_5 = fn.partial(move_win, {x=0, y=-5}) -- move window down 5 percent of screen winops.move_win_down_5 = fn.partial(move_win, {x=0, y=5}) -- resize window right 5 percent of screen winops.resize_win_right_5 = fn.partial(resize_win, {x=5, y=0}) -- resize window left 5 percent of screen winops.resize_win_left_5 = fn.partial(resize_win, {x=-5, y=0}) -- resize window up 5 percent of screen winops.resize_win_up_5 = fn.partial(resize_win, {x=0, y=-5}) -- resize window down 5 percent of screen winops.resize_win_down_5 = fn.partial(resize_win, {x=0, y=5}) local function throw_win(direction) local win = hs.window.focusedWindow() winutil.throw_win(win, direction) end -- throw window to right side of screen winops.throw_right = fn.partial(throw_win, "right") -- throw window to left side of screen winops.throw_left = fn.partial(throw_win, "left") -- throw window to top of screen winops.throw_up = fn.partial(throw_win, "up") -- throw window to bottom of screen winops.throw_down = fn.partial(throw_win, "down") local function expand_fill_win(direction) local win = hs.window.focusedWindow() winutil.expand_fill_win(win, direction) end -- expand window to right side of screen winops.expand_fill_right = fn.partial(expand_fill_win, "right") -- expand window to left side of screen winops.expand_fill_left = fn.partial(expand_fill_win, "left") -- expand window to top of screen winops.expand_fill_up = fn.partial(expand_fill_win, "up") -- expand window to bottom of screen winops.expand_fill_down = fn.partial(expand_fill_win, "down") return winops
mit
duk3luk3/MoonGen
lua/include/lib/StackTracePlus/init.lua
44
12501
-- tables local _G = _G local string, io, debug, coroutine = string, io, debug, coroutine -- functions local tostring, print, require = tostring, print, require local next, assert = next, assert local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs local error = error assert(debug, "debug table must be available at this point") local io_open = io.open local string_gmatch = string.gmatch local string_sub = string.sub local table_concat = table.concat local _M = { max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)' } -- this tables should be weak so the elements in them won't become uncollectable local m_known_tables = { [_G] = "_G (global table)" } local function add_known_module(name, desc) local ok, mod = pcall(require, name) if ok then m_known_tables[mod] = desc end end add_known_module("string", "string module") add_known_module("io", "io module") add_known_module("os", "os module") add_known_module("table", "table module") add_known_module("math", "math module") add_known_module("package", "package module") add_known_module("debug", "debug module") add_known_module("coroutine", "coroutine module") -- lua5.2 add_known_module("bit32", "bit32 module") -- luajit add_known_module("bit", "bit module") add_known_module("jit", "jit module") local m_user_known_tables = {} local m_known_functions = {} for _, name in ipairs{ -- Lua 5.2, 5.1 "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "load", "loadfile", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require", "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", -- Lua 5.1 "gcinfo", "getfenv", "loadstring", "module", "newproxy", "setfenv", "unpack", -- TODO: add table.* etc functions } do if _G[name] then m_known_functions[_G[name]] = name end end local m_user_known_functions = {} local function safe_tostring (value) local ok, err = pcall(tostring, value) if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end end -- Private: -- Parses a line, looking for possible function definitions (in a very naïve way) -- Returns '(anonymous)' if no function name was found in the line local function ParseLine(line) assert(type(line) == "string") --print(line) local match = line:match("^%s*function%s+(%w+)") if match then --print("+++++++++++++function", match) return match end match = line:match("^%s*local%s+function%s+(%w+)") if match then --print("++++++++++++local", match) return match end match = line:match("^%s*local%s+(%w+)%s+=%s+function") if match then --print("++++++++++++local func", match) return match end match = line:match("%s*function%s*%(") -- this is an anonymous function if match then --print("+++++++++++++function2", match) return "(anonymous)" end return "(anonymous)" end -- Private: -- Tries to guess a function's name when the debug info structure does not have it. -- It parses either the file or the string where the function is defined. -- Returns '?' if the line where the function is defined is not found local function GuessFunctionName(info) --print("guessing function name") if type(info.source) == "string" and info.source:sub(1,1) == "@" then local file, err = io_open(info.source:sub(2), "r") if not file then print("file not found: "..tostring(err)) -- whoops! return "?" end local line for i = 1, info.linedefined do line = file:read("*l") end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) else local line local lineNumber = 0 for l in string_gmatch(info.source, "([^\n]+)\n-") do lineNumber = lineNumber + 1 if lineNumber == info.linedefined then line = l break end end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) end end --- -- Dumper instances are used to analyze stacks and collect its information. -- local Dumper = {} Dumper.new = function(thread) local t = { lines = {} } for k,v in pairs(Dumper) do t[k] = v end t.dumping_same_thread = (thread == coroutine.running()) -- if a thread was supplied, bind it to debug.info and debug.get -- we also need to skip this additional level we are introducing in the callstack (only if we are running -- in the same thread we're inspecting) if type(thread) == "thread" then t.getinfo = function(level, what) if t.dumping_same_thread and type(level) == "number" then level = level + 1 end return debug.getinfo(thread, level, what) end t.getlocal = function(level, loc) if t.dumping_same_thread then level = level + 1 end return debug.getlocal(thread, level, loc) end else t.getinfo = debug.getinfo t.getlocal = debug.getlocal end return t end -- helpers for collecting strings to be used when assembling the final trace function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table_concat(self.lines) end --- -- Private: -- Iterates over the local variables of a given function. -- -- @param level The stack level where the function is. -- function Dumper:DumpLocals (level) local prefix = "\t " local i = 1 if self.dumping_same_thread then level = level + 1 end local name, value = self.getlocal(level, i) if not name then return end self:add("\tLocal variables:\r\n") while name do if type(value) == "number" then self:add_f("%s%s = number: %g\r\n", prefix, name, value) elseif type(value) == "boolean" then self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value)) elseif type(value) == "string" then self:add_f("%s%s = string: %q\r\n", prefix, name, value) elseif type(value) == "userdata" then self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value)) elseif type(value) == "nil" then self:add_f("%s%s = nil\r\n", prefix, name) elseif type(value) == "table" then if m_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value]) elseif m_user_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value]) else local txt = "{" for k,v in pairs(value) do txt = txt..safe_tostring(k)..":"..safe_tostring(v) if #txt > _M.max_tb_output_len then txt = txt.." (more...)" break end if next(value, k) then txt = txt..", " end end self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}") end elseif type(value) == "function" then local info = self.getinfo(value, "nS") local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value] if info.what == "C" then self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value))) else local source = info.short_src if source:sub(2,7) == "string" then source = source:sub(9) -- uno más, por el espacio que viene (string "Baragent.Main", por ejemplo) end --for k,v in pairs(info) do print(k,v) end fun_name = fun_name or GuessFunctionName(info) self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source) end elseif type(value) == "thread" then self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value)) end i = i + 1 name, value = self.getlocal(level, i) end end --- -- Public: -- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc. -- This function is suitable to be used as an error handler with pcall or xpcall -- -- @param thread An optional thread whose stack is to be inspected (defaul is the current thread) -- @param message An optional error string or object. -- @param level An optional number telling at which level to start the traceback (default is 1) -- -- Returns a string with the stack trace and a string with the original error. -- function _M.stacktrace(thread, message, level) if type(thread) ~= "thread" then -- shift parameters left thread, message, level = nil, thread, message end thread = thread or coroutine.running() level = level or 1 local dumper = Dumper.new(thread) local original_error if type(message) == "table" then dumper:add("an error object {\r\n") local first = true for k,v in pairs(message) do if first then dumper:add(" ") first = false else dumper:add(",\r\n ") end dumper:add(safe_tostring(k)) dumper:add(": ") dumper:add(safe_tostring(v)) end dumper:add("\r\n}") original_error = dumper:concat_lines() elseif type(message) == "string" then dumper:add(message) original_error = message end dumper:add("\r\n") dumper:add[[ Stack Traceback =============== ]] --print(error_message) local level_to_show = level if dumper.dumping_same_thread then level = level + 1 end local info = dumper.getinfo(level, "nSlf") while info do if info.what == "main" then if string_sub(info.source, 1, 1) == "@" then dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline) else dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline) end elseif info.what == "C" then --print(info.namewhat, info.name) --for k,v in pairs(info) do print(k,v, type(v)) end local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func) dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name) --dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value))) elseif info.what == "tail" then --print("tail") --for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name) dumper:add_f("(%d) tail call\r\n", level_to_show) dumper:DumpLocals(level) elseif info.what == "Lua" then local source = info.short_src local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name if source:sub(2, 7) == "string" then source = source:sub(9) end local was_guessed = false if not function_name or function_name == "?" then --for k,v in pairs(info) do print(k,v, type(v)) end function_name = GuessFunctionName(info) was_guessed = true end -- test if we have a file name local function_type = (info.namewhat == "") and "function" or info.namewhat if info.source and info.source:sub(1, 1) == "@" then dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") elseif info.source and info.source:sub(1,1) == '#' then dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") else dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source) end dumper:DumpLocals(level) else dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what) end level = level + 1 level_to_show = level_to_show + 1 info = dumper.getinfo(level, "nSlf") end return dumper:concat_lines(), original_error end -- -- Adds a table to the list of known tables function _M.add_known_table(tab, description) if m_known_tables[tab] then error("Cannot override an already known table") end m_user_known_tables[tab] = description end -- -- Adds a function to the list of known functions function _M.add_known_function(fun, description) if m_known_functions[fun] then error("Cannot override an already known function") end m_user_known_functions[fun] = description end return _M
mit
cshore/packages
utils/luci-app-lxc/files/controller/lxc.lua
26
4082
--[[ LuCI LXC module Copyright (C) 2014, Cisco Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Author: Petar Koretic <petar.koretic@sartura.hr> ]]-- module("luci.controller.lxc", package.seeall) require "ubus" local conn = ubus.connect() if not conn then error("Failed to connect to ubus") end function fork_exec(command) local pid = nixio.fork() if pid > 0 then return elseif pid == 0 then -- change to root dir nixio.chdir("/") -- patch stdin, out, err to /dev/null local null = nixio.open("/dev/null", "w+") if null then nixio.dup(null, nixio.stderr) nixio.dup(null, nixio.stdout) nixio.dup(null, nixio.stdin) if null:fileno() > 2 then null:close() end end -- replace with target command nixio.exec("/bin/sh", "-c", command) end end function index() page = node("admin", "services", "lxc") page.target = cbi("lxc") page.title = _("LXC Containers") page.order = 70 page = entry({"admin", "services", "lxc_create"}, call("lxc_create"), nil) page.leaf = true page = entry({"admin", "services", "lxc_action"}, call("lxc_action"), nil) page.leaf = true page = entry({"admin", "services", "lxc_get_downloadable"}, call("lxc_get_downloadable"), nil) page.leaf = true page = entry({"admin", "services", "lxc_configuration_get"}, call("lxc_configuration_get"), nil) page.leaf = true page = entry({"admin", "services", "lxc_configuration_set"}, call("lxc_configuration_set"), nil) page.leaf = true end function lxc_get_downloadable() luci.http.prepare_content("application/json") local f = io.popen('uname -m', 'r') local target = f:read('*a') f:close() target = target:gsub("^%s*(.-)%s*$", "%1") local templates = {} local f = io.popen('lxc-create -n just_want_to_list_available_lxc_templates -t download -- --list', 'r') for line in f:lines() do local dist,version = line:match("^(%S+)%s+(%S+)%s+" .. target .. "%s+default%s+%S+$") if dist~=nil and version~=nil then templates[#templates + 1] = dist .. ":" .. version end end f:close() luci.http.write_json(templates) end function lxc_create(lxc_name, lxc_template) luci.http.prepare_content("text/plain") local uci = require("uci").cursor() local url = uci:get("lxc", "lxc", "url") if not pcall(dofile, "/etc/openwrt_release") then return luci.http.write("1") end local f = io.popen('uname -m', 'r') local target = f:read('*a') f:close() target = target:gsub("^%s*(.-)%s*$", "%1") local lxc_dist = lxc_template:gsub("(.*):(.*)", '%1') local lxc_release = lxc_template:gsub("(.*):(.*)", '%2') local data = conn:call("lxc", "create", { name = lxc_name, template = "download", args = { "--server", url, "--no-validate", "--dist", lxc_dist, "--release", lxc_release, "--arch", target } } ) luci.http.write(data) end function lxc_action(lxc_action, lxc_name) luci.http.prepare_content("application/json") local data, ec = conn:call("lxc", lxc_action, lxc_name and { name = lxc_name} or {} ) luci.http.write_json(ec and {} or data) end function lxc_get_config_path() local f = io.open("/etc/lxc/lxc.conf", "r") local content = f:read("*all") f:close() local ret = content:match('^%s*lxc.lxcpath%s*=%s*([^%s]*)') if ret then return ret .. "/" else return "/srv/lxc/" end end function lxc_configuration_get(lxc_name) luci.http.prepare_content("text/plain") local f = io.open(lxc_get_config_path() .. lxc_name .. "/config", "r") local content = f:read("*all") f:close() luci.http.write(content) end function lxc_configuration_set(lxc_name) luci.http.prepare_content("text/plain") local lxc_configuration = luci.http.formvalue("lxc_configuration") if lxc_configuration == nil then return luci.http.write("1") end local f, err = io.open(lxc_get_config_path() .. lxc_name .. "/config","w+") if not f then return luci.http.write("2") end f:write(lxc_configuration) f:close() luci.http.write("0") end
gpl-2.0
mua/BlockingBad
support.lua
1
4793
---------------------------- -- Author: M. Utku Altinkaya -- utkualtinkaya@gmail.com ---------------------------- -- some support functions I've took from Lua Wiki function Class( baseClass ) local new_class = {} local class_mt = { __index = new_class } function new_class:create(...) local newinst = {} setmetatable( newinst, class_mt ) newinst:init(...) return newinst end if baseClass then setmetatable( new_class, { __index = baseClass } ) end return new_class end --[[ Save Table to File Load Table from File v 1.0 Lua 5.2 compatible Only Saves Tables, Numbers and Strings Insides Table References are saved Does not save Userdata, Metatables, Functions and indices of these ---------------------------------------------------- table.save( table , filename ) on failure: returns an error msg ---------------------------------------------------- table.load( filename or stringtable ) Loads a table that has been saved via the table.save function on success: returns a previously saved table on failure: returns as second argument an error msg ---------------------------------------------------- Licensed under the same terms as Lua itself. ]]-- do -- declare local variables --// exportstring( string ) --// returns a "Lua" portable version of the string local function exportstring( s ) return string.format("%q", s) end --// The Save Function function table.save( tbl,filename ) local charS,charE = " ","\n" local file,err = io.open( filename, "wb" ) if err then return err end -- initiate variables for save procedure local tables,lookup = { tbl },{ [tbl] = 1 } file:write( "return {"..charE ) for idx,t in ipairs( tables ) do file:write( "-- Table: {"..idx.."}"..charE ) file:write( "{"..charE ) local thandled = {} for i,v in ipairs( t ) do thandled[i] = true local stype = type( v ) -- only handle value if stype == "table" then if not lookup[v] then table.insert( tables, v ) lookup[v] = #tables end file:write( charS.."{"..lookup[v].."},"..charE ) elseif stype == "string" then file:write( charS..exportstring( v )..","..charE ) elseif stype == "number" then file:write( charS..tostring( v )..","..charE ) end end for i,v in pairs( t ) do -- escape handled values if (not thandled[i]) then local str = "" local stype = type( i ) -- handle index if stype == "table" then if not lookup[i] then table.insert( tables,i ) lookup[i] = #tables end str = charS.."[{"..lookup[i].."}]=" elseif stype == "string" then str = charS.."["..exportstring( i ).."]=" elseif stype == "number" then str = charS.."["..tostring( i ).."]=" end if str ~= "" then stype = type( v ) -- handle value if stype == "table" then if not lookup[v] then table.insert( tables,v ) lookup[v] = #tables end file:write( str.."{"..lookup[v].."},"..charE ) elseif stype == "string" then file:write( str..exportstring( v )..","..charE ) elseif stype == "number" then file:write( str..tostring( v )..","..charE ) end end end end file:write( "},"..charE ) end file:write( "}" ) file:close() end --// The Load Function function table.load( sfile ) local ftables,err = loadfile( sfile ) if err then return _,err end local tables = ftables() for idx = 1,#tables do local tolinki = {} for i,v in pairs( tables[idx] ) do if type( v ) == "table" then tables[idx][i] = tables[v[1]] end if type( i ) == "table" and tables[i[1]] then table.insert( tolinki,{ i,tables[i[1]] } ) end end -- link indices for _,v in ipairs( tolinki ) do tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil end end return tables[1] end -- close do end
bsd-3-clause
gajop/Zero-K
scripts/armpw.lua
15
3943
include "constants.lua" -- pieces local head = piece "head" local hips = piece "hips" local chest = piece "chest" -- left arm local lshoulder = piece "lshoulder" local lforearm = piece "lforearm" local gun = piece "gun" local magazine = piece "magazine" local flare = piece "flare" local ejector = piece "ejector" -- right arm local rshoulder = piece "rshoulder" local rforearm = piece "rforearm" -- left leg local lthigh = piece "lthigh" local lshin = piece "lshin" local lfoot = piece "lfoot" -- right leg local rthigh = piece "rthigh" local rshin = piece "rshin" local rfoot = piece "rfoot" local smokePiece = {head, hips, chest} --constants local runspeed = 8 local steptime = 40 -- variables local firing = 0 --signals local SIG_Restore = 1 local SIG_Walk = 2 local SIG_Aim = 4 function script.Create() StartThread(SmokeUnit, smokePiece) Turn(flare, x_axis, 1.6, 5) Turn(lshoulder, x_axis, -0.9, 5) Turn(lforearm, z_axis, -0.2, 5) end local function Walk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) while (true) do Turn(lshoulder, x_axis, -1.2, runspeed*0.2) Turn(hips, z_axis, 0.1, runspeed*0.05) Turn(rshoulder, x_axis, 0.5, runspeed*0.3) Turn(rthigh, x_axis, -1.5, runspeed*1) Turn(rshin, x_axis, 1.3, runspeed*1) -- Turn(rfoot, x_axis, 0.5, runspeed*1) Turn(lshin, x_axis, 0.2, runspeed*1) Turn(lthigh, x_axis, 1.2, runspeed*1) WaitForTurn(rthigh, x_axis) Sleep(steptime) Turn(lshoulder, x_axis, -0.6, runspeed*0.2) Turn(hips, z_axis, -0.1, runspeed*0.05) Turn(rshoulder, x_axis, -0.5, runspeed*0.3) Turn(lthigh, x_axis, -1.5, runspeed*1) Turn(lshin, x_axis, 1.3, runspeed*1) -- Turn(lfoot, x_axis, 0.5, runspeed*1) Turn(rshin, x_axis, 0.2, runspeed*1) Turn(rthigh, x_axis, 1.2, runspeed*1) WaitForTurn(lthigh, x_axis) Sleep(steptime) end end local function StopWalk() Signal(SIG_Walk) SetSignalMask(SIG_Walk) Turn(hips, z_axis, 0, 0.5) Turn(lthigh, x_axis, 0, 2) Turn(lshin, x_axis, 0, 2) Turn(lfoot, x_axis, 0, 2) Turn(rthigh, x_axis, 0, 2) Turn(rshin, x_axis, 0, 2) Turn(rfoot, x_axis, 0, 2) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(StopWalk) end local function RestoreAfterDelay() Signal(SIG_Restore) SetSignalMask(SIG_Restore) Sleep(2000) firing = 0 Turn(chest, y_axis, 0, 3) Turn(lshoulder, x_axis, -0.9, 5) Turn(rshoulder, x_axis, 0, 3) Turn(lforearm, z_axis, -0.2, 5) Turn(lshoulder, z_axis, 0, 3) Turn(rshoulder, z_axis, 0, 3) Turn(head, y_axis, 0, 2) Turn(head, x_axis, 0, 2) Spin(magazine, y_axis, 0) end function script.QueryWeapon(num) return flare end function script.AimFromWeapon(num) return chest end function script.AimWeapon(num, heading, pitch) Signal(SIG_Aim) SetSignalMask(SIG_Aim) --[[ Gun Hugger Turn(chest, y_axis, 1.1 + heading, 12) Turn(lshoulder, x_axis, -1 -pitch, 12) Turn(rshoulder, x_axis, -0.9 -pitch, 12) Turn(rshoulder, z_axis, 0.3, 9) Turn(lshoulder, z_axis, -0.3, 9) Turn(head, y_axis, -0.8, 9) Turn(head, x_axis, -pitch, 9)--]] -- Outstreched Arm firing = 1 Turn(chest, y_axis, heading, 12) Turn(lforearm, z_axis, 0, 5) Turn(lshoulder, x_axis, -pitch - 1.5, 12) WaitForTurn(chest, y_axis) WaitForTurn(lshoulder, x_axis) StartThread(RestoreAfterDelay) return true end function script.FireWeapon(num) Spin(magazine, y_axis, 2) EmitSfx(ejector, 1024) EmitSfx(flare, 1025) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= .25) then Explode(hips, sfxNone) Explode(head, sfxNone) Explode(chest, sfxNone) return 1 -- corpsetype elseif (severity <= .5) then Explode(hips, sfxNone) Explode(head, sfxNone) Explode(chest, sfxShatter) return 1 -- corpsetype else Explode(hips, sfxShatter) Explode(head, sfxSmoke + sfxFire) Explode(chest, sfxSmoke + sfxFire + sfxExplode) return 2 -- corpsetype end end
gpl-2.0
Shayan123456/bottt
plugins/Boobs.lua
150
1613
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. ًں”‍", "!butts: Get a butts NSFW image. ًں”‍" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
nobie/sesame_fw
feeds/luci/applications/luci-olsr/dist/usr/lib/lua/luci/model/cbi/olsr/olsrdplugins.lua
54
7297
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2009 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 ip = require "luci.ip" local fs = require "nixio.fs" if arg[1] then mp = Map("olsrd", translate("OLSR - Plugins")) p = mp:section(TypedSection, "LoadPlugin", translate("Plugin configuration")) p:depends("library", arg[1]) p.anonymous = true ign = p: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 lib = p:option(DummyValue, "library", translate("Library")) lib.default = arg[1] local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = ip.IPv4(val[i]) or ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s]+)%s+([^%s]+)")() local cidr if ip and mask and ip:match(":") then cidr = ip.IPv6(ip, mask) elseif ip and mask then cidr = ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "br-lan" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", Cidr2IpMask } }, ["olsrd_nameservice.so.0.3"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { DynamicList, "service", "http://me.olsr:80|tcp|my little homepage" }, { Value, "services_file", "/var/run/services_olsr" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" }, { DynamicList, "mac", "xx:xx:xx:xx:xx:xx[,0-255]" }, { Value, "macs_file", "/path/to/macs_file" }, { Value, "macs_change_script", "/path/to/script" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "127.0.0.1" } }, ["olsrd_jsoninfo.so.0.0"] = { { Value, "accept", "127.0.0.1" }, { Value, "port", "9090" }, { Value, "UUIDFile", "/etc/olsrd/olsrd.uuid" }, }, ["olsrd_watchdog.so.0.1"] = { { Value, "file", "/var/run/olsrd.watchdog" }, { Value, "interval", "30" } }, ["olsrd_mdns.so.1.0.0"] = { { DynamicList, "NonOlsrIf", "lan" } }, ["olsrd_p2pd.so.0.1.0"] = { { DynamicList, "NonOlsrIf", "lan" }, { Value, "P2pdTtl", "10" } }, ["olsrd_arprefresh.so.0.1"] = {}, ["olsrd_dot_draw.so.0.3"] = {}, ["olsrd_dyn_gw_plain.so.0.4"] = {}, ["olsrd_pgraph.so.1.1"] = {}, ["olsrd_tas.so.0.1"] = {} } -- build plugin options with dependencies if knownPlParams[arg[1]] then for _, option in ipairs(knownPlParams[arg[1]]) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.optional = true bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end field.optional = true field.default = default --field:depends({ library = arg[1] }) end end end return mp else mpi = Map("olsrd", translate("OLSR - Plugins")) local plugins = {} mpi.uci:foreach("olsrd", "LoadPlugin", function(section) if section.library and not plugins[section.library] then plugins[section.library] = true end end ) -- create a loadplugin section for each found plugin for v in fs.dir("/usr/lib") do if v:sub(1, 6) == "olsrd_" then if not plugins[v] then mpi.uci:section( "olsrd", "LoadPlugin", nil, { library = v, ignore = 1 } ) end end end t = mpi:section( TypedSection, "LoadPlugin", translate("Plugins") ) t.anonymous = true t.template = "cbi/tblsection" t.override_scheme = true function t.extedit(self, section) local lib = self.map:get(section, "library") or "" return luci.dispatcher.build_url("admin", "services", "olsrd", "plugins") .. "/" .. lib end ign = t:option( Flag, "ignore", translate("Enabled") ) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end t:option( DummyValue, "library", translate("Library") ) return mpi end
gpl-2.0
antoche/openvibe
openvibe-scenarios/trunc/share/openvibe-scenarios/bci/motor-imagery/motor-imagery-bci-graz-stimulator.lua
4
2295
dofile("../share/openvibe-plugins/stimulation/lua-stimulator-stim-codes.lua") function initialize(box) number_of_trials = box:get_setting(2) first_class = _G[box:get_setting(3)] second_class = _G[box:get_setting(4)] baseline_duration = box:get_setting(5) wait_for_beep_duration = box:get_setting(6) wait_for_cue_duration = box:get_setting(7) display_cue_duration = box:get_setting(8) feedback_duration = box:get_setting(9) end_of_trial_min_duration = box:get_setting(10) end_of_trial_max_duration = box:get_setting(11) -- initializes random seed math.randomseed(os.time()) -- fill the sequence table with predifined order sequence = {} for i = 1, number_of_trials do table.insert(sequence, 1, first_class) table.insert(sequence, 1, second_class) end -- randomize the sequence for i = 1, number_of_trials do a = math.random(1, number_of_trials*2) b = math.random(1, number_of_trials*2) swap = sequence[a] sequence[a] = sequence[b] sequence[b] = swap end end function process(box) local t=0 -- manages baseline box:send_stimulation(1, OVTK_StimulationId_ExperimentStart, t, 0) t = t + 5 box:send_stimulation(1, OVTK_StimulationId_BaselineStart, t, 0) box:send_stimulation(1, OVTK_StimulationId_Beep, t, 0) t = t + baseline_duration box:send_stimulation(1, OVTK_StimulationId_BaselineStop, t, 0) box:send_stimulation(1, OVTK_StimulationId_Beep, t, 0) t = t + 5 -- manages trials for i = 1, number_of_trials*2 do -- first display cross on screen box:send_stimulation(1, OVTK_GDF_Start_Of_Trial, t, 0) box:send_stimulation(1, OVTK_GDF_Cross_On_Screen, t, 0) t = t + wait_for_beep_duration -- warn the user the cue is going to appear box:send_stimulation(1, OVTK_StimulationId_Beep, t, 0) t = t + wait_for_cue_duration -- display cue box:send_stimulation(1, sequence[i], t, 0) t = t + display_cue_duration -- provide feedback box:send_stimulation(1, OVTK_GDF_Feedback_Continuous, t, 0) t = t + feedback_duration -- ends trial box:send_stimulation(1, OVTK_GDF_End_Of_Trial, t, 0) t = t + math.random(end_of_trial_min_duration, end_of_trial_max_duration) end box:send_stimulation(1, OVTK_StimulationId_ExperimentStop, t, 0) t = t + 5 box:send_stimulation(1, OVTK_StimulationId_Train, t, 0) end
lgpl-2.1
nobie/sesame_fw
feeds/luci/modules/admin-mini/dist/usr/lib/lua/luci/model/cbi/mini/wifi.lua
73
11663
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wifi"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end -- WLAN-Scan-Table -- t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return self.map:get(section, "ESSID") end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") if hwtype == "atheros" then mode = s:option(ListValue, "hwmode", translate("Mode")) mode.override_values = true mode:value("", "auto") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true end ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "atheros" or hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "atheros" or hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "atheros" or hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" or hwtype == "atheros" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
gpl-2.0
nobie/sesame_fw
feeds/luci/applications/luci-minidlna/luasrc/controller/minidlna.lua
73
1448
--[[ LuCI - Lua Configuration Interface - miniDLNA support Copyright 2012 Gabor Juhos <juhosg@openwrt.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$ ]]-- module("luci.controller.minidlna", package.seeall) function index() if not nixio.fs.access("/etc/config/minidlna") then return end local page page = entry({"admin", "services", "minidlna"}, cbi("minidlna"), _("miniDLNA")) page.dependent = true entry({"admin", "services", "minidlna_status"}, call("minidlna_status")) end function minidlna_status() local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local port = tonumber(uci:get_first("minidlna", "minidlna", "port")) local status = { running = (sys.call("pidof minidlna >/dev/null") == 0), audio = 0, video = 0, image = 0 } if status.running then local fd = sys.httpget("http://127.0.0.1:%d/" % (port or 8200), true) if fd then local html = fd:read("*a") if html then status.audio = (tonumber(html:match("Audio files: (%d+)")) or 0) status.video = (tonumber(html:match("Video files: (%d+)")) or 0) status.image = (tonumber(html:match("Image files: (%d+)")) or 0) end fd:close() end end luci.http.prepare_content("application/json") luci.http.write_json(status) end
gpl-2.0
AnsonSmith/kong
spec/plugins/ssl/access_spec.lua
5
4011
local spec_helper = require "spec.spec_helpers" local ssl_util = require "kong.plugins.ssl.ssl_util" local url = require "socket.url" local IO = require "kong.tools.io" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local ssl_fixtures = require "spec.plugins.ssl.fixtures" local STUB_GET_SSL_URL = spec_helper.STUB_GET_SSL_URL local STUB_GET_URL = spec_helper.STUB_GET_URL local API_URL = spec_helper.API_URL describe("SSL Plugin", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { { name = "API TESTS 11 (ssl)", public_dns = "ssl1.com", target_url = "http://mockbin.com" }, { name = "API TESTS 12 (ssl)", public_dns = "ssl2.com", target_url = "http://mockbin.com" }, { name = "API TESTS 13 (ssl)", public_dns = "ssl3.com", target_url = "http://mockbin.com" } }, plugin_configuration = { { name = "ssl", value = { cert = ssl_fixtures.cert, key = ssl_fixtures.key }, __api = 1 }, { name = "ssl", value = { cert = ssl_fixtures.cert, key = ssl_fixtures.key, only_https = true }, __api = 2 } } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("SSL Util", function() it("should not convert an invalid cert to DER", function() assert.falsy(ssl_util.cert_to_der("asd")) end) it("should convert a valid cert to DER", function() assert.truthy(ssl_util.cert_to_der(ssl_fixtures.cert)) end) it("should not convert an invalid key to DER", function() assert.falsy(ssl_util.key_to_der("asd")) end) it("should convert a valid key to DER", function() assert.truthy(ssl_util.key_to_der(ssl_fixtures.key)) end) end) describe("SSL Resolution", function() it("should return default CERTIFICATE when requesting other APIs", function() local parsed_url = url.parse(STUB_GET_SSL_URL) local res = IO.os_execute("(echo \"GET /\"; sleep 2) | openssl s_client -connect "..parsed_url.host..":"..tostring(parsed_url.port).." -servername test4.com") assert.truthy(res:match("US/ST=California/L=San Francisco/O=Kong/OU=IT Department/CN=localhost")) end) it("should work when requesting a specific API", function() local parsed_url = url.parse(STUB_GET_SSL_URL) local res = IO.os_execute("(echo \"GET /\"; sleep 2) | openssl s_client -connect "..parsed_url.host..":"..tostring(parsed_url.port).." -servername ssl1.com") assert.truthy(res:match("US/ST=California/L=San Francisco/O=Kong/OU=IT/CN=ssl1.com")) end) end) describe("only_https", function() it("should block request without https", function() local response, status, headers = http_client.get(STUB_GET_URL, nil, { host = "ssl2.com" }) assert.are.equal(426, status) assert.are.same("close, Upgrade", headers.connection) assert.are.same("TLS/1.0, HTTP/1.1", headers.upgrade) assert.are.same("Please use HTTPS protocol", cjson.decode(response).message) end) it("should not block request with https", function() local _, status = http_client.get(STUB_GET_SSL_URL, nil, { host = "ssl2.com" }) assert.are.equal(200, status) end) end) describe("should work with curl", function() local response = http_client.get(API_URL.."/apis/", {public_dns="ssl3.com"}) local api_id = cjson.decode(response).data[1].id local kong_working_dir = spec_helper.get_env(spec_helper.TEST_CONF_FILE).configuration.nginx_working_dir local ssl_cert_path = IO.path:join(kong_working_dir, "ssl", "kong-default.crt") local ssl_key_path = IO.path:join(kong_working_dir, "ssl", "kong-default.key") local res = IO.os_execute("curl -s -o /dev/null -w \"%{http_code}\" "..API_URL.."/apis/"..api_id.."/plugins/ --form \"name=ssl\" --form \"value.cert=@"..ssl_cert_path.."\" --form \"value.key=@"..ssl_key_path.."\"") assert.are.equal(201, tonumber(res)) end) end)
apache-2.0
casseveritt/premake
tests/actions/codeblocks/codeblocks_files.lua
21
1664
-- -- tests/actions/codeblocks/codeblocks_files.lua -- Validate generation of files block in CodeLite C/C++ projects. -- Copyright (c) 2011 Jason Perkins and the Premake project -- T.codeblocks_files = { } local suite = T.codeblocks_files local codeblocks = premake.codeblocks -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) codeblocks.files(prj) end -- -- Test grouping and nesting -- function suite.SimpleSourceFile() files { "hello.cpp" } prepare() test.capture [[ <Unit filename="hello.cpp"> </Unit> ]] end function suite.SingleFolderLevel() files { "src/hello.cpp" } prepare() test.capture [[ <Unit filename="src/hello.cpp"> </Unit> ]] end function suite.MultipleFolderLevels() files { "src/greetings/hello.cpp" } prepare() test.capture [[ <Unit filename="src/greetings/hello.cpp"> </Unit> ]] end -- -- Test source file type handling -- function suite.CFileInCppProject() files { "hello.c" } prepare() test.capture [[ <Unit filename="hello.c"> <Option compilerVar="CC" /> </Unit> ]] end function suite.WindowsResourceFile() files { "hello.rc" } prepare() test.capture [[ <Unit filename="hello.rc"> <Option compilerVar="WINDRES" /> </Unit> ]] end function suite.PchFile() files { "hello.h" } pchheader "hello.h" prepare() test.capture [[ <Unit filename="hello.h"> <Option compilerVar="CPP" /> <Option compile="1" /> <Option weight="0" /> <Add option="-x c++-header" /> </Unit> ]] end
bsd-3-clause
gajop/Zero-K
LuaUI/Widgets/unit_shield_guard.lua
12
18168
-- $Id$ --[[ local versionName = "v1.0b" function widget:GetInfo() return { name = "Shield Guard", desc = versionName .. " Units walking with Area Shield will move at same speed. Area Shield will slow down for slow unit and fast unit will slow down for Area Shield. Work with GUARD (Area Shield) command & MOVE command, but doesn't work with queueing (result only apply to first queue).", author = "Google Frog, +renovated by msafwan", date = "9 Mar, 2009, +9 April 2012", license = "GNU GPL, v2 or later", layer = 5, enabled = false -- loaded by default? } end -- Speedups local CMD_MOVE = CMD.MOVE local CMD_GUARD = CMD.GUARD local CMD_SET_WANTED_MAX_SPEED = CMD.SET_WANTED_MAX_SPEED local CMD_WAITCODE_GATHER = CMD.WAITCODE_GATHER local spGetSelectedUnits = Spring.GetSelectedUnits local spGetUnitDefID = Spring.GetUnitDefID local spGetTeamUnits = Spring.GetTeamUnits local spSendCommands = Spring.SendCommands local spGiveOrderToUnitArray = Spring.GiveOrderToUnitArray local team = Spring.GetMyTeamID() local areaShieldUnit = {} --//variable: store all relevant Area Shield's unitIDs & its follower's unitIDs local follower_to_areaShieldUnit_meta = {} --//variable: remember which unit was placed under which Area Shield unit local enableEcho = false --//constant: tools to fix bug local areaShieldCount = 0 local shieldSpeed=0 ---------------------------- -- CONFIG local shieldUnitName = { "core_spectre", "corthud", } ---------------------------- -- Add/remove shielded -- Override and add units guarding areaShieldUnit function widget:CommandNotify(id, params, options) --if enableEcho then Spring.Echo(areaShieldCount) end --if enableEcho then Spring.Echo(options) end if areaShieldCount > 0 and not options.shift then --//skip everything if player never build any Area Shield unit, and skip "SHIFT" since qeueuing is not supported by this widget. local selectedUnits = spGetSelectedUnits() local availableAreaShieldUnit = {} for i=1, #selectedUnits, 1 do local selectedUnitID = selectedUnits[i] if areaShieldUnit[selectedUnitID] then availableAreaShieldUnit[#availableAreaShieldUnit+1] = selectedUnitID end end if #availableAreaShieldUnit > 0 and id == CMD_MOVE then --//perform command substitution when areaShield is part of the selection and is using MOVE command. local maxSpeed=shieldSpeed for i=1, #availableAreaShieldUnit , 1 do --//append "selectedUnit" with the list of unit that guarding the area-Shield. These extra unit will also be given the same move command local areaShieldID = availableAreaShieldUnit[i] local followerList = Deepcopy(areaShieldUnit[areaShieldID].guardedBy) --//NEEDED: because LUA didn't copy the table's value, instead it refer to the table itself and any changes made to the copy is not localized & will propagate to the original table local listLenght = #followerList for j=1, listLenght, 1 do local endOfFollowerIndex = #followerList selectedUnits[#selectedUnits+1]=followerList[endOfFollowerIndex] local unitDefID = spGetUnitDefID(followerList[endOfFollowerIndex]) local unitDef = UnitDefs[unitDefID] local speed = unitDef.speed/30 if speed< maxSpeed then maxSpeed= speed end followerList[endOfFollowerIndex] = nil --//add nil to endOfTable so that '#' index shifted down by 1. So "followerList" will be read from top-down as the cycle continue end end --if enableEcho then Spring.Echo(maxSpeed .. " maxSpeed ") Spring.Echo(CMD_WAITCODE_GATHER .." " .. CMD.GATHERWAIT .. " waitcodeGather, gatherwait") end spGiveOrderToUnitArray(selectedUnits, id, params,{}) --//use "ctrl" to activate engine's formation move, use "shift" to add this command on top of previous command. --spGiveOrderToUnitArray(selectedUnits, CMD_SET_WANTED_MAX_SPEED, {maxSpeed},{"shift",}) --spGiveOrderToUnitArray(selectedUnits, CMD_WAITCODE_GATHER, {},{"shift"}) --// allow units to wait each other before going to next queue (assuming player will queue another command) for i=1, #availableAreaShieldUnit , 1 do --//go over the areaShield's "guardBy" list and queue a (preserve the) GUARD order local areaShieldUnitID = availableAreaShieldUnit[i] local followerList = areaShieldUnit[areaShieldUnitID].guardedBy if enableEcho then Spring.Echo(areaShieldUnitID .. " areaShieldUnitID") end spGiveOrderToUnitArray(followerList, CMD_GUARD, {areaShieldUnitID,},{"shift"}) --//tell units to queue GUARD the area shield units end return true --//make Spring skip user's command (because we already replaced with a new one) elseif #availableAreaShieldUnit == 0 then --//remove any unit from the "guarding Area Shield ('guardBy')" list if unit receive command which did not involve any Area Shield units for i=1, #selectedUnits, 1 do local unitID = selectedUnits[i] if follower_to_areaShieldUnit_meta[unitID] then local areaShieldUnitID = follower_to_areaShieldUnit_meta[unitID].areaShieldUnitID local positionInTable = follower_to_areaShieldUnit_meta[unitID].positionInTable local guardedBy = areaShieldUnit[areaShieldUnitID].guardedBy if enableEcho then Spring.Echo(guardedBy) end guardedBy, follower_to_areaShieldUnit_meta = RemoveTableEntry(guardedBy, positionInTable, follower_to_areaShieldUnit_meta) --//remove table entry & metaTable entry and fill the space areaShieldUnit[areaShieldUnitID].guardedBy = guardedBy --//update the "guardedBy" table with the latest changes end end end if (id == CMD_GUARD) then if enableEcho then Spring.Echo("isGuard command") end local targetID = params[1] if areaShieldUnit[targetID] then --//if targetID is an areaShield unit, then put the selected unit into the "guardedBy" list in the areaShield's table... for i=1, #selectedUnits, 1 do local notAreaShield = true for areaShieldID, _ in pairs(areaShieldUnit) do --//exclude any Area Shield unit from the "guardedBy" list. This prevent bug and also gave nice feature local unitID = selectedUnits[i] if areaShieldID == unitID then notAreaShield = false end end if notAreaShield then local placeToPut = #areaShieldUnit[targetID].guardedBy +1 areaShieldUnit[targetID].guardedBy[placeToPut] = selectedUnits[i] --//insert selected unitID into the areaShield's "guardedBy" table --if enableEcho then Spring.Echo(targetID .. " targetID") end follower_to_areaShieldUnit_meta[selectedUnits[i] ]= {areaShieldUnitID = targetID,positionInTable = placeToPut,} end end end end end end ----------------------- --Add shield function Deepcopy(object) --//method to actually copy a table instead of refering to the table's object (to fix a bug). Reference: http://lua-users.org/wiki/CopyTable , http://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value local lookup_table = {} local function _copy(object) if type(object) ~= "table" then return object elseif lookup_table[object] then return lookup_table[object] end local new_table = {} lookup_table[object] = new_table for index, value in pairs(object) do new_table[_copy(index)] = _copy(value) end return setmetatable(new_table, getmetatable(object)) end return _copy(object) end function widget:UnitCreated(unitID, unitDefID, unitTeam) --//record all Area Shield unit into "areaShieldUnit". if unitTeam ~= team then return end local unitDef = UnitDefs[unitDefID] if (unitDef ~= nil) then for i=1, #shieldUnitName,1 do if enableEcho then Spring.Echo(unitDef.name .. " " .. shieldUnitName[i]) end if (unitDef.name == shieldUnitName[i]) then shieldSpeed = unitDef.speed/30 --local waits = shieldWait[unitDef.name] if enableEcho then Spring.Echo("areaShield Insert") end areaShieldUnit[unitID] = {guardedBy = {},} --waits = waits,} areaShieldCount = areaShieldCount +1 break end end end end ----------------------- --Remove shield or follower_to_areaShieldUnit_meta function RemoveTableEntry(unitIDTable, index, metaTable) --//will remove an entry and then fill the void with entry from the top index local normalEntry = true local endOfTable = #unitIDTable if index == endOfTable then normalEntry = false end--//check if index is on the endOfTable or not. If is endOfTable then just remove entry and done. metaTable[unitIDTable[index] ] = nil --//empty the metaTable associated with current index unitIDTable[index] = nil --//empty the current index if normalEntry then unitIDTable[index] = unitIDTable[endOfTable] --//move endOfTable entry to the current index local unitID = unitIDTable[endOfTable] metaTable[unitID].positionInTable = index --//after moving unitID to current index: also update its meta table accordingly. unitIDTable[endOfTable] = nil end return unitIDTable, metaTable end function widget:UnitDestroyed(unitID, unitDefID, unitTeam) if areaShieldUnit[unitID] then -- remove Area Shield unit from record for i=1, #areaShieldUnit[unitID].guardedBy, 1 do local followerID = areaShieldUnit[unitID].guardedBy[i] follower_to_areaShieldUnit_meta[followerID] = nil end areaShieldUnit[unitID] = nil areaShieldCount = areaShieldCount -1 end if follower_to_areaShieldUnit_meta[unitID] then -- clear the mapping between AreaShield unit and follower's unitID. local areaShieldUnitID = follower_to_areaShieldUnit_meta[unitID].areaShieldUnitID local positionInTable = follower_to_areaShieldUnit_meta[unitID].positionInTable local guardedBy = areaShieldUnit[areaShieldUnitID].guardedBy guardedBy, follower_to_areaShieldUnit_meta = RemoveTableEntry(guardedBy, positionInTable, follower_to_areaShieldUnit_meta) --//remove table entry & metaTable entry and fill the space areaShieldUnit[areaShieldUnitID].guardedBy = guardedBy --//update the "guardedBy" table with the latest changes end end ----------------------- --Add/Remove shield or follower_to_areaShieldUnit_meta if given/taken function widget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) if (newTeam == team) then widget:UnitCreated(unitID, unitDefID, newTeam) end if (oldTeam == team) then widget:UnitDestroyed(unitID, unitDefID, newTeam) end end ----------------------- --Add shield names to array function widget:Initialize() local units = spGetTeamUnits(team) for i, id in ipairs(units) do widget:UnitCreated(id, spGetUnitDefID(id),team) end end --]] --Previous implementation (for future reference). It work by sending several individual command every half a second, but this might be considered a spam by Spring and is causing user command to be delayed (probably able to use "spGiveOrderToUnitArray" to fix but not tested yet). function widget:GetInfo() return { name = "Shield Guard", desc = "Replaces guarding mobile shields with follow. Shields move at speed of slowest unit following and wait for stragglers.", author = "Google Frog", date = "9 Mar, 2009", license = "GNU GPL, v2 or later", layer = 5, enabled = true -- loaded by default? } end -- Speedups local CMD_MOVE = CMD.MOVE local CMD_WAIT = CMD.WAIT local CMD_STOP = CMD.STOP local CMD_GUARD = CMD.GUARD local CMD_SET_WANTED_MAX_SPEED = CMD.SET_WANTED_MAX_SPEED local CMD_OPT_SHIFT = CMD.OPT_SHIFT local CMD_OPT_RIGHT = CMD.OPT_RIGHT local CMD_INSERT = CMD.INSERT local CMD_REMOVE = CMD.REMOVE local spGiveOrderToUnit = Spring.GiveOrderToUnit local spGetUnitPosition = Spring.GetUnitPosition local spGetSelectedUnits = Spring.GetSelectedUnits local spValidUnitID = Spring.ValidUnitID local spGetUnitDefID = Spring.GetUnitDefID local spGetCommandQueue = Spring.GetCommandQueue local spGetTeamUnits = Spring.GetTeamUnits local spGetUnitSeparation = Spring.GetUnitSeparation VFS.Include("LuaRules/Utilities/ClampPosition.lua") local GiveClampedOrderToUnit = Spring.Utilities.GiveClampedOrderToUnit local team = Spring.GetMyTeamID() local shields = {} local follower = {} ---------------------------- -- CONFIG local shieldRangeSafety = 20 -- how close to the edge shields should wait at local shieldReactivateRange = 100 -- how far from the edge shields should reactivate at local shieldieeStopDis = 120 -- how far from the shield the shieldiees should stop local shieldRadius = {core_spectre = 300, corthud = 80, cornecro = 80} local shieldWait = {core_spectre = true, corthud = false, cornecro = false} local shieldArray = { "corthud", "cornecro", } ---------------------------- -- Removes all CMD_SET_WANTED_MAX_SPEED from unitIDs queue --local function removeSetMaxSpeed(unit) ---------------------------- -- Update shield info and wait if units are lagging behind local function updateShields() for unit, i in pairs(shields) do i.ux,i.uy,i.uz = spGetUnitPosition(unit) if i.waits then spGiveOrderToUnit(unit, CMD_REMOVE, {1}, {"alt"} ) spGiveOrderToUnit(unit, CMD_INSERT, {1, CMD_SET_WANTED_MAX_SPEED, CMD.OPT_RIGHT, i.maxVel }, {"alt"} ) local cQueue = spGetCommandQueue(unit, 1) if (#cQueue ~= 0) and (i.folCount ~= 0) then local wait = (cQueue[1].id == CMD_WAIT) if wait then wait = false for cid, j in pairs(i.shieldiees) do local dis = spGetUnitSeparation(unit,cid) if dis > i.reactiveRange then wait = true end end if (not wait) then spGiveOrderToUnit(unit,CMD_WAIT,{},CMD_OPT_RIGHT) end else wait = false for cid, j in pairs(i.shieldiees) do local dis = spGetUnitSeparation(unit,cid) if dis > i.range then wait = true end end if wait then spGiveOrderToUnit(unit,CMD_WAIT,{},CMD_OPT_RIGHT) end end end end end end ---------------------------- -- Update shield info and wait if units are lagging behind local function updateFollowers() for unit, v in pairs(follower) do if (v.fol) then -- give move orders to shieldiees local dis = spGetUnitSeparation(unit,v.fol) if dis > v.range then GiveClampedOrderToUnit(unit,CMD_MOVE,{shields[v.fol].ux,shields[v.fol].uy,shields[v.fol].uz},CMD_OPT_RIGHT) elseif (shieldieeStopDis < dis) then GiveClampedOrderToUnit(unit,CMD_MOVE,{shields[v.fol].ux,shields[v.fol].uy,shields[v.fol].uz},CMD_OPT_RIGHT) else spGiveOrderToUnit(unit,CMD_STOP,{},CMD_OPT_RIGHT) end end end end -- update following and shield function widget:GameFrame(n) if (n%15<1) then updateShields() updateFollowers() end end ---------------------------- -- Add/remove shielded -- Override and add units guarding shields function widget:CommandNotify(id, params, options) local units = spGetSelectedUnits() for _,sid in ipairs(units) do if follower[sid] then local c = shields[follower[sid].fol] c.shieldiees[sid] = nil if c.maxVelID == sid then c.maxVel = c.selfVel c.maxVelID = -1 spGiveOrderToUnit(follower[sid].fol, CMD_INSERT, {1, CMD_SET_WANTED_MAX_SPEED, CMD.OPT_RIGHT, c.selfVel }, {"alt"} ) for cid, j in pairs(c.shieldiees) do if j.vel < c.maxVel then c.maxVel = j.vel c.maxVelID = cid end end end c.folCount = c.folCount-1 follower[sid] = nil end end if (id == CMD_GUARD) then local uid = params[1] for cid,v in pairs(shields) do if (uid == cid) then for _,sid in ipairs(units) do local ud = UnitDefs[spGetUnitDefID(sid)] if ud.canMove and not ud.isFactory and ud.buildSpeed == 0 then local speed = ud.speed/30 if speed < v.maxVel then v.maxVel = speed v.maxVelID = sid end follower[sid] = { fol = cid, vel = speed, range = v.range } v.shieldiees[sid] = follower[sid] v.folCount = v.folCount+1 else spGiveOrderToUnit(sid, id, params, options) end end return true end end end end ----------------------- --Add shield function widget:UnitCreated(unitID, unitDefID, unitTeam) if unitTeam ~= team then return end local ud = UnitDefs[unitDefID] if (ud ~= nil) then for i, name in pairs(shieldArray) do if (ud.name == name) then local ux,uy,uz = spGetUnitPosition(unitID) local speed = ud.speed/30 local shieldRange = shieldRadius[ud.name] local waits = shieldWait[ud.name] shields[unitID] = {id = unitID, ux = ux, uy = uy, uz = uz, range = shieldRange-shieldRangeSafety, reactiveRange = shieldRange-shieldReactivateRange, shieldiees = {}, folCount = 0, waits = waits, selfVel = speed, maxVel = speed, maxVelID = -1 } break end end end end ----------------------- --Remove shield or follower function widget:UnitDestroyed(unitID, unitDefID, unitTeam) local ud = UnitDefs[unitDefID] if shields[unitID] then -- remove shield for fid, j in pairs(shields[unitID].shieldiees) do follower[fid] = nil end shields[unitID] = nil end if follower[unitID] then -- remove follower local c = shields[follower[unitID].fol] c.shieldiees[unitID] = nil if c.maxVelID == unitID then c.maxVel = c.selfVel c.maxVelID = -1 spGiveOrderToUnit(follower[unitID].fol, CMD_INSERT, {1, CMD_SET_WANTED_MAX_SPEED, CMD.OPT_RIGHT, c.selfVel }, {"alt"} ) for cid, j in pairs(c.shieldiees) do if j.vel < c.maxVel then c.maxVel = j.vel c.maxVelID = cid end end end c.folCount = c.folCount-1 follower[unitID] = nil end end ----------------------- --Add/Remove shield or follower if given/taken function widget:UnitTaken(unitID, unitDefID, oldTeam, newTeam) if (newTeam == team) then widget:UnitCreated(unitID, unitDefID, newTeam) end if (oldTeam == team) then widget:UnitDestroyed(unitID, unitDefID, newTeam) end end ----------------------- --Add shield names to array function widget:Initialize() local units = spGetTeamUnits(team) for i, id in ipairs(units) do widget:UnitCreated(id, spGetUnitDefID(id),team) end end
gpl-2.0
amir32002/feedback-networks
lib/CoarseFineCriterion2.lua
1
5412
------------------------------------------------------------------------ --[[FineCoarseCriterion ]]-- -- Lin Sun 2016@Stanford ------------------------------------------------------------------------ require 'nn' require 'rnn' local FineCoarseCriterion, parent = torch.class('nn.FineCoarseCriterion2', 'nn.Criterion') function FineCoarseCriterion:__init(criterion, fm, bm) parent.__init(self) self.criterion_f = criterion self.criterion_c = criterion self.fm = fm self.bm = bm print(#fm, #bm) if torch.isTypeOf(criterion, 'nn.ModuleCriterion') then error("SequencerCriterion shouldn't decorate a ModuleCriterion. ".. "Instead, try the other way around : ".. "ModuleCriterion decorates a SequencerCriterion. ".. "Its modules can also be similarly decorated with a Sequencer.") end self.clones_f = {} self.clones_c = {} self.gradInput = {} print('[INFO] using nn.FineCoarseCriterion2') end function FineCoarseCriterion:getStepCriterion(step) assert(step, "expecting step at arg 1") local criterion_f = self.clones_f[step] local criterion_c = self.clones_c[step] if not criterion_f or not criterion_c then criterion_f = self.criterion_f:clone() self.clones_f[step] = criterion_f criterion_c = self.criterion_c:clone() self.clones_c[step] = criterion_c end return criterion_f, criterion_c end function FineCoarseCriterion:updateOutput(input, target_both) self.output = 0 local target = target_both.f local ctarget = target_both.c local nStep if torch.isTensor(input) then assert(torch.isTensor(target), "expecting target Tensor since input is a Tensor") assert(target:size(1) == input:size(1), "target should have as many elements as input") nStep = input:size(1) else assert(torch.type(target) == 'table', "expecting target table") assert(#target == #input, "target should have as many elements as input") nStep = #input end for i=1,nStep do local criterion_f, criterion_c = self:getStepCriterion(i) ii = i num = ii -- ii = i - 1 -- num = ii * 2 temp = input[i]:clone() cinput = nn.Log():forward(nn.Exp():forward(temp:float()) * self.fm:float()) -- if i < 10 then -- self.output = self.output + (num/nStep)*criterion_f:forward(input[i], target[i]) + (1.0-num/nStep)*criterion_c:forward(cinput:cuda(), ctarget[i]) -- else -- self.output = self.output + criterion_f:forward(input[i], target[i]) + 0*criterion_c:forward(cinput:cuda(), ctarget[i]) -- end self.output = self.output + criterion_c:forward(cinput:cuda(), ctarget[i]) + 0*criterion_f:forward(input[i], target[i]) -- print("forward") -- print(criterion_f.output) -- print(criterion_c.output) end return self.output end function FineCoarseCriterion:updateGradInput(input, target_both) local target = target_both.f local ctarget = target_both.c self.gradInput = {} if torch.isTensor(input) then assert(torch.isTensor(target), "expecting target Tensor since input is a Tensor") assert(target:size(1) == input:size(1), "target should have as many elements as input") nStep = input:size(1) else assert(torch.type(target) == 'table', "expecting gradOutput table") assert(#target == #input, "target should have as many elements as input") nStep = #input end local fineGradInput = {} local coarseGradInput = {} local tableGradInput = {} for i=1,nStep do ii = i num = ii -- ii = i - i -- num = ii * 2 local criterion_f, criterion_c = self:getStepCriterion(i) fineGradInput[i] = criterion_f:backward(input[i], target[i]) --print('input') --print(torch.sum(input[i])) temp = input[i]:clone() exp = nn.Exp() middle1 = exp:forward(temp:float()) middle2 = middle1 * self.fm:float() cinput = nn.Log():forward(middle2) d_loss= criterion_c:backward(cinput:cuda(),ctarget[i]):float() --print('values') --print(torch.sum(loss)) --print(torch.sum(value)) --print(torch.sum(middle)) d_cinput = nn.Log():backward(middle2, d_loss) d_middle1 = d_cinput * self.bm:float() d_temp = exp:backward(temp, d_middle1) coarseGradInput[i] = d_temp:cuda() print ('Iter', i) print('coarseGradInput_min:', torch.min(coarseGradInput[i])) print('fineGradInput_min: ', torch.min(fineGradInput[i])) print('coarseGradInput_sum:', torch.sum(fineGradInput[i])) print('fineGradInput_sum: ', torch.sum(coarseGradInput[i])) -- if i < 10 then -- tableGradInput[i] = (0.5 + ii/nStep)*fineGradInput[i] + (0.5 - ii/nStep)*coarseGradInput[i] -- tableGradInput[i] = (num/nStep)*fineGradInput[i] + (1.0-num/nStep)*coarseGradInput[i] -- else -- tableGradInput[i] = fineGradInput[i] + 0*coarseGradInput[i] -- end tableGradInput[i] = coarseGradInput[i] + 0*fineGradInput[i] end if torch.isTensor(input) then self.gradInput = tableGradInput[1].new() self.gradInput:resize(nStep, unpack(tableGradInput[1]:size():totable())) for step=1,nStep do self.gradInput[step]:copy(tableGradInput[step]) end else self.gradInput = tableGradInput end return self.gradInput end
mit
gajop/Zero-K
LuaUI/i18nlib/spec/i18n_variants_spec.lua
21
2057
require 'spec.assert_same' local variants = require 'i18n.variants' describe("i18n.variants", function() it("is a table", function() assert_equal('table', type(variants)) end) describe(".ancestry", function() it("returns just the locale for simple locales", function() assert_same(variants.ancestry('en'), {'en'}) end) it("returns self and parents for composite locales", function() assert_same(variants.ancestry('en-US-texas'), {'en-US-texas', 'en-US', 'en'}) end) end) describe(".isParent", function() it("works as expected", function() assert_true(variants.isParent('en', 'en-US')) assert_false(variants.isParent('en-US', 'en')) assert_false(variants.isParent('en', 'fr')) assert_false(variants.isParent('en', 'english')) assert_false(variants.isParent('en', 'en')) end) end) describe(".root", function() it("returns just the locale for simple locales", function() assert_equal('en', variants.root('en')) end) it("returns the root for composite locales", function() assert_equal('en', variants.root('en-US')) end) end) describe(".fallbacks", function() describe("when given locales of the same ancestry", function() it("returns the locale ancestry if given exactly the same locale twice", function() assert_same(variants.fallbacks('en-US','en-US'), {'en-US', 'en'}) end) it("returns the locale ancestry if fallbackLocale is parent of locale", function() assert_same(variants.fallbacks('en-US','en'), {'en-US', 'en'}) end) it("returns the fallbackLocale ancestry if locale is parent of fallbackLocale", function() assert_same(variants.fallbacks('en','en-US'), {'en-US', 'en'}) end) end) describe("when given two different locales", function() it("returns the first locale first, followed by the fallback locale ancestry", function() assert_same(variants.fallbacks('fr-CA', 'en-US'), {'fr-CA', 'fr', 'en-US', 'en'}) end) end) end) end)
gpl-2.0
danteinforno/wesnoth
data/ai/micro_ais/cas/ca_patrol.lua
26
6200
local AH = wesnoth.require "ai/lua/ai_helper.lua" local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua" local function get_patrol(cfg) local filter = cfg.filter or { id = cfg.id } local patrol = AH.get_units_with_moves { side = wesnoth.current.side, { "and", filter } }[1] return patrol end local ca_patrol = {} function ca_patrol:evaluation(ai, cfg) if get_patrol(cfg) then return cfg.ca_score end return 0 end function ca_patrol:execution(ai, cfg) local patrol = get_patrol(cfg) local patrol_vars = MAIUV.get_mai_unit_variables(patrol, cfg.ai_id) -- Set up waypoints, taking into account whether 'reverse' is set -- This works even the first time, when patrol_vars.patrol_reverse is not set yet cfg.waypoint_x = AH.split(cfg.waypoint_x, ",") cfg.waypoint_y = AH.split(cfg.waypoint_y, ",") local n_wp = #cfg.waypoint_x local waypoints = {} for i = 1,n_wp do if patrol_vars.patrol_reverse then waypoints[i] = { tonumber(cfg.waypoint_x[n_wp-i+1]), tonumber(cfg.waypoint_y[n_wp-i+1]) } else waypoints[i] = { tonumber(cfg.waypoint_x[i]), tonumber(cfg.waypoint_y[i]) } end end -- If not set, set next location (first move) -- This needs to be in WML format, so that it persists over save/load cycles if (not patrol_vars.patrol_x) then patrol_vars.patrol_x = waypoints[1][1] patrol_vars.patrol_y = waypoints[1][2] patrol_vars.patrol_reverse = false MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) end while patrol.moves > 0 do -- Check whether one of the enemies to be attacked is next to the patroller -- If so, don't move, but attack that enemy local adjacent_enemy = wesnoth.get_units { id = cfg.attack, { "filter_adjacent", { id = patrol.id } }, { "filter_side", {{ "enemy_of", { side = wesnoth.current.side } }} } }[1] if adjacent_enemy then break end -- Also check whether we're next to any unit (enemy or ally) which is on the next waypoint local unit_on_wp = wesnoth.get_units { x = patrol_vars.patrol_x, y = patrol_vars.patrol_y, { "filter_adjacent", { id = patrol.id } } }[1] for i,wp in ipairs(waypoints) do -- If the patrol is on a waypoint or adjacent to one that is occupied by any unit if ((patrol.x == wp[1]) and (patrol.y == wp[2])) or (unit_on_wp and ((unit_on_wp.x == wp[1]) and (unit_on_wp.y == wp[2]))) then if (i == n_wp) then -- Move him to the first one (or reverse route), if he's on the last waypoint -- Unless cfg.one_time_only is set if cfg.one_time_only then patrol_vars.patrol_x = waypoints[n_wp][1] patrol_vars.patrol_y = waypoints[n_wp][2] MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) else -- Go back to first WP or reverse direction if cfg.out_and_back then patrol_vars.patrol_x = waypoints[n_wp-1][1] patrol_vars.patrol_y = waypoints[n_wp-1][2] -- We also need to reverse the waypoints right here, as this might not be the end of the move patrol_vars.patrol_reverse = not patrol_vars.patrol_reverse MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) local tmp_wp = {} for j,wp2 in ipairs(waypoints) do tmp_wp[n_wp-j+1] = wp2 end waypoints = tmp_wp else patrol_vars.patrol_x = waypoints[1][1] patrol_vars.patrol_y = waypoints[1][2] MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) end end else -- ... else move him on toward the next waypoint patrol_vars.patrol_x = waypoints[i+1][1] patrol_vars.patrol_y = waypoints[i+1][2] MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars) end end end -- If we're on the last waypoint on one_time_only is set, stop here if cfg.one_time_only and (patrol.x == waypoints[n_wp][1]) and (patrol.y == waypoints[n_wp][2]) then AH.checked_stopunit_moves(ai, patrol) else -- Otherwise move toward next WP local x, y = wesnoth.find_vacant_tile(patrol_vars.patrol_x, patrol_vars.patrol_y, patrol) local nh = AH.next_hop(patrol, x, y) if nh and ((nh[1] ~= patrol.x) or (nh[2] ~= patrol.y)) then AH.checked_move(ai, patrol, nh[1], nh[2]) else AH.checked_stopunit_moves(ai, patrol) end end if (not patrol) or (not patrol.valid) then return end end -- Attack unit on the last waypoint under all circumstances if cfg.one_time_only is set local adjacent_enemy if cfg.one_time_only then adjacent_enemy = wesnoth.get_units{ x = waypoints[n_wp][1], y = waypoints[n_wp][2], { "filter_adjacent", { id = patrol.id } }, { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } } }[1] end -- Otherwise attack adjacent enemy (if specified) if (not adjacent_enemy) then adjacent_enemy = wesnoth.get_units{ id = cfg.attack, { "filter_adjacent", { id = patrol.id } }, { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } } }[1] end if adjacent_enemy then AH.checked_attack(ai, patrol, adjacent_enemy) end if (not patrol) or (not patrol.valid) then return end AH.checked_stopunit_all(ai, patrol) end return ca_patrol
gpl-2.0
Mistranger/OpenRA
mods/cnc/maps/gdi01/gdi01.lua
5
3949
--[[ Copyright 2007-2017 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] MCVReinforcements = { "mcv" } InfantryReinforcements = { "e1", "e1", "e1" } VehicleReinforcements = { "jeep" } NodPatrol = { "e1", "e1" } GDIBaseBuildings = { "pyle", "fact", "nuke" } SendNodPatrol = function() Reinforcements.Reinforce(enemy, NodPatrol, { nod0.Location, nod1.Location }, 15, function(soldier) soldier.AttackMove(nod2.Location) soldier.Move(nod3.Location) soldier.Hunt() end) end SetGunboatPath = function(gunboat) gunboat.AttackMove(gunboatLeft.Location) gunboat.AttackMove(gunboatRight.Location) end ReinforceWithLandingCraft = function(units, transportStart, transportUnload, rallypoint) local transport = Actor.Create("oldlst", true, { Owner = player, Facing = 0, Location = transportStart }) local subcell = 0 Utils.Do(units, function(a) transport.LoadPassenger(Actor.Create(a, false, { Owner = transport.Owner, Facing = transport.Facing, Location = transportUnload, SubCell = subcell })) subcell = subcell + 1 end) transport.ScriptedMove(transportUnload) transport.CallFunc(function() Utils.Do(units, function() local a = transport.UnloadPassenger() a.IsInWorld = true a.MoveIntoWorld(transport.Location - CVec.New(0, 1)) if rallypoint ~= nil then a.Move(rallypoint) end end) end) transport.Wait(5) transport.ScriptedMove(transportStart) transport.Destroy() end Reinforce = function(units) Media.PlaySpeechNotification(player, "Reinforce") ReinforceWithLandingCraft(units, lstStart.Location, lstEnd.Location, reinforcementsTarget.Location) end CheckForBase = function(player) local buildings = 0 Utils.Do(GDIBaseBuildings, function(name) if #player.GetActorsByType(name) > 0 then buildings = buildings + 1 end end) return buildings == #GDIBaseBuildings end WorldLoaded = function() player = Player.GetPlayer("GDI") enemy = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) secureAreaObjective = player.AddPrimaryObjective("Eliminate all Nod forces in the area.") beachheadObjective = player.AddSecondaryObjective("Establish a beachhead.") ReinforceWithLandingCraft(MCVReinforcements, lstStart.Location + CVec.New(2, 0), lstEnd.Location + CVec.New(2, 0), mcvTarget.Location) Reinforce(InfantryReinforcements) Trigger.OnIdle(Gunboat, function() SetGunboatPath(Gunboat) end) SendNodPatrol() Trigger.AfterDelay(DateTime.Seconds(10), function() Reinforce(InfantryReinforcements) end) Trigger.AfterDelay(DateTime.Seconds(60), function() Reinforce(VehicleReinforcements) end) end Tick = function() if enemy.HasNoRequiredUnits() then player.MarkCompletedObjective(secureAreaObjective) end if DateTime.GameTime > DateTime.Seconds(5) and player.HasNoRequiredUnits() then player.MarkFailedObjective(beachheadObjective) player.MarkFailedObjective(secureAreaObjective) end if DateTime.GameTime % DateTime.Seconds(1) == 0 and not player.IsObjectiveCompleted(beachheadObjective) and CheckForBase(player) then player.MarkCompletedObjective(beachheadObjective) end end
gpl-3.0
gajop/Zero-K
LuaRules/Configs/MetalSpots/Altair_Crossing-V1.lua
38
1516
return { spots = { {x = 3864, z = 2136, metal = 2.2}, {x = 888, z = 4024, metal = 1}, {x = 3944, z = 184, metal = 1}, {x = 568, z = 1928, metal = 2.2}, {x = 1528, z = 1560, metal = 2.6}, {x = 3640, z = 2056, metal = 2.2}, {x = 568, z = 3144, metal = 2.2}, {x = 1912, z = 4040, metal = 2.6}, {x = 1592, z = 4024, metal = 1}, {x = 360, z = 1800, metal = 2.2}, {x = 3240, z = 3992, metal = 1}, {x = 120, z = 3992, metal = 1}, {x = 3720, z = 904, metal = 2.2}, {x = 552, z = 872, metal = 2.2}, {x = 2360, z = 4024, metal = 1}, {x = 1784, z = 184, metal = 1}, {x = 2392, z = 152, metal = 1}, {x = 3736, z = 3096, metal = 2.2}, {x = 360, z = 3016, metal = 2.2}, {x = 1992, z = 120, metal = 2.6}, {x = 88, z = 152, metal = 1}, {x = 2392, z = 2376, metal = 2.6}, {x = 360, z = 2024, metal = 2.2}, {x = 936, z = 280, metal = 1}, {x = 3960, z = 3992, metal = 1}, {x = 376, z = 968, metal = 2.2}, {x = 3096, z = 152, metal = 1}, {x = 3544, z = 3288, metal = 2.2}, {x = 3800, z = 1848, metal = 2.2}, {x = 3528, z = 776, metal = 2.2}, } }
gpl-2.0
mardraze/prosody-modules
mod_storage_multi/mod_storage_multi.lua
32
2258
-- mod_storage_multi local storagemanager = require"core.storagemanager"; local backends = module:get_option_array(module.name); -- TODO better name? -- TODO migrate data "upwards" -- one → one successful write is success -- all → all backends must report success -- majority → majority of backends must report success local policy = module:get_option_string(module.name.."_policy", "all"); local keyval_store = {}; keyval_store.__index = keyval_store; function keyval_store:get(username) local backends = self.backends; local data, err; for i = 1, #backends do module:log("debug", "%s:%s:get(%q)", tostring(backends[i].get), backends[i]._store, username); data, err = backends[i]:get(username); if err then module:log("error", tostring(err)); elseif not data then module:log("debug", "No data returned"); else module:log("debug", "Data returned"); return data, err; end end end -- This is where it gets complicated function keyval_store:set(username, data) local backends = self.backends; local ok, err, backend; local all, one, oks = true, false, 0; for i = 1, #backends do backend = backends[i]; module:log("debug", "%s:%s:set(%q)", tostring(backends[i].get), backends[i].store, username); ok, err = backend:set(username, data); if not ok then module:log("error", "Error in storage driver %s: %s", backend.name, tostring(err)); else oks = oks + 1; end one = one or ok; -- At least one successful write all = all and ok; -- All successful end if policy == "all" then return all, err elseif policy == "majority" then return oks > (#backends/2), err; end -- elseif policy == "one" then return one, err; end local stores = { keyval = keyval_store; } local driver = {}; function driver:open(store, typ) local store_mt = stores[typ or "keyval"]; if store_mt then local my_backends = {}; local driver, opened for i = 1, #backends do driver = storagemanager.load_driver(module.host, backends[i]); opened = driver:open(store, typ); my_backends[i] = assert(driver:open(store, typ)); my_backends[i]._store = store; end return setmetatable({ backends = my_backends }, store_mt); end return nil, "unsupported-store"; end module:provides("storage", driver);
mit