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 |
|---|---|---|---|---|---|
luadch/luadch | scripts/etc_blacklist.lua | 1 | 5823 | --[[
etc_blacklist.lua by pulsar
v0.8: by pulsar
- removed "hub.reloadusers()"
- removed "hub.restartscripts()"
v0.7:
- small fix in help function / thx Sopor
v0.6:
- add table lookups
- fix permission
- cleaning code
- fix database import / thx DerWahre
- add "deleted by" info
v0.5:
- changed database path and filename
- from now on all scripts uses the same database folder
v0.4:
- export scriptsettings to "/cfg/cfg.tbl"
v0.3:
- added: seperate levelcheck for delete feature
v0.2:
- added: hub.restartscripts() & hub.reloadusers()
v0.1:
- show blacklisted users
- delete blacklisted users
]]--
--------------
--[SETTINGS]--
--------------
local scriptname = "etc_blacklist"
local scriptversion = "0.8"
local cmd = "blacklist"
local cmd_p_show = "show"
local cmd_p_del = "del"
----------------------------
--[DEFINITION/DECLARATION]--
----------------------------
--// table lookups
local cfg_get = cfg.get
local cfg_loadlanguage = cfg.loadlanguage
local hub_debug = hub.debug
local hub_import = hub.import
local utf_match = utf.match
local utf_format = utf.format
local hub_getbot = hub.getbot()
local util_loadtable = util.loadtable
local util_savetable = util.savetable
--// imports
local help, ucmd, hubcmd
local scriptlang = cfg_get( "language" )
local oplevel = cfg_get( "etc_blacklist_oplevel" )
local masterlevel = cfg_get( "etc_blacklist_masterlevel" )
local blacklist_file = "scripts/data/cmd_delreg_blacklist.tbl"
--// msgs
local lang, err = cfg_loadlanguage( scriptlang, scriptname ); lang = lang or { }; err = err and hub_debug( err )
local help_title = lang.help_title or "Blacklist"
local help_usage = lang.help_usage or "[+!#]blacklist show"
local help_desc = lang.help_desc or "show blacklisted users"
local help_title2 = lang.help_title2 or "Blacklist"
local help_usage2 = lang.help_usage2 or "[+!#]blacklist del <nick>"
local help_desc2 = lang.help_desc2 or "delete user from blacklist"
local msg_denied = lang.msg_denied or "You are not allowed to use this command."
local msg_usage = lang.msg_usage or "Usage: [+!#]blacklist show / [+!#]blacklist del <nick>"
local msg_01 = lang.msg_01 or "\t Username: "
local msg_02 = lang.msg_02 or "\t Deleted on: "
local msg_06 = lang.msg_06 or "\t Deleted by: "
local msg_03 = lang.msg_03 or "\t Reason: "
local msg_04 = lang.msg_04 or "The following user was deleted from Blacklist: "
local msg_05 = lang.msg_05 or "Error: User not found."
local ucmd_menu_show = lang.ucmd_menu_show or { "Hub", "etc", "Blacklist", "show" }
local ucmd_menu_del = lang.ucmd_menu_del or { "Hub", "etc", "Blacklist", "user delete" }
local ucmd_nick = lang.ucmd_nick or "Username:"
local msg_out = lang.msg_out or [[
=== BLACKLIST =========================================================================================
%s
========================================================================================= BLACKLIST ===
]]
----------
--[CODE]--
----------
local onbmsg = function( user, adccmd, parameters )
local blacklist_tbl = util_loadtable( blacklist_file ) or {}
local param1 = utf_match( parameters, "^(%S+)" )
local param2 = utf_match( parameters, "^%a+ (%S+)" )
local user_level = user:level()
if param1 == cmd_p_show then
if user_level >= oplevel then
local msg = ""
for k, v in pairs( blacklist_tbl ) do
local date = blacklist_tbl[ k ][ "tDate" ] or ""
local by = blacklist_tbl[ k ][ "tBy" ] or ""
local reason = blacklist_tbl[ k ][ "tReason" ] or ""
msg = msg .. "\n" ..
msg_01 .. k .. "\n" ..
msg_02 .. date .. "\n" ..
msg_06 .. by .. "\n" ..
msg_03 .. reason .. "\n"
end
local blacklist = utf_format( msg_out, msg )
user:reply( blacklist, hub_getbot )
return PROCESSED
else
user:reply( msg_denied, hub_getbot )
return PROCESSED
end
end
if param1 == cmd_p_del then
if user_level >= masterlevel then
if blacklist_tbl[ param2 ] then
blacklist_tbl[ param2 ] = nil
util_savetable( blacklist_tbl, "blacklist_tbl", blacklist_file )
user:reply( msg_04 .. param2, hub_getbot )
return PROCESSED
else
user:reply( msg_05, hub_getbot )
return PROCESSED
end
else
user:reply( msg_denied, hub_getbot )
return PROCESSED
end
end
user:reply( msg_usage, hub_getbot )
return PROCESSED
end
hub.setlistener( "onStart", {},
function()
help = hub_import( "cmd_help" )
if help then
help.reg( help_title, help_usage, help_desc, oplevel )
help.reg( help_title2, help_usage2, help_desc2, masterlevel )
end
ucmd = hub_import( "etc_usercommands" )
if ucmd then
ucmd.add( ucmd_menu_show, cmd, { cmd_p_show }, { "CT1" }, oplevel )
ucmd.add( ucmd_menu_del, cmd, { cmd_p_del, "%[line:" .. ucmd_nick .. "]" }, { "CT1" }, masterlevel )
end
hubcmd = hub_import( "etc_hubcommands" )
assert( hubcmd )
assert( hubcmd.add( cmd, onbmsg ) )
return nil
end
)
hub_debug( "** Loaded " .. scriptname .. " " .. scriptversion .." **" ) | gpl-3.0 |
mrvigeo/salib2 | plugins/stats.lua | 866 | 4001 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'teleseed' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' then
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(chat_id)
else
return
end
end
if matches[2] == "teleseed" then -- Put everything you like :)
if not is_admin(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[!/]([Ss]tats)$",
"^[!/]([Ss]tatslist)$",
"^[!/]([Ss]tats) (group) (%d+)",
"^[!/]([Ss]tats) (teleseed)",-- Put everything you like :)
"^[!/]([Tt]eleseed)"-- Put everything you like :)
},
run = run
}
end
| gpl-2.0 |
puustina/openjam | src/minigameBeachWalk.lua | 1 | 7979 | local results = require "src.results"
local countdown = require "src.countdown"
local anim8 = require "lib.anim8"
local beachWalk = {
name = "Beach Walk",
description = "Collect the clams.",
controls = "LEFT RIGHT",
thumbnail = nil,
-- game specific
over = false,
player = nil,
seaShells = {},
playerSpeedOrig = 48,
playerTurnSpeedOrig = math.pi,
seaShellCount = 7,
shellR = 16,
sand = love.graphics.newImage("assets/beachWalk/sand.png"),
footImg = love.graphics.newImage("assets/beachWalk/foot.png"),
clamImg = love.graphics.newImage("assets/beachWalk/clam.png"),
clamAnim = anim8.newAnimation(anim8.newGrid(32, 32, 4*32, 32)('1-4', 1, '3-2', 1), 0.3),
fail = love.graphics.newImage("assets/beachWalk/fail.png")
}
local bindings = {
LEFT = function(beachWalk, dt)
beachWalk.player.angle = (beachWalk.player.angle - beachWalk.playerTurnSpeed * dt)%(math.pi * 2)
end,
RIGHT = function(beachWalk, dt)
beachWalk.player.angle = (beachWalk.player.angle + beachWalk.playerTurnSpeed * dt)%(math.pi * 2)
end
}
function beachWalk:init()
self.timer = Timer.new()
end
function beachWalk:entering()
self.playerSpeed = Game.speed * self.playerSpeedOrig
self.playerTurnSpeed = self.playerTurnSpeedOrig
countdown:reset()
countdown:start()
self.over = false
local r = 16
self.player = {
x = math.random(r, Game.original.w - r),
y = math.random(r, Game.original.h - r),
angle = math.random(0, 2 * math.pi),
steps = {},
r = r,
dist = 0
}
self.player.steps[1] = { self.player.x, self.player.y, self.player.angle }
local overlap = function(newShell, player, shells)
for i, j in ipairs(shells) do
if math.sqrt(math.pow(j.x - newShell.x, 2) + math.pow(j.y - newShell.y, 2)) < 2 * beachWalk.shellR then
return true
end
end
if math.sqrt(math.pow(player.x - newShell.x, 2) + math.pow(player.y - newShell.y, 2)) < (player.r + beachWalk.shellR) then
return true
end
return false
end
self.seaShells = {}
for i = 1, self.seaShellCount do
repeat
newShell = {
x = math.random(self.shellR, Game.original.w - self.shellR),
y = math.random(self.shellR, Game.original.h - self.shellR)
}
until not overlap(newShell, self.player, self.seaShells)
self.seaShells[#self.seaShells + 1] = newShell
end
end
function beachWalk:left()
self.timer:clear()
end
function beachWalk:update(dt)
self.clamAnim:update(dt)
if Game.paused then return end
if not countdown:over() then
countdown:update(dt)
return
end
self.timer:update(dt)
if self.over then return end
for i, j in pairs(bindings) do
if love.keyboard.isDown(Controls[i]) then j(self, dt) end
end
self.player.dist = self.player.dist + self.playerSpeed * dt
local eps = 0.1
if self.player.dist >= (2 * self.player.r + eps) then
self.player.dist = self.player.dist - 2 * self.player.r
local newX = self.player.x + (2 * (self.player.r + eps)) * math.cos(self.player.angle)
local newY = self.player.y + (2 * (self.player.r + eps)) * math.sin(self.player.angle)
self.player.steps[#self.player.steps + 1] = {
newX, newY, self.player.angle
}
-- do we need to wrap?
if newX < self.player.r then
self.player.steps[#self.player.steps + 1] = {
newX + Game.original.w, newY, self.player.angle, double = true
}
elseif newX > (Game.original.w - self.player.r) then
self.player.steps[#self.player.steps + 1] = {
newX - Game.original.w, newY, self.player.angle, double = true
}
end
if newY < self.player.r then
self.player.steps[#self.player.steps + 1] = {
newX, newY + Game.original.h, self.player.angle, double = true
}
elseif newY > (Game.original.h - self.player.r) then
self.player.steps[#self.player.steps + 1] = {
newX, newY - Game.original.h, self.player.angle, double = true
}
end
love.audio.play(Game.sources.stepSand)
self.player.x = newX%Game.original.w
self.player.y = newY%Game.original.h
-- collisions
local collides = function(x1, y1, r1, x2, y2, r2)
return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) < (r1 + r2)
end
local killTable = false
local d = 0
if self.player.steps[#self.player.steps].double then d = -1 end
local lS = self.player.steps[#self.player.steps]
local llS = self.player.steps[#self.player.steps - 1]
for i, j in ipairs(self.seaShells) do
if collides(lS[1], lS[2], self.player.r,
j.x, j.y, self.shellR) or (d == -1 and
collides(llS[1], llS[2], self.player.r, j.x, j.y, self.shellR)) then
love.audio.play(Game.sources.selection)
j.kill = true
killTable = true
end
end
if killTable then
for i = #self.seaShells, 1, -1 do
if self.seaShells[i].kill then
table.remove(self.seaShells, i)
end
end
end
if #self.seaShells == 0 then
self.over = true
Game.result = "WIN"
self.timer:add(2 * (1/Game.speed), function() Venus.switch(results) end)
return -- can't lose anymore
end
local r = self.player.r
for i = 1, #self.player.steps - 1 + d do
local s = self.player.steps[i]
if collides(s[1], s[2], r, lS[1], lS[2], r) or
(d == -1 and collides(s[1], s[2], r, llS[1], llS[2], r)) then
self.over = true
Game.result = "LOSE"
local removeStep = function()
if #beachWalk.player.steps == 0 then return end
if beachWalk.player.steps[#beachWalk.player.steps].double then
table.remove(beachWalk.player.steps, #beachWalk.player.steps)
end
table.remove(beachWalk.player.steps, #beachWalk.player.steps)
end
self.timer:addPeriodic((2 * (1/Game.speed))/#self.player.steps, removeStep)
self.timer:add(2 * (1/Game.speed), function() Venus.switch(results) end)
return
end
end
end
end
function beachWalk:draw()
preDraw()
love.graphics.setColor(255, 255, 255)
love.graphics.draw(self.sand)
local step = -1
for i, j in ipairs(self.player.steps) do
if j.double then step = -step end
love.graphics.setColor(255, 255, 255, 100)
love.graphics.draw(self.footImg, j[1], j[2], j[3] + math.pi/2, step == 1 and 1 or -1, 1, self.player.r, self.player.r)
if i == #self.player.steps and not self.over then
local newX = j[1] + 2 * self.player.r * math.cos(self.player.angle)
local newY = j[2] + 2 * self.player.r * math.sin(self.player.angle)
love.graphics.setColor(255, 255, 255, 35)
love.graphics.draw(self.footImg, newX, newY, self.player.angle + math.pi/2, step == 1 and -1 or 1, 1, self.player.r, self.player.r)
if j.double then
local other = self.player.steps[#self.player.steps - 1]
local newX = other[1] + 2 * self.player.r * math.cos(self.player.angle)
local newY = other[2] + 2 * self.player.r * math.sin(self.player.angle)
love.graphics.draw(self.footImg, newX, newY, self.player.angle + math.pi/2, step == 1 and -1 or 1, 1, self.player.r, self.player.r)
end
end
step = -step
end
for i, j in ipairs(self.seaShells) do
love.graphics.setColor(255, 255, 255)
self.clamAnim:draw(self.clamImg, j.x, j.y, 0, 1, 1, self.shellR, self.shellR)
end
if Game.result == "WIN" then
love.graphics.setColor(255, 255, 255, 100)
local x = self.player.x + self.player.r * math.cos(self.player.angle)
local y = self.player.y + self.player.r * math.sin(self.player.angle)
love.graphics.draw(self.fail, x, y, self.player.angle + math.pi/2, 1, 1, self.fail:getWidth()/2, self.fail:getHeight())
-- lazy hack
love.graphics.draw(self.fail, x + Game.original.w, y, self.player.angle + math.pi/2, 1, 1, self.fail:getWidth()/2, self.fail:getHeight())
love.graphics.draw(self.fail, x - Game.original.w, y, self.player.angle + math.pi/2, 1, 1, self.fail:getWidth()/2, self.fail:getHeight())
love.graphics.draw(self.fail, x, y + Game.original.h, self.player.angle + math.pi/2, 1, 1, self.fail:getWidth()/2, self.fail:getHeight())
love.graphics.draw(self.fail, x, y - Game.original.h, self.player.angle + math.pi/2, 1, 1, self.fail:getWidth()/2, self.fail:getHeight())
end
if not countdown:over() then countdown:draw() end
postDraw()
end
return beachWalk
| gpl-3.0 |
RuiChen1113/luci | libs/luci-lib-nixio/docsrc/nixio.lua | 151 | 15824 | --- General POSIX IO library.
module "nixio"
--- Look up a hostname and service via DNS.
-- @class function
-- @name nixio.getaddrinfo
-- @param host hostname to lookup (optional)
-- @param family address family [<strong>"any"</strong>, "inet", "inet6"]
-- @param service service name or port (optional)
-- @return Table containing one or more tables containing: <ul>
-- <li>family = ["inet", "inet6"]</li>
-- <li>socktype = ["stream", "dgram", "raw"]</li>
-- <li>address = Resolved IP-Address</li>
-- <li>port = Resolved Port (if service was given)</li>
-- </ul>
--- Reverse look up an IP-Address via DNS.
-- @class function
-- @name nixio.getnameinfo
-- @param ipaddr IPv4 or IPv6-Address
-- @return FQDN
--- (Linux, BSD) Get a list of available network interfaces and their addresses.
-- @class function
-- @name nixio.getifaddrs
-- @return Table containing one or more tables containing: <ul>
-- <li>name = Interface Name</li>
-- <li>family = ["inet", "inet6", "packet"]</li>
-- <li>addr = Interface Address (IPv4, IPv6, MAC, ...)</li>
-- <li>broadaddr = Broadcast Address</li>
-- <li>dstaddr = Destination Address (Point-to-Point)</li>
-- <li>netmask = Netmask (if available)</li>
-- <li>prefix = Prefix (if available)</li>
-- <li>flags = Table of interface flags (up, multicast, loopback, ...)</li>
-- <li>data = Statistics (Linux, "packet"-family)</li>
-- <li>hatype = Hardware Type Identifier (Linix, "packet"-family)</li>
-- <li>ifindex = Interface Index (Linux, "packet"-family)</li>
-- </ul>
--- Get protocol entry by name.
-- @usage This function returns nil if the given protocol is unknown.
-- @class function
-- @name nixio.getprotobyname
-- @param name protocol name to lookup
-- @return Table containing the following fields: <ul>
-- <li>name = Protocol Name</li>
-- <li>proto = Protocol Number</li>
-- <li>aliases = Table of alias names</li>
-- </ul>
--- Get protocol entry by number.
-- @usage This function returns nil if the given protocol is unknown.
-- @class function
-- @name nixio.getprotobynumber
-- @param proto protocol number to lookup
-- @return Table containing the following fields: <ul>
-- <li>name = Protocol Name</li>
-- <li>proto = Protocol Number</li>
-- <li>aliases = Table of alias names</li>
-- </ul>
--- Get all or a specifc proto entry.
-- @class function
-- @name nixio.getproto
-- @param proto protocol number or name to lookup (optional)
-- @return Table (or if no parameter is given, a table of tables)
-- containing the following fields: <ul>
-- <li>name = Protocol Name</li>
-- <li>proto = Protocol Number</li>
-- <li>aliases = Table of alias names</li>
-- </ul>
--- Create a new socket and bind it to a network address.
-- This function is a shortcut for calling nixio.socket and then bind()
-- on the socket object.
-- @usage This functions calls getaddrinfo(), socket(),
-- setsockopt() and bind() but NOT listen().
-- @usage The <em>reuseaddr</em>-option is automatically set before binding.
-- @class function
-- @name nixio.bind
-- @param host Hostname or IP-Address (optional, default: all addresses)
-- @param port Port or service description
-- @param family Address family [<strong>"any"</strong>, "inet", "inet6"]
-- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"]
-- @return Socket Object
--- Create a new socket and connect to a network address.
-- This function is a shortcut for calling nixio.socket and then connect()
-- on the socket object.
-- @usage This functions calls getaddrinfo(), socket() and connect().
-- @class function
-- @name nixio.connect
-- @param host Hostname or IP-Address (optional, default: localhost)
-- @param port Port or service description
-- @param family Address family [<strong>"any"</strong>, "inet", "inet6"]
-- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"]
-- @return Socket Object
--- Open a file.
-- @class function
-- @name nixio.open
-- @usage Although this function also supports the traditional fopen()
-- file flags it does not create a file stream but uses the open() syscall.
-- @param path Filesystem path to open
-- @param flags Flag string or number (see open_flags).
-- [<strong>"r"</strong>, "r+", "w", "w+", "a", "a+"]
-- @param mode File mode for newly created files (see chmod, umask).
-- @see nixio.umask
-- @see nixio.open_flags
-- @return File Object
--- Generate flags for a call to open().
-- @class function
-- @name nixio.open_flags
-- @usage This function cannot fail and will never return nil.
-- @usage The "nonblock" and "ndelay" flags are aliases.
-- @usage The "nonblock", "ndelay" and "sync" flags are no-ops on Windows.
-- @param flag1 First Flag ["append", "creat", "excl", "nonblock", "ndelay",
-- "sync", "trunc", "rdonly", "wronly", "rdwr"]
-- @param ... More Flags [-"-]
-- @return flag to be used as second paramter to open
--- Duplicate a file descriptor.
-- @class function
-- @name nixio.dup
-- @usage This funcation calls dup2() if <em>newfd</em> is set, otherwise dup().
-- @param oldfd Old descriptor [File Object, Socket Object (POSIX only)]
-- @param newfd New descriptor to serve as copy (optional)
-- @return File Object of new descriptor
--- Create a pipe.
-- @class function
-- @name nixio.pipe
-- @return File Object of the read end
-- @return File Object of the write end
--- Get the last system error code.
-- @class function
-- @name nixio.errno
-- @return Error code
--- Get the error message for the corresponding error code.
-- @class function
-- @name nixio.strerror
-- @param errno System error code
-- @return Error message
--- Sleep for a specified amount of time.
-- @class function
-- @usage Not all systems support nanosecond precision but you can expect
-- to have at least maillisecond precision.
-- @usage This function is not signal-protected and may fail with EINTR.
-- @param seconds Seconds to wait (optional)
-- @param nanoseconds Nanoseconds to wait (optional)
-- @name nixio.nanosleep
-- @return true
--- Generate events-bitfield or parse revents-bitfield for poll.
-- @class function
-- @name nixio.poll_flags
-- @param mode1 revents-Flag bitfield returned from poll to parse OR
-- ["in", "out", "err", "pri" (POSIX), "hup" (POSIX), "nval" (POSIX)]
-- @param ... More mode strings for generating the flag [-"-]
-- @see nixio.poll
-- @return table with boolean fields reflecting the mode parameter
-- <strong>OR</strong> bitfield to use for the events-Flag field
--- Wait for some event on a file descriptor.
-- poll() sets the revents-field of the tables provided by fds to a bitfield
-- indicating the events that occured.
-- @class function
-- @usage This function works in-place on the provided table and only
-- writes the revents field, you can use other fields on your demand.
-- @usage All metamethods on the tables provided as fds are ignored.
-- @usage The revents-fields are not reset when the call times out.
-- You have to check the first return value to be 0 to handle this case.
-- @usage If you want to wait on a TLS-Socket you have to use the underlying
-- socket instead.
-- @usage On Windows poll is emulated through select(), can only be used
-- on socket descriptors and cannot take more than 64 descriptors per call.
-- @usage This function is not signal-protected and may fail with EINTR.
-- @param fds Table containing one or more tables containing <ul>
-- <li> fd = I/O Descriptor [Socket Object, File Object (POSIX)]</li>
-- <li> events = events to wait for (bitfield generated with poll_flags)</li>
-- </ul>
-- @param timeout Timeout in milliseconds
-- @name nixio.poll
-- @see nixio.poll_flags
-- @return number of ready IO descriptors
-- @return the fds-table with revents-fields set
--- (POSIX) Clone the current process.
-- @class function
-- @name nixio.fork
-- @return the child process id for the parent process, 0 for the child process
--- (POSIX) Send a signal to one or more processes.
-- @class function
-- @name nixio.kill
-- @param target Target process of process group.
-- @param signal Signal to send
-- @return true
--- (POSIX) Get the parent process id of the current process.
-- @class function
-- @name nixio.getppid
-- @return parent process id
--- (POSIX) Get the user id of the current process.
-- @class function
-- @name nixio.getuid
-- @return process user id
--- (POSIX) Get the group id of the current process.
-- @class function
-- @name nixio.getgid
-- @return process group id
--- (POSIX) Set the group id of the current process.
-- @class function
-- @name nixio.setgid
-- @param gid New Group ID
-- @return true
--- (POSIX) Set the user id of the current process.
-- @class function
-- @name nixio.setuid
-- @param gid New User ID
-- @return true
--- (POSIX) Change priority of current process.
-- @class function
-- @name nixio.nice
-- @param nice Nice Value
-- @return true
--- (POSIX) Create a new session and set the process group ID.
-- @class function
-- @name nixio.setsid
-- @return session id
--- (POSIX) Wait for a process to change state.
-- @class function
-- @name nixio.waitpid
-- @usage If the "nohang" is given this function becomes non-blocking.
-- @param pid Process ID (optional, default: any childprocess)
-- @param flag1 Flag (optional) ["nohang", "untraced", "continued"]
-- @param ... More Flags [-"-]
-- @return process id of child or 0 if no child has changed state
-- @return ["exited", "signaled", "stopped"]
-- @return [exit code, terminate signal, stop signal]
--- (POSIX) Get process times.
-- @class function
-- @name nixio.times
-- @return Table containing: <ul>
-- <li>utime = user time</li>
-- <li>utime = system time</li>
-- <li>cutime = children user time</li>
-- <li>cstime = children system time</li>
-- </ul>
--- (POSIX) Get information about current system and kernel.
-- @class function
-- @name nixio.uname
-- @return Table containing: <ul>
-- <li>sysname = operating system</li>
-- <li>nodename = network name (usually hostname)</li>
-- <li>release = OS release</li>
-- <li>version = OS version</li>
-- <li>machine = hardware identifier</li>
-- </ul>
--- Change the working directory.
-- @class function
-- @name nixio.chdir
-- @param path New working directory
-- @return true
--- Ignore or use set the default handler for a signal.
-- @class function
-- @name nixio.signal
-- @param signal Signal
-- @param handler ["ign", "dfl"]
-- @return true
--- Get the ID of the current process.
-- @class function
-- @name nixio.getpid
-- @return process id
--- Get the current working directory.
-- @class function
-- @name nixio.getcwd
-- @return workign directory
--- Get the current environment table or a specific environment variable.
-- @class function
-- @name nixio.getenv
-- @param variable Variable (optional)
-- @return environment table or single environment variable
--- Set or unset a environment variable.
-- @class function
-- @name nixio.setenv
-- @usage The environment variable will be unset if value is ommited.
-- @param variable Variable
-- @param value Value (optional)
-- @return true
--- Execute a file to replace the current process.
-- @class function
-- @name nixio.exec
-- @usage The name of the executable is automatically passed as argv[0]
-- @usage This function does not return on success.
-- @param executable Executable
-- @param ... Parameters
--- Invoke the shell and execute a file to replace the current process.
-- @class function
-- @name nixio.execp
-- @usage The name of the executable is automatically passed as argv[0]
-- @usage This function does not return on success.
-- @param executable Executable
-- @param ... Parameters
--- Execute a file with a custom environment to replace the current process.
-- @class function
-- @name nixio.exece
-- @usage The name of the executable is automatically passed as argv[0]
-- @usage This function does not return on success.
-- @param executable Executable
-- @param arguments Argument Table
-- @param environment Environment Table (optional)
--- Sets the file mode creation mask.
-- @class function
-- @name nixio.umask
-- @param mask New creation mask (see chmod for format specifications)
-- @return the old umask as decimal mode number
-- @return the old umask as mode string
--- (Linux) Get overall system statistics.
-- @class function
-- @name nixio.sysinfo
-- @return Table containing: <ul>
-- <li>uptime = system uptime in seconds</li>
-- <li>loads = {loadavg1, loadavg5, loadavg15}</li>
-- <li>totalram = total RAM</li>
-- <li>freeram = free RAM</li>
-- <li>sharedram = shared RAM</li>
-- <li>bufferram = buffered RAM</li>
-- <li>totalswap = total SWAP</li>
-- <li>freeswap = free SWAP</li>
-- <li>procs = number of running processes</li>
-- </ul>
--- Create a new socket.
-- @class function
-- @name nixio.socket
-- @param domain Domain ["inet", "inet6", "unix"]
-- @param type Type ["stream", "dgram", "raw"]
-- @return Socket Object
--- (POSIX) Send data from a file to a socket in kernel-space.
-- @class function
-- @name nixio.sendfile
-- @param socket Socket Object
-- @param file File Object
-- @param length Amount of data to send (in Bytes).
-- @return bytes sent
--- (Linux) Send data from / to a pipe in kernel-space.
-- @class function
-- @name nixio.splice
-- @param fdin Input I/O descriptor
-- @param fdout Output I/O descriptor
-- @param length Amount of data to send (in Bytes).
-- @param flags (optional, bitfield generated by splice_flags)
-- @see nixio.splice_flags
-- @return bytes sent
--- (Linux) Generate a flag bitfield for a call to splice.
-- @class function
-- @name nixio.splice_flags
-- @param flag1 First Flag ["move", "nonblock", "more"]
-- @param ... More flags [-"-]
-- @see nixio.splice
-- @return Flag bitfield
--- (POSIX) Open a connection to the system logger.
-- @class function
-- @name nixio.openlog
-- @param ident Identifier
-- @param flag1 Flag 1 ["cons", "nowait", "pid", "perror", "ndelay", "odelay"]
-- @param ... More flags [-"-]
--- (POSIX) Close the connection to the system logger.
-- @class function
-- @name nixio.closelog
--- (POSIX) Write a message to the system logger.
-- @class function
-- @name nixio.syslog
-- @param priority Priority ["emerg", "alert", "crit", "err", "warning",
-- "notice", "info", "debug"]
-- @param message
--- (POSIX) Set the logmask of the system logger for current process.
-- @class function
-- @name nixio.setlogmask
-- @param priority Priority ["emerg", "alert", "crit", "err", "warning",
-- "notice", "info", "debug"]
--- (POSIX) Encrypt a user password.
-- @class function
-- @name nixio.crypt
-- @param key Key
-- @param salt Salt
-- @return password hash
--- (POSIX) Get all or a specific user group.
-- @class function
-- @name nixio.getgr
-- @param group Group ID or groupname (optional)
-- @return Table containing: <ul>
-- <li>name = Group Name</li>
-- <li>gid = Group ID</li>
-- <li>passwd = Password</li>
-- <li>mem = {Member #1, Member #2, ...}</li>
-- </ul>
--- (POSIX) Get all or a specific user account.
-- @class function
-- @name nixio.getpw
-- @param user User ID or username (optional)
-- @return Table containing: <ul>
-- <li>name = Name</li>
-- <li>uid = ID</li>
-- <li>gid = Group ID</li>
-- <li>passwd = Password</li>
-- <li>dir = Home directory</li>
-- <li>gecos = Information</li>
-- <li>shell = Shell</li>
-- </ul>
--- (Linux, Solaris) Get all or a specific shadow password entry.
-- @class function
-- @name nixio.getsp
-- @param user username (optional)
-- @return Table containing: <ul>
-- <li>namp = Name</li>
-- <li>expire = Expiration Date</li>
-- <li>flag = Flags</li>
-- <li>inact = Inactivity Date</li>
-- <li>lstchg = Last change</li>
-- <li>max = Maximum</li>
-- <li>min = Minimum</li>
-- <li>warn = Warning</li>
-- <li>pwdp = Password Hash</li>
-- </ul>
--- Create a new TLS context.
-- @class function
-- @name nixio.tls
-- @param mode TLS-Mode ["client", "server"]
-- @return TLSContext Object
| apache-2.0 |
Ettercap/ettercap | src/lua/share/scripts/http_requests.lua | 12 | 2720 | ---
--
-- Created by Ryan Linn and Mike Ryan
-- Copyright (C) 2012 Trustwave Holdings, Inc.
description = "Script to show HTTP requsts";
local http = require("http")
local packet = require("packet")
local bin = require("bit")
hook_point = http.hook
packetrule = function(packet_object)
-- If this isn't a tcp packet, it's not really a HTTP request
-- since we're hooked in the HTTP dissector, we can assume that this
-- should never fail, but it's a good sanity check
if packet.is_tcp(packet_object) == false then
return false
end
return true
end
-- Here's your action.
action = function(packet_object)
local p = packet_object
-- Parse the http data into an HTTP object
local hobj = http.parse_http(p)
-- If there's no http object, get out
if hobj == nil then
return
end
-- Get out session key for tracking req->reply pairs
local session_id = http.session_id(p,hobj)
-- If we can't track sessions, this won't work, get out
if session_id == nil then
return
end
-- We have a session, lets get our registry space
local reg = ettercap.reg.create_namespace(session_id)
-- If it's a request, save the request to the registry
-- We'll need this for the response
if hobj.request then
reg.request = hobj
-- we have a response object, let't put the log together
elseif hobj.response then
-- If we haven't seen the request, we don't have anything to share
if not reg.request then
return
end
-- Get the status code
local code = hobj.status_code
-- Build the request URL
-- If we have a 2XX or 4XX or 5XX code, we won't need to log redirect
-- so just log the request and code
if code >= 200 and code < 300 or code >= 400 then
ettercap.log("HTTP_REQ: %s:%d -> %s:%d %s %s %d (%s)\n",
packet.dst_ip(p),
packet.dst_port(p),
packet.src_ip(p),
packet.src_port(p),
reg.request.verb ,reg.request.url , hobj.status_code, hobj.status_msg)
-- These codes require redirect, so log the redirect as well
elseif code >= 300 and code <= 303 then
local redir = ""
-- Get the redirect location
if hobj.headers["Location"] then
redir = hobj.headers["Location"]
end
-- Log the request/response with the redirect
ettercap.log("HTTP_REQ: %s:%d -> %s:%d %s %s -> %s %d (%s)\n",
packet.dst_ip(p),
packet.dst_port(p),
packet.src_ip(p),
packet.src_port(p),
reg.request.verb ,reg.request.url, redir, hobj.status_code, hobj.status_msg)
end
end
end
| gpl-2.0 |
omid1212/hgbok | plugins/moderation.lua | 336 | 9979 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
local username = v.username
data[tostring(msg.to.id)] = {
moderators = {[tostring(member_id)] = username},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as moderator for this group.')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
else
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
if msg.from.username then
username = msg.from.username
else
username = msg.from.print_name
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={[tostring(msg.from.id)] = username},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return 'Group has been added, and @'..username..' has been promoted as moderator for this group.'
end
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
moderators ={},
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'no',
lock_photo = 'no',
lock_member = 'no'
}
}
save_data(_config.moderation.data, data)
return 'Group has been added.'
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return 'Group has been removed'
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function admin_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
elseif mod_cmd == 'adminprom' then
return admin_promote(receiver, member_username, member_id)
elseif mod_cmd == 'admindem' then
return admin_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message .. '- '..v..' [' ..k.. '] \n'
end
return message
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if next(data['admins']) == nil then --fix way
return 'No admin available.'
end
local message = 'List for Bot admins:\n'
for k,v in pairs(data['admins']) do
message = message .. '- ' .. v ..' ['..k..'] \n'
end
return message
end
function run(msg, matches)
if matches[1] == 'debug' then
return debugs(msg)
end
if not is_chat_msg(msg) then
return "Only works on group"
end
local mod_cmd = matches[1]
local receiver = get_receiver(msg)
if matches[1] == 'modadd' then
return modadd(msg)
end
if matches[1] == 'modrem' then
return modrem(msg)
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return "Only moderator can promote"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return "Only moderator can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
return modlist(msg)
end
if matches[1] == 'adminprom' then
if not is_admin(msg) then
return "Only sudo can promote user as admin"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'admindem' then
if not is_admin(msg) then
return "Only sudo can promote user as admin"
end
local member = string.gsub(matches[2], "@", "")
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'adminlist' then
if not is_admin(msg) then
return 'Admin only!'
end
return admin_list(msg)
end
if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
end
return {
description = "Moderation plugin",
usage = {
moderator = {
"!promote <username> : Promote user as moderator",
"!demote <username> : Demote user from moderator",
"!modlist : List of moderators",
},
admin = {
"!modadd : Add group to moderation list",
"!modrem : Remove group from moderation list",
},
sudo = {
"!adminprom <username> : Promote user as admin (must be done from a group)",
"!admindem <username> : Demote user from admin (must be done from a group)",
},
},
patterns = {
"^!(modadd)$",
"^!(modrem)$",
"^!(promote) (.*)$",
"^!(demote) (.*)$",
"^!(modlist)$",
"^!(adminprom) (.*)$", -- sudoers only
"^!(admindem) (.*)$", -- sudoers only
"^!(adminlist)$",
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_created)$",
},
run = run,
}
end
| gpl-2.0 |
liuxuezhan/skynet | test/testmysql.lua | 18 | 3820 | local skynet = require "skynet"
local mysql = require "skynet.db.mysql"
local function dump(obj)
local getIndent, quoteStr, wrapKey, wrapVal, dumpObj
getIndent = function(level)
return string.rep("\t", level)
end
quoteStr = function(str)
return '"' .. string.gsub(str, '"', '\\"') .. '"'
end
wrapKey = function(val)
if type(val) == "number" then
return "[" .. val .. "]"
elseif type(val) == "string" then
return "[" .. quoteStr(val) .. "]"
else
return "[" .. tostring(val) .. "]"
end
end
wrapVal = function(val, level)
if type(val) == "table" then
return dumpObj(val, level)
elseif type(val) == "number" then
return val
elseif type(val) == "string" then
return quoteStr(val)
else
return tostring(val)
end
end
dumpObj = function(obj, level)
if type(obj) ~= "table" then
return wrapVal(obj)
end
level = level + 1
local tokens = {}
tokens[#tokens + 1] = "{"
for k, v in pairs(obj) do
tokens[#tokens + 1] = getIndent(level) .. wrapKey(k) .. " = " .. wrapVal(v, level) .. ","
end
tokens[#tokens + 1] = getIndent(level - 1) .. "}"
return table.concat(tokens, "\n")
end
return dumpObj(obj, 0)
end
local function test2( db)
local i=1
while true do
local res = db:query("select * from cats order by id asc")
print ( "test2 loop times=" ,i,"\n","query result=",dump( res ) )
res = db:query("select * from cats order by id asc")
print ( "test2 loop times=" ,i,"\n","query result=",dump( res ) )
skynet.sleep(1000)
i=i+1
end
end
local function test3( db)
local i=1
while true do
local res = db:query("select * from cats order by id asc")
print ( "test3 loop times=" ,i,"\n","query result=",dump( res ) )
res = db:query("select * from cats order by id asc")
print ( "test3 loop times=" ,i,"\n","query result=",dump( res ) )
skynet.sleep(1000)
i=i+1
end
end
skynet.start(function()
local function on_connect(db)
db:query("set charset utf8");
end
local db=mysql.connect({
host="127.0.0.1",
port=3306,
database="skynet",
user="root",
password="1",
max_packet_size = 1024 * 1024,
on_connect = on_connect
})
if not db then
print("failed to connect")
end
print("testmysql success to connect to mysql server")
local res = db:query("drop table if exists cats")
res = db:query("create table cats "
.."(id serial primary key, ".. "name varchar(5))")
print( dump( res ) )
res = db:query("insert into cats (name) "
.. "values (\'Bob\'),(\'\'),(null)")
print ( dump( res ) )
res = db:query("select * from cats order by id asc")
print ( dump( res ) )
-- test in another coroutine
skynet.fork( test2, db)
skynet.fork( test3, db)
-- multiresultset test
res = db:query("select * from cats order by id asc ; select * from cats")
print ("multiresultset test result=", dump( res ) )
print ("escape string test result=", mysql.quote_sql_str([[\mysql escape %string test'test"]]) )
-- bad sql statement
local res = db:query("select * from notexisttable" )
print( "bad query test result=" ,dump(res) )
local i=1
while true do
local res = db:query("select * from cats order by id asc")
print ( "test1 loop times=" ,i,"\n","query result=",dump( res ) )
res = db:query("select * from cats order by id asc")
print ( "test1 loop times=" ,i,"\n","query result=",dump( res ) )
skynet.sleep(1000)
i=i+1
end
--db:disconnect()
--skynet.exit()
end)
| mit |
vipteam1/VIPTEAM | plugins/infoeng.lua | 1 | 10422 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( #all ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
do
local Arian = 119626024 --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..') به\n '..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 = 'whois:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'› whois: (Sudo) \n\n'
elseif is_admin2(result.id) then
text = text..'› whois: (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'› whois: (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'›whois: (Moderator) \n\n'
else
text = text..'›whois: (Member) \n\n'
end
else
text = text..'› whois : '..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..'› msg : '..user_info_msgs..'\n\n'
text = text..'ِ'
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 = 'whois:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Arian) then
text = text..'› whois: (Sudo) \n\n'
elseif is_admin2(result.id) then
text = text..'› whois: (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'› whois: (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'› whois: (Moderator) \n\n'
else
text = text..'› whois: (Member) \n\n'
end
else
text = text..'› whois : '..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..'› msg : '..user_info_msgs..'\n\n'
text = text..'ِ'
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 = '♍️- name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'♑️- username : '..Username..'\n'
..'♑️- your ID : '..result.from.id..'\n\n'
local hash = 'whois:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == tonumber(Arian) then
text = text..'💟- whois: (Sudo) \n\n'
elseif is_admin2(result.from.id) then
text = text..'💟- whois: (Admin) \n\n'
elseif is_owner2(result.from.id, result.to.id) then
text = text..'💟- whois: (Owner) \n\n'
elseif is_momod2(result.from.id, result.to.id) then
text = text..'💟- whois: (Moderator) \n\n'
else
text = text..'💟- whois: (Member) \n\n'
end
else
text = text..'› whois : '..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..'ℹ️- msgs : '..user_info_msgs..'\n'
text = text..'ِ'
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 Owners !"
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'
local text = text..'📊- رقم هاتفك : '..(msg.from.phone or 'لا يوجد ')..'\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(Arian) then
text = text..'✔️- مُوٌڦعُڲ : —انت مطور— \n'
elseif is_sudo(msg) then
text = text..'💡- مُوٌڦعُڲ : —انت مطور— \n'
elseif is_owner(msg) then
text = text..'💯- مُوٌڦعُڲ : —انت مشرف— \n'
elseif is_momod(msg) then
text = text..'🚀- مُوٌڦعُڲ : —انت ادمن— \n'
else
text = text..'🐸- مُوٌڦعُڲ : —انت عضو--\n'
end
else
text = text..'💡 whois : '..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
return reply_msg(msg.id, text, ok_cb, false)
end
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == '' 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]) (.*)$",
"^[/!](info)$",
"^[/!](info) (.*)$",
"^[Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
},
run = run
}
end
-- post by : @vip_team1
--[[ ldocal geroup_ovwner = dpata[toostring(misg.tno.itd)]['set_owner']
if group_owner then
local dev point= get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_vip_team1(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = vip_team1(matches[2])
save_data(_config.moderation.data, data)
dev[point(msg.to.id, name_log.." ["..dev.point.id.."] set ["..matches[2].."] as owner")
local text = "[ "..matches[2].." ] added as owner"
return text
end]]
| gpl-2.0 |
kamichidu/lua-jclass | lib/util/lookahead_queue.lua | 1 | 2514 | local prototype= require 'prototype'
local lookahead_queue= prototype {
default= prototype.assignment_copy,
table= prototype.deep_copy,
use_extra_meta= true,
}
lookahead_queue.elements= {}
function lookahead_queue.from_iterator(iterator)
assert(iterator, 'cannot create from nil value')
local obj= lookahead_queue:clone()
for e in iterator do
table.insert(obj.elements, e)
end
return obj
end
function lookahead_queue.from_string(s)
assert(s, 'cannot create from nil value')
return lookahead_queue.from_iterator(s:gmatch('.'))
end
function lookahead_queue:poll()
assert(#(self.elements) > 0, 'elements is empty')
return table.remove(self.elements, 1)
end
function lookahead_queue:peek()
assert(#(self.elements) > 0, 'elements is empty')
return self.elements[1]
end
function lookahead_queue:lookahead(k)
assert(k > 0 and k < #(self.elements), 'overflow')
return self.elements[1 + k]
end
function lookahead_queue:push_back(...)
assert(#{...} > 0, 'no elements passed')
for i, element in ipairs({...}) do
table.insert(self.elements, element)
end
end
function lookahead_queue:size()
return #(self.elements)
end
local meta= getmetatable(lookahead_queue) or {}
function meta.__len(op)
return 30
end
setmetatable(lookahead_queue, meta)
return lookahead_queue
--[[
=pod
=head1 NAME
lookahead_queue - queue which can lookahead access for its element.
=head1 SYNOPSIS
local lookahead_queue= require 'lookahead_queue'
local q= lookahead_queue.from_iterator(('abcd'):gmatch('.'))
assert(q:poll() == 'a')
assert(q:peek() == 'b')
assert(q:poll() == 'b')
assert(q:lookahead(1) == 'd')
=head1 DESCRIPTION
=head2 PROVIDED FUNCTIONS
=over 4
=item B<lookahead_queue.from_iterator(iterator)>
create new lookahead_queue object from iterator.
=item B<lookahead_queue.from_string(s)>
create new lookahead_queue object from string.
this is equivalent to C<lookahead_queue.from_iterator(s:gmatch('.'))>
=back
=head2 PROVIDED METHODS
=over 4
=item B<lookahead_queue:poll()>
retrieve and remove first element of this queue.
=item B<lookahead_queue:peek()>
retrieve first element of this queue.
this function doesn't remove retrieved element.
=item B<lookahead_queue:lookahead(k)>
retrieve `k'th element of this queue.
this function doesn't remove retrieved element.
=back
=head1 AUTHOR
kamichidu - L<c.kamunagi@gmail.com>
=head1 LICENSE
see `LICENSE' file.
=cut
--]]
| mit |
Habbie/hammerspoon | extensions/mouse/test_mouse.lua | 6 | 1301 | hs.mouse = require("hs.mouse")
function testMouseCount()
assertGreaterThan(0, hs.mouse.count())
assertGreaterThan(0, hs.mouse.count(true))
return success()
end
function testMouseNames()
local names = hs.mouse.names()
assertIsTable(names)
assertIsString(names[1])
return success()
end
function testMouseAbsolutePosition()
local pos = hs.mouse.getAbsolutePosition()
assertIsTable(pos)
assertIsNumber(pos.x)
assertIsNumber(pos.y)
local newPos = hs.geometry.point(pos.x + 1, pos.y + 1)
hs.mouse.setAbsolutePosition(newPos)
local afterPos = hs.mouse.getAbsolutePosition()
assertIsAlmostEqual(newPos.x, afterPos.x, 1)
assertIsAlmostEqual(newPos.y, afterPos.y, 1)
return success()
end
function testScrollDirection()
local scrollDir = hs.mouse.scrollDirection()
assertTrue(scrollDir == "natural" or "normal")
return success()
end
function testMouseTrackingSpeed()
local originalSpeed = hs.mouse.trackingSpeed()
assertIsNumber(originalSpeed)
hs.mouse.trackingSpeed(0.0)
assertIsEqual(0.0, hs.mouse.trackingSpeed())
hs.mouse.trackingSpeed(3.0)
assertIsEqual(3.0, hs.mouse.trackingSpeed())
hs.mouse.trackingSpeed(originalSpeed)
return success()
end
| mit |
uhvhugvhhbbh545hhhyg/rekjx | plugins/control.lua | 2 | 2481 |
local function run(msg, matches)
if matches[1]:lower() == 'join' and matches[2] and is_admin(msg) then
channel_invite('channel#id'..matches[2], 'user#id'..msg.from.id, ok_cb, false)
end
if matches[1]:lower() == '1m' and matches[2] then
if not is_sudo(msg) then return end
local time = os.time()
local buytime = tonumber(os.time())
local timeexpire = tonumber(buytime) + (tonumber(1 * 30) * 86400)
redis:hset('expiretime','channel#id'..matches[2],timeexpire)
enable_channel('channel#id'..matches[2])
send_large_msg('channel#id'..matches[2], 'Group charged For 30 Days', ok_cb, false)
return reply_msg(msg.id, 'Done', ok_cb, false)
end
if matches[1]:lower() == '3m' and matches[2] then
if not is_sudo(msg) then return end
local time = os.time()
local buytime = tonumber(os.time())
local timeexpire = tonumber(buytime) + (tonumber(3 * 30) * 86400)
redis:hset('expiretime','channel#id'..matches[2],timeexpire)
enable_channel('channel#id'..matches[2])
send_large_msg('channel#id'..matches[2], 'Group charged For 90 Days', ok_cb, false)
return reply_msg(msg.id, 'Done', ok_cb, false)
end
if matches[1]:lower() == 'unlimit' and matches[2] then
if not is_sudo(msg) then return end
local time = os.time()
local buytime = tonumber(os.time())
local timeexpire = tonumber(buytime) + (tonumber(2 * 99999999999) * 86400)
redis:hset('expiretime','channel#id'..matches[2],timeexpire)
enable_channel('channel#id'..matches[2])
send_large_msg('channel#id'..matches[2], 'Group charged For unlimited', ok_cb, false)
return reply_msg(msg.id, 'Done', ok_cb, false)
end
if matches[1]:lower() == 'leave' and matches[2] and is_sudo(msg) then
leave_channel('channel#id'..matches[2], ok_cb, false)
apileavechat(msg, '-100'..matches[2])
return 'Done\nI Exited the Group : '..matches[2]
elseif matches[1]:lower() == 'leave' and not matches[2] and is_admin(msg) then
leave_channel('channel#id'..msg.to.id, ok_cb, false)
apileavechat(msg, '-100'..msg.to.id)
end
end
return {
patterns = {
"^[/!#](1[Mm])(%d+)(.*)$",
"^[/!#](3[Mm])(%d+)(.*)$",
"^[/!#]([Jj]oin)(%d+)$",
"^[/!#]([Uu]nlimite)(%d+)$",
"^[/!#]([Ll]eave)(%d+) (.*)$",
},
run = run,
} | gpl-2.0 |
Noneatme/mta-lostresources | [gamemodes]/twd/client/CObjectCreator.lua | 1 | 1624 | -- #######################################
-- ## Project: MTA:The Walking Death ##
-- ## Name: ObjectCreator ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
--[[
]]
cFunc["create_objects"] = function()
-- Logger --
logger = Logger:New();
-- Alles Moegliche
fontManager = FontManager:New();
cameraMover = CameraMover:New();
soundManager = SoundManager:New();
messageBox = CG.MessageBox:New();
optionBox = CG.OptionBox:New();
importer = Importer:New();
world = World:New();
ego = Ego:New();
ausdauerManager = AusdauerManager:New();
expManager = ExpManager:New();
renderUserbar = RenderUserbar:New();
chatBox = ChatBox:New();
chatBox:AddGroup("System", true);
chatBox:AddGroup("Local chat", false, 255, 255, 0);
chatBox:AddGroup("Global chat", false, 255, 255, 255);
chatBox:AddGroup("Support chat", false, 0, 255, 255);
chatBox:SelectGroup("System");
chatBox:Hide();
outputChatBox("Welcome to MTA:The Walking Death!", 255, 255, 255);
outputChatBox("");
outputChatBox("Key Shortcuts:", 255, 255, 255);
outputChatBox("#FFFF00L - Local Chat #FFFFFF| G - Global Chat", 255, 255, 255);
outputChatBox("#00FFFFH - Help Chat #FFFFFF| M - System Chat", 255, 255, 255)
outputChatBox("#FFFFFFPress #00FF00't'#FFFFFF to chat.", 255, 255, 255);
-- Register Manager
registerManager = RegisterManager:New();
registerManager:Open();
end
-- EVENT HANDLER --
cFunc["create_objects"](); | gpl-2.0 |
Lautitia/newfies-dialer | lua/libs/fsm.lua | 15 | 7426 | -- ==========================================================================================
--
-- Finite State Machine Class for Lua 5.1 & Corona SDK
--
-- Written by Erik Cornelisse, inspired by Luiz Henrique de Figueiredo
-- E-mail: e.cornelisse@gmail.com
--
-- Version 1.0 April 27, 2011
--
-- Class is MIT Licensed
-- Copyright (c) 2011 Erik Cornelisse
--
-- Feel free to change but please send new versions, improvements or
-- new features to me and help us to make it better.
--
-- ==========================================================================================
--[[ A design pattern for doing finite state machines (FSMs) in Lua.
Based on a very appreciated contribution of Luiz Henrique de Figueiredo
Original code from http://lua-users.org/wiki/FiniteStateMachine
The FSM is described with: old_state, event, new_state and action.
One easy way to do this in Lua would be to create a table in exactly
the form above:
yourStateTransitionTable = {
{state1, event1, state2, action1},
{state1, event2, state3, action2},
...
}
The function FSM takes the simple syntax above and creates tables
for (state, event) pairs with fields (action, new):
function FSM(yourStateTransitionTable)
local stt = {}
for _,v in ipairs(t) do
local old, event, new, action = v[1], v[2], v[3], v[4]
if stt[old] == nil then a[old] = {} end
stt[old][event] = {new = new, action = action}
end
return stt
end
Note that this scheme works for states and events of any type: number,
string, functions, tables, anything. Such is the power of associate arrays.
However, the double array stt[old][event] caused a problem for event = nil
Instead a single array is used, constructed as stt[state .. SEPARATOR .. event]
Where SEPARATOR is a constant and defined as '.'
Three special state transitions are added to the original code:
- any state but a specific event
- any event but a specific state
- unknown state-event combination to be used for exception handling
The any state and event are defined by the ANY constant, defined as '*'
The unknown state-event is defined as the combination of ANY.ANY (*.*)
A default exception handler for unknown state-event combinations is
provided and therefore a specification a your own exception handling is
optional.
After creating a new FSM, the initial state is set to the first defined
state in your state transition table. With add(t) and delete(t), new state
transition can be added and removed later.
A DEBUG-like method called silent is included to prevent wise-guy remarks
about things you shouldn't be doing.
USAGE EXAMPLES:
-------------------------------------------------------------------------------
FSM = require "fsm"
function action1() print("Performing action 1") end
function action2() print("Performing action 2") end
-- Define your state transitions here
local myStateTransitionTable = {
{"state1", "event1", "state2", action1},
{"state2", "event2", "state3", action2},
{"*", "event3", "state2", action1}, -- for any state
{"*", "*", "state2", action2} -- exception handler
}
-- Create your finite state machine
fsm = FSM.new(myStateTransitionTable)
-- Use your finite state machine
-- which starts by default with the first defined state
print("Current FSM state: " .. fsm:get())
-- Or you can set another state
fsm:set("state2")
print("Current FSM state: " .. fsm:get())
-- Resond on "event" and last set "state"
fsm:fire("event2")
print("Current FSM state: " .. fsm:get())
Output:
-------
Current FSM state: state1
Current FSM state: state2
Performing action 2
Current FSM state: state3
REMARKS:
-------------------------------------------------------------------------------
Sub-states are not supported by additional methods to keep the code simple.
If you need sub-states, you can create them as 'state.substate' directly.
A specific remove method is not provided because I didn't need one (I think)
But feel free to implement one yourself :-)
One more thing, did I already mentioned that I am new to Lua?
Well, I learn a lot of other examples, so do not forget yours.
CONCLUSION:
-------------------------------------------------------------------------------
A small amount of code is required to use the power of a Finite State Machine.
I wrote this code to implement generic graphical objects where the presentation
and behaviour of the objects can be specified by using state-transition tables.
This resulted in less code (and less bugs), a higher modularity and above all a
reduction of the complexity.
Finite state machines can be used to force (at least parts of) your code into
deterministic behaviour.
Have fun !!
--]]
--MODULE CODE
-------------------------------------------------------------------------------
module(..., package.seeall)
-- FSM CONSTANTS --------------------------------------------------------------
SEPARATOR = '.'
ANY = '*'
ANYSTATE = ANY .. SEPARATOR
ANYEVENT = SEPARATOR .. ANY
UNKNOWN = ANYSTATE .. ANY
function new(t)
local self = {}
-- ATTRIBUTES -------------------------------------------------------------
local state = t[1][1] -- current state, default the first one
local stt = {} -- state transition table
local str = "" -- <state><SEPARATOR><event> combination
local silence = false -- use silent() for whisper mode
-- METHODS ----------------------------------------------------------------
-- some getters and setters
function self:set(s) state = s end
function self:get() return state end
function self:silent() silence = true end
-- default exception handling
local function exception()
if silence == false then
print("FSM: unknown combination: " .. str) end
return false
end
-- respond based on current state and event
function self:fire(event)
local act = stt[state .. SEPARATOR .. event]
-- raise exception for unknown state-event combination
if act == nil then
-- search for wildcard "states" for this event
act = stt[ANYSTATE .. event]
-- if still not a match than check any event
if act == nil then
-- check if there is a wildcard event
act = stt[state .. ANYEVENT]
if act == nil then
act = stt[UNKNOWN]; str = state .. SEPARATOR .. event end
end
end
-- set next state as current state
state = act.newState
return act.action()
end
-- add new state transitions to the FSM
function self:add(t)
for _,v in ipairs(t) do
local oldState, event, newState, action = v[1], v[2], v[3], v[4]
stt[oldState .. SEPARATOR .. event] = {newState = newState, action = action}
end
return #t -- the requested number of state-transitions to be added
end
-- remove state transitions from the FSM
function self:delete(t)
for _,v in ipairs(t) do
local oldState, event = v[1], v[2]
if oldState == ANY and event == ANY then
if not silence then
print( "FSM: you should not delete the exception handler" )
print( "FSM: but assign another exception action" )
end
-- assign default exception handler but stay in current state
stt[exception] = {newState = state, action = exception}
else
stt[oldState .. SEPARATOR .. event] = nil
end
end
return #t -- the requested number of state-transitions to be deleted
end
-- initalise state transition table
stt[UNKNOWN] = {newState = state, action = exception}
self:add(t)
-- return FSM methods
return self
end
| mpl-2.0 |
mms92/wire | lua/wire/stools/vthruster.lua | 9 | 8209 | WireToolSetup.setCategory( "Physics/Force" )
WireToolSetup.open( "vthruster", "Vector Thruster", "gmod_wire_vectorthruster", nil, "Vector Thrusters" )
if ( CLIENT ) then
language.Add( "Tool.wire_vthruster.name", "Vector Thruster Tool (Wire)" )
language.Add( "Tool.wire_vthruster.desc", "Spawns a vector thruster for use with the wire system." )
language.Add( "Tool.wire_vthruster.0", "Primary: Create/Update Vector Thruster" )
language.Add( "Tool.wire_vthruster.1", "Primary: Set the Angle, hold Shift to lock to 45 degrees" )
language.Add( "WireVThrusterTool_Mode", "Mode:" )
language.Add( "WireVThrusterTool_Angle", "Use Yaw/Pitch Inputs Instead" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 10 )
TOOL.ClientConVar[ "force" ] = "1500"
TOOL.ClientConVar[ "force_min" ] = "0"
TOOL.ClientConVar[ "force_max" ] = "10000"
TOOL.ClientConVar[ "model" ] = "models/jaanus/wiretool/wiretool_speed.mdl"
TOOL.ClientConVar[ "bidir" ] = "1"
TOOL.ClientConVar[ "soundname" ] = ""
TOOL.ClientConVar[ "oweffect" ] = "fire"
TOOL.ClientConVar[ "uweffect" ] = "same"
TOOL.ClientConVar[ "owater" ] = "1"
TOOL.ClientConVar[ "uwater" ] = "1"
TOOL.ClientConVar[ "mode" ] = "0"
TOOL.ClientConVar[ "angleinputs" ] = "0"
if SERVER then
function TOOL:GetConVars()
return self:GetClientNumber( "force" ), self:GetClientNumber( "force_min" ), self:GetClientNumber( "force_max" ), self:GetClientInfo( "oweffect" ),
self:GetClientInfo( "uweffect" ), self:GetClientNumber( "owater" ) ~= 0, self:GetClientNumber( "uwater" ) ~= 0, self:GetClientNumber( "bidir" ) ~= 0,
self:GetClientInfo( "soundname" ), self:GetClientNumber( "mode" ), self:GetClientNumber( "angleinputs" ) ~= 0
end
end
function TOOL:LeftClick( trace )
local numobj = self:NumObjects()
local ply = self:GetOwner()
if (numobj == 0) then
if IsValid(trace.Entity) and trace.Entity:IsPlayer() then return false end
// If there's no physics object then we can't constraint it!
if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end
if (CLIENT) then return true end
local ent = WireToolObj.LeftClick_Make(self, trace, ply )
if isbool(ent) then return ent end
if IsValid(ent) then
ent:GetPhysicsObject():EnableMotion( false )
self:ReleaseGhostEntity()
self:SetObject(1, trace.Entity, trace.HitPos, trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone), trace.PhysicsBone, trace.HitNormal)
self:SetObject(2, ent, trace.HitPos, Phys, 0, trace.HitNormal)
self:SetStage(1)
end
else
if (CLIENT) then return true end
local anchor, wire_thruster = self:GetEnt(1), self:GetEnt(2)
local anchorbone = self:GetBone(1)
local normal = self:GetNormal(1)
local const = WireLib.Weld(wire_thruster, anchor, trace.PhysicsBone, true, false)
local Phys = wire_thruster:GetPhysicsObject()
Phys:EnableMotion( true )
undo.Create("WireVThruster")
undo.AddEntity( wire_thruster )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_vthrusters", wire_thruster )
ply:AddCleanup( "wire_vthrusters", const )
self:ClearObjects()
end
return true
end
local degrees = 0
function TOOL:Think()
if (self:NumObjects() > 0) then
if ( SERVER ) then
local Phys2 = self:GetPhys(2)
local Norm2 = self:GetNormal(2)
local cmd = self:GetOwner():GetCurrentCommand()
degrees = degrees + cmd:GetMouseX() * 0.05
local ra = degrees
if (self:GetOwner():KeyDown(IN_SPEED)) then ra = math.Round(ra/45)*45 end
local Ang = Norm2:Angle()
Ang.pitch = Ang.pitch + 90
Ang:RotateAroundAxis(Norm2, ra)
Phys2:SetAngles( Ang )
Phys2:Wake()
end
else
WireToolObj.Think(self) -- Basic ghost
end
end
if (CLIENT) then
function TOOL:FreezeMovement()
return self:GetStage() == 1
end
end
function TOOL:Holster()
if self:NumObjects() > 0 and IsValid(self:GetEnt(2)) then
self:GetEnt(2):Remove()
end
self:ClearObjects()
end
function TOOL.BuildCPanel(panel)
WireToolHelpers.MakePresetControl(panel, "wire_vthruster")
WireDermaExts.ModelSelect(panel, "wire_vthruster_model", list.Get( "ThrusterModels" ), 4, true)
local Effects = {
["#No Effects"] = "none",
//["#Same as over water"] = "same",
["#Flames"] = "fire",
["#Plasma"] = "plasma",
["#Smoke"] = "smoke",
["#Smoke Random"] = "smoke_random",
["#Smoke Do it Youself"] = "smoke_diy",
["#Rings"] = "rings",
["#Rings Growing"] = "rings_grow",
["#Rings Shrinking"] = "rings_shrink",
["#Bubbles"] = "bubble",
["#Magic"] = "magic",
["#Magic Random"] = "magic_color",
["#Magic Do It Yourself"] = "magic_diy",
["#Colors"] = "color",
["#Colors Random"] = "color_random",
["#Colors Do It Yourself"] = "color_diy",
["#Blood"] = "blood",
["#Money"] = "money",
["#Sperms"] = "sperm",
["#Feathers"] = "feather",
["#Candy Cane"] = "candy_cane",
["#Goldstar"] = "goldstar",
["#Water Small"] = "water_small",
["#Water Medium"] = "water_medium",
["#Water Big"] = "water_big",
["#Water Huge"] = "water_huge",
["#Striderblood Small"] = "striderblood_small",
["#Striderblood Medium"] = "striderblood_medium",
["#Striderblood Big"] = "striderblood_big",
["#Striderblood Huge"] = "striderblood_huge",
["#More Sparks"] = "more_sparks",
["#Spark Fountain"] = "spark_fountain",
["#Jetflame"] = "jetflame",
["#Jetflame Blue"] = "jetflame_blue",
["#Jetflame Red"] = "jetflame_red",
["#Jetflame Purple"] = "jetflame_purple",
["#Comic Balls"] = "balls",
["#Comic Balls Random"] = "balls_random",
["#Comic Balls Fire Colors"] = "balls_firecolors",
["#Souls"] = "souls",
//["#Debugger 10 Seconds"] = "debug_10", These are just buggy and shouldn't be used.
//["#Debugger 30 Seconds"] = "debug_30",
//["#Debugger 60 Seconds"] = "debug_60",
["#Fire and Smoke"] = "fire_smoke",
["#Fire and Smoke Huge"] = "fire_smoke_big",
["#5 Growing Rings"] = "rings_grow_rings",
["#Color and Magic"] = "color_magic",
}
local CateGoryOW = vgui.Create("DCollapsibleCategory")
CateGoryOW:SetSize(0, 50)
CateGoryOW:SetExpanded(0)
CateGoryOW:SetLabel("Overwater Effect List")
local ctrl = vgui.Create( "MatSelect", CateGoryOW )
ctrl:SetItemWidth( 128 )
ctrl:SetItemHeight( 128 )
ctrl:SetConVar("wire_vthruster_oweffect")
for name, mat in pairs( Effects ) do
ctrl:AddMaterialEx( name, "gui/thrustereffects/"..mat, mat, {wire_vthruster_oweffect = mat} )
end
CateGoryOW:SetContents( ctrl )
panel:AddItem(CateGoryOW)
Effects["#Same as over water"] = "same"
local CateGoryUW = vgui.Create("DCollapsibleCategory")
CateGoryUW:SetSize(0, 50)
CateGoryUW:SetExpanded(0)
CateGoryUW:SetLabel("Underwater Effect List")
local ctrlUW = vgui.Create( "MatSelect", CateGoryUW )
ctrlUW:SetItemWidth( 128 )
ctrlUW:SetItemHeight( 128 )
ctrlUW:SetConVar("wire_vthruster_uweffect")
for name, mat in pairs( Effects ) do
ctrlUW:AddMaterialEx( name, "gui/thrustereffects/"..mat, mat, {wire_vthruster_uweffect = mat} )
end
CateGoryUW:SetContents( ctrlUW )
panel:AddItem(CateGoryUW)
local lst = {}
for k,v in pairs( list.Get("ThrusterSounds") ) do
lst[k] = {}
for k2,v2 in pairs( v ) do
lst[k]["wire_v"..k2] = v2
end
end
panel:AddControl( "ListBox", { Label = "#Thruster_Sounds", Options = lst } )
panel:NumSlider("#WireThrusterTool_force", "wire_vthruster_force", 1, 10000, 2 )
panel:NumSlider("#WireThrusterTool_force_min", "wire_vthruster_force_min", -10000, 10000, 2 )
panel:NumSlider("#WireThrusterTool_force_max", "wire_vthruster_force_max", -10000, 10000, 2 )
panel:CheckBox("#WireThrusterTool_bidir", "wire_vthruster_bidir")
panel:CheckBox("#WireThrusterTool_owater", "wire_vthruster_owater")
panel:CheckBox("#WireThrusterTool_uwater", "wire_vthruster_uwater")
panel:AddControl("ListBox", {
Label = "#WireVThrusterTool_Mode",
Options = {
["#XYZ Local"] = { wire_vthruster_mode = "0" },
["#XYZ World"] = { wire_vthruster_mode = "1" },
["#XY Local, Z World"] = { wire_vthruster_mode = "2" },
}
})
panel:CheckBox("#WireVThrusterTool_Angle", "wire_vthruster_angleinputs")
end
list.Set( "ThrusterModels", "models/jaanus/wiretool/wiretool_speed.mdl", {} )
| apache-2.0 |
SammyJames/Rave | Rave.lua | 1 | 4239 | ----------------------------------------------------------
-- Rave - a chat addon
--
-- @author Pawkette ( pawkette.heals@gmail.com )
----------------------------------------------------------
local kAddonName, kVersion = 'Rave', 1.0
local Rave = Rave
local Constants = Rave.Constants
local tinsert = table.insert
local tremove = table.remove
local ZO_SavedVars = ZO_SavedVars
local CBM = CALLBACK_MANAGER
local LINK_HANDLER = LINK_HANDLER
function Rave:Initialize( control )
self.Window:Initialize( control )
self.Edit:Initialize( control:GetNamedChild( 'Edit' ) )
self:RegisterEvent( EVENT_ADD_ON_LOADED, function( ... ) self:HandleAddonLoaded( ... ) end )
self:RegisterEvent( EVENT_CHAT_MESSAGE_CHANNEL, function( ... ) self:HandleChatMessage( ... ) end )
self:RegisterEvent( EVENT_CHAT_CHANNEL_JOIN, function( ... ) self:HandleChatChannelJoin( ... ) end )
self:RegisterEvent( EVENT_CHAT_CHANNEL_LEAVE, function( ... ) self:HandleChatChannelLeave( ... ) end )
end
function Rave:HandleAddonLoaded( addon )
if ( addon ~= kAddonName ) then
return
end
self.db = ZO_SavedVars:NewAccountWide( 'RAVE_DB', kVersion, nil, nil )
ZO_CreateStringId("SI_BINDING_NAME_RAVE_GUILD1", "Guild 1")
ZO_CreateStringId("SI_BINDING_NAME_RAVE_GUILD2", "Guild 2")
ZO_CreateStringId("SI_BINDING_NAME_RAVE_GUILD3", "Guild 3")
ZO_CreateStringId("SI_BINDING_NAME_RAVE_GUILD4", "Guild 4")
ZO_CreateStringId("SI_BINDING_NAME_RAVE_GUILD5", "Guild 5")
CBM:FireCallbacks( Constants.Callbacks.Loaded )
end
function Rave:OnUpdate( frameTime )
if ( not #self.Modules ) then
return
end
local modules = self.Modules
for i=1,#modules do
modules[ i ]:OnUpdate( frameTime )
end
end
function Rave:RegisterModule( moduleId, module, version )
if ( self.Modules[ moduleId ] and self.Modules[ moduleId ].__version > version ) then
return
end
print( 'Rave module registered %s', tostring( moduleId ) )
self.Modules[ moduleId ] = module:New( moduleId, version )
end
function Rave:GetModule( moduleId )
if ( not self.Modules[ moduleId ] ) then
return nil
end
return self.Modules[ moduleId ]
end
function Rave:RegisterEvent( event, callback )
if ( not self.EventRegistry[ event ] ) then
self.EventRegistry[ event ] = {}
end
tinsert( self.EventRegistry[ event ], callback )
self.Window:RegisterEvent( event, function( ... ) self:HandleEvent( ... ) end )
end
function Rave:UnregisterEvent( event, callback )
if ( not self.EventRegistry[ event ] ) then
return
end
local listeners = self.EventRegistry[ event ]
for i=#listeners,1,-1 do
if ( listeners[ i ] == callback ) then
tremove( listeners, i )
break
end
end
if ( #listeners == 0 ) then
self.EventRegistry[ event ] = nil
end
end
function Rave:HandleEvent( event, ... )
if ( not self.EventRegistry[ event ] ) then
return
end
local listeners = self.EventRegistry[ event ]
for i=1,#listeners do
listeners[ i ]( ... )
end
end
function Rave:GetModuleSettings( moduleId )
if ( not self.db[ moduleId ] ) then
self.db[ moduleId ] = {}
end
return self.db[ moduleId ]
end
function Rave:SetModuleSettings( moduleId, settings )
self.db[ moduleId ] = settings
end
function Rave:RegisterKey( keyId, callback )
if ( self.KeyRegistry[ keyId ] ) then
print( 'This key is already registered, sorry.' )
return
end
self.KeyRegistry[ keyId ] = callback
end
function Rave:UnregisterKey( keyId, callback )
if ( not self.KeyRegistry[ keyId ] ) then
return
end
self.KeyRegistry[ keyId ] = nil
end
function Rave:KeyUp( keyId )
if ( not self.KeyRegistry[ keyId ] ) then
return
end
self.KeyRegistry[ keyId ]()
end
function Rave:HandleChatMessage( messageType, from, text )
end
function Rave:HandleChatChannelJoin( ... )
-- body
end
function Rave:HandleChatChannelLeave( ... )
-- body
end
function Rave:StartChatInput( text, channel, target )
-- body
end | mit |
sami2448/sam | plugins/on&off.lua | 2 | 1712 | — Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'Robot is Online'
end
_config.disabled_channels[receiver] = false
save_config()
return "Robot is Online"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "Robot is Offline"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
— If sender is moderator then re-enable the channel
—if is_sudo(msg) then
if is_momod(msg) then
if msg.text == "[!/]bot on" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
— Enable a channel
if matches[1] == 'on' then
return enable_channel(receiver)
end
— Disable a channel
if matches[1] == 'off' then
return disable_channel(receiver)
end
end
return {
description = "Robot Switch",
usage = {
"/bot on : enable robot in group",
"/bot off : disable robot in group" },
patterns = {
"^[!/]bot? (on)",
"^[!/]bot? (off)" },
run = run,
privileged = true,
—moderated = true,
pre_process = pre_process
}
| gpl-2.0 |
shkan/telebot7 | plugins/time.lua | 120 | 2804 | -- Implement a command !time [area] which uses
-- 2 Google APIs to get the desired result:
-- 1. Geocoding to get from area to a lat/long pair
-- 2. Timezone to get the local time in that lat/long location
-- Globals
-- If you have a google api key for the geocoding/timezone api
api_key = nil
base_api = "https://maps.googleapis.com/maps/api"
dateFormat = "%A %d %B - %H:%M:%S"
-- Need the utc time for the google api
function utctime()
return os.time(os.date("!*t"))
end
-- Use the geocoding api to get the lattitude and longitude with accuracy specifier
-- CHECKME: this seems to work without a key??
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Get the data
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
-- Use timezone api to get the time in the lat,
-- Note: this needs an API key
function get_time(lat,lng)
local api = base_api .. "/timezone/json?"
-- Get a timestamp (server time is relevant here)
local timestamp = utctime()
local parameters = "location=" ..
URL.escape(lat) .. "," ..
URL.escape(lng) ..
"×tamp="..URL.escape(timestamp)
if api_key ~=nil then
parameters = parameters .. "&key="..api_key
end
local res,code = https.request(api..parameters)
if code ~= 200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Construct what we want
-- The local time in the location is:
-- timestamp + rawOffset + dstOffset
local localTime = timestamp + data.rawOffset + data.dstOffset
return localTime, data.timeZoneId
end
return localTime
end
function getformattedLocalTime(area)
if area == nil then
return "The time in nowhere is never"
end
lat,lng,acc = get_latlong(area)
if lat == nil and lng == nil then
return 'In "'..area..'" they dont have time'
end
local localTime, timeZoneId = get_time(lat,lng)
return "Local: "..timeZoneId.."\nTime: ".. os.date(dateFormat,localTime)
end
function run(msg, matches)
return getformattedLocalTime(matches[1])
end
return {
description = "Get Time Give by Local Name",
usage = "/time (local) : view local time",
patterns = {"^[!/]time (.*)$"},
run = run
}
| gpl-2.0 |
sigma-random/PrefSDK | formats/pdf/definition.lua | 1 | 2670 | local pref = require("pref")
local PdfTypes = require("formats.pdf.types")
local PdfParser = require("formats.pdf.parser")
local DataType = pref.datatype
local PdfFormat = pref.format.create("Portable Document Format", "Documents", "Dax", "1.1b")
function PdfFormat:validate(validator)
validator:checkAscii(0, "%PDF-")
end
function PdfFormat:parse(formattree)
local pdfparser = PdfParser()
local objtable = pdfparser:analyze(formattree.buffer)
for i, v in ipairs(objtable) do
if v.type == PdfTypes.PdfWhitespace then
self:createPdfWhitespaceStruct(formattree, v)
elseif v.type == PdfTypes.PdfComment then
self:createPdfCommentStruct(formattree, v)
elseif v.type == PdfTypes.PdfObject then
self:createPdfObjectStruct(formattree, v)
elseif v.type == PdfTypes.PdfHeader then
self:createPdfHeaderStruct(formattree, v)
elseif v.type == PdfTypes.PdfXRef then
self:createPdfXRefStruct(formattree, v)
elseif v.type == PdfTypes.PdfTrailer then
self:createPdfTrailerStruct(formattree, v)
else
pref.error("Unknown PdfType")
return
end
end
end
function PdfFormat:createPdfWhitespaceStruct(formattree, obj)
local pdfobj = formattree:addStructure("PDFWHITESPACE", obj.startpos)
pdfobj:addField(DataType.Blob, "Whitespace", obj.endpos - obj.startpos)
end
function PdfFormat:createPdfCommentStruct(formattree, obj)
local pdfobj = formattree:addStructure("PDFCOMMENT", obj.startpos)
pdfobj:addField(DataType.Blob, "Comment", obj.endpos - obj.startpos)
end
function PdfFormat:createPdfObjectStruct(formattree, obj)
local pdfobj = formattree:addStructure("PDFOBJECT", obj.startpos):dynamicInfo(PdfFormat.getObjectName)
pdfobj:addField(DataType.Blob, "Data", obj.endpos - obj.startpos)
end
function PdfFormat:createPdfHeaderStruct(formattree, obj)
local pdfobj = formattree:addStructure("PDFHEADER", obj.startpos)
pdfobj:addField(DataType.Character, "Header", obj.endpos - obj.startpos)
end
function PdfFormat:createPdfXRefStruct(formattree, obj)
local pdfobj = formattree:addStructure("PDFXREF", obj.startpos)
pdfobj:addField(DataType.Blob, "Data", obj.endpos - obj.startpos)
end
function PdfFormat:createPdfTrailerStruct(formattree, obj)
local pdfobj = formattree:addStructure("PDFTRAILER", obj.startpos)
pdfobj:addField(DataType.Character, "Trailer", obj.endpos - obj.startpos)
end
function PdfFormat.getObjectName(objstruct, formattree)
local buffer, offset = formattree.buffer, objstruct.offset
local objpos = buffer:indexOf("obj", offset)
return "Object(Number, Revision): " .. buffer:readString(offset, (objpos - offset) - 1)
end
return PdfFormat | gpl-3.0 |
thenumbernine/hydro-cl-lua | tests/euler fluid equations/plot.lua | 1 | 1246 | #!/usr/bin/env luajit
-- plot the var-ranges.txt created by running the app.lua with 'output variable ranges' set
require 'ext'
local fn = assert((...))
local matrix = require 'matrix'
local _ = range
local ls = file(fn):read():trim():split'\n'
local cols = ls:remove(1):split'\t'
local m = matrix(ls:map(function(l)
return l:split'\t':map(function(w)
return w == 'inf' and math.huge
or (w == '-inf' and -math.huge
or assert(tonumber(w), "failed to convert to number "..tostring(w)))
end)
end)):transpose()
--[[ using gnuplot
cols = range((#cols-1)/2):map(function(i)
local name = cols[2*i-1]
if i > 1 then
name = assert(name:match('(.*)_max')):gsub('_', ' ')
end
return name
end)
require 'gnuplot'(table({
output = 'gnuplot.png',
--style = 'data lines',
--style = 'fill transparent solid 0.2 noborder',
style = 'fill transparent pattern 4 bo',
data = m(_,_(1,3000)),
}, cols:sub(2):map(function(title, i)
return {
using = table{1,2*i,2*i+1}:concat':',
title = title,
with = 'filledcurves',
}
end)))
--]]
-- [[ using interactive plot
m = m(_, _(1, 3199))
local t = m[1]
require 'plot2d'(cols:sub(2):map(function(title,i)
local s = matrix{t, m[i+1]}
s.enabled = true
return s, title
end))
--]]
| mit |
mms92/wire | lua/effects/thruster_ring_grow1.lua | 10 | 1652 |
EFFECT.Mat = Material( "effects/select_ring" )
/*---------------------------------------------------------
Initializes the effect. The data is a table of data
which was passed from the server.
---------------------------------------------------------*/
function EFFECT:Init( data )
local size = 16
self:SetCollisionBounds( Vector( -size,-size,-size ), Vector( size,size,size ) )
local Pos = data:GetOrigin() + data:GetNormal() * 2
self:SetPos( Pos )
self:SetAngles( data:GetNormal():Angle() + Angle( 0.01, 0.01, 0.01 ) )
self.Pos = data:GetOrigin()
self.Normal = data:GetNormal()
self.Speed = 2
self.Size = 16
self.Alpha = 255
end
/*---------------------------------------------------------
THINK
---------------------------------------------------------*/
function EFFECT:Think( )
local speed = FrameTime() * self.Speed
//if (self.Speed > 100) then self.Speed = self.Speed - 1000 * speed end
//self.Size = self.Size + speed * self.Speed
self.Size = self.Size + (255 - self.Alpha)*0.06
self.Alpha = self.Alpha - 250.0 * speed
self:SetPos( self:GetPos() + self.Normal * speed * 128 )
if (self.Alpha < 0 ) then return false end
if (self.Size < 0) then return false end
return true
end
/*---------------------------------------------------------
Draw the effect
---------------------------------------------------------*/
function EFFECT:Render( )
if (self.Alpha < 1 ) then return end
render.SetMaterial( self.Mat )
render.DrawQuadEasy( self:GetPos(),
self:GetAngles():Forward(),
self.Size, self.Size,
Color( math.Rand( 10, 100), math.Rand( 100, 220), math.Rand( 240, 255), self.Alpha )
)
end
| apache-2.0 |
LuaDist2/luaposix | lib/posix/deprecated.lua | 1 | 31197 | --[[
POSIX library for Lua 5.1, 5.2 & 5.3.
Copyright (C) 2014-2017 Gary V. Vaughan
]]
--[[--
Legacy Lua POSIX bindings.
Undocumented Legacy APIs for compatibility with previous releases.
@module posix.deprecated
]]
local _argcheck = require "posix._argcheck"
local bit = require "bit32"
-- Lua 5.3 has table.unpack but not _G.unpack
-- Lua 5.2 has table.unpack and _G.unpack
-- Lua 5.1 has _G.unpack but not table.unpack
local unpack = table.unpack or unpack
local argerror, argtypeerror, badoption =
_argcheck.argerror, _argcheck.argtypeerror, _argcheck.badoption
local band, bnot, bor = bit.band, bit.bnot, bit.bor
local checkint, checkselection, checkstring, checktable =
_argcheck.checkint, _argcheck.checkselection, _argcheck.checkstring, _argcheck.checktable
local optint, optstring, opttable =
_argcheck.optint, _argcheck.optstring, _argcheck.opttable
local toomanyargerror = _argcheck.toomanyargerror
-- Convert a legacy API tm table to a posix.time.PosixTm compatible table.
local function PosixTm (legacytm)
return {
tm_sec = legacytm.sec,
tm_min = legacytm.min,
tm_hour = legacytm.hour,
-- For compatibility with Lua os.date() use "day" if "monthday" is
-- not set.
tm_mday = legacytm.monthday or legacytm.day,
tm_mon = legacytm.month - 1,
tm_year = legacytm.year - 1900,
tm_wday = legacytm.weekday,
tm_yday = legacytm.yearday,
tm_isdst = legacytm.is_dst and 1 or 0,
}
end
-- Convert a posix.time.PosixTm into a legacy API tm table.
local function LegacyTm (posixtm)
return {
sec = posixtm.tm_sec,
min = posixtm.tm_min,
hour = posixtm.tm_hour,
monthday = posixtm.tm_mday,
day = posixtm.tm_mday,
month = posixtm.tm_mon + 1,
year = posixtm.tm_year + 1900,
weekday = posixtm.tm_wday,
yearday = posixtm.tm_yday,
is_dst = posixtm.tm_isdst ~= 0,
}
end
local function doselection (name, argoffset, fields, map)
if #fields == 1 and type (fields[1]) == "table" then fields = fields[1] end
if not (next (fields)) then
return map
else
local r = {}
for i, v in ipairs (fields) do
if map[v] then
r[#r + 1] = map[v]
else
argerror (name, i + argoffset, "invalid option '" .. v .. "'", 2)
end
end
return unpack (r)
end
end
local st = require "posix.sys.stat"
local S_IRUSR, S_IWUSR, S_IXUSR = st.S_IRUSR, st.S_IWUSR, st.S_IXUSR
local S_IRGRP, S_IWGRP, S_IXGRP = st.S_IRGRP, st.S_IWGRP, st.S_IXGRP
local S_IROTH, S_IWOTH, S_IXOTH = st.S_IROTH, st.S_IWOTH, st.S_IXOTH
local S_ISUID, S_ISGID, S_IRWXU, S_IRWXG, S_IRWXO =
st.S_ISUID, st.S_ISGID, st.S_IRWXU, st.S_IRWXG, st.S_IRWXO
local mode_map = {
{ c = "r", b = S_IRUSR }, { c = "w", b = S_IWUSR }, { c = "x", b = S_IXUSR },
{ c = "r", b = S_IRGRP }, { c = "w", b = S_IWGRP }, { c = "x", b = S_IXGRP },
{ c = "r", b = S_IROTH }, { c = "w", b = S_IWOTH }, { c = "x", b = S_IXOTH },
}
local function pushmode (mode)
local m = {}
for i = 1, 9 do
if band (mode, mode_map[i].b) ~= 0 then m[i] = mode_map[i].c else m[i] = "-" end
end
if band (mode, S_ISUID) ~= 0 then
if band (mode, S_IXUSR) ~= 0 then m[3] = "s" else m[3] = "S" end
end
if band (mode, S_ISGID) ~= 0 then
if band (mode, S_IXGRP) ~= 0 then m[6] = "s" else m[6] = "S" end
end
return table.concat (m)
end
local M = {}
--- Bind an address to a socket.
-- @function bind
-- @int fd socket descriptor to act on
-- @tparam PosixSockaddr addr socket address
-- @treturn[1] bool `true`, if successful
-- @return[2] nil
-- @treturn[2] string error messag
-- @treturn[2] int errnum
-- @see bind(2)
local sock = require "posix.sys.socket"
local bind = sock.bind
function M.bind (...)
local rt = { bind (...) }
if rt[1] == 0 then return true end
return unpack (rt)
end
--- Find the precision of a clock.
-- @function clock_getres
-- @string[opt="realtime"] name name of clock, one of "monotonic",
-- "process\_cputime\_id", "realtime", or "thread\_cputime\_id"
-- @treturn[1] int seconds
-- @treturn[21 int nanoseconds, if successful
-- @return[2] nil
-- @treturn[2] string error message
-- @treturn[2] int errnum
-- @see clock_getres(3)
local tm = require "posix.time"
local _clock_getres = tm.clock_getres
local function get_clk_id_const (name)
local map = {
monotonic = tm.CLOCK_MONOTONIC,
process_cputime_id = tm.CLOCK_PROCESS_TIME_ID,
thread_cputime_id = tm.CLOCK_THREAD_CPUTIME_ID,
}
return map[name] or tm.CLOCK_REALTIME
end
local function clock_getres (name)
local ts = _clock_getres (get_clk_id_const (name))
return ts.tv_sec, ts.tv_nsec
end
if _clock_getres == nil then
-- Not supported by underlying system
elseif _DEBUG ~= false then
M.clock_getres = function (...)
local argt = {...}
optstring ("clock_getres", 1, argt[1], "realtime")
if #argt > 1 then toomanyargerror ("clock_getres", 1, #argt) end
return clock_getres (...)
end
else
M.clock_getres = clock_getres
end
--- Read a clock
-- @function clock_gettime
-- @string[opt="realtime"] name name of clock, one of "monotonic",
-- "process\_cputime\_id", "realtime", or "thread\_cputime\_id"
-- @treturn[1] int seconds
-- @treturn[21 int nanoseconds, if successful
-- @return[2] nil
-- @treturn[2] string error message
-- @treturn[2] int errnum
-- @see clock_gettime(3)
local tm = require "posix.time"
local _clock_gettime = tm.clock_gettime
local function clock_gettime (name)
local ts = _clock_gettime (get_clk_id_const (name))
return ts.tv_sec, ts.tv_nsec
end
if _clock_gettime == nil then
-- Not supported by underlying system
elseif _DEBUG ~= false then
M.clock_gettime = function (...)
local argt = {...}
optstring ("clock_gettime", 1, argt[1], "realtime")
if #argt > 1 then toomanyargerror ("clock_gettime", 1, #argt) end
return clock_gettime (...)
end
else
M.clock_gettime = clock_gettime
end
--- Initiate a connection on a socket.
-- @function connect
-- @int fd socket descriptor to act on
-- @tparam PosixSockaddr addr socket address
-- @treturn[1] bool `true`, if successful
-- @return[2] nil
-- @treturn[2] string error message
-- @treturn[2] int errnum
-- @see connect(2)
local sock = require "posix.sys.socket"
local connect = sock.connect
function M.connect (...)
local rt = { connect (...) }
if rt[1] == 0 then return true end
return unpack (rt)
end
--- Execute a program without using the shell.
-- @function exec
-- @string path
-- @tparam[opt] table|strings ... table or tuple of arguments (table can include index 0)
-- @return nil
-- @treturn string error message
-- @see execve(2)
local unistd = require "posix.unistd"
local _exec = unistd.exec
local function exec (path, ...)
local argt = {...}
if #argt == 1 and type (argt[1]) == "table" then
argt = argt[1]
end
return _exec (path, argt)
end
if _DEBUG ~= false then
M.exec = function (...)
local argt = {...}
checkstring ("exec", 1, argt[1])
if type (argt[2]) ~= "table" and type (argt[2]) ~= "string" and type (argt[2]) ~= "nil" then
argtypeerror ("exec", 2, "string, table or nil", argt[2])
end
if #argt > 2 then
if type (argt[2]) == "table" then
toomanyargerror ("exec", 2, #argt)
else
for i = 3, #argt do
checkstring ("exec", i, argt[i])
end
end
end
return exec (...)
end
else
M.exec = exec
end
--- Execute a program with the shell.
-- @function execp
-- @string path
-- @tparam[opt] table|strings ... table or tuple of arguments (table can include index 0)
-- @return nil
-- @treturn string error message
-- @see execve(2)
local unistd = require "posix.unistd"
local _execp = unistd.execp
local function execp (path, ...)
local argt = {...}
if #argt == 1 and type (argt[1]) == "table" then
argt = argt[1]
end
return _execp (path, argt)
end
if _DEBUG ~= false then
M.execp = function (...)
local argt = {...}
checkstring ("execp", 1, argt[1])
if type (argt[2]) ~= "table" and type (argt[2]) ~= "string" and type (argt[2]) ~= "nil" then
argtypeerror ("execp", 2, "string, table or nil", argt[2])
end
if #argt > 2 then
if type (argt[2]) == "table" then
toomanyargerror ("execp", 2, #argt)
else
for i = 3, #argt do
checkstring ("execp", i, argt[i])
end
end
end
return execp (...)
end
else
M.execp = execp
end
--- Instruct kernel on appropriate cache behaviour for a file or file segment.
-- @function fadvise
-- @tparam file fh Lua file object
-- @int offset start of region
-- @int len number of bytes in region
-- @int advice one of `POSIX_FADV_NORMAL, `POSIX_FADV_SEQUENTIAL,
-- `POSIX_FADV_RANDOM`, `POSIX_FADV_\NOREUSE`, `POSIX_FADV_WILLNEED` or
-- `POSIX_FADV_DONTNEED`
-- @treturn[1] int `0`, if successful
-- @return[2] nil
-- @treturn[2] string error message
-- @treturn[2] int errnum
-- @see posix_fadvise(2)
local fc = require "posix.fcntl"
local stdio = require "posix.stdio"
local posix_fadvise = fc.posix_fadvise
local fileno = stdio.fileno
local function fadvise (fh, ...)
return posix_fadvise (fileno (fh), ...)
end
if posix_fadvise == nil then
-- Not supported by underlying system
elseif _DEBUG ~= false then
M.fadvise = function (...)
argt = {...}
if io.type (argt[1]) ~= "file" then
argtypeerror ("fadvise", 1, "FILE*", argt[1])
end
checkint ("fadvise", 2, argt[2])
checkint ("fadvise", 3, argt[3])
checkint ("fadvise", 4, argt[4])
if #argt > 4 then toomanyargerror ("fadvise", 4, #argt) end
return fadvise (...)
end
else
M.fadvise = fadvise
end
--- Match a filename against a shell pattern.
-- @function fnmatch
-- @string pat shell pattern
-- @string name filename
-- @return true or false
-- @raise error if fnmatch failed
-- @see posix.fnmatch.fnmatch
local fnm = require "posix.fnmatch"
function M.fnmatch (...)
local r = fnm.fnmatch (...)
if r == 0 then
return true
elseif r == fnm.FNM_NOMATCH then
return false
end
error "fnmatch failed"
end
--- Group information.
-- @table group
-- @string name name of group
-- @int gid unique group id
-- @string ... list of group members
--- Information about a group.
-- @function getgroup
-- @tparam[opt=current group] int|string group id or group name
-- @treturn group group information
-- @usage
-- print (posix.getgroup (posix.getgid ()).name)
local grp = require "posix.grp"
local unistd = require "posix.unistd"
local getgrgid, getgrnam = grp.getgrgid, grp.getgrnam
local getegid = unistd.getegid
local function getgroup (grp)
if grp == nil then grp = getegid () end
local g
if type (grp) == "number" then
g = getgrgid (grp)
elseif type (grp) == "string" then
g = getgrnam (grp)
else
argtypeerror ("getgroup", 1, "string, int or nil", grp)
end
if g ~= nil then
return {name=g.gr_name, gid=g.gr_gid, mem=g.gr_mem}
end
end
if _DEBUG ~= false then
M.getgroup = function (...)
local argt = {...}
if #argt > 1 then toomanyargerror ("getgroup", 1, #argt) end
return getgroup (...)
end
else
M.getgroup = getgroup
end
--- Get the password entry for a user.
-- @function getpasswd
-- @tparam[opt=current user] int|string user name or id
-- @string ... field names, each one of "uid", "name", "gid", "passwd",
-- "dir" or "shell"
-- @return ... values, or a table of all fields if *user* is `nil`
-- @usage for a,b in pairs (posix.getpasswd "root") do print (a, b) end
-- @usage print (posix.getpasswd ("root", "shell"))
local pwd = require "posix.pwd"
local unistd = require "posix.unistd"
local getpwnam, getpwuid = pwd.getpwnam, pwd.getpwuid
local geteuid = unistd.geteuid
local function getpasswd (user, ...)
if user == nil then user = geteuid () end
local p
if type (user) == "number" then
p = getpwuid (user)
elseif type (user) == "string" then
p = getpwnam (user)
else
argtypeerror ("getpasswd", 1, "string, int or nil", user)
end
if p ~= nil then
return doselection ("getpasswd", 1, {...}, {
dir = p.pw_dir,
gid = p.pw_gid,
name = p.pw_name,
passwd = p.pw_passwd,
shell = p.pw_shell,
uid = p.pw_uid,
})
end
end
if _DEBUG ~= false then
M.getpasswd = function (user, ...)
checkselection ("getpasswd", 2, {...}, 2)
return getpasswd (user, ...)
end
else
M.getpasswd = getpasswd
end
--- Get process identifiers.
-- @function getpid
-- @tparam[opt] table|string type one of "egid", "euid", "gid", "uid",
-- "pgrp", "pid" or "ppid"; or a single list of the same
-- @string[opt] ... unless *type* was a table, zero or more additional
-- type strings
-- @return ... values, or a table of all fields if no option given
-- @usage for a,b in pairs (posix.getpid ()) do print (a, b) end
-- @usage print (posix.getpid ("uid", "euid"))
local unistd = require "posix.unistd"
local getegid, geteuid, getgid, getuid =
unistd.getegid, unistd.geteuid, unistd.getgid, unistd.getuid
local _getpid, getpgrp, getppid =
unistd.getpid, unistd.getpgrp, unistd.getppid
local function getpid (...)
return doselection ("getpid", 0, {...}, {
egid = getegid (),
euid = geteuid (),
gid = getgid (),
uid = getuid (),
pgrp = getpgrp (),
pid = _getpid (),
ppid = getppid (),
})
end
if _DEBUG ~= false then
M.getpid = function (...)
checkselection ("getpid", 1, {...}, 2)
return getpid (...)
end
else
M.getpid = getpid
end
--- Get resource limits for this process.
-- @function getrlimit
-- @string resource one of "core", "cpu", "data", "fsize", "nofile",
-- "stack" or "as"
-- @treturn[1] int soft limit
-- @treturn[1] int hard limit, if successful
-- @return[2] nil
-- @treturn[2] string error message
-- @treturn[2] int errnum
local resource = require "posix.sys.resource"
local _getrlimit = resource.getrlimit
local rlimit_map = {
core = resource.RLIMIT_CORE,
cpu = resource.RLIMIT_CPU,
data = resource.RLIMIT_DATA,
fsize = resource.RLIMIT_FSIZE,
nofile = resource.RLIMIT_NOFILE,
stack = resource.RLIMIT_STACK,
as = resource.RLIMIT_AS,
}
local function getrlimit (rcstr)
local rc = rlimit_map[string.lower (rcstr)]
if rc == nil then
argerror("getrlimit", 1, "invalid option '" .. rcstr .. "'")
end
local rlim = _getrlimit (rc)
return rlim.rlim_cur, rlim.rlim_max
end
if _DEBUG ~= false then
M.getrlimit = function (...)
local argt = {...}
checkstring ("getrlimit", 1, argt[1])
if #argt > 1 then toomanyargerror ("getrlimit", 1, #argt) end
return getrlimit (...)
end
else
M.getrlimit = getrlimit
end
--- Get time of day.
-- @function gettimeofday
-- @treturn timeval time elapsed since *epoch*
-- @see gettimeofday(2)
local systime = require "posix.sys.time"
local gettimeofday = systime.gettimeofday
function M.gettimeofday (...)
local tv = gettimeofday (...)
return { sec = tv.tv_sec, usec = tv.tv_usec }
end
--- Convert epoch time value to a broken-down UTC time.
-- Here, broken-down time tables the month field is 1-based not
-- 0-based, and the year field is the full year, not years since
-- 1900.
-- @function gmtime
-- @int[opt=now] t seconds since epoch
-- @treturn table broken-down time
local tm = require "posix.time"
local _gmtime, time = tm.gmtime, tm.time
local function gmtime (epoch)
return LegacyTm (_gmtime (epoch or time ()))
end
if _DEBUG ~= false then
M.gmtime = function (...)
local argt = {...}
optint ("gmtime", 1, argt[1])
if #argt > 1 then toomanyargerror ("gmtime", 1, #argt) end
return gmtime (...)
end
else
M.gmtime = gmtime
end
--- Get host id.
-- @function hostid
-- @treturn int unique host identifier
local unistd = require "posix.unistd"
M.hostid = unistd.gethostid
--- Check for any printable character except space.
-- @function isgraph
-- @see isgraph(3)
-- @string character to act on
-- @treturn bool non-`false` if character is in the class
local ctype = require "posix.ctype"
local isgraph = ctype.isgraph
function M.isgraph (...)
return isgraph (...) ~= 0
end
--- Check for any printable character including space.
-- @function isprint
-- @string character to act on
-- @treturn bool non-`false` if character is in the class
-- @see isprint(3)
local ctype = require "posix.ctype"
local isprint = ctype.isprint
function M.isprint (...)
return isprint (...) ~= 0
end
--- Convert epoch time value to a broken-down local time.
-- Here, broken-down time tables the month field is 1-based not
-- 0-based, and the year field is the full year, not years since
-- 1900.
-- @function localtime
-- @int[opt=now] t seconds since epoch
-- @treturn table broken-down time
local tm = require "posix.time"
local _localtime, time = tm.localtime, tm.time
local function localtime (epoch)
return LegacyTm (_localtime (epoch or time ()))
end
if _DEBUG ~= false then
M.localtime = function (...)
local argt = {...}
optint ("localtime", 1, argt[1])
if #argt > 1 then toomanyargerror ("localtime", 1, #argt) end
return localtime (...)
end
else
M.localtime = localtime
end
--- Convert a broken-down localtime table into an epoch time.
-- @function mktime
-- @tparam tm broken-down localtime table
-- @treturn in seconds since epoch
-- @see mktime(3)
-- @see localtime
local tm = require "posix.time"
local _mktime, localtime, time = tm.mktime, tm.localtime, tm.time
local function mktime (legacytm)
local posixtm = legacytm and PosixTm (legacytm) or localtime (time ())
return _mktime (posixtm)
end
if _DEBUG ~= false then
M.mktime = function (...)
local argt = {...}
opttable ("mktime", 1, argt[1])
if #argt > 1 then toomanyargerror ("mktime", 1, #argt) end
return mktime (...)
end
else
M.mktime = mktime
end
--- Sleep with nanosecond precision.
-- @function nanosleep
-- @int seconds requested sleep time
-- @int nanoseconds requested sleep time
-- @treturn[1] int `0` if requested time has elapsed
-- @return[2] nil
-- @treturn[2] string error message
-- @treturn[2] int errnum
-- @treturn[2] int unslept seconds remaining, if interrupted
-- @treturn[2] int unslept nanoseconds remaining, if interrupted
-- @see nanosleep(2)
-- @see posix.unistd.sleep
local tm = require "posix.time"
local _nanosleep = tm.nanosleep
local function nanosleep (sec, nsec)
local r, errmsg, errno, timespec = _nanosleep {tv_sec = sec, tv_nsec = nsec}
if r == 0 then return 0 end
return r, errmsg, errno, timespec.tv_sec, timespec.tv_nsec
end
if _DEBUG ~= false then
M.nanosleep = function (...)
local argt = {...}
checkint ("nanosleep", 1, argt[1])
checkint ("nanosleep", 2, argt[2])
if #argt > 2 then toomanyargerror ("nanosleep", 2, #argt) end
return nanosleep (...)
end
else
M.nanosleep = nanosleep
end
--- Open the system logger.
-- @function openlog
-- @string ident all messages will start with this
-- @string[opt] option any combination of 'c' (directly to system console
-- if an error sending), 'n' (no delay) and 'p' (show PID)
-- @int [opt=`LOG_USER`] facility one of `LOG_AUTH`, `LOG_AUTHORITY`,
-- `LOG_CRON`, `LOG_DAEMON`, `LOG_KERN`, `LOG_LPR`, `LOG_MAIL`,
-- `LOG_NEWS`, `LOG_SECURITY`, `LOG_USER`, `LOG_UUCP` or `LOG_LOCAL0`
-- through `LOG_LOCAL7`
-- @see syslog(3)
local bit = require "bit32"
local log = require "posix.syslog"
local bor = bit.bor
local _openlog = log.openlog
local optionmap = {
[' '] = 0,
c = log.LOG_CONS,
n = log.LOG_NDELAY,
p = log.LOG_PID,
}
local function openlog (ident, optstr, facility)
local option = 0
if optstr then
for i = 1, #optstr do
local c = optstr:sub (i, i)
if optionmap[c] == nil then
badoption ("openlog", 2, "openlog", c)
end
option = bor (option, optionmap[c])
end
end
return _openlog (ident, option, facility)
end
if _DEBUG ~= false then
M.openlog = function (...)
local argt = {...}
checkstring ("openlog", 1, argt[1])
optstring ("openlog", 2, argt[2])
optint ("openlog", 3, argt[3])
if #argt > 3 then toomanyargerror ("openlog", 3, #argt) end
return openlog (...)
end
else
M.openlog = openlog
end
--- Get configuration information at runtime.
-- @function pathconf
-- @string[opt="."] path file to act on
-- @tparam[opt] table|string key one of "CHOWN_RESTRICTED", "LINK_MAX",
-- "MAX_CANON", "MAX_INPUT", "NAME_MAX", "NO_TRUNC", "PATH_MAX", "PIPE_BUF"
-- or "VDISABLE"
-- @string[opt] ... unless *type* was a table, zero or more additional
-- type strings
-- @return ... values, or a table of all fields if no option given
-- @see sysconf(2)
-- @usage for a,b in pairs (posix.pathconf "/dev/tty") do print (a, b) end
local unistd = require "posix.unistd"
local _pathconf = unistd.pathconf
local Spathconf = { CHOWN_RESTRICTED = 1, LINK_MAX = 1, MAX_CANON = 1,
MAX_INPUT = 1, NAME_MAX = 1, NO_TRUNC = 1, PATH_MAX = 1, PIPE_BUF = 1,
VDISABLE = 1 }
local function pathconf (path, ...)
local argt, map = {...}, {}
if path ~= nil and Spathconf[path] ~= nil then
path, argt = ".", {path, ...}
end
for k in pairs (Spathconf) do
map[k] = _pathconf (path or ".", unistd["_PC_" .. k])
end
return doselection ("pathconf", 1, {...}, map)
end
if _DEBUG ~= false then
M.pathconf = function (path, ...)
if path ~= nil and Spathconf[path] ~= nil then
checkselection ("pathconf", 1, {path, ...}, 2)
else
optstring ("pathconf", 1, path, ".", 2)
checkselection ("pathconf", 2, {...}, 2)
end
return pathconf (path, ...)
end
else
M.pathconf = pathconf
end
--- Set resource limits for this process.
-- @function setrlimit
-- @string resource one of "core", "cpu", "data", "fsize", "nofile",
-- "stack" or "as"
-- @int[opt] softlimit process may receive a signal when reached
-- @int[opt] hardlimit process may be terminated when reached
-- @treturn[1] int `0`, if successful
-- @return[2] nil
-- @treturn[2] string error message
-- @treturn[2] int errnum
local resource = require "posix.sys.resource"
local _setrlimit = resource.setrlimit
local rlimit_map = {
core = resource.RLIMIT_CORE,
cpu = resource.RLIMIT_CPU,
data = resource.RLIMIT_DATA,
fsize = resource.RLIMIT_FSIZE,
nofile = resource.RLIMIT_NOFILE,
stack = resource.RLIMIT_STACK,
as = resource.RLIMIT_AS,
}
local function setrlimit (rcstr, cur, max)
local rc = rlimit_map[string.lower (rcstr)]
if rc == nil then
argerror("setrlimit", 1, "invalid option '" .. rcstr .. "'")
end
local lim
if cur == nil or max == nil then
lim= _getrlimit (rc)
end
return _setrlimit (rc, {
rlim_cur = cur or lim.rlim_cur,
rlim_max = max or lim.rlim_max,
})
end
if _DEBUG ~= false then
M.setrlimit = function (...)
local argt = {...}
checkstring ("setrlimit", 1, argt[1])
optint ("setrlimit", 2, argt[2])
optint ("setrlimit", 3, argt[3])
if #argt > 3 then toomanyargerror ("setrlimit", 3, #argt) end
return setrlimit (...)
end
else
M.getrlimit = getrlimit
end
--- Information about an existing file path.
-- If the file is a symbolic link, return information about the link
-- itself.
-- @function stat
-- @string path file to act on
-- @tparam[opt] table|string field one of "dev", "ino", "mode", "nlink",
-- "uid", "gid", "rdev", "size", "atime", "mtime", "ctime" or "type"
-- @string[opt] ... unless *field* was a table, zero or more additional
-- field names
-- @return values, or table of all fields if no option given
-- @see stat(2)
-- @usage for a,b in pairs (P,stat "/etc/") do print (a, b) end
local st = require "posix.sys.stat"
local S_ISREG, S_ISLNK, S_ISDIR, S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK =
st.S_ISREG, st.S_ISLNK, st.S_ISDIR, st.S_ISCHR, st.S_ISBLK, st.S_ISFIFO, st.S_ISSOCK
local function filetype (mode)
if S_ISREG (mode) ~= 0 then
return "regular"
elseif S_ISLNK (mode) ~= 0 then
return "link"
elseif S_ISDIR (mode) ~= 0 then
return "directory"
elseif S_ISCHR (mode) ~= 0 then
return "character device"
elseif S_ISBLK (mode) ~= 0 then
return "block device"
elseif S_ISFIFO (mode) ~= 0 then
return "fifo"
elseif S_ISSOCK (mode) ~= 0 then
return "socket"
else
return "?"
end
end
local _stat = st.lstat -- for bugwards compatibility with v<=32
local function stat (path, ...)
local info = _stat (path)
if info ~= nil then
return doselection ("stat", 1, {...}, {
dev = info.st_dev,
ino = info.st_ino,
mode = pushmode (info.st_mode),
nlink = info.st_nlink,
uid = info.st_uid,
gid = info.st_gid,
size = info.st_size,
atime = info.st_atime,
mtime = info.st_mtime,
ctime = info.st_ctime,
type = filetype (info.st_mode),
})
end
end
if _DEBUG ~= false then
M.stat = function (path, ...)
checkstring ("stat", 1, path, 2)
checkselection ("stat", 2, {...}, 2)
return stat (path, ...)
end
else
M.stat = stat
end
--- Fetch file system statistics.
-- @function statvfs
-- @string path any path within the mounted file system
-- @tparam[opt] table|string field one of "bsize", "frsize", "blocks",
-- "bfree", "bavail", "files", "ffree", "favail", "fsid", "flag",
-- "namemax"
-- @string[opt] ... unless *field* was a table, zero or more additional
-- field names
-- @return values, or table of all fields if no option given
-- @see statvfs(2)
-- @usage for a,b in pairs (P,statvfs "/") do print (a, b) end
local sv = require "posix.sys.statvfs"
local _statvfs = sv.statvfs
local function statvfs (path, ...)
local info = _statvfs (path)
if info ~= nil then
return doselection ("statvfs", 1, {...}, {
bsize = info.f_bsize,
frsize = info.f_frsize,
blocks = info.f_blocks,
bfree = info.f_bfree,
bavail = info.f_bavail,
files = info.f_files,
ffree = info.f_ffree,
favail = info.f_favail,
fsid = info.f_fsid,
flag = info.f_flag,
namemax = info.f_namemax,
})
end
end
if _DEBUG ~= false then
M.statvfs = function (path, ...)
checkstring ("statvfs", 1, path, 2)
checkselection ("statvfs", 2, {...}, 2)
return statvfs (path, ...)
end
else
M.statvfs = statvfs
end
--- Write a time out according to a format.
-- @function strftime
-- @string format specifier with `%` place-holders
-- @tparam PosixTm tm broken-down local time
-- @treturn string *format* with place-holders plugged with *tm* values
-- @see strftime(3)
local tm = require "posix.time"
local _strftime, localtime, time = tm.strftime, tm.localtime, tm.time
local function strftime (fmt, legacytm)
local posixtm = legacytm and PosixTm (legacytm) or localtime (time ())
return _strftime (fmt, posixtm)
end
if _DEBUG ~= false then
M.strftime = function (...)
local argt = {...}
checkstring ("strftime", 1, argt[1])
opttable ("strftime", 2, argt[2])
if #argt > 2 then toomanyargerror ("strftime", 2, #argt) end
return strftime (...)
end
else
M.strftime = strftime
end
--- Parse a date string.
-- @function strptime
-- @string s
-- @string format same as for `strftime`
-- @usage posix.strptime('20','%d').monthday == 20
-- @treturn[1] PosixTm broken-down local time
-- @treturn[1] int next index of first character not parsed as part of the date
-- @return[2] nil
-- @see strptime(3)
local tm = require "posix.time"
local _strptime = tm.strptime
local function strptime (s, fmt)
return _strptime (s, fmt)
end
if _DEBUG ~= false then
M.strptime = function (...)
local argt = {...}
checkstring ("strptime", 1, argt[1])
checkstring ("strptime", 2, argt[2])
if #argt > 2 then toomanyargerror ("strptime", 2, #argt) end
local tm, i = strptime (...)
return LegacyTm (tm), i
end
else
M.strptime = strptime
end
--- Get configuration information at runtime.
-- @function sysconf
-- @tparam[opt] table|string key one of "ARG_MAX", "CHILD_MAX",
-- "CLK_TCK", "JOB_CONTROL", "NGROUPS_MAX", "OPEN_MAX", "SAVED_IDS",
-- "STREAM_MAX", "TZNAME_MAX" or "VERSION"
-- @string[opt] ... unless *type* was a table, zero or more additional
-- type strings
-- @return ... values, or a table of all fields if no option given
-- @see sysconf(2)
-- @usage for a,b in pairs (posix.sysconf ()) do print (a, b) end
-- @usage print (posix.sysconf ("STREAM_MAX", "ARG_MAX"))
local unistd = require "posix.unistd"
local _sysconf = unistd.sysconf
local function sysconf (...)
return doselection ("sysconf", 0, {...}, {
ARG_MAX = _sysconf (unistd._SC_ARG_MAX),
CHILD_MAX = _sysconf (unistd._SC_CHILD_MAX),
CLK_TCK = _sysconf (unistd._SC_CLK_TCK),
JOB_CONTROL = _sysconf (unistd._SC_JOB_CONTROL),
NGROUPS_MAX = _sysconf (unistd._SC_NGROUPS_MAX),
OPEN_MAX = _sysconf (unistd._SC_OPEN_MAX),
PAGESIZE = _sysconf (unistd._SC_PAGESIZE),
SAVED_IDS = _sysconf (unistd._SC_SAVED_IDS),
STREAM_MAX = _sysconf (unistd._SC_STREAM_MAX),
TZNAME_MAX = _sysconf (unistd._SC_TZNAME_MAX),
VERSION = _sysconf (unistd._SC_VERSION),
})
end
if _DEBUG ~= false then
M.sysconf = function (...)
checkselection ("sysconf", 1, {...}, 2)
return sysconf (...)
end
else
M.sysconf = sysconf
end
--- Get the current process times.
-- @function times
-- @tparam[opt] table|string key one of "utime", "stime", "cutime",
-- "cstime" or "elapsed"
-- @string[opt] ... unless *key* was a table, zero or more additional
-- key strings.
-- @return values, or a table of all fields if no keys given
-- @see times(2)
-- @usage for a,b in pairs(posix.times ()) do print (a, b) end
-- @usage print (posix.times ("utime", "elapsed")
local tms = require "posix.sys.times"
local _times = tms.times
local function times (...)
local info = _times ()
return doselection ("times", 0, {...}, {
utime = info.tms_utime,
stime = info.tms_stime,
cutime = info.tms_cutime,
cstime = info.tms_cstime,
elapsed = info.elapsed,
})
end
if _DEBUG ~= false then
M.times = function (...)
checkselection ("times", 1, {...}, 2)
return times (...)
end
else
M.times = times
end
--- Return information about this machine.
-- @function uname
-- @see uname(2)
-- @string[opt="%s %n %r %v %m"] format contains zero or more of:
--
-- * %m machine name
-- * %n node name
-- * %r release
-- * %s sys name
-- * %v version
--
--@treturn[1] string filled *format* string, if successful
--@return[2] nil
--@treturn string error message
local utsname = require "posix.sys.utsname"
local _uname = utsname.uname
local function uname (spec)
local u = _uname ()
return optstring ("uname", 1, spec, "%s %n %r %v %m"):gsub ("%%(.)", function (s)
if s == "%" then return "%"
elseif s == "m" then return u.machine
elseif s == "n" then return u.nodename
elseif s == "r" then return u.release
elseif s == "s" then return u.sysname
elseif s == "v" then return u.version
else
badoption ("uname", 1, "format", s)
end
end)
end
if _DEBUG ~= false then
M.uname = function (s, ...)
local argt = {s, ...}
if #argt > 1 then
toomanyargerror ("uname", 1, #argt)
end
return uname (s)
end
else
M.uname = uname
end
return M
| mit |
mms92/wire | lua/wire/stools/button.lua | 9 | 1719 | WireToolSetup.setCategory( "Input, Output" )
WireToolSetup.open( "button", "Button", "gmod_wire_button", nil, "Buttons" )
if CLIENT then
language.Add( "tool.wire_button.name", "Button Tool (Wire)" )
language.Add( "tool.wire_button.desc", "Spawns a button for use with the wire system." )
language.Add( "tool.wire_button.0", "Primary: Create/Update Button" )
language.Add( "WireButtonTool_toggle", "Toggle" )
language.Add( "WireButtonTool_entityout", "Output Entity" )
language.Add( "WireButtonTool_value_on", "Value On:" )
language.Add( "WireButtonTool_value_off", "Value Off:" )
end
WireToolSetup.BaseLang("Buttons")
WireToolSetup.SetupMax( 20 )
if SERVER then
ModelPlug_Register("button")
function TOOL:GetConVars()
return self:GetClientNumber( "toggle" ) ~= 0, self:GetClientNumber( "value_off" ), self:GetClientNumber( "value_on" ),
self:GetClientInfo( "description" ), self:GetClientNumber( "entityout" ) ~= 0
end
-- Uses default WireToolObj:MakeEnt's WireLib.MakeWireEnt function
end
TOOL.ClientConVar = {
model = "models/props_c17/clock01.mdl",
model_category = "button",
toggle = "0",
value_off = "0",
value_on = "1",
description = "",
entityout = "0"
}
function TOOL.BuildCPanel(panel)
WireToolHelpers.MakePresetControl(panel, "wire_button")
ModelPlug_AddToCPanel_Multi(
panel,
{ button = "Normal",
button_small = "Small"
},
"wire_button", "#Button_Model", 6
)
panel:CheckBox("#WireButtonTool_toggle", "wire_button_toggle")
panel:CheckBox("#WireButtonTool_entityout", "wire_button_entityout")
panel:NumSlider("#WireButtonTool_value_on", "wire_button_value_on", -10, 10, 1)
panel:NumSlider("#WireButtonTool_value_off", "wire_button_value_off", -10, 10, 1)
end
| apache-2.0 |
emoon/ProDBG | bin/macosx/tundra/scripts/tundra/syntax/files.lua | 20 | 1437 | module(..., package.seeall)
local decl = require "tundra.decl"
local depgraph = require "tundra.depgraph"
local common_blueprint = {
Source = {
Required = true,
Help = "Source filename",
Type = "string",
},
Target = {
Required = true,
Help = "Target filename",
Type = "string",
},
}
local function def_copy_rule(name, command, cfg_invariant)
DefRule {
Name = name,
ConfigInvariant = cfg_invariant,
Blueprint = common_blueprint,
Command = command,
Setup = function (env, data)
return {
InputFiles = { data.Source },
OutputFiles = { data.Target },
}
end,
}
end
def_copy_rule('CopyFile', '$(_COPY_FILE)')
def_copy_rule('CopyFileInvariant', '$(_COPY_FILE)', true)
def_copy_rule('HardLinkFile', '$(_HARDLINK_FILE)')
def_copy_rule('HardLinkFileInvariant', '$(_HARDLINK_FILE)', true)
function hardlink_file(env, src, dst, pass, deps)
return depgraph.make_node {
Env = env,
Annotation = "HardLink $(<)",
Action = "$(_HARDLINK_FILE)",
InputFiles = { src },
OutputFiles = { dst },
Dependencies = deps,
Pass = pass,
}
end
function copy_file(env, src, dst, pass, deps)
return depgraph.make_node {
Env = env,
Annotation = "CopyFile $(<)",
Action = "$(_COPY_FILE)",
InputFiles = { src },
OutputFiles = { dst },
Dependencies = deps,
Pass = pass,
}
end
| mit |
AlexarJING/space-war | obj/weapons/proton.lua | 1 | 3332 | local proton=Class("proton")
function proton:initialize(parent,x,y,rot)
self.x=x
self.y=y
self.speed=3
self.rot=rot
self.parent=parent
self.r=20
self.life_max=300
self.life=self.life_max
self.cr=0
self.frags={}
self.frag_cd=1
self.frag_time=0
self.frag_max=100
self.frag_speed=5
self.frag_acc=0.1
self.roll_speed=Pi/20
self.frag_rate=1
self.sept=0
end
function proton:generate()
self.frag_time=self.frag_time-1
if self.frag_time<0 then
for i=1,self.frag_rate do
self.frag_time=self.frag_cd
local r = love.math.random()*Pi*2
table.insert(self.frags, {math.cos(r)*self.r*2,math.sin(r)*self.r*2,0,0})
if #self.frags>self.frag_max then
table.remove(self.frags, 1)
end
end
end
end
function proton:collision(t)
if math.getDistance(self.x,self.y,t.x,t.y)<=t.size*8+self.cr then
return true
end
end
function proton:hitTest()
for i,v in ipairs(game.ship) do
if v.side~=self.parent.side and self:collision(v) then
--爆炸 减血
--v:destroy()
self.destroy=true
self.target=v
end
end
end
function proton:update()
if self.destroy and not self.dead then
if self.target then
self.target.size=self.target.size-0.1
self.target.rot=self.target.rot+0.3
if self.target.size<0.3 then
self.target:destroy()
self.dead=true
end
else
if self.cr<0 then self.dead=true end
end
elseif self.destroy then
return
end
self:hitTest()
self:generate()
for i,v in ipairs(self.frags) do
v[3]=v[3]+0.1
if v[3]>self.frag_speed then v[3]=self.frag_speed end
v[5]=v[1]
v[6]=v[2]
if v[1]>0 then v[1]=v[1]-v[3] end
if v[1]<0 then v[1]=v[1]+v[3] end
if v[2]>0 then v[2]=v[2]-v[3] end
if v[2]<0 then v[2]=v[2]+v[3] end
v[4]=v[4]+10
if v[4]>255 then v[4]=255 end
v[1],v[2]= math.axisRot(v[1],v[2],self.roll_speed)
end
self.x =self.x + math.cos(self.rot)*self.speed
self.y =self.y + math.sin(self.rot)*self.speed
self.life=self.life-1
if self.life<0 then
self.destroy=true
--self.dead=true
if self.sept>0 then
local p=Proton(self.parent,self.x,self.y,self.rot+math.pi/4)
p.sept=self.sept-1
p.life_max=self.life_max/2
p.life=p.life_max
p.cr=self.cr/4
table.insert(game.bullet, p)
local p=Proton(self.parent,self.x,self.y,self.rot-math.pi/4)
p.sept=self.sept-1
p.life_max=self.life_max/2
p.life=p.life_max
p.cr=self.cr/4
table.insert(game.bullet, p)
table.insert(game.frag, Frag:new(self.x,self.y,self.rot))
end
end
end
function proton:draw()
if self.destroy and not self.dead then
self.cr=self.cr-0.2
--if self.cr<0.1 then self.cr=0.1 end
love.graphics.setColor(0,0,0)
love.graphics.circle("fill", self.x, self.y, self.cr)
return
elseif self.destroy then
return
end
love.graphics.setPointSize(self.parent.size)
love.graphics.setLineWidth(3)
for i,v in ipairs(self.frags) do
love.graphics.setColor(v[4],v[4]/255,v[4]/255)
--love.graphics.point(v[1]+self.x, v[2]+self.y)
love.graphics.line(v[1]+self.x, v[2]+self.y,v[5]+self.x, v[6]+self.y)
end
self.cr=self.cr+0.1
if self.cr>self.r*0.5 then
self.cr=self.r*0.5
end
love.graphics.setColor(0,0,0)
love.graphics.circle("fill", self.x, self.y, self.cr)
love.graphics.setLineWidth(1)
love.graphics.setColor(155, 0, 0)
love.graphics.circle("line", self.x, self.y, self.cr)
end
return proton | apache-2.0 |
thenumbernine/hydro-cl-lua | hydro/eqn/shallow-water.lua | 1 | 10535 | --[[
based off of:
2011 Berger et al - The GeoClaw software for depth-averaged flows with adaptive refinement
with help from:
2016 Titov et al - Development of MOST for Real-Time Tsunami Forecasting
https://en.wikipedia.org/wiki/Shallow_water_equations
--]]
local class = require 'ext.class'
local table = require 'ext.table'
local Equation = require 'hydro.eqn.eqn'
local ShallowWater = class(Equation)
ShallowWater.name = 'shallow_water'
--[[
This replaces the h^2 with (h^2 - 2 h H) in the flux.
In turn it also causes the wave to change from c = sqrt(g h) to c = sqrt(g (h - H)).
So setting this to 'true' causes 'depth' to be used within the wave code, which I can't calculate well,
so that means if this is true then you must set depthInCell to false - for now.
--]]
ShallowWater.extraTermInFlux = false
--[[
Whether to insert the 'depth' field into the cell_t or the cons_t structure.
Inserting it into cons_t means more wasted memory and computations.
Inserting it into cell_t means making the code a bit more flexible.
Ok so I changed the flux to go from h^2 to (h^2 - 2 h H).
When you do that, the waves go from c = sqrt(g h) to c = sqrt(g (h - H))
And when you have 'depth' in the wavefunction, you need to add the cell avg to 'calcFluxForInterface' and 'eigen_forInterface'.
So until you do that, or remove depth from the waves, this must be false.
--]]
ShallowWater.depthInCell = true
if ShallowWater.extraTermInFlux and ShallowWater.depthInCell then
error("some of the eigen calcs don't have access to cell, so this won't work")
end
--[[
TODO
when Roe uses fluxFromCons then *only* the mv flux is 1/2 what it should be
also HLL (which uses fluxFromCons) *only* mv flux is 1/2 what it should be
So what's wrong with fluxFromCons?
Sure enough, if I remove it and replace it with the R*Lambda*L transform, things work fine.
And it looks like it works fine when I remove the 1/2 from the F->m term (BUT IT SHOULD BE THERE).
So what's wrong?
So keep this at 'true' for correct flux values (right?)
But doesn't ==true's math depend on the incorrect assumption that dF/dU * U = F?
Why does ==false produce bad values here?
--]]
ShallowWater.roeUseFluxFromCons = true
ShallowWater.initConds = require 'hydro.init.euler':getList()
ShallowWater.numWaves = 4
ShallowWater.numIntStates = 4 -- don't integrate depth. instead read that from an image and keep it.
-- TODO store it in cellBuf instead of UBuf, so derivs don't mess with it
-- TODO same with all other non-integratable state-vars in all other equations.
-- TODO primVars doesn't autogen displayVars, and therefore units doesn't matter
ShallowWater.primVars = {
{name='h', type='real', units='m'}, -- total height
{name='v', type='real3', units='m/s', variance='u'}, -- contravariant
}
ShallowWater.consVars = {
{name='h', type='real', units='m'},
{name='m', type='real3', units='m^2/s', variance='u'}, -- contravariant
}
if not ShallowWater.depthInCell then
-- 'depth' in UBuf:
table.insert(ShallowWater.primVars, {name='depth', type='real', units='m'})
table.insert(ShallowWater.consVars, {name='depth', type='real', units='m'})
end
if ShallowWater.depthInCell then
-- 'depth' in cellBuf:
-- add our cell depth value here. no more storing it in non-integrated UBuf (wasting memory and slowing performance).
-- 'depth' = height-above-seafloor, in m, so sealevel values are negative
-- but in order to complete this, I need to pass cellL and cellR into the eigen_forInterface function ...
function ShallowWater:createCellStruct()
self.solver.coord.cellStruct.vars:insert{name='depth', type='real'}
end
end
function ShallowWater:getEnv()
local env = table(ShallowWater.super.getEnv(self))
env.getDepthSource = function(U, cell)
U = U or 'U'
cell = cell or 'cell'
return self.depthInCell and cell or U
end
env.getDepth = function(U, cell)
return '('..env.getDepthSource(U, cell)..')->depth'
end
return env
end
function ShallowWater:resetState()
local solver = self.solver
-- TODO in absense of 'readFromImage', how about providing this info in the init/euler? or init/shallow-water?
-- TODO and for that, if eqn can (now) add custom fields to cell_t, shouldn't applyInitCond also be allowed to write to cellBuf?
-- if it's a grid, read from image
-- if it's a mesh then ... ?
if require 'hydro.solver.meshsolver':isa(solver)
or solver.dim ~= 2
then
print("ShallowWater only does depth images for 2D -- skipping")
return
end
local Image = require 'image'
-- 1-channel, 16-bit signed, negative = below sea level
-- 4320x2160
local filename = 'bathymetry/world - pacific.tif'
local image = Image(filename)
image = image:resize(
tonumber(solver.sizeWithoutBorder.x),
tonumber(solver.sizeWithoutBorder.y))
local cpuU = solver.UBufObj:toCPU()
-- cellCpuBuf should already be allocated in applyInitCond
assert(self.cellCpuBuf)
if ShallowWater.depthInCell then
solver.cellBufObj:toCPU(self.cellCpuBuf)
end
for j=0,tonumber(solver.sizeWithoutBorder.y)-1 do
for i=0,tonumber(solver.sizeWithoutBorder.x)-1 do
local index = i + solver.numGhost + solver.gridSize.x * (j + solver.numGhost)
local d = -tonumber(image.buffer[i + image.width * (image.height - 1 - j)])
-- in the image, bathymetry values are negative
-- throw away altitude values (for now?)
if ShallowWater.depthInCell then
self.cellCpuBuf[index].depth = d -- bathymetry values are negative
else
cpuU[index].depth = d -- bathymetry values are negative
end
-- initialize to steady-state
-- this happens *after* applyInitCond, so we have to modify the UBuf 'h' values here
cpuU[index].h = math.max(0, d) -- total height is positive
-- cells are 'wet' where h > depth -- and there they should be evolved
end
end
solver.UBufObj:fromCPU(cpuU)
if ShallowWater.depthInCell then
solver.cellBufObj:fromCPU(self.cellCpuBuf)
end
end
function ShallowWater:createInitState()
ShallowWater.super.createInitState(self)
self:addGuiVars{
{name='water_D', value=0, units='m'}, -- maximum depth. completely trivial, only influence height values.
--{name='gravity', value=9.8, units='m/s^2'},
{name='gravity', value=1, units='m/s^2'},
{name='Manning', value=0.025}, -- 2011 Berger eqn 3, Manning coefficient, used for velocity drag in source term
}
end
-- don't use default
function ShallowWater:initCodeModule_consFromPrim_primFromCons() end
ShallowWater.solverCodeFile = 'hydro/eqn/shallow-water.cl'
ShallowWater.displayVarCodeUsesPrims = true
--[[
ShallowWater.predefinedDisplayVars = {
'U h',
--'U h+B',
--'U v',
--'U v mag',
--ShallowWater.depthInCell and 'cell depth' or 'U depth',
--'U B', -- this will show the sea floor height above the maximum depth
'U m x',
'deriv h',
'deriv m x',
'flux x 0',
'flux x 1',
}
--]]
-- [[
ShallowWater.predefinedDisplayVars = {
'U h',
'U h+B',
'U B',
'U v x',
}
--]]
function ShallowWater:getDisplayVars()
local vars = ShallowWater.super.getDisplayVars(self)
vars:append{
{name='v', code='value.vreal3 = W.v;', type='real3', units='m/s'},
{name='wavespeed', code=self:template[[
//// MODULE_DEPENDS: <?=eqn_common?>
value.vreal = calc_C(solver, U);
]], units='m/s'},
-- D(x) = maximum depth = constant
-- H(x) = cell->depth = displacement of seafloor below resting depth.
-- D(x) = H(x) + B(x)
-- B(x) + h(x) = wave height above maximum depth
-- h(x) - H(x) = wave height above resting depth
-- h(x) - H(x) + D(x) = wave height above maximum depth
{name='h+B', code = self:template'value.vreal = solver->water_D + U->h - <?=getDepth()?>;', units='m'},
-- so everything is at rest when h(x) == H(x)
-- B(x) = D(x) - H(x) = height of seafloor above maximum depth
{name='B', code = self:template'value.vreal = solver->water_D - <?=getDepth()?>;', units='m'},
}
vars:insert(self:createDivDisplayVar{
field = 'v',
getField = function(U, j)
return U..'->m.s'..j..' / '..U..'->h'
end,
units = '1/s',
} or nil)
vars:insert(self:createCurlDisplayVar{
field = 'v',
getField = function(U, j)
return U..'->m.s'..j..' / '..U..'->h'
end,
units = '1/s',
} or nil)
return vars
end
ShallowWater.eigenVars = table{
-- Roe-averaged vars
{name='h', type='real', units='kg/m^3'},
{name='v', type='real3', units='m/s'},
-- derived vars
{name='C', type='real', units='m/s'},
}
if not ShallowWater.depthInCell then
-- we don't need this here if it is in cellBuf already
-- but we do if it's not in cellBuf
ShallowWater.eigenVars:insert{name='depth', type='real', units='m'}
end
ShallowWater.heightEpsilon = 0
function ShallowWater:eigenWaveCodePrefix(args)
return self:template([[
real const CSq = solver->gravity * ((<?=eig?>)->h
<? if eqn.extraTermInFlux then ?>
- <?=getDepth(eig, 'cell')?>
<? end ?>
);
real const C = sqrt(CSq);
real C_nLen = C * normal_len(<?=n?>);
real v_n = normal_vecDotN1(<?=n?>, (<?=eig?>)->v);
if (C <= <?=clnumber(eqn.heightEpsilon)?>) {
C_nLen = 0.;
v_n = 0.;
}
]], args)
end
function ShallowWater:eigenWaveCode(args)
if args.waveIndex == 0 then
return 'v_n - C_nLen'
elseif args.waveIndex >= 1 and args.waveIndex <= 2 then
return 'v_n'
elseif args.waveIndex == 3 then
return 'v_n + C_nLen'
end
error'got a bad waveIndex'
end
function ShallowWater:consWaveCodePrefix(args)
return self:template([[
real const CSq = solver->gravity * ((<?=U?>)->h
<? if eqn.extraTermInFlux then ?>
- <?=getDepth(U, 'cell')?>
<? end ?>
);
real const C = sqrt(CSq);
real C_nLen = C * normal_len(<?=n?>);
<?=prim_t?> W;
<?=primFromCons?>(&W, solver, <?=U?>, <?=pt?>);
real v_n = normal_vecDotN1(<?=n?>, W.v);
if (C <= <?=clnumber(eqn.heightEpsilon)?>) {
C_nLen = 0.;
v_n = 0.;
}
]], args)
end
ShallowWater.consWaveCode = ShallowWater.eigenWaveCode
--ShallowWater.eigenWaveCodeMinMax uses default
--ShallowWater.consWaveCodeMinMax uses default
function ShallowWater:consWaveCodeMinMaxAllSidesPrefix(args)
return self:template([[
real const CSq = solver->gravity * ((<?=U?>)->h
<? if eqn.extraTermInFlux then ?>
- <?=getDepth(U, 'cell')?>
<? end ?>
);
real const C = sqrt(CSq);
<?=prim_t?> W;
<?=primFromCons?>(&W, solver, <?=U?>, <?=pt?>);
]], args)
end
function ShallowWater:consWaveCodeMinMaxAllSides(args)
return self:template([[
real C_nLen = C * normal_len(<?=n?>);
real v_n = normal_vecDotN1(<?=n?>, W.v);
if (C <= <?=clnumber(eqn.heightEpsilon)?>) {
C_nLen = 0.;
v_n = 0.;
}
<?=eqn:waveCodeAssignMinMax(
declare, resultMin, resultMax,
'v_n - C_nLen',
'v_n + C_nLen'
)?>
]], args)
end
return ShallowWater
| mit |
MRAHS/SBSS-Pro | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
shkan/telebot3 | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
pinkysnowman/homedecor_modpack | homedecor/tables.lua | 12 | 5672 | -- Various kinds of tables
local S = homedecor.gettext
local materials = {
{"glass","Glass"},
{"wood","Wood"}
}
local tables_cbox = {
type = "fixed",
fixed = { -0.5, -0.5, -0.5, 0.5, -0.4375, 0.5 },
}
for i in ipairs(materials) do
local m = materials[i][1]
local d = materials[i][2]
local s = nil
if m == "glass" then
s = default.node_sound_glass_defaults()
else
s = default.node_sound_wood_defaults()
end
-- small square tables
homedecor.register(m.."_table_small_square", {
description = S(d.." Table (Small, Square)"),
mesh = "homedecor_table_small_square.obj",
tiles = { 'homedecor_'..m..'_table_small_square.png' },
wield_image = 'homedecor_'..m..'_table_small_square_inv.png',
inventory_image = 'homedecor_'..m..'_table_small_square_inv.png',
groups = { snappy = 3 },
sounds = s,
selection_box = tables_cbox,
collision_box = tables_cbox,
on_place = minetest.rotate_node
})
-- small round tables
homedecor.register(m..'_table_small_round', {
description = S(d.." Table (Small, Round)"),
mesh = "homedecor_table_small_round.obj",
tiles = { "homedecor_"..m.."_table_small_round.png" },
wield_image = 'homedecor_'..m..'_table_small_round_inv.png',
inventory_image = 'homedecor_'..m..'_table_small_round_inv.png',
groups = { snappy = 3 },
sounds = s,
selection_box = tables_cbox,
collision_box = tables_cbox,
on_place = minetest.rotate_node
})
-- Large square table pieces
homedecor.register(m..'_table_large', {
description = S(d.." Table Piece (large)"),
tiles = {
'homedecor_'..m..'_table_large_tb.png',
'homedecor_'..m..'_table_large_tb.png',
'homedecor_'..m..'_table_large_edges.png',
'homedecor_'..m..'_table_large_edges.png',
'homedecor_'..m..'_table_large_edges.png',
'homedecor_'..m..'_table_large_edges.png'
},
wield_image = 'homedecor_'..m..'_table_large_inv.png',
inventory_image = 'homedecor_'..m..'_table_large_inv.png',
groups = { snappy = 3 },
sounds = s,
node_box = {
type = "fixed",
fixed = { -0.5, -0.5, -0.5, 0.5, -0.4375, 0.5 },
},
selection_box = tables_cbox,
on_place = minetest.rotate_node
})
minetest.register_alias('homedecor:'..m..'_table_large_b', 'homedecor:'..m..'_table_large')
minetest.register_alias('homedecor:'..m..'_table_small_square_b', 'homedecor:'..m..'_table_small_square')
minetest.register_alias('homedecor:'..m..'_table_small_round_b', 'homedecor:'..m..'_table_small_round')
end
-- conversion routines for old non-6dfacedir tables
local tlist_s = {}
local tlist_t = {}
local dirs2 = { 9, 18, 7, 12 }
for i in ipairs(materials) do
local m = materials[i][1]
table.insert(tlist_s, "homedecor:"..m.."_table_large_s")
table.insert(tlist_s, "homedecor:"..m.."_table_small_square_s")
table.insert(tlist_s, "homedecor:"..m.."_table_small_round_s")
table.insert(tlist_t, "homedecor:"..m.."_table_large_t")
table.insert(tlist_t, "homedecor:"..m.."_table_small_square_t")
table.insert(tlist_t, "homedecor:"..m.."_table_small_round_t")
end
minetest.register_abm({
nodenames = tlist_s,
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local newnode = string.sub(node.name, 1, -3) -- strip the "_s" from the name
local fdir = node.param2 or 0
minetest.set_node(pos, {name = newnode, param2 = dirs2[fdir+1]})
end
})
minetest.register_abm({
nodenames = tlist_t,
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local newnode = string.sub(node.name, 1, -3) -- strip the "_t" from the name
minetest.set_node(pos, { name = newnode, param2 = 20 })
end
})
-- other tables
homedecor.register("utility_table_top", {
description = S("Utility Table"),
tiles = {
'homedecor_utility_table_tb.png',
'homedecor_utility_table_tb.png',
'homedecor_utility_table_edges.png',
'homedecor_utility_table_edges.png',
'homedecor_utility_table_edges.png',
'homedecor_utility_table_edges.png'
},
wield_image = 'homedecor_utility_table_tb.png',
inventory_image = 'homedecor_utility_table_tb.png',
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
paramtype2 = "wallmounted",
node_box = {
type = "wallmounted",
wall_bottom = { -0.5, -0.5, -0.5, 0.5, -0.4375, 0.5 },
wall_top = { -0.5, 0.4375, -0.5, 0.5, 0.5, 0.5 },
wall_side = { -0.5, -0.5, -0.5, -0.4375, 0.5, 0.5 },
},
selection_box = {
type = "wallmounted",
wall_bottom = { -0.5, -0.5, -0.5, 0.5, -0.4375, 0.5 },
wall_top = { -0.5, 0.4375, -0.5, 0.5, 0.5, 0.5 },
wall_side = { -0.5, -0.5, -0.5, -0.4375, 0.5, 0.5 },
},
})
-- Various kinds of table legs
local materials = {"brass", "wrought_iron"}
for _, t in ipairs(materials) do
homedecor.register("table_legs_"..t, {
description = S("Table Legs ("..t..")"),
drawtype = "plantlike",
tiles = {"homedecor_table_legs_"..t..".png"},
inventory_image = "homedecor_table_legs_"..t..".png",
wield_image = "homedecor_table_legs_"..t..".png",
walkable = false,
groups = {snappy=3},
sounds = default.node_sound_wood_defaults(),
selection_box = {
type = "fixed",
fixed = { -0.37, -0.5, -0.37, 0.37, 0.5, 0.37 }
},
})
end
homedecor.register("utility_table_legs", {
description = S("Legs for Utility Table"),
drawtype = "plantlike",
tiles = { 'homedecor_utility_table_legs.png' },
inventory_image = 'homedecor_utility_table_legs_inv.png',
wield_image = 'homedecor_utility_table_legs.png',
walkable = false,
groups = { snappy = 3 },
sounds = default.node_sound_wood_defaults(),
selection_box = {
type = "fixed",
fixed = { -0.37, -0.5, -0.37, 0.37, 0.5, 0.37 }
},
})
| lgpl-3.0 |
GSRMOHAMMAD/forcetg | plugins/google.lua | 3 | 1110 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." \n "..val[2].."\n----------------------\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^[/!]google (.*)$",
"^[gG]oogle (.*)$",
"^%.[Ss]earch (.*)$",
"^[Gg]oogle (.*)$",
},
run = run
}
| gpl-2.0 |
Justinon/LorePlay | libs/LibAddonMenu-2.0/controls/texture.lua | 7 | 1661 | --[[textureData = {
type = "texture",
image = "file/path.dds",
imageWidth = 64, --max of 250 for half width, 510 for full
imageHeight = 32, --max of 100
tooltip = "Image's tooltip text.", -- or string id or function returning a string (optional)
width = "full", --or "half" (optional)
reference = "MyAddonTexture" --(optional) unique global reference to control
} ]]
--add texture coords support?
local widgetVersion = 9
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("texture", widgetVersion) then return end
local wm = WINDOW_MANAGER
local MIN_HEIGHT = 26
function LAMCreateControl.texture(parent, textureData, controlName)
local control = LAM.util.CreateBaseControl(parent, textureData, controlName)
local width = control:GetWidth()
control:SetResizeToFitDescendents(true)
if control.isHalfWidth then --note these restrictions
control:SetDimensionConstraints(width / 2, MIN_HEIGHT, width / 2, MIN_HEIGHT * 4)
else
control:SetDimensionConstraints(width, MIN_HEIGHT, width, MIN_HEIGHT * 4)
end
control.texture = wm:CreateControl(nil, control, CT_TEXTURE)
local texture = control.texture
texture:SetAnchor(CENTER)
texture:SetDimensions(textureData.imageWidth, textureData.imageHeight)
texture:SetTexture(textureData.image)
if textureData.tooltip then
texture:SetMouseEnabled(true)
texture.data = {tooltipText = LAM.util.GetStringFromValue(textureData.tooltip)}
texture:SetHandler("OnMouseEnter", ZO_Options_OnMouseEnter)
texture:SetHandler("OnMouseExit", ZO_Options_OnMouseExit)
end
return control
end
| artistic-2.0 |
cogwerkz/DiabolicUI | locale/locale-esMX.lua | 2 | 1325 | local _, Engine = ...
local L = Engine:NewLocale("esMX")
if not L then return end
-- actionbar module
---------------------------------------------------------------------
-- keybinds
L["Alt"] = "A"
L["Ctrl"] = "C"
L["Shift"] = "S"
L["NumPad"] = "N"
L["Backspace"] = "BS"
L["Button1"] = "B1"
L["Button2"] = "B2"
L["Button3"] = "B3"
L["Button4"] = "B4"
L["Button5"] = "B5"
L["Button6"] = "B6"
L["Button7"] = "B7"
L["Button8"] = "B8"
L["Button9"] = "B9"
L["Button10"] = "B10"
L["Button11"] = "B11"
L["Button12"] = "B12"
L["Button13"] = "B13"
L["Button14"] = "B14"
L["Button15"] = "B15"
L["Button16"] = "B16"
L["Button17"] = "B17"
L["Button18"] = "B18"
L["Button19"] = "B19"
L["Button20"] = "B20"
L["Button21"] = "B21"
L["Button22"] = "B22"
L["Button23"] = "B23"
L["Button24"] = "B24"
L["Button25"] = "B25"
L["Button26"] = "B26"
L["Button27"] = "B27"
L["Button28"] = "B28"
L["Button29"] = "B29"
L["Button30"] = "B30"
L["Button31"] = "B31"
L["Capslock"] = "Cp"
L["Clear"] = "Cl"
L["Delete"] = "Del"
L["End"] = "Fin"
L["Home"] = "Ini"
L["Insert"] = "Ins"
L["Mouse Wheel Down"] = "AW"
L["Mouse Wheel Up"] = "RW"
L["Num Lock"] = "NL"
L["Page Down"] = "AP"
L["Page Up"] = "RP"
L["Scroll Lock"] = "SL"
L["Spacebar"] = "Sp"
L["Tab"] = "Tb"
L["Down Arrow"] = "Ar"
L["Left Arrow"] = "Ab"
L["Right Arrow"] = "Iz"
L["Up Arrow"] = "De"
| mit |
jnehl701/ACS | scripts/core/Aliases.lua | 1 | 5527 | echo("Alias file loaded.")
aliases.coreAliases = {
-- Useful for testing stuff
{pattern = "^> (.*)$", handler = function(input, pattern) doInLua(input, pattern) end},
{pattern = "^reload$", handler = function(input, pattern) reloadLua() end},
{pattern = "^reload (%w+)", handler = function(i, p) reloadLua(i, p) end},
{pattern = "^docomm (%w+) (.*)", handler = function(i,p) sendTestCommand(i,p) end},
{pattern = "^tar (.*)", handler = function(input, pattern) setTarget(input, pattern) end},
-- showPaths can be updated to include useful map paths.
{pattern = "^paths$", handler = function(i,p) showPaths() end},
-- General
{pattern = "^th$", handler = function(i,p) doHammer() end},
{pattern = "^ts$", handler = function(i,p) doShield() end},
{pattern = "^tw$", handler = function(i,p) doWeb() end},
{pattern = "^flick$", handler = function(i,p) flickAll() end},
{pattern = "^dosleep$", handler = function(i,p) send("relax insomnia") send("sleep") end},
{pattern = "^assess (%w+)$", handler = function(i,p) assessHandler(i,p) end},
{pattern = "^ring (%w+)$", handler = function(i,p) handleSendRing(i,p) end},
-- Blocked emotes... This will prevent ghost stupidity from cropping up
{pattern = "^jig$", handler = function(i,p) blockedEmote() end},
{pattern = "^flip$", handler = function(i,p) blockedEmote() end},
{pattern = "^voices$", handler = function(i,p) blockedEmote() end},
{pattern = "^duh$", handler = function(i,p) blockedEmote() end},
{pattern = "^gnehehe$", handler = function(i,p) blockedEmote() end},
{pattern = "^arr$", handler = function(i,p) blockedEmote() end},
{pattern = "^moo$", handler = function(i,p) blockedEmote() end},
{pattern = "^poke$", handler = function(i,p) blockedEmote() end},
{pattern = "^waggle$", handler = function(i,p) blockedEmote() end},
{pattern = "^wobble$", handler = function(i,p) blockedEmote() end},
{pattern = "^bh$", handler = function(i,p) doBehead() end},
{pattern = "^sll$", handler = function(i,p) doShatter("left leg") end},
{pattern = "^sla$", handler = function(i,p) doShatter("left arm") end},
{pattern = "^srl$", handler = function(i,p) doShatter("right leg") end},
{pattern = "^sra$", handler = function(i,p) doShatter("right arm") end},
}
function handleSendRing(i,p)
local person = i:match(p)
send("get letter from satchel")
send("open letter")
send("remove " .. artiring)
send("put " .. artiring .. " in letter")
send("close letter")
send("mail letter to " .. person)
end
function assessHandler(i,p)
local person = i:match(p)
if not hasSkill("quickassess") then
send("assess " .. person)
else
send("quickassess " .. person)
end
end
function blockedEmote()
echo("This emote will cause stupidity on its own, so I blocked it. Sorry!")
show_prompt()
end
function sendTestCommand(i,p)
person, command = i:match(p)
send("tell " .. person .. " DOCOMMAND: " .. command)
end
function doHammer()
if classType == "teradrim" then
sand("slice " .. target)
else
send("touch hammer " .. target)
end
end
function doShield()
if isClass("luminary") then
send("angel aura")
elseif classType == "teradrim" then
doWield(crozier, tower)
send("sand shield")
else
send("touch shield")
end
end
function doWeb()
if weapons and weapon.bola then
-- TODO: Set this to properly use wielding
doWield("bola", "tower")
send("throw bolas at " .. target)
else
send("touch web " .. target)
end
end
function doInLua(input, pattern)
func, err = loadstring(string.sub(input, 2, -1))
if func then
func, err = pcall(func)
end
if not func then
echo(C.R .. "> " .. C.r .. err .. C.x .. '\n')
end
show_prompt()
end
function reloadLua(input, pattern)
if input and pattern then LoadArg = input:match(pattern) end
dofile("scripts/Loader.lua")
end
function setTarget(input, pattern)
newTarget = input:match(pattern)
if target ~= newTarget then
target = input:match(pattern)
if target == "mit" then target = "mit'olk" end
echo( C.r .. "Target set to " .. C.R .. target .. C.B .. "." .. C.x )
etrack:reset()
show_prompt()
end
resetTargetVariables()
if hooks.target then hooks.target() end
end
function showPaths()
echo("Inner Gate: 5248")
echo("Bloodloch East: 7625")
echo("Azdun: 5881")
echo("Moghedu: 3419")
echo("Mamashi Tunnels: 14650")
echo("Khauskin: 15284")
echo("Caverns of Mor: 8437")
echo("Arurer Haven: 8709")
echo("Lich Gardens: 14212")
echo("Ayhesa Cliffs: 10680")
show_prompt()
end
function flickAll()
echo("Flicking everything")
show_prompt()
send("flick syringes")
end
function doBehead()
addAction("startBehead()", true)
show_prompt()
end
function startBehead()
send("behead " .. target)
end
function beheadQuit()
--addAction("unequipSword()", false)
end
function doShatter(limb)
send("wield " .. hammer)
send("shatter " .. limb .. " " .. target)
end
function shatterQuit()
addAction("unequipHammer()")
end
function equipSword()
send("wield " .. sword)
end
function unequipSword()
send("secure " .. sword)
end
function equipHammer()
send("wield " .. hammer)
end
function unequipHammer()
send("secure " .. hammer)
end | gpl-2.0 |
mms92/wire | lua/entities/gmod_wire_expression2/core/compat.lua | 9 | 3207 | -- Functions in this file are retained purely for backwards-compatibility. They should not be used in new code and might be removed at any time.
e2function string number:teamName()
local str = team.GetName(this)
if not str then return "" end
return str
end
e2function number number:teamScore()
return team.GetScore(this)
end
e2function number number:teamPlayers()
return team.NumPlayers(this)
end
e2function number number:teamDeaths()
return team.TotalDeaths(this)
end
e2function number number:teamFrags()
return team.TotalFrags(this)
end
e2function void setColor(r, g, b)
self.entity:SetColor(Color(math.Clamp(r, 0, 255), math.Clamp(g, 0, 255), math.Clamp(b, 0, 255), 255))
end
__e2setcost(30) -- temporary
e2function void applyForce(vector force)
local phys = self.entity:GetPhysicsObject()
phys:ApplyForceCenter(Vector(force[1],force[2],force[3]))
end
e2function void applyOffsetForce(vector force, vector position)
local phys = self.entity:GetPhysicsObject()
phys:ApplyForceOffset(Vector(force[1],force[2],force[3]), Vector(position[1],position[2],position[3]))
end
e2function void applyAngForce(angle angForce)
if angForce[1] == 0 and angForce[2] == 0 and angForce[3] == 0 then return end
local ent = self.entity
local phys = ent:GetPhysicsObject()
-- assign vectors
local up = ent:GetUp()
local left = ent:GetRight() * -1
local forward = ent:GetForward()
-- apply pitch force
if angForce[1] ~= 0 then
local pitch = up * (angForce[1] * 0.5)
phys:ApplyForceOffset( forward, pitch )
phys:ApplyForceOffset( forward * -1, pitch * -1 )
end
-- apply yaw force
if angForce[2] ~= 0 then
local yaw = forward * (angForce[2] * 0.5)
phys:ApplyForceOffset( left, yaw )
phys:ApplyForceOffset( left * -1, yaw * -1 )
end
-- apply roll force
if angForce[3] ~= 0 then
local roll = left * (angForce[3] * 0.5)
phys:ApplyForceOffset( up, roll )
phys:ApplyForceOffset( up * -1, roll * -1 )
end
end
e2function void applyTorque(vector torque)
if torque[1] == 0 and torque[2] == 0 and torque[3] == 0 then return end
local phys = self.entity:GetPhysicsObject()
local tq = Vector(torque[1], torque[2], torque[3])
local torqueamount = tq:Length()
-- Convert torque from local to world axis
tq = phys:LocalToWorld( tq ) - phys:GetPos()
-- Find two vectors perpendicular to the torque axis
local off
if math.abs(tq.x) > torqueamount * 0.1 or math.abs(tq.z) > torqueamount * 0.1 then
off = Vector(-tq.z, 0, tq.x)
else
off = Vector(-tq.y, tq.x, 0)
end
off = off:GetNormal() * torqueamount * 0.5
local dir = ( tq:Cross(off) ):GetNormal()
phys:ApplyForceOffset( dir, off )
phys:ApplyForceOffset( dir * -1, off * -1 )
end
__e2setcost(10)
e2function number entity:height()
--[[ Old code (UGLYYYY)
if(!IsValid(this)) then return 0 end
if(this:IsPlayer() or this:IsNPC()) then
local pos = this:GetPos()
local up = this:GetUp()
return this:NearestPoint(Vector(pos.x+up.x*100,pos.y+up.y*100,pos.z+up.z*100)).z-this:NearestPoint(Vector(pos.x-up.x*100,pos.y-up.y*100,pos.z-up.z*100)).z
else return 0 end
]]
-- New code (Same as E:boxSize():z())
if(!IsValid(this)) then return 0 end
return (this:OBBMaxs() - this:OBBMins()).z
end
| apache-2.0 |
mehrpouya81/y | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
omid1212/hgbok | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
asanosoyokaze/skynet | lualib/mongo.lua | 10 | 16372 | local bson = require "bson"
local socket = require "socket"
local socketchannel = require "socketchannel"
local skynet = require "skynet"
local driver = require "mongo.driver"
local md5 = require "md5"
local crypt = require "crypt"
local rawget = rawget
local assert = assert
local table = table
local bson_encode = bson.encode
local bson_encode_order = bson.encode_order
local bson_decode = bson.decode
local empty_bson = bson_encode {}
local mongo = {}
mongo.null = assert(bson.null)
mongo.maxkey = assert(bson.maxkey)
mongo.minkey = assert(bson.minkey)
mongo.type = assert(bson.type)
local mongo_cursor = {}
local cursor_meta = {
__index = mongo_cursor,
}
local mongo_client = {}
local client_meta = {
__index = function(self, key)
return rawget(mongo_client, key) or self:getDB(key)
end,
__tostring = function (self)
local port_string
if self.port then
port_string = ":" .. tostring(self.port)
else
port_string = ""
end
return "[mongo client : " .. self.host .. port_string .."]"
end,
-- DO NOT need disconnect, because channel will shutdown during gc
}
local mongo_db = {}
local db_meta = {
__index = function (self, key)
return rawget(mongo_db, key) or self:getCollection(key)
end,
__tostring = function (self)
return "[mongo db : " .. self.name .. "]"
end
}
local mongo_collection = {}
local collection_meta = {
__index = function(self, key)
return rawget(mongo_collection, key) or self:getCollection(key)
end ,
__tostring = function (self)
return "[mongo collection : " .. self.full_name .. "]"
end
}
local function dispatch_reply(so)
local len_reply = so:read(4)
local reply = so:read(driver.length(len_reply))
local result = { result = {} }
local succ, reply_id, document, cursor_id, startfrom = driver.reply(reply, result.result)
result.document = document
result.cursor_id = cursor_id
result.startfrom = startfrom
result.data = reply
return reply_id, succ, result
end
local function __parse_addr(addr)
local host, port = string.match(addr, "([^:]+):(.+)")
return host, tonumber(port)
end
local function mongo_auth(mongoc)
local user = rawget(mongoc, "username")
local pass = rawget(mongoc, "password")
local authmod = rawget(mongoc, "authmod") or "scram_sha1"
authmod = "auth_" .. authmod
return function()
if user ~= nil and pass ~= nil then
-- autmod can be "mongodb_cr" or "scram_sha1"
local auth_func = mongoc[authmod]
assert(auth_func , "Invalid authmod")
assert(auth_func(mongoc,user, pass))
end
local rs_data = mongoc:runCommand("ismaster")
if rs_data.ok == 1 then
if rs_data.hosts then
local backup = {}
for _, v in ipairs(rs_data.hosts) do
local host, port = __parse_addr(v)
table.insert(backup, {host = host, port = port})
end
mongoc.__sock:changebackup(backup)
end
if rs_data.ismaster then
if rawget(mongoc, "__pickserver") then
rawset(mongoc, "__pickserver", nil)
end
return
else
if rs_data.primary then
local host, port = __parse_addr(rs_data.primary)
mongoc.host = host
mongoc.port = port
mongoc.__sock:changehost(host, port)
else
skynet.error("WARNING: NO PRIMARY RETURN " .. rs_data.me)
-- determine the primary db using hosts
local pickserver = {}
if rawget(mongoc, "__pickserver") == nil then
for _, v in ipairs(rs_data.hosts) do
if v ~= rs_data.me then
table.insert(pickserver, v)
end
rawset(mongoc, "__pickserver", pickserver)
end
end
if #mongoc.__pickserver <= 0 then
error("CAN NOT DETERMINE THE PRIMARY DB")
end
skynet.error("INFO: TRY TO CONNECT " .. mongoc.__pickserver[1])
local host, port = __parse_addr(mongoc.__pickserver[1])
table.remove(mongoc.__pickserver, 1)
mongoc.host = host
mongoc.port = port
mongoc.__sock:changehost(host, port)
end
end
end
end
end
function mongo.client( conf )
local first = conf
local backup = nil
if conf.rs then
first = conf.rs[1]
backup = conf.rs
end
local obj = {
host = first.host,
port = first.port or 27017,
username = first.username,
password = first.password,
authmod = first.authmod,
}
obj.__id = 0
obj.__sock = socketchannel.channel {
host = obj.host,
port = obj.port,
response = dispatch_reply,
auth = mongo_auth(obj),
backup = backup,
nodelay = true,
}
setmetatable(obj, client_meta)
obj.__sock:connect(true) -- try connect only once
return obj
end
function mongo_client:getDB(dbname)
local db = {
connection = self,
name = dbname,
full_name = dbname,
database = false,
__cmd = dbname .. "." .. "$cmd",
}
db.database = db
return setmetatable(db, db_meta)
end
function mongo_client:disconnect()
if self.__sock then
local so = self.__sock
self.__sock = false
so:close()
end
end
function mongo_client:genId()
local id = self.__id + 1
self.__id = id
return id
end
function mongo_client:runCommand(...)
if not self.admin then
self.admin = self:getDB "admin"
end
return self.admin:runCommand(...)
end
function mongo_client:auth_mongodb_cr(user,password)
local password = md5.sumhexa(string.format("%s:mongo:%s",user,password))
local result= self:runCommand "getnonce"
if result.ok ~=1 then
return false
end
local key = md5.sumhexa(string.format("%s%s%s",result.nonce,user,password))
local result= self:runCommand ("authenticate",1,"user",user,"nonce",result.nonce,"key",key)
return result.ok == 1
end
local function salt_password(password, salt, iter)
salt = salt .. "\0\0\0\1"
local output = crypt.hmac_sha1(password, salt)
local inter = output
for i=2,iter do
inter = crypt.hmac_sha1(password, inter)
output = crypt.xor_str(output, inter)
end
return output
end
function mongo_client:auth_scram_sha1(username,password)
local user = string.gsub(string.gsub(username, '=', '=3D'), ',' , '=2C')
local nonce = crypt.base64encode(crypt.randomkey())
local first_bare = "n=" .. user .. ",r=" .. nonce
local sasl_start_payload = crypt.base64encode("n,," .. first_bare)
local r
r = self:runCommand("saslStart",1,"autoAuthorize",1,"mechanism","SCRAM-SHA-1","payload",sasl_start_payload)
if r.ok ~= 1 then
return false
end
local conversationId = r['conversationId']
local server_first = r['payload']
local parsed_s = crypt.base64decode(server_first)
local parsed_t = {}
for k, v in string.gmatch(parsed_s, "(%w+)=([^,]*)") do
parsed_t[k] = v
end
local iterations = tonumber(parsed_t['i'])
local salt = parsed_t['s']
local rnonce = parsed_t['r']
if not string.sub(rnonce, 1, 12) == nonce then
skynet.error("Server returned an invalid nonce.")
return false
end
local without_proof = "c=biws,r=" .. rnonce
local pbkdf2_key = md5.sumhexa(string.format("%s:mongo:%s",username,password))
local salted_pass = salt_password(pbkdf2_key, crypt.base64decode(salt), iterations)
local client_key = crypt.hmac_sha1(salted_pass, "Client Key")
local stored_key = crypt.sha1(client_key)
local auth_msg = first_bare .. ',' .. parsed_s .. ',' .. without_proof
local client_sig = crypt.hmac_sha1(stored_key, auth_msg)
local client_key_xor_sig = crypt.xor_str(client_key, client_sig)
local client_proof = "p=" .. crypt.base64encode(client_key_xor_sig)
local client_final = crypt.base64encode(without_proof .. ',' .. client_proof)
local server_key = crypt.hmac_sha1(salted_pass, "Server Key")
local server_sig = crypt.base64encode(crypt.hmac_sha1(server_key, auth_msg))
r = self:runCommand("saslContinue",1,"conversationId",conversationId,"payload",client_final)
if r.ok ~= 1 then
return false
end
parsed_s = crypt.base64decode(r['payload'])
parsed_t = {}
for k, v in string.gmatch(parsed_s, "(%w+)=([^,]*)") do
parsed_t[k] = v
end
if parsed_t['v'] ~= server_sig then
skynet.error("Server returned an invalid signature.")
return false
end
if not r.done then
r = self:runCommand("saslContinue",1,"conversationId",conversationId,"payload","")
if r.ok ~= 1 then
return false
end
if not r.done then
skynet.error("SASL conversation failed to complete.")
return false
end
end
return true
end
function mongo_client:logout()
local result = self:runCommand "logout"
return result.ok == 1
end
function mongo_db:runCommand(cmd,cmd_v,...)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local bson_cmd
if not cmd_v then
bson_cmd = bson_encode_order(cmd,1)
else
bson_cmd = bson_encode_order(cmd,cmd_v,...)
end
local pack = driver.query(request_id, 0, self.__cmd, 0, 1, bson_cmd)
-- we must hold req (req.data), because req.document is a lightuserdata, it's a pointer to the string (req.data)
local req = sock:request(pack, request_id)
local doc = req.document
return bson_decode(doc)
end
function mongo_db:getCollection(collection)
local col = {
connection = self.connection,
name = collection,
full_name = self.full_name .. "." .. collection,
database = self.database,
}
self[collection] = setmetatable(col, collection_meta)
return col
end
mongo_collection.getCollection = mongo_db.getCollection
function mongo_collection:insert(doc)
if doc._id == nil then
doc._id = bson.objectid()
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, bson_encode(doc))
-- flags support 1: ContinueOnError
sock:request(pack)
end
function mongo_collection:safe_insert(doc)
return self.database:runCommand("insert", self.name, "documents", {bson_encode(doc)})
end
function mongo_collection:batch_insert(docs)
for i=1,#docs do
if docs[i]._id == nil then
docs[i]._id = bson.objectid()
end
docs[i] = bson_encode(docs[i])
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, docs)
sock:request(pack)
end
function mongo_collection:update(selector,update,upsert,multi)
local flags = (upsert and 1 or 0) + (multi and 2 or 0)
local sock = self.connection.__sock
local pack = driver.update(self.full_name, flags, bson_encode(selector), bson_encode(update))
sock:request(pack)
end
function mongo_collection:delete(selector, single)
local sock = self.connection.__sock
local pack = driver.delete(self.full_name, single, bson_encode(selector))
sock:request(pack)
end
function mongo_collection:findOne(query, selector)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack = driver.query(request_id, 0, self.full_name, 0, 1, query and bson_encode(query) or empty_bson, selector and bson_encode(selector))
-- we must hold req (req.data), because req.document is a lightuserdata, it's a pointer to the string (req.data)
local req = sock:request(pack, request_id)
local doc = req.document
return bson_decode(doc)
end
function mongo_collection:find(query, selector)
return setmetatable( {
__collection = self,
__query = query and bson_encode(query) or empty_bson,
__selector = selector and bson_encode(selector),
__ptr = nil,
__data = nil,
__cursor = nil,
__document = {},
__flags = 0,
__skip = 0,
__sortquery = nil,
__limit = 0,
} , cursor_meta)
end
-- cursor:sort { key = 1 } or cursor:sort( {key1 = 1}, {key2 = -1})
function mongo_cursor:sort(key, key_v, ...)
if key_v then
local key_list = {}
for _, kp in ipairs {key, key_v, ...} do
local next_func, t = pairs(kp)
local k, v = next_func(t, v) -- The first key pair
table.insert(key_list, k)
table.insert(key_list, v)
end
key = bson_encode_order(table.unpack(key_list))
end
self.__sortquery = bson_encode {['$query'] = self.__query, ['$orderby'] = key}
return self
end
function mongo_cursor:skip(amount)
self.__skip = amount
return self
end
function mongo_cursor:limit(amount)
self.__limit = amount
return self
end
function mongo_cursor:count(with_limit_and_skip)
local cmd = {
'count', self.__collection.name,
'query', self.__query,
}
if with_limit_and_skip then
local len = #cmd
cmd[len+1] = 'limit'
cmd[len+2] = self.__limit
cmd[len+3] = 'skip'
cmd[len+4] = self.__skip
end
local ret = self.__collection.database:runCommand(table.unpack(cmd))
assert(ret and ret.ok == 1)
return ret.n
end
-- For compatibility.
-- collection:createIndex({username = 1}, {unique = true})
local function createIndex_onekey(self, key, option)
local doc = {}
for k,v in pairs(option) do
doc[k] = v
end
local k,v = next(key) -- support only one key
assert(next(key,k) == nil, "Use new api for multi-keys")
doc.name = doc.name or (k .. "_" .. v)
doc.key = key
return self.database:runCommand("createIndexes", self.name, "indexes", {doc})
end
local function IndexModel(option)
local doc = {}
for k,v in pairs(option) do
if type(k) == "string" then
doc[k] = v
end
end
local keys = {}
local name
for _, kv in ipairs(option) do
local k,v
if type(kv) == "string" then
k = kv
v = 1
else
k,v = next(kv)
end
table.insert(keys, k)
table.insert(keys, v)
name = (name == nil) and k or (name .. "_" .. k)
name = name .. "_" .. v
end
assert(name, "Need keys")
doc.name = doc.name or name
doc.key = bson_encode_order(table.unpack(keys))
return doc
end
-- collection:createIndex { { key1 = 1}, { key2 = 1 }, unique = true }
-- or collection:createIndex { "key1", "key2", unique = true }
-- or collection:createIndex( { key1 = 1} , { unique = true } ) -- For compatibility
function mongo_collection:createIndex(arg1 , arg2)
if arg2 then
return createIndex_onekey(self, arg1, arg2)
else
return self.database:runCommand("createIndexes", self.name, "indexes", { IndexModel(arg1) })
end
end
function mongo_collection:createIndexes(...)
local idx = { ... }
for k,v in ipairs(idx) do
idx[k] = IndexModel(v)
end
return self.database:runCommand("createIndexes", self.name, "indexes", idx)
end
mongo_collection.ensureIndex = mongo_collection.createIndex
function mongo_collection:drop()
return self.database:runCommand("drop", self.name)
end
-- collection:dropIndex("age_1")
-- collection:dropIndex("*")
function mongo_collection:dropIndex(indexName)
return self.database:runCommand("dropIndexes", self.name, "index", indexName)
end
-- collection:findAndModify({query = {name = "userid"}, update = {["$inc"] = {nextid = 1}}, })
-- keys, value type
-- query, table
-- sort, table
-- remove, bool
-- update, table
-- new, bool
-- fields, bool
-- upsert, boolean
function mongo_collection:findAndModify(doc)
assert(doc.query)
assert(doc.update or doc.remove)
local cmd = {"findAndModify", self.name};
for k, v in pairs(doc) do
table.insert(cmd, k)
table.insert(cmd, v)
end
return self.database:runCommand(table.unpack(cmd))
end
function mongo_cursor:hasNext()
if self.__ptr == nil then
if self.__document == nil then
return false
end
local conn = self.__collection.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack
if self.__data == nil then
local query = self.__sortquery or self.__query
pack = driver.query(request_id, self.__flags, self.__collection.full_name, self.__skip, -self.__limit, query, self.__selector)
else
if self.__cursor then
pack = driver.more(request_id, self.__collection.full_name, -self.__limit, self.__cursor)
else
-- no more
self.__document = nil
self.__data = nil
return false
end
end
local ok, result = pcall(sock.request,sock,pack, request_id)
local doc = result.document
local cursor = result.cursor_id
if ok then
if doc then
self.__document = result.result
self.__data = result.data
self.__ptr = 1
self.__cursor = cursor
return true
else
self.__document = nil
self.__data = nil
self.__cursor = nil
return false
end
else
self.__document = nil
self.__data = nil
self.__cursor = nil
if doc then
local err = bson_decode(doc)
error(err["$err"])
else
error("Reply from mongod error")
end
end
end
return true
end
function mongo_cursor:next()
if self.__ptr == nil then
error "Call hasNext first"
end
local r = bson_decode(self.__document[self.__ptr])
self.__ptr = self.__ptr + 1
if self.__ptr > #self.__document then
self.__ptr = nil
end
return r
end
function mongo_cursor:close()
-- todo: warning hasNext after close
if self.__cursor then
local sock = self.__collection.connection.__sock
local pack = driver.kill(self.__cursor)
sock:request(pack)
end
end
return mongo
| mit |
Lautitia/newfies-dialer | lua/libs/tag_replace.lua | 4 | 3193 | --
-- Newfies-Dialer License
-- http://www.newfies-dialer.org
--
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this file,
-- You can obtain one at http://mozilla.org/MPL/2.0/.
--
-- Copyright (C) 2011-2014 Star2Billing S.L.
--
-- The Initial Developer of the Original Code is
-- Arezqui Belaid <info@star2billing.com>
--
function mtable_jsoncontact(contact)
--decode json from additional_vars
if contact['additional_vars'] then
decdata = decodejson(contact['additional_vars'])
if decdata and type(decdata) == "table" then
-- Merge Table
mcontact = table_merge(contact, decdata)
else
mcontact = contact
end
else
mcontact = contact
end
return mcontact
end
--
-- Function Replace place holders by tag value.
-- This function will replace all the following tags :
-- {last_name}
-- {first_name}
-- {email}
-- {country}
-- {city}
-- {contact}
-- as well as, get additional_vars, and replace json tags
--
function tag_replace(text, contact)
--if no text return empty string
if not text or text == '' then
return ''
end
--check if we got tag {__} in the text
if not string.find(text, "[{|}]") then
return text
end
--get merged table of contact with the json additional_vars
mcontact = mtable_jsoncontact(contact)
if not type(mcontact) == "table" then
return text
end
for k, v in pairs(mcontact) do
if k == 'contact' or k == 'Phone1' or k == 'Phone2' or k == 'Phone3' then
newv = ''
for i = 1, string.len(v) do
newv = newv..string.sub(v, i, i)..' '
end
text = string.gsub(text, '{'..k..'}', newv)
elseif string.sub(k, -3) ~= '_id' then
text = string.gsub(text, '{'..k..'}', v)
end
end
-- with .- you match the smallest expression
text = string.gsub(text, '{.-}', '')
return text
end
--
-- Merge table
--
function table_merge(t1, t2)
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
table_merge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
--
-- Decode Json and return false if the json have an error
--
function decodejson(jsondata)
local json = require("json")
cError, res = pcall(json.decode,jsondata)
if not cError then
return false
end
return res
end
--
-- Test
--
if false then
local inspect = require "inspect"
text = "Hello there {first_name}, your city is {city} and your age is {age}, your number is {contact}"
contact = {
additional_vars = '{"country": "canada", "age": "32", "city":"barcelona"}',
campaign_id = "38",
city = "",
contact = "32132123123",
}
print(inspect(contact))
ntext = tag_replace(text, contact)
print("\nReplaced Text : "..ntext)
print("\nend")
end
| mpl-2.0 |
emoon/ProDBG | bin/win32/scripts/tundra/syntax/rust-cargo.lua | 3 | 7655 | -- rust-cargo.lua - Support for Rust and Cargo
module(..., package.seeall)
local nodegen = require "tundra.nodegen"
local files = require "tundra.syntax.files"
local path = require "tundra.path"
local util = require "tundra.util"
local depgraph = require "tundra.depgraph"
local native = require "tundra.native"
_rust_cargo_program_mt = nodegen.create_eval_subclass { }
_rust_cargo_shared_lib_mt = nodegen.create_eval_subclass { }
_rust_cargo_crate_mt = nodegen.create_eval_subclass { }
-- This allows us to get absolut objectdir to send to Cargo as Cargo can "move around"
-- in the path this make sure it always finds the directory
local function get_absolute_object_dir(env)
local base_dir = env:interpolate('$(OBJECTDIR)')
local cwd = native.getcwd()
return cwd .. "$(SEP)" .. base_dir
end
-- This function will gather up so extra dependencies. In the case when we depend on a Rust crate
-- We simply return the sources to allow the the unit being built to depend on it. The reason
-- for this is that Cargo will not actually link with this step but it's only used to make
-- sure it gets built when a Crate changes
function get_extra_deps(data, env)
local libsuffix = { env:get("LIBSUFFIX") }
local sources = data.Sources
local source_depts = {}
local extra_deps = {}
for _, dep in util.nil_ipairs(data.Depends) do
if dep.Keyword == "StaticLibrary" then
local node = dep:get_dag(env:get_parent())
extra_deps[#extra_deps + 1] = node
node:insert_output_files(sources, libsuffix)
elseif dep.Keyword == "RustCrate" then
local node = dep:get_dag(env:get_parent())
source_depts[#source_depts + 1] = dep.Decl.Sources
end
end
return extra_deps, source_depts
end
local cmd_line_type_prog = 0
local cmd_line_type_shared_lib = 1
local cmd_line_type_crate = 2
function build_rust_action_cmd_line(env, data, program)
local static_libs = ""
-- build an string with all static libs this code depends on
for _, dep in util.nil_ipairs(data.Depends) do
if dep.Keyword == "StaticLibrary" then
local node = dep:get_dag(env:get_parent())
static_libs = static_libs .. dep.Decl.Name .. " "
end
end
local tundra_dir = get_absolute_object_dir(env);
-- The way Cargo sets it's target directory is by using a env variable which is quite ugly but that is the way it works.
-- So before running the command we set the target directory of
-- We also set the tundra cmd line as env so we can use that inside the build.rs
-- to link with the libs in the correct path
local target = path.join(tundra_dir, "__" .. data.Name)
local target_dir = ""
local export = "export ";
local merge = " ; ";
if native.host_platform == "windows" then
export = "set "
merge = "&&"
end
target_dir = export .. "CARGO_TARGET_DIR=" .. target .. merge
tundra_dir = export .. "TUNDRA_OBJECTDIR=" .. tundra_dir .. merge
if static_libs ~= "" then
-- Remove trailing " "
local t = string.sub(static_libs, 1, string.len(static_libs) - 1)
static_libs = export .. "TUNDRA_STATIC_LIBS=\"" .. t .. "\"" .. merge
end
local variant = env:get('CURRENT_VARIANT')
local release = ""
local output_target = ""
local output_name = ""
-- Make sure output_name gets prefixed/sufixed correctly
if program == cmd_line_type_prog then
output_name = data.Name .. "$(HOSTPROGSUFFIX)"
elseif program == cmd_line_type_shared_lib then
output_name = "$(SHLIBPREFIX)" .. data.Name .. "$(HOSTSHLIBSUFFIX)"
else
output_name = "$(SHLIBPREFIX)" .. data.Name .. ".rlib"
end
-- If variant is debug (default) we assume that we should use debug and not release mode
if variant == "debug" then
output_target = path.join(target, "debug$(SEP)" .. output_name)
else
output_target = path.join(target, "release$(SEP)" .. output_name)
release = " --release "
end
-- If user hasn't set any specific cargo opts we use build as default
-- Setting RUST_CARGO_OPTS = "build" by default doesn't seem to work as if user set
-- RUST_CARGO_OPTS = "test" the actual string is "build test" which doesn't work
local cargo_opts = env:interpolate("$(RUST_CARGO_OPTS)")
if cargo_opts == "" then
cargo_opts = "build"
end
local rustc_flags = ""
-- Check if we have some extra flags set for rustc
local rust_opts = env:interpolate("$(RUST_OPTS)")
if rust_opts ~= "" then
rustc_flags = export .. "RUSTFLAGS=\"" .. rust_opts .. "\"" .. merge
end
local action_cmd_line = rustc_flags .. tundra_dir .. target_dir .. static_libs .. "$(RUST_CARGO) " .. cargo_opts .. " --manifest-path=" .. data.CargoConfig .. release
return action_cmd_line, output_target
end
function _rust_cargo_program_mt:create_dag(env, data, deps)
local action_cmd_line, output_target = build_rust_action_cmd_line(env, data, cmd_line_type_prog)
local extra_deps, dep_sources = get_extra_deps(data, env)
local build_node = depgraph.make_node {
Env = env,
Pass = data.Pass,
InputFiles = util.merge_arrays({ data.CargoConfig }, data.Sources, util.flatten(dep_sources)),
Annotation = path.join("$(OBJECTDIR)", data.Name),
Label = "Cargo Program $(@)",
Action = action_cmd_line,
OutputFiles = { output_target },
Dependencies = util.merge_arrays(deps, extra_deps),
}
local dst ="$(OBJECTDIR)" .. "$(SEP)" .. path.get_filename(env:interpolate(output_target))
local src = output_target
-- Copy the output file to the regular $(OBJECTDIR)
return files.copy_file(env, src, dst, data.Pass, { build_node })
end
function _rust_cargo_shared_lib_mt:create_dag(env, data, deps)
local action_cmd_line, output_target = build_rust_action_cmd_line(env, data, cmd_line_type_shared_lib)
local extra_deps, dep_sources = get_extra_deps(data, env)
local build_node = depgraph.make_node {
Env = env,
Pass = data.Pass,
InputFiles = util.merge_arrays({ data.CargoConfig }, data.Sources, util.flatten(dep_sources)),
Annotation = path.join("$(OBJECTDIR)", data.Name),
Label = "Cargo SharedLibrary $(@)",
Action = action_cmd_line,
OutputFiles = { output_target },
Dependencies = util.merge_arrays(deps, extra_deps),
}
local dst ="$(OBJECTDIR)" .. "$(SEP)" .. path.get_filename(env:interpolate(output_target))
local src = output_target
-- Copy the output file to the regular $(OBJECTDIR)
return files.copy_file(env, src, dst, data.Pass, { build_node })
end
function _rust_cargo_crate_mt:create_dag(env, data, deps)
local action_cmd_line, output_target = build_rust_action_cmd_line(env, data, cmd_line_type_crate)
local extra_deps, dep_sources = get_extra_deps(data, env)
local build_node = depgraph.make_node {
Env = env,
Pass = data.Pass,
InputFiles = util.merge_arrays({ data.CargoConfig }, data.Sources, util.flatten(dep_sources)),
Annotation = path.join("$(OBJECTDIR)", data.Name),
Label = "Cargo Crate $(@)",
Action = action_cmd_line,
OutputFiles = { output_target },
Dependencies = util.merge_arrays(deps, extra_deps),
}
return build_node
end
local rust_blueprint = {
Name = {
Type = "string",
Required = true,
Help = "Name of the project. Must match the name in Cargo.toml"
},
CargoConfig = {
Type = "string",
Required = true,
Help = "Path to Cargo.toml"
},
Sources = {
Required = true,
Help = "List of source files",
Type = "source_list",
ExtensionKey = "RUST_SUFFIXES",
},
}
nodegen.add_evaluator("RustProgram", _rust_cargo_program_mt, rust_blueprint)
nodegen.add_evaluator("RustSharedLibrary", _rust_cargo_shared_lib_mt, rust_blueprint)
nodegen.add_evaluator("RustCrate", _rust_cargo_crate_mt, rust_blueprint)
| mit |
amirfucker/uzzy_bot | bot/bot.lua | 1 | 7044 | 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 = '0.14.6'
-- 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)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_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
print('\27[36mNot valid: Telegram message\27[39m')
return false
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
if plugins[disabled_plugin].hidden then
print('Plugin '..disabled_plugin..' is disabled on this chat')
else
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
end
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 = {
"echo",
"get",
"boobs",
"tagall",
"banhammer",
"google",
"groupmanager",
"leave",
"help",
"id",
"location",
"plugins",
"channels",
"set",
"Anti-bot",
"stats",
"time",
"moderation"},
sudo_users = {147509695,170716752},
disabled_channels = {},
moderation = {data = 'data/moderation.json'}
}
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)
--vardump (chat)
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('\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 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
cogwerkz/DiabolicUI | modules/unitframes/elements/health.lua | 2 | 4173 | local _, Engine = ...
local Handler = Engine:GetHandler("UnitFrame")
local C = Engine:GetDB("Data: Colors")
local F = Engine:GetDB("Library: Format")
-- Lua API
local _G = _G
local math_floor = math.floor
local pairs = pairs
local tonumber = tonumber
local tostring = tostring
local unpack = unpack
-- WoW API
local UnitClassification = _G.UnitClassification
local UnitHealth = _G.UnitHealth
local UnitHealthMax = _G.UnitHealthMax
local UnitIsConnected = _G.UnitIsConnected
local UnitIsDeadOrGhost = _G.UnitIsDeadOrGhost
local UnitIsPlayer = _G.UnitIsPlayer
local UnitIsUnit = _G.UnitIsUnit
local UnitIsTapDenied = _G.UnitIsTapDenied
local UnitLevel = _G.UnitLevel
local UnitPlayerControlled = _G.UnitPlayerControlled
local UnitReaction = _G.UnitReaction
local Update = function(self, event, ...)
local Health = self.Health
local unit = self.unit
local curHealth = UnitHealth(unit)
local maxHealth = UnitHealthMax(unit)
local isUnavailable
if UnitIsPlayer(unit) then
if (not UnitIsConnected(unit)) then
curHealth = 1
maxHealth = 1
isUnavailable = "offline"
elseif UnitIsDeadOrGhost(unit) then
curHealth = 0
maxHealth = 0
isUnavailable = UnitIsGhost(unit) and "ghost" or "dead"
end
elseif UnitIsDead(unit) then
curHealth = 0
maxHealth = 0
isUnavailable = "dead"
end
Health:SetMinMaxValues(0, maxHealth)
Health:SetValue(curHealth)
if Health.Value then
if (not isUnavailable) then
if (curHealth == 0 or maxHealth == 0) and (not Health.Value.showAtZero) then
Health.Value:SetText("")
else
if Health.Value.showDeficit then
if Health.Value.showPercent then
if Health.Value.showMaximum then
Health.Value:SetFormattedText("%s / %s - %d%%", F.Short(maxHealth - curHealth), F.Short(maxHealth), math_floor(curHealth/maxHealth * 100))
else
Health.Value:SetFormattedText("%s / %d%%", F.Short(maxHealth - curHealth), math_floor(curHealth/maxHealth * 100))
end
else
if Health.Value.showMaximum then
Health.Value:SetFormattedText("%s / %s", F.Short(maxHealth - curHealth), F.Short(maxHealth))
else
Health.Value:SetFormattedText("%s / %s", F.Short(maxHealth - curHealth))
end
end
else
if Health.Value.showPercent then
if Health.Value.showMaximum then
Health.Value:SetFormattedText("%s / %s - %d%%", F.Short(curHealth), F.Short(maxHealth), math_floor(curHealth/maxHealth * 100))
elseif Health.Value.hideMinimum then
Health.Value:SetFormattedText("%d%%", math_floor(curHealth/maxHealth * 100))
else
Health.Value:SetFormattedText("%s / %d%%", F.Short(curHealth), math_floor(curHealth/maxHealth * 100))
end
else
if Health.Value.showMaximum then
Health.Value:SetFormattedText("%s / %s", F.Short(curHealth), F.Short(maxHealth))
else
Health.Value:SetFormattedText("%s / %s", F.Short(curHealth))
end
end
end
end elseif (isUnavailable == "dead") then
Health.Value:SetText(DEAD)
elseif (isUnavailable == "ghost") then
Health.Value:SetText(DEAD)
elseif (isUnavailable == "offline") then
Health.Value:SetText(PLAYER_OFFLINE)
end
end
if Health.PostUpdate then
return Health:PostUpdate(unit, curHealth, maxHealth, isUnavailable)
end
end
local Enable = function(self)
local Health = self.Health
if Health then
Health._owner = self
if Health.frequent then
self:EnableFrequentUpdates("Health", Health.frequent)
else
self:RegisterEvent("UNIT_HEALTH", Update)
self:RegisterEvent("UNIT_MAXHEALTH", Update)
self:RegisterEvent("UNIT_HAPPINESS", Update)
self:RegisterEvent("UNIT_FACTION", Update)
self:RegisterEvent("PLAYER_ENTERING_WORLD", Update)
end
return true
end
end
local Disable = function(self)
local Health = self.Health
if Health then
if (not Health.frequent) then
self:UnregisterEvent("UNIT_HEALTH", Update)
self:UnregisterEvent("UNIT_MAXHEALTH", Update)
self:UnregisterEvent("UNIT_HAPPINESS", Update)
self:UnregisterEvent("UNIT_FACTION", Update)
self:UnregisterEvent("PLAYER_ENTERING_WORLD", Update)
end
end
end
Handler:RegisterElement("Health", Enable, Disable, Update) | mit |
liangjz92/deep_cqa | util/Yahoo.lua | 1 | 4550 | --[[
Yahoo manner 数据集的warper,用类的形式提供服务
liangjz 2015-3-22
训练集,通过get_sample获得一个三元组
测试集
问题数据,通过
--]]
--require('..')
local cjson = require('cjson')
local DataSet = torch.class('Yahoo') --保险语料库的读取warper
function DataSet:__init(name,negative_size)
local data_file =nil
if name=='train' then
data_file = 'data/yahoo/family.json'
end
if name=='dev' then
data_file = 'data/yahoo/business.json'
end
if name=='test' then
data_file = 'data/yahoo/health.json'
end
local tmp= cjson.decode(io.open(data_file,'r'):read())
self.questions = tmp[1]
self.answer_set = tmp[2]
self.indices = torch.randperm(#self.questions) --对训练样本进行乱序处理
self.current_train = 1 --当前样本的下标 ,一个样本只有一个正确答案
self.current_negative = 1 --当前选取的负样本为第多少个负样本(针对这个训练样本来说)
self.negative_size =negative_size or 1 --负样本采样个数,默认为1
self.answer_vecs ={} --存储答案的中间结果
self.answer_index = 1 --遍历答案时的下标
self.dev_index = 0 --遍历验证集时下标
self.test_index = 0 --遍历测试集时的下标
end
function DataSet:getNextPair() --生成下一对问题-正样本-负样本对
if self.current_train > #self.questions then return nil end --数据集已经遍历完毕
local qst = self.questions[self.current_train][1] ..' ' .. self.questions[self.current_train][2] --一个问题
local true_id = self.questions[self.current_train][3] --一个正确答案
local false_id = deep_cqa.ins_meth.random_negative_id({self.questions[self.current_train][3]},#self.questions-1,deep_cqa.config.random_seed)
deep_cqa.config.random_seed = (deep_cqa.config.random_seed +5)%50000000 --随机种子
true_id = tostring(tonumber(true_id))
false_id = tostring(tonumber(false_id))
local false_answer = self.answer_set[false_id]
local true_answer = self.answer_set[true_id]
self.current_negative = self.current_negative + 1
if self.current_negative > self.negative_size then
self.current_negative = 1
self.current_train = self.current_train + 1
end
return {qst,true_answer,false_answer} --返回sample三元组
end
function DataSet:resetTrainset(negative_size) --重新设定训练集
self.indices = torch.randperm(#self.questions) --对训练样本进行乱序处理
self.current_train = 1 --当前样本的下标
self.current_negative = 1 --当前选取的负样本为第多少个负样本(针对这个训练样本来说)
self.negative_size =negative_size or self.negative_size --负样本采样个数
end
function DataSet:getAnswer(answer_id) --根据编号返回答案的文本内容
answer_id = tostring(tonumber(answer_id))
return self.answer_set[answer_id]
end
function DataSet:getNextAnswer(marker) --返回下一个编号的答案
local reset = (marker == true) or false --是否从头开始
if reset then self.answer_index = 0 end
if self.answer_index >= #self.questions then return nil end --超出下标则返回空答案
self.answer_index = self.answer_index + 1
return {self.answer_index-1,self.answer_set[tostring(self.answer_index-1)]} --返回答案下标和答案内容的二元组
end
function DataSet:saveAnswerVec(answer_id,answer_vec) --保存答案的向量表达形式
answer_id = tonumber(answer_id)
self.answer_vecs[answer_id] = answer_vec
end
function DataSet:getAnswerVec(answer_id) --读取答案的向量表达形式
answer_id = tonumber(answer_id)
return self.answer_vecs[answer_id]
end
function DataSet:getNextTest(marker) --获取下一个验证集样本 【正确ids,问题,候选ids】
local reset = (marker == true) or false --是否从头开始
if reset then self.dev_index = 1 end
if self.dev_index > #self.questions then return nil end --超出下标则返回空验证组
local tmp ={}
tmp[1] = self.questions[self.dev_index][1] .. ' ' .. self.questions[self.dev_index][2]
tmp[2] = self.questions[self.dev_index][3]
tmp[3] = self.questions[self.dev_index][4]
self.dev_index = self.dev_index + 1
return tmp --返回验证集的三元组
end
--[[
function DataSet:getNextTest(marker) --获取下一个测试集样本
print('getNextTest method is empty')
local reset = (marker == true) or false --是否从头开始
if reset then self.test_index = 1 end
if self.test_index > self.test_set.size then return nil end --超出下标则返回空答案
self.test_index = self.test_index + 1
return self.test_set[self.test_index + 1]
end
--]]
| apache-2.0 |
erwincoumans/premake-dev-iphone-xcode4 | tests/actions/make/test_wiidev.lua | 3 | 1262 | --
-- tests/actions/make/test_wiidev.lua
-- Tests for Wii homebrew support in makefiles.
-- Copyright (c) 2011 Jason Perkins and the Premake project
--
T.make_wiidev = { }
local suite = T.make_wiidev
local make = premake.make
local cpp = premake.make.cpp
local sln, prj, cfg
function suite.setup()
_ACTION = "gmake"
sln = solution("MySolution")
configurations { "Debug", "Release" }
platforms { "WiiDev" }
prj = project("MyProject")
premake.bake.buildconfigs()
cfg = premake.getconfig(prj, "Debug", "WiiDev")
end
--
-- Make sure that the Wii-specific flags are passed to the tools.
--
function suite.writesCorrectFlags()
cpp.flags(cfg, premake.gcc)
test.capture [[
CPPFLAGS += -MMD -MP -I$(LIBOGC_INC) $(MACHDEP) -MP $(DEFINES) $(INCLUDES)
CFLAGS += $(CPPFLAGS) $(ARCH)
CXXFLAGS += $(CFLAGS)
LDFLAGS += -s -L$(LIBOGC_LIB) $(MACHDEP)
RESFLAGS += $(DEFINES) $(INCLUDES)
]]
end
--
-- Make sure the dev kit include is written to each Wii build configuration.
--
function suite.writesIncludeBlock()
make.settings(cfg, premake.gcc)
test.capture [[
ifeq ($(strip $(DEVKITPPC)),)
$(error "DEVKITPPC environment variable is not set")'
endif
include $(DEVKITPPC)/wii_rules'
]]
end
| bsd-3-clause |
ArchShaman/Zero-K | scripts/cadenza.lua | 16 | 11499 | include "constants.lua"
--------------------------------------------------------------------------------
-- pieces
--------------------------------------------------------------------------------
local base, pelvis, torso = piece("base", "pelvis", "torso")
local rthigh, rleg, rfoot, lthigh, lleg, lfoot = piece("rthigh", "rleg", "rfoot", "lthigh", "lleg", "lfoot")
local lbturret, lbbarrel1, lbbarrel2, rbturret, rbbarrel1, rbbarrel2 = piece("lbturret", "lbbarrel1", "lbbarrel2", "rbturret", "rbbarrel1", "rbbarrel2")
local lbflare1, lbflare2, rbflare1, rbflare2 = piece("lbflare1", "lbflare2", "rbflare1", "rbflare2")
local luparm, llarm, lfbarrel1, lfbarrel2, lfflare1, lfflare2 = piece("luparm", "llarm", "lfbarrel1", "lfbarrel2", "lfflare1", "lfflare2")
local ruparm, rlarm, rfbarrel1, rfbarrel2, rfflare1, rfflare2 = piece("ruparm", "rlarm", "rfbarrel1", "rfbarrel2", "rfflare1", "rfflare2")
local gunIndex = {1,1,1}
local flares = {
{lfflare1, lfflare2, rfflare1, rfflare2},
{lbflare1, rbflare1, lbflare2, rbflare2},
{base}
}
local smokePiece = {torso}
--------------------------------------------------------------------------------
-- constants
--------------------------------------------------------------------------------
-- Signal definitions
local SIG_WALK = 1
local SIG_RESTORE = 8
local SIG_AIM = 2
local TORSO_SPEED_YAW = math.rad(240)
local ARM_SPEED_PITCH = math.rad(120)
local PACE = 2
local THIGH_FRONT_ANGLE = -math.rad(50)
local THIGH_FRONT_SPEED = math.rad(60) * PACE
local THIGH_BACK_ANGLE = math.rad(30)
local THIGH_BACK_SPEED = math.rad(60) * PACE
local SHIN_FRONT_ANGLE = math.rad(45)
local SHIN_FRONT_SPEED = math.rad(90) * PACE
local SHIN_BACK_ANGLE = math.rad(10)
local SHIN_BACK_SPEED = math.rad(90) * PACE
local ARM_FRONT_ANGLE = -math.rad(20)
local ARM_FRONT_SPEED = math.rad(22.5) * PACE
local ARM_BACK_ANGLE = math.rad(10)
local ARM_BACK_SPEED = math.rad(22.5) * PACE
--[[
local FOREARM_FRONT_ANGLE = -math.rad(15)
local FOREARM_FRONT_SPEED = math.rad(40) * PACE
local FOREARM_BACK_ANGLE = -math.rad(10)
local FOREARM_BACK_SPEED = math.rad(40) * PACE
]]--
local TORSO_ANGLE_MOTION = math.rad(10)
local TORSO_SPEED_MOTION = math.rad(15)*PACE
local LEG_JUMP_COIL_ANGLE = math.rad(15)
local LEG_JUMP_COIL_SPEED = math.rad(90)
local LEG_JUMP_RELEASE_ANGLE = math.rad(18)
local LEG_JUMP_RELEASE_SPEED = math.rad(420)
local UPARM_JUMP_COIL_ANGLE = math.rad(15)
local UPARM_JUMP_COIL_SPEED = math.rad(60)
local LARM_JUMP_COIL_ANGLE = math.rad(30)
local LARM_JUMP_COIL_SPEED = math.rad(90)
local UPARM_JUMP_RELEASE_ANGLE = math.rad(80)
local UPARM_JUMP_RELEASE_SPEED = math.rad(240)
local LARM_JUMP_RELEASE_ANGLE = math.rad(90)
local LARM_JUMP_RELEASE_SPEED = math.rad(360)
local RESTORE_DELAY = 6000
--------------------------------------------------------------------------------
-- vars
--------------------------------------------------------------------------------
local armsFree = true
local jumpDir = 1
local bJumping = false
local bSomersault = false
--------------------------------------------------------------------------------
-- funcs
--------------------------------------------------------------------------------
local function RestorePose()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
Turn(base, x_axis, 0, math.rad(60))
Move(pelvis, y_axis, 0, 1)
Turn(rthigh, x_axis, 0, math.rad(200))
Turn(rleg, x_axis, 0, math.rad(200))
Turn(lthigh, x_axis, 0, math.rad(200))
Turn(lleg, x_axis, 0, math.rad(200))
Turn(luparm, x_axis, 0, math.rad(120))
Turn(ruparm, x_axis, 0, math.rad(120))
Turn(llarm, x_axis, 0, math.rad(180))
Turn(rlarm, x_axis, 0, math.rad(180))
Turn(luparm, z_axis, math.rad(45))
Turn(ruparm, z_axis, math.rad(-45))
end
-- jump stuff
function preJump(turn,distance)
Signal(SIG_WALK)
Signal(SIG_RESTORE)
bJumping = true
local radians = turn*2*math.pi/2^16
if radians > 0 then
if radians > math.rad(120) then
jumpDir = 3
elseif radians > math.rad(60) then
jumpDir = 2
else
jumpDir = 1
end
else
if radians < math.rad(-120) then
jumpDir = 3
elseif radians < math.rad(-60) then
jumpDir = 4
else
jumpDir = 1
end
end
-- coil for jump
Move(pelvis, y_axis, -5, 10)
Turn(torso, y_axis, 0, math.rad(180))
Turn(lthigh, y_axis, math.rad(30), math.rad(60))
Turn(rthigh, y_axis, math.rad(-30), math.rad(60))
Turn(lthigh, x_axis, -LEG_JUMP_COIL_ANGLE, LEG_JUMP_COIL_SPEED)
Turn(rthigh, x_axis, -LEG_JUMP_COIL_ANGLE, LEG_JUMP_COIL_SPEED)
Turn(lleg, x_axis, LEG_JUMP_COIL_ANGLE, LEG_JUMP_COIL_SPEED)
Turn(rleg, x_axis, LEG_JUMP_COIL_ANGLE, LEG_JUMP_COIL_SPEED)
Turn(luparm, z_axis, UPARM_JUMP_COIL_ANGLE, UPARM_JUMP_COIL_SPEED)
Turn(ruparm, z_axis, -UPARM_JUMP_COIL_ANGLE, UPARM_JUMP_COIL_SPEED)
Turn(llarm, x_axis, LARM_JUMP_COIL_ANGLE, LARM_JUMP_COIL_SPEED)
Turn(rlarm, x_axis, LARM_JUMP_COIL_ANGLE, LARM_JUMP_COIL_SPEED)
end
function beginJump()
-- release jump
Move(pelvis, y_axis, 0, 24)
Turn(lthigh, y_axis, 0, math.rad(180))
Turn(rthigh, y_axis, 0, math.rad(180))
Turn(lthigh, x_axis, LEG_JUMP_RELEASE_ANGLE, LEG_JUMP_RELEASE_SPEED)
Turn(rthigh, x_axis, LEG_JUMP_RELEASE_ANGLE, LEG_JUMP_RELEASE_SPEED)
Turn(lleg, x_axis, -2*LEG_JUMP_RELEASE_ANGLE, LEG_JUMP_RELEASE_SPEED)
Turn(rleg, x_axis, -2*LEG_JUMP_RELEASE_ANGLE, LEG_JUMP_RELEASE_SPEED)
--Turn(luparm, z_axis, UPARM_JUMP_RELEASE_ANGLE, UPARM_JUMP_RELEASE_SPEED)
--Turn(ruparm, z_axis, -UPARM_JUMP_RELEASE_ANGLE, UPARM_JUMP_RELEASE_SPEED)
Turn(llarm, x_axis, LARM_JUMP_RELEASE_ANGLE, LARM_JUMP_RELEASE_SPEED)
Turn(rlarm, x_axis, LARM_JUMP_RELEASE_ANGLE, LARM_JUMP_RELEASE_SPEED)
bSomersault = true
end
function jumping()
end
function halfJump()
end
function endJump()
EmitSfx(base, 4096 + 2)
bJumping = false
RestorePose()
end
local function Somersault()
Sleep(100)
if jumpDir == 1 then
Turn(pelvis, x_axis, math.rad(22), math.rad(40))
elseif jumpDir == 2 then
elseif jumpDir == 3 then
Turn(pelvis, x_axis, math.rad(-22), math.rad(40))
else
end
-- curl up body
Sleep(600)
--Turn(luparm, y_axis, -math.rad(45), UPARM_JUMP_RELEASE_SPEED)
--Turn(ruparm, y_axis, math.rad(45), UPARM_JUMP_RELEASE_SPEED)
Turn(llarm, x_axis, LARM_JUMP_COIL_ANGLE, LARM_JUMP_RELEASE_SPEED)
Turn(rlarm, x_axis, LARM_JUMP_COIL_ANGLE, LARM_JUMP_RELEASE_SPEED)
Turn(lthigh, x_axis, -math.rad(90), LEG_JUMP_RELEASE_SPEED)
Turn(rthigh, x_axis, -math.rad(90), LEG_JUMP_RELEASE_SPEED)
Turn(lleg, x_axis, math.rad(30), LEG_JUMP_RELEASE_SPEED)
Turn(rleg, x_axis, math.rad(30), LEG_JUMP_RELEASE_SPEED)
Sleep(200)
-- spin
if jumpDir == 1 then
Turn(pelvis, x_axis, math.rad(200), math.rad(240))
elseif jumpDir == 2 then
elseif jumpDir == 3 then
Turn(pelvis, x_axis, math.rad(-200), math.rad(240))
else
end
WaitForTurn(pelvis, x_axis)
Turn(pelvis, x_axis, 0, math.rad(240))
-- strike a pose
Turn(luparm, y_axis, 0, UPARM_JUMP_COIL_SPEED*1.5)
Turn(ruparm, y_axis, 0, UPARM_JUMP_COIL_SPEED*1.5)
Turn(luparm, z_axis, UPARM_JUMP_RELEASE_ANGLE, UPARM_JUMP_COIL_SPEED*1.5)
Turn(ruparm, z_axis, -UPARM_JUMP_RELEASE_ANGLE, UPARM_JUMP_COIL_SPEED*1.5)
Turn(llarm, x_axis, LARM_JUMP_RELEASE_ANGLE, LARM_JUMP_COIL_SPEED*1.5)
Turn(rlarm, x_axis, LARM_JUMP_RELEASE_ANGLE, LARM_JUMP_COIL_SPEED*1.5)
Turn(lthigh, x_axis, 1.75*LEG_JUMP_COIL_ANGLE, LEG_JUMP_COIL_SPEED*1.5)
Turn(rthigh, x_axis, -math.rad(50), LEG_JUMP_COIL_SPEED*1.5)
Turn(lleg, x_axis, -LEG_JUMP_COIL_ANGLE, LEG_JUMP_RELEASE_SPEED)
Turn(rleg, x_axis, math.rad(40), LEG_JUMP_RELEASE_SPEED*1.5)
end
-- needed because the gadgets throw tantrums if you start a thread in the above functions
function SomersaultLoop()
while true do
if bSomersault then
bSomersault = false
Somersault()
end
Sleep(100)
end
end
-- not jump stuff
local function Walk()
Signal(SIG_WALK)
SetSignalMask(SIG_WALK)
Turn(base, x_axis, math.rad(10), math.rad(30))
while true do
--left leg up, right leg back
Turn(lthigh, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED)
Turn(lleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED)
Turn(rthigh, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED)
Turn(rleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED)
if (armsFree) then
--left arm back, right arm front
Turn(torso, y_axis, TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION)
Turn(luparm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
Turn(ruparm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED)
end
WaitForTurn(lthigh, x_axis)
Sleep(0)
--right leg up, left leg back
Turn(lthigh, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED)
Turn(lleg, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED)
Turn(rthigh, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED)
Turn(rleg, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED)
if (armsFree) then
--left arm front, right arm back
Turn(torso, y_axis, -TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION)
Turn(luparm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED)
Turn(ruparm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
end
WaitForTurn(rthigh, x_axis)
Sleep(0)
end
end
function script.Create()
Turn(luparm, z_axis, math.rad(45))
Turn(ruparm, z_axis, math.rad(-45))
Turn(lbflare1, x_axis, math.rad(-120))
Turn(lbflare2, x_axis, math.rad(-120))
Turn(rbflare1, x_axis, math.rad(-120))
Turn(rbflare2, x_axis, math.rad(-120))
Turn(lbflare1, y_axis, math.rad(-45))
Turn(lbflare2, y_axis, math.rad(-45))
Turn(rbflare1, y_axis, math.rad(45))
Turn(rbflare2, y_axis, math.rad(45))
StartThread(SmokeUnit, smokePiece)
StartThread(SomersaultLoop)
end
function script.StartMoving()
StartThread(Walk)
end
function script.StopMoving()
StartThread(RestorePose)
end
local function RestoreAfterDelay()
Signal(SIG_RESTORE)
SetSignalMask(SIG_RESTORE)
Sleep(RESTORE_DELAY)
armsFree = true
Turn(torso, y_axis, 0, TORSO_SPEED_YAW)
Turn(luparm, x_axis, 0, ARM_SPEED_PITCH)
Turn(ruparm, x_axis, 0, ARM_SPEED_PITCH)
end
function script.AimWeapon(num, heading, pitch)
if num == 1 then
if bJumping then return false end
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
armsFree = false
Turn(torso, y_axis, heading, TORSO_SPEED_YAW)
Turn(luparm, x_axis, -pitch, ARM_SPEED_PITCH)
Turn(ruparm, x_axis, -pitch, ARM_SPEED_PITCH)
WaitForTurn(torso, y_axis)
WaitForTurn(luparm, x_axis)
WaitForTurn(ruparm, x_axis)
end
return true
end
function script.FireWeapon(num)
end
function script.Shot(num)
gunIndex[num] = gunIndex[num] + 1
if gunIndex[num] > 4 then gunIndex[num] = 1 end
if num == 1 then
EmitSfx(flares[num][gunIndex[num]], 1024)
EmitSfx(flares[num][gunIndex[num]], 1026)
else
EmitSfx(flares[num][gunIndex[num]], 1027)
end
end
function script.QueryWeapon(num)
return(flares[num][gunIndex[num]])
end
function script.AimFromWeapon(num)
return torso
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < 0.5 then
Explode(torso, sfxNone)
Explode(luparm, sfxNone)
Explode(ruparm, sfxNone)
Explode(pelvis, sfxNone)
Explode(lthigh, sfxNone)
Explode(rthigh, sfxNone)
Explode(rleg, sfxNone)
Explode(lleg, sfxNone)
return 1
else
Explode(torso, sfxShatter)
Explode(luparm, sfxSmoke + sfxFire + sfxExplode)
Explode(ruparm, sfxSmoke + sfxFire + sfxExplode)
Explode(pelvis, sfxShatter)
Explode(lthigh, sfxShatter)
Explode(rthigh, sfxShatter)
Explode(rleg, sfxShatter)
Explode(lleg, sfxShatter)
return 2
end
end
| gpl-2.0 |
d9magai/freeciv | dependencies/tolua-5.2/src/bin/lua/define.lua | 14 | 1243 | -- tolua: define class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: define.lua,v 1.3 2009/11/24 16:45:13 fabraham Exp $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Define class
-- Represents a numeric const definition
-- The following filds are stored:
-- name = constant name
classDefine = {
name = '',
}
classDefine.__index = classDefine
setmetatable(classDefine,classFeature)
-- register define
function classDefine:register ()
output(' tolua_constant(tolua_S,"'..self.lname..'",'..self.name..');')
end
-- Print method
function classDefine:print (ident,close)
print(ident.."Define{")
print(ident.." name = '"..self.name.."',")
print(ident.." lname = '"..self.lname.."',")
print(ident.."}"..close)
end
-- Internal constructor
function _Define (t)
setmetatable(t,classDefine)
t:buildnames()
if t.name == '' then
error("#invalid define")
end
append(t)
return t
end
-- Constructor
-- Expects a string representing the constant name
function Define (n)
return _Define{
name = n
}
end
| gpl-2.0 |
ArchShaman/Zero-K | LuaRules/Gadgets/unit_carrier_drones.lua | 4 | 31653 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Carrier Drones",
desc = "Spawns drones for aircraft carriers",
author = "TheFatConroller, modified by KingRaptor",
date = "12.01.2008",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true
}
end
--Version 1.003
--Changelog:
--24/6/2014 added carrier building drone on emit point.
--around 1/1/2017: added hold fire functionality, recall drones button, circular drone leash, drones pay attention to set target
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
include("LuaRules/Configs/customcmds.h.lua")
local AddUnitDamage = Spring.AddUnitDamage
local CreateUnit = Spring.CreateUnit
local GetCommandQueue = Spring.GetCommandQueue
local GetUnitIsStunned = Spring.GetUnitIsStunned
local GetUnitPieceMap = Spring.GetUnitPieceMap
local GetUnitPiecePosDir= Spring.GetUnitPiecePosDir
local GetUnitPosition = Spring.GetUnitPosition
local GiveOrderToUnit = Spring.GiveOrderToUnit
local SetUnitPosition = Spring.SetUnitPosition
local SetUnitNoSelect = Spring.SetUnitNoSelect
local TransferUnit = Spring.TransferUnit
local spGetUnitRulesParam = Spring.GetUnitRulesParam
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local spGetGameFrame = Spring.GetGameFrame
local random = math.random
local CMD_ATTACK = CMD.ATTACK
local emptyTable = {}
local INLOS_ACCESS = {inlos = true}
-- thingsWhichAreDrones is an optimisation for AllowCommand, no longer used but it'll stay here for now
local carrierDefs, thingsWhichAreDrones, unitRulesCarrierDefs = include "LuaRules/Configs/drone_defs.lua"
local DEFAULT_UPDATE_ORDER_FREQUENCY = 40 -- gameframes
local IDLE_DISTANCE = 120
local ACTIVE_DISTANCE = 180
local DRONE_HEIGHT = 120
local RECALL_TIMEOUT = 300
local generateDrones = {}
local carrierList = {}
local droneList = {}
local drones_to_move = {}
local killList = {}
local GiveClampedOrderToUnit = Spring.Utilities.GiveClampedOrderToUnit
local recallDronesCmdDesc = {
id = CMD_RECALL_DRONES,
type = CMDTYPE.ICON,
name = 'Recall Drones',
cursor = 'Load units',
action = 'recalldrones',
tooltip = 'Recall any owned drones to the mothership.',
}
local toggleDronesCmdDesc = {
id = CMD_TOGGLE_DRONES,
type = CMDTYPE.ICON_MODE,
name = 'Drone Generation',
cursor = 'Load units',
action = 'toggledrones',
tooltip = 'Toggle drone creation.',
params = {1, 'Disabled','Enabled'}
}
local toggleParams = {params = {1, 'Disabled','Enabled'}}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function RandomPointInUnitCircle()
local angle = random(0, 2*math.pi)
local distance = math.pow(random(0, 1), 0.5)
return math.cos(angle)*distance, math.sin(angle)*distance
end
local function ChangeDroneRulesParam(unitID, diff)
local count = Spring.GetUnitRulesParam(unitID, "dronesControlled") or 0
count = count + diff
Spring.SetUnitRulesParam(unitID, "dronesControlled", count, INLOS_ACCESS)
end
local function InitCarrier(unitID, carrierData, teamID, maxDronesOverride)
local toReturn = {teamID = teamID, droneSets = {}, occupiedPieces={}, droneInQueue= {}}
local unitPieces = GetUnitPieceMap(unitID)
local usedPieces = carrierData.spawnPieces
if usedPieces then
toReturn.spawnPieces = {}
for i = 1, #usedPieces do
toReturn.spawnPieces[i] = unitPieces[usedPieces[i]]
end
toReturn.pieceIndex = 1
end
local maxDronesTotal = 0
for i = 1, #carrierData do
-- toReturn.droneSets[i] = Spring.Utilities.CopyTable(carrierData[i])
toReturn.droneSets[i] = {nil}
--same as above, but we assign reference to "carrierDefs[i]" table in memory to avoid duplicates, DO NOT CHANGE ITS CONTENT (its constant & config value only).
toReturn.droneSets[i].config = carrierData[i]
toReturn.droneSets[i].maxDrones = (maxDronesOverride and maxDronesOverride[i]) or carrierData[i].maxDrones
maxDronesTotal = maxDronesTotal + toReturn.droneSets[i].maxDrones
toReturn.droneSets[i].reload = carrierData[i].reloadTime
toReturn.droneSets[i].droneCount = 0
toReturn.droneSets[i].drones = {}
toReturn.droneSets[i].buildCount = 0
end
if maxDronesTotal > 0 then
Spring.SetUnitRulesParam(unitID, "dronesControlled", 0, INLOS_ACCESS)
Spring.SetUnitRulesParam(unitID, "dronesControlledMax", maxDronesTotal, INLOS_ACCESS)
end
return toReturn
end
local function CreateCarrier(unitID)
Spring.InsertUnitCmdDesc(unitID, recallDronesCmdDesc)
Spring.InsertUnitCmdDesc(unitID, toggleDronesCmdDesc)
generateDrones[unitID] = true
end
local function Drones_InitializeDynamicCarrier(unitID)
if carrierList[unitID] then
return
end
local carrierData = {}
local maxDronesOverride = {}
for name, data in pairs(unitRulesCarrierDefs) do
local drones = Spring.GetUnitRulesParam(unitID, "carrier_count_" .. name)
if drones then
carrierData[#carrierData + 1] = data
maxDronesOverride[#maxDronesOverride + 1] = drones
CreateCarrier(unitID)
end
end
carrierList[unitID] = InitCarrier(unitID, carrierData, Spring.GetUnitTeam(unitID), maxDronesOverride)
end
-- communicates to unitscript, copied from unit_float_toggle; should be extracted to utility
-- preferably that before i PR this
local function callScript(unitID, funcName, args)
local func = Spring.UnitScript.GetScriptEnv(unitID)[funcName]
if func then
Spring.UnitScript.CallAsUnit(unitID, func, args)
end
end
local function NewDrone(unitID, droneName, setNum, droneBuiltExternally)
local carrierEntry = carrierList[unitID]
local _, _, _, x, y, z = GetUnitPosition(unitID, true)
local xS, yS, zS = x, y, z
local rot = 0
local piece = nil
if carrierEntry.spawnPieces and not droneBuiltExternally then
local index = carrierEntry.pieceIndex
piece = carrierEntry.spawnPieces[index];
local px, py, pz, pdx, pdy, pdz = GetUnitPiecePosDir(unitID, piece)
xS, yS, zS = px, py, pz
rot = Spring.GetHeadingFromVector(pdx, pdz)/65536*2*math.pi + math.pi
index = index + 1
if index > #carrierEntry.spawnPieces then
index = 1
end
carrierEntry.pieceIndex = index
else
local angle = math.rad(random(1, 360))
xS = (x + (math.sin(angle) * 20))
zS = (z + (math.cos(angle) * 20))
rot = angle
end
--Note: create unit argument: (unitDefID|unitDefName, x, y, z, facing, teamID, build, flattenGround, targetID, builderID)
local droneID = CreateUnit(droneName, xS, yS, zS, 1, carrierList[unitID].teamID, droneBuiltExternally and true, false, nil, unitID)
if droneID then
Spring.SetUnitRulesParam(droneID, "parent_unit_id", unitID)
Spring.SetUnitRulesParam(droneID, "drone_set_index", setNum)
local droneSet = carrierEntry.droneSets[setNum]
droneSet.droneCount = droneSet.droneCount + 1
ChangeDroneRulesParam(unitID, 1)
droneSet.drones[droneID] = true
--SetUnitPosition(droneID, xS, zS, true)
Spring.MoveCtrl.Enable(droneID)
Spring.MoveCtrl.SetPosition(droneID, xS, yS, zS)
--Spring.MoveCtrl.SetRotation(droneID, 0, rot, 0)
Spring.MoveCtrl.Disable(droneID)
Spring.SetUnitCOBValue(droneID, 82, (rot - math.pi)*65536/2/math.pi)
local states = Spring.GetUnitStates(unitID) or emptyTable
GiveOrderToUnit(droneID, CMD.MOVE_STATE, { 2 }, 0)
GiveOrderToUnit(droneID, CMD.FIRE_STATE, { states.movestate }, 0)
GiveOrderToUnit(droneID, CMD.IDLEMODE, { 0 }, 0)
local rx, rz = RandomPointInUnitCircle()
-- Drones intentionall use CMD.MOVE instead of CMD_RAW_MOVE as they do not require any of the features
GiveClampedOrderToUnit(droneID, CMD.MOVE, {x + rx*IDLE_DISTANCE, y+DRONE_HEIGHT, z + rz*IDLE_DISTANCE}, 0)
GiveOrderToUnit(droneID, CMD.GUARD, {unitID} , CMD.OPT_SHIFT)
SetUnitNoSelect(droneID, true)
droneList[droneID] = {carrier = unitID, set = setNum}
end
return droneID, rot
end
--START OF----------------------------
--drone nanoframe attachment code:----
function AddUnitToEmptyPad(carrierID, droneType)
local carrierData = carrierList[carrierID]
local unitIDAdded
local CheckCreateStart = function(pieceNum)
if not carrierData.occupiedPieces[pieceNum] then -- Note: We could do a strict checking of empty space here (Spring.GetUnitInBox()) before spawning drone, but that require a loop to check if & when its empty.
local droneDefID = carrierData.droneSets[droneType].config.drone
unitIDAdded = NewDrone(carrierID, droneDefID, droneType, true)
if unitIDAdded then
local offsets = carrierData.droneSets[droneType].config.offsets
SitOnPad(unitIDAdded, carrierID, pieceNum, offsets)
carrierData.occupiedPieces[pieceNum] = true
if carrierData.droneSets[droneType].config.colvolTweaked then --can be used to move collision volume away from carrier to avoid collision
Spring.SetUnitMidAndAimPos(unitIDAdded, offsets.colvolMidX, offsets.colvolMidY, offsets.colvolMidZ, offsets.aimX, offsets.aimY, offsets.aimZ, true)
--offset whole colvol & aim point (red dot) above the carrier (use /debugcolvol to check)
end
return true
end
end
return false
end
if carrierList[carrierID].spawnPieces then --have airpad or emit point
for i=1, #carrierList[carrierID].spawnPieces do
local pieceNum = carrierList[carrierID].spawnPieces[i]
if CheckCreateStart(pieceNum) then
--- notify carrier that it should start a drone building animation
callScript(carrierID, "Carrier_droneStarted", pieceNum)
break
end
end
else
CheckCreateStart(0) --use unit's body as emit point
end
return unitIDAdded
end
local coroutines = {}
local coroutineCount = 0
local coroutine = coroutine
local Sleep = coroutine.yield
local assert = assert
local function StartScript(fn)
local co = coroutine.create(fn)
coroutineCount = coroutineCount + 1 --in case new co-routine is added in same frame
coroutines[coroutineCount] = co
end
function UpdateCoroutines()
coroutineCount = #coroutines
local i = 1
while (i <= coroutineCount) do
local co = coroutines[i]
if (coroutine.status(co) ~= "dead") then
assert(coroutine.resume(co))
i = i + 1
else
coroutines[i] = coroutines[coroutineCount]
coroutines[coroutineCount] = nil
coroutineCount = coroutineCount - 1
end
end
end
local function GetPitchYawRoll(front, top) --This allow compatibility with Spring 91
--NOTE:
--angle measurement and direction setting is based on right-hand coordinate system, but Spring might rely on left-hand coordinate system.
--So, input for math.sin and math.cos, or positive/negative sign, or math.atan2 might be swapped with respect to the usual whenever convenient.
--1) Processing FRONT's vector to get Pitch and Yaw
local x, y, z = front[1], front[2], front[3]
local xz = math.sqrt(x*x + z*z) --hypothenus
local yaw = math.atan2 (x/xz, z/xz) --So facing south is 0-radian, and west is negative radian, and east is positive radian
local pitch = math.atan2 (y, xz) --So facing upward is positive radian, and downward is negative radian
--2) Processing TOP's vector to get Roll
x, y, z = top[1], top[2], top[3]
--rotate coordinate around Y-axis until Yaw value is 0 (a reset)
local newX = x* math.cos (-yaw) + z* math.sin (-yaw)
local newY = y
local newZ = z* math.cos (-yaw) - x* math.sin (-yaw)
x, y, z = newX, newY, newZ
--rotate coordinate around X-axis until Pitch value is 0 (a reset)
newX = x
newY = y* math.cos (-pitch) + z* math.sin (-pitch)
newZ = z* math.cos (-pitch) - y* math.sin (-pitch)
x, y, z = newX, newY, newZ
local roll = math.atan2 (x, y) --So lifting right wing is positive radian, and lowering right wing is negative radian
return pitch, yaw, roll
end
local function GetOffsetRotated(rx, ry, rz, front, top, right)
local offX = front[1]*rz + top[1]*ry - right[1]*rx
local offY = front[2]*rz + top[2]*ry - right[2]*rx
local offZ = front[3]*rz + top[3]*ry - right[3]*rx
return offX, offY, offZ
end
local HEADING_TO_RAD = (math.pi*2/2^16)
local RAD_TO_HEADING = 1/HEADING_TO_RAD
local PI = math.pi
local cos = math.cos
local sin = math.sin
local acos = math.acos
local floor = math.floor
local sqrt = math.sqrt
local exp = math.exp
local min = math.min
local mcSetVelocity = Spring.MoveCtrl.SetVelocity
local mcSetRotationVelocity = Spring.MoveCtrl.SetRotationVelocity
local mcSetPosition = Spring.MoveCtrl.SetPosition
local mcSetRotation = Spring.MoveCtrl.SetRotation
local mcDisable = Spring.MoveCtrl.Disable
local mcEnable = Spring.MoveCtrl.Enable
local function GetBuildRate(unitID)
if not generateDrones[unitID] then
return 0
end
local stunned_or_inbuild = GetUnitIsStunned(unitID) or (spGetUnitRulesParam(unitID, "disarmed") == 1)
if stunned_or_inbuild then
return 0
end
return spGetUnitRulesParam(unitID, "totalReloadSpeedChange") or 1
end
function SitOnPad(unitID, carrierID, padPieceID, offsets)
-- From unit_refuel_pad_handler.lua (author: GoogleFrog)
-- South is 0 radians and increases counter-clockwise
Spring.SetUnitHealth(unitID, {build = 0})
local GetPlacementPosition = function(inputID, pieceNum)
if (pieceNum == 0) then
local _, _, _, mx, my, mz = Spring.GetUnitPosition(inputID, true)
local dx, dy, dz = Spring.GetUnitDirection(inputID)
return mx, my, mz, dx, dy, dz
else
return Spring.GetUnitPiecePosDir(inputID, pieceNum)
end
end
local AddNextDroneFromQueue = function(inputID)
if #carrierList[inputID].droneInQueue > 0 then
if AddUnitToEmptyPad(inputID, carrierList[inputID].droneInQueue[1]) then --pad cleared, immediately add any unit from queue
table.remove(carrierList[inputID].droneInQueue, 1)
end
end
end
mcEnable(unitID)
Spring.SetUnitLeaveTracks(unitID, false)
Spring.SetUnitBlocking(unitID, false, false, true, true, false, true, false)
mcSetVelocity(unitID, 0, 0, 0)
mcSetPosition(unitID, GetPlacementPosition(carrierID, padPieceID))
-- deactivate unit to cause the lups jets away
Spring.SetUnitCOBValue(unitID, COB.ACTIVATION, 0)
local function SitLoop()
local previousDir, currentDir
local pitch, yaw, roll, pitch, yaw, roll
local px, py, pz, dx, dy, dz, vx, vy, vz, offx, offy, offz
-- local magnitude, newPadHeading
local miscPriorityKey = "drone_" .. unitID
local oldBuildRate = false
local buildProgress, health
local droneType = droneList[unitID].set
local droneInfo = carrierList[carrierID].droneSets[droneType] --may persist even after "carrierList[carrierID]" is emptied
local build_step = droneInfo.config.buildStep
local build_step_health = droneInfo.config.buildStepHealth
local buildStepCost = droneInfo.config.buildStepCost
local perSecondCost = droneInfo.config.perSecondCost
local resTable
if buildStepCost then
resTable = {
m = buildStepCost,
e = buildStepCost,
}
end
while true do
if (not droneList[unitID]) then --droneList[unitID] became NIL when drone or carrier is destroyed (in UnitDestroyed()). Is NIL at beginning of frame and this piece of code run at end of frame
if carrierList[carrierID] then
droneInfo.buildCount = droneInfo.buildCount - 1
carrierList[carrierID].occupiedPieces[padPieceID] = false
AddNextDroneFromQueue(carrierID) --add next drone in this vacant position
GG.StopMiscPriorityResourcing(carrierID, miscPriorityKey)
end
return --nothing else to do
elseif (not carrierList[carrierID]) then --carrierList[carrierID] is NIL because it was MORPHED.
carrierID = droneList[unitID].carrier
padPieceID = (carrierList[carrierID].spawnPieces and carrierList[carrierID].spawnPieces[1]) or 0
carrierList[carrierID].occupiedPieces[padPieceID] = true --block pad
oldBuildRate = false -- Update MiscPriority for morphed unit.
end
vx, vy, vz = Spring.GetUnitVelocity(carrierID)
px, py, pz, dx, dy, dz = GetPlacementPosition(carrierID, padPieceID)
currentDir = dx + dy*100 + dz* 10000
if previousDir ~= currentDir then --refresh pitch/yaw/roll calculation when unit had slight turning
previousDir = currentDir
front, top, right = Spring.GetUnitVectors(carrierID)
pitch, yaw, roll = GetPitchYawRoll(front, top)
offx, offy, offz = GetOffsetRotated(offsets[1], offsets[2], offsets[3], front, top, right)
end
mcSetVelocity(unitID, vx, vy, vz)
mcSetPosition(unitID, px + vx + offx, py + vy + offy, pz + vz + offz)
mcSetRotation(unitID, -pitch, yaw, -roll) --Spring conveniently rotate Y-axis first, X-axis 2nd, and Z-axis 3rd which allow Yaw, Pitch & Roll control.
local buildRate = GetBuildRate(carrierID)
if perSecondCost and oldBuildRate ~= buildRate then
oldBuildRate = buildRate
GG.StartMiscPriorityResourcing(carrierID, perSecondCost*buildRate, false, miscPriorityKey)
resTable.m = buildStepCost*buildRate
resTable.e = buildStepCost*buildRate
end
-- Check if the change can be carried out
if (buildRate > 0) and ((not perSecondCost) or (GG.AllowMiscPriorityBuildStep(carrierID, Spring.GetUnitTeam(carrierID), false, resTable) and Spring.UseUnitResource(carrierID, resTable))) then
health, _, _, _, buildProgress = Spring.GetUnitHealth(unitID)
buildProgress = buildProgress + (build_step*buildRate) --progress
Spring.SetUnitHealth(unitID, {health = health + (build_step_health*buildRate), build = buildProgress})
if buildProgress >= 1 then
callScript(carrierID, "Carrier_droneCompleted", padPieceID)
break
end
end
Sleep()
end
GG.StopMiscPriorityResourcing(carrierID, miscPriorityKey)
droneInfo.buildCount = droneInfo.buildCount - 1
carrierList[carrierID].occupiedPieces[padPieceID] = false
Spring.SetUnitLeaveTracks(unitID, true)
Spring.SetUnitVelocity(unitID, 0, 0, 0)
Spring.SetUnitBlocking(unitID, false, true, true, true, false, true, false)
mcDisable(unitID)
GG.UpdateUnitAttributes(unitID) --update pending attribute changes in unit_attributes.lua if available
if droneInfo.config.colvolTweaked then
Spring.SetUnitMidAndAimPos(unitID, 0, 0, 0, 0, 0, 0, true)
end
-- activate unit and its jets
Spring.SetUnitCOBValue(unitID, COB.ACTIVATION, 1)
AddNextDroneFromQueue(carrierID) --this create next drone in this position (in this same GameFrame!), so it might look overlapped but that's just minor details
end
StartScript(SitLoop)
end
--drone nanoframe attachment code------
--END----------------------------------
-- morph uses this
--[[
local function transferCarrierData(unitID, unitDefID, unitTeam, newUnitID)
-- UnitFinished (above) should already be called for this new unit.
if carrierList[newUnitID] then
carrierList[newUnitID] = Spring.Utilities.CopyTable(carrierList[unitID], true) -- deep copy?
-- old carrier data removal (transfering drones to new carrier, old will "die" (on morph) silently without taking drones together to the grave)...
local carrier = carrierList[unitID]
for i=1, #carrier.droneSets do
local set = carrier.droneSets[i]
for droneID in pairs(set.drones) do
droneList[droneID].carrier = newUnitID
GiveOrderToUnit(droneID, CMD.GUARD, {newUnitID} , CMD.OPT_SHIFT)
end
end
carrierList[unitID] = nil
end
end
--]]
local function isCarrier(unitID)
if (carrierList[unitID]) then
return true
end
return false
end
-- morph uses this
GG.isCarrier = isCarrier
--GG.transferCarrierData = transferCarrierData
local function GetDistance(x1, x2, y1, y2)
return ((x1-x2)^2 + (y1-y2)^2)^0.5
end
local function UpdateCarrierTarget(carrierID, frame)
local cQueueC = GetCommandQueue(carrierID, 1)
local droneSendDistance = nil
local px, py, pz
local target
local recallDrones = false
local attackOrder = false
local setTargetOrder = false
--checks if there is an active recall order
local recallFrame = spGetUnitRulesParam(carrierID,"recall_frame_start")
if recallFrame then
if frame > recallFrame + RECALL_TIMEOUT then
--recall has expired
spSetUnitRulesParam(carrierID,"recall_frame_start",nil)
else
recallDrones = true
end
end
--Handles an attack order given to the carrier.
if not recallDrones and cQueueC and cQueueC[1] and cQueueC[1].id == CMD_ATTACK then
local ox, oy, oz = GetUnitPosition(carrierID)
local params = cQueueC[1].params
if #params == 1 then
target = {params[1]}
px, py, pz = GetUnitPosition(params[1])
else
px, py, pz = cQueueC[1].params[1], cQueueC[1].params[2], cQueueC[1].params[3]
end
if px then
droneSendDistance = GetDistance(ox, px, oz, pz)
end
attackOrder = true --attack order overrides set target
end
--Handles a setTarget order given to the carrier.
if not recallDrones and not attackOrder then
local targetType = spGetUnitRulesParam(carrierID,"target_type")
if targetType and targetType > 0 then
local ox, oy, oz = GetUnitPosition(carrierID)
if targetType == 1 then --targeting ground
px, py, pz = spGetUnitRulesParam(carrierID,"target_x"), spGetUnitRulesParam(carrierID,"target_y"), spGetUnitRulesParam(carrierID,"target_z")
end
if targetType == 2 then --targeting units
local target_id = spGetUnitRulesParam(carrierID,"target_id")
target = {target_id}
px, py, pz = GetUnitPosition(target_id)
end
if px then
droneSendDistance = GetDistance(ox, px, oz, pz)
end
setTargetOrder = true
end
end
local states = Spring.GetUnitStates(carrierID) or emptyTable
local holdfire = states.firestate == 0
local rx, rz
for i = 1, #carrierList[carrierID].droneSets do
local set = carrierList[carrierID].droneSets[i]
local tempCONTAINER
for droneID in pairs(set.drones) do
tempCONTAINER = droneList[droneID]
droneList[droneID] = nil -- to keep AllowCommand from blocking the order
local droneStates = Spring.GetUnitStates(carrierID) or emptyTable
if attackOrder or setTargetOrder then
-- drones fire at will if carrier has an attack/target order
-- a drone bomber probably should not do this
GiveOrderToUnit(droneID, CMD.FIRE_STATE, { 2 }, 0)
else
-- update firestate based on that of carrier
GiveOrderToUnit(droneID, CMD.FIRE_STATE, { states.firestate }, 0)
end
if recallDrones then
-- move drones to carrier
px, py, pz = GetUnitPosition(carrierID)
rx, rz = RandomPointInUnitCircle()
GiveClampedOrderToUnit(droneID, CMD.MOVE, {px + rx*IDLE_DISTANCE, py+DRONE_HEIGHT, pz + rz*IDLE_DISTANCE}, 0)
GiveOrderToUnit(droneID, CMD.GUARD, {carrierID} , CMD.OPT_SHIFT)
elseif droneSendDistance and droneSendDistance < set.config.range then
-- attacking
if target then
GiveOrderToUnit(droneID, CMD.ATTACK, target, 0)
else
rx, rz = RandomPointInUnitCircle()
GiveClampedOrderToUnit(droneID, CMD.FIGHT, {px + rx*ACTIVE_DISTANCE, py+DRONE_HEIGHT, pz + rz*ACTIVE_DISTANCE}, 0)
end
else
-- return to carrier unless in combat
local cQueue = GetCommandQueue(droneID, -1)
local engaged = false
for i=1, (cQueue and #cQueue or 0) do
if cQueue[i].id == CMD.FIGHT and droneStates.firestate > 0 then
-- if currently fighting AND not on hold fire
engaged = true
break
end
end
if not engaged then
px, py, pz = GetUnitPosition(carrierID)
rx, rz = RandomPointInUnitCircle()
GiveClampedOrderToUnit(droneID, holdfire and CMD.MOVE or CMD.FIGHT, {px + rx*IDLE_DISTANCE, py+DRONE_HEIGHT, pz + rz*IDLE_DISTANCE}, 0)
GiveOrderToUnit(droneID, CMD.GUARD, {carrierID} , CMD.OPT_SHIFT)
end
end
droneList[droneID] = tempCONTAINER
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function ToggleDronesCommand(unitID, newState)
local cmdDescID = Spring.FindUnitCmdDesc(unitID, CMD_TOGGLE_DRONES)
if (cmdDescID) then
toggleParams.params[1] = newState
Spring.EditUnitCmdDesc(unitID, cmdDescID, toggleParams)
generateDrones[unitID] = (newState == 1)
end
end
function gadget:AllowCommand_GetWantedCommand()
return true
end
function gadget:AllowCommand_GetWantedUnitDefID()
return true
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if droneList[unitID] then
return false
end
if not carrierList[unitID] then
return true
end
if cmdID == CMD_TOGGLE_DRONES then
ToggleDronesCommand(unitID, cmdParams[1])
return false
end
if (cmdID == CMD.ATTACK or cmdID == CMD.FIGHT or cmdID == CMD.PATROL or cmdID == CMD_UNIT_SET_TARGET or cmdID == CMD_UNIT_SET_TARGET_CIRCLE) then
spSetUnitRulesParam(unitID,"recall_frame_start",nil)
return true
end
if (cmdID == CMD_RECALL_DRONES) then
-- Gives drones a command to recall to the carrier
for i = 1, #carrierList[unitID].droneSets do
local set = carrierList[unitID].droneSets[i]
for droneID in pairs(set.drones) do
px, py, pz = GetUnitPosition(unitID)
local temp = droneList[droneID]
droneList[droneID] = nil -- to keep AllowCommand from blocking the order
local rx, rz = RandomPointInUnitCircle()
GiveClampedOrderToUnit(droneID, CMD.MOVE, {px + rx*IDLE_DISTANCE, py+DRONE_HEIGHT, pz + rz*IDLE_DISTANCE}, 0)
GiveOrderToUnit(droneID, CMD.GUARD, {unitID} , CMD.OPT_SHIFT)
droneList[droneID] = temp
end
end
frame = spGetGameFrame()
spSetUnitRulesParam(unitID,"recall_frame_start",frame)
return false
end
return true
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
if (carrierList[unitID]) then
local newUnitID = GG.wasMorphedTo and GG.wasMorphedTo[unitID]
local carrier = carrierList[unitID]
if newUnitID and carrierList[newUnitID] then --MORPHED, and MORPHED to another carrier. Note: unit_morph.lua create unit first before destroying it, so "carrierList[]" is already initialized.
local newCarrier = carrierList[newUnitID]
ToggleDronesCommand(newUnitID, ((generateDrones[unitID] ~= false) and 1) or 0)
for i = 1, #carrier.droneSets do
local set = carrier.droneSets[i]
local newSetID = -1
local droneCount = 0
for j = 1, #newCarrier.droneSets do
if newCarrier.droneSets[j].config.drone == set.config.drone then --same droneType? copy old drone data
newCarrier.droneSets[j].droneCount = set.droneCount
droneCount = droneCount + set.droneCount
newCarrier.droneSets[j].reload = set.reload
newCarrier.droneSets[j].drones = set.drones
newSetID = j
end
end
ChangeDroneRulesParam(newUnitID, droneCount)
for droneID in pairs(set.drones) do
droneList[droneID].carrier = newUnitID
droneList[droneID].set = newSetID
GiveOrderToUnit(droneID, CMD.GUARD, {newUnitID} , CMD.OPT_SHIFT)
end
end
else --Carried died
for i = 1, #carrier.droneSets do
local set = carrier.droneSets[i]
for droneID in pairs(set.drones) do
droneList[droneID] = nil
killList[droneID] = true
end
end
end
generateDrones[unitID] = nil
carrierList[unitID] = nil
elseif (droneList[unitID]) then
local carrierID = droneList[unitID].carrier
local setID = droneList[unitID].set
if setID > -1 then --is -1 when carrier morphed and drone is incompatible with the carrier
local droneSet = carrierList[carrierID].droneSets[setID]
droneSet.droneCount = (droneSet.droneCount - 1)
ChangeDroneRulesParam(carrierID, -1)
droneSet.drones[unitID] = nil
end
droneList[unitID] = nil
end
end
function gadget:UnitCreated(unitID, unitDefID, unitTeam)
if (carrierDefs[unitDefID]) then
CreateCarrier(unitID)
end
end
function gadget:UnitFinished(unitID, unitDefID, unitTeam)
if Spring.GetUnitRulesParam(unitID, "comm_level") then
Drones_InitializeDynamicCarrier(unitID)
end
if (carrierDefs[unitDefID]) and not carrierList[unitID] then
carrierList[unitID] = InitCarrier(unitID, carrierDefs[unitDefID], unitTeam)
end
end
function gadget:UnitGiven(unitID, unitDefID, newTeam)
if carrierList[unitID] then
carrierList[unitID].teamID = newTeam
for i = 1, #carrierList[unitID].droneSets do
local set = carrierList[unitID].droneSets[i]
for droneID, _ in pairs(set.drones) do
-- Only transfer drones which are allied with the carrier. This is to
-- make carriers and capture interact in a robust, simple way. A captured
-- drone will take up a slot on the carrier and attack the carriers allies.
-- A captured carrier will need to have its drones killed or captured to
-- free up slots.
local droneTeam = Spring.GetUnitTeam(droneID)
if droneTeam and Spring.AreTeamsAllied(droneTeam, newTeam) then
drones_to_move[droneID] = newTeam
end
end
end
end
end
function gadget:GameFrame(n)
if (((n+1) % 30) == 0) then
for carrierID, carrier in pairs(carrierList) do
if (not GetUnitIsStunned(carrierID)) then
for i = 1, #carrier.droneSets do
local set = carrier.droneSets[i]
if (set.reload > 0) then
local reloadMult = spGetUnitRulesParam(carrierID, "totalReloadSpeedChange") or 1
set.reload = (set.reload - reloadMult)
elseif (set.droneCount < set.maxDrones) and set.buildCount < set.config.maxBuild then --not reach max count and finished previous queue
if generateDrones[carrierID] then
for n = 1, set.config.spawnSize do
if (set.droneCount >= set.maxDrones) then
break
end
carrierList[carrierID].droneInQueue[ #carrierList[carrierID].droneInQueue + 1 ] = i
if AddUnitToEmptyPad(carrierID, i ) then
set.buildCount = set.buildCount + 1;
table.remove(carrierList[carrierID].droneInQueue, 1)
end
end
set.reload = set.config.reloadTime -- apply reloadtime when queuing construction (not when it actually happens) - helps keep a constant creation rate over time
end
end
end
end
end
for droneID, team in pairs(drones_to_move) do
TransferUnit(droneID, team, false)
drones_to_move[droneID] = nil
end
for unitID in pairs(killList) do
Spring.DestroyUnit(unitID, true)
killList[unitID] = nil
end
end
if ((n % DEFAULT_UPDATE_ORDER_FREQUENCY) == 0) then
for i, _ in pairs(carrierList) do
UpdateCarrierTarget(i, n)
end
end
UpdateCoroutines() --maintain nanoframe position relative to carrier
end
function gadget:Initialize()
gadgetHandler:RegisterCMDID(CMD_RECALL_DRONES)
gadgetHandler:RegisterCMDID(CMD_TOGGLE_DRONES)
GG.Drones_InitializeDynamicCarrier = Drones_InitializeDynamicCarrier
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
local team = Spring.GetUnitTeam(unitID)
gadget:UnitCreated(unitID, unitDefID, team)
local build = select(5, Spring.GetUnitHealth(unitID))
if build == 1 then
gadget:UnitFinished(unitID, unitDefID, team)
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Save/Load
local function LoadDrone(unitID, parentID)
Spring.DestroyUnit(unitID, false, true)
end
function gadget:Load(zip)
for _, unitID in ipairs(Spring.GetAllUnits()) do
local parentID = Spring.GetUnitRulesParam(unitID, "parent_unit_id")
if parentID then
LoadDrone(unitID, parentID)
end
end
end
| gpl-2.0 |
Paaskehare/SurvivalTD | game/survival_td/scripts/vscripts/gamemode.lua | 1 | 28647 | -- This is the primary barebones gamemode script and should be used to assist in initializing your game mode
-- Set this to true if you want to see a complete debug output of all events/processes done by barebones
-- You can also change the cvar 'barebones_spew' at any time to 1 or 0 for output/no output
BAREBONES_DEBUG_SPEW = false
if GameMode == nil then
DebugPrint( '[BAREBONES] creating barebones game mode' )
_G.GameMode = class({})
end
-- This library allow for easily delayed/timed actions
require('libraries/timers')
-- This library can be used for advancted physics/motion/collision of units. See PhysicsReadme.txt for more information.
require('libraries/physics')
-- This library can be used for advanced 3D projectile systems.
require('libraries/projectiles')
-- This library can be used for sending panorama notifications to the UIs of players/teams/everyone
require('libraries/notifications')
-- These internal libraries set up barebones's events and processes. Feel free to inspect them/change them if you need to.
require('internal/gamemode')
require('internal/events')
-- settings.lua is where you can specify many different properties for your game mode and is one of the core barebones files.
require('settings')
-- events.lua is where you can specify the actions to be taken when any event occurs and is one of the core barebones files.
require('events')
require('mechanics')
-- "preload" the upgrade tower ability, so we can extend that in other upgrade abilities
require('abilities/upgrade_tower')
--[[
This function should be used to set up Async precache calls at the beginning of the gameplay.
In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made
after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also
be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will
precache the precache{} block statement of the unit and all precache{} block statements for every Ability#
defined on the unit.
This function should only be called once. If you want to/need to precache more items/abilities/units at a later
time, you can call the functions individually (for example if you want to precache units in a new wave of
holdout).
This function should generally only be used if the Precache() function in addon_game_mode.lua is not working.
]]
function GameMode:PostLoadPrecache()
DebugPrint("[BAREBONES] Performing Post-Load precache")
--PrecacheItemByNameAsync("item_example_item", function(...) end)
--PrecacheItemByNameAsync("example_ability", function(...) end)
--PrecacheUnitByNameAsync("npc_dota_hero_viper", function(...) end)
--PrecacheUnitByNameAsync("npc_dota_hero_enigma", function(...) end)
end
--[[
This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in.
It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in.
]]
function GameMode:OnFirstPlayerLoaded()
DebugPrint("[BAREBONES] First Player has loaded")
end
--[[
This function is called once and only once after all players have loaded into the game, right as the hero selection time begins.
It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc)
]]
function GameMode:OnAllPlayersLoaded()
DebugPrint("[BAREBONES] All Players have loaded into the game")
end
function GameMode:PromptError(player, message, sound)
sound = sound or "General.CantAttack"
EmitSoundOnClient(sound, player)
CustomGameEventManager:Send_ServerToPlayer( player, "custom_error_message", {message = message} )
end
function GameMode:IsWithinTeamBounds(team, position)
local bounds = GameMode.TeamBoundaries[team]
if bounds then
return (bounds.nw and bounds.se and
position.x > bounds.nw.x and position.x < bounds.se.x and
position.y < bounds.nw.y and position.y > bounds.se.y)
end
return false
end
--[[
This function is called once and only once for every player when they spawn into the game for the first time. It is also called
if the player's hero is replaced with a new hero for any reason. This function is useful for initializing heroes, such as adding
levels, changing the starting gold, removing/adding abilities, adding physics, etc.
The hero parameter is the hero entity that just spawned in
]]
function GameMode:OnHeroInGame(hero)
DebugPrint("[BAREBONES] Hero spawned in game for first time -- " .. hero:GetUnitName())
local player = hero:GetPlayerOwner()
if player == nil then return end
--local EntPlayerID = GameMode.TeamToEntPlayer[player:GetTeam()]
DebugPrint("setting tower queue")
player.vTowerQueue = nil
DebugPrint("setting initial gold")
-- This line for example will set the starting gold of every hero to 100 unreliable gold
hero:SetGold(GameMode.InitialGold, false)
-- apply physics
Physics:Unit(hero)
DebugPrint("adding modifier")
hero:AddNewModifier(hero, nil, "modifier_movespeed_cap", {})
DebugPrint("setting auto unstuck")
hero:SetAutoUnstuck(false)
DebugPrint("setting ground behavior")
hero:SetGroundBehavior(PHYSICS_GROUND_NOTHING)
DebugPrint("setting nav collission type")
hero:SetNavCollisionType(PHYSICS_NAV_NONE)
DebugPrint("setting hero killed last wave")
hero.killedLastWave = false
--if EntPlayerID then
-- local ent_bounds_ne = Entities:FindByName(nil, "player" .. EntPlayerID .. "_bound_ne"):GetAbsOrigin()
-- local ent_bounds_sw = Entities:FindByName(nil, "player" .. EntPlayerID .. "_bound_sw")
-- hero.bounds_ne = ent_bounds_ne:GetAbsOrigin()
-- hero.bounds_sw = ent_bounds_sw:GetAbsOrigin()
--end
DebugPrint("creating timer")
Timers:CreateTimer(function()
local position = hero:GetAbsOrigin()
hero:SetAbsOrigin(Vector(position.x, position.y, 500))
return .03
end)
DebugPrint("leveling abilities")
local buildAbility = hero:FindAbilityByName("build_tower")
local upgradeAbility = hero:FindAbilityByName("upgrade_tier")
local invincibilityAbility = hero:FindAbilityByName("custom_ability_invincibility")
--hero:UpgradeAbility(buildAbility)
if buildAbility ~= nil then buildAbility:SetLevel(1) end
if upgradeAbility ~= nil then upgradeAbility:SetLevel(1) end
if invincibilityAbility ~= nil then invincibilityAbility:SetLevel(1) end
DebugPrint("resetting ability points")
hero:SetAbilityPoints(0)
--[[ --These lines if uncommented will replace the W ability of any hero that loads into the game
--with the "example_ability" ability
local abil = hero:GetAbilityByIndex(1)
hero:RemoveAbility(abil:GetAbilityName())
hero:AddAbility("example_ability")]]
end
function GameMode:SnapToBuildGrid(target)
local UnitWidth = 128
local UnitWidthHalf = UnitWidth / 2
local x = UnitWidthHalf * math.floor((target.x + 0.5) / UnitWidthHalf) + (UnitWidthHalf / 2)
local y = UnitWidthHalf * math.floor((target.y + 0.5) / UnitWidthHalf) + (UnitWidthHalf / 2)
local pos = Vector(x, y, GameMode.BuildGridHeight)
--[[DebugDrawBox(
pos,
Vector(-UnitWidthHalf, -UnitWidthHalf, 0), --Vector(pos.x - 32, pos.y - 32, pos.z),
Vector(UnitWidthHalf, UnitWidthHalf, UnitWidthHalf), --Vector(pos.x + 32, pos.y + 32, pos.z + 32),
200, 0, 0, 5,
1.0
)--]]
return pos
end
function GameMode:IsFlyingWave(wave)
for i=0,#GameMode.FlyingWaves do
if GameMode.FlyingWaves[i] == wave then
return true
end
end
return false
end
function GameMode:IsBossWave(wave)
for i=0,#GameMode.BossWaves do
if GameMode.BossWaves[i] == wave then
return true
end
end
return false
end
function GameMode:SpawnCreepWave(unit, player, round)
local round = round or 0
local EntTeamID = GameMode.TeamToEntTeam[player:GetTeam()]
local strTeamID = tostring(player:GetTeam())
local spawn = Entities:FindByName(nil, "player" .. EntTeamID .. "_wavespawner")
local waypoint = Entities:FindByName(nil, "player" .. EntTeamID .. "_waypoint1")
local spawnLocation = spawn:GetAbsOrigin()
local i = 0
-- Only spawn one unit if it's a boss wave
local creepCount = (not GameMode:IsBossWave(unit)) and GameMode.CreepCount or 1
local healthMultiplier = GameMode.DifficultyHealth[ GameMode.TeamDifficulty[strTeamID] ]
Timers:CreateTimer(function()
if i < creepCount then
local creep = CreateUnitByName(unit, spawnLocation, true, nil, nil, DOTA_TEAM_NOTEAM)
-- difficulty level doesnt kick in until level 3
if round > 2 and healthMultiplier > 1.0 then
local health = creep:GetBaseMaxHealth() * healthMultiplier
creep:SetBaseMaxHealth(health)
creep:SetMaxHealth(health)
creep:SetHealth(health)
end
creep:SetForwardVector(Vector(-1, 0, 0)) -- make the creeps point west when spawning
creep:SetInitialGoalEntity(waypoint)
i = i + 1
return .5
end
end)
end
function GameMode:FormatWaveAnnounce(wave)
local isBoss = GameMode:IsBossWave(wave)
local isFlying = GameMode:IsFlyingWave(wave)
return string.format("<font color=\"#00aeff\">%s</font>%s%s",
wave,
(isBoss and " (<font color=\"#be7fe5\">Boss</font>)" or ""),
(isFlying and " (<font color=\"#ff8800\">Flying</font>)" or "")
)
end
function GameMode:SpawnNextWave(team, delay)
local delay = delay or 0
local heroes = HeroList:GetAllHeroes()
local EntTeamID = GameMode.TeamToEntTeam[team]
local strTeamID = tostring(team)
print("[SurvivalTD] " ..strTeamID)
local waveInfo = GameMode.WaveInfo[strTeamID]
if not waveInfo then return end
local CurrentGameTime = GameRules:GetGameTime()
waveInfo.Round = waveInfo.Round + 1
local CurrentRound = waveInfo.Round
if CurrentRound > GameMode.TotalRounds then return end
waveInfo.UnitName = "creep_wave_" .. CurrentRound
waveInfo.Count = (not GameMode:IsBossWave(waveInfo.UnitName)) and GameMode.CreepCount or 1
local NextRoundName = "creep_wave_" .. (CurrentRound + 1)
CustomNetTables:SetTableValue( "game_state", "teamstate", GameMode.WaveInfo )
--if GameMode:IsFlyingWave(NextRoundName) then
-- GameRules:SendCustomMessage("Next Round is Air! - Build some air towers now if you haven't already", 1, 1)
--elseif GameMode:IsBossWave(NextRoundName) then
-- GameRules:SendCustomMessage("Next Round is a boss wave! Only one enemy, but huge bounty", 1, 1)
--end
local IsNextFlying = GameMode:IsFlyingWave(NextRoundName)
local IsNextBoss = GameMode:IsBossWave(NextRoundName)
-- Next round starts
-- make sure we don't go past the previous nextroundtime
if waveInfo.NextRoundTime > 0 and ((CurrentGameTime + delay) > waveInfo.NextRoundTime) then
delay = (CurrentGameTime + delay) - waveInfo.NextRoundTime
end
Timers:CreateTimer(delay, function()
waveInfo.NextRoundTime = CurrentGameTime + GameMode.RoundTime
for _,player in pairs(GameMode:GetPlayersOnTeam(team)) do
local hero = player:GetAssignedHero()
if hero and hero:IsAlive() then
-- the builder starts with the initial gold for round 1
print("[SurvivalTD] Checking if round is above one")
if CurrentRound > 1 then
hero:SetGold(hero:GetGold() + GameMode.GoldPerRound, false)
end
-- Spawn the wave
print("[SurvivalTD] Spawning the wave")
GameMode:SpawnCreepWave(waveInfo.UnitName, player, CurrentRound)
if IsNextFlying or IsNextBoss then
CustomGameEventManager:Send_ServerToPlayer( player, "team_notification", {
message = IsNextFlying and "custom_game_next_wave_flying" or "custom_game_next_wave_boss"
})
if NextRoundName == GameMode.FlyingWaves[1] then
CustomGameEventManager:Send_ServerToPlayer( player, "team_notification", {
message = IsNextFlying and "custom_game_next_wave_flying_tip"
})
end
if NextRoundName == GameMode.BossWaves[1] then
CustomGameEventManager:Send_ServerToPlayer( player, "team_notification", {
message = IsNextFlying and "custom_game_next_wave_boss_tip"
})
end
end
CustomGameEventManager:Send_ServerToPlayer( player, "wave_notification", {UnitName = waveInfo.UnitName, Round = CurrentRound} )
print("[SurvivalTD] sending next_round_timer to client JS")
CustomGameEventManager:Send_ServerToPlayer( player, "next_round_timer", {
time = waveInfo.NextRoundTime,
round = CurrentRound,
roundtime = GameMode.RoundTime
})
end
end
end)
-- Start a timer that will spawn the next wave
print("[SurvivalTD] Starting timer for next wave")
-- make sure the next wave isn't invoked elsewhere
local TimerRound = CurrentRound
Timers:CreateTimer(GameMode.RoundTime, function()
local info = GameMode.WaveInfo[strTeamID]
if TimerRound == info.Round then
print("[SurvivalTD] timer expired .. spawning next wave")
GameMode:SpawnNextWave(team)
end
end)
end
--[[
This function is called once and only once when the game completely begins (about 0:00 on the clock). At this point,
gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function
is useful for starting any game logic timers/thinkers, beginning the first round, etc.
]]
function GameMode:OnGameInProgress()
DebugPrint("[BAREBONES] The game has officially begun")
GameRules:SendCustomMessage("#chat_command_info", 1, 1)
-- loop over the teams and start their initial waves
for team=DOTA_TEAM_FIRST, DOTA_TEAM_COUNT do
local EntTeam = GameMode.TeamToEntTeam[team]
if EntTeam then
GameMode:SpawnNextWave(team)
end
end
Timers:CreateTimer(0, function()
-- Set time of day to keep it sunny all the time
GameRules:SetTimeOfDay(0.5)
return 30.0 -- Rerun this timer every 30 game-time seconds
end)
end
-- This function initializes the game mode and is called before anyone loads into the game
-- It can be used to pre-initialize any values/tables that will be needed later
function GameMode:InitGameMode()
GameMode = self
DebugPrint('[BAREBONES] Starting to load Barebones gamemode...')
-- Call the internal function to set up the rules/behaviors specified in constants.lua
-- This also sets up event hooks for all event handlers in events.lua
-- Check out internals/gamemode to see/modify the exact code
GameMode:_InitGameMode()
GameRules:GetGameModeEntity():SetExecuteOrderFilter( Dynamic_Wrap( GameMode, 'FilterExecuteOrder' ), self)
LinkLuaModifier("modifier_movespeed_cap", "abilities/modifier_movespeed_cap", LUA_MODIFIER_MOTION_NONE)
-- Constants for difficulty
GameMode.DIFFICULTY_EASY = 0
GameMode.DIFFICULTY_NORMAL = 1
GameMode.DIFFICULTY_HARD = 2
GameMode.DifficultyHealth = {
[GameMode.DIFFICULTY_EASY] = 1.0, -- 100%
[GameMode.DIFFICULTY_NORMAL] = 1.1, -- 110%
[GameMode.DIFFICULTY_HARD] = 1.2 -- 120%
}
-- entities in the map are named by player id's, but we want to reference them by team
GameMode.TeamToEntTeam = {
[DOTA_TEAM_GOODGUYS] = 0,
[DOTA_TEAM_BADGUYS] = 1,
[DOTA_TEAM_CUSTOM_1] = 2,
[DOTA_TEAM_CUSTOM_2] = 3,
[DOTA_TEAM_CUSTOM_3] = 4,
[DOTA_TEAM_CUSTOM_4] = 5,
[DOTA_TEAM_CUSTOM_5] = 6,
[DOTA_TEAM_CUSTOM_6] = 7,
[DOTA_TEAM_CUSTOM_7] = 8,
[DOTA_TEAM_CUSTOM_8] = 9
}
-- Initial Variables
GameMode.CurrentRound = 0
GameMode.InitialLives = 10
GameMode.RoundTime = 65
GameMode.FastSpawnDelay = 15
GameMode.InitialGold = 100
GameMode.GoldPerRound = 55
GameMode.CreepCount = 16
GameMode.TotalRounds = 34
GameMode.CreepTeam = DOTA_TEAM_CUSTOM_8
GameMode.GameWinner = GameMode.CreepTeam
GameMode.FlyingWaves = {"creep_wave_8", "creep_wave_14", "creep_wave_20", "creep_wave_26", "creep_wave_29"}
GameMode.BossWaves = {"creep_wave_9", "creep_wave_19", "creep_wave_34"}
GameMode.TeamLives = {
[tostring(DOTA_TEAM_GOODGUYS)] = GameMode.InitialLives,
[tostring(DOTA_TEAM_BADGUYS)] = GameMode.InitialLives,
[tostring(DOTA_TEAM_CUSTOM_1)] = GameMode.InitialLives,
[tostring(DOTA_TEAM_CUSTOM_2)] = GameMode.InitialLives
}
GameMode.TeamDifficulty = {
[tostring(DOTA_TEAM_GOODGUYS)] = GameMode.DIFFICULTY_EASY,
[tostring(DOTA_TEAM_BADGUYS)] = GameMode.DIFFICULTY_EASY,
[tostring(DOTA_TEAM_CUSTOM_1)] = GameMode.DIFFICULTY_EASY,
[tostring(DOTA_TEAM_CUSTOM_2)] = GameMode.DIFFICULTY_EASY
}
GameMode.WaveInfo = {
[tostring(DOTA_TEAM_GOODGUYS)] = {Round = 0, Count = 0, UnitName = "", NextRoundTime = 0},
[tostring(DOTA_TEAM_BADGUYS)] = {Round = 0, Count = 0, UnitName = "", NextRoundTime = 0},
[tostring(DOTA_TEAM_CUSTOM_1)] = {Round = 0, Count = 0, UnitName = "", NextRoundTime = 0},
[tostring(DOTA_TEAM_CUSTOM_2)] = {Round = 0, Count = 0, UnitName = "", NextRoundTime = 0}
}
local GetBoundaryEntityPos = (function(team, corner)
local entTeamID = GameMode.TeamToEntTeam[team]
local ent_bounds = Entities:FindByName(nil, "team" .. entTeamID .. "_bound_" .. corner)
if IsValidEntity(ent_bounds) then
return ent_bounds:GetAbsOrigin()
else
return Vector(0,0,0)
end
end)
GameMode.TeamBoundaries = {
[DOTA_TEAM_GOODGUYS] = {
nw = GetBoundaryEntityPos(DOTA_TEAM_GOODGUYS, "nw"),
se = GetBoundaryEntityPos(DOTA_TEAM_GOODGUYS, "se")
},
[DOTA_TEAM_BADGUYS] = {
nw = GetBoundaryEntityPos(DOTA_TEAM_BADGUYS, "nw"),
se = GetBoundaryEntityPos(DOTA_TEAM_BADGUYS, "se")
},
[DOTA_TEAM_CUSTOM_1] = {
nw = GetBoundaryEntityPos(DOTA_TEAM_CUSTOM_1, "nw"),
se = GetBoundaryEntityPos(DOTA_TEAM_CUSTOM_1, "se")
},
[DOTA_TEAM_CUSTOM_2] = {
nw = GetBoundaryEntityPos(DOTA_TEAM_CUSTOM_2, "nw"),
se = GetBoundaryEntityPos(DOTA_TEAM_CUSTOM_2, "se")
}
}
GameMode.BuildGridHeight = 256
-- Loading tower values
GameMode.Towers = {}
local UnitKV = LoadKeyValues("scripts/npc/npc_units_custom.txt")
print("[SurvivalTD] Initializing Build_Tower: ")
for key,value in pairs(UnitKV) do
if key:find("tower_") then
GameMode.Towers[key] = {
GoldCost = value.GoldCost or 10,
BuildTime = value.BuildTime or 1,
Level = value.RequiresLevel or 0,
Hotkey = value.Hotkey or "",
Portrait = value.Portrait or "",
AttackDamageMin = value.AttackDamageMin or 0,
AttackDamageMax = value.AttackDamageMax or 0,
AttackRange = value.AttackRange or 0,
IsUpgrade = (value.IsUpgrade == 1) or false,
AttacksEnabled = value.AttacksEnabled or "ground,air"
}
--CustomNetTables:SetTableValue( "towers", key, GameMode.Towers[key] );
print(string.format("[SurvivalTD] Tower: %q Costs: %i", key, value.GoldCost))
end
--build_tower.vGoldCosts[]
end
-- Commands can be registered for debugging purposes or as functions that can be called by the custom Scaleform UI
Convars:RegisterCommand( "spawn_wave", Dynamic_Wrap(GameMode, 'SpawnWaveConsoleCommand'), "A console command example", FCVAR_CHEAT )
--local OutOfWorldVector = Vector(11000,11000,0)
CustomGameEventManager:RegisterListener( "build_tower_cast", function(eventSourceIndex, args)
local player = PlayerResource:GetPlayer(args.PlayerID)
if not player.vTowerQueue then return end
local hero = player:GetAssignedHero()
if hero == nil then return end
local ability = hero:FindAbilityByName("build_tower")
if ability == nil then return end
print("[SurvivalTD] build tower cast")
local position = Vector(args.position['0'], args.position['1'], args.position['2'])
hero:CastAbilityOnPosition(position, ability, args.PlayerID)
end)
CustomGameEventManager:RegisterListener( "build_tower_cancel", function(eventSourceIndex, args)
local player = PlayerResource:GetPlayer(args.PlayerID)
player.vTowerQueue = nil
end)
CustomGameEventManager:RegisterListener( "build_tower_phase", function(eventSourceIndex, args)
local player = PlayerResource:GetPlayer(args.PlayerID)
if args.tower == nil then return end
local tower = args.tower
local towerAttr = GameMode.Towers[tower]
local AttackRange = towerAttr and towerAttr.AttackRange or 0
-- Dummy function, it just returns the first key from the table given
--local tower = (function( t ) for k,v in pairs(t) do return k; end end)(args.tower)
print("Builder wants to build tower: " .. tower)
player.vTowerQueue = tower
--player.vTowerUnit = CreateUnitByName(tower, OutOfWorldVector, false, nil, nil, player:GetTeam())
--CustomGameEventManager:Send_ServerToPlayer(player, "building_helper_enable", {["state"] = "active", ["size"] = size, ["entIndex"] = player.mgd:GetEntityIndex(), ["MaxScale"] = fMaxScale} )
--CustomGameEventManager:Send_ServerToPlayer(player, "build_tower_ghost_enable", {["state"] = "active", ["size"] = 256, ["entIndex"] = player.vTowerUnit:GetEntityIndex(), ["MaxScale"] = 256} )
CustomGameEventManager:Send_ServerToPlayer(player, "build_tower_ghost_enable", {AttackRange = AttackRange})
end)
-- custom units do not supporting casting lua abilities for whatever reason
local CastUnitAbilityFix = (function(eventSourceIndex, args)
local player = PlayerResource:GetPlayer(args.PlayerID)
local abilityIndex = args.ability
local unitIndex = args.unit
ExecuteOrderFromTable({
UnitIndex = unitIndex,
OrderType = DOTA_UNIT_ORDER_CAST_NO_TARGET,
AbilityIndex = abilityIndex
})
end)
local PlayerChangedDifficulty = (function(eventSourceIndex, args)
if GameRules:State_Get() == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP then
local player = PlayerResource:GetPlayer(args.PlayerID)
strTeamID = tostring(player:GetTeam())
local difficulty = args.difficulty
if difficulty == GameMode.DIFFICULTY_EASY or difficulty == GameMode.DIFFICULTY_NORMAL or difficulty == GameMode.DIFFICULTY_HARD then
GameMode.TeamDifficulty[strTeamID] = difficulty
CustomNetTables:SetTableValue( "game_state", "difficulty", GameMode.TeamDifficulty )
end
end
end)
--CustomGameEventManager:RegisterListener( "sell_tower", CastUnitAbilityFix )
--CustomGameEventManager:RegisterListener( "upgrade_tower", CastUnitAbilityFix )
CustomGameEventManager:RegisterListener( "player_changed_difficulty", PlayerChangedDifficulty )
CustomNetTables:SetTableValue( "game_state", "towers", GameMode.Towers )
CustomNetTables:SetTableValue( "game_state", "settings", {
InitialLives = GameMode.InitialLives,
FlyingWaves = GameMode.FlyingWaves,
BossWaves = GameMode.BossWaves,
TotalRounds = GameMode.TotalRounds,
BuildGridHeight = GameMode.BuildGridHeight,
TierCosts = {40, 80, 120, 0} -- Upgrade cost of level 2,3,4
})
CustomNetTables:SetTableValue( "game_state", "lives", GameMode.TeamLives)
CustomNetTables:SetTableValue( "game_state", "difficulty", GameMode.TeamDifficulty)
CustomNetTables:SetTableValue( "game_state", "teamstate", GameMode.WaveInfo)
DebugPrint('[BAREBONES] Done loading Barebones gamemode!\n\n')
end
-- Gets the team owning the current area or nil
function GameMode:GetTeamOwningArea(position)
--local heroes = HeroList:GetAllHeroes()
--for _,hero in pairs(heroes) do
-- if (GameMode:IsWithinTeamBounds(hero, position)) then
-- return hero:GetPlayerOwner()
-- end
--end
for team=DOTA_TEAM_FIRST, DOTA_TEAM_COUNT do
local EntTeam = GameMode.TeamToEntTeam[team]
if EntTeam and GameMode:IsWithinTeamBounds(team, position) then
return team
end
end
return nil
end
function GameMode:GetPlayersOnTeam(team)
local playerCount = PlayerResource:GetPlayerCountForTeam(team)
local players = {}
if playerCount > 0 then
for i=1,playerCount do
local PlayerID = PlayerResource:GetNthPlayerIDOnTeam(team, i)
if PlayerResource:IsValidPlayerID(PlayerID) then
table.insert(players, PlayerResource:GetPlayer(PlayerID))
end
end
end
--if playerCount > 0 then
-- local i = 0
-- return (function()
-- i = i + 1
-- local PlayerID = PlayerResource:GetNthPlayerIDOnTeam(team, i)
--
-- if i <= playerCount and PlayerResource:IsValidPlayerID(PlayerID) then
-- return PlayerResource:GetPlayer(PlayerID)
-- end
-- end)
--end
return players
end
-- Triggers when a player has lost all of his lives
function GameMode:OnGameOver(player)
print("[SurvivalTD] game is over for player ..")
local hero = player:GetAssignedHero()
local units = FindUnitsInRadius(
hero:GetTeamNumber(), -- team number
hero:GetAbsOrigin(), -- radius around builder
nil, -- cacheUnit
FIND_UNITS_EVERYWHERE, -- radius
DOTA_UNIT_TARGET_TEAM_FRIENDLY, -- teamFilter
DOTA_UNIT_TARGET_ALL, -- type filter
DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES,
FIND_ANY_ORDER, -- order
false -- canGrowCache
)
for _,unit in pairs(units) do
if unit:IsAlive() then
unit:ForceKill(false)
end
end
if hero:IsAlive() then
hero:ForceKill(false)
end
GameMode:CheckGameOver()
end
-- Check if all players are dead, and then end the game
function GameMode:CheckGameOver()
local heroes = HeroList:GetAllHeroes()
for _,hero in pairs(heroes) do
if hero:IsAlive() and not hero.killedLastWave then
return
end
end
GameRules:SendCustomMessage("Game will end in 20 seconds", 1, 1)
GameMode:TriggerGameEnd(20.0)
end
function GameMode:TriggerGameEnd(timeout)
timeout = timeout or 30.0
Timers:CreateTimer(timeout, function()
GameRules:SetGameWinner(GameMode.GameWinner)
end)
end
function GameMode:WantBuildTower()
print("want build tower")
--Abilities.ExecuteAbility( integer nAbilityEntIndex, integer nCasterEntIndex, boolean bIsQuickCast )
end
function GameMode:SpawnWaveConsoleCommand(...)
local args = {...}
local wave = args[1] or "creep_wave_1"
print("[SurvivalTD] Spawning creep wave: " .. wave)
local cmdPlayer = Convars:GetCommandClient()
GameMode:SpawnCreepWave(wave, cmdPlayer, 0)
end
function GameMode:FilterExecuteOrder( filterTable )
local units = filterTable["units"]
local order_type = filterTable["order_type"]
local issuer = filterTable["issuer_player_id_const"]
local abilityIndex = filterTable["entindex_ability"]
local targetIndex = filterTable["entindex_target"]
local x = tonumber(filterTable["position_x"])
local y = tonumber(filterTable["position_y"])
local z = tonumber(filterTable["position_z"])
local point = Vector(x,y,z)
-- Skip Prevents order loops
if units["0"] == nil then return true end
local unit = EntIndexToHScript(units["0"])
if unit and unit.skip then
unit.skip = false
return true
end
if order_type == DOTA_UNIT_ORDER_ATTACK_TARGET then
local target = EntIndexToHScript(targetIndex)
local errorMsg = nil
for n, unit_index in pairs(units) do
local unit = EntIndexToHScript(unit_index)
local player = unit:GetPlayerOwner()
local hero = player and player:GetAssignedHero() or nil
if UnitCanAttackTarget(unit, target) then --and
--((hero and GameMode:IsWithinHeroBounds(hero, target:GetAbsOrigin())) or hero == nil) then -- uncommented for now, since it's unnescessary
unit.skip = true
ExecuteOrderFromTable({ UnitIndex = unit_index, OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET, TargetIndex = targetIndex, Queue = 0})
else
-- stop idle acquire
unit:SetIdleAcquire(false)
ExecuteOrderFromTable({ UnitIndex = unit_index, OrderType = DOTA_UNIT_ORDER_STOP, Queue = 0})
if not errorMsg then
local target_type = GetMovementCapability(target)
if target_type == "air" then
GameMode:PromptError(player, "error_cant_attack_air")
elseif target_type == "ground" then
GameMode:PromptError(player, "error_cant_attack_ground")
end
errorMsg = true
end
end
end
errorMsg = nil
return false
end
return true
end
| mit |
erwincoumans/premake-dev-iphone-xcode4 | tests/actions/vstudio/vc200x/test_compiler_block.lua | 1 | 7116 | --
-- tests/actions/vstudio/vc200x/test_compiler_block.lua
-- Validate generation the VCCLCompiler element in Visual Studio 200x C/C++ projects.
-- Copyright (c) 2011-2012 Jason Perkins and the Premake project
--
T.vs200x_compiler_block = { }
local suite = T.vs200x_compiler_block
local vc200x = premake.vstudio.vc200x
--
-- Setup/teardown
--
local sln, prj, cfg
function suite.setup()
_ACTION = "vs2008"
sln, prj = test.createsolution()
end
local function prepare()
cfg = premake5.project.getconfig(prj, "Debug")
vc200x.VCCLCompilerTool_ng(cfg)
end
--
-- Verify the basic structure of the compiler block with no flags or settings.
--
function suite.looksGood_onDefaultSettings()
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="0"
/>
]]
end
--
-- If include directories are specified, the <AdditionalIncludeDirectories> should be added.
--
function suite.additionalIncludeDirs_onIncludeDirs()
includedirs { "include/lua", "include/zlib" }
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="include\lua;include\zlib"
]]
end
--
-- Verify the handling of the Symbols flag. The format must be set, and the
-- debug runtime library must be selected.
--
function suite.looksGood_onSymbolsFlag()
flags "Symbols"
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="4"
/>
]]
end
--
-- Verify the handling of the Symbols in conjunction with the Optimize flag.
-- The release runtime library must be used.
--
function suite.looksGood_onSymbolsAndOptimizeFlags()
flags { "Symbols", "Optimize" }
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="3"
StringPooling="true"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="3"
/>
]]
end
--
-- Verify the handling of the C7 debug information format.
--
function suite.looksGood_onC7DebugFormat()
flags "Symbols"
debugformat "C7"
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="1"
/>
]]
end
--
-- Verify the handling of precompiled headers.
--
function suite.compilerBlock_OnPCH()
pchheader "source/common.h"
pchsource "source/common.cpp"
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="common.h"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="0"
/>
]]
end
--
-- Floating point flag tests
--
function suite.compilerBlock_OnFpFast()
flags { "FloatFast" }
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
FloatingPointModel="2"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="0"
/>
]]
end
function suite.compilerBlock_OnFpStrict()
flags { "FloatStrict" }
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
FloatingPointModel="1"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="0"
/>
]]
end
--
-- Verify that the PDB file uses the target name if specified.
--
function suite.pdfUsesTargetName_onTargetName()
targetname "foob"
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\foob.pdb"
DebugInformationFormat="0"
/>
]]
end
--
-- Check that the "minimal rebuild" flag is applied correctly.
--
function suite.minimalRebuildFlagsSet_onMinimalRebuildAndSymbols()
flags { "Symbols", "NoMinimalRebuild" }
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="4"
/>
]]
end
--
-- Check that the CompileAs value is set correctly for C language projects.
--
function suite.compileAsSet_onC()
language "C"
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="0"
CompileAs="1"
/>
]]
end
--
-- Verify the correct runtime library is used when symbols are enabled.
--
function suite.runtimeLibraryIsDebug_onSymbolsNoOptimize()
flags { "Symbols" }
prepare()
test.capture [[
<Tool
Name="VCCLCompilerTool"
Optimization="0"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="4"
/>
]]
end
--
-- Xbox 360 uses the same structure, but changes the element name.
--
function suite.looksGood_onXbox360()
system "Xbox360"
prepare()
test.capture [[
<Tool
Name="VCCLX360CompilerTool"
Optimization="0"
BasicRuntimeChecks="3"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0"
WarningLevel="3"
ProgramDataBaseFileName="$(OutDir)\MyProject.pdb"
DebugInformationFormat="0"
/>
]]
end
| bsd-3-clause |
brahmi2/prosody-modules | mod_swedishchef/mod_swedishchef.lua | 32 | 1690 | -- Copyright (C) 2009 Florian Zeitz
-- Copyright (C) 2009 Matthew Wild
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local trigger_string = module:get_option_string("swedishchef_trigger");
trigger_string = (trigger_string and trigger_string .. " ") or "";
local chef = {
{ th = "t" },
{ ow = "o"},
{["([^%w])o"] = "%1oo",
O = "Oo"},
{au = "oo",
u = "oo", U = "Oo"},
{["([^o])o([^o])"] = "%1u%2"},
{ir = "ur",
an = "un", An = "Un", Au = "Oo"},
{e = "i", E = "I"},
{ i = function () return select(math.random(2), "i", "ee"); end },
{a = "e", A = "E"},
{["e([^%w])"] = "e-a%1"},
{f = "ff"},
{v = "f", V = "F"},
{w = "v", W = "V"} };
function swedish(english)
local eng, url = english:match("(.*)(http://.*)$");
if eng then english = eng; end
for _,v in ipairs(chef) do
for k,v in pairs(v) do
english = english:gsub(k,v);
end
end
english = english:gsub("the", "zee");
english = english:gsub("The", "Zee");
english = english:gsub("tion", "shun");
english = english:gsub("[.!?]$", "%1\nBork Bork Bork!");
return tostring(english..((url and url) or ""));
end
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local body, bodyindex;
for k,v in ipairs(stanza) do
if v.name == "body" then
body, bodyindex = v, k;
end
end
if not body then return; end
body = body:get_text();
if body and (body:find(trigger_string, 1, true) == 1) then
module:log("debug", body:find(trigger_string, 1, true));
stanza[bodyindex][1] = swedish(body:gsub("^" .. trigger_string, "", 1));
end
end
module:hook("message/bare", check_message);
| mit |
jchuang1977/my_luci | modules/admin-full/luasrc/controller/admin/index.lua | 79 | 1245 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.index", package.seeall)
function index()
local root = node()
if not root.target then
root.target = alias("admin")
root.index = true
end
local page = node("admin")
page.target = firstchild()
page.title = _("Administration")
page.order = 10
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.ucidata = true
page.index = true
-- Empty services menu to be populated by addons
entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true
entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90)
end
function action_logout()
local dsp = require "luci.dispatcher"
local sauth = require "luci.sauth"
if dsp.context.authsession then
sauth.kill(dsp.context.authsession)
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
| apache-2.0 |
DigitalCrypto/scite-mql | additions/Ctagsdx.lua | 3 | 6325 | -- browse a tags database from SciTE!
-- Set this property:
-- ctags.path.php=<full path to tags file>
-- 1. Multiple tags are handled correctly; a drop-down
-- list is presented
-- 2. There is a full stack of marks available.
-- 3. If ctags.path.php is not defined, will try to find a tags file in the current dir.
if scite_Command then
scite_Command {
'Find Tag|find_ctag $(CurrentWord)|Ctrl+.',
'Go to Mark|goto_mark|Alt+.',
'Set Mark|set_mark|Ctrl+\'',
'Select from Mark|select_mark|Ctrl+/',
}
end
local gMarkStack = {}
local sizeof = table.getn
local push = table.insert
local pop = table.remove
local top = function(s) return s[sizeof(s)] end
local _UserListSelection
-- Parse string
function eval(str)
if type(str) == "string" then
return loadstring("return " .. str)()
elseif type(str) == "number" then
return loadstring("return " .. tostring(str))()
else
error("is not a string")
end
end
-- this centers the cursor position
-- easy enough to make it optional!
function ctags_center_pos(line)
if not line then
line = editor:LineFromPosition(editor.CurrentPos)
end
local top = editor.FirstVisibleLine
local middle = top + editor.LinesOnScreen/2
editor:LineScroll(0,line - middle)
end
local function open_file(file,line,was_pos)
scite.Open(file)
if not was_pos then
editor:GotoLine(line)
ctags_center_pos(line)
else
editor:GotoPos(line)
ctags_center_pos()
end
end
function set_mark()
push(gMarkStack,{file=props['FilePath'],pos=editor.CurrentPos})
end
function goto_mark()
local mark = pop(gMarkStack)
if mark then
open_file(mark.file,mark.pos,true)
end
end
function select_mark()
local mark = top(gMarkStack)
print (mark)
if mark then
local p1 = mark.pos
local p2 = editor.CurrentPos
print(p1..','..p2)
editor:SetSel(p1,p2)
end
end
local find = string.find
local function extract_path(path)
-- given a full path, find the directory part
local s1,s2 = find(path,'/[^/]+$')
if not s1 then -- try backslashes!
s1,s2 = find(path,'\\[^\\]+$')
end
if s1 then
return string.sub(path,1,s1-1)
else
return nil
end
end
local function ReadTagFile(file)
local f = io.open(file)
if not f then return nil end
local tags = {}
-- now we can pick up the tags!
for line in f:lines() do
-- skip if line is comment
if find(line,'^[^!]') then
local _,_,tag = find(line,'^([^\t]+)\t')
local existing_line = tags[tag]
if not existing_line then
tags[tag] = line..'@'
else
tags[tag] = existing_line..line..'@'
end
end
end
return tags
end
local gTagFile
local tags
local function OpenTag(tag)
-- ask SciTE to open the file
local file_name = tag.file
local path = extract_path(gTagFile)
--if path then file_name = path..'/'..file_name end
set_mark()
scite.Open(file_name)
-- depending on what kind of tag, either search for the pattern,
-- or go to the line.
local pattern = tag.pattern
if type(pattern) == 'string' then
local p1 = editor:findtext(pattern)
if p1 then
editor:GotoPos(p1)
ctags_center_pos()
end
else
local tag_line = pattern
editor:GotoLine(tag_line)
ctags_center_pos(tag_line)
end
end
function locate_tags(dir)
--function test(dir)
local filefound = nil
local slash, f
_,_,slash = string.find(dir,"([/\\])")
while dir do
file = dir .. slash .. "tags"
--print ( "---" .. file)
f = io.open(file)
if f then
filefound = file
break
end
_,_,dir = string.find(dir,"(.+)[/\\][^/\\]+$")
--print(dir)
end
return filefound
end
function find_ctag(f,partial)
-- search for tags files first
local result
result = props['ctags.path.php']
if not result then
result = locate_tags(props['FileDir'])
end
if not result then
print("No tags found!")
return
end
if result ~= gTagFile then
--print("Reloading tag from:"..result)
gTagFile = result
tags = ReadTagFile(gTagFile)
end
if tags == nil then return end
if partial then
result = ''
for tag,val in tags do
if find(tag,f) then
result = result..val..'@'
end
end
else
result = tags[f]
end
if not result then return end -- not found
local matches = {}
local k = 0;
for line in string.gfind(result,'([^@]+)@') do
k = k + 1
local s1,s2,tag_name,file_name,tag_pattern,tag_property = find(line,'([^\t]*)\t([^\t]*)\t/^(.*)$/;\"\t(.*)')
if s1 ~= nil then
tag_pattern = tag_pattern:gsub('\\/','/')
matches[k] = {tag=f,file=file_name,pattern=tag_pattern,property=tag_property}
end
end
if k == 0 then return end
if k > 1 then -- multiple tags found
local list = {}
for i,t in ipairs(matches) do
table.insert(list,i..' '..t.file..':'..t.pattern)
end
scite_UserListShow(list,1,function(s)
local _,_,tok = find(s,'^(%d+)')
local idx = tonumber(tok) -- very important!
OpenTag(matches[idx])
end)
else
OpenTag(matches[1])
end
end
function locate_tags(dir)
--function test(dir)
local filefound = nil
local slash, f
_,_,slash = string.find(dir,"([/\\])")
while dir do
file = dir .. slash .. "tags"
--print ( "---" .. file)
f = io.open(file)
if f then
filefound = file
break
end
_,_,dir = string.find(dir,"(.+)[/\\][^/\\]+$")
--print(dir)
end
return filefound
end
function reset_tags()
gTagFile = nil
tags = {}
end
-- the handler is always reset!
function scite_UserListShow(list,start,fn)
local s = ''
local sep = '#'
local n = sizeof(list)
for i = start,n-1 do
s = s..list[i]..sep
end
s = s..list[n]
s = s:gsub('\t',' '):gsub('[ \t]+',' '):gsub('[ ]+$','')
_UserListSelection = fn
local pane = editor
if not pane.Focus then pane = output end
pane.AutoCSeparator = string.byte(sep)
pane:UserListShow(13,s)
pane.AutoCSeparator = string.byte(' ')
end
AddEventHandler("OnUserListSelection", function(tp,str)
if _UserListSelection then
local callback = _UserListSelection
_UserListSelection = nil
return callback(str)
else return false end
end) | isc |
erwincoumans/premake-dev-iphone-xcode4 | tests/actions/vstudio/vc200x/test_debug_settings.lua | 1 | 2419 | --
-- tests/actions/vstudio/vc200x/test_debugdir.lua
-- Validate handling of the working directory for debugging.
-- Copyright (c) 2011-2012 Jason Perkins and the Premake project
--
T.vstudio_vs200x_debugdir = { }
local suite = T.vstudio_vs200x_debugdir
local vc200x = premake.vstudio.vc200x
local project = premake5.project
--
-- Setup
--
local sln, prj, cfg
function suite.setup()
sln, prj = test.createsolution()
end
local function prepare()
cfg = project.getconfig(prj, "Debug")
vc200x.debugdir_ng(cfg)
end
--
-- If no debug settings are specified, an empty block should be generated.
--
function suite.emptyBlock_onNoSettings()
prepare()
test.capture [[
<DebugSettings
/>
]]
end
--
-- If a working directory is provided, it should be specified relative to
-- the project.
--
function suite.workingDir_onRelativePath()
location "build"
debugdir "bin/debug"
prepare()
test.capture [[
<DebugSettings
WorkingDirectory="..\bin\debug"
/>
]]
end
--
-- Make sure debug arguments are being written.
--
function suite.commandArguments_onDebugArgs()
debugargs { "arg1", "arg2" }
prepare()
test.capture [[
<DebugSettings
CommandArguments="arg1 arg2"
/>
]]
end
--
-- Make sure environment variables are being written.
--
function suite.environmentVarsSet_onDebugEnvs()
debugenvs { "key=value" }
prepare()
test.capture [[
<DebugSettings
Environment="key=value"
/>
]]
end
--
-- Make sure quotes around environment variables are properly escaped.
--
function suite.environmentVarsEscaped_onQuotes()
debugenvs { 'key="value"' }
prepare()
test.capture [[
<DebugSettings
Environment="key="value""
/>
]]
end
--
-- If multiple environment variables are specified, make sure they get
-- separated properly.
--
function suite.environmentVars_onMultipleValues()
debugenvs { "key=value", "foo=bar" }
prepare()
test.capture [[
<DebugSettings
Environment="key=value
foo=bar"
/>
]]
end
--
-- Make sure that environment merging is turned off if the build
-- flag is set.
--
function suite.environmentVarsSet_onDebugEnvs()
debugenvs { "key=value" }
flags { "DebugEnvsDontMerge" }
prepare()
test.capture [[
<DebugSettings
Environment="key=value"
EnvironmentMerge="false"
/>
]]
end
| bsd-3-clause |
ArchShaman/Zero-K | scripts/planescout.lua | 5 | 1312 | include 'constants.lua'
include "fixedwingTakeOff.lua"
--------------------------------------------------------------------
-- constants/vars
--------------------------------------------------------------------
local base, nozzle, thrust = piece("base", "nozzle", "thrust")
local smokePiece = {base}
local SIG_CLOAK = 1
local CLOAK_TIME = 5000
local SIG_TAKEOFF = 2
local takeoffHeight = UnitDefNames["planescout"].wantedHeight
--------------------------------------------------------------------
-- functions
--------------------------------------------------------------------
local function Decloak()
Signal(SIG_CLOAK)
SetSignalMask(SIG_CLOAK)
Sleep(CLOAK_TIME)
Spring.SetUnitCloak(unitID, false)
end
function Cloak()
Spring.SetUnitCloak(unitID, 2)
StartThread(Decloak)
end
function script.StopMoving()
StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF)
end
function script.Create()
StartThread(TakeOffThread, takeoffHeight, SIG_TAKEOFF)
StartThread(SmokeUnit, smokePiece)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < 0.5 or (Spring.GetUnitMoveTypeData(unitID).aircraftState == "crashing") then
Explode(nozzle, sfxFall)
return 1
else
Explode(base, sfxShatter)
Explode(nozzle, sfxFall + sfxSmoke)
return 2
end
end
| gpl-2.0 |
Jobq/vlc-mdc | share/lua/playlist/dailymotion.lua | 19 | 3036 | --[[
Translate Daily Motion video webpages URLs to the corresponding
FLV URL.
$Id$
Copyright © 2007-2011 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "dailymotion." )
and string.match( vlc.peek( 2048 ), "<!DOCTYPE.*video_type" )
end
function find( haystack, needle )
local _,_,ret = string.find( haystack, needle )
return ret
end
-- Parse function.
function parse()
prefres = get_prefres()
while true
do
line = vlc.readline()
if not line then
break
end
if string.match( line, "\"sequence\"")
then
line = vlc.strings.decode_uri(line):gsub("\\/", "/")
arturl = find( line, "\"videoPreviewURL\":\"([^\"]*)\"")
name = find( line, "\"videoTitle\":\"([^\"]*)\"")
if name then
name = string.gsub( name, "+", " " )
end
description = find( line, "\"videoDescription\":\"([^\"]*)\"")
if description then
description = string.gsub( description, "+", " " )
end
for _,param in ipairs({ "hd1080URL", "hd720URL", "hqURL", "sdURL" }) do
path = string.match( line, "\""..param.."\":\"([^\"]*)\"" )
if path then
if prefres < 0 then
break
end
height = string.match( path, "/cdn/%w+%-%d+x(%d+)/video/" )
if not height then
height = string.match( param, "(%d+)" )
end
if not height or tonumber(height) <= prefres then
break
end
end
end
if not path then
break
end
return { { path = path; name = name; description = description; url = vlc.path; arturl = arturl } }
end
end
vlc.msg.err("Couldn't extract the video URL from dailymotion")
return { }
end
| gpl-2.0 |
alarouche/premake-core | tests/tools/test_snc.lua | 16 | 3478 | --
-- tests/test_snc.lua
-- Automated test suite for the SNC toolset interface.
-- Copyright (c) 2012-2013 Jason Perkins and the Premake project
--
local suite = test.declare("tools_snc")
local snc = premake.tools.snc
--
-- Setup/teardown
--
local wks, prj, cfg
function suite.setup()
wks, prj = test.createWorkspace()
system "PS3"
end
local function prepare()
cfg = test.getconfig(prj, "Debug")
end
--
-- Check the selection of tools based on the target system.
--
function suite.tools_onDefaults()
prepare()
test.isnil(snc.gettoolname(cfg, "cc"))
test.isnil(snc.gettoolname(cfg, "cxx"))
test.isnil(snc.gettoolname(cfg, "ar"))
end
function suite.tools_onPS3()
system "PS3"
prepare()
test.isnil(snc.gettoolname(cfg, "cc"))
test.isnil(snc.gettoolname(cfg, "cxx"))
test.isnil(snc.gettoolname(cfg, "ar"))
end
--
-- By default, the -MMD -MP are used to generate dependencies.
--
function suite.cppflags_defaultWithMMD()
prepare()
test.isequal({ "-MMD", "-MP" }, snc.getcppflags(cfg))
end
--
-- Check the translation of CFLAGS.
--
function suite.cflags_onFatalWarnings()
flags { "FatalWarnings" }
prepare()
test.isequal({ "-Xquit=2" }, snc.getcflags(cfg))
end
--
-- Check the optimization flags.
--
function suite.cflags_onNoOptimize()
optimize "Off"
prepare()
test.isequal({ "-O0" }, snc.getcflags(cfg))
end
function suite.cflags_onOptimize()
optimize "On"
prepare()
test.isequal({ "-O1" }, snc.getcflags(cfg))
end
function suite.cflags_onOptimizeSize()
optimize "Size"
prepare()
test.isequal({ "-Os" }, snc.getcflags(cfg))
end
function suite.cflags_onOptimizeSpeed()
optimize "Speed"
prepare()
test.isequal({ "-O2" }, snc.getcflags(cfg))
end
function suite.cflags_onOptimizeFull()
optimize "Full"
prepare()
test.isequal({ "-O3" }, snc.getcflags(cfg))
end
function suite.cflags_onOptimizeDebug()
optimize "Debug"
prepare()
test.isequal({ "-Od" }, snc.getcflags(cfg))
end
--
-- Turn on exceptions and RTTI by default, to match the other Premake supported toolsets.
--
function suite.cxxflags_onDefault()
prepare()
test.isequal({ "-Xc+=exceptions", "-Xc+=rtti" }, snc.getcxxflags(cfg))
end
--
-- Check the translation of LDFLAGS.
--
function suite.cflags_onDefaults()
prepare()
test.isequal({ "-s" }, snc.getldflags(cfg))
end
--
-- Check the formatting of linked libraries.
--
function suite.links_onSystemLibs()
links { "fs_stub", "net_stub" }
prepare()
test.isequal({ "-lfs_stub", "-lnet_stub" }, snc.getlinks(cfg))
end
--
-- When linking to a static sibling library, the relative path to the library
-- should be used instead of the "-l" flag. This prevents linking against a
-- shared library of the same name, should one be present.
--
function suite.links_onStaticSiblingLibrary()
links { "MyProject2" }
test.createproject(wks)
system "Linux"
kind "StaticLib"
location "MyProject2"
targetdir "lib"
prepare()
test.isequal({ "lib/libMyProject2.a" }, snc.getlinks(cfg))
end
--
-- When linking object files, leave off the "-l".
--
function suite.links_onObjectFile()
links { "generated.o" }
prepare()
test.isequal({ "generated.o" }, snc.getlinks(cfg))
end
--
-- Check handling of forced includes.
--
function suite.forcedIncludeFiles()
forceincludes { "stdafx.h", "include/sys.h" }
prepare()
test.isequal({'-include stdafx.h', '-include include/sys.h'}, snc.getforceincludes(cfg))
end
| bsd-3-clause |
rashed8271/bot | lang/italian_lang.lua | 32 | 20741 | --------------------------------------------------
-- ____ ____ _____ --
-- | \| _ )_ _|___ ____ __ __ --
-- | |_ ) _ \ | |/ ·__| _ \_| \/ | --
-- |____/|____/ |_|\____/\_____|_/\/\_| --
-- --
--------------------------------------------------
-- --
-- Developers: @Josepdal & @MaSkAoS --
-- Support: @Skneos, @iicc1 & @serx666 --
-- --
-- Translated by: @baconnn --
-- --
--------------------------------------------------
local LANG = 'it'
local function run(msg, matches)
if permissions(msg.from.id, msg.to.id, "lang_install") then
-------------------------
-- Translation version --
-------------------------
set_text(LANG, 'versione', '0.1')
set_text(LANG, 'versionExtended', 'Versione traduzione 0.1')
-------------
-- Plugins --
-------------
-- global plugins --
set_text(LANG, 'require_sudo', 'Questo plugin richiede i privilegi di sudo.')
set_text(LANG, 'require_admin', 'Questo plugin richiede privilegi da admin o superiori.')
set_text(LANG, 'require_mod', 'Questo plugin richiede privilegi da moderatore o superiori.')
-- welcome.lua
set_text(LANG, 'weloff', 'Welcome enabled.')
set_text(LANG, 'welon', 'Welcome disabled.')
set_text(LANG, 'byeon', 'Goodbye enabled.')
set_text(LANG, 'byeoff', 'Goodbye disabled.')
set_text(LANG, 'welcome1', 'Hi ')
set_text(LANG, 'welcome2', 'Welcome to ')
set_text(LANG, 'weldefault', 'The welcome is the default.')
set_text(LANG, 'byedefault', 'The goodbye is the default.')
set_text(LANG, 'newbye', 'Goodbye saved! is')
set_text(LANG, 'bye1', 'Bye ')
set_text(LANG, 'bye2', ' thank you for your visit.')
set_text(LANG, 'welnew', 'Welcome saved! is')
-- Spam.lua --
set_text(LANG, 'reportUser', 'UTENTE')
set_text(LANG, 'reportReason', 'Riportato per')
set_text(LANG, 'reportGroup', 'Gruppo')
set_text(LANG, 'reportMessage', 'Messagio')
set_text(LANG, 'allowedSpamT', 'Lo spam è ora consentito in questo gruppo.')
set_text(LANG, 'allowedSpamL', 'Lo spam è ora consentito in questo supergruppo.')
set_text(LANG, 'notAllowedSpamT', 'Lo spam non è consentito in questo gruppo.')
set_text(LANG, 'notAllowedSpamL', 'Lo spam non è consentito in questo supegruppo.')
-- bot.lua --
set_text(LANG, 'botOn', 'Sono tornato. Let\'s do this')
set_text(LANG, 'botOff', 'Nulla da fare qui')
-- settings.lua --
set_text(LANG, 'user', 'Utente')
set_text(LANG, 'isFlooding', 'sta floodando')
set_text(LANG, 'noStickersT', 'Gli stickers non sono consentiti in questo gruppo.')
set_text(LANG, 'noStickersL', 'Gli stickers non sono consentiti in questo supergruppo.')
set_text(LANG, 'stickersT', 'Gli stickers sono ora consentiti in questo gruppo.')
set_text(LANG, 'stickersL', 'Gli stickers non sono consentiti in questo supegruppo.')
set_text(LANG, 'noTgservicesT', 'Telegram services muted in this chat.')
set_text(LANG, 'noTgservicesL', 'Telegram services muted in this supergroup.')
set_text(LANG, 'tgservicesT', 'Telegram services allowed in this chat.')
set_text(LANG, 'tgservicesL', 'Telegram services allowed in this supergroup.')
set_text(LANG, 'LinksT', 'Links are now allowed in this chat.')
set_text(LANG, 'LinksL', 'Links are now allowed in this supergroup.')
set_text(LANG, 'noLinksT', 'Links are not allowed in this chat.')
set_text(LANG, 'noLinksL', 'Links are not allowed in this supergroup.')
set_text(LANG, 'gifsT', 'Le gif sono ora consentite in questo gruppo.')
set_text(LANG, 'gifsL', 'Le gif sono ora consentite in questo supergruppo.')
set_text(LANG, 'noGifsT', 'Le gif non sono consentite in questo gruppo.')
set_text(LANG, 'noGifsL', 'Le gif non sono consentite in questo supergruppo.')
set_text(LANG, 'photosT', 'Le immagini sono ora consentite in questo gruppo.')
set_text(LANG, 'photosL', 'Le immagini sono ora consentite in questo supergruppo.')
set_text(LANG, 'noPhotosT', 'Le immagini non sono consentite in questo gruppo.')
set_text(LANG, 'noPhotosL', 'Le immagini non sono consentite in questo supergruppo.')
set_text(LANG, 'botsT', 'Bots are now allowed in this chat.')
set_text(LANG, 'botsL', 'Bots are now allowed in this supergroup.')
set_text(LANG, 'noBotsT', 'Bots are not allowed in this chat.')
set_text(LANG, 'noBotsL', 'Bots are not allowed in this supergroup.')
set_text(LANG, 'arabicT', 'I caratteri arabi sono ora consentiti in questo gruppo.')
set_text(LANG, 'arabicL', 'I caratteri arabi sono ora consentiti in questo supergruppo.')
set_text(LANG, 'noArabicT', 'I caratteri arabi non sono consentiti in questo gruppo.')
set_text(LANG, 'noArabicL', 'I caratteri arabi non sono consentiti in questo supergruppo.')
set_text(LANG, 'audiosT', 'I vocali sono ora consentiti in questo gruppo.')
set_text(LANG, 'audiosL', 'I vocali sono ora consentiti in questo supergruppo.')
set_text(LANG, 'noAudiosT', 'I vocali non consentiti in questo gruppo.')
set_text(LANG, 'noAudiosL', 'I vocali non consentiti in questo supergruppo.')
set_text(LANG, 'kickmeT', 'L\'autokick è ora bilitato in questo gruppo.')
set_text(LANG, 'kickmeL', 'L\'autokick è ora bilitato in questo supergruppo.')
set_text(LANG, 'noKickmeT', 'L\'autokick non è bilitato in questo gruppo.')
set_text(LANG, 'noKickmeL', 'L\'autokick non è bilitato in questo supergruppo.')
set_text(LANG, 'floodT', 'Il flood è ora consentito in questo gruppo.')
set_text(LANG, 'floodL', 'Il flood è ora consentito in questo supergruppo.')
set_text(LANG, 'noFloodT', 'Il flood non è consentito in questo gruppo.')
set_text(LANG, 'noFloodL', 'Il flood non è consentito in questo supergruppo.')
set_text(LANG, 'floodTime', 'L\'intervallo di tempo per il controllo del flood è stato impostato a ')
set_text(LANG, 'floodMax', 'Il numero di messaggi per floodare è stato impostato a ')
set_text(LANG, 'gSettings', 'Impostazioni del gruppo')
set_text(LANG, 'sSettings', 'Impostazioni del supergruppo')
set_text(LANG, 'allowed', 'consentito')
set_text(LANG, 'noAllowed', 'non consentito')
set_text(LANG, 'noSet', 'non impostato')
set_text(LANG, 'stickers', 'Stickers')
set_text(LANG, 'tgservices', 'Tg services')
set_text(LANG, 'links', 'Link')
set_text(LANG, 'arabic', 'Caratteri arabi')
set_text(LANG, 'bots', 'Bot')
set_text(LANG, 'gifs', 'Gif')
set_text(LANG, 'photos', 'Immagini')
set_text(LANG, 'audios', 'Vocali')
set_text(LANG, 'kickme', 'Kickme')
set_text(LANG, 'spam', 'Spam')
set_text(LANG, 'gName', 'Nome del gruppo')
set_text(LANG, 'flood', 'Flood')
set_text(LANG, 'language', 'Lingiaggio')
set_text(LANG, 'mFlood', 'Flood massimo')
set_text(LANG, 'tFlood', 'Intervallo flood')
set_text(LANG, 'setphoto', 'Immagine del gruppo')
set_text(LANG, 'photoSaved', 'Foto salvata!')
set_text(LANG, 'photoFailed', 'Errore, per favore prova di nuovo!')
set_text(LANG, 'setPhotoAborted', 'Interruzione impostazione della foto...')
set_text(LANG, 'sendPhoto', 'Per favore, invia un\'immagine')
set_text(LANG, 'chatSetphoto', 'Now you can setphoto in this chat.')
set_text(LANG, 'channelSetphoto', 'Now you can setphoto in this channel.')
set_text(LANG, 'notChatSetphoto', 'Now you can\'t setphoto in this chat.')
set_text(LANG, 'notChannelSetphoto', 'Now you can\'t setphoto in this channel.')
set_text(LANG, 'setPhotoError', 'Please, enable setphoto settings.')
set_text(LANG, 'linkSaved', 'Nuovo link salvato.')
set_text(LANG, 'groupLink', 'Link del gruppo')
set_text(LANG, 'sGroupLink', 'Link del supergruppo')
set_text(LANG, 'noLinkSet', 'Il link non è ancora stato settato. Per favore impostalo con #setlink [Link].')
set_text(LANG, 'chatRename', 'Ora il gruppo può essere rinominato.')
set_text(LANG, 'channelRename', 'Ora il supergruppo può essere rinominato.')
set_text(LANG, 'notChatRename', 'Ora il gruppo non può essere rinominato.')
set_text(LANG, 'notChannelRename', 'Ora il supergruppo non può essere rinominato.')
set_text(LANG, 'lockMembersT', 'Il numero di membri è stato bloccato in questo gruppo.')
set_text(LANG, 'lockMembersL', 'Il numero di membri è stato bloccato in questo supergruppo.')
set_text(LANG, 'notLockMembersT', 'Il numero di membri è stato sbloccato in questo gruppo.')
set_text(LANG, 'notLockMembersL', 'Il numero di membri è stato sbloccato in questo supergruppo.')
set_text(LANG, 'langUpdated', 'La lingua del bot è stata aggiornata a: ')
set_text(LANG, 'chatUpgrade', 'Chat Upgraded Successfully.')
set_text(LANG, 'notInChann', 'You can\'t do this in a supergroup.')
set_text(LANG, 'desChanged', 'Channel description has been changed.')
set_text(LANG, 'desOnlyChannels', 'Description only can be changed in channels.')
set_text(LANG, 'muteAll', 'Everyone is muted now.')
set_text(LANG, 'unmuteAll', 'Everyone can talk now.')
set_text(LANG, 'muteAllX:1', 'This channel has been muted for')
set_text(LANG, 'muteAllX:2', 'seconds.')
set_text(LANG, 'createGroup:1', 'Group')
set_text(LANG, 'createGroup:2', 'created.')
set_text(LANG, 'newGroupWelcome', 'Welcome to your new group.')
-- export_gban.lua --
set_text(LANG, 'accountsGban', 'Utenti bannati globalmente.')
-- giverank.lua --
set_text(LANG, 'alreadyAdmin', 'Questo utente è già un amministratore.')
set_text(LANG, 'alreadyMod', 'Questo utente è già un moderatore.')
set_text(LANG, 'newAdmin', 'Nuovo amministratore')
set_text(LANG, 'newMod', 'Nuovo moderatore')
set_text(LANG, 'nowUser', 'è ora un utente.')
set_text(LANG, 'modList', 'Lista dei moderatori')
set_text(LANG, 'adminList', 'Lista degli amministratori')
set_text(LANG, 'modEmpty', 'La lista dei moderatori è vuota in questo gruppo.')
set_text(LANG, 'adminEmpty', 'La lista degli amministratori è vuota.')
-- id.lua --
set_text(LANG, 'user', 'Utente')
set_text(LANG, 'supergroupName', 'Nome del supergruppo')
set_text(LANG, 'chatName', 'Nome del gruppo')
set_text(LANG, 'supergroup', 'Supergruppo')
set_text(LANG, 'chat', 'Gruppo')
-- moderation.lua --
set_text(LANG, 'userUnmuted:1', 'Utente')
set_text(LANG, 'userUnmuted:2', 'desilenziato.')
set_text(LANG, 'userMuted:1', 'Utente')
set_text(LANG, 'userMuted:2', 'silenziato.')
set_text(LANG, 'kickUser:1', 'Utente')
set_text(LANG, 'kickUser:2', 'kickato.')
set_text(LANG, 'banUser:1', 'Utente')
set_text(LANG, 'banUser:2', 'bannato.')
set_text(LANG, 'unbanUser:1', 'Utente')
set_text(LANG, 'unbanUser:2', 'unbannato.')
set_text(LANG, 'gbanUser:1', 'Utente')
set_text(LANG, 'gbanUser:2', 'bannato globalmente.')
set_text(LANG, 'ungbanUser:1', 'Utente')
set_text(LANG, 'ungbanUser:2', 'unbannato globalmente.')
set_text(LANG, 'addUser:1', 'Utente')
set_text(LANG, 'addUser:2', 'aggiunto al gruppo.')
set_text(LANG, 'addUser:3', 'aggiunto al supergruppo.')
set_text(LANG, 'kickmeBye', 'ciao.')
-- plugins.lua --
set_text(LANG, 'plugins', 'Plugins')
set_text(LANG, 'installedPlugins', 'plugins installati.')
set_text(LANG, 'pEnabled', 'abilitato.')
set_text(LANG, 'pDisabled', 'disabilitato.')
set_text(LANG, 'isEnabled:1', 'Il plugin')
set_text(LANG, 'isEnabled:2', 'è abilitato.')
set_text(LANG, 'notExist:1', 'Il plugin')
set_text(LANG, 'notExist:2', 'non esiste.')
set_text(LANG, 'notEnabled:1', 'Il plugin')
set_text(LANG, 'notEnabled:2', 'non è abilitato.')
set_text(LANG, 'pNotExists', 'Il plugin non esiste.')
set_text(LANG, 'pDisChat:1', 'Il plugin')
set_text(LANG, 'pDisChat:2', 'è disabilitato in questa chat.')
set_text(LANG, 'anyDisPlugin', 'Non ci sono plugin diabilitati.')
set_text(LANG, 'anyDisPluginChat', 'Non ci sono plugin disabilitati in questa chat.')
set_text(LANG, 'notDisabled', 'Questo plugin non è diabilitato')
set_text(LANG, 'enabledAgain:1', 'Il plugin')
set_text(LANG, 'enabledAgain:2', 'è di nuovo abilitato')
-- commands.lua --
set_text(LANG, 'commandsT', 'Comandi')
set_text(LANG, 'errorNoPlug', 'Questo plugin non esiste o non ha una descrizione.')
-- rules.lua --
set_text(LANG, 'setRules', 'Chat rules have been updated.')
set_text(LANG, 'remRules', 'Chat rules have been removed.')
------------
-- Usages --
------------
-- bot.lua --
set_text(LANG, 'bot:0', 2)
set_text(LANG, 'bot:1', '#bot on: abilita il bot sul gruppo corrente.')
set_text(LANG, 'bot:2', '#bot off: disabilita il bot sul gruppo corrente.')
-- commands.lua --
set_text(LANG, 'commands:0', 2)
set_text(LANG, 'commands:1', '#commands: mostra la descrizione di ogni plugin.')
set_text(LANG, 'commands:2', '#commands [plugin]: descrizione del plugin.')
-- export_gban.lua --
set_text(LANG, 'export_gban:0', 2)
set_text(LANG, 'export_gban:1', '#gbans installer: invia un file lua per condividere la tua lista di ban globali ed inviarla in un altro gruppo.')
set_text(LANG, 'export_gban:2', '#gbans list: invia un archivio con la lista degli utenti bannati globalmente.')
-- gban_installer.lua --
set_text(LANG, 'gban_installer:0', 1)
set_text(LANG, 'gban_installer:1', '#install gbans: aggiungi una lista di utenti al db redis dei ban globali.')
-- giverank.lua --
set_text(LANG, 'giverank:0', 9)
set_text(LANG, 'giverank:1', '#rank admin (risposta): promuovi ad amministratore tramite risposta.')
set_text(LANG, 'giverank:2', '#rank admin <id_utente>/<username>: aggiungi un amministratore tramite ID/username.')
set_text(LANG, 'giverank:3', '#rank mod (risposta): aggiungi un moderatore tramite risposta.')
set_text(LANG, 'giverank:4', '#rank mod <id_utente>/<username>: aggiungi un moderatore tramite ID/Username.')
set_text(LANG, 'giverank:5', '#rank guest (risposta): rimuovi un amministratore tramite risposta.')
set_text(LANG, 'giverank:6', '#rank guest <user_id>/<user_name>: rimuovi un amministratore tramite ID/Username.')
set_text(LANG, 'giverank:7', '#admins: lista degli amministratori del gruppo.')
set_text(LANG, 'giverank:8', '#mods: lista dei moderatori del gruppo.')
set_text(LANG, 'giverank:9', '#members: lista dei membri della chat.')
-- id.lua --
set_text(LANG, 'id:0', 6)
set_text(LANG, 'id:1', '#id: mostra il tuo ID e l\'ID del gruppo se ti trovi in una chat.')
set_text(LANG, 'id:2', '#ids chat: mostra gli ID dei membri del gruppo.')
set_text(LANG, 'id:3', '#ids channel: mostra gli ID dei membri del supergruppo.')
set_text(LANG, 'id:4', '#id <username>: mostra l\'ID dell\'utente in questa chat.')
set_text(LANG, 'id:5', '#whois <id_utente>/<username>: mostra lo username.')
set_text(LANG, 'id:6', '#whois (risposta): mostra l\'ID.')
-- moderation.lua --
set_text(LANG, 'moderation:0', 18)
set_text(LANG, 'moderation:1', '#add: rispondendo ad un messaggio, l\'utente verrà aggiunto al gruppo/supergruppo.')
set_text(LANG, 'moderation:2', '#add <id>/<username>: aggiungi un utente tramite ID/username al gruppo/supergruppo.')
set_text(LANG, 'moderation:3', '#kick: rispondendo ad un messaggio, l\'utente verrà rimosso dal gruppo/supergruppo.')
set_text(LANG, 'moderation:4', '#kick <id>/<username>: rimuovi un utente tramite ID/username al gruppo/supergruppo.')
set_text(LANG, 'moderation:5', '#kickme: fatti rimuovere.')
set_text(LANG, 'moderation:6', '#ban: rispondendo ad un messaggio, l\'utente verrà bannato dal gruppo/supergruppo.')
set_text(LANG, 'moderation:7', '#ban <id>/<username>: banna un utente tramite ID/username al gruppo/supergruppo.')
set_text(LANG, 'moderation:8', '#unban: rispondendo ad un messaggio, l\'utente verrà unbannato dal gruppo/supergruppo.')
set_text(LANG, 'moderation:9', '#unban <id>/<username>: unbanna un utente tramite ID/username al gruppo/supergruppo.')
set_text(LANG, 'moderation:10', '#gban: rispondendo ad un messaggio, l\'utente verrà bannato globalmente da ogni gruppo/supergruppo.')
set_text(LANG, 'moderation:11', '#gban <id>/<username>: banna globalmente un utente tramite ID/username da ogni gruppo/supergruppo.')
set_text(LANG, 'moderation:12', '#ungban: rispondendo ad un messaggio, l\'utente verrà unbannato globalmente.')
set_text(LANG, 'moderation:13', '#ungban <id>/<username>: unbanna globalmente un utente tramite ID/username.')
set_text(LANG, 'moderation:14', '#mute: rispondendo ad un messaggio, l\'utente verrà silenziato nel corrente supergruppo, ed ogni suo messaggio verrà cancellato.')
set_text(LANG, 'moderation:15', '#mute <id>/<username>: l\'utente verrà silenziato tramite ID/username nel corrente supergruppo, ed ogni suo messaggio verrà cancellato.')
set_text(LANG, 'moderation:16', '#unmute: rispondendo ad un messaggio, l\'utente verrà desilenziato nel corrente supergruppo.')
set_text(LANG, 'moderation:17', '#unmute <id>/<username>: l\'utente verrà desilenziato tramite ID/username nel corrente supergruppo.')
set_text(LANG, 'moderation:18', '#rem: rispondendo ad un messaggio, questo verrà rimosso.')
-- settings.lua --
set_text(LANG, 'settings:0', 20)
set_text(LANG, 'settings:1', '#settings stickers enable/disable: quando abilitato, ogni sticker verrà rimosso.')
set_text(LANG, 'settings:2', '#settings links enable/disable: quando abilitato, ogni link verrà rimosso.')
set_text(LANG, 'settings:3', '#settings arabic enable/disabl: quando abilitato, ogni messaggio contenente caratteri arabi e persiani verrà rimosso.')
set_text(LANG, 'settings:4', '#settings bots enable/disable: quando abilitato, ogni ogni bot aggiunto verrà rimosso.')
set_text(LANG, 'settings:5', '#settings gifs enable/disable: quando abilitato, ogni gif verrà rimossa.')
set_text(LANG, 'settings:6', '#settings photos enable/disable: quando abilitato, ogni immagine verrà rimossa.')
set_text(LANG, 'settings:7', '#settings audios enable/disable: quando abilitato, ogni vocale verrà rimosso.')
set_text(LANG, 'settings:8', '#settings kickme enable/disable: quando abilitato, gli utenti possono kickarsi autonomamente.')
set_text(LANG, 'settings:9', '#settings spam enable/disable: quando abilitato, ogni link spam verrà rimosso.')
set_text(LANG, 'settings:10', '#settings setphoto enable/disable: quando abilitato, se un utente cambia icona del gruppo, il bot ripristinerà quella salvata.')
set_text(LANG, 'settings:11', '#settings setname enable/disable: quando abilitato, se un utente cambia il nome del gruppo, il bot ripristinerà il nome salvato.')
set_text(LANG, 'settings:12', '#settings lockmembers enable/disable: quando abilitato, il bot rimuoverà ogni utente che etrerà nel gruppo.')
set_text(LANG, 'settings:13', '#settings floodtime <secondi>: imposta l\'intervallo di monitoraggio del flood.')
set_text(LANG, 'settings:14', '#settings maxflood <messaggi>: imposta il numero di messaggi inviati nel floodtime affinchè vengano considerati flood.')
set_text(LANG, 'settings:15', '#setname <nome gruppo>: vambia il nome della chat.')
set_text(LANG, 'settings:16', '#setphoto <poi invia la foto>: cambia la foto della chat.')
set_text(LANG, 'settings:17', '#lang <language (en, es...)>: cambia l\'idioma del bot.')
set_text(LANG, 'settings:18', '#setlink <link>: salva il link del gruppo.')
set_text(LANG, 'settings:19', '#link: mostra il link del gruppo.')
set_text(LANG, 'settings:20', '#settings tgservices enable/disable: when disabled, new user participant message will be erased.')
-- plugins.lua --
set_text(LANG, 'plugins:0', 4)
set_text(LANG, 'plugins:1', '#plugins: mostra una lista di tutti i plugin.')
set_text(LANG, 'plugins:2', '#plugins <enable>/<disable> [plugin]: abilita/disabilita il plugin specifico.')
set_text(LANG, 'plugins:3', '#plugins <enable>/<disable> [plugin] chat: abilita/disabilita il plugin specifico, ma solo sulla chat corrente.')
set_text(LANG, 'plugins:4', '#plugins reload: ricarica tutti i plugin.')
-- version.lua --
set_text(LANG, 'version:0', 1)
set_text(LANG, 'version:1', '#version: mostra la versione del bot.')
-- rules.lua --
set_text(LANG, 'rules:0', 1)
set_text(LANG, 'rules:1', '#rules: mostra le regole della chat.')
if matches[1] == 'install' then
return 'ℹ️¸ L\'italiano è stato installato come lingua del bot.'
elseif matches[1] == 'update' then
return 'ℹ️ Stringhe italiane aggiornate.'
end
else
return "ℹ️ Questo plugin richiede i privilegi di sudo."
end
end
return {
patterns = {
'[!/#](install) (italian_lang)$',
'[!/#](update) (italian_lang)$'
},
run = run
}
| gpl-2.0 |
switch-ch/switchdrive-ansible | roles/haproxy/templates/lua/ldapUserLookup.lua | 1 | 1868 | package.cpath = package.cpath .. ";/usr/lib/lua/5.3/?.so";
local lualdap = require "lualdap"
local ldap = nil;
local servers = {"86.119.30.169", "86.119.34.136"}
local server_id = 0;
function connect()
-- "{hostvars[groups['ldap'][0]].inventory_hostname}}",
ldap = assert (lualdap.open_simple (
servers[server_id+1],
"cn=admin,dc=cloud,dc=switch,dc=ch",
"{{ldap_password}}"))
end
core.register_init(function()
--core.Warning("connecting to " .. servers[server_id+1]);
end)
core.register_task(function()
if (ldap == nil) then
server_id = (server_id + 1) % 2;
connect();
end
core.Warning("connecting to " .. servers[server_id+1]);
end)
function search(user)
local result = "not found";
for dn, attribs in ldap:search {
base = "ou=Users,dc=cloud,dc=switch,dc=ch",
scope = "subtree",
filter = "(&(&(&(objectclass=inetOrgPerson)(objectclass=eduMember))(isMemberOf=ownCloud)(mail=" .. user .. ")))",
sizelimit = 1,
attrs = {"o", "isMemberOf"}
} do
for name, values in pairs (attribs) do
-- result = result .. name;
if (name == "o") then
if type (values) == "string" then
result = values;
elseif type (values) == "table" then
local n = table.getn(values)
for i = 1, (n-1) do
result = result .. "," .. values[i];
end
end
end
end
end
return result;
end
core.register_converters("ldapUserLookup", function(user)
if (ldap == nil) then
server_id = (server_id + 1) % 2;
connect();
end
local status, result = pcall(search, user);
if (status == false) then
ldap = nil;
end
return result;
end)
| agpl-3.0 |
brahmi2/prosody-modules | mod_couchdb/couchdb/mod_couchdb.lua | 32 | 2155 |
local http = require "socket.http";
local url = require "socket.url";
local couchapi = module:require("couchdb/couchapi");
local json = module:require("couchdb/json");
local couchdb_url = assert(module:get_option("couchdb_url"), "Option couchdb_url not specified");
local db = couchapi.db(couchdb_url);
local function couchdb_get(key)
local a,b = db:doc(key):get()
print(json.encode(a));
if b == 404 then return nil; end
if b == 200 then b = nil; end
return a.payload,b;
end
local function couchdb_put(key, value)
local a,b = db:doc(key):get();
return db:doc(key):put({ payload = value, _rev = a and a._rev });
end
local st = require "util.stanza";
local handlers = {};
handlers.accounts = {
get = function(self, user)
return couchdb_get(self.host.."/"..user.."/account");
end;
set = function(self, user, data)
return couchdb_put(self.host.."/"..user.."/account", data);
end;
};
handlers.vcard = {
get = function(self, user)
return couchdb_get(self.host.."/"..user.."/vcard");
end;
set = function(self, user, data)
return couchdb_put(self.host.."/"..user.."/vcard", data);
end;
};
handlers.private = {
get = function(self, user)
return couchdb_get(self.host.."/"..user.."/private");
end;
set = function(self, user, data)
return couchdb_put(self.host.."/"..user.."/private", data);
end;
};
handlers.roster = {
get = function(self, user)
return couchdb_get(self.host.."/"..user.."/roster");
end;
set = function(self, user, data)
return couchdb_put(self.host.."/"..user.."/roster", data);
end;
};
-----------------------------
local driver = {};
function driver:open(datastore, typ)
local handler = handlers[datastore];
if not handler then return nil; end
local host = module.host;
--local cache_key = host.." "..datastore;
--if self.ds_cache[cache_key] then return self.ds_cache[cache_key]; end
local instance = setmetatable({ host = host, datastore = datastore }, { __index = handler });
--for key,val in pairs(handler) do
-- instance[key] = val;
--end
--if instance.init then instance:init(); end
--self.ds_cache[cache_key] = instance;
return instance;
end
module:provides("storage", driver);
| mit |
ArchShaman/Zero-K | scripts/striderdetriment.lua | 9 | 9561 | include 'constants.lua'
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- pieces
local pelvis, torso, head, shouldercannon, shoulderflare = piece('pelvis', 'torso', 'head', 'shouldercannon', 'shoulderflare')
local aaturret, aagun, aaflare1, aaflare2, headlaser1, headlaser2, headlaser3 = piece('AAturret', 'AAguns', 'AAflare1', 'AAflare2', 'headlaser1', 'headlaser2', 'headlaser3')
local larm, larmcannon, larmbarrel1, larmflare1, larmbarrel2, larmflare2, larmbarrel3, larmflare3 = piece('larm', 'larmcannon', 'larmbarrel1', 'larmflare1',
'larmbarrel2', 'larmflare2', 'larmbarrel3', 'larmflare3')
local rarm, rarmcannon, rarmbarrel1, rarmflare1, rarmbarrel2, rarmflare2, rarmbarrel3, rarmflare3 = piece('rarm', 'rarmcannon', 'rarmbarrel1', 'rarmflare1',
'rarmbarrel2', 'rarmflare2', 'rarmbarrel3', 'rarmflare3')
local lupleg, lmidleg, lleg, lfoot, lftoe, lbtoe = piece('lupleg', 'lmidleg', 'lleg', 'lfoot', 'lftoe', 'lbtoe')
local rupleg, rmidleg, rleg, rfoot, rftoe, rbtoe = piece('rupleg', 'rmidleg', 'rleg', 'rfoot', 'rftoe', 'rbtoe')
local leftLeg = { thigh=piece'lupleg', knee=piece'lmidleg', shin=piece'lleg', foot=piece'lfoot', toef=piece'lftoe', toeb=piece'lbtoe' }
local rightLeg = { thigh=piece'rupleg', knee=piece'rmidleg', shin=piece'rleg', foot=piece'rfoot', toef=piece'rftoe', toeb=piece'rbtoe' }
local smokePiece = { torso, head, shouldercannon }
local gunFlares = {
{larmflare1, larmflare2, larmflare3, rarmflare1, rarmflare2, rarmflare3},
{aaflare1, aaflare2},
{shoulderflare},
{headlaser1, headlaser2, headlaser3}
}
local barrels = {larmbarrel1, larmbarrel2, larmbarrel3, rarmbarrel1, rarmbarrel2, rarmbarrel3}
local aimpoints = {torso, aaturret, shoulderflare, head}
local gunIndex = {1,1,1,1}
local flareIndex = {1,1,1,1}
local lastTorsoHeading = 0
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--signals
local SIG_Restore = 1
local SIG_Walk = 2
local PACE = 0.8
-- four leg positions - front to straight, then to back, then to bent (then front again)
local LEG_FRONT_ANGLES = { thigh=math.rad(-40), knee=math.rad(-10), shin=math.rad(50), foot=math.rad(0), toef=math.rad(0), toeb=math.rad(15) }
local LEG_FRONT_SPEEDS = { thigh=math.rad(60)*PACE, knee=math.rad(60)*PACE, shin=math.rad(110)*PACE, foot=math.rad(90)*PACE, toef=math.rad(90)*PACE, toeb=math.rad(30)*PACE }
local LEG_STRAIGHT_ANGLES = { thigh=math.rad(-10), knee=math.rad(-20), shin=math.rad(30), foot=math.rad(0), toef=math.rad(0), toeb=math.rad(0) }
local LEG_STRAIGHT_SPEEDS = { thigh=math.rad(60)*PACE, knee=math.rad(30)*PACE, shin=math.rad(40)*PACE, foot=math.rad(90)*PACE, toef=math.rad(90)*PACE, toeb=math.rad(30)*PACE }
local LEG_BACK_ANGLES = { thigh=math.rad(10), knee=math.rad(-5), shin=math.rad(15), foot=math.rad(0), toef=math.rad(-20), toeb=math.rad(-10) }
local LEG_BACK_SPEEDS = { thigh=math.rad(30)*PACE, knee=math.rad(60)*PACE, shin=math.rad(90)*PACE, foot=math.rad(90)*PACE, toef=math.rad(40)*PACE, toeb=math.rad(60)*PACE }
local LEG_BENT_ANGLES = { thigh=math.rad(-15), knee=math.rad(20), shin=math.rad(-20), foot=math.rad(0), toef=math.rad(0), toeb=math.rad(0) }
local LEG_BENT_SPEEDS = { thigh=math.rad(60)*PACE, knee=math.rad(90)*PACE, shin=math.rad(90)*PACE, foot=math.rad(90)*PACE, toef=math.rad(90)*PACE, toeb=math.rad(90)*PACE }
local TORSO_ANGLE_MOTION = math.rad(8)
local TORSO_SPEED_MOTION = math.rad(15)*PACE
local TORSO_TILT_ANGLE = math.rad(15)
local TORSO_TILT_SPEED = math.rad(15)*PACE
local PELVIS_LIFT_HEIGHT = 6
local PELVIS_LIFT_SPEED = 16
local PELVIS_LOWER_HEIGHT = 2
local PELVIS_LOWER_SPEED = 16
local ARM_FRONT_ANGLE = math.rad(-15)
local ARM_FRONT_SPEED = math.rad(35) * PACE
local ARM_BACK_ANGLE = math.rad(5)
local ARM_BACK_SPEED = math.rad(30) * PACE
local isFiring = false
local CHARGE_TIME = 60 -- frames
local FIRE_TIME = 120
local unitDefID = Spring.GetUnitDefID(unitID)
local wd = UnitDefs[unitDefID].weapons[3] and UnitDefs[unitDefID].weapons[3].weaponDef
local reloadTime = wd and WeaponDefs[wd].reload*30 or 30
wd = UnitDefs[unitDefID].weapons[1] and UnitDefs[unitDefID].weapons[1].weaponDef
local reloadTimeShort = wd and WeaponDefs[wd].reload*30 or 30
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function script.Create()
Turn(larm, z_axis, -0.1)
Turn(rarm, z_axis, 0.1)
Turn(shoulderflare, x_axis, math.rad(-90))
StartThread(SmokeUnit, smokePiece)
end
local function Step(frontLeg, backLeg)
-- contact: legs fully extended in stride
for i,p in pairs(frontLeg) do
Turn(frontLeg[i], x_axis, LEG_FRONT_ANGLES[i], LEG_FRONT_SPEEDS[i])
Turn(backLeg[i], x_axis, LEG_BACK_ANGLES[i], LEG_BACK_SPEEDS[i])
end
-- swing arms and body
if not(isFiring) then
if (frontLeg == leftLeg) then
Turn(torso, y_axis, TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION)
Turn(larm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
Turn(larmcannon, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
Turn(rarm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED)
else
Turn(torso, y_axis, -TORSO_ANGLE_MOTION, TORSO_SPEED_MOTION)
Turn(larm, x_axis, ARM_FRONT_ANGLE, ARM_FRONT_SPEED)
Turn(rarmcannon, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
Turn(rarm, x_axis, ARM_BACK_ANGLE, ARM_BACK_SPEED)
end
end
Move(pelvis, y_axis, PELVIS_LOWER_HEIGHT, PELVIS_LOWER_SPEED)
Turn(torso, x_axis, TORSO_TILT_ANGLE, TORSO_TILT_SPEED)
for i, p in pairs(frontLeg) do
WaitForTurn(frontLeg[i], x_axis)
WaitForTurn(backLeg[i], x_axis)
end
-- passing (front foot flat under body, back foot passing with bent knee)
for i, p in pairs(frontLeg) do
Turn(frontLeg[i], x_axis, LEG_STRAIGHT_ANGLES[i], LEG_STRAIGHT_SPEEDS[i])
Turn(backLeg[i], x_axis, LEG_BENT_ANGLES[i], LEG_BENT_SPEEDS[i])
end
Move(pelvis, y_axis, PELVIS_LIFT_HEIGHT, PELVIS_LIFT_SPEED)
Turn(torso, x_axis, 0, TORSO_TILT_SPEED)
for i, p in pairs(frontLeg) do
WaitForTurn(frontLeg[i], x_axis)
WaitForTurn(backLeg[i], x_axis)
end
Sleep(0)
end
local function Walk()
Signal(SIG_Walk)
SetSignalMask(SIG_Walk)
while (true) do
Step(leftLeg, rightLeg)
Step(rightLeg, leftLeg)
end
end
local function StopWalk()
Signal(SIG_Walk)
SetSignalMask(SIG_Walk)
Move(torso, y_axis, 0, 100)
for i,p in pairs(leftLeg) do
Turn(leftLeg[i], x_axis, 0, LEG_STRAIGHT_SPEEDS[i])
Turn(rightLeg[i], x_axis, 0, 2)
end
Turn(pelvis, z_axis, 0, 1)
Turn(torso, x_axis, 0, 1)
if not(isFiring) then
Turn(torso, y_axis, 0, 4)
end
Move(pelvis, y_axis, 0, 50)
Turn(rarm, x_axis, 0, 1)
Turn(larm, x_axis, 0, 1)
end
function script.StartMoving()
StartThread(Walk)
end
function script.StopMoving()
StartThread(StopWalk)
end
local function RestoreAfterDelay()
Signal(SIG_Restore)
SetSignalMask(SIG_Restore)
Sleep(5000)
Turn(head, y_axis, 0, 2)
Turn(torso, y_axis, 0, 1.5)
Turn(larm, x_axis, 0, 2)
Turn(rarm, x_axis, 0, 2)
Turn(shouldercannon, x_axis, 0, math.rad(90))
isFiring = false
lastTorsoHeading = 0
end
function script.AimFromWeapon(num)
return aimpoints[num]
end
function script.QueryWeapon(num)
return gunFlares[num][ flareIndex[num] ]
end
function script.AimWeapon(num, heading, pitch)
local SIG_AIM = 2^(num+1)
isFiring = true
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
StartThread(RestoreAfterDelay)
if num == 1 then
Turn(torso, y_axis, heading, math.rad(180))
Turn(larm, x_axis, -pitch, math.rad(120))
Turn(rarm, x_axis, -pitch, math.rad(120))
WaitForTurn(torso, y_axis)
WaitForTurn(larm, x_axis)
elseif num == 2 then
Turn(aaturret, y_axis, heading - lastTorsoHeading, math.rad(360))
Turn(aagun, x_axis, -pitch, math.rad(240))
WaitForTurn(aaturret, y_axis)
WaitForTurn(aagun, x_axis)
elseif num == 3 then
--Turn(torso, y_axis, heading, math.rad(180))
--Turn(shouldercannon, x_axis, math.rad(90) - pitch, math.rad(270))
--WaitForTurn(torso, y_axis)
--WaitForTurn(shouldercannon, x_axis)
elseif num == 4 then
Turn(torso, y_axis, heading, math.rad(180))
WaitForTurn(torso, y_axis)
end
if num ~= 2 then
lastTorsoHeading = heading
end
return true
end
function script.Shot(num)
if num == 1 then
Move(barrels[gunIndex[1]], z_axis, -20)
Move(barrels[gunIndex[1]], z_axis, 0, 20)
end
flareIndex[num] = gunIndex[num] -- store current gunIndex in flareIndex
gunIndex[num] = gunIndex[num] + 1
if gunIndex[num] > #gunFlares[num] then
gunIndex[num] = 1
end
end
function script.BlockShot(num, targetID)
if not targetID then
return false
end
if GG.DontFireRadar_CheckBlock(unitID, targetID) then
return true
end
-- Seperation check is not required as the physics of the missile seems to result in a
-- time to impact of between 140 and 150 frames in almost all cases.
if GG.OverkillPrevention_CheckBlock(unitID, targetID, 800.1, 150, false, false, true) then
return true
end
return false
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
if (severity <= .5) then
Explode(torso, sfxNone)
Explode(head, sfxNone)
Explode(pelvis, sfxNone)
Explode(rarmcannon, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(larmcannon, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(larm, sfxShatter)
return 1 -- corpsetype
else
Explode(torso, sfxShatter)
Explode(head, sfxSmoke + sfxFire)
Explode(pelvis, sfxShatter)
return 2 -- corpsetype
end
end
| gpl-2.0 |
jokerdevv/Joker-Developer | plugins/msg_checks.lua | 10 | 10753 | --[[
# For More Information ....!
# Developer : Aziz < @devss_bot > #Dev
# our channel: @help_tele
]]
--Begin msg_checks.lua
--Begin pre_process function
local function pre_process(msg)
-- Begin 'RondoMsgChecks' text checks by @rondoozle
if is_chat_msg(msg) or is_super_group(msg) then
if msg and not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user
local data = load_data(_config.moderation.data)
local print_name = user_print_name(msg.from):gsub("", "") -- get rid of rtl in names
local name_log = print_name:gsub("_", " ") -- name for log
local to_chat = msg.to.type == 'chat'
if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then
settings = data[tostring(msg.to.id)]['settings']
else
return
end
if settings.lock_arabic then
lock_arabic = settings.lock_arabic
else
lock_arabic = 'no'
end
if settings.lock_rtl then
lock_rtl = settings.lock_rtl
else
lock_rtl = 'no'
end
if settings.lock_link then
lock_link = settings.lock_link
else
lock_link = 'no'
end
if settings.lock_member then
lock_member = settings.lock_member
else
lock_member = 'no'
end
if settings.lock_spam then
lock_spam = settings.lock_spam
else
lock_spam = 'no'
end
if settings.lock_sticker then
lock_sticker = settings.lock_sticker
else
lock_sticker = 'no'
end
if settings.lock_contacts then
lock_contacts = settings.lock_contacts
else
lock_contacts = 'no'
end
if settings.strict then
strict = settings.strict
else
strict = 'no'
end
if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then
delete_msg(msg.id, ok_cb, false)
if to_chat then
-- kick_user(msg.from.id, msg.to.id)
end
end
if msg.text then -- msg.text checks
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
local _nl, real_digits = string.gsub(msg.text, '%d', '')
if lock_spam == "yes" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
delete_msg(msg.id, ok_cb, false)
kick_user(msg.from.id, msg.to.id)
end
end
local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=")
if is_link_msg and lock_link == "yes" and not is_bot then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_squig_msg = msg.text:match("[\216-\219][\128-\191]")
if is_squig_msg and lock_arabic == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local print_name = msg.from.print_name
local is_rtl = print_name:match("") or msg.text:match("")
if is_rtl and lock_rtl == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then
delete_msg(msg.id, ok_cb, false)
if to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
end
if msg.media then -- msg.media checks
if msg.media.title then
local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if is_link_title and lock_link == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]")
if is_squig_title and lock_arabic == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
end
if msg.media.description then
local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if is_link_desc and lock_link == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]")
if is_squig_desc and lock_arabic == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
end
if msg.media.caption then -- msg.media.caption checks
local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if is_link_caption and lock_link == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]")
if is_squig_caption and lock_arabic == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_username_caption = msg.media.caption:match("^@[%a%d]")
if is_username_caption and lock_link == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
if lock_sticker == "yes" and msg.media.caption:match("sticker.webp") then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
end
if msg.media.type:match("contact") and lock_contacts == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg",
if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
-- kick_user(msg.from.id, msg.to.id)
end
end
local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4")
if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
-- kick_user(msg.from.id, msg.to.id)
end
end
if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video")
if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
end
if msg.fwd_from then
if msg.fwd_from.title then
local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if is_link_title and lock_link == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]")
if is_squig_title and lock_arabic == "yes" then
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
kick_user(msg.from.id, msg.to.id)
end
end
end
if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then
delete_msg(msg.id, ok_cb, false)
end
end
if msg.service then -- msg.service checks
local action = msg.action.type
if action == 'chat_add_user_link' then
local user_id = msg.from.id
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and Service Msg deleted (#spam name)")
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and kicked (#spam name)")
kick_user(msg.from.id, msg.to.id)
end
end
local print_name = msg.from.print_name
local is_rtl_name = print_name:match("")
if is_rtl_name and lock_rtl == "yes" then
savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#RTL char in name)")
kick_user(user_id, msg.to.id)
end
if lock_member == 'yes' then
savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#lockmember)")
kick_user(user_id, msg.to.id)
delete_msg(msg.id, ok_cb, false)
end
end
if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then
local user_id = msg.action.user.id
if string.len(msg.action.user.print_name) > 70 and lock_group_spam == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: Service Msg deleted (#spam name)")
delete_msg(msg.id, ok_cb, false)
if strict == "yes" or to_chat then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#spam name) ")
delete_msg(msg.id, ok_cb, false)
kick_user(msg.from.id, msg.to.id)
end
end
local print_name = msg.action.user.print_name
local is_rtl_name = print_name:match("")
if is_rtl_name and lock_rtl == "yes" then
savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#RTL char in name)")
kick_user(user_id, msg.to.id)
end
if msg.to.type == 'channel' and lock_member == 'yes' then
savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#lockmember)")
kick_user(user_id, msg.to.id)
delete_msg(msg.id, ok_cb, false)
end
end
end
end
end
-- End 'RondoMsgChecks' text checks by @Rondoozle
return msg
end
--End pre_process function
return {
patterns = {},
pre_process = pre_process
}
--End msg_checks.lua
--By @Rondoozle
| gpl-2.0 |
jboecker/dcs-witchcraft | WitchcraftExport.lua | 1 | 4752 | -- This is a stripped-down version of witchcraft.lua adapted to work
-- as a backend for the Lua Console within the Export.lua environment.
-- Call this file from export.lua to use the Witchcraft Lua Console
-- in the DCS Export environment.
-- Note that you should not run a mission that calls witchcraft.start() at the same time,
-- as both will connect to the server at the same time, which probably leads to interesting(TM) results.
do
local witchcraft = {}
witchcraft.host = "localhost"
witchcraft.port = 3001
local require = require
local loadfile = loadfile
package.path = package.path..";.\\LuaSocket\\?.lua"
package.cpath = package.cpath..";.\\LuaSocket\\?.dll"
local JSON = loadfile("Scripts\\JSON.lua")()
witchcraft.JSON = JSON
local socket = require("socket")
function witchcraft.step(arg, time)
witchcraft.txbuf = witchcraft.txbuf .. '{"type":"dummy"}\n'
if witchcraft.txbuf:len() > 0 then
local bytes_sent = nil
local ret1, ret2, ret3 = witchcraft.conn:send(witchcraft.txbuf)
if ret1 then
bytes_sent = ret1
else
--env.info("could not send witchcraft: "..ret2)
if ret3 == 0 then
if ret2 == "closed" then
witchcraft.txbuf = '{"type":"dummy"}\n'
witchcraft.rxbuf = ""
witchcraft.lastUnitUpdateTime = 0
witchcraft.conn = socket.tcp()
witchcraft.conn:settimeout(.0001)
--env.info("witchcraft: socket was closed")
end
--env.info("reconnecting to "..tostring(witchcraft.host)..":"..tostring(witchcraft.port))
witchcraft.conn:connect(witchcraft.host, witchcraft.port)
return
end
bytes_sent = ret3
end
witchcraft.txbuf = witchcraft.txbuf:sub(bytes_sent + 1)
else
if witchcraft.txidle_hook then
local bool, err = pcall(witchcraft.txidle_hook)
if not bool then
--env.info("witchcraft.txidle_hook() failed: "..err)
end
end
end
local line, err = witchcraft.conn:receive()
if err then
--env.info("witchcraft read error: "..err)
else
msg = JSON:decode(line)
if msg.type == "lua" then
local response_msg = {}
response_msg.type = "luaresult"
response_msg.name = msg.name
local f, error_msg = loadstring(msg.code, msg.name)
if f then
witchcraft.context = {}
witchcraft.context.arg = msg.arg
setfenv(f, witchcraft.mission_env)
response_msg.success, response_msg.result = pcall(f)
else
response_msg.success = false
response_msg.result = tostring(error_msg)
end
local response_string = ""
local function encode_response()
response_string = JSON:encode(response_msg):gsub("\n","").."\n"
end
local success, result = pcall(encode_response)
if not success then
response_msg.success = false
response_msg.result = tostring(result)
encode_response()
end
witchcraft.txbuf = witchcraft.txbuf .. response_string
end
end
end
witchcraft.start = function(mission_env_)
witchcraft.mission_env = mission_env_
if not witchcraft.scheduled then
witchcraft.lastUnitUpdateTime = 0
witchcraft.unitUpdateInterval = 0
witchcraft.txbuf = '{"type":"dummy"}\n'
witchcraft.rxbuf = ""
witchcraft.lastUnitUpdateTime = 0
witchcraft.conn = socket.tcp()
witchcraft.conn:settimeout(.0001)
witchcraft.conn:connect(witchcraft.host, witchcraft.port)
witchcraft.scheduled = true
end
end
witchcraft.log = function(data)
local msg = { ["type"] = "log", ["data"] = data };
witchcraft.txbuf = witchcraft.txbuf .. JSON:encode(msg):gsub("\n","").."\n"
end
-- Prev Export functions.
local PrevExport = {}
PrevExport.LuaExportStart = LuaExportStart
PrevExport.LuaExportStop = LuaExportStop
PrevExport.LuaExportAfterNextFrame = LuaExportAfterNextFrame
local lastStepTime = 0
-- Lua Export Functions
LuaExportStart = function()
witchcraft.start(_G)
-- Chain previously-included export as necessary
if PrevExport.LuaExportStart then
PrevExport.LuaExportStart()
end
end
LuaExportStop = function()
-- Chain previously-included export as necessary
if PrevExport.LuaExportStop then
PrevExport.LuaExportStop()
end
end
function LuaExportAfterNextFrame()
local curTime = LoGetModelTime()
if curTime >= lastStepTime then
local bool, err = pcall(witchcraft.step)
if not bool then
--env.info("witchcraft.step() failed: "..err)
end
lastStepTime = curTime + .1
end
-- Chain previously-included export as necessary
if PrevExport.LuaExportAfterNextFrame then
PrevExport.LuaExportAfterNextFrame()
end
end
end
| gpl-3.0 |
focusworld/big | plugins/banhammer.lua | 4 | 11920 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$",
"^([Bb]anall) (.*)$",
"^([Bb]anall)$",
"^([Bb]anlist) (.*)$",
"^([Bb]anlist)$",
"^([Gg]banlist)$",
"^([Bb]an) (.*)$",
"^([Kk]ick)$",
"^([Uu]nban) (.*)$",
"^([Uu]nbanall) (.*)$",
"^([Uu]nbanall)$",
"^([Kk]ick) (.*)$",
"^([Kk]ickme)$",
"^([Bb]an)$",
"^([Uu]nban)$",
"^([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
darkstalker/moonhowl | src/moonhowl/gui/dm_view.lua | 1 | 1353 | local lgi = require "lgi"
local Gtk = lgi.Gtk
local object = require "moonhowl.object"
local ui = require "moonhowl.ui"
local dm_view = object:extend()
function dm_view:_init()
self.icon = ui.image_view:new()
self.handle = Gtk.Box{
id = "dm_view",
spacing = 10,
self.icon.handle,
Gtk.EventBox{
id = "content",
Gtk.Box{
orientation = Gtk.Orientation.VERTICAL,
hexpand = true,
spacing = 5,
Gtk.Label{ id = "header", use_markup = true, xalign = 0, ellipsize = "END" },
Gtk.Label{ id = "text", use_markup = true, xalign = 0, vexpand = true, wrap = true, wrap_mode = "WORD_CHAR" },
},
},
}
self.icon.handle.valign = Gtk.Align.START
self.icon.handle.margin_top = 3
local child = self.handle.child
self.header = child.header
self.text = child.text
end
function dm_view:set_content(dm)
self.content = dm
local icon = ""
if dm._type == "stream_dm" then
dm = dm.direct_message
icon = "✉ "
end
local user = dm.sender
self.header:set_label(('%s<b>%s</b> <span color="gray">%s</span>'):format(icon, user.screen_name, user.name))
self.text:set_label(dm.text)
self.icon:set_content(user.profile_image_url)
end
return dm_view
| mpl-2.0 |
ashemedai/ProDBG | bin/macosx/tundra/scripts/tundra/boot.lua | 25 | 4138 | module(..., package.seeall)
-- Use "strict" when developing to flag accesses to nil global variables
-- This has very low perf impact (<0.1%), so always leave it on.
require "strict"
local os = require "os"
local platform = require "tundra.platform"
local util = require "tundra.util"
local depgraph = require "tundra.depgraph"
local unitgen = require "tundra.unitgen"
local buildfile = require "tundra.buildfile"
local native = require "tundra.native"
-- This trio is so useful we want them everywhere without imports.
function _G.printf(msg, ...)
local str = string.format(msg, ...)
print(str)
end
function _G.errorf(msg, ...)
local str = string.format(msg, ...)
error(str)
end
function _G.croak(msg, ...)
local str = string.format(msg, ...)
io.stderr:write(str, "\n")
os.exit(1)
end
-- Expose benchmarking function for those times everything sucks
--
-- Wrap a function so that it prints execution times.
--
-- Usage:
-- foo = bench("foo", foo) -- benchmark function foo
function _G.bench(name, fn)
return function (...)
local t1 = native.get_timer()
local result = { fn(...) }
local t2 = native.get_timer()
printf("%s: %ss", name, native.timerdiff(t1, t2))
return unpack(result)
end
end
local environment = require "tundra.environment"
local nodegen = require "tundra.nodegen"
local decl = require "tundra.decl"
local path = require "tundra.path"
local depgraph = require "tundra.depgraph"
local dagsave = require "tundra.dagsave"
_G.SEP = platform.host_platform() == "windows" and "\\" or "/"
_G.Options = {
FullPaths = 1
}
local function make_default_env(build_data, add_unfiltered_vars)
local default_env = environment.create()
default_env:set_many {
["OBJECTROOT"] = "t2-output",
["SEP"] = SEP,
}
local host_platform = platform.host_platform()
do
local mod_name = "tundra.host." .. host_platform
local mod = require(mod_name)
mod.apply_host(default_env)
end
-- Add any unfiltered entries from the build data's Env and ReplaceEnv to the
-- default environment. For config environments, this will be false, because we
-- want to wait until the config's tools have run before adding any user
-- customizations.
if add_unfiltered_vars then
if build_data.Env then
nodegen.append_filtered_env_vars(default_env, build_data.Env, nil, true)
end
if build_data.ReplaceEnv then
nodegen.replace_filtered_env_vars(default_env, build_data.ReplaceEnv, nil, true)
end
end
return default_env
end
function generate_dag_data(build_script_fn)
local build_data = buildfile.run(build_script_fn)
local env = make_default_env(build_data.BuildData, false)
local raw_nodes, node_bindings = unitgen.generate_dag(
build_data.BuildTuples,
build_data.BuildData,
build_data.Passes,
build_data.Configs,
env)
dagsave.save_dag_data(
node_bindings,
build_data.DefaultVariant,
build_data.DefaultSubVariant,
build_data.ContentDigestExtensions,
build_data.Options)
end
function generate_ide_files(build_script_fn, ide_script)
-- We are generating IDE integration files. Load the specified
-- integration module rather than DAG builders.
--
-- Also, default to using full paths for all commands to aid with locating
-- sources better.
Options.FullPaths = 1
local build_data = buildfile.run(build_script_fn)
local build_tuples = assert(build_data.BuildTuples)
local raw_data = assert(build_data.BuildData)
local passes = assert(build_data.Passes)
local env = make_default_env(raw_data, true)
if not ide_script:find('.', 1, true) then
ide_script = 'tundra.ide.' .. ide_script
end
require(ide_script)
-- Generate dag
local raw_nodes, node_bindings = unitgen.generate_dag(
build_data.BuildTuples,
build_data.BuildData,
build_data.Passes,
build_data.Configs,
env)
-- Pass the build tuples directly to the generator and let it write
-- files.
nodegen.generate_ide_files(build_tuples, build_data.DefaultNodes, raw_nodes, env, raw_data.IdeGenerationHints, ide_script)
end
| mit |
DBReinitialized/PigBot | Source/deps/discordia/utils/OrderedCache.lua | 4 | 2513 | local Cache = require('./Cache')
local OrderedCache, property, method = class('OrderedCache', Cache)
OrderedCache.__description = "Extention of Cache that maintains object order using a linked list. If the ordered cache is full, adding a new object will discard the oldest object."
function OrderedCache:__init(array, constructor, key, limit, parent)
Cache.__init(self, array, constructor, key, parent)
self._limit = limit
self._next = {}
self._prev = {}
end
function OrderedCache:_add(obj)
local key = self._key
if self._count == 0 then
self._first = obj
self._last = obj
else
self._next[self._last[key]] = obj
self._prev[obj[key]] = self._last
self._last = obj
end
if self._count == self._limit then self:remove(self._first) end
self._objects[obj[key]] = obj
self._count = self._count + 1
end
function OrderedCache:_remove(obj)
local key = self._key
if self._count == 1 then
self._first = nil
self._last = nil
else
local prev = self._prev[obj[key]]
local next = self._next[obj[key]]
if obj == self._last then
self._last = prev
self._next[prev[key]] = nil
elseif obj == self._first then
self._first = next
self._prev[next[key]] = nil
else
self._next[prev[key]] = next
self._prev[next[key]] = prev
end
end
self._objects[obj[key]] = nil
self._count = self._count - 1
end
local function iterLastToFirst(self)
local obj = self._last
local key = self._key
return function()
local ret = obj
obj = obj and self._prev[obj[key]] or nil
return ret
end
end
local function iterFirstToLast(self)
local obj = self._first
local key = self._key
return function()
local ret = obj
obj = obj and self._next[obj[key]] or nil
return ret
end
end
local function iter(self, reverse)
return reverse and self:iterLastToFirst() or self:iterFirstToLast()
end
property('limit', '_limit', nil, 'number', "The maximum amount of objects that can be cached before the cache starts to empty")
property('first', '_first', nil, '*', "The first, or oldest, object in the cache")
property('last', '_last', nil, '*', "The last, or newest, object in the cache")
method('iterLastToFirst', iterLastToFirst, nil, "Returns an iterator for the objects in order of last (newest) to first (oldest).")
method('iterFirstToLast', iterFirstToLast, nil, "Returns an iterator for the objects in order of first (oldest) to last (newest).")
method('iter', iter, '[reverse]', "Equivalent to `iterFirstToLast` (or `iterLastToFirst` if reverse is `true`).")
return OrderedCache
| mit |
phi-psi/luci | modules/admin-full/luasrc/model/cbi/admin_network/vlan.lua | 55 | 8246 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network."))
local fs = require "nixio.fs"
local switches = { }
m.uci:foreach("network", "switch",
function(x)
local sid = x['.name']
local switch_name = x.name or sid
local has_vlan = nil
local has_learn = nil
local has_vlan4k = nil
local has_jumbo3 = nil
local min_vid = 0
local max_vid = 16
local num_vlans = 16
local cpu_port = tonumber(fs.readfile("/proc/switch/eth0/cpuport") or 5)
local num_ports = cpu_port + 1
local switch_title
local enable_vlan4k = false
-- Parse some common switch properties from swconfig help output.
local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name)
if swc then
local is_port_attr = false
local is_vlan_attr = false
while true do
local line = swc:read("*l")
if not line then break end
if line:match("^%s+%-%-vlan") then
is_vlan_attr = true
elseif line:match("^%s+%-%-port") then
is_vlan_attr = false
is_port_attr = true
elseif line:match("cpu @") then
switch_title = line:match("^switch%d: %w+%((.-)%)")
num_ports, cpu_port, num_vlans =
line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)")
num_ports = tonumber(num_ports) or 6
num_vlans = tonumber(num_vlans) or 16
cpu_port = tonumber(cpu_port) or 5
min_vid = 1
elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end
elseif line:match(": enable_vlan4k") then
enable_vlan4k = true
elseif line:match(": enable_vlan") then
has_vlan = "enable_vlan"
elseif line:match(": enable_learning") then
has_learn = "enable_learning"
elseif line:match(": max_length") then
has_jumbo3 = "max_length"
end
end
swc:close()
end
-- Switch properties
s = m:section(NamedSection, x['.name'], "switch",
switch_title and translatef("Switch %q (%s)", switch_name, switch_title)
or translatef("Switch %q", switch_name))
s.addremove = false
if has_vlan then
s:option(Flag, has_vlan, translate("Enable VLAN functionality"))
end
if has_learn then
x = s:option(Flag, has_learn, translate("Enable learning and aging"))
x.default = x.enabled
end
if has_jumbo3 then
x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough"))
x.enabled = "3"
x.rmempty = true
end
-- VLAN table
s = m:section(TypedSection, "switch_vlan",
switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title)
or translatef("VLANs on %q", switch_name))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
-- Filter by switch
s.filter = function(self, section)
local device = m:get(section, "device")
return (device and device == switch_name)
end
-- Override cfgsections callback to enforce row ordering by vlan id.
s.cfgsections = function(self)
local osections = TypedSection.cfgsections(self)
local sections = { }
local section
for _, section in luci.util.spairs(
osections,
function(a, b)
return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999)
< (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999)
end
) do
sections[#sections+1] = section
end
return sections
end
-- When creating a new vlan, preset it with the highest found vid + 1.
s.create = function(self, section, origin)
-- Filter by switch
if m:get(origin, "device") ~= switch_name then
return
end
local sid = TypedSection.create(self, section)
local max_nr = 0
local max_id = 0
m.uci:foreach("network", "switch_vlan",
function(s)
if s.device == switch_name then
local nr = tonumber(s.vlan)
local id = has_vlan4k and tonumber(s[has_vlan4k])
if nr ~= nil and nr > max_nr then max_nr = nr end
if id ~= nil and id > max_id then max_id = id end
end
end)
m:set(sid, "device", switch_name)
m:set(sid, "vlan", max_nr + 1)
if has_vlan4k then
m:set(sid, has_vlan4k, max_id + 1)
end
return sid
end
local port_opts = { }
local untagged = { }
-- Parse current tagging state from the "ports" option.
local portvalue = function(self, section)
local pt
for pt in (m:get(section, "ports") or ""):gmatch("%w+") do
local pc, tu = pt:match("^(%d+)([tu]*)")
if pc == self.option then return (#tu > 0) and tu or "u" end
end
return ""
end
-- Validate port tagging. Ensure that a port is only untagged once,
-- bail out if not.
local portvalidate = function(self, value, section)
-- ensure that the ports appears untagged only once
if value == "u" then
if not untagged[self.option] then
untagged[self.option] = true
elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup
return nil,
translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1)
end
end
return value
end
local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name)
local mx_vid = has_vlan4k and 4094 or (num_vlans - 1)
vid.rmempty = false
vid.forcewrite = true
vid.vlan_used = { }
vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))"
-- Validate user provided VLAN ID, make sure its within the bounds
-- allowed by the switch.
vid.validate = function(self, value, section)
local v = tonumber(value)
local m = has_vlan4k and 4094 or (num_vlans - 1)
if v ~= nil and v >= min_vid and v <= m then
if not self.vlan_used[v] then
self.vlan_used[v] = true
return value
else
return nil,
translatef("Invalid VLAN ID given! Only unique IDs are allowed")
end
else
return nil,
translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m)
end
end
-- When writing the "vid" or "vlan" option, serialize the port states
-- as well and write them as "ports" option to uci.
vid.write = function(self, section, value)
local o
local p = { }
for _, o in ipairs(port_opts) do
local v = o:formvalue(section)
if v == "t" then
p[#p+1] = o.option .. v
elseif v == "u" then
p[#p+1] = o.option
end
end
if enable_vlan4k then
m:set(sid, "enable_vlan4k", "1")
end
m:set(section, "ports", table.concat(p, " "))
return Value.write(self, section, value)
end
-- Fallback to "vlan" option if "vid" option is supported but unset.
vid.cfgvalue = function(self, section)
return m:get(section, has_vlan4k or "vlan")
or m:get(section, "vlan")
end
-- Build per-port off/untagged/tagged choice lists.
local pt
for pt = 0, num_ports - 1 do
local title
if pt == cpu_port then
title = translate("CPU")
else
title = translatef("Port %d", pt)
end
local po = s:option(ListValue, tostring(pt), title)
po:value("", translate("off"))
po:value("u", translate("untagged"))
po:value("t", translate("tagged"))
po.cfgvalue = portvalue
po.validate = portvalidate
po.write = function() end
port_opts[#port_opts+1] = po
end
switches[#switches+1] = switch_name
end
)
-- Switch status template
s = m:section(SimpleSection)
s.template = "admin_network/switch_status"
s.switches = switches
return m
| apache-2.0 |
ryanplusplus/xlua | exercises/food-chain/food-chain_spec.lua | 2 | 4089 | local song = require('food-chain')
describe('food-hain', function ()
it('fly', function ()
local expected = "I know an old lady who swallowed a fly.\nI don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(1))
end)
it('spider', function ()
local expected = "I know an old lady who swallowed a spider.\nIt wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(2))
end)
it('bird', function ()
local expected = "I know an old lady who swallowed a bird.\n" ..
"How absurd to swallow a bird!\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(3))
end)
it('cat', function ()
local expected = "I know an old lady who swallowed a cat.\n" ..
"Imagine that, to swallow a cat!\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(4))
end)
it('dog', function ()
local expected = "I know an old lady who swallowed a dog.\n" ..
"What a hog, to swallow a dog!\n" ..
"She swallowed the dog to catch the cat.\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(5))
end)
it('goat', function ()
local expected = "I know an old lady who swallowed a goat.\n" ..
"Just opened her throat and swallowed a goat!\n" ..
"She swallowed the goat to catch the dog.\n" ..
"She swallowed the dog to catch the cat.\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(6))
end)
it('cow', function ()
local expected = "I know an old lady who swallowed a cow.\n" ..
"I don't know how she swallowed a cow!\n" ..
"She swallowed the cow to catch the goat.\n" ..
"She swallowed the goat to catch the dog.\n" ..
"She swallowed the dog to catch the cat.\n" ..
"She swallowed the cat to catch the bird.\n" ..
"She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. " ..
"Perhaps she'll die.\n"
assert.are.equal(expected, song.verse(7))
end)
it('horse', function ()
local expected = "I know an old lady who swallowed a horse.\n" ..
"She's dead, of course!\n"
assert.are.equal(expected, song.verse(8))
end)
it('multiple verses', function ()
local expected = ""
expected = "I know an old lady who swallowed a fly.\nI don't know why she swallowed the fly. Perhaps she'll die.\n\n" ..
"I know an old lady who swallowed a spider.\nIt wriggled and jiggled and tickled inside her.\n" ..
"She swallowed the spider to catch the fly.\n" ..
"I don't know why she swallowed the fly. Perhaps she'll die.\n\n"
assert.are.equal(expected, song.verses(1, 2))
end)
it('the whole song', function ()
assert.are.equal(song.verses(1, 8), song.sing())
end)
end)
| mit |
gevero/S4 | examples/Liu_OE_17_21897_2009/fig3f.lua | 7 | 1392 | -- Fig. 3f of
-- Victor Liu, Michelle Povinelli, and Shanhui Fan,
-- "Resonance-enhanced optical forces between coupled photonic crystal slabs",
-- Optics Express, Vol. 17, No. 24, 2009
S = S4.NewSimulation()
S:SetLattice({1,0}, {0,0}) -- 1D lattice
S:SetNumG(27)
-- Material definition
S:AddMaterial("Silicon", {12,0}) -- real and imag parts
S:AddMaterial("Vacuum", {1,0})
S:AddLayer(
'AirAbove', --name
0, --thickness
'Vacuum') --background material
S:AddLayer('Slab', 0.5, 'Vacuum')
S:SetLayerPatternRectangle('Slab', -- which layer to alter
'Silicon', -- material in rectangle
{0,0}, -- center
0, -- tilt angle (degrees)
{0.25, 0.5}) -- half-widths
S:AddLayerCopy('Spacer', 0.65, 'AirAbove')
S:AddLayerCopy('Slab2', 0.5, 'Slab')
S:AddLayerCopy('AirBelow', 0, 'AirAbove')
-- E polarized along the grating "rods"
S:SetExcitationPlanewave(
{0,0}, -- incidence angles (spherical coordinates: phi in [0,180], theta in [0,360])
{0,0}, -- s-polarization amplitude and phase (in degrees)
{1,0}) -- p-polarization amplitude and phase
S:SetFrequency(0.6306178089044143)
for x=-0.5,3.5,0.02 do
for z=-1,2.65,0.02 do
Ex,Ey,Ez = S:GetEField({x,0,z})
print(x..'\t'..z..'\t'..Ey)
end
print('')
end
| gpl-2.0 |
erwincoumans/premake-dev-iphone-xcode4 | src/actions/xcode/xcode_common.lua | 1 | 29158 | --
-- xcode_common.lua
-- Functions to generate the different sections of an Xcode project.
-- Copyright (c) 2009-2011 Jason Perkins and the Premake project
--
local xcode = premake.xcode
local tree = premake.tree
--
-- Return the Xcode build category for a given file, based on the file extension.
--
-- @param node
-- The node to identify.
-- @returns
-- An Xcode build category, one of "Sources", "Resources", "Frameworks", or nil.
--
function xcode.getbuildcategory(node)
local categories = {
[".a"] = "Frameworks",
[".c"] = "Sources",
[".cc"] = "Sources",
[".cpp"] = "Sources",
[".cxx"] = "Sources",
[".dylib"] = "Frameworks",
[".framework"] = "Frameworks",
[".m"] = "Sources",
[".mm"] = "Sources",
[".strings"] = "Resources",
[".nib"] = "Resources",
[".xib"] = "Resources",
[".icns"] = "Resources",
[".png"] = "Resources",
}
return categories[path.getextension(node.name)]
end
--
-- Return the displayed name for a build configuration, taking into account the
-- configuration and platform, i.e. "Debug 32-bit Universal".
--
-- @param cfg
-- The configuration being identified.
-- @returns
-- A build configuration name.
--
function xcode.getconfigname(cfg)
local name = cfg.name
if #cfg.project.solution.xcode.platforms > 1 then
name = name .. " " .. premake.action.current().valid_platforms[cfg.platform]
end
return name
end
--
-- Return the Xcode type for a given file, based on the file extension.
--
-- @param fname
-- The file name to identify.
-- @returns
-- An Xcode file type, string.
--
function xcode.getfiletype(node)
local types = {
[".c"] = "sourcecode.c.c",
[".cc"] = "sourcecode.cpp.cpp",
[".cpp"] = "sourcecode.cpp.cpp",
[".css"] = "text.css",
[".cxx"] = "sourcecode.cpp.cpp",
[".framework"] = "wrapper.framework",
[".gif"] = "image.gif",
[".h"] = "sourcecode.c.h",
[".html"] = "text.html",
[".lua"] = "sourcecode.lua",
[".m"] = "sourcecode.c.objc",
[".mm"] = "sourcecode.cpp.objc",
[".nib"] = "wrapper.nib",
[".pch"] = "sourcecode.c.h",
[".plist"] = "text.plist.xml",
[".strings"] = "text.plist.strings",
[".xib"] = "file.xib",
[".icns"] = "image.icns",
}
return types[path.getextension(node.path)] or "text"
end
--
-- Return the Xcode product type, based target kind.
--
-- @param node
-- The product node to identify.
-- @returns
-- An Xcode product type, string.
--
function xcode.getproducttype(node)
local types = {
ConsoleApp = "com.apple.product-type.tool",
WindowedApp = "com.apple.product-type.application",
StaticLib = "com.apple.product-type.library.static",
SharedLib = "com.apple.product-type.library.dynamic",
}
return types[node.cfg.kind]
end
--
-- Return the Xcode target type, based on the target file extension.
--
-- @param node
-- The product node to identify.
-- @returns
-- An Xcode target type, string.
--
function xcode.gettargettype(node)
local types = {
ConsoleApp = "\"compiled.mach-o.executable\"",
WindowedApp = "wrapper.application",
StaticLib = "archive.ar",
SharedLib = "\"compiled.mach-o.dylib\"",
}
return types[node.cfg.kind]
end
--
-- Return a unique file name for a project. Since Xcode uses .xcodeproj's to
-- represent both solutions and projects there is a likely change of a name
-- collision. Tack on a number to differentiate them.
--
-- @param prj
-- The project being queried.
-- @returns
-- A uniqued file name
--
function xcode.getxcodeprojname(prj)
-- if there is a solution with matching name, then use "projectname1.xcodeproj"
-- just get something working for now
local fname = premake.project.getfilename(prj, "%%.xcodeproj")
return fname
end
--
-- Returns true if the file name represents a framework.
--
-- @param fname
-- The name of the file to test.
--
function xcode.isframework(fname)
return (path.getextension(fname) == ".framework")
end
--
-- Retrieves a unique 12 byte ID for an object. This function accepts and ignores two
-- parameters 'node' and 'usage', which are used by an alternative implementation of
-- this function for testing.
--
-- @returns
-- A 24-character string representing the 12 byte ID.
--
function xcode.newid()
return string.format("%04X%04X%04X%04X%04X%04X",
math.random(0, 32767),
math.random(0, 32767),
math.random(0, 32767),
math.random(0, 32767),
math.random(0, 32767),
math.random(0, 32767))
end
--
-- Create a product tree node and all projects in a solution; assigning IDs
-- that are needed for inter-project dependencies.
--
-- @param sln
-- The solution to prepare.
--
function xcode.preparesolution(sln)
-- create and cache a list of supported platforms
sln.xcode = { }
sln.xcode.platforms = premake.filterplatforms(sln, premake.action.current().valid_platforms, "Universal")
for prj in premake.solution.eachproject(sln) do
-- need a configuration to get the target information
local cfg = premake.getconfig(prj, prj.configurations[1], sln.xcode.platforms[1])
-- build the product tree node
local node = premake.tree.new(path.getname(cfg.buildtarget.bundlepath))
node.cfg = cfg
node.id = premake.xcode.newid(node, "product")
node.targetid = premake.xcode.newid(node, "target")
-- attach it to the project
prj.xcode = {}
prj.xcode.projectnode = node
end
end
--
-- Print out a list value in the Xcode format.
--
-- @param list
-- The list of values to be printed.
-- @param tag
-- The Xcode specific list tag.
--
function xcode.printlist(list, tag, cfg)
if xcode.BuildSettingsExists(tag, cfg) then
return -- Don't write settings
end
if #list > 0 then
_p(4,'%s = (', tag)
for _, item in ipairs(list) do
_p(5, '"%s",', item)
end
_p(4,');')
end
end
--
-- Check if build settings is overrided by user with xcodebuildsettings {}
-- @param buildsettingName
-- The list of values to be printed.
-- @param cfg
-- configuration
--
function xcode.BuildSettingsExists(buildsettingName, cfg)
if #cfg.xcodebuildsettings > 0 then
for _, item in ipairs(cfg.xcodebuildsettings) do
local _, k = string.find(item, "=")
local itemName = string.sub(item, 1, k - 1)
itemName = string.gsub(itemName, "%s", "")
end
end
return false
end
--
-- Print user build settings contained in xcodebuildsettings
-- @param offset
-- offset used by function _p
-- @param cfg
-- configuration
--
function xcodePrintUserSettings(offset, cfg)
for _, item in ipairs(cfg.xcodebuildsettings) do
_p(offset, item .. ';')
end
end
--
-- Print xcode build setting if not overrided by user
-- @param offset
-- offset used by function _p
-- @param cfg
-- configuration
--
function xcode.PrintBuildSetting(offset, buildsetting, cfg)
-- Check that the settings was not overriden by xcode buildsettings
if #cfg.xcodebuildsettings > 0 then
local _, j = string.find(buildsetting, "=")
local buildsettingName = string.sub(buildsetting, 1, j - 1)
buildsettingName = string.gsub(buildsettingName, "%s", "")
if xcode.BuildSettingsExists(buildsettingName, cfg) then
return
end
end
_p(offset, buildsetting)
end
---------------------------------------------------------------------------
-- Section generator functions, in the same order in which they appear
-- in the .pbxproj file
---------------------------------------------------------------------------
function xcode.Header()
_p('// !$*UTF8*$!')
_p('{')
_p(1,'archiveVersion = 1;')
_p(1,'classes = {')
_p(1,'};')
_p(1,'objectVersion = 45;')
_p(1,'objects = {')
_p('')
end
function xcode.PBXBuildFile(tr)
_p('/* Begin PBXBuildFile section */')
tree.traverse(tr, {
onnode = function(node)
if node.buildid then
_p(2,'%s /* %s in %s */ = {isa = PBXBuildFile; fileRef = %s /* %s */; };',
node.buildid, node.name, xcode.getbuildcategory(node), node.id, node.name)
end
end
})
_p('/* End PBXBuildFile section */')
_p('')
end
function xcode.PBXContainerItemProxy(tr)
if #tr.projects.children > 0 then
_p('/* Begin PBXContainerItemProxy section */')
for _, node in ipairs(tr.projects.children) do
_p(2,'%s /* PBXContainerItemProxy */ = {', node.productproxyid)
_p(3,'isa = PBXContainerItemProxy;')
_p(3,'containerPortal = %s /* %s */;', node.id, path.getname(node.path))
_p(3,'proxyType = 2;')
_p(3,'remoteGlobalIDString = %s;', node.project.xcode.projectnode.id)
_p(3,'remoteInfo = "%s";', node.project.xcode.projectnode.name)
_p(2,'};')
_p(2,'%s /* PBXContainerItemProxy */ = {', node.targetproxyid)
_p(3,'isa = PBXContainerItemProxy;')
_p(3,'containerPortal = %s /* %s */;', node.id, path.getname(node.path))
_p(3,'proxyType = 1;')
_p(3,'remoteGlobalIDString = %s;', node.project.xcode.projectnode.targetid)
_p(3,'remoteInfo = "%s";', node.project.xcode.projectnode.name)
_p(2,'};')
end
_p('/* End PBXContainerItemProxy section */')
_p('')
end
end
function xcode.PBXFileReference(tr)
_p('/* Begin PBXFileReference section */')
tree.traverse(tr, {
onleaf = function(node)
-- I'm only listing files here, so ignore anything without a path
if not node.path then
return
end
-- is this the product node, describing the output target?
if node.kind == "product" then
_p(2,'%s /* %s */ = {isa = PBXFileReference; explicitFileType = %s; includeInIndex = 0; name = "%s"; path = "%s"; sourceTree = BUILT_PRODUCTS_DIR; };',
node.id, node.name, xcode.gettargettype(node), node.name, path.getname(node.cfg.buildtarget.bundlepath))
-- is this a project dependency?
elseif node.parent.parent == tr.projects then
local relpath = path.getrelative(tr.project.location, node.parent.project.location)
_p(2,'%s /* %s */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = "%s"; path = "%s"; sourceTree = SOURCE_ROOT; };',
node.parent.id, node.parent.name, node.parent.name, path.join(relpath, node.parent.name))
-- something else
else
local pth, src
if xcode.isframework(node.path) then
--respect user supplied paths
if string.find(node.path,'/') then
if string.find(node.path,'^%.')then
error('relative paths are not currently supported for frameworks')
end
pth = node.path
else
pth = "/System/Library/Frameworks/" .. node.path
end
src = "absolute"
else
-- something else; probably a source code file
src = "group"
-- if the parent node is virtual, it won't have a local path
-- of its own; need to use full relative path from project
if node.parent.isvpath then
pth = node.cfg.name
else
pth = tree.getlocalpath(node)
end
end
_p(2,'%s /* %s */ = {isa = PBXFileReference; lastKnownFileType = %s; name = "%s"; path = "%s"; sourceTree = "<%s>"; };',
node.id, node.name, xcode.getfiletype(node), node.name, pth, src)
end
end
})
_p('/* End PBXFileReference section */')
_p('')
end
function xcode.PBXFrameworksBuildPhase(tr)
_p('/* Begin PBXFrameworksBuildPhase section */')
_p(2,'%s /* Frameworks */ = {', tr.products.children[1].fxstageid)
_p(3,'isa = PBXFrameworksBuildPhase;')
_p(3,'buildActionMask = 2147483647;')
_p(3,'files = (')
-- write out library dependencies
tree.traverse(tr.frameworks, {
onleaf = function(node)
_p(4,'%s /* %s in Frameworks */,', node.buildid, node.name)
end
})
-- write out project dependencies
tree.traverse(tr.projects, {
onleaf = function(node)
_p(4,'%s /* %s in Frameworks */,', node.buildid, node.name)
end
})
_p(3,');')
_p(3,'runOnlyForDeploymentPostprocessing = 0;')
_p(2,'};')
_p('/* End PBXFrameworksBuildPhase section */')
_p('')
end
function xcode.PBXGroup(tr)
_p('/* Begin PBXGroup section */')
tree.traverse(tr, {
onnode = function(node)
-- Skip over anything that isn't a proper group
if (node.path and #node.children == 0) or node.kind == "vgroup" then
return
end
-- project references get special treatment
if node.parent == tr.projects then
_p(2,'%s /* Products */ = {', node.productgroupid)
else
_p(2,'%s /* %s */ = {', node.id, node.name)
end
_p(3,'isa = PBXGroup;')
_p(3,'children = (')
for _, childnode in ipairs(node.children) do
_p(4,'%s /* %s */,', childnode.id, childnode.name)
end
_p(3,');')
if node.parent == tr.projects then
_p(3,'name = Products;')
else
_p(3,'name = "%s";', node.name)
if node.path and not node.isvpath then
local p = node.path
if node.parent.path then
p = path.getrelative(node.parent.path, node.path)
end
_p(3,'path = "%s";', p)
end
end
_p(3,'sourceTree = "<group>";')
_p(2,'};')
end
}, true)
_p('/* End PBXGroup section */')
_p('')
end
function xcode.PBXNativeTarget(tr)
_p('/* Begin PBXNativeTarget section */')
for _, node in ipairs(tr.products.children) do
local name = tr.project.name
_p(2,'%s /* %s */ = {', node.targetid, name)
_p(3,'isa = PBXNativeTarget;')
_p(3,'buildConfigurationList = %s /* Build configuration list for PBXNativeTarget "%s" */;', node.cfgsection, name)
_p(3,'buildPhases = (')
if #tr.project.prebuildcommands > 0 then
_p(4,'9607AE1010C857E500CD1376 /* Prebuild */,')
end
_p(4,'%s /* Resources */,', node.resstageid)
_p(4,'%s /* Sources */,', node.sourcesid)
if #tr.project.prelinkcommands > 0 then
_p(4,'9607AE3510C85E7E00CD1376 /* Prelink */,')
end
_p(4,'%s /* Frameworks */,', node.fxstageid)
if #tr.project.postbuildcommands > 0 then
_p(4,'9607AE3710C85E8F00CD1376 /* Postbuild */,')
end
_p(3,');')
_p(3,'buildRules = (')
_p(3,');')
_p(3,'dependencies = (')
for _, node in ipairs(tr.projects.children) do
_p(4,'%s /* PBXTargetDependency */,', node.targetdependid)
end
_p(3,');')
_p(3,'name = "%s";', name)
local p
if node.cfg.kind == "ConsoleApp" then
p = "$(HOME)/bin"
elseif node.cfg.kind == "WindowedApp" then
p = "$(HOME)/Applications"
end
if p then
_p(3,'productInstallPath = "%s";', p)
end
_p(3,'productName = "%s";', name)
_p(3,'productReference = %s /* %s */;', node.id, node.name)
_p(3,'productType = "%s";', xcode.getproducttype(node))
_p(2,'};')
end
_p('/* End PBXNativeTarget section */')
_p('')
end
function xcode.PBXProject(tr)
_p('/* Begin PBXProject section */')
_p(2,'08FB7793FE84155DC02AAC07 /* Project object */ = {')
_p(3,'isa = PBXProject;')
_p(3,'buildConfigurationList = 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "%s" */;', tr.name)
_p(3,'compatibilityVersion = "Xcode 3.2";')
_p(3,'hasScannedForEncodings = 1;')
_p(3,'mainGroup = %s /* %s */;', tr.id, tr.name)
_p(3,'projectDirPath = "";')
if #tr.projects.children > 0 then
_p(3,'projectReferences = (')
for _, node in ipairs(tr.projects.children) do
_p(4,'{')
_p(5,'ProductGroup = %s /* Products */;', node.productgroupid)
_p(5,'ProjectRef = %s /* %s */;', node.id, path.getname(node.path))
_p(4,'},')
end
_p(3,');')
end
_p(3,'projectRoot = "";')
_p(3,'targets = (')
for _, node in ipairs(tr.products.children) do
_p(4,'%s /* %s */,', node.targetid, node.name)
end
_p(3,');')
_p(2,'};')
_p('/* End PBXProject section */')
_p('')
end
function xcode.PBXReferenceProxy(tr)
if #tr.projects.children > 0 then
_p('/* Begin PBXReferenceProxy section */')
tree.traverse(tr.projects, {
onleaf = function(node)
_p(2,'%s /* %s */ = {', node.id, node.name)
_p(3,'isa = PBXReferenceProxy;')
_p(3,'fileType = %s;', xcode.gettargettype(node))
_p(3,'path = "%s";', node.path)
_p(3,'remoteRef = %s /* PBXContainerItemProxy */;', node.parent.productproxyid)
_p(3,'sourceTree = BUILT_PRODUCTS_DIR;')
_p(2,'};')
end
})
_p('/* End PBXReferenceProxy section */')
_p('')
end
end
function xcode.PBXResourcesBuildPhase(tr)
_p('/* Begin PBXResourcesBuildPhase section */')
for _, target in ipairs(tr.products.children) do
_p(2,'%s /* Resources */ = {', target.resstageid)
_p(3,'isa = PBXResourcesBuildPhase;')
_p(3,'buildActionMask = 2147483647;')
_p(3,'files = (')
tree.traverse(tr, {
onnode = function(node)
if xcode.getbuildcategory(node) == "Resources" then
_p(4,'%s /* %s in Resources */,', node.buildid, node.name)
end
end
})
_p(3,');')
_p(3,'runOnlyForDeploymentPostprocessing = 0;')
_p(2,'};')
end
_p('/* End PBXResourcesBuildPhase section */')
_p('')
end
function xcode.PBXShellScriptBuildPhase(tr)
local wrapperWritten = false
local function doblock(id, name, which)
-- start with the project-level commands (most common)
local prjcmds = tr.project[which]
local commands = table.join(prjcmds, {})
-- see if there are any config-specific commands to add
for _, cfg in ipairs(tr.configs) do
local cfgcmds = cfg[which]
if #cfgcmds > #prjcmds then
table.insert(commands, 'if [ "${CONFIGURATION}" = "' .. xcode.getconfigname(cfg) .. '" ]; then')
for i = #prjcmds + 1, #cfgcmds do
table.insert(commands, cfgcmds[i])
end
table.insert(commands, 'fi')
end
end
if #commands > 0 then
if not wrapperWritten then
_p('/* Begin PBXShellScriptBuildPhase section */')
wrapperWritten = true
end
_p(2,'%s /* %s */ = {', id, name)
_p(3,'isa = PBXShellScriptBuildPhase;')
_p(3,'buildActionMask = 2147483647;')
_p(3,'files = (')
_p(3,');')
_p(3,'inputPaths = (');
_p(3,');');
_p(3,'name = %s;', name);
_p(3,'outputPaths = (');
_p(3,');');
_p(3,'runOnlyForDeploymentPostprocessing = 0;');
_p(3,'shellPath = /bin/sh;');
_p(3,'shellScript = "%s";', table.concat(commands, "\\n"):gsub('"', '\\"'))
_p(2,'};')
end
end
doblock("9607AE1010C857E500CD1376", "Prebuild", "prebuildcommands")
doblock("9607AE3510C85E7E00CD1376", "Prelink", "prelinkcommands")
doblock("9607AE3710C85E8F00CD1376", "Postbuild", "postbuildcommands")
if wrapperWritten then
_p('/* End PBXShellScriptBuildPhase section */')
end
end
function xcode.PBXSourcesBuildPhase(tr)
_p('/* Begin PBXSourcesBuildPhase section */')
for _, target in ipairs(tr.products.children) do
_p(2,'%s /* Sources */ = {', target.sourcesid)
_p(3,'isa = PBXSourcesBuildPhase;')
_p(3,'buildActionMask = 2147483647;')
_p(3,'files = (')
tree.traverse(tr, {
onleaf = function(node)
if xcode.getbuildcategory(node) == "Sources" then
_p(4,'%s /* %s in Sources */,', node.buildid, node.name)
end
end
})
_p(3,');')
_p(3,'runOnlyForDeploymentPostprocessing = 0;')
_p(2,'};')
end
_p('/* End PBXSourcesBuildPhase section */')
_p('')
end
function xcode.PBXVariantGroup(tr)
_p('/* Begin PBXVariantGroup section */')
tree.traverse(tr, {
onbranch = function(node)
if node.kind == "vgroup" then
_p(2,'%s /* %s */ = {', node.id, node.name)
_p(3,'isa = PBXVariantGroup;')
_p(3,'children = (')
for _, lang in ipairs(node.children) do
_p(4,'%s /* %s */,', lang.id, lang.name)
end
_p(3,');')
_p(3,'name = %s;', node.name)
_p(3,'sourceTree = "<group>";')
_p(2,'};')
end
end
})
_p('/* End PBXVariantGroup section */')
_p('')
end
function xcode.PBXTargetDependency(tr)
if #tr.projects.children > 0 then
_p('/* Begin PBXTargetDependency section */')
tree.traverse(tr.projects, {
onleaf = function(node)
_p(2,'%s /* PBXTargetDependency */ = {', node.parent.targetdependid)
_p(3,'isa = PBXTargetDependency;')
_p(3,'name = "%s";', node.name)
_p(3,'targetProxy = %s /* PBXContainerItemProxy */;', node.parent.targetproxyid)
_p(2,'};')
end
})
_p('/* End PBXTargetDependency section */')
_p('')
end
end
function xcode.XCBuildConfiguration_Target(tr, target, cfg)
local cfgname = xcode.getconfigname(cfg)
_p(2,'%s /* %s */ = {', cfg.xcode.targetid, cfgname)
_p(3,'isa = XCBuildConfiguration;')
_p(3,'buildSettings = {')
--_p(4,'ALWAYS_SEARCH_USER_PATHS = NO;')
xcodePrintUserSettings(4, cfg)
xcode.PrintBuildSetting(4,'ALWAYS_SEARCH_USER_PATHS = NO;', cfg)
if not cfg.flags.Symbols then
--_p(4,'DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";')
xcode.PrintBuildSetting(4,'DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";', cfg)
end
if cfg.kind ~= "StaticLib" and cfg.buildtarget.prefix ~= "" then
--_p(4,'EXECUTABLE_PREFIX = %s;', cfg.buildtarget.prefix)
xcode.PrintBuildSetting(4,'EXECUTABLE_PREFIX = '.. cfg.buildtarget.prefix .. ';', cfg)
end
local outdir = path.getdirectory(cfg.buildtarget.bundlepath)
if outdir ~= "." then
--_p(4,'CONFIGURATION_BUILD_DIR = %s;', outdir)
xcode.PrintBuildSetting(4,'CONFIGURATION_BUILD_DIR = "' .. outdir .. '";', cfg)
end
--_p(4,'GCC_DYNAMIC_NO_PIC = NO;')
--_p(4,'GCC_MODEL_TUNING = G5;')
xcode.PrintBuildSetting(4,'GCC_DYNAMIC_NO_PIC = NO;',cfg)
xcode.PrintBuildSetting(4,'GCC_MODEL_TUNING = G5;', cfg)
if tr.infoplist then
-- _p(4,'INFOPLIST_FILE = "%s";', tr.infoplist.path)
xcode.PrintBuildSetting( 4,'INFOPLIST_FILE = "' .. tr.infoplist.path .. '";', cfg)
end
installpaths = {
ConsoleApp = '/usr/local/bin',
WindowedApp = '"$(HOME)/Applications"',
SharedLib = '/usr/local/lib',
StaticLib = '/usr/local/lib',
}
--_p(4,'INSTALL_PATH = %s;', installpaths[cfg.kind])
xcode.PrintBuildSetting(4,'INSTALL_PATH = ' .. installpaths[cfg.kind] .. ';', cfg)
--_p(4,'PRODUCT_NAME = "%s";', cfg.buildtarget.basename)
xcode.PrintBuildSetting(4,'PRODUCT_NAME = "' .. cfg.buildtarget.basename .. '";', cfg)
_p(3,'};')
_p(3,'name = "%s";', cfgname)
_p(2,'};')
end
function xcode.XCBuildConfiguration_Project(tr, cfg)
local cfgname = xcode.getconfigname(cfg)
_p(2,'%s /* %s */ = {', cfg.xcode.projectid, cfgname)
_p(3,'isa = XCBuildConfiguration;')
_p(3,'buildSettings = {')
xcodePrintUserSettings(4, cfg)
local archs = {
Native = "$(NATIVE_ARCH_ACTUAL)",
x32 = "i386",
x64 = "x86_64",
Universal32 = "$(ARCHS_STANDARD_32_BIT)",
Universal64 = "$(ARCHS_STANDARD_64_BIT)",
Universal = "$(ARCHS_STANDARD_32_64_BIT)",
iPhone = '(armv6, armv7)',
}
--_p(4,'ARCHS = "%s";', archs[cfg.platform])
if cfg.platform:lower() == "iphone" then
xcode.PrintBuildSetting(4,'SDKROOT = iphoneos;', cfg)
else
xcode.PrintBuildSetting(4,'SDKROOT = macosx;', cfg)
end
xcode.PrintBuildSetting(4,'ARCHS = "'.. archs[cfg.platform] ..'";', cfg)
local targetdir = path.getdirectory(cfg.buildtarget.bundlepath)
if targetdir ~= "." then
--_p(4,'CONFIGURATION_BUILD_DIR = "$(SYMROOT)";');
xcode.PrintBuildSetting(4,'CONFIGURATION_BUILD_DIR = "$(SYMROOT)";', cfg);
end
--_p(4,'CONFIGURATION_TEMP_DIR = "$(OBJROOT)";')
xcode.PrintBuildSetting(4, 'CONFIGURATION_TEMP_DIR = "$(OBJROOT)";', cfg)
if cfg.flags.Symbols then
-- _p(4,'COPY_PHASE_STRIP = NO;')
xcode.PrintBuildSetting(4,'COPY_PHASE_STRIP = NO;', cfg)
end
--_p(4,'GCC_C_LANGUAGE_STANDARD = gnu99;')
xcode.PrintBuildSetting(4,'GCC_C_LANGUAGE_STANDARD = gnu99;', cfg)
if cfg.flags.NoExceptions then
--_p(4,'GCC_ENABLE_CPP_EXCEPTIONS = NO;')
xcode.PrintBuildSetting(4,'GCC_ENABLE_CPP_EXCEPTIONS = NO;', cfg)
end
if cfg.flags.NoRTTI then
--_p(4,'GCC_ENABLE_CPP_RTTI = NO;')
xcode.PrintBuildSetting( 4,'GCC_ENABLE_CPP_RTTI = NO;', cfg)
end
if _ACTION ~= "xcode4" and cfg.flags.Symbols and not cfg.flags.NoEditAndContinue then
--_p(4,'GCC_ENABLE_FIX_AND_CONTINUE = YES;')
xcode.PrintBuildSetting(4,'GCC_ENABLE_FIX_AND_CONTINUE = YES;', cfg)
end
if cfg.flags.NoExceptions then
--_p(4,'GCC_ENABLE_OBJC_EXCEPTIONS = NO;')
xcode.PrintBuildSetting(4,'GCC_ENABLE_OBJC_EXCEPTIONS = NO;', cfg)
end
if cfg.flags.Optimize or cfg.flags.OptimizeSize then
--_p(4,'GCC_OPTIMIZATION_LEVEL = s;')
xcode.PrintBuildSetting(4,'GCC_OPTIMIZATION_LEVEL = s;', cfg)
elseif cfg.flags.OptimizeSpeed then
--_p(4,'GCC_OPTIMIZATION_LEVEL = 3;')
xcode.PrintBuildSetting(4,'GCC_OPTIMIZATION_LEVEL = 3;', cfg)
else
--_p(4,'GCC_OPTIMIZATION_LEVEL = 0;')
xcode.PrintBuildSetting(4,'GCC_OPTIMIZATION_LEVEL = 0;', cfg)
end
if cfg.pchheader and not cfg.flags.NoPCH then
--_p(4,'GCC_PRECOMPILE_PREFIX_HEADER = YES;')
--_p(4,'GCC_PREFIX_HEADER = "%s";', cfg.pchheader)
xcode.PrintBuildSetting(4,'GCC_PRECOMPILE_PREFIX_HEADER = YES;', cfg)
xcode.PrintBuildSetting(4,'GCC_PREFIX_HEADER = "' .. cfg.pchheader .. '";', cfg)
end
xcode.printlist(cfg.defines, 'GCC_PREPROCESSOR_DEFINITIONS',cfg)
--_p(4,'GCC_SYMBOLS_PRIVATE_EXTERN = NO;')
xcode.PrintBuildSetting(4,'GCC_SYMBOLS_PRIVATE_EXTERN = NO;', cfg)
if cfg.flags.FatalWarnings then
--_p(4,'GCC_TREAT_WARNINGS_AS_ERRORS = YES;')
xcode.PrintBuildSetting(4,'GCC_TREAT_WARNINGS_AS_ERRORS = YES;', cfg)
end
--_p(4,'GCC_WARN_ABOUT_RETURN_TYPE = YES;')
--_p(4,'GCC_WARN_UNUSED_VARIABLE = YES;')
xcode.PrintBuildSetting(4,'GCC_WARN_ABOUT_RETURN_TYPE = YES;', cfg)
xcode.PrintBuildSetting(4,'GCC_WARN_UNUSED_VARIABLE = YES;', cfg)
xcode.printlist(cfg.includedirs, 'HEADER_SEARCH_PATHS',cfg)
xcode.printlist(cfg.libdirs, 'LIBRARY_SEARCH_PATHS',cfg)
--_p(4,'OBJROOT = "%s";', cfg.objectsdir)
--_p(4,'ONLY_ACTIVE_ARCH = %s;',iif(premake.config.isdebugbuild(cfg),'YES','NO'))
xcode.PrintBuildSetting(4,'OBJROOT = "' .. cfg.objectsdir .. '";', cfg)
xcode.PrintBuildSetting(4,'ONLY_ACTIVE_ARCH = '.. iif(premake.config.isdebugbuild(cfg),'YES','NO') ..';', cfg)
-- build list of "other" C/C++ flags
local checks = {
["-ffast-math"] = cfg.flags.FloatFast,
["-ffloat-store"] = cfg.flags.FloatStrict,
["-fomit-frame-pointer"] = cfg.flags.NoFramePointer,
}
local flags = { }
for flag, check in pairs(checks) do
if check then
table.insert(flags, flag)
end
end
xcode.printlist(table.join(flags, cfg.buildoptions), 'OTHER_CFLAGS',cfg)
-- build list of "other" linked flags. All libraries that aren't frameworks
-- are listed here, so I don't have to try and figure out if they are ".a"
-- or ".dylib", which Xcode requires to list in the Frameworks section
flags = { }
for _, lib in ipairs(premake.getlinks(cfg, "system")) do
if not xcode.isframework(lib) then
table.insert(flags, "-l" .. lib)
end
end
flags = table.join(flags, cfg.linkoptions)
xcode.printlist(flags, 'OTHER_LDFLAGS',cfg)
if cfg.flags.StaticRuntime then
--_p(4,'STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = static;')
xcode.PrintBuildSetting(4, 'STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = static;', cfg)
end
if targetdir ~= "." then
--_p(4,'SYMROOT = "%s";', targetdir)
xcode.PrintBuildSetting(4,'SYMROOT = "' .. targetdir .. '";', cfg)
end
if cfg.flags.ExtraWarnings then
--_p(4,'WARNING_CFLAGS = "-Wall";')
xcode.PrintBuildSetting(4,'WARNING_CFLAGS = "-Wall";', cfg)
end
_p(3,'};')
_p(3,'name = "%s";', cfgname)
_p(2,'};')
end
function xcode.XCBuildConfiguration(tr)
_p('/* Begin XCBuildConfiguration section */')
for _, target in ipairs(tr.products.children) do
for _, cfg in ipairs(tr.configs) do
xcode.XCBuildConfiguration_Target(tr, target, cfg)
end
end
for _, cfg in ipairs(tr.configs) do
xcode.XCBuildConfiguration_Project(tr, cfg)
end
_p('/* End XCBuildConfiguration section */')
_p('')
end
function xcode.XCBuildConfigurationList(tr)
local sln = tr.project.solution
_p('/* Begin XCConfigurationList section */')
for _, target in ipairs(tr.products.children) do
_p(2,'%s /* Build configuration list for PBXNativeTarget "%s" */ = {', target.cfgsection, target.name)
_p(3,'isa = XCConfigurationList;')
_p(3,'buildConfigurations = (')
for _, cfg in ipairs(tr.configs) do
_p(4,'%s /* %s */,', cfg.xcode.targetid, xcode.getconfigname(cfg))
end
_p(3,');')
_p(3,'defaultConfigurationIsVisible = 0;')
_p(3,'defaultConfigurationName = "%s";', xcode.getconfigname(tr.configs[1]))
_p(2,'};')
end
_p(2,'1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "%s" */ = {', tr.name)
_p(3,'isa = XCConfigurationList;')
_p(3,'buildConfigurations = (')
for _, cfg in ipairs(tr.configs) do
_p(4,'%s /* %s */,', cfg.xcode.projectid, xcode.getconfigname(cfg))
end
_p(3,');')
_p(3,'defaultConfigurationIsVisible = 0;')
_p(3,'defaultConfigurationName = "%s";', xcode.getconfigname(tr.configs[1]))
_p(2,'};')
_p('/* End XCConfigurationList section */')
_p('')
end
function xcode.Footer()
_p(1,'};')
_p('\trootObject = 08FB7793FE84155DC02AAC07 /* Project object */;')
_p('}')
end
| bsd-3-clause |
piller187/LeadwerksComponentSystem | LcsSample/scripts/GUI/Slider.lua | 1 | 27093 | --Styles
if Style==nil then Style={} end
if Style.Slider==nil then Style.Slider={} end
Style.Slider.Horizontal=1
Style.Slider.Vertical=2
Style.Slider.Scrollbar=4
Style.Slider.Trackbar=8
Style.Slider.Stepper=16
--Initial values
Script.hovered=false
Script.itemheight=20
Script.sliderwidth=19
Script.sliderincrements = 1
Script.arrowsize=10
Script.stepperarrowsize=7
Script.trackbarknobsize=8
Script.knobwidth=12
--function Script:DoubleCLick(button,x,y)
--end
function Script:UpdateSlider()
local gui = self.widget:GetGUI()
local sz = self.widget:GetSize(true)
local scale = gui:GetScale()
if self.itemheight*scale * self.widget:CountItems()>sz.height then
self.slidervisible=true
--self.sliderrange.x = sz.height
--self.sliderrange.y = self.itemheight*scale * self.widget:CountItems()
self.widget:SetRange(sz.height,self.itemheight*scale * self.widget:CountItems())
else
self.slidervisible=nil
end
self.itemcount=self.widget:CountItems()
self.guiscale = scale
end
function Script:Draw(x,y,width,height)
local gui = self.widget:GetGUI()
local pos = self.widget:GetPosition(true)
local sz = self.widget:GetSize(true)
local scale = gui:GetScale()
local style = self.widget:GetStyle()
--System:Print(self.widget:GetPosition().x)
if self:bitand(style,Style.Slider.Horizontal)==false then
-----------------------------------------------
--Draw vertical slider
-----------------------------------------------
if self:bitand(style,Style.Slider.Trackbar)==true then
-----------------------------------------------
--Trackbar style
-----------------------------------------------
gui:SetColor(0.2)
gui:DrawRect(pos.x+sz.width/2-scale*2,pos.y+self.trackbarknobsize*scale/2,scale*4,sz.height-self.trackbarknobsize*scale+1,0)
if self.hovered then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x+sz.width/2-scale*2,pos.y+self.trackbarknobsize*scale/2,scale*4,sz.height-self.trackbarknobsize*scale+1,1)
--Draw ticks
--[[for n=0,self.sliderrange.y-1 do
local y = n / (self.sliderrange.y-1) * (sz.height - self.trackbarknobsize*scale)
if n==0 or n==self.sliderrange.y-1 then
gui:SetColor(0)
gui:DrawLine(pos.x + sz.width/2 - 2.5*2*scale,self.trackbarknobsize*scale/2 + pos.y + y,pos.x + sz.width/2 + 2*2.5*scale,self.trackbarknobsize*scale/2 + pos.y + y)
else
gui:SetColor(0)
gui:DrawLine(pos.x + sz.width/2 + 2*scale,self.trackbarknobsize*scale/2 + pos.y + y,pos.x + sz.width/2 + 3*scale + 2*scale,self.trackbarknobsize*scale/2 + pos.y + y)
end
end]]
--Draw knob
local y = self.widget:GetSliderValue() / (self.widget:GetRange().y-1) * (sz.height - self.trackbarknobsize*scale) - self.trackbarknobsize*scale/2
local rx = pos.x + sz.width/2 - self.knobwidth/2*scale
local ry = pos.y + self.trackbarknobsize*scale/2 + y
local rw = self.knobwidth*scale
local rh = self.trackbarknobsize*scale
if self.knobhoveredstate then
gui:SetColor(1)
else
gui:SetColor(0.7)
end
gui:DrawPolygon(rx,ry, rx+rw,ry, rx+rw+rh/2, ry+rh/2, rx+rw, ry+rh, rx, ry+rh, 0)
if self.hovered then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawPolygon(rx,ry, rx+rw,ry, rx+rw+rh/2, ry+rh/2, rx+rw, ry+rh, rx, ry+rh, 1)
elseif self:bitand(style,Style.Slider.Stepper)==true then
-----------------------------------------------
--Stepper style
-----------------------------------------------
local arrowsz = self.stepperarrowsize*scale
--Top button
if self.arrowpressed==-1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x,pos.y,sz.width,math.floor(sz.height/2),0)
end
if self.sliderhoverstate==-1 then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x,pos.y,sz.width,math.floor(sz.height/2),1)
if self.sliderhoverstate==-1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
gui:DrawPolygon(pos.x + (sz.width - arrowsz)/2, pos.y + (sz.height/2+arrowsz/2)/2,pos.x + sz.width/2, pos.y + (sz.height/2-arrowsz/2)/2,pos.x + (sz.width + arrowsz)/2, pos.y + (sz.height/2+arrowsz/2)/2,0)
--Bottom button
if self.arrowpressed==1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x,pos.y + math.floor(sz.height/2),sz.width,math.floor(sz.height/2),0)
end
if self.sliderhoverstate==1 then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x,pos.y + math.floor(sz.height/2),sz.width,math.floor(sz.height/2),1)
if self.sliderhoverstate==1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
gui:DrawPolygon(pos.x + (sz.width - arrowsz)/2, sz.height - sz.height/2 + pos.y + (sz.height/2-arrowsz/2)/2, pos.x + sz.width/2, sz.height - sz.height/2 + pos.y + (sz.height/2+arrowsz/2)/2, pos.x + (sz.width + arrowsz)/2, sz.height - sz.height/2 + pos.y + (sz.height/2-arrowsz/2)/2,0)
else
-----------------------------------------------
--Scrollbar style
-----------------------------------------------
--Top button
if self.arrowpressed==-1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x,pos.y,sz.width,self.sliderwidth*scale,0)
end
gui:SetColor(0,0,0)
gui:DrawRect(pos.x,pos.y,sz.width,self.sliderwidth*scale,1)
if self.sliderhoverstate==-1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
gui:DrawPolygon(pos.x + (sz.width - self.arrowsize*scale)/2, pos.y + (self.sliderwidth*scale+self.arrowsize*scale/2)/2, pos.x + sz.width/2, pos.y + (self.sliderwidth*scale-self.arrowsize*scale/2)/2, pos.x + (sz.width + self.arrowsize*scale)/2, pos.y + (self.sliderwidth*scale+self.arrowsize*scale/2)/2,0)
--Track
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x,pos.y+self.sliderwidth*scale,sz.x,sz.height-self.sliderwidth*scale*2,0)
--Bottom button
if self.arrowpressed==1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x,pos.y+sz.height-self.sliderwidth*scale,sz.width,self.sliderwidth*scale,0)
end
gui:SetColor(0,0,0)
gui:DrawRect(pos.x,pos.y+sz.height-self.sliderwidth*scale,sz.width,self.sliderwidth*scale,1)
if self.sliderhoverstate==1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
gui:DrawPolygon(pos.x + (sz.width - self.arrowsize*scale)/2, sz.height - self.sliderwidth*scale + pos.y + (self.sliderwidth*scale-self.arrowsize*scale/2)/2, pos.x + sz.width/2, sz.height - self.sliderwidth*scale + pos.y + (self.sliderwidth*scale+self.arrowsize*scale/2)/2,pos.x + (sz.width + self.arrowsize*scale)/2, sz.height - self.sliderwidth*scale + pos.y + (self.sliderwidth*scale-self.arrowsize*scale/2)/2,0)
--Slider knob
local knob = self:GetKnobArea()
gui:SetColor(0.25,0.25,0.25)
gui:DrawRect(pos.x,pos.y+scale*self.sliderwidth+knob.position,sz.width,knob.size,0)
gui:SetColor(0,0,0)
gui:DrawRect(pos.x,pos.y+scale*self.sliderwidth+knob.position-1,sz.width,knob.size+2,1)
--Outline
if self.hovered then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x,pos.y,sz.x,sz.y,1)
end
else
-----------------------------------------------
--Draw horizontal slider
-----------------------------------------------
if self:bitand(style,Style.Slider.Trackbar)==true then
-----------------------------------------------
--Trackbar style
-----------------------------------------------
gui:SetColor(0.2)
gui:DrawRect(pos.x+self.trackbarknobsize*scale/2,pos.y+sz.height/2-scale*2,sz.width-self.trackbarknobsize*scale+1,scale*4,0)
--if self.hovered then
-- gui:SetColor(51/255/4,151/255/4,1/4)
--else
gui:SetColor(0,0,0)
--end
gui:DrawRect(pos.x+self.trackbarknobsize*scale/2,pos.y+sz.height/2-scale*2,sz.width-self.trackbarknobsize*scale+1,scale*4,1)
--Draw ticks
--[[for n=0,self.sliderrange.y-1 do
local x = n / (self.sliderrange.y-1) * (sz.width - self.trackbarknobsize*scale)
if n==0 or n==self.sliderrange.y-1 then
gui:SetColor(0)
--gui:DrawLine(pos.x + sz.width/2 - 2.5*2*scale,self.trackbarknobsize*scale/2 + pos.y + y,pos.x + sz.width/2 + 2*2.5*scale,self.trackbarknobsize*scale/2 + pos.y + y)
gui:DrawLine(self.trackbarknobsize*scale/2 + pos.x + x,pos.y + sz.height/2 - 2.5*2*scale,self.trackbarknobsize*scale/2 + pos.x + x,pos.y + sz.height/2 + 2*2.5*scale)
else
gui:SetColor(0)
--gui:DrawLine(pos.x + sz.width/2 + 2*scale,self.trackbarknobsize*scale/2 + pos.y + y,pos.x + sz.width/2 + 3*scale + 2*scale,self.trackbarknobsize*scale/2 + pos.y + y)
gui:DrawLine(self.trackbarknobsize*scale/2 + pos.x + x,pos.y + sz.height/2 + 2*scale,self.trackbarknobsize*scale/2 + pos.x + x,pos.y + sz.height/2 + 3*scale + 2*scale)
end
end]]
--Draw knob
local x = self.widget:GetSliderValue() / (self.widget:GetRange().y-1) * (sz.width - self.trackbarknobsize*scale) - self.trackbarknobsize*scale/2
local rx = pos.x + self.trackbarknobsize*scale/2 + x
local ry = pos.y + sz.height/2 - self.knobwidth/2*scale
local rw = self.trackbarknobsize*scale
local rh = self.knobwidth*scale
if self.knobhoveredstate then
gui:SetColor(1)
else
gui:SetColor(0.7)
end
gui:DrawPolygon(rx,ry, rx,ry+rh, rx+rw/2, ry+rh+rw/2, rx+rw, ry+rh, rx+rw, ry, 0)
if self.hovered then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawPolygon(rx,ry, rx,ry+rh, rx+rw/2, ry+rh+rw/2, rx+rw, ry+rh, rx+rw, ry, 1)
elseif self:bitand(style,Style.Slider.Stepper)==true then
-----------------------------------------------
--Stepper style
-----------------------------------------------
local arrowsz = self.stepperarrowsize*scale
--Left button
if self.arrowpressed==-1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x,pos.y,math.floor(sz.width/2),sz.height,0)
end
if self.sliderhoverstate==-1 then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x,pos.y,math.floor(sz.width/2),sz.height,1)
if self.sliderhoverstate==-1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
local v0 = Vec2(pos.x + (sz.width/2+arrowsz/2)/2, pos.y + (sz.height - arrowsz)/2)
local v1 = Vec2(pos.x + (sz.width/2-arrowsz/2)/2, pos.y + sz.height/2)
local v2 = Vec2(pos.x + (sz.width/2+arrowsz/2)/2, pos.y + (sz.height + arrowsz)/2)
gui:DrawPolygon(v0.x, v0.y, v1.x, v1.y, v2.x, v2.y, 0)
--Right button
if self.arrowpressed==1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x + math.floor(sz.width/2),pos.y,math.floor(sz.width/2),sz.height,0)
end
if self.sliderhoverstate==1 then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x + math.floor(sz.width/2),pos.y,math.floor(sz.width/2),sz.height,1)
if self.sliderhoverstate==1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
local v0 = Vec2(sz.width - sz.width/2 + pos.x + (sz.width/2-arrowsz/2)/2, pos.y + (sz.height - arrowsz)/2)
local v1 = Vec2(sz.width - sz.width/2 + pos.x + (sz.width/2+arrowsz/2)/2, pos.y + sz.height/2)
local v2 = Vec2(sz.width - sz.width/2 + pos.x + (sz.width/2-arrowsz/2)/2, pos.y + (sz.height + arrowsz)/2)
gui:DrawPolygon(v0.x, v0.y, v1.x, v1.y, v2.x, v2.y, 0)
else
-----------------------------------------------
--Scrollbar style
-----------------------------------------------
--Left button
if self.arrowpressed==-1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x,pos.y,self.sliderwidth*scale,sz.height,0)
end
gui:SetColor(0,0,0)
gui:DrawRect(pos.x,pos.y,self.sliderwidth*scale,sz.height,1)
if self.sliderhoverstate==-1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
local v0 = Vec2(pos.x + (self.sliderwidth*scale+self.arrowsize*scale/2)/2, pos.y + (sz.height - self.arrowsize*scale)/2)
local v1 = Vec2(pos.x + (self.sliderwidth*scale-self.arrowsize*scale/2)/2, pos.y + sz.height/2)
local v2 = Vec2(pos.x + (self.sliderwidth*scale+self.arrowsize*scale/2)/2, pos.y + (sz.height + self.arrowsize*scale)/2)
gui:DrawPolygon(v0.x, v0.y, v1.x, v1.y, v2.x, v2.y, 0)
--Track
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x+self.sliderwidth*scale,pos.y,sz.width-self.sliderwidth*scale*2,sz.y,0)
--Right button
if self.arrowpressed==1 then
gui:SetColor(0.2,0.2,0.2)
gui:DrawRect(pos.x+sz.width-self.sliderwidth*scale,pos.y,self.sliderwidth*scale,sz.height,0)
end
gui:SetColor(0,0,0)
gui:DrawRect(pos.x+sz.width-self.sliderwidth*scale,pos.y,self.sliderwidth*scale,sz.height,1)
if self.sliderhoverstate==1 then
gui:SetColor(1,1,1)
else
gui:SetColor(0.75,0.75,0.75)
end
local v0 = Vec2(pos.x + sz.width - self.sliderwidth*scale + (self.sliderwidth*scale-self.arrowsize*scale/2)/2, pos.y + (sz.height - self.arrowsize*scale)/2)
local v1 = Vec2(pos.x + sz.width - self.sliderwidth*scale + (self.sliderwidth*scale+self.arrowsize*scale/2)/2, pos.y + sz.height/2)
local v2 = Vec2(pos.x + sz.width - self.sliderwidth*scale + (self.sliderwidth*scale-self.arrowsize*scale/2)/2, pos.y + (sz.height + self.arrowsize*scale)/2)
gui:DrawPolygon(v0.x, v0.y, v1.x, v1.y, v2.x, v2.y, 0)
--Slider knob
local knob = self:GetKnobArea()
gui:SetColor(0.25,0.25,0.25)
gui:DrawRect(pos.x+scale*self.sliderwidth+knob.position,pos.y,knob.size,sz.height,0)
gui:SetColor(0,0,0)
gui:DrawRect(pos.x+scale*self.sliderwidth+knob.position-1,pos.y,knob.size+2,sz.height,1)
--Outline
if self.hovered then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x,pos.y,sz.x,sz.y,1)
end
end
--[[
local item = self.widget:GetSelectedItem()
local y=0
local firstitem = math.floor(self.offset / (self.itemheight*scale))
local lastitem = math.ceil((self.offset + sz.height) / (self.itemheight*scale))
firstitem = math.max(0,firstitem)
lastitem = math.min(lastitem,self.widget:CountItems()-1)
for item=firstitem,lastitem do
y=item*scale*self.itemheight
if item==self.widget:GetSelectedItem() then
--if self.focused==true then
gui:SetColor(51/255/2,151/255/2,1/2)
--else
-- gui:SetColor(0.4,0.4,0.4)
--end
gui:DrawRect(pos.x,pos.y+y-self.offset,sz.width,scale*self.itemheight)
end
gui:SetColor(0.75,0.75,0.75)
gui:DrawText(self.widget:GetItemText(item), scale * 8 + pos.x, pos.y + y - self.offset, sz.width, scale * self.itemheight, Text.Left + Text.VCenter)
end
if self.hovered then
gui:SetColor(51/255/4,151/255/4,1/4)
else
gui:SetColor(0,0,0)
end
gui:DrawRect(pos.x,pos.y,sz.width-1,sz.height-1,1)
]]
end
function Script:GetKnobArea()
local knob = {}
local scale = self.widget:GetGUI():GetScale()
local sz = self.widget:GetSize(true)
local style = self.widget:GetStyle()
if self:bitand(style,Style.Slider.Horizontal)==false then
knob.position = Math:Round(self.widget:GetSliderValue() / self.widget:GetRange().y * (sz.height-scale*self.sliderwidth*2))
knob.size = Math:Round(self.widget:GetRange().x / self.widget:GetRange().y * (sz.height-scale*self.sliderwidth*2))
else
knob.position = Math:Round(self.widget:GetSliderValue() / self.widget:GetRange().y * (sz.width-scale*self.sliderwidth*2))
knob.size = Math:Round(self.widget:GetRange().x / self.widget:GetRange().y * (sz.width-scale*self.sliderwidth*2))
end
return knob
end
function Script:SetValue(value)
if value~=self.widget:GetSliderValue() then
self.widget:SetSliderValue(value)
if self.owner then
self.owner:UpdateSlider(self.widget)
end
end
end
function Script:MouseWheel(delta)
local prevoffset = self.widget:GetSliderValue()
local scale = self.widget:GetGUI():GetScale()
local style = self.widget:GetStyle()
if self:bitand(style,Style.Slider.Trackbar) or self:bitand(style,Style.Slider.Stepper) then
self:SetValue(self.offset + delta)
else
self:SetValue(self.widget:GetSliderValue() + delta * self.sliderincrements)
end
self:SetValue(math.min( math.max(0,self.widget:GetSliderValue()) ,self.widget:GetRange().y-self.widget:GetRange().x))
if prevoffset~=self.widget:GetSliderValue() then
self.widget:Redraw()
EventQueue:Emit(Event.WidgetAction,self.widget,self.widget:GetSliderValue())
end
--[[local item = self.widget:GetSelectedItem() + delta
item = math.max(item,0)
item = math.min(item,self.widget:CountItems()-1)
if item~=self.widget:GetSelectedItem() then
self.widget:SelectItem(item)
EventQueue:Emit(Event.WidgetSelect,self.widget,item)
end]]
end
function Script:MouseEnter(x,y)
self.hovered = true
self.widget:Redraw()
end
function Script:MouseLeave(x,y)
self.hovered = false
self.sliderhoverstate = nil
self.arrowpressed=nil
self.widget:Redraw()
end
function Script:MouseUp(button,x,y)
if button==Mouse.Left then
self.knobgrabbed = false
if self.arrowpressed~=nil then
self.arrowpressed=nil
self.widget:Redraw()
end
end
end
function Script:MouseMove(x,y)
local prevhoverstate = self.sliderhoverstate
local prevknobhoveredstate = self.knobhoveredstate
self.knobhoveredstate = nil
self.sliderhoverstate = nil
if self.knobgrabbed==true then
local state=self.widget:GetSliderValue()
local style = self.widget:GetStyle()
local knob = self:GetKnobArea()
local scale = self.widget:GetGUI():GetScale()
if self:bitand(style,Style.Slider.Horizontal)==false then
if self:bitand(style,Style.Slider.Trackbar) then
local sz = self.widget:GetSize(true)
self:SetValue(Math:Round(((y - self.knobgrabposition)+self.trackbarknobsize*scale/2) / (sz.height - self.trackbarknobsize*scale) * (self.widget:GetRange().y-1)))
else
local knobposition = y - self.knobgrabposition
local sz = self.widget:GetSize(true)
self:SetValue(Math:Round(knobposition / ((sz.y-self.sliderwidth*scale*2) - knob.size) * (self.widget:GetRange().y-self.widget:GetRange().x)))
end
else
if self:bitand(style,Style.Slider.Trackbar) then
local sz = self.widget:GetSize(true)
self:SetValue(Math:Round(((x - self.knobgrabposition)+self.trackbarknobsize*scale/2) / (sz.width - self.trackbarknobsize*scale) * (self.widget:GetRange().y-1)))
else
local knobposition = x - self.knobgrabposition
local sz = self.widget:GetSize(true)
self:SetValue(Math:Round(knobposition / ((sz.x-self.sliderwidth*scale*2) - knob.size) * (self.widget:GetRange().y-self.widget:GetRange().x)))
end
end
self:SetValue(math.max(self.widget:GetSliderValue(),0))
self:SetValue(math.min(self.widget:GetSliderValue(),self.widget:GetRange().y-self.widget:GetRange().x))
if self.widget:GetSliderValue()~=state then
self.widget:Redraw()
EventQueue:Emit(Event.WidgetAction,self.widget,self.widget:GetSliderValue())
end
else
local scale = self.widget:GetGUI():GetScale()
local sz = self.widget:GetSize(true)
local knob = self:GetKnobArea()
if x>=0 and x<sz.width and y>=0 and y<sz.height then
local style = self.widget:GetStyle()
if self:bitand(style,Style.Slider.Horizontal)==false then
if self:bitand(style,Style.Slider.Stepper) then
if y<sz.height/2 then
self.sliderhoverstate=-1
else
self.sliderhoverstate=1
end
elseif self:bitand(style,Style.Slider.Trackbar) then
if x>(sz.width-self.knobwidth*scale)/2 and x<(sz.width+self.knobwidth*scale)/2 then
local kh = self.trackbarknobsize*scale
local ky = self.widget:GetSliderValue() / (self.widget:GetRange().y-1) * (sz.height - self.trackbarknobsize*scale) - self.trackbarknobsize*scale/2 + kh/2
if y>=ky and y<ky+kh then
self.knobhoveredstate=true
end
end
else
if y<self.sliderwidth*scale then
self.sliderhoverstate=-1
elseif y>sz.height-self.sliderwidth*scale then
self.sliderhoverstate=1
end
end
else
if self:bitand(style,Style.Slider.Stepper) then
if x<sz.width/2 then
self.sliderhoverstate=-1
else
self.sliderhoverstate=1
end
else
if x<self.sliderwidth*scale then
self.sliderhoverstate=-1
elseif x>sz.width-self.sliderwidth*scale then
self.sliderhoverstate=1
end
end
end
end
end
if prevhoverstate~=self.sliderhoverstate or prevknobhoveredstate~=self.knobhoveredstate then
self.widget:Redraw()
end
end
function Script:GainFocus()
self.focused = true
end
function Script:LoseFocus()
self.focused = false
self.widget:Redraw()
end
function Script:MouseDown(button,x,y)
local state = self.widget:GetSliderValue()
self.focused=true
if button==Mouse.Left then
local style = self.widget:GetStyle()
local scale = self.widget:GetGUI():GetScale()
local sz = self.widget:GetSize(true)
if x>0 and y>0 and x<sz.width and y<sz.height then
if self:bitand(style,Style.Slider.Horizontal)==false then
if self:bitand(style,Style.Slider.Stepper)==true then
if y<sz.height/2 then
self.arrowpressed=-1
self:MouseWheel(-1)
self.widget:Redraw()
else
self.arrowpressed=1
self:MouseWheel(1)
self.widget:Redraw()
end
return
elseif self:bitand(style,Style.Slider.Trackbar)==true then
if x>(sz.width-self.knobwidth*scale)/2 and x<(sz.width+self.knobwidth*scale)/2 then
local kh = self.trackbarknobsize*scale
local ky = self.widget:GetSliderValue() / (self.widget:GetRange().y-1) * (sz.height - self.trackbarknobsize*scale) - self.trackbarknobsize*scale/2 + kh/2
if y<ky then
--Step up
self:MouseWheel(-1)
elseif y>ky+kh then
--Step down
self:MouseWheel(1)
else
--Grab thew slider knob
self.knobgrabbed=true
self.knobgrabposition = y - ky + kh/2
end
end
else
if y<self.sliderwidth*scale then
self.arrowpressed=-1
self:MouseWheel(-1)
self.widget:Redraw()
elseif y>sz.height - self.sliderwidth*scale then
self.arrowpressed=1
self:MouseWheel(1)
self.widget:Redraw()
else
local knob = self:GetKnobArea()
if y-self.sliderwidth*scale<knob.position then
--Move the knob up
self:SetValue(self.widget:GetSliderValue() - knob.size / (sz.height - self.sliderwidth*scale*2) * self.widget:GetRange().y)
self:SetValue(math.max(self.widget:GetSliderValue(),0))
self.widget:Redraw()
elseif y-self.sliderwidth*scale>knob.position + knob.size then
--Move the knob down
self:SetValue(self.widget:GetSliderValue() + knob.size / (sz.height - self.sliderwidth*scale*2) * self.widget:GetRange().y)
self:SetValue(math.min(self.widget:GetSliderValue(),self.widget:GetRange().y-self.widget:GetRange().x))
self.widget:Redraw()
else
--Grab thew slider knob
self.knobgrabbed=true
self.knobgrabposition = y - knob.position
end
end
end
else
if self:bitand(style,Style.Slider.Stepper)==true then
if x<sz.width/2 then
self.arrowpressed=-1
self:MouseWheel(-1)
self.widget:Redraw()
else
self.arrowpressed=1
self:MouseWheel(1)
self.widget:Redraw()
end
return
elseif self:bitand(style,Style.Slider.Trackbar)==true then
if y>(sz.height-self.knobwidth*scale)/2 and y<(sz.height+self.knobwidth*scale)/2 then
local kw = self.trackbarknobsize*scale
local kx = self.widget:GetSliderValue() / (self.widget:GetRange().y-1) * (sz.width - self.trackbarknobsize*scale) - self.trackbarknobsize*scale/2 + kw/2
if x<kx then
--Step up
self:MouseWheel(-1)
elseif x>kx+kw then
--Step down
self:MouseWheel(1)
else
--Grab thew slider knob
self.knobgrabbed=true
self.knobgrabposition = x - kx + kw/2
end
end
else
if x<self.sliderwidth*scale then
self.arrowpressed=-1
self:MouseWheel(-1)
self.widget:Redraw()
return
elseif x>sz.width - self.sliderwidth*scale then
self.arrowpressed=1
self:MouseWheel(1)
self.widget:Redraw()
return
else
local knob = self:GetKnobArea()
if x-self.sliderwidth*scale<knob.position then
--Move the knob left
self:SetValue(self.widget:GetSliderValue() - knob.size / (sz.width - self.sliderwidth*scale*2) * self.widget:GetRange().y)
self:SetValue(math.max(self.widget:GetSliderValue(),0))
self.widget:Redraw()
elseif x-self.sliderwidth*scale>knob.position + knob.size then
--Move the knob right
self:SetValue(self.widget:GetSliderValue() + knob.size / (sz.width - self.sliderwidth*scale*2) * self.widget:GetRange().y)
self:SetValue(math.min(self.widget:GetSliderValue(),self.widget:GetRange().y-self.widget:GetRange().x))
self.widget:Redraw()
else
--Grab thew slider knob
self.knobgrabbed=true
self.knobgrabposition = x - knob.position
end
end
end
end
end
end
if self.widget:GetSliderValue()~=state then
EventQueue:Emit(Event.WidgetAction,self.widget,self.widget:GetSliderValue())
end
end
function Script:bitand(set, flag)
return set % (2*flag) >= flag
end
function Script:KeyDown(button)
local state = self.widget:GetSliderValue()
local style = self.widget:GetStyle()
if button==Key.Right or button==Key.Down then--(button==Key.Right and self:bitand(style,Style.Slider.Horizontal)==true) or (button==Key.Down and self:bitand(style,Style.Slider.Horizontal)==false) then
self:SetValue(self.widget:GetSliderValue() + self.sliderincrements)
self:SetValue(math.min(self.widget:GetSliderValue(),self.widget:GetRange().y-self.widget:GetRange().x))
end
if button==Key.Left or button==Key.Up then--(button==Key.Left and self:bitand(style,Style.Slider.Horizontal)==true) or (button==Key.Up and self:bitand(style,Style.Slider.Horizontal)==false) then
self:SetValue(self.widget:GetSliderValue() - self.sliderincrements)
self:SetValue(math.max(self.widget:GetSliderValue(),0))
end
if self.widget:GetSliderValue()~=state then
self.widget:Redraw()
EventQueue:Emit(Event.WidgetAction,self.widget,self.widget:GetSliderValue())
end
end
| gpl-3.0 |
ktosiu/nodemcu-firmware | lua_modules/http/http.lua | 89 | 6624 | ------------------------------------------------------------------------------
-- HTTP server module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
------------------------------------------------------------------------------
local collectgarbage, tonumber, tostring = collectgarbage, tonumber, tostring
local http
do
------------------------------------------------------------------------------
-- request methods
------------------------------------------------------------------------------
local make_req = function(conn, method, url)
local req = {
conn = conn,
method = method,
url = url,
}
-- return setmetatable(req, {
-- })
return req
end
------------------------------------------------------------------------------
-- response methods
------------------------------------------------------------------------------
local send = function(self, data, status)
local c = self.conn
-- TODO: req.send should take care of response headers!
if self.send_header then
c:send("HTTP/1.1 ")
c:send(tostring(status or 200))
-- TODO: real HTTP status code/name table
c:send(" OK\r\n")
-- we use chunked transfer encoding, to not deal with Content-Length:
-- response header
self:send_header("Transfer-Encoding", "chunked")
-- TODO: send standard response headers, such as Server:, Date:
end
if data then
-- NB: no headers allowed after response body started
if self.send_header then
self.send_header = nil
-- end response headers
c:send("\r\n")
end
-- chunked transfer encoding
c:send(("%X\r\n"):format(#data))
c:send(data)
c:send("\r\n")
end
end
local send_header = function(self, name, value)
local c = self.conn
-- NB: quite a naive implementation
c:send(name)
c:send(": ")
c:send(value)
c:send("\r\n")
end
-- finalize request, optionally sending data
local finish = function(self, data, status)
local c = self.conn
-- NB: req.send takes care of response headers
if data then
self:send(data, status)
end
-- finalize chunked transfer encoding
c:send("0\r\n\r\n")
-- close connection
c:close()
end
--
local make_res = function(conn)
local res = {
conn = conn,
}
-- return setmetatable(res, {
-- send_header = send_header,
-- send = send,
-- finish = finish,
-- })
res.send_header = send_header
res.send = send
res.finish = finish
return res
end
------------------------------------------------------------------------------
-- HTTP parser
------------------------------------------------------------------------------
local http_handler = function(handler)
return function(conn)
local req, res
local buf = ""
local method, url
local ondisconnect = function(conn)
collectgarbage("collect")
end
-- header parser
local cnt_len = 0
local onheader = function(conn, k, v)
-- TODO: look for Content-Type: header
-- to help parse body
-- parse content length to know body length
if k == "content-length" then
cnt_len = tonumber(v)
end
if k == "expect" and v == "100-continue" then
conn:send("HTTP/1.1 100 Continue\r\n")
end
-- delegate to request object
if req and req.onheader then
req:onheader(k, v)
end
end
-- body data handler
local body_len = 0
local ondata = function(conn, chunk)
-- NB: do not reset node in case of lengthy requests
tmr.wdclr()
-- feed request data to request handler
if not req or not req.ondata then return end
req:ondata(chunk)
-- NB: once length of seen chunks equals Content-Length:
-- onend(conn) is called
body_len = body_len + #chunk
-- print("-B", #chunk, body_len, cnt_len, node.heap())
if body_len >= cnt_len then
req:ondata()
end
end
local onreceive = function(conn, chunk)
-- merge chunks in buffer
if buf then
buf = buf .. chunk
else
buf = chunk
end
-- consume buffer line by line
while #buf > 0 do
-- extract line
local e = buf:find("\r\n", 1, true)
if not e then break end
local line = buf:sub(1, e - 1)
buf = buf:sub(e + 2)
-- method, url?
if not method then
local i
-- NB: just version 1.1 assumed
_, i, method, url = line:find("^([A-Z]+) (.-) HTTP/1.1$")
if method then
-- make request and response objects
req = make_req(conn, method, url)
res = make_res(conn)
end
-- header line?
elseif #line > 0 then
-- parse header
local _, _, k, v = line:find("^([%w-]+):%s*(.+)")
-- header seems ok?
if k then
k = k:lower()
onheader(conn, k, v)
end
-- headers end
else
-- spawn request handler
-- NB: do not reset in case of lengthy requests
tmr.wdclr()
handler(req, res)
tmr.wdclr()
-- NB: we feed the rest of the buffer as starting chunk of body
ondata(conn, buf)
-- buffer no longer needed
buf = nil
-- NB: we explicitly reassign receive handler so that
-- next received chunks go directly to body handler
conn:on("receive", ondata)
-- parser done
break
end
end
end
conn:on("receive", onreceive)
conn:on("disconnection", ondisconnect)
end
end
------------------------------------------------------------------------------
-- HTTP server
------------------------------------------------------------------------------
local srv
local createServer = function(port, handler)
-- NB: only one server at a time
if srv then srv:close() end
srv = net.createServer(net.TCP, 15)
-- listen
srv:listen(port, http_handler(handler))
return srv
end
------------------------------------------------------------------------------
-- HTTP server methods
------------------------------------------------------------------------------
http = {
createServer = createServer,
}
end
return http
| mit |
ktosiu/nodemcu-firmware | examples/fragment.lua | 55 | 19918 | pwm.setup(0,500,50) pwm.setup(1,500,50) pwm.setup(2,500,50)
pwm.start(0) pwm.start(1) pwm.start(2)
function led(r,g,b) pwm.setduty(0,g) pwm.setduty(1,b) pwm.setduty(2,r) end
wifi.sta.autoconnect(1)
a=0
tmr.alarm( 1000,1,function() if a==0 then a=1 led(50,50,50) else a=0 led(0,0,0) end end)
sv:on("receive", function(s,c) s:send("<h1> Hello, world.</h1>") print(c) end )
sk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(80,"115.239.210.27")
sk:send("GET / HTTP/1.1\r\nHost: 115.239.210.27\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
sk:connect(80,"192.168.0.66")
sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
i2c.setup(0,1,0,i2c.SLOW)
function read_bmp(addr) i2c.start(0) i2c.address(0,119,i2c.RECEIVER) c=i2c.read(0,1) i2c.stop(0) print(string.byte(c)) end
function read_bmp(addr) i2c.start(0) i2c.address(0,119,i2c.TRANSMITTER) i2c.write(0,addr) i2c.stop(0) i2c.start(0) i2c.address(0,119,i2c.RECEIVER) c=i2c.read(0,2) i2c.stop(0) return c end
s=net.createServer(net.TCP) s:listen(80,function(c) end)
ss=net.createServer(net.TCP) ss:listen(80,function(c) end)
s=net.createServer(net.TCP) s:listen(80,function(c) c:on("receive",function(s,c) print(c) end) end)
s=net.createServer(net.UDP)
s:on("receive",function(s,c) print(c) end)
s:listen(5683)
su=net.createConnection(net.UDP)
su:on("receive",function(su,c) print(c) end)
su:connect(5683,"192.168.18.101")
su:send("hello")
mm=node.list()
for k, v in pairs(mm) do print('file:'..k..' len:'..v) end
for k,v in pairs(d) do print("n:"..k..", s:"..v) end
gpio.mode(0,gpio.INT) gpio.trig(0,"down",function(l) print("level="..l) end)
t0 = 0;
function tr0(l) print(tmr.now() - t0) t0 = tmr.now()
if l==1 then gpio.trig(0,"down") else gpio.trig(0,"up") end end
gpio.mode(0,gpio.INT)
gpio.trig(0,"down",tr0)
su=net.createConnection(net.UDP)
su:on("receive",function(su,c) print(c) end)
su:connect(5001,"114.215.154.114")
su:send([[{"type":"signin","name":"nodemcu","password":"123456"}]])
su:send([[{"type":"signout","name":"nodemcu","password":"123456"}]])
su:send([[{"type":"connect","from":"nodemcu","to":"JYP","password":"123456"}]])
su:send("hello world")
s=net.createServer(net.TCP) s:listen(8008,function(c) c:on("receive",function(s,c) print(c) pcall(loadstring(c)) end) end)
s=net.createServer(net.TCP) s:listen(8008,function(c) con_std = c function s_output(str) if(con_std~=nil) then con_std:send(str) end end
node.output(s_output, 0) c:on("receive",function(c,l) node.input(l) end) c:on("disconnection",function(c) con_std = nil node.output(nil) end) end)
s=net.createServer(net.TCP)
s:listen(23,function(c)
con_std = c
function s_output(str)
if(con_std~=nil)
then con_std:send(str)
end
end
node.output(s_output, 0)
c:on("receive",function(c,l) node.input(l) end)
c:on("disconnection",function(c)
con_std = nil
node.output(nil)
end)
end)
srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive",function(conn,payload)
print(node.heap()) door="open" if gpio.read(8)==1 then door="open" else door="closed" end
conn:send("<h1> Door Sensor. The door is " .. door ..".</h1>") conn:close() end) end)
srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive",function(conn,payload)
print(node.heap()) print(adc.read(0)) door="open" if gpio.read(0)==1 then door="open" else door="closed" end
conn:send("<h1> Door Sensor. The door is " .. door ..".</h1>") end) conn:on("sent",function(conn) conn:close() end) end)
srv=net.createServer(net.TCP) srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(node.heap())
door="open"
if gpio.read(0)==1 then door="open" else door="closed" end
conn:send("<h1> Door Sensor. The door is " .. door ..".</h1>")
end)
conn:on("sent",function(conn) conn:close() end)
end)
port = 9999
hostip = "192.168.1.99"
sk=net.createConnection(net.TCP, false)
sk:on("receive", function(conn, pl) print(pl) end )
sk:connect(port, hostip)
file.remove("init.lua")
file.open("init.lua","w")
file.writeline([[print("Petes Tester 4")]])
file.writeline([[tmr.alarm(5000, 0, function() dofile("thelot.lua") end )]])
file.close()
file.remove("thelot.lua")
file.open("thelot.lua","w")
file.writeline([[tmr.stop()]])
file.writeline([[connecttoap = function (ssid,pw)]])
file.writeline([[print(wifi.sta.getip())]])
file.writeline([[wifi.setmode(wifi.STATION)]])
file.writeline([[tmr.delay(1000000)]])
file.writeline([[wifi.sta.config(ssid,pw)]])
file.writeline([[tmr.delay(5000000)]])
file.writeline([[print("Connected to ",ssid," as ",wifi.sta.getip())]])
file.writeline([[end]])
file.writeline([[connecttoap("MyHub","0011223344")]])
file.close()
s=net.createServer(net.UDP) s:listen(5683) s:on("receive",function(s,c) print(c) s:send("echo:"..c) end)
s:on("sent",function(s) print("echo donn") end)
sk=net.createConnection(net.UDP, 0) sk:on("receive", function(sck, c) print(c) end ) sk:connect(8080,"192.168.0.88")
sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.88\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
srv=net.createServer(net.TCP, 5) srv:listen(80,function(conn) conn:on("receive",function(conn,payload)
print(node.heap()) print(adc.read(0)) door="open" if gpio.read(0)==1 then door="open" else door="closed" end
conn:send("<h1> Door Sensor. The door is " .. door ..".</h1>") end) end)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(payload) print(node.heap())
conn:send("<h1> Hello, NodeMcu.</h1>")
end)
conn:on("sent",function(conn) conn:close() end)
end)
function startServer()
print("WIFI AP connected. Wicon IP:")
print(wifi.sta.getip())
sv=net.createServer(net.TCP,180)
sv:listen(8080,function(conn)
print("Wifi console connected.")
function s_output(str)
if(conn~=nil) then
conn:send(str)
end
end
node.output(s_output,0)
conn:on("receive",function(conn,pl)
node.input(pl)
if (conn==nil) then
print("conn is nil")
end
print("hello")
mycounter=0 srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive",function(conn,payload)
if string.find(payload,"?myarg=") then mycounter=mycounter+1
m="<br/>Value= " .. string.sub(payload,string.find(payload,"?myarg=")+7,string.find(payload,"HTTP")-2) else m="" end
conn:send("<h1> Hello, this is Pete's web page.</h1>How are you today.<br/> Count=" .. mycounter .. m .. "Heap=".. node.heap())
end) conn:on("sent",function(conn) conn:close() conn = nil end) end)
srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive",function(conn,payload)
conn:send("HTTP/1.1 200 OK\r\n") conn:send("Connection: close\r\n\r\n") conn:send("<h1> Hello, NodeMcu.</h1>")
print(node.heap()) conn:close() end) end)
conn=net.createConnection(net.TCP)
conn:dns("www.nodemcu.com",function(conn,ip) print(ip) print("hell") end)
function connected(conn) conn:on("receive",function(conn,payload)
conn:send("HTTP/1.1 200 OK\r\n") conn:send("Connection: close\r\n\r\n") conn:send("<h1> Hello, NodeMcu.</h1>")
print(node.heap()) conn:close() end) end
srv=net.createServer(net.TCP)
srv:on("connection",function(conn) conn:on("receive",function(conn,payload)
conn:send("HTTP/1.1 200 OK\r\n") conn:send("Connection: close\r\n\r\n") conn:send("<h1> Hello, NodeMcu.</h1>")
print(node.heap()) conn:close() end) end)
srv:listen(80)
-- sieve.lua
-- the sieve of Eratosthenes programmed with coroutines
-- typical usage: lua -e N=500 sieve.lua | column
-- generate all the numbers from 2 to n
function gen (n) return coroutine.wrap(function () for i=2,n do coroutine.yield(i) end end) end
-- filter the numbers generated by `g', removing multiples of `p'
function filter (p, g) return coroutine.wrap(function () for n in g do if n%p ~= 0 then coroutine.yield(n) end end end) end
N=N or 500 -- from command line
x = gen(N) -- generate primes up to N
while 1 do
local n = x() -- pick a number until done
if n == nil then break end
print(n) -- must be a prime number
x = filter(n, x) -- now remove its multiples
end
file.remove("mylistener.lua")
file.open("mylistener.lua","w")
file.writeline([[gpio2 = 9]])
file.writeline([[gpio0 = 8]])
file.writeline([[gpio.mode(gpio2,gpio.OUTPUT)]])
file.writeline([[gpio.write(gpio2,gpio.LOW)]])
file.writeline([[gpio.mode(gpio0,gpio.OUTPUT)]])
file.writeline([[gpio.write(gpio0,gpio.LOW)]])
file.writeline([[l1="0\n"]])
file.writeline([[l2="0\n"]])
file.writeline([[l3="0\n"]])
file.writeline([[l4="0\n"]])
file.writeline([[sv=net.createServer(net.TCP, 5) ]])
file.writeline([[sv:listen(4000,function(c)]])
file.writeline([[c:on("disconnection", function(c) print("Bye") end )]])
file.writeline([[c:on("receive", function(sck, pl) ]])
-- file.writeline([[print(pl) ]])
file.writeline([[if (pl=="GO1\n") then c:send(l1) ]])
file.writeline([[elseif pl=="GO2\n" then c:send(l2) ]])
file.writeline([[elseif pl=="GO3\n" then c:send(l3) ]])
file.writeline([[elseif pl=="GO4\n" then c:send(l4) ]])
file.writeline([[elseif pl=="YES1\n" then l1="1\n" c:send("OK\n") gpio.write(gpio2,gpio.HIGH) ]])
file.writeline([[elseif pl=="NO1\n" then l1="0\n" c:send("OK\n") gpio.write(gpio2,gpio.LOW) ]])
file.writeline([[elseif pl=="YES2\n" then l2="1\n" c:send("OK\n") gpio.write(gpio0,gpio.HIGH) ]])
file.writeline([[elseif pl=="NO2\n" then l2="0\n" c:send("OK\n") gpio.write(gpio0,gpio.LOW) ]])
file.writeline([[elseif pl=="YES3\n" then l3="1\n" c:send("OK\n") print(node.heap()) ]])
file.writeline([[elseif pl=="NO3\n" then l3="0\n" c:send("OK\n") print(node.heap()) ]])
file.writeline([[elseif pl=="YES4\n" then l4="1\n" c:send("OK\n") print(node.heap()) ]])
file.writeline([[elseif pl=="NO4\n" then l4="0\n" c:send("OK\n") print(node.heap()) ]])
file.writeline([[else c:send("0\n") print(node.heap()) ]])
file.writeline([[end]])
file.writeline([[end)]])
file.writeline([[end)]])
file.close()
file.remove("myli.lua") file.open("myli.lua","w")
file.writeline([[sv=net.createServer(net.TCP, 5) ]])
file.writeline([[sv:listen(4000,function(c)]])
file.writeline([[c:on("disconnection", function(c) print("Bye") end )]])
--file.writeline([[c:on("sent", function(c) c:close() end )]])
file.writeline([[c:on("receive", function(sck, pl) ]])
file.writeline([[sck:send("0\n") print(node.heap()) ]])
file.writeline([[end)]]) file.writeline([[end)]]) file.close()
sv=net.createServer(net.TCP, 50) sv:listen(4000,function(c) c:on("disconnection",function(c) print("Bye") end)
c:on("receive", function(sck, pl) sck:send("0\n") print(node.heap()) end) end)
sv=net.createServer(net.TCP, 5) sv:listen(4000,function(c) c:on("disconnection",function(c) print("Bye") end)
c:on("receive", function(sck, pl) sck:send("0\n") print(node.heap()) end) c:on("sent", function(sck) sck:close() end) end)
s=net.createServer(net.UDP)
s:on("receive",function(s,c) print(c) end)
s:listen(8888)
print("This is a long long long line to test the memory limit of nodemcu firmware\n")
collectgarbage("setmemlimit",8)
print(collectgarbage("getmemlimit"))
tmr.alarm(1,5000,1,function() print("alarm 1") end)
tmr.stop(1)
tmr.alarm(0,1000,1,function() print("alarm 0") end)
tmr.stop(0)
tmr.alarm(2,2000,1,function() print("alarm 2") end)
tmr.stop(2)
tmr.alarm(6,2000,1,function() print("alarm 6") end)
tmr.stop(6)
for k,v in pairs(_G.package.loaded) do print(k) end
for k,v in pairs(_G) do print(k) end
for k,v in pairs(d) do print("n:"..k..", s:"..v) end
a="pin=9"
t={}
for k, v in string.gmatch(a, "(%w+)=(%w+)") do t[k]=v end
print(t["pin"])
function switch() gpio.mode(4,gpio.OUTPUT) gpio.mode(5,gpio.OUTPUT) tmr.delay(1000000) print("hello world") end
tmr.alarm(0,10000,0,function () uart.setup(0,9600,8,0,1) end) switch()
sk=net.createConnection(net.TCP, 0) sk:on("receive", function(sck, c) print(c) end ) sk:connect(80,"www.nodemcu.com") sk:send("GET / HTTP/1.1\r\nHost: www.nodemcu.com\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
sk=net.createConnection(net.TCP, 0) sk:on("receive", function(sck, c) print(c) end )
sk:on("connection", function(sck) sck:send("GET / HTTP/1.1\r\nHost: www.nodemcu.com\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n") end ) sk:connect(80,"www.nodemcu.com")
sk=net.createConnection(net.TCP, 0) sk:on("receive", function(sck, c) print(c) end ) sk:connect(80,"115.239.210.27")
sk:send("GET / HTTP/1.1\r\nHost: 115.239.210.27\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")
sk=net.createConnection(net.TCP, 1) sk:on("receive", function(sck, c) print(c) end )
sk:on("connection", function(sck) sck:send("GET / HTTPS/1.1\r\nHost: www.google.com.hk\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n") end ) sk:connect(443,"173.194.72.199")
wifi.sta.setip({ip="192.168.18.119",netmask="255.255.255.0",gateway="192.168.18.1"})
uart.on("data","\r",function(input) if input=="quit\r" then uart.on("data") else print(input) end end, 0)
uart.on("data","\n",function(input) if input=="quit\n" then uart.on("data") else print(input) end end, 0)
uart.on("data", 5 ,function(input) if input=="quit\r" then uart.on("data") else print(input) end end, 0)
uart.on("data", 0 ,function(input) if input=="q" then uart.on("data") else print(input) end end, 0)
uart.on("data","\r",function(input) if input=="quit" then uart.on("data") else print(input) end end, 1)
for k, v in pairs(file.list()) do print('file:'..k..' len:'..v) end
m=mqtt.Client()
m:connect("192.168.18.101",1883)
m:subscribe("/topic",0,function(m) print("sub done") end)
m:on("message",function(m,t,pl) print(t..":") if pl~=nil then print(pl) end end )
m:publish("/topic","hello",0,0)
uart.setup(0,9600,8,0,1,0)
sv=net.createServer(net.TCP, 60)
global_c = nil
sv:listen(9999, function(c)
if global_c~=nil then
global_c:close()
end
global_c=c
c:on("receive",function(sck,pl) uart.write(0,pl) end)
end)
uart.on("data",4, function(data)
if global_c~=nil then
global_c:send(data)
end
end, 0)
file.open("hello.lua","w+")
file.writeline([[print("hello nodemcu")]])
file.writeline([[print(node.heap())]])
file.close()
node.compile("hello.lua")
dofile("hello.lua")
dofile("hello.lc")
-- use copper addon for firefox
cs=coap.Server()
cs:listen(5683)
myvar=1
cs:var("myvar") -- get coap://192.168.18.103:5683/v1/v/myvar will return the value of myvar: 1
-- function should tack one string, return one string.
function myfun(payload)
print("myfun called")
respond = "hello"
return respond
end
cs:func("myfun") -- post coap://192.168.18.103:5683/v1/f/myfun will call myfun
cc = coap.Client()
cc:get(coap.CON, "coap://192.168.18.100:5683/.well-known/core")
cc:post(coap.NON, "coap://192.168.18.100:5683/", "Hello")
file.open("test1.txt", "a+") for i = 1, 100*1000 do file.write("x") end file.close() print("Done.")
for n,s in pairs(file.list()) do print(n.." size: "..s) end
file.remove("test1.txt")
for n,s in pairs(file.list()) do print(n.." size: "..s) end
file.open("test2.txt", "a+") for i = 1, 1*1000 do file.write("x") end file.close() print("Done.")
function TestDNSLeak()
c=net.createConnection(net.TCP, 0)
c:connect(80, "bad-name.tlddfdf")
tmr.alarm(1, 3000, 0, function() print("hack socket close, MEM: "..node.heap()) c:close() end) -- socket timeout hack
print("MEM: "..node.heap())
end
v="abc%0D%0Adef"
print(string.gsub(v, "%%(%x%x)", function(x) return string.char(tonumber(x, 16)) end))
function ex(x) string.find("abc%0Ddef","bc") return 's' end
string.gsub("abc%0Ddef", "%%(%x%x)", ex)
function ex(x) string.char(35) return 's' end
string.gsub("abc%0Ddef", "%%(%x%x)", ex) print("hello")
function ex(x) string.lower('Ab') return 's' end
string.gsub("abc%0Ddef", "%%(%x%x)", ex) print("hello")
v="abc%0D%0Adef"
pcall(function() print(string.gsub(v, "%%(%x%x)", function(x) return string.char(tonumber(x, 16)) end)) end)
mosca -v | bunyan
m=mqtt.Client()
m:connect("192.168.18.88",1883)
topic={}
topic["/topic1"]=0
topic["/topic2"]=0
m:subscribe(topic,function(m) print("sub done") end)
m:on("message",function(m,t,pl) print(t..":") if pl~=nil then print(pl) end end )
m:publish("/topic1","hello",0,0)
m:publish("/topic3","hello",0,0) m:publish("/topic4","hello",0,0)
m=mqtt.Client()
m:connect("192.168.18.88",1883)
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:subscribe("/topic2",0,function(m) print("sub done") end)
m:on("message",function(m,t,pl) print(t..":") if pl~=nil then print(pl) end end )
m:publish("/topic1","hello",0,0)
m:publish("/topic3","hello",0,0) m:publish("/topic4","hello",0,0)
m:publish("/topic1","hello1",0,0) m:publish("/topic2","hello2",0,0)
m:publish("/topic1","hello",1,0)
m:subscribe("/topic3",0,function(m) print("sub done") end)
m:publish("/topic3","hello3",2,0)
m=mqtt.Client()
m:connect("192.168.18.88",1883, function(con) print("connected hello") end)
m=mqtt.Client()
m:on("connect",function(m) print("connection") end )
m:connect("192.168.18.88",1883)
m:on("offline",function(m) print("disconnection") end )
m=mqtt.Client()
m:on("connect",function(m) print("connection "..node.heap()) end )
m:on("offline", function(conn)
if conn == nil then print("conn is nil") end
print("Reconnect to broker...")
print(node.heap())
conn:connect("192.168.18.88",1883,0,1)
end)
m:connect("192.168.18.88",1883,0,1)
m=mqtt.Client()
m:on("connect",function(m) print("connection "..node.heap()) end )
m:on("offline", function(conn)
if conn == nil then print("conn is nil") end
print("Reconnect to broker...")
print(node.heap())
conn:connect("192.168.18.88",1883)
end)
m:connect("192.168.18.88",1883)
m:close()
m=mqtt.Client()
m:connect("192.168.18.88",1883)
m:on("message",function(m,t,pl) print(t..":") if pl~=nil then print(pl) end end )
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:publish("/topic1","hello3",2,0) m:publish("/topic1","hello2",2,0)
m:publish("/topic1","hello3",0,0) m:publish("/topic1","hello2",2,0)
m:subscribe("/topic2",2,function(m) print("sub done") end)
m:publish("/topic2","hello3",0,0) m:publish("/topic2","hello2",2,0)
m=mqtt.Client()
m:on("connect",function(m)
print("connection "..node.heap())
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:publish("/topic1","hello3",0,0) m:publish("/topic1","hello2",2,0)
end )
m:on("offline", function(conn)
print("disconnect to broker...")
print(node.heap())
end)
m:connect("192.168.18.88",1883,0,1)
-- serout( pin, firstLevel, delay_table, [repeatNum] )
gpio.mode(1,gpio.OUTPUT,gpio.PULLUP)
gpio.serout(1,1,{30,30,60,60,30,30}) -- serial one byte, b10110010
gpio.serout(1,1,{30,70},8) -- serial 30% pwm 10k, lasts 8 cycles
gpio.serout(1,1,{3,7},8) -- serial 30% pwm 100k, lasts 8 cycles
gpio.serout(1,1,{0,0},8) -- serial 50% pwm as fast as possible, lasts 8 cycles
gpio.mode(1,gpio.OUTPUT,gpio.PULLUP)
gpio.serout(1,0,{20,10,10,20,10,10,10,100}) -- sim uart one byte 0x5A at about 100kbps
gpio.serout(1,1,{8,18},8) -- serial 30% pwm 38k, lasts 8 cycles
-- Lua: mqtt.Client(clientid, keepalive, user, pass)
-- test with cloudmqtt.com
m_dis={}
function dispatch(m,t,pl)
if pl~=nil and m_dis[t] then
m_dis[t](pl)
end
end
function topic1func(pl)
print("get1: "..pl)
end
function topic2func(pl)
print("get2: "..pl)
end
m_dis["/topic1"]=topic1func
m_dis["/topic2"]=topic2func
m=mqtt.Client("nodemcu1",60,"test","test123")
m:on("connect",function(m)
print("connection "..node.heap())
m:subscribe("/topic1",0,function(m) print("sub done") end)
m:subscribe("/topic2",0,function(m) print("sub done") end)
m:publish("/topic1","hello",0,0) m:publish("/topic2","world",0,0)
end )
m:on("offline", function(conn)
print("disconnect to broker...")
print(node.heap())
end)
m:on("message",dispatch )
m:connect("m11.cloudmqtt.com",11214,0,1)
-- Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
tmr.alarm(0,10000,1,function() local pl = "time: "..tmr.time()
m:publish("/topic1",pl,0,0)
end)
| mit |
ArchShaman/Zero-K | effects/gundam_jetflash.lua | 25 | 1649 | -- jetflash
return {
["jetflash"] = {
bitmapmuzzleflame = {
air = true,
class = [[CBitmapMuzzleFlame]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
colormap = [[0.9 0.8 0.7 0.01 0.9 0.5 0.2 0.01 0 0 0 0.01]],
dir = [[dir]],
frontoffset = 0.05,
fronttexture = [[empty]],
length = 15,
sidetexture = [[shot]],
size = 7,
sizegrowth = 1,
ttl = 2,
},
},
redpuff = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
underwater = 1,
water = true,
properties = {
airdrag = 1,
colormap = [[1 0.6 0 0.01 0.9 0.8 0.7 0.01 0 0 0 0.01]],
directional = true,
emitrot = 1,
emitrotspread = 5,
emitvector = [[dir]],
gravity = [[0.0, 0, .0]],
numparticles = 3,
particlelife = 1,
particlelifespread = 2,
particlesize = 1,
particlesizespread = 3,
particlespeed = 0,
particlespeedspread = 3,
pos = [[0.0, 1, 0.0]],
sizegrowth = 0.9,
sizemod = 1,
texture = [[dirt]],
useairlos = true,
},
},
},
}
| gpl-2.0 |
hacker44-h44/1456 | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
ArchShaman/Zero-K | units/staticantinuke.lua | 1 | 4067 | unitDef = {
unitname = [[staticantinuke]],
name = [[Antinuke]],
description = [[Strategic Nuke Interception System]],
acceleration = 0,
activateWhenBuilt = true,
brakeRate = 0,
buildCostMetal = 3000,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 6,
buildingGroundDecalSizeY = 6,
buildingGroundDecalType = [[antinuke_decal.dds]],
buildPic = [[staticantinuke.png]],
category = [[SINK]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[70 55 110]],
collisionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
removewait = 1,
nuke_coverage = 2500,
modelradius = [[50]],
},
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 5,
footprintZ = 8,
iconType = [[antinuke]],
idleAutoHeal = 5,
idleTime = 1800,
levelGround = false,
maxDamage = 3300,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
objectName = [[antinuke.s3o]],
radarDistance = 2500,
radarEmitHeight = 24,
script = [[staticantinuke.lua]],
selfDestructAs = [[LARGE_BUILDINGEX]],
sightDistance = 660,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardmap = [[oooooooooooooooooooooooooooooooooooooooo]],
weapons = {
{
def = [[AMD_ROCKET]],
},
},
weaponDefs = {
AMD_ROCKET = {
name = [[Anti-Nuke Missile Fake]],
areaOfEffect = 420,
avoidFriendly = false,
avoidGround = false,
avoidFeature = false,
collideFriendly = false,
collideGround = false,
collideFeature = false,
coverage = 100000,
craterBoost = 1,
craterMult = 2,
customParams = {
reaim_time = 15,
nuke_coverage = 2500,
},
damage = {
default = 1500,
subs = 75,
},
explosionGenerator = [[custom:ANTINUKE]],
fireStarter = 100,
flightTime = 20,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
interceptor = 1,
model = [[antinukemissile.s3o]],
noSelfDamage = true,
range = 3800,
reloadtime = 6,
smokeTrail = true,
soundHit = [[weapon/missile/vlaunch_hit]],
soundStart = [[weapon/missile/missile_launch]],
startVelocity = 400,
tolerance = 4000,
tracks = true,
turnrate = 65535,
weaponAcceleration = 800,
weaponTimer = 0.4,
weaponType = [[StarburstLauncher]],
weaponVelocity = 1600,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 5,
footprintZ = 8,
object = [[antinuke_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 5,
footprintZ = 8,
object = [[debris4x4a.s3o]],
},
},
}
return lowerkeys({ staticantinuke = unitDef })
| gpl-2.0 |
ArchShaman/Zero-K | units/chicken_digger_b.lua | 5 | 3435 | unitDef = {
unitname = [[chicken_digger_b]],
name = [[Digger (burrowed)]],
description = [[Burrowing Scout/Raider]],
acceleration = 0.26,
activateWhenBuilt = false,
brakeRate = 0.205,
buildCostEnergy = 0,
buildCostMetal = 0,
builder = false,
buildPic = [[chicken_digger.png]],
buildTime = 40,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND BURROWED]],
customParams = {
statsname = "chicken_digger",
},
explodeAs = [[SMALL_UNITEX]],
fireState = 1,
floater = false,
footprintX = 2,
footprintZ = 2,
iconType = [[chicken]],
idleAutoHeal = 20,
idleTime = 300,
leaveTracks = false,
maxDamage = 180,
maxSlope = 72,
maxVelocity = 0.9,
maxWaterDepth = 15,
minCloakDistance = 75,
movementClass = [[TKBOT2]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB]],
objectName = [[chicken_digger_b.s3o]],
onoffable = true,
power = 40,
selfDestructAs = [[SMALL_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:emg_shells_l]],
[[custom:flashmuzzle1]],
[[custom:dirt]],
},
},
sightDistance = 0,
stealth = true,
trackOffset = 0,
trackStrength = 6,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 18,
turnRate = 806,
upright = false,
waterline = 8,
workerTime = 0,
weapons = {
{
def = [[WEAPON]],
mainDir = [[0 0 1]],
maxAngleDif = 120,
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
},
weaponDefs = {
WEAPON = {
name = [[Claws]],
alphaDecay = 0.1,
areaOfEffect = 8,
colormap = [[1 0.95 0.4 1 1 0.95 0.4 1 0 0 0 0.01 1 0.7 0.2 1]],
craterBoost = 0,
craterMult = 0,
damage = {
default = 80,
planes = 80,
subs = 4,
},
explosionGenerator = [[custom:EMG_HIT]],
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
intensity = 0.7,
interceptedByShieldType = 1,
noGap = false,
noSelfDamage = true,
range = 100,
reloadtime = 1.2,
rgbColor = [[1 0.95 0.4]],
separation = 1.5,
size = 1.75,
sizeDecay = 0,
soundHit = [[chickens/chickenbig2]],
soundStart = [[chickens/chicken]],
sprayAngle = 1180,
stages = 10,
targetborder = 1,
tolerance = 5000,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 500,
},
},
}
return lowerkeys({ chicken_digger_b = unitDef })
| gpl-2.0 |
galnegus/Glaskross | lib/sperm/loveframes/objects/imagebutton.lua | 3 | 7501 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2013 Kenny Shields --
--]]------------------------------------------------
-- imagebutton object
local newobject = loveframes.NewObject("imagebutton", "loveframes_object_imagebutton", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()
self.type = "imagebutton"
self.text = "Image Button"
self.width = 50
self.height = 50
self.internal = false
self.down = false
self.clickable = true
self.enabled = true
self.image = nil
self.OnClick = nil
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
self:CheckHover()
local hover = self.hover
local downobject = loveframes.downobject
local down = self.down
local parent = self.parent
local base = loveframes.base
local update = self.Update
if not hover then
self.down = false
else
if downobject == self then
self.down = true
end
end
if not down and downobject == self then
self.hover = true
end
-- move to parent if there is a parent
if parent ~= base then
self.x = self.parent.x + self.staticx
self.y = self.parent.y + self.staticy
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawImageButton or skins[defaultskin].DrawImageButton
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local hover = self.hover
if hover and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
self.down = true
loveframes.downobject = self
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local hover = self.hover
local down = self.down
local clickable = self.clickable
local enabled = self.enabled
local onclick = self.OnClick
if hover and down and clickable and button == "l" then
if enabled then
if onclick then
onclick(self, x, y)
end
end
end
self.down = false
end
--[[---------------------------------------------------------
- func: SetText(text)
- desc: sets the object's text
--]]---------------------------------------------------------
function newobject:SetText(text)
self.text = text
end
--[[---------------------------------------------------------
- func: GetText()
- desc: gets the object's text
--]]---------------------------------------------------------
function newobject:GetText()
return self.text
end
--[[---------------------------------------------------------
- func: SetClickable(bool)
- desc: sets whether the object can be clicked or not
--]]---------------------------------------------------------
function newobject:SetClickable(bool)
self.clickable = bool
end
--[[---------------------------------------------------------
- func: GetClickable(bool)
- desc: gets whether the object can be clicked or not
--]]---------------------------------------------------------
function newobject:GetClickable()
return self.clickable
end
--[[---------------------------------------------------------
- func: SetClickable(bool)
- desc: sets whether the object is enabled or not
--]]---------------------------------------------------------
function newobject:SetEnabled(bool)
self.enabled = bool
end
--[[---------------------------------------------------------
- func: GetEnabled()
- desc: gets whether the object is enabled or not
--]]---------------------------------------------------------
function newobject:GetEnabled()
return self.enabled
end
--[[---------------------------------------------------------
- func: SetImage(image)
- desc: sets the object's image
--]]---------------------------------------------------------
function newobject:SetImage(image)
if type(image) == "string" then
self.image = love.graphics.newImage(image)
else
self.image = image
end
end
--[[---------------------------------------------------------
- func: GetImage()
- desc: gets whether the object is enabled or not
--]]---------------------------------------------------------
function newobject:GetImage()
return self.image
end
--[[---------------------------------------------------------
- func: SizeToImage()
- desc: makes the object the same size as its image
--]]---------------------------------------------------------
function newobject:SizeToImage()
local image = self.image
if image then
self.width = image:getWidth()
self.height = image:getHeight()
end
end
--[[---------------------------------------------------------
- func: GetImageSize()
- desc: gets the size of the object's image
--]]---------------------------------------------------------
function newobject:GetImageSize()
local image = self.image
if image then
return image:getWidth(), image:getHeight()
end
end
--[[---------------------------------------------------------
- func: GetImageWidth()
- desc: gets the width of the object's image
--]]---------------------------------------------------------
function newobject:GetImageWidth()
local image = self.image
if image then
return image:getWidth()
end
end
--[[---------------------------------------------------------
- func: GetImageWidth()
- desc: gets the height of the object's image
--]]---------------------------------------------------------
function newobject:GetImageHeight()
local image = self.image
if image then
return image:getHeight()
end
end | mit |
sahilshah/openface | training/donkey.lua | 2 | 2989 | -- Source: https://github.com/facebook/fbcunn/blob/master/examples/imagenet/donkey.lua
--
-- Copyright (c) 2014, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
local gm = assert(require 'graphicsmagick')
paths.dofile('dataset.lua')
paths.dofile('util.lua')
ffi=require 'ffi'
-- This file contains the data-loading logic and details.
-- It is run by each data-loader thread.
------------------------------------------
-- a cache file of the training metadata (if doesnt exist, will be created)
local trainCache = paths.concat(opt.cache, 'trainCache.t7')
local testCache = paths.concat(opt.cache, 'testCache.t7')
-- Check for existence of opt.data
if not os.execute('cd ' .. opt.data) then
error(("could not chdir to '%s'"):format(opt.data))
end
local loadSize = {3, opt.imgDim, opt.imgDim}
local sampleSize = {3, opt.imgDim, opt.imgDim}
-- function to load the image, jitter it appropriately (random crops etc.)
local trainHook = function(self, path)
-- load image with size hints
local input = gm.Image():load(path, self.loadSize[3], self.loadSize[2])
input:size(self.sampleSize[3], self.sampleSize[2])
local out = input
-- do hflip with probability 0.5
if torch.uniform() > 0.5 then out:flop(); end
out = out:toTensor('float','RGB','DHW')
return out
end
if paths.filep(trainCache) then
print('Loading train metadata from cache')
trainLoader = torch.load(trainCache)
trainLoader.sampleHookTrain = trainHook
else
print('Creating train metadata')
trainLoader = dataLoader{
paths = {paths.concat(opt.data, 'train')},
loadSize = loadSize,
sampleSize = sampleSize,
split = 100,
verbose = true
}
torch.save(trainCache, trainLoader)
trainLoader.sampleHookTrain = trainHook
end
collectgarbage()
-- do some sanity checks on trainLoader
do
local class = trainLoader.imageClass
local nClasses = #trainLoader.classes
assert(class:max() <= nClasses, "class logic has error")
assert(class:min() >= 1, "class logic has error")
end
-- End of train loader section
--------------------------------------------------------------------------------
--[[ Section 2: Create a test data loader (testLoader), ]]--
if paths.filep(testCache) then
print('Loading test metadata from cache')
testLoader = torch.load(testCache)
else
print('Creating test metadata')
testLoader = dataLoader{
paths = {paths.concat(opt.data, 'val')},
loadSize = loadSize,
sampleSize = sampleSize,
-- split = 0,
split = 100,
verbose = true,
-- force consistent class indices between trainLoader and testLoader
forceClasses = trainLoader.classes
}
torch.save(testCache, testLoader)
end
collectgarbage()
-- End of test loader section
| apache-2.0 |
brahmi2/prosody-modules | mod_onhold/mod_onhold.lua | 32 | 2253 | -- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
-- Copyright (C) 2009 Jeff Mitchell
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local datamanager = require "util.datamanager";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local st = require "util.stanza";
local datetime = require "util.datetime";
local ipairs = ipairs;
local onhold_jids = module:get_option("onhold_jids") or {};
for _, jid in ipairs(onhold_jids) do onhold_jids[jid] = true; end
function process_message(event)
local session, stanza = event.origin, event.stanza;
local to = stanza.attr.to;
local from = jid_bare(stanza.attr.from);
local node, host;
local onhold_node, onhold_host;
if to then
node, host = jid_split(to)
else
node, host = session.username, session.host;
end
if onhold_jids[from] then
stanza.attr.stamp, stanza.attr.stamp_legacy = datetime.datetime(), datetime.legacy();
local result = datamanager.list_append(node, host, "onhold", st.preserialize(stanza));
stanza.attr.stamp, stanza.attr.stamp_legacy = nil, nil;
return true;
end
return nil;
end
module:hook("message/bare", process_message, 5);
module:hook("message/full", process_message, 5);
module:hook("presence/bare", function(event)
if event.origin.presence then return nil; end
local session = event.origin;
local node, host = session.username, session.host;
local from;
local de_stanza;
local data = datamanager.list_load(node, host, "onhold");
local newdata = {};
if not data then return nil; end
for _, stanza in ipairs(data) do
de_stanza = st.deserialize(stanza);
from = jid_bare(de_stanza.attr.from);
if not onhold_jids[from] then
de_stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = host, stamp = de_stanza.attr.stamp}):up(); -- XEP-0203
de_stanza:tag("x", {xmlns = "jabber:x:delay", from = host, stamp = de_stanza.attr.stamp_legacy}):up(); -- XEP-0091 (deprecated)
de_stanza.attr.stamp, de_stanza.attr.stamp_legacy = nil, nil;
session.send(de_stanza);
else
table.insert(newdata, stanza);
end
end
datamanager.list_store(node, host, "onhold", newdata);
return nil;
end, 5);
| mit |
ytjiang/redis | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
alarouche/premake-core | src/host/lua-5.1.4/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
haima-zju/redis-3.0-annotated | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
erwincoumans/premake-dev-iphone-xcode4 | tests/actions/xcode/test_xcode_dependencies.lua | 20 | 9645 | --
-- tests/actions/xcode/test_xcode_dependencies.lua
-- Automated test suite for Xcode project dependencies.
-- Copyright (c) 2009-2011 Jason Perkins and the Premake project
--
T.xcode3_deps = { }
local suite = T.xcode3_deps
local xcode = premake.xcode
---------------------------------------------------------------------------
-- Setup/Teardown
---------------------------------------------------------------------------
local sln, prj, prj2, tr
function suite.setup()
premake.action.set("xcode3")
xcode.used_ids = { } -- reset the list of generated IDs
sln, prj = test.createsolution()
links { "MyProject2" }
prj2 = test.createproject(sln)
kind "StaticLib"
configuration "Debug"
targetsuffix "-d"
end
local function prepare()
premake.bake.buildconfigs()
xcode.preparesolution(sln)
tr = xcode.buildprjtree(premake.solution.getproject(sln, 1))
end
---------------------------------------------------------------------------
-- PBXBuildFile tests
---------------------------------------------------------------------------
function suite.PBXBuildFile_ListsDependencyTargets_OnStaticLib()
prepare()
xcode.PBXBuildFile(tr)
test.capture [[
/* Begin PBXBuildFile section */
[libMyProject2-d.a:build] /* libMyProject2-d.a in Frameworks */ = {isa = PBXBuildFile; fileRef = [libMyProject2-d.a] /* libMyProject2-d.a */; };
/* End PBXBuildFile section */
]]
end
function suite.PBXBuildFile_ListsDependencyTargets_OnSharedLib()
kind "SharedLib"
prepare()
xcode.PBXBuildFile(tr)
test.capture [[
/* Begin PBXBuildFile section */
[libMyProject2-d.dylib:build] /* libMyProject2-d.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = [libMyProject2-d.dylib] /* libMyProject2-d.dylib */; };
/* End PBXBuildFile section */
]]
end
---------------------------------------------------------------------------
-- PBXContainerItemProxy tests
---------------------------------------------------------------------------
function suite.PBXContainerItemProxy_ListsProjectConfigs()
prepare()
xcode.PBXContainerItemProxy(tr)
test.capture [[
/* Begin PBXContainerItemProxy section */
[MyProject2.xcodeproj:prodprox] /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = [MyProject2.xcodeproj] /* MyProject2.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = [libMyProject2-d.a:product];
remoteInfo = "libMyProject2-d.a";
};
[MyProject2.xcodeproj:targprox] /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = [MyProject2.xcodeproj] /* MyProject2.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = [libMyProject2-d.a:target];
remoteInfo = "libMyProject2-d.a";
};
/* End PBXContainerItemProxy section */
]]
end
---------------------------------------------------------------------------
-- PBXFileReference tests
---------------------------------------------------------------------------
function suite.PBXFileReference_ListsDependencies()
prepare()
xcode.PBXFileReference(tr)
test.capture [[
/* Begin PBXFileReference section */
[MyProject:product] /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = "MyProject"; path = "MyProject"; sourceTree = BUILT_PRODUCTS_DIR; };
[MyProject2.xcodeproj] /* MyProject2.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = "MyProject2.xcodeproj"; path = "MyProject2.xcodeproj"; sourceTree = SOURCE_ROOT; };
/* End PBXFileReference section */
]]
end
function suite.PBXFileReference_UsesRelativePaths()
prj.location = "MyProject"
prj2.location = "MyProject2"
prepare()
xcode.PBXFileReference(tr)
test.capture [[
/* Begin PBXFileReference section */
[MyProject:product] /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = "MyProject"; path = "MyProject"; sourceTree = BUILT_PRODUCTS_DIR; };
[MyProject2.xcodeproj] /* MyProject2.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = "MyProject2.xcodeproj"; path = "../MyProject2/MyProject2.xcodeproj"; sourceTree = SOURCE_ROOT; };
/* End PBXFileReference section */
]]
end
---------------------------------------------------------------------------
-- PBXFrameworksBuildPhase tests
---------------------------------------------------------------------------
function suite.PBXFrameworksBuildPhase_ListsDependencies_OnStaticLib()
prepare()
xcode.PBXFrameworksBuildPhase(tr)
test.capture [[
/* Begin PBXFrameworksBuildPhase section */
[MyProject:fxs] /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
[libMyProject2-d.a:build] /* libMyProject2-d.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
]]
end
function suite.PBXFrameworksBuildPhase_ListsDependencies_OnSharedLib()
kind "SharedLib"
prepare()
xcode.PBXFrameworksBuildPhase(tr)
test.capture [[
/* Begin PBXFrameworksBuildPhase section */
[MyProject:fxs] /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
[libMyProject2-d.dylib:build] /* libMyProject2-d.dylib in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
]]
end
---------------------------------------------------------------------------
-- PBXGroup tests
---------------------------------------------------------------------------
function suite.PBXGroup_ListsDependencies()
prepare()
xcode.PBXGroup(tr)
test.capture [[
/* Begin PBXGroup section */
[MyProject] /* MyProject */ = {
isa = PBXGroup;
children = (
[Products] /* Products */,
[Projects] /* Projects */,
);
name = "MyProject";
sourceTree = "<group>";
};
[Products] /* Products */ = {
isa = PBXGroup;
children = (
[MyProject:product] /* MyProject */,
);
name = "Products";
sourceTree = "<group>";
};
[Projects] /* Projects */ = {
isa = PBXGroup;
children = (
[MyProject2.xcodeproj] /* MyProject2.xcodeproj */,
);
name = "Projects";
sourceTree = "<group>";
};
[MyProject2.xcodeproj:prodgrp] /* Products */ = {
isa = PBXGroup;
children = (
[libMyProject2-d.a] /* libMyProject2-d.a */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
]]
end
---------------------------------------------------------------------------
-- PBXNativeTarget tests
---------------------------------------------------------------------------
function suite.PBXNativeTarget_ListsDependencies()
prepare()
xcode.PBXNativeTarget(tr)
test.capture [[
/* Begin PBXNativeTarget section */
[MyProject:target] /* MyProject */ = {
isa = PBXNativeTarget;
buildConfigurationList = [MyProject:cfg] /* Build configuration list for PBXNativeTarget "MyProject" */;
buildPhases = (
[MyProject:rez] /* Resources */,
[MyProject:src] /* Sources */,
[MyProject:fxs] /* Frameworks */,
);
buildRules = (
);
dependencies = (
[MyProject2.xcodeproj:targdep] /* PBXTargetDependency */,
);
name = "MyProject";
productInstallPath = "$(HOME)/bin";
productName = "MyProject";
productReference = [MyProject:product] /* MyProject */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
]]
end
---------------------------------------------------------------------------
-- PBXProject tests
---------------------------------------------------------------------------
function suite.PBXProject_ListsDependencies()
prepare()
xcode.PBXProject(tr)
test.capture [[
/* Begin PBXProject section */
08FB7793FE84155DC02AAC07 /* Project object */ = {
isa = PBXProject;
buildConfigurationList = 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "MyProject" */;
compatibilityVersion = "Xcode 3.2";
hasScannedForEncodings = 1;
mainGroup = [MyProject] /* MyProject */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = [MyProject2.xcodeproj:prodgrp] /* Products */;
ProjectRef = [MyProject2.xcodeproj] /* MyProject2.xcodeproj */;
},
);
projectRoot = "";
targets = (
[MyProject:target] /* MyProject */,
);
};
/* End PBXProject section */
]]
end
---------------------------------------------------------------------------
-- PBXReferenceProxy tests
---------------------------------------------------------------------------
function suite.PBXReferenceProxy_ListsDependencies()
prepare()
xcode.PBXReferenceProxy(tr)
test.capture [[
/* Begin PBXReferenceProxy section */
[libMyProject2-d.a] /* libMyProject2-d.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libMyProject2-d.a";
remoteRef = [MyProject2.xcodeproj:prodprox] /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
]]
end
---------------------------------------------------------------------------
-- PBXTargetDependency tests
---------------------------------------------------------------------------
function suite.PBXTargetDependency_ListsDependencies()
prepare()
xcode.PBXTargetDependency(tr)
test.capture [[
/* Begin PBXTargetDependency section */
[MyProject2.xcodeproj:targdep] /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = "libMyProject2-d.a";
targetProxy = [MyProject2.xcodeproj:targprox] /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
]]
end
| bsd-3-clause |
KurdyMalloy/packages | net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/ruleconfig.lua | 82 | 4185 | -- ------ extra functions ------ --
function ruleCheck() -- determine if rule needs a protocol specified
local sourcePort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".src_port"))
local destPort = ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".dest_port"))
if sourcePort ~= "" or destPort ~= "" then -- ports configured
local protocol = ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".proto"))
if protocol == "" or protocol == "all" then -- no or improper protocol
error_protocol = 1
end
end
end
function ruleWarn() -- display warning message at the top of the page
if error_protocol == 1 then
return "<font color=\"ff0000\"><strong>WARNING: this rule is incorrectly configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>"
else
return ""
end
end
function cbiAddPolicy(field)
uci.cursor():foreach("mwan3", "policy",
function (section)
field:value(section[".name"])
end
)
end
function cbiAddProtocol(field)
local protocols = ut.trim(sys.exec("cat /etc/protocols | grep ' # ' | awk '{print $1}' | grep -vw -e 'ip' -e 'tcp' -e 'udp' -e 'icmp' -e 'esp' | grep -v 'ipv6' | sort | tr '\n' ' '"))
for p in string.gmatch(protocols, "%S+") do
field:value(p)
end
end
-- ------ rule configuration ------ --
dsp = require "luci.dispatcher"
sys = require "luci.sys"
ut = require "luci.util"
arg[1] = arg[1] or ""
error_protocol = 0
ruleCheck()
m5 = Map("mwan3", translate("MWAN Rule Configuration - ") .. arg[1],
translate(ruleWarn()))
m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "rule")
mwan_rule = m5:section(NamedSection, arg[1], "rule", "")
mwan_rule.addremove = false
mwan_rule.dynamic = false
src_ip = mwan_rule:option(Value, "src_ip", translate("Source address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
src_ip.datatype = ipaddr
src_port = mwan_rule:option(Value, "src_port", translate("Source port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
dest_ip = mwan_rule:option(Value, "dest_ip", translate("Destination address"),
translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes"))
dest_ip.datatype = ipaddr
dest_port = mwan_rule:option(Value, "dest_port", translate("Destination port"),
translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes"))
proto = mwan_rule:option(Value, "proto", translate("Protocol"),
translate("View the contents of /etc/protocols for protocol descriptions"))
proto.default = "all"
proto.rmempty = false
proto:value("all")
proto:value("ip")
proto:value("tcp")
proto:value("udp")
proto:value("icmp")
proto:value("esp")
cbiAddProtocol(proto)
sticky = mwan_rule:option(ListValue, "sticky", translate("Sticky"),
translate("Traffic from the same source IP address that previously matched this rule within the sticky timeout period will use the same WAN interface"))
sticky.default = "0"
sticky:value("1", translate("Yes"))
sticky:value("0", translate("No"))
timeout = mwan_rule:option(Value, "timeout", translate("Sticky timeout"),
translate("Seconds. Acceptable values: 1-1000000. Defaults to 600 if not set"))
timeout.datatype = "range(1, 1000000)"
ipset = mwan_rule:option(Value, "ipset", translate("IPset"),
translate("Name of IPset rule. Requires IPset rule in /etc/dnsmasq.conf (eg \"ipset=/youtube.com/youtube\")"))
use_policy = mwan_rule:option(Value, "use_policy", translate("Policy assigned"))
cbiAddPolicy(use_policy)
use_policy:value("unreachable", translate("unreachable (reject)"))
use_policy:value("blackhole", translate("blackhole (drop)"))
use_policy:value("default", translate("default (use main routing table)"))
-- ------ currently configured policies ------ --
mwan_policy = m5:section(TypedSection, "policy", translate("Currently Configured Policies"))
mwan_policy.addremove = false
mwan_policy.dynamic = false
mwan_policy.sortable = false
mwan_policy.template = "cbi/tblsection"
return m5
| gpl-2.0 |
jchuang1977/my_luci | applications/luci-mjpg-streamer/luasrc/model/cbi/mjpg-streamer.lua | 2 | 1432 | --[[
LuCI - Lua Configuration Interface - mjpg-streamer support
Script by oldoldstone@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local running=(luci.sys.call("pidof mjpg_streamer > /dev/null") == 0)
m=Map("mjpg-streamer",translate("MJPG Streamer"),translate("MJPG-streamer takes JPGs from Linux-UVC compatible webcams, filesystem or other input plugins and streams them as M-JPEG via HTTP to webbrowsers, VLC and other software."))
s = m:section(TypedSection, "mjpg-streamer", translate("Settings"))
s.anonymous = true
s:option(Flag, "enabled", translate("Enable"))
device = s:option(Value, "device", translate("Device"))
device.rmempty = false
for dev in nixio.fs.glob("/dev/video[0-9]") do
device:value(nixio.fs.basename(dev))
end
resolution = s:option(Value, "resolution", translate("Resolution"))
resolution.rmempty = false
fps = s:option(Value, "fps", translate("FPS"))
fps.rmempty = false
www = s:option(Value, "www", translate("Web folder"))
www.rmempty = false
port = s:option(Value, "port", translate("Port"))
port.rmempty = false
username=s:option(Value, "username", translate("User Name"))
password=s:option(Value, "password", translate("Password"))
password.password = true
return m
| apache-2.0 |
ArchShaman/Zero-K | units/shieldarty.lua | 4 | 3911 | unitDef = {
unitname = [[shieldarty]],
name = [[Racketeer]],
description = [[Disarming Artillery]],
acceleration = 0.25,
brakeRate = 0.75,
buildCostMetal = 350,
buildPic = [[SHIELDARTY.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
corpse = [[DEAD]],
customParams = {
},
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[walkerlrarty]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 780,
maxSlope = 36,
maxVelocity = 1.8,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT2]],
noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP UNARMED]],
objectName = [[dominator.s3o]],
script = [[shieldarty.lua]],
selfDestructAs = [[BIG_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:STORMMUZZLE]],
[[custom:STORMBACK]],
},
},
sightDistance = 325,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 1800,
upright = true,
weapons = {
{
def = [[EMP_ROCKET]],
onlyTargetCategory = [[FIXEDWING GUNSHIP SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
},
weaponDefs = {
EMP_ROCKET = {
name = [[Disarm Cruise Missile]],
areaOfEffect = 24,
cegTag = [[disarmtrail]],
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customParams = {
burst = Shared.BURST_RELIABLE,
disarmDamageMult = 1,
disarmDamageOnly = 1,
disarmTimer = 6, -- seconds
light_camera_height = 1500,
light_color = [[1 1 1]],
},
damage = {
default = 2500,
},
edgeEffectiveness = 0.4,
explosionGenerator = [[custom:WHITE_LIGHTNING_BOMB]],
fireStarter = 0,
flightTime = 6,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 2,
model = [[wep_merl.s3o]],
noSelfDamage = true,
range = 940,
reloadtime = 10,
smokeTrail = false,
soundHit = [[weapon/missile/vlaunch_emp_hit]],
soundHitVolume = 9.0,
soundStart = [[weapon/missile/missile_launch_high]],
soundStartVolume = 11.0,
startvelocity = 250,
--texture1 = [[spark]], --flare
texture3 = [[spark]], --flame
tolerance = 4000,
tracks = true,
turnRate = 38000,
weaponAcceleration = 275,
weaponTimer = 1.18,
weaponType = [[StarburstLauncher]],
weaponVelocity = 800,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[dominator_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ shieldarty = unitDef })
| gpl-2.0 |
spectras/keyleds | keyledsd/effects/whack-a-mole.lua | 1 | 3017 |
config = {
moleIntervalIncrement = .95,
moleLifetimeIncrement = .98,
startColor = keyleds.config.startColor or tocolor(.5, .5, 0),
endColor = keyleds.config.endColor or tocolor(1, 0, 0),
keys = keyleds.groups[keyleds.config.group] or keyleds.db
}
scoreKeys = {"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"}
scoreColors = {tocolor(0, 1, 0), tocolor(1, .8, 0), tocolor(1,0, 0)}
transparent = tocolor(0, 0, 0, 0)
-- Game cycle
function init()
buffer = RenderTarget:new()
initGame()
end
function initGame()
print("New Game")
moles = {}
successes, failures = 0, 0
moleInterval = 2000
nextMole = 1000
moleLifetime = 3000
buffer:fill(transparent)
renderScore(failures)
end
function renderScore(score)
local color
local baseColor = math.floor(score / #scoreKeys) + 1
local baseScore = score - (score % #scoreKeys)
for index, key in ipairs(scoreKeys) do
if index <= score - baseScore then
color = scoreColors[baseColor + 1]
else
color = scoreColors[baseColor]
end
buffer[key] = color
end
end
function handleSuccess()
successes = successes + 1
if failures > 0 then failures = failures - 1 end
moleInterval = 500 * (config.moleIntervalIncrement^math.sqrt(successes))
moleLifetime = 3000 * (config.moleLifetimeIncrement^math.sqrt(successes))
renderScore(failures)
print("score: ", successes)
end
function handleFailure()
failures = failures + 1
renderScore(failures)
end
-- Mole updates
function makeMole(lifetime)
local mole = {}
mole.key = config.keys[math.random(#config.keys)]
mole.age = 0
mole.lifetime = lifetime
return mole
end
function updateMoles(ms)
local mole, age, ratio
for index = #moles, 1, -1 do
mole = moles[index]
age = mole.age + ms
if age < mole.lifetime then
ratio = age / mole.lifetime
buffer[mole.key] = config.startColor * (1 - ratio) + config.endColor * ratio
mole.age = age
else
killMole(index)
handleFailure()
end
end
end
function killMole(index)
local mole = moles[index]
buffer[mole.key] = transparent
table.remove(moles, index)
end
-- Events
function render(ms, target)
updateMoles(ms)
if failures >= 2 * #scoreKeys then
initGame()
end
if nextMole > ms then
nextMole = nextMole - ms
else
local newMole = makeMole(moleLifetime)
table.insert(moles, newMole)
buffer[newMole.key] = config.startColor
nextMole = moleInterval
end
target:blend(buffer)
end
function onKeyEvent(key, isPress)
if not isPress then return end
for index, mole in ipairs(moles) do
if mole.key == key then
killMole(index)
handleSuccess()
return
end
end
handleFailure()
end
function onContextChange(context)
initGame()
end
| gpl-3.0 |
eigenl/tge | bin/scripts/raycaster/renderer.lua | 1 | 4194 | Renderer = {}
Renderer.castRays = function ()
local w = 80
local h = 25
for x = 0, w-1, 1 do
-- Calculate ray position and direction
local rayColumn = ((2 * x) / w) - 1
local rayPosX = Player.PosX
local rayPosY = Player.PosY
local rayDirX = Player.DirX + Player.PlaneX * rayColumn
local rayDirY = Player.DirY + Player.PlaneY * rayColumn
-- Which tile of the map are we in
local mapX, mapY = math.floor(rayPosX), math.floor(rayPosY)
-- Length of ray from current position to next x or y-side
local sideDistX, sideDistY
--Length of ray from one x or y-side to next x or y-side
local deltaDistX = math.sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX))
local deltaDistY = math.sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY))
local perpWallDist
-- What direction to step in x or y-direction (either +1 or -1)
local stepX, stepY
local wallHit = 0
local side
-- Calculate step and initial sideDist
if rayDirX < 0 then
stepX = -1
sideDistX = (rayPosX - mapX) * deltaDistX
else
stepX = 1
sideDistX = (mapX + 1.0 - rayPosX) * deltaDistX
end
if rayDirY < 0 then
stepY = -1
sideDistY = (rayPosY - mapY) * deltaDistY
else
stepY = 1
sideDistY = (mapY + 1.0 - rayPosY) * deltaDistY
end
-- Perform DDA
while wallHit == 0 do
-- jump to next map square, OR in x-direction, OR in y-direction
if sideDistX < sideDistY then
sideDistX = sideDistX + deltaDistX
mapX = mapX + stepX
side = 0
else
sideDistY = sideDistY + deltaDistY
mapY = mapY + stepY
side = 1
end
-- Check if ray has hit a wall
wallHit = Map.Data[mapX + 1][mapY + 1]
end
-- Calculate distance projected on camera direction (oblique distance will give fisheye effect!)
if side == 0 then
perpWallDist = math.abs((mapX - rayPosX + (1 - stepX) / 2) / rayDirX)
else
perpWallDist = math.abs((mapY - rayPosY + (1 - stepY) / 2) / rayDirY)
end
--[[
local wallX = fif(side == 1, rayPosX + ((mapY - rayPosY + (1 - stepY) / 2) / rayDirY) * rayDirX, rayPosY + ((mapX - rayPosX + (1 - stepX) / 2) / rayDirX) * rayDirY)
wallX = (wallX - math.floor(wallX))
]]--
-- Calculate height of line to draw on screen
local lineHeight = fif(perpWallDist == 0, 25, math.abs(math.floor(h / perpWallDist)))
-- Calculate lowest and highest row to fill in current column
local drawStart = ((-lineHeight / 2) + (h / 2))
local drawEnd = math.floor((lineHeight / 2) + (h / 2))
local halfBlock = math.floor(drawStart) == drawStart
drawStart = math.floor(drawStart)
if drawStart < 0 then drawStart = 0 end
if drawEnd >= h then drawEnd = h - 1 end
local wallColor
local bottomEdgeColor
if wallHit == 1 then
wallColor = fif(side == 0, Color.LightRed, Color.Red)
bottomEdgeColor = fif(side == 0, Color.Red, Color.Black)
elseif wallHit == 2 then
wallColor = fif(side == 0, Color.LightBlue, Color.Blue)
bottomEdgeColor = fif(side == 0, Color.Blue, Color.Black)
elseif wallHit == 3 then
wallColor = fif(side == 0, Color.Yellow, Color.Brown)
bottomEdgeColor = fif(side == 0, Color.Brown, Color.Black)
elseif wallHit == 4 then
wallColor = fif(side == 0, Color.LightGreen, Color.Green)
bottomEdgeColor = fif(side == 0, Color.Green, Color.Black)
elseif wallHit == 5 then
wallColor = fif(side == 0, Color.LightMagenta, Color.Magenta)
bottomEdgeColor = fif(side == 0, Color.Magenta, Color.Black)
end
for j = drawStart, drawEnd, 1 do
Screen.put({x = x, y = j, background = wallColor})
end
if halfBlock == true then
Screen.put({x = x, y = drawStart-1, value = "▄", color = wallColor, background = Map.CeilingColor})
Screen.put({x = x, y = drawEnd, value = "▀", color = bottomEdgeColor, background = Map.FloorColor})
else
Screen.put({x = x, y = drawEnd, value = "▄", color = bottomEdgeColor, background = wallColor})
end
end
end
Renderer.drawFloorsAndCeilings = function ()
Screen.fillRect({x = 0, y = 0, width = 80, height = 12, color = Map.CeilingColor})
Screen.fillRect({x = 0, y = 12, width = 80, height = 13, color = Map.FloorColor})
end
| mit |
erwincoumans/premake-dev-iphone-xcode4 | tests/test_vs2002_sln.lua | 14 | 1629 | --
-- tests/test_vs2002_sln.lua
-- Automated test suite for Visual Studio 2002 solution generation.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
T.vs2002_sln = { }
local suite = T.vs2002_sln
local sln2002 = premake.vstudio.sln2002
--
-- Configure a solution for testing
--
local sln
function suite.setup()
_ACTION = 'vs2002'
sln = solution "MySolution"
configurations { "Debug", "Release" }
platforms {}
prj = project "MyProject"
language "C++"
kind "ConsoleApp"
uuid "AE61726D-187C-E440-BD07-2556188A6565"
premake.bake.buildconfigs()
end
--
-- Make sure I've got the basic layout correct
--
function suite.BasicLayout()
sln2002.generate(sln)
test.capture [[
Microsoft Visual Studio Solution File, Format Version 7.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MyProject", "MyProject.vcproj", "{AE61726D-187C-E440-BD07-2556188A6565}"
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
ConfigName.0 = Debug
ConfigName.1 = Release
EndGlobalSection
GlobalSection(ProjectDependencies) = postSolution
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{AE61726D-187C-E440-BD07-2556188A6565}.Debug.ActiveCfg = Debug|Win32
{AE61726D-187C-E440-BD07-2556188A6565}.Debug.Build.0 = Debug|Win32
{AE61726D-187C-E440-BD07-2556188A6565}.Release.ActiveCfg = Release|Win32
{AE61726D-187C-E440-BD07-2556188A6565}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
]]
end
| bsd-3-clause |
mixflowtech/logsensor | lib/luajit/src/jit/bc.lua | 78 | 5620 | ----------------------------------------------------------------------------
-- LuaJIT bytecode listing module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module lists the bytecode of a Lua function. If it's loaded by -jbc
-- it hooks into the parser and lists all functions of a chunk as they
-- are parsed.
--
-- Example usage:
--
-- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)'
-- luajit -jbc=- foo.lua
-- luajit -jbc=foo.list foo.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_LISTFILE. The file is overwritten every time the module
-- is started.
--
-- This module can also be used programmatically:
--
-- local bc = require("jit.bc")
--
-- local function foo() print("hello") end
--
-- bc.dump(foo) --> -- BYTECODE -- [...]
-- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello"
--
-- local out = {
-- -- Do something with each line:
-- write = function(t, ...) io.write(...) end,
-- close = function(t) end,
-- flush = function(t) end,
-- }
-- bc.dump(foo, out)
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local bit = require("bit")
local sub, gsub, format = string.sub, string.gsub, string.format
local byte, band, shr = string.byte, bit.band, bit.rshift
local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck
local funcuvname = jutil.funcuvname
local bcnames = vmdef.bcnames
local stdout, stderr = io.stdout, io.stderr
------------------------------------------------------------------------------
local function ctlsub(c)
if c == "\n" then return "\\n"
elseif c == "\r" then return "\\r"
elseif c == "\t" then return "\\t"
else return format("\\%03d", byte(c))
end
end
-- Return one bytecode line.
local function bcline(func, pc, prefix)
local ins, m = funcbc(func, pc)
if not ins then return end
local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128)
local a = band(shr(ins, 8), 0xff)
local oidx = 6*band(ins, 0xff)
local op = sub(bcnames, oidx+1, oidx+6)
local s = format("%04d %s %-6s %3s ",
pc, prefix or " ", op, ma == 0 and "" or a)
local d = shr(ins, 16)
if mc == 13*128 then -- BCMjump
return format("%s=> %04d\n", s, pc+d-0x7fff)
end
if mb ~= 0 then
d = band(d, 0xff)
elseif mc == 0 then
return s.."\n"
end
local kc
if mc == 10*128 then -- BCMstr
kc = funck(func, -d-1)
kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub))
elseif mc == 9*128 then -- BCMnum
kc = funck(func, d)
if op == "TSETM " then kc = kc - 2^52 end
elseif mc == 12*128 then -- BCMfunc
local fi = funcinfo(funck(func, -d-1))
if fi.ffid then
kc = vmdef.ffnames[fi.ffid]
else
kc = fi.loc
end
elseif mc == 5*128 then -- BCMuv
kc = funcuvname(func, d)
end
if ma == 5 then -- BCMuv
local ka = funcuvname(func, a)
if kc then kc = ka.." ; "..kc else kc = ka end
end
if mb ~= 0 then
local b = shr(ins, 24)
if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end
return format("%s%3d %3d\n", s, b, d)
end
if kc then return format("%s%3d ; %s\n", s, d, kc) end
if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits
return format("%s%3d\n", s, d)
end
-- Collect branch targets of a function.
local function bctargets(func)
local target = {}
for pc=1,1000000000 do
local ins, m = funcbc(func, pc)
if not ins then break end
if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end
end
return target
end
-- Dump bytecode instructions of a function.
local function bcdump(func, out, all)
if not out then out = stdout end
local fi = funcinfo(func)
if all and fi.children then
for n=-1,-1000000000,-1 do
local k = funck(func, n)
if not k then break end
if type(k) == "proto" then bcdump(k, out, true) end
end
end
out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined))
local target = bctargets(func)
for pc=1,1000000000 do
local s = bcline(func, pc, target[pc] and "=>")
if not s then break end
out:write(s)
end
out:write("\n")
out:flush()
end
------------------------------------------------------------------------------
-- Active flag and output file handle.
local active, out
-- List handler.
local function h_list(func)
return bcdump(func, out)
end
-- Detach list handler.
local function bclistoff()
if active then
active = false
jit.attach(h_list)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach list handler.
local function bcliston(outfile)
if active then bclistoff() end
if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(h_list, "bc")
active = true
end
-- Public module functions.
return {
line = bcline,
dump = bcdump,
targets = bctargets,
on = bcliston,
off = bclistoff,
start = bcliston -- For -j command line option.
}
| apache-2.0 |
phi-psi/luci | applications/luci-firewall/luasrc/model/cbi/firewall/forwards.lua | 85 | 3942 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2012 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 ds = require "luci.dispatcher"
local ft = require "luci.tools.firewall"
m = Map("firewall", translate("Firewall - Port Forwards"),
translate("Port forwarding allows remote computers on the Internet to \
connect to a specific computer or service within the \
private LAN."))
--
-- Port Forwards
--
s = m:section(TypedSection, "redirect", translate("Port Forwards"))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
s.sortable = true
s.extedit = ds.build_url("admin/network/firewall/forwards/%s")
s.template_addremove = "firewall/cbi_addforward"
function s.create(self, section)
local n = m:formvalue("_newfwd.name")
local p = m:formvalue("_newfwd.proto")
local E = m:formvalue("_newfwd.extzone")
local e = m:formvalue("_newfwd.extport")
local I = m:formvalue("_newfwd.intzone")
local a = m:formvalue("_newfwd.intaddr")
local i = m:formvalue("_newfwd.intport")
if p == "other" or (p and a) then
created = TypedSection.create(self, section)
self.map:set(created, "target", "DNAT")
self.map:set(created, "src", E or "wan")
self.map:set(created, "dest", I or "lan")
self.map:set(created, "proto", (p ~= "other") and p or "all")
self.map:set(created, "src_dport", e)
self.map:set(created, "dest_ip", a)
self.map:set(created, "dest_port", i)
self.map:set(created, "name", n)
end
if p ~= "other" then
created = nil
end
end
function s.parse(self, ...)
TypedSection.parse(self, ...)
if created then
m.uci:save("firewall")
luci.http.redirect(ds.build_url(
"admin/network/firewall/redirect", created
))
end
end
function s.filter(self, sid)
return (self.map:get(sid, "target") ~= "SNAT")
end
ft.opt_name(s, DummyValue, translate("Name"))
local function forward_proto_txt(self, s)
return "%s-%s" %{
translate("IPv4"),
ft.fmt_proto(self.map:get(s, "proto"),
self.map:get(s, "icmp_type")) or "TCP+UDP"
}
end
local function forward_src_txt(self, s)
local z = ft.fmt_zone(self.map:get(s, "src"), translate("any zone"))
local a = ft.fmt_ip(self.map:get(s, "src_ip"), translate("any host"))
local p = ft.fmt_port(self.map:get(s, "src_port"))
local m = ft.fmt_mac(self.map:get(s, "src_mac"))
if p and m then
return translatef("From %s in %s with source %s and %s", a, z, p, m)
elseif p or m then
return translatef("From %s in %s with source %s", a, z, p or m)
else
return translatef("From %s in %s", a, z)
end
end
local function forward_via_txt(self, s)
local a = ft.fmt_ip(self.map:get(s, "src_dip"), translate("any router IP"))
local p = ft.fmt_port(self.map:get(s, "src_dport"))
if p then
return translatef("Via %s at %s", a, p)
else
return translatef("Via %s", a)
end
end
match = s:option(DummyValue, "match", translate("Match"))
match.rawhtml = true
match.width = "50%"
function match.cfgvalue(self, s)
return "<small>%s<br />%s<br />%s</small>" % {
forward_proto_txt(self, s),
forward_src_txt(self, s),
forward_via_txt(self, s)
}
end
dest = s:option(DummyValue, "dest", translate("Forward to"))
dest.rawhtml = true
dest.width = "40%"
function dest.cfgvalue(self, s)
local z = ft.fmt_zone(self.map:get(s, "dest"), translate("any zone"))
local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any host"))
local p = ft.fmt_port(self.map:get(s, "dest_port")) or
ft.fmt_port(self.map:get(s, "src_dport"))
if p then
return translatef("%s, %s in %s", a, p, z)
else
return translatef("%s in %s", a, z)
end
end
ft.opt_enabled(s, Flag, translate("Enable")).width = "1%"
return m
| apache-2.0 |
gevero/S4 | examples/Li_JOSA_14_2758_1997/ex1_normal.lua | 7 | 1262 | -- Extension of Example 1A in
-- Lifeng Li,
-- "New formulation of the Fourier modal method for crossed surface-relief gratings"
-- Journal of the Optical Society of America A, Vol. 14, No. 10, p. 2758 (1997)
-- This would be in Fig. 6
S = S4.NewSimulation()
S:SetLattice({2.5,0}, {0,2.5})
S:SetNumG(200)
S:AddMaterial("Dielectric", {2.25,0}) -- real and imag parts
S:AddMaterial("Vacuum", {1,0})
S:AddLayer('StuffAbove', 0 , 'Dielectric')
S:AddLayer('Slab', 1.0, 'Vacuum')
S:SetLayerPatternRectangle('Slab', 'Dielectric', {-1.25/2,-1.25/2}, 0, {1.25/2, 1.25/2})
S:SetLayerPatternRectangle('Slab', 'Dielectric', { 1.25/2, 1.25/2}, 0, {1.25/2, 1.25/2})
S:AddLayer('AirBelow', 0, 'Vacuum')
S:SetExcitationPlanewave(
{0,0}, -- incidence angles
{1,0}, -- s-polarization amplitude and phase (in degrees)
{0,0}) -- p-polarization amplitude and phase
S:UsePolarizationDecomposition()
S:UseNormalVectorBasis()
S:SetResolution(8)
--S:OutputLayerPatternRealization('Slab', 128, 128)
S:SetFrequency(1)
for ng = 41,401,40 do
S:SetNumG(ng)
power_inc = S:GetPoyntingFlux('StuffAbove', 0)
G = S:GetGList()
P = S:GetPoyntingFluxByOrder('AirBelow', 0)
actualg = S:GetNumG()
print(actualg, P[6][1]/power_inc) -- 1+4+1
end
| gpl-2.0 |
mixflowtech/logsensor | src/program/lisper/dev-env-docker/l2tp.lua | 28 | 7462 | #!snabb/src/snabb snsh
io.stdout:setvbuf'no'
io.stderr:setvbuf'no'
--L2TP IP-over-IPv6 tunnelling program for testing.
local function assert(v, ...)
if v then return v, ... end
error(tostring((...)), 2)
end
local ffi = require'ffi'
local S = require'syscall'
local C = ffi.C
local htons = require'syscall.helpers'.htons
local DEBUG = os.getenv'DEBUG'
local function hex(s)
return (s:gsub('(.)(.?)', function(c1, c2)
return c2 and #c2 == 1 and
string.format('%02x%02x ', c1:byte(), c2:byte()) or
string.format('%02x ', c1:byte())
end))
end
local digits = {}
for i=0,9 do digits[string.char(('0'):byte()+i)] = i end
for i=0,5 do digits[string.char(('a'):byte()+i)] = 10+i end
for i=0,5 do digits[string.char(('A'):byte()+i)] = 10+i end
local function parsehex(s)
return (s:gsub('[%s%:%.]*(%x)(%x)[%s%:%.]*', function(hi, lo)
local hi = digits[hi]
local lo = digits[lo]
return string.char(lo + hi * 16)
end))
end
local function open_tap(name)
local fd = assert(S.open('/dev/net/tun', 'rdwr, nonblock'))
local ifr = S.t.ifreq{flags = 'tap, no_pi', name = name}
assert(fd:ioctl('tunsetiff', ifr))
return fd
end
local function open_raw(name)
local fd = assert(S.socket('packet', 'raw, nonblock', htons(S.c.ETH_P.all)))
local ifr = S.t.ifreq{name = name}
assert(S.ioctl(fd, 'siocgifindex', ifr))
assert(S.bind(fd, S.t.sockaddr_ll{
ifindex = ifr.ivalue,
protocol = 'all'}))
return fd
end
local mtu = 1500
local rawbuf = ffi.new('uint8_t[?]', mtu)
local tapbuf = ffi.new('uint8_t[?]', mtu)
local function read_buf(buf, fd)
return buf, assert(S.read(fd, buf, mtu))
end
local function write(fd, s, len)
assert(S.write(fd, s, len))
end
local tapname, ethname, smac, dmac, sip, dip, sid, did = unpack(main.parameters)
if not (tapname and ethname and smac and dmac and sip and dip and sid and did) then
print('Usage: l2tp.lua TAP ETH SMAC DMAC SIP DIP SID DID')
print' TAP: the tunneled interface: will be created if not present.'
print' ETH: the tunneling interface: must have an IPv6 assigned.'
print' SMAC: the MAC address of ETH.'
print' DMAC: the MAC address of the gateway interface.'
print' SIP: the IPv6 of ETH (long form).'
print' DIP: the IPv6 of ETH at the other endpoint (long form).'
print' SID: session ID (hex)'
print' DID: peer session ID (hex)'
os.exit(1)
end
smac = parsehex(smac)
dmac = parsehex(dmac)
sip = parsehex(sip)
dip = parsehex(dip)
sid = parsehex(sid)
did = parsehex(did)
local tap = open_tap(tapname)
local raw = open_raw(ethname)
print('tap ', tapname)
print('raw ', ethname)
print('smac ', hex(smac))
print('dmac ', hex(dmac))
print('sip ', hex(sip))
print('dip ', hex(dip))
print('sid ', hex(sid))
print('did ', hex(did))
local l2tp_ct = ffi.typeof[[
struct {
// ethernet
char dmac[6];
char smac[6];
uint16_t ethertype;
// ipv6
uint32_t flow_id; // version, tc, flow_id
int8_t payload_length_hi;
int8_t payload_length_lo;
int8_t next_header;
uint8_t hop_limit;
char src_ip[16];
char dst_ip[16];
// l2tp
//uint32_t session_id;
char session_id[4];
char cookie[8];
} __attribute__((packed))
]]
local l2tp_ct_size = ffi.sizeof(l2tp_ct)
local l2tp_ctp = ffi.typeof('$*', l2tp_ct)
local function decap_l2tp_buf(buf, len)
if len < l2tp_ct_size then return nil, 'packet too small' end
local p = ffi.cast(l2tp_ctp, buf)
if p.ethertype ~= 0xdd86 then return nil, 'not ipv6' end
if p.next_header ~= 115 then return nil, 'not l2tp' end
local dmac = ffi.string(p.dmac, 6)
local smac = ffi.string(p.smac, 6)
local sip = ffi.string(p.src_ip, 16)
local dip = ffi.string(p.dst_ip, 16)
local sid = ffi.string(p.session_id, 4) --p.session_id
local payload_size = len - l2tp_ct_size
return smac, dmac, sip, dip, sid, l2tp_ct_size, payload_size
end
local function encap_l2tp_buf(smac, dmac, sip, dip, did, payload, payload_size, outbuf)
local p = ffi.cast(l2tp_ctp, outbuf)
ffi.copy(p.dmac, dmac)
ffi.copy(p.smac, smac)
p.ethertype = 0xdd86
p.flow_id = 0x60
local ipsz = payload_size + 12
p.payload_length_hi = bit.rshift(ipsz, 8)
p.payload_length_lo = bit.band(ipsz, 0xff)
p.next_header = 115
p.hop_limit = 64
ffi.copy(p.src_ip, sip)
ffi.copy(p.dst_ip, dip)
ffi.copy(p.session_id, did)
ffi.fill(p.cookie, 8)
ffi.copy(p + 1, payload, payload_size)
return outbuf, l2tp_ct_size + payload_size
end
--fast select ----------------------------------------------------------------
--select() is gruesome.
local band, bor, shl, shr = bit.band, bit.bor, bit.lshift, bit.rshift
local function getbit(b, bits)
return band(bits[shr(b, 3)], shl(1, band(b, 7))) ~= 0
end
local function setbit(b, bits)
bits[shr(b, 3)] = bor(bits[shr(b, 3)], shl(1, band(b, 7)))
end
ffi.cdef[[
typedef struct {
uint8_t bits[128]; // 1024 bits
} xfd_set;
int xselect(int, xfd_set*, xfd_set*, xfd_set*, void*) asm("select");
]]
local function FD_ISSET(d, set) return getbit(d, set.bits) end
local function FD_SET(d, set)
assert(d <= 1024)
setbit(d, set.bits)
end
local fds0 = ffi.new'xfd_set'
local fds = ffi.new'xfd_set'
local fds_size = ffi.sizeof(fds)
local rawfd = raw:getfd()
local tapfd = tap:getfd()
FD_SET(rawfd, fds0)
FD_SET(tapfd, fds0)
local maxfd = math.max(rawfd, tapfd) + 1
local EINTR = 4
local function can_read() --returns true if fd has data, false if timed out
ffi.copy(fds, fds0, fds_size)
::retry::
local ret = C.xselect(maxfd, fds, nil, nil, nil)
if ret == -1 then
if C.errno() == EINTR then goto retry end
error('select errno '..tostring(C.errno()))
end
return FD_ISSET(rawfd, fds), FD_ISSET(tapfd, fds)
end
------------------------------------------------------------------------------
while true do
local can_raw, can_tap = can_read()
if can_raw or can_tap then
if can_raw then
local buf, len = read_buf(rawbuf, raw)
local smac1, dmac1, sip1, dip1, did1, payload_offset, payload_size = decap_l2tp_buf(buf, len)
local accept = smac1
and smac1 == dmac
and dmac1 == smac
and dip1 == sip
and sip1 == dip
and did1 == sid
if DEBUG then
if accept or smac1 then
print('read', accept and 'accepted' or 'rejected')
print(' smac ', hex(smac1))
print(' dmac ', hex(dmac1))
print(' sip ', hex(sip1))
print(' dip ', hex(dip1))
print(' did ', hex(did1))
print(' # ', payload_size)
end
end
if accept then
write(tap, buf + payload_offset, payload_size)
end
end
if can_tap then
local payload, payload_size = read_buf(tapbuf, tap)
local frame, frame_size = encap_l2tp_buf(smac, dmac, sip, dip, did, payload, payload_size, rawbuf)
if DEBUG then
print('write')
print(' smac ', hex(smac))
print(' dmac ', hex(dmac))
print(' sip ', hex(sip))
print(' dip ', hex(dip))
print(' did ', hex(did))
print(' #in ', payload_size)
print(' #out ', frame_size)
end
write(raw, frame, frame_size)
end
end
end
tap:close()
raw:close()
| apache-2.0 |
mixflowtech/logsensor | lib/ljsyscall/syscall/linux/mips/constants.lua | 24 | 9285 | -- mips specific constants
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local h = require "syscall.helpers"
local octal = h.octal
local abi = require "syscall.abi"
local arch = {}
arch.SIG = {
HUP = 1,
INT = 2,
QUIT = 3,
ILL = 4,
TRAP = 5,
ABRT = 6,
EMT = 7,
FPE = 8,
KILL = 9,
BUS = 10,
SEGV = 11,
SYS = 12,
PIPE = 13,
ALRM = 14,
TERM = 15,
USR1 = 16,
USR2 = 17,
CHLD = 18,
PWR = 19,
WINCH = 20,
URG = 21,
IO = 22,
STOP = 23,
TSTP = 24,
CONT = 25,
TTIN = 26,
TTOU = 27,
VTALRM = 28,
PROF = 29,
XCPU = 30,
XFSZ = 31,
}
arch.SOCK = {
DGRAM = 1,
STREAM = 2,
RAW = 3,
RDM = 4,
SEQPACKET = 5,
DCCP = 6,
PACKET = 10,
CLOEXEC = octal('02000000'),
NONBLOCK = octal('0200'),
}
arch.MAP = {
SHARED = 0x001,
PRIVATE = 0x002,
TYPE = 0x00f,
FIXED = 0x010,
NORESERVE = 0x0400,
ANONYMOUS = 0x0800,
GROWSDOWN = 0x1000,
DENYWRITE = 0x2000,
EXECUTABLE = 0x4000,
LOCKED = 0x8000,
POPULATE = 0x10000,
NONBLOCK = 0x20000,
STACK = 0x40000,
HUGETLB = 0x80000,
}
local __O_SYNC = 0x4000
arch.O = {
RDONLY = 0x0000,
WRONLY = 0x0001,
RDWR = 0x0002,
ACCMODE = 0x0003,
APPEND = 0x0008,
DSYNC = 0x0010,
NONBLOCK = 0x0080,
CREAT = 0x0100,
TRUNC = 0x0200,
EXCL = 0x0400,
NOCTTY = 0x0800,
LARGEFILE= 0x2000,
DIRECT = 0x8000,
DIRECTORY= 0x10000,
NOFOLLOW = 0x20000,
NOATIME = 0x40000,
CLOEXEC = octal '02000000',
}
arch.O_SYNC = __O_SYNC + arch.O.DSYNC -- compatibility, see notes in header, we do not expose __O_SYNC TODO check if this is best way
arch.TFD = {
CLOEXEC = octal '02000000',
NONBLOCK = octal '00000200',
}
arch.E = {
PERM = 1,
NOENT = 2,
SRCH = 3,
INTR = 4,
IO = 5,
NXIO = 6,
["2BIG"] = 7,
NOEXEC = 8,
BADF = 9,
CHILD = 10,
AGAIN = 11,
NOMEM = 12,
ACCES = 13,
FAULT = 14,
NOTBLK = 15,
BUSY = 16,
EXIST = 17,
XDEV = 18,
NODEV = 19,
NOTDIR = 20,
ISDIR = 21,
INVAL = 22,
NFILE = 23,
MFILE = 24,
NOTTY = 25,
TXTBSY = 26,
FBIG = 27,
NOSPC = 28,
SPIPE = 29,
ROFS = 30,
MLINK = 31,
PIPE = 32,
DOM = 33,
RANGE = 34,
NOMSG = 35,
IDRM = 36,
CHRNG = 37,
L2NSYNC = 38,
L3HLT = 39,
L3RST = 40,
LNRNG = 41,
UNATCH = 42,
NOCSI = 43,
L2HLT = 44,
DEADLK = 45,
NOLCK = 46,
BADE = 50,
BADR = 51,
XFULL = 52,
NOANO = 53,
BADRQC = 54,
BADSLT = 55,
DEADLOCK = 56,
BFONT = 59,
NOSTR = 60,
NODATA = 61,
TIME = 62,
NOSR = 63,
NONET = 64,
NOPKG = 65,
REMOTE = 66,
NOLINK = 67,
ADV = 68,
SRMNT = 69,
COMM = 70,
PROTO = 71,
DOTDOT = 73,
MULTIHOP = 74,
BADMSG = 77,
NAMETOOLONG = 78,
OVERFLOW = 79,
NOTUNIQ = 80,
BADFD = 81,
REMCHG = 82,
LIBACC = 83,
LIBBAD = 84,
LIBSCN = 85,
LIBMAX = 86,
LIBEXEC = 87,
ILSEQ = 88,
NOSYS = 89,
LOOP = 90,
RESTART = 91,
STRPIPE = 92,
NOTEMPTY = 93,
USERS = 94,
NOTSOCK = 95,
DESTADDRREQ = 96,
MSGSIZE = 97,
PROTOTYPE = 98,
NOPROTOOPT = 99,
PROTONOSUPPORT= 120,
SOCKTNOSUPPORT= 121,
OPNOTSUPP = 122,
PFNOSUPPORT = 123,
AFNOSUPPORT = 124,
ADDRINUSE = 125,
ADDRNOTAVAIL = 126,
NETDOWN = 127,
NETUNREACH = 128,
NETRESET = 129,
CONNABORTED = 130,
CONNRESET = 131,
NOBUFS = 132,
ISCONN = 133,
NOTCONN = 134,
UCLEAN = 135,
NOTNAM = 137,
NAVAIL = 138,
ISNAM = 139,
REMOTEIO = 140,
INIT = 141,
REMDEV = 142,
SHUTDOWN = 143,
TOOMANYREFS = 144,
TIMEDOUT = 145,
CONNREFUSED = 146,
HOSTDOWN = 147,
HOSTUNREACH = 148,
ALREADY = 149,
INPROGRESS = 150,
STALE = 151,
CANCELED = 158,
NOMEDIUM = 159,
MEDIUMTYPE = 160,
NOKEY = 161,
KEYEXPIRED = 162,
KEYREVOKED = 163,
KEYREJECTED = 164,
OWNERDEAD = 165,
NOTRECOVERABLE= 166,
RFKILL = 167,
HWPOISON = 168,
DQUOT = 1133,
}
arch.SFD = {
CLOEXEC = octal "02000000",
NONBLOCK = octal "00000200",
}
arch.IN_INIT = {
CLOEXEC = octal("02000000"),
NONBLOCK = octal("00000200"),
}
arch.SA = {
ONSTACK = 0x08000000,
RESETHAND = 0x80000000,
RESTART = 0x10000000,
SIGINFO = 0x00000008,
NODEFER = 0x40000000,
NOCLDWAIT = 0x00010000,
NOCLDSTOP = 0x00000001,
}
arch.SIGPM = {
BLOCK = 1,
UNBLOCK = 2,
SETMASK = 3,
}
arch.SI = {
ASYNCNL = -60,
TKILL = -6,
SIGIO = -5,
MESGQ = -4,
TIMER = -3,
ASYNCIO = -2,
QUEUE = -1,
USER = 0,
KERNEL = 0x80,
}
arch.POLL = {
IN = 0x001,
PRI = 0x002,
OUT = 0x004,
ERR = 0x008,
HUP = 0x010,
NVAL = 0x020,
RDNORM = 0x040,
RDBAND = 0x080,
WRBAND = 0x100,
MSG = 0x400,
REMOVE = 0x1000,
RDHUP = 0x2000,
}
arch.POLL.WRNORM = arch.POLL.OUT
arch.RLIMIT = {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
NOFILE = 5,
AS = 6,
RSS = 7,
NPROC = 8,
MEMLOCK = 9,
LOCKS = 10,
SIGPENDING = 11,
MSGQUEUE = 12,
NICE = 13,
RTPRIO = 14,
RTTIME = 15,
}
-- note RLIM64_INFINITY looks like it varies by MIPS ABI but this is a glibc bug
arch.SO = {
DEBUG = 0x0001,
REUSEADDR = 0x0004,
KEEPALIVE = 0x0008,
DONTROUTE = 0x0010,
BROADCAST = 0x0020,
LINGER = 0x0080,
OOBINLINE = 0x0100,
--REUSEPORT = 0x0200, -- not in kernel headers, although MIPS has had for longer
TYPE = 0x1008,
ERROR = 0x1007,
SNDBUF = 0x1001,
RCVBUF = 0x1002,
SNDLOWAT = 0x1003,
RCVLOWAT = 0x1004,
SNDTIMEO = 0x1005,
RCVTIMEO = 0x1006,
ACCEPTCONN = 0x1009,
PROTOCOL = 0x1028,
DOMAIN = 0x1029,
NO_CHECK = 11,
PRIORITY = 12,
BSDCOMPAT = 14,
PASSCRED = 17,
PEERCRED = 18,
SECURITY_AUTHENTICATION = 22,
SECURITY_ENCRYPTION_TRANSPORT = 23,
SECURITY_ENCRYPTION_NETWORK = 24,
BINDTODEVICE = 25,
ATTACH_FILTER = 26,
DETACH_FILTER = 27,
PEERNAME = 28,
TIMESTAMP = 29,
PEERSEC = 30,
SNDBUFFORCE = 31,
RCVBUFFORCE = 33,
PASSSEC = 34,
TIMESTAMPNS = 35,
MARK = 36,
TIMESTAMPING = 37,
RXQ_OVFL = 40,
WIFI_STATUS = 41,
PEEK_OFF = 42,
NOFCS = 43,
--LOCK_FILTER = 44, -- neither in our kernel headers
--SELECT_ERR_QUEUE = 45,
}
arch.SO.STYLE = arch.SO.TYPE
arch.SOLSOCKET = 0xffff -- remainder of SOL values same
arch.F = {
DUPFD = 0,
GETFD = 1,
SETFD = 2,
GETFL = 3,
SETFL = 4,
GETLK = 14,
SETLK = 6,
SETLKW = 7,
SETOWN = 24,
GETOWN = 23,
SETSIG = 10,
GETSIG = 11,
GETLK64 = 33,
SETLK64 = 34,
SETLKW64 = 35,
SETOWN_EX = 15,
GETOWN_EX = 16,
SETLEASE = 1024,
GETLEASE = 1025,
NOTIFY = 1026,
SETPIPE_SZ = 1031,
GETPIPE_SZ = 1032,
DUPFD_CLOEXEC = 1030,
}
arch.TIOCM = {
LE = 0x001,
DTR = 0x002,
RTS = 0x004,
ST = 0x010,
SR = 0x020,
CTS = 0x040,
CAR = 0x100,
RNG = 0x200,
DSR = 0x400,
OUT1 = 0x2000,
OUT2 = 0x4000,
LOOP = 0x8000,
}
arch.CC = {
VINTR = 0,
VQUIT = 1,
VERASE = 2,
VKILL = 3,
VMIN = 4,
VTIME = 5,
VEOL2 = 6,
VSWTC = 7,
VSTART = 8,
VSTOP = 9,
VSUSP = 10,
-- VDSUSP not supported
VREPRINT = 12,
VDISCARD = 13,
VWERASE = 14,
VLNEXT = 15,
VEOF = 16,
VEOL = 17,
}
arch.CC.VSWTCH = arch.CC.VSWTC
arch.LFLAG = {
ISIG = octal '0000001',
ICANON = octal '0000002',
XCASE = octal '0000004',
ECHO = octal '0000010',
ECHOE = octal '0000020',
ECHOK = octal '0000040',
ECHONL = octal '0000100',
NOFLSH = octal '0000200',
IEXTEN = octal '0000400',
ECHOCTL = octal '0001000',
ECHOPRT = octal '0002000',
ECHOKE = octal '0004000',
FLUSHO = octal '0020000',
PENDIN = octal '0040000',
TOSTOP = octal '0100000',
EXTPROC = octal '0200000',
}
arch.LFLAG.ITOSTOP = arch.LFLAG.TOSTOP
return arch
| apache-2.0 |
danielg4/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/nat_traffic.lua | 79 | 1251 | local function scrape()
-- documetation about nf_conntrack:
-- https://www.frozentux.net/iptables-tutorial/chunkyhtml/x1309.html
nat_metric = metric("node_nat_traffic", "gauge" )
for e in io.lines("/proc/net/nf_conntrack") do
-- output(string.format("%s\n",e ))
local fields = space_split(e)
local src, dest, bytes;
bytes = 0;
for _, field in ipairs(fields) do
if src == nil and string.match(field, '^src') then
src = string.match(field,"src=([^ ]+)");
elseif dest == nil and string.match(field, '^dst') then
dest = string.match(field,"dst=([^ ]+)");
elseif string.match(field, '^bytes') then
local b = string.match(field, "bytes=([^ ]+)");
bytes = bytes + b;
-- output(string.format("\t%d %s",ii,field ));
end
end
-- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) .- bytes=([^ ]+)");
-- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) sport=[^ ]+ dport=[^ ]+ packets=[^ ]+ bytes=([^ ]+)")
local labels = { src = src, dest = dest }
-- output(string.format("src=|%s| dest=|%s| bytes=|%s|", src, dest, bytes ))
nat_metric(labels, bytes )
end
end
return { scrape = scrape }
| gpl-2.0 |
terry2012/codereason | scripts/valu/and.lua | 3 | 1376 | function onPre(v)
--say that we could have a 32-bit value in any general purpose register
regClass = {}
regClass[CLASS] = GenericRegister
regClass[VALUE] = 21
regClass[WIDTH] = 32
vee.setregclass(v, regClass)
--and then say that we have some other 32-bit value in any general purpose
--register
regClass = {}
regClass[CLASS] = GenericRegister
regClass[VALUE] = 18
regClass[WIDTH] = 32
vee.setregclass(v, regClass)
end
function checkReg(v, reg, width, val)
tmp = vee.getreg(v, reg, width)
if tmp ~= nil then
if tmp == val then
return true
end
end
return false
end
function onPost(v)
--check and see if we branched to the value we wanted to branch to
eip = vee.getreg(v, EIP, 32)
if eip == nil then
return false
end
if vee.getexit(v) == Return then
--if we branched where we wanted to, then check and see if any GPR
--contains the result of 0x1 + 0x2
if checkReg(v, EAX, 32, 16) or
checkReg(v, EBX, 32, 16) or
checkReg(v, ECX, 32, 16) or
checkReg(v, EDX, 32, 16) or
checkReg(v, ESI, 32, 16) or
checkReg(v, EDI, 32, 16) or
checkReg(v, EBP, 32, 16) then
return true
end
end
return false
end
vee.register(onPre, onPost)
| mit |
ArchShaman/Zero-K | units/factoryamph.lua | 3 | 2331 | unitDef = {
unitname = [[factoryamph]],
name = [[Amphbot Factory]],
description = [[Produces Amphibious Bots, Builds at 10 m/s]],
buildCostMetal = Shared.FACTORY_COST,
builder = true,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 10,
buildingGroundDecalSizeY = 10,
buildingGroundDecalType = [[factoryamph_aoplane.dds]],
buildoptions = {
[[amphcon]],
[[amphraid]],
[[amphimpulse]],
[[amphfloater]],
[[amphriot]],
[[amphassault]],
[[amphlaunch]],
[[amphaa]],
[[amphbomb]],
[[amphtele]],
},
buildPic = [[factoryamph.png]],
canMove = true,
canPatrol = true,
category = [[UNARMED SINK]],
collisionVolumeOffsets = [[0 0 -16]],
collisionVolumeScales = [[104 70 36]],
collisionVolumeType = [[box]],
selectionVolumeOffsets = [[0 0 14]],
selectionVolumeScales = [[104 70 96]],
selectionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
modelradius = [[100]],
aimposoffset = [[0 0 -26]],
midposoffset = [[0 0 -10]],
sortName = [[8]],
solid_factory = [[3]],
default_spacing = 8,
unstick_help = 1,
},
energyUse = 0,
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 7,
footprintZ = 7,
iconType = [[facamph]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 4000,
maxSlope = 15,
minCloakDistance = 150,
moveState = 1,
noAutoFire = false,
objectName = [[factory2.s3o]],
script = "factoryamph.lua",
selfDestructAs = [[LARGE_BUILDINGEX]],
showNanoSpray = false,
sightDistance = 273,
useBuildingGroundDecal = true,
workerTime = Shared.FACTORY_BUILDPOWER,
yardMap = [[ooooooo ooooooo ooooooo ccccccc ccccccc ccccccc ccccccc]],
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 7,
footprintZ = 7,
object = [[FACTORY2_DEAD.s3o]],
},
HEAP = {
blocking = false,
footprintX = 7,
footprintZ = 7,
object = [[debris4x4c.s3o]],
},
},
}
return lowerkeys({ factoryamph = unitDef })
| gpl-2.0 |
atatsu/strugglebus | genwiki.lua | 1 | 1338 | package.path = package.path .. ";" .. "./mtmmo/?.lua"
local nodevalues = require("nodevalues")
local constants = require("constants")
local nodes = {}
for k, v in pairs(nodevalues) do
local mod_node = k
local category, exp = unpack(v)
category = constants.SKILLS[category]
local found, _, modname, nodename = mod_node:find("^([^%s]+):([^%s]+)$")
if nodes[category] == nil then
nodes[category] = {}
end
if nodes[category][modname] == nil then
nodes[category][modname] = {}
end
nodes[category][modname][nodename] = exp
end
local sort = function(t)
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
table.sort(keys)
local i = 0
local iter = function()
i = i + 1
if keys[i] == nil then return nil
else return keys[i], t[keys[i]]
end
end
return iter
end
local output = ""
for category, modnodes in sort(nodes) do
output = output .. "##" .. category .. "\n"
for modname, nodes in sort(modnodes) do
output = output .. "###" .. modname .. "\n"
for nodename, exp in sort(nodes) do
output = output .. "`" .. nodename .. "`" .. " = " .. "`" .. exp .. "`" .. "\n\n"
end
end
end
local file = io.open("./wiki/Node-Values.md", "w")
file:write(output)
file:close()
| bsd-2-clause |
SawyerHood/mal | lua/step5_tco.lua | 12 | 3143 | #!/usr/bin/env lua
local table = require('table')
local readline = require('readline')
local utils = require('utils')
local types = require('types')
local reader = require('reader')
local printer = require('printer')
local Env = require('env')
local core = require('core')
local List, Vector, HashMap = types.List, types.Vector, types.HashMap
-- read
function READ(str)
return reader.read_str(str)
end
-- eval
function eval_ast(ast, env)
if types._symbol_Q(ast) then
return env:get(ast)
elseif types._list_Q(ast) then
return List:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._vector_Q(ast) then
return Vector:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._hash_map_Q(ast) then
local new_hm = {}
for k,v in pairs(ast) do
new_hm[EVAL(k, env)] = EVAL(v, env)
end
return HashMap:new(new_hm)
else
return ast
end
end
function EVAL(ast, env)
while true do
--print("EVAL: "..printer._pr_str(ast,true))
if not types._list_Q(ast) then return eval_ast(ast, env) end
local a0,a1,a2,a3 = ast[1], ast[2],ast[3],ast[4]
if not a0 then return ast end
local a0sym = types._symbol_Q(a0) and a0.val or ""
if 'def!' == a0sym then
return env:set(a1, EVAL(a2, env))
elseif 'let*' == a0sym then
local let_env = Env:new(env)
for i = 1,#a1,2 do
let_env:set(a1[i], EVAL(a1[i+1], let_env))
end
env = let_env
ast = a2 -- TCO
elseif 'do' == a0sym then
local el = eval_ast(ast:slice(2,#ast-1), env)
ast = ast[#ast] -- TCO
elseif 'if' == a0sym then
local cond = EVAL(a1, env)
if cond == types.Nil or cond == false then
if a3 then ast = a3 else return types.Nil end -- TCO
else
ast = a2 -- TCO
end
elseif 'fn*' == a0sym then
return types.MalFunc:new(function(...)
return EVAL(a2, Env:new(env, a1, arg))
end, a2, env, a1)
else
local args = eval_ast(ast, env)
local f = table.remove(args, 1)
if types._malfunc_Q(f) then
ast = f.ast
env = Env:new(f.env, f.params, args) -- TCO
else
return f(unpack(args))
end
end
end
end
-- print
function PRINT(exp)
return printer._pr_str(exp, true)
end
-- repl
local repl_env = Env:new()
function rep(str)
return PRINT(EVAL(READ(str),repl_env))
end
-- core.lua: defined using Lua
for k,v in pairs(core.ns) do
repl_env:set(types.Symbol:new(k), v)
end
-- core.mal: defined using mal
rep("(def! not (fn* (a) (if a false true)))")
if #arg > 0 and arg[1] == "--raw" then
readline.raw = true
end
while true do
line = readline.readline("user> ")
if not line then break end
xpcall(function()
print(rep(line))
end, function(exc)
if exc then
if types._malexception_Q(exc) then
exc = printer._pr_str(exc.val, true)
end
print("Error: " .. exc)
print(debug.traceback())
end
end)
end
| mpl-2.0 |
dangersos/fffff | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
amirquick/quick | plugins/ress.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.