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 |
|---|---|---|---|---|---|
mtroyka/Zero-K | LuaRules/Gadgets/game_resign.lua | 12 | 1334 | function gadget:GetInfo() return {
name = "Resign Gadget",
desc = "Resign stuff",
author = "KingRaptor",
date = "2012.5.1",
license = "Public domain",
layer = 0,
enabled = true,
} end
if (not gadgetHandler:IsSyncedCode()) then return end
local spGetPlayerInfo = Spring.GetPlayerInfo
local spKillTeam = Spring.KillTeam
local spSetTeamRulesParam = Spring.SetTeamRulesParam
local spGetPlayerList = Spring.GetPlayerList
function gadget:RecvLuaMsg (msg, senderID)
if msg == "forceresign" then
local team = select(4, spGetPlayerInfo(senderID))
spKillTeam(team)
spSetTeamRulesParam(team, "WasKilled", 1)
end
end
function gadget:GotChatMsg (msg, senderID)
if (string.find(msg, "resignteam") == 1) then
local allowed = false
if (senderID == 255) then -- Springie
allowed = true
else
local playerkeys = select (10, spGetPlayerInfo(senderID))
if (playerkeys and playerkeys.admin and (playerkeys.admin == "1")) then
allowed = true
end
end
if not allowed then return end
local target = string.sub(msg, 12)
local people = spGetPlayerList()
for i = 1, #people do
local personID = people[i]
local nick, _, _, teamID = spGetPlayerInfo(personID)
if (target == nick) then
spKillTeam (teamID)
spSetTeamRulesParam (teamID, "WasKilled", 1)
return
end
end
end
end
| gpl-2.0 |
thedraked/darkstar | scripts/zones/Western_Adoulin/npcs/Preterig.lua | 14 | 1184 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Preterig
-- Type: Shop NPC
-- @zone 256
-- @pos 6 0 -53 256
-----------------------------------
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Standard shop
player:showText(npc, PRETERIG_SHOP_TEXT);
local stock =
{
0x1147, 300, -- Apple Juice
0x1738, 125, -- Frontier Soda
0x1145, 1560, -- Melon Pie
0x1146, 200, -- Orange Juice
}
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
alalazo/wesnoth | data/ai/micro_ais/cas/ca_wolves_multipacks_functions.lua | 4 | 5523 | local H = wesnoth.require "helper"
local W = H.set_wml_action_metatable {}
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
local M = wesnoth.map
local wolves_multipacks_functions = {}
function wolves_multipacks_functions.clear_label(x, y)
W.label{ x = x, y = y, text = "" }
end
function wolves_multipacks_functions.put_label(x, y, text)
-- For displaying the wolf pack number underneath each wolf
-- Only use gray for now, but easily expandable to add a color option
text = "<span color='#c0c0c0'>" .. text .. "</span>"
W.label{ x = x, y = y, text = text }
end
function wolves_multipacks_functions.assign_packs(cfg)
-- Assign the pack numbers to each wolf. Keeps numbers of existing packs
-- (unless pack size is down to one). Pack number is stored in wolf unit variables
-- Also returns a table with the packs (locations and id's of each wolf in a pack)
local pack_size = cfg.pack_size or 3
local wolves = wesnoth.get_units { side = wesnoth.current.side, type = cfg.type or "Wolf" }
local packs = {}
-- Find wolves that already have a pack number assigned
for _,w in ipairs(wolves) do
local pack = MAIUV.get_mai_unit_variables(w, cfg.ai_id, "pack_number")
if pack then
if (not packs[pack]) then packs[pack] = {} end
table.insert(packs[pack], { x = w.x, y = w.y, id = w.id })
end
end
-- Remove packs of one
-- Do not change numbers of existing packs -> pack numbers might not be consecutive afterward
for pack_number,pack in pairs(packs) do
if (#pack == 1) then
local wolf = wesnoth.get_unit(pack[1].x, pack[1].y)
MAIUV.delete_mai_unit_variables(wolf, cfg.ai_id)
packs[pack_number] = nil
end
end
-- Find wolves that are not in a pack (new ones or those removed above)
local nopack_wolves = {}
for _,w in ipairs(wolves) do
local pack_number = MAIUV.get_mai_unit_variables(w, cfg.ai_id, "pack_number")
if (not pack_number) then
table.insert(nopack_wolves, w)
end
end
-- Now assign the nopack wolves to packs
-- First, go through packs that have less than pack_size members
for pack_number,pack in pairs(packs) do
if (#pack < pack_size) then
local min_dist, best_wolf, best_ind = 9e99
for ind,wolf in ipairs(nopack_wolves) do
-- Criterion is distance from the first two wolves of the pack
local dist1 = M.distance_between(wolf.x, wolf.y, pack[1].x, pack[1].y)
local dist2 = M.distance_between(wolf.x, wolf.y, pack[2].x, pack[2].y)
if (dist1 + dist2 < min_dist) then
min_dist = dist1 + dist2
best_wolf, best_ind = wolf, ind
end
end
if best_wolf then
table.insert(packs[pack_number], { x = best_wolf.x, y = best_wolf.y, id = best_wolf.id })
MAIUV.set_mai_unit_variables(best_wolf, cfg.ai_id, { pack_number = pack_number })
table.remove(nopack_wolves, best_ind)
end
end
end
-- Second, group remaining single wolves
-- At the beginning of the scenario, this means all wolves
while (#nopack_wolves > 0) do
-- Find the first available pack number
new_pack_number = 1
while packs[new_pack_number] do new_pack_number = new_pack_number + 1 end
-- If there are <=pack_size wolves left, that's the pack
if (#nopack_wolves <= pack_size) then
packs[new_pack_number] = {}
for _,w in ipairs(nopack_wolves) do
table.insert(packs[new_pack_number], { x = w.x, y = w.y, id = w.id })
MAIUV.set_mai_unit_variables(w, cfg.ai_id, { pack_number = new_pack_number })
end
break
end
-- If more than pack_size wolves left, find those that are closest together
-- They form the next pack
local new_pack_wolves = {}
while (#new_pack_wolves < pack_size) do
local min_dist, best_wolf, best_wolf_ind = 9e99
for ind,nopack_wolf in ipairs(nopack_wolves) do
local dist = 0
for _,pack_wolf in ipairs(new_pack_wolves) do
dist = dist + M.distance_between(nopack_wolf.x, nopack_wolf.y, pack_wolf.x, pack_wolf.y)
end
if dist < min_dist then
min_dist, best_wolf, best_wolf_ind = dist, nopack_wolf, ind
end
end
table.insert(new_pack_wolves, best_wolf)
table.remove(nopack_wolves, best_wolf_ind)
end
-- Now insert the best pack into that 'packs' array
packs[new_pack_number] = {}
for ind = 1,pack_size do
table.insert(
packs[new_pack_number],
{ x = new_pack_wolves[ind].x, y = new_pack_wolves[ind].y, id = new_pack_wolves[ind].id }
)
MAIUV.set_mai_unit_variables(new_pack_wolves[ind], cfg.ai_id, { pack_number = new_pack_number })
end
end
-- Put labels out there for all wolves
if cfg.show_pack_number then
for pack_number,pack in pairs(packs) do
for _,wolf in ipairs(pack) do
wolves_multipacks_functions.put_label(wolf.x, wolf.y, pack_number)
end
end
end
return packs
end
return wolves_multipacks_functions
| gpl-2.0 |
dmccuskey/dmc-utils | dmc_corona/lib/dmc_lua/lua_class.lua | 16 | 14025 | --====================================================================--
-- dmc_lua/lua_class.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Lua Library : Lua Objects
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== Imports
-- none
--====================================================================--
--== Setup, Constants
-- cache globals
local assert, type, rawget, rawset = assert, type, rawget, rawset
local getmetatable, setmetatable = getmetatable, setmetatable
local sformat = string.format
local tinsert = table.insert
local tremove = table.remove
-- table for copies from lua_utils
local Utils = {}
-- forward declare
local ClassBase
--====================================================================--
--== Class Support Functions
--== Start: copy from lua_utils ==--
-- extend()
-- Copy key/values from one table to another
-- Will deep copy any value from first table which is itself a table.
--
-- @param fromTable the table (object) from which to take key/value pairs
-- @param toTable the table (object) in which to copy key/value pairs
-- @return table the table (object) that received the copied items
--
function Utils.extend( fromTable, toTable )
if not fromTable or not toTable then
error( "table can't be nil" )
end
function _extend( fT, tT )
for k,v in pairs( fT ) do
if type( fT[ k ] ) == "table" and
type( tT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], tT[ k ] )
elseif type( fT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], {} )
else
tT[ k ] = v
end
end
return tT
end
return _extend( fromTable, toTable )
end
--== End: copy from lua_utils ==--
-- registerCtorName
-- add names for the constructor
--
local function registerCtorName( name, class )
class = class or ClassBase
--==--
assert( type( name ) == 'string', "ctor name should be string" )
assert( class.is_class, "Class is not is_class" )
class[ name ] = class.__ctor__
return class[ name ]
end
-- registerDtorName
-- add names for the destructor
--
local function registerDtorName( name, class )
class = class or ClassBase
--==--
assert( type( name ) == 'string', "dtor name should be string" )
assert( class.is_class, "Class is not is_class" )
class[ name ] = class.__dtor__
return class[ name ]
end
--[[
obj:superCall( 'string', ... )
obj:superCall( Class, 'string', ... )
--]]
-- superCall()
-- function to intelligently find methods in object hierarchy
--
local function superCall( self, ... )
local args = {...}
local arg1 = args[1]
assert( type(arg1)=='table' or type(arg1)=='string', "superCall arg not table or string" )
--==--
-- pick off arguments
local parent_lock, method, params
if type(arg1) == 'table' then
parent_lock = tremove( args, 1 )
method = tremove( args, 1 )
else
method = tremove( args, 1 )
end
params = args
local self_dmc_super = self.__dmc_super
local super_flag = ( self_dmc_super ~= nil )
local result = nil
-- finds method name in class hierarchy
-- returns found class or nil
-- @params classes list of Classes on which to look, table/list
-- @params name name of method to look for, string
-- @params lock Class object with which to constrain searching
--
local function findMethod( classes, name, lock )
if not classes then return end -- when using mixins, etc
local cls = nil
for _, class in ipairs( classes ) do
if not lock or class == lock then
if rawget( class, name ) then
cls = class
break
else
-- check parents for method
cls = findMethod( class.__parents, name )
if cls then break end
end
end
end
return cls
end
local c, s -- class, super
-- structure in which to save our place
-- in case superCall() is invoked again
--
if self_dmc_super == nil then
self.__dmc_super = {} -- a stack
self_dmc_super = self.__dmc_super
-- find out where we are in hierarchy
s = findMethod( { self.__class }, method )
tinsert( self_dmc_super, s )
end
-- pull Class from stack and search for method on Supers
-- look for method on supers
-- call method if found
--
c = self_dmc_super[ # self_dmc_super ]
-- TODO: when c==nil
-- if c==nil or type(c)~='table' then return end
s = findMethod( c.__parents, method, parent_lock )
if s then
tinsert( self_dmc_super, s )
result = s[method]( self, unpack( args ) )
tremove( self_dmc_super, # self_dmc_super )
end
-- this is the first iteration and last
-- so clean up callstack, etc
--
if super_flag == false then
parent_lock = nil
tremove( self_dmc_super, # self_dmc_super )
self.__dmc_super = nil
end
return result
end
-- initializeObject
-- this is the beginning of object initialization
-- either Class or Instance
-- this is what calls the parent constructors, eg new()
-- called from newClass(), __create__(), __call()
--
-- @params obj the object context
-- @params params table with :
-- set_isClass = true/false
-- data contains {...}
--
local function initializeObject( obj, params )
params = params or {}
--==--
assert( params.set_isClass ~= nil, "initializeObject requires paramter 'set_isClass'" )
local is_class = params.set_isClass
local args = params.data or {}
-- set Class/Instance flag
obj.__is_class = params.set_isClass
-- call Parent constructors, if any
-- do in reverse
--
local parents = obj.__parents
for i = #parents, 1, -1 do
local parent = parents[i]
assert( parent, "Lua Objects: parent is nil, check parent list" )
rawset( obj, '__parent_lock', parent )
if parent.__new__ then
parent.__new__( obj, unpack( args ) )
end
end
rawset( obj, '__parent_lock', nil )
return obj
end
-- newindexFunc()
-- override the normal Lua lookup functionality to allow
-- property setter functions
--
-- @param t object table
-- @param k key
-- @param v value
--
local function newindexFunc( t, k, v )
local o, f
-- check for key in setters table
o = rawget( t, '__setters' ) or {}
f = o[k]
if f then
-- found setter, so call it
f(t,v)
else
-- place key/value directly on object
rawset( t, k, v )
end
end
-- multiindexFunc()
-- override the normal Lua lookup functionality to allow
-- property getter functions
--
-- @param t object table
-- @param k key
--
local function multiindexFunc( t, k )
local o, val
--== do key lookup in different places on object
-- check for key in getters table
o = rawget( t, '__getters' ) or {}
if o[k] then return o[k](t) end
-- check for key directly on object
val = rawget( t, k )
if val ~= nil then return val end
-- check OO hierarchy
-- check Parent Lock else all of Parents
--
o = rawget( t, '__parent_lock' )
if o then
if o then val = o[k] end
if val ~= nil then return val end
else
local par = rawget( t, '__parents' )
for _, o in ipairs( par ) do
if o[k] ~= nil then
val = o[k]
break
end
end
if val ~= nil then return val end
end
return nil
end
-- blessObject()
-- create new object, setup with Lua OO aspects, dmc-style aspects
-- @params inheritance table of supers/parents (dmc-style objects)
-- @params params
-- params.object
-- params.set_isClass
--
local function blessObject( inheritance, params )
params = params or {}
params.object = params.object or {}
params.set_isClass = params.set_isClass == true and true or false
--==--
local o = params.object
local o_id = tostring(o)
local mt = {
__index = multiindexFunc,
__newindex = newindexFunc,
__tostring = function(obj)
return obj:__tostring__(o_id)
end,
__call = function( cls, ... )
return cls:__ctor__( ... )
end
}
setmetatable( o, mt )
-- add Class property, access via getters:supers()
o.__parents = inheritance
o.__is_dmc = true
-- create lookup tables - setters, getters
o.__setters = {}
o.__getters = {}
-- copy down all getters/setters of parents
-- do in reverse order, to match order of property lookup
for i = #inheritance, 1, -1 do
local cls = inheritance[i]
if cls.__getters then
o.__getters = Utils.extend( cls.__getters, o.__getters )
end
if cls.__setters then
o.__setters = Utils.extend( cls.__setters, o.__setters )
end
end
return o
end
local function newClass( inheritance, params )
inheritance = inheritance or {}
params = params or {}
params.set_isClass = true
params.name = params.name or "<unnamed class>"
--==--
assert( type( inheritance ) == 'table', "first parameter should be nil, a Class, or a list of Classes" )
-- wrap single-class into table list
-- testing for DMC-Style objects
-- TODO: see if we can test for other Class libs
--
if inheritance.is_class == true then
inheritance = { inheritance }
elseif ClassBase and #inheritance == 0 then
-- add default base Class
tinsert( inheritance, ClassBase )
end
local o = blessObject( inheritance, {} )
initializeObject( o, params )
-- add Class property, access via getters:class()
o.__class = o
-- add Class property, access via getters:NAME()
o.__name = params.name
return o
end
-- backward compatibility
--
local function inheritsFrom( baseClass, options, constructor )
baseClass = baseClass == nil and baseClass or { baseClass }
return newClass( baseClass, options )
end
--====================================================================--
--== Base Class
--====================================================================--
ClassBase = newClass( nil, { name="Class Class" } )
-- __ctor__ method
-- called by 'new()' and other registrations
--
function ClassBase:__ctor__( ... )
local params = {
data = {...},
set_isClass = false
}
--==--
local o = blessObject( { self.__class }, params )
initializeObject( o, params )
return o
end
-- __dtor__ method
-- called by 'destroy()' and other registrations
--
function ClassBase:__dtor__()
self:__destroy__()
end
function ClassBase:__new__( ... )
return self
end
function ClassBase:__tostring__( id )
return sformat( "%s (%s)", self.NAME, id )
end
function ClassBase:__destroy__()
end
function ClassBase.__getters:NAME()
return self.__name
end
function ClassBase.__getters:class()
return self.__class
end
function ClassBase.__getters:supers()
return self.__parents
end
function ClassBase.__getters:is_class()
return self.__is_class
end
-- deprecated
function ClassBase.__getters:is_intermediate()
return self.__is_class
end
function ClassBase.__getters:is_instance()
return not self.__is_class
end
function ClassBase.__getters:version()
return self.__version
end
function ClassBase:isa( the_class )
local isa = false
local cur_class = self.class
-- test self
if cur_class == the_class then
isa = true
-- test parents
else
local parents = self.__parents
for i=1, #parents do
local parent = parents[i]
if parent.isa then
isa = parent:isa( the_class )
end
if isa == true then break end
end
end
return isa
end
-- optimize()
-- move super class methods to object
--
function ClassBase:optimize()
function _optimize( obj, inheritance )
if not inheritance or #inheritance == 0 then return end
for i=#inheritance,1,-1 do
local parent = inheritance[i]
-- climb up the hierarchy
_optimize( obj, parent.__parents )
-- make local references to all functions
for k,v in pairs( parent ) do
if type( v ) == 'function' then
obj[ k ] = v
end
end
end
end
_optimize( self, { self.__class } )
end
-- deoptimize()
-- remove super class (optimized) methods from object
--
function ClassBase:deoptimize()
for k,v in pairs( self ) do
if type( v ) == 'function' then
self[ k ] = nil
end
end
end
-- Setup Class Properties (function references)
registerCtorName( 'new', ClassBase )
registerDtorName( 'destroy', ClassBase )
ClassBase.superCall = superCall
--====================================================================--
--== Lua Objects Exports
--====================================================================--
-- makeNewClassGlobal
-- modifies the global namespace with newClass()
-- add or remove
--
local function makeNewClassGlobal( is_global )
is_global = is_global~=nil and is_global or true
if _G.newClass ~= nil then
print( "WARNING: newClass exists in global namespace" )
elseif is_global == true then
_G.newClass = newClass
else
_G.newClass = nil
end
end
makeNewClassGlobal() -- start it off
return {
__version=VERSION,
__superCall=superCall, -- for testing
setNewClassGlobal=makeNewClassGlobal,
registerCtorName=registerCtorName,
registerDtorName=registerDtorName,
inheritsFrom=inheritsFrom, -- backwards compatibility
newClass=newClass,
Class=ClassBase
}
| mit |
wljcom/vlc-2.2 | share/lua/meta/art/01_googleimage.lua | 74 | 1764 | --[[
Gets an artwork from images.google.com
$Id$
Copyright © 2007 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 descriptor()
return { scope="network" }
end
-- Return the artwork
function fetch_art()
if vlc.item == nil then return nil end
local meta = vlc.item:metas()
-- Radio Entries
if meta["Listing Type"] == "radio"
then
title = meta["title"] .. " radio logo"
-- TV Entries
elseif meta["Listing Type"] == "tv"
then
title = meta["title"] .. " tv logo"
-- Album entries
elseif meta["artist"] and meta["album"] then
title = meta["artist"].." "..meta["album"].." cover"
elseif meta["artist"] and meta["title"] then
title = meta["artist"].." "..meta["title"].." cover"
else
return nil
end
fd = vlc.stream( "http://images.google.com/images?q="..vlc.strings.encode_uri_component( title ) )
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, _, arturl = string.find( page, "<img height=\"([0-9]+)\" src=\"([^\"]+gstatic.com[^\"]+)\"" )
return arturl
end
| gpl-2.0 |
SnabbCo/snabbswitch | lib/luajit/testsuite/test/sysdep/ffi_lib_z.lua | 6 | 3348 | local ffi = require("ffi")
local compress, uncompress
if ffi.abi("win") then
ffi.cdef[[
int RtlGetCompressionWorkSpaceSize(uint16_t fmt,
unsigned long *wsbufsz, unsigned long *wsfragsz);
int RtlCompressBuffer(uint16_t fmt,
const uint8_t *src, unsigned long srclen,
uint8_t *dst, unsigned long dstsz,
unsigned long chunk, unsigned long *dstlen, void *workspace);
int RtlDecompressBuffer(uint16_t fmt,
uint8_t *dst, unsigned long dstsz,
const uint8_t *src, unsigned long srclen,
unsigned long *dstlen);
]]
local ntdll = ffi.load("ntdll")
local fmt = 0x0102
local workspace
do
local res = ffi.new("unsigned long[2]")
ntdll.RtlGetCompressionWorkSpaceSize(fmt, res, res+1)
workspace = ffi.new("uint8_t[?]", res[0])
end
function compress(txt)
local buf = ffi.new("uint8_t[?]", 4096)
local buflen = ffi.new("unsigned long[1]")
local res = ntdll.RtlCompressBuffer(fmt, txt, #txt, buf, 4096,
4096, buflen, workspace)
assert(res == 0)
return ffi.string(buf, buflen[0])
end
function uncompress(comp, n)
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]")
local res = ntdll.RtlDecompressBuffer(fmt, buf, n, comp, #comp, buflen)
assert(res == 0)
return ffi.string(buf, buflen[0])
end
else
ffi.cdef[[
unsigned long compressBound(unsigned long sourceLen);
int compress2(uint8_t *dest, unsigned long *destLen,
const uint8_t *source, unsigned long sourceLen, int level);
int uncompress(uint8_t *dest, unsigned long *destLen,
const uint8_t *source, unsigned long sourceLen);
]]
local zlib = ffi.load("z")
function compress(txt)
local n = tonumber(zlib.compressBound(#txt))
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]", n)
local res = zlib.compress2(buf, buflen, txt, #txt, 9)
assert(res == 0)
return ffi.string(buf, tonumber(buflen[0]))
end
function uncompress(comp, n)
local buf = ffi.new("uint8_t[?]", n)
local buflen = ffi.new("unsigned long[1]", n)
local res = zlib.uncompress(buf, buflen, comp, #comp)
assert(res == 0)
return ffi.string(buf, tonumber(buflen[0]))
end
end
local txt = [[Rebellious subjects, enemies to peace,
Profaners of this neighbour-stained steel,--
Will they not hear? What, ho! you men, you beasts,
That quench the fire of your pernicious rage
With purple fountains issuing from your veins,
On pain of torture, from those bloody hands
Throw your mistemper'd weapons to the ground,
And hear the sentence of your moved prince.
Three civil brawls, bred of an airy word,
By thee, old Capulet, and Montague,
Have thrice disturb'd the quiet of our streets,
And made Verona's ancient citizens
Cast by their grave beseeming ornaments,
To wield old partisans, in hands as old,
Canker'd with peace, to part your canker'd hate:
If ever you disturb our streets again,
Your lives shall pay the forfeit of the peace.
For this time, all the rest depart away:
You Capulet; shall go along with me:
And, Montague, come you this afternoon,
To know our further pleasure in this case,
To old Free-town, our common judgment-place.
Once more, on pain of death, all men depart.]]
txt = txt..txt..txt..txt
local c = compress(txt)
assert(2*#c < #txt)
local txt2 = uncompress(c, #txt)
assert(txt2 == txt)
| apache-2.0 |
Xkeeper0/emu-lua | nes-fceux/pac-man.lua | 1 | 3756 | function getMode()
local ghostMode = memory.readbyte(0xD0)
local ghostModeTimer = memory.readbyte(0x00CF) * 0x3C + (0x3C - memory.readbyte(0x00d1))
local text = "Chase"
if math.fmod(ghostMode, 2) == 0 then
text = "Scatter"
end
return { modeName = text, modeCount = ghostMode, modeTimer = ghostModeTimer, modeRaw1 = memory.readbyte(0x00CF), modeRaw2 = memory.readbyte(0x00D1)}
end
function framesToSeconds(frames)
return frames / 60;
end
Object = {
values = {
addresses = {
x = nil,
xs = nil,
y = nil,
ys = nil,
color = nil,
dir = nil,
},
},
x = nil,
xs = nil,
y = nil,
ys = nil,
color = nil,
dir = nil,
};
Object_mt = { __index = Object };
--Objectv_mt = { __index = Object.getValue };
Objectv_mt = { __index =
function (s,k)
return memory.readbyte(s.addresses[k])
end
}
setmetatable( Object , Object_mt );
setmetatable( Object.values , Objectv_mt );
function Object:new()
local ret = {};
ret.values = { addresses = {} };
setmetatable( ret, Object_mt );
setmetatable( ret.values , Objectv_mt );
return ret
end
function Object:getPosition()
return {
x = self.values.x, -- + self.values.xs / 0x100 - 8,
y = self.values.y, -- + self.values.ys / 0x100 + 8,
dir = self.values.dir
}
end;
function Object:drawPosition()
local pos = self:getPosition()
gui.line(pos.x - 1, pos.y , pos.x + 1, pos.y , "white");
gui.line(pos.x , pos.y - 1, pos.x , pos.y + 1, "white");
local directions = {
[0] = function (x, y) gui.line(x, y, x , y - 5, "white"); end,
[1] = function (x, y) gui.line(x, y, x - 5, y , "white"); end,
[2] = function (x, y) gui.line(x, y, x , y + 5, "white"); end,
[3] = function (x, y) gui.line(x, y, x + 5, y , "white"); end,
[4] = function (x, y) gui.line(x - 5, y, x + 5, y , "red"); end,
}
--gui.text(pos.x + 2, pos.y + 2, string.format("%d %d", pos.dir, self.values.dx), "gray", "clear");
if directions[pos.dir] then
directions[pos.dir](pos.x, pos.y)
end
end;
Pacman = Object:new()
Pacman.values.addresses = {
x = 0x001A,
xs = 0x001B,
y = 0x001C,
ys = 0x001D,
dir = 0x0050,
dx = 0x0050,
}
Blinky = Object:new()
Blinky.values.addresses = {
x = 0x001E,
xs = 0x001F,
y = 0x0020,
ys = 0x0021,
dir = 0x00B9,
dx = 0x00BA,
}
Pinky = Object:new()
Pinky.values.addresses = {
x = 0x0022,
xs = 0x0023,
y = 0x0024,
ys = 0x0025,
dir = 0x00BB,
dx = 0x00BC,
}
Inky = Object:new()
Inky.values.addresses = {
x = 0x0026,
xs = 0x0027,
y = 0x0028,
ys = 0x0029,
dir = 0x00BD,
dx = 0x00BE,
}
Clyde = Object:new()
Clyde.values.addresses = {
x = 0x002A,
xs = 0x002B,
y = 0x002C,
ys = 0x002D,
dir = 0x00BF,
dx = 0x00C0,
}
print(Pacman);
print(Blinky);
print(Pinky);
print(Inky);
print(Clyde);
LockPacman = false
while true do
inpt = input.get()
if inpt['Q'] then
LockPacman = true
end
if LockPacman then
memory.writebyte(0x001a, 170)
memory.writebyte(0x001c, 92)
end
-- local line = 0
-- thisObject = Blinky:getPosition()
Pacman:drawPosition()
Blinky:drawPosition()
Pinky:drawPosition()
Inky:drawPosition()
Clyde:drawPosition()
-- Blue timer
bluetimer = memory.readbyte(0x0089) * 0x3C + (0x3C - memory.readbyte(0x008A))
gui.text(200, 0, bluetimer)
mode = getMode();
gui.text(180, 90, string.format("%d: %s\n%5.1f\n%02X %02X", mode.modeCount, mode.modeName, framesToSeconds(mode.modeTimer), mode.modeRaw1, mode.modeRaw2))
DotsRemaining = memory.readbyte(0x006A)
BlinkySpeedup1Dots = memory.readbyte(0x008D)
BlinkySpeedup2Dots = memory.readbyte(0x008E)
gui.text(180, 120, string.format("Dots left: %3d\nBlinky1:%3d\nBlinky2:%3d", DotsRemaining, BlinkySpeedup1Dots, BlinkySpeedup2Dots))
emu.frameadvance();
end; | mit |
thedraked/darkstar | scripts/globals/weaponskills/catastrophe.lua | 19 | 2122 | -----------------------------------
-- Catastrophe
-- Scythe weapon skill
-- Skill Level: N/A
-- Drain target's HP. Bec de Faucon/Apocalypse: Additional effect: Haste
-- This weapon skill is available with the stage 5 relic Scythe Apocalypse or within Dynamis with the stage 4 Bec de Faucon.
-- Also available without Aftermath effects with the Crisis Scythe. After 13 weapon skills have been used successfully, gives one "charge" of Catastrophe.
-- Aligned with the Shadow Gorget & Soil Gorget.
-- Aligned with the Shadow Belt & Soil Belt.
-- Element: None
-- Modifiers: INT:40% ; AGI:40%
-- 100%TP 200%TP 300%TP
-- 2.75 2.75 2.75
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.4; params.int_wsc = 0.4; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.agi_wsc = 0.0; params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
-- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect.
if (damage > 0) then
local amDuration = 20 * math.floor(tp/1000);
player:addStatusEffect(EFFECT_AFTERMATH, 100, 0, amDuration, 0, 6);
end
if (target:isUndead() == false) then
local drain = (damage * 0.4);
player:addHP(drain);
end
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
master041/tele-master-asli | plugins/gnuplot.lua | 622 | 1813 | --[[
* Gnuplot plugin by psykomantis
* dependencies:
* - gnuplot 5.00
* - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html
*
]]
-- Gnuplot needs absolute path for the plot, so i run some commands to find where we are
local outputFile = io.popen("pwd","r")
io.input(outputFile)
local _pwd = io.read("*line")
io.close(outputFile)
local _absolutePlotPath = _pwd .. "/data/plot.png"
local _scriptPath = "./data/gnuplotScript.gpl"
do
local function gnuplot(msg, fun)
local receiver = get_receiver(msg)
-- We generate the plot commands
local formattedString = [[
set grid
set terminal png
set output "]] .. _absolutePlotPath .. [["
plot ]] .. fun
local file = io.open(_scriptPath,"w");
file:write(formattedString)
file:close()
os.execute("gnuplot " .. _scriptPath)
os.remove (_scriptPath)
return _send_photo(receiver, _absolutePlotPath)
end
-- Check all dependencies before executing
local function checkDependencies()
local status = os.execute("gnuplot -h")
if(status==true) then
status = os.execute("gnuplot -e 'set terminal png'")
if(status == true) then
return 0 -- OK ready to go!
else
return 1 -- missing libgd2-xpm-dev
end
else
return 2 -- missing gnuplot
end
end
local function run(msg, matches)
local status = checkDependencies()
if(status == 0) then
return gnuplot(msg,matches[1])
elseif(status == 1) then
return "It seems that this bot miss a dependency :/"
else
return "It seems that this bot doesn't have gnuplot :/"
end
end
return {
description = "use gnuplot through telegram, only plot single variable function",
usage = "!gnuplot [single variable function]",
patterns = {"^!gnuplot (.+)$"},
run = run
}
end
| gpl-2.0 |
keharriso/rogue-with-friends | Position.lua | 1 | 4651 | -- Rogue with Friends - a 2D, real-time, multiplayer roguelike
-- ---------------------------------------------------------------
-- Released under the GNU AGPLv3 or later. See README.md for info.
local Point = require "Point"
local concat = table.concat
-- A Position represents the location of a game object in an Area.
--
-- A Position is also a Point, and supports all Point methods.
--
-- Positions can be converted back and forth between an encoded form (number
-- or string) and decoded form (Position object) [see Position:encode,
-- Position.decode].
--
-- Positions have neighboring positions. These exist as offsets in a
-- particular direction. [see Position:getDirection, Position.getDirections,
-- Position:getNeighbor, Position:getNeighbors].
local Position = setmetatable({}, {__index = Point})
Position.mt = {__index = Position}
-- Two Positions are equal if their encodings are equal.
function Position.mt.__eq(a, b)
return a:encode() == b:encode()
end
-- [private] Neighbor coordinate offset array.
local neighbors = {N = {0, -1}, NE = { 1, -1}, E = { 1, 0}, SE = { 1, 1},
S = {0, 1}, SW = {-1, 1}, W = {-1, 0}, NW = {-1, -1}}
-- [private] Array of possible directions.
local directions = {}
for dir,_ in pairs(neighbors) do
directions[#directions+1] = dir
end
-- Returns an iterator over all possible directions.
function Position.getDirections()
local i, n = 0, #directions
return function ()
i = i + 1
return i <= n and directions[i] or nil
end
end
-- [private] Cache the encoding for a Position.
local function reencode(pos)
pos[3] = nil
pos[3] = concat(pos, ",")
end
-- Construct a new Position from the given coordinates. `coords` should be an
-- array of {x, y}. `coords` is consumed by this function and should not be
-- reused or modified.
function Position.new(coords)
setmetatable(coords, Position.mt)
reencode(coords)
return coords
end
-- Construct a new Position with the same coordinates as this one.
function Position:clone()
local x, y = self:unpack()
return setmetatable({x, y, self:encode()}, Position.mt)
end
-- Decode a Position from a value returned by Position:encode().
function Position.decode(code)
local pos = setmetatable({nil, nil, code}, Position.mt)
local x, y = code:match "([^,]+),([^,]+)"
pos[1], pos[2] = tonumber(x), tonumber(y)
return pos
end
-- Encode a Position as a number or string.
function Position:encode()
-- Return the cached encoding.
return self[3]
end
-- Set this Position's x component.
function Position:setX(x)
Point.setX(self, x)
-- Recompute the cached encoding.
reencode(self)
end
-- Set this Position's y component.
function Position:setY(y)
Point.setY(self, y)
-- Recompute the cached encoding.
reencode(self)
end
-- Set this Position's components (x, y).
function Position:pack(x, y)
Point.pack(self, x, y)
-- Recompute the cached encoding.
reencode(self)
end
-- Return the nearest direction from this Position to the given one, or nil if
-- this position is closer than any of its neighbors.
function Position:getDirection(p)
if self == p then return nil end
local best, bestDist = nil, math.huge
for dir,n in pairs(self:getNeighbors()) do
local dist = self:getDistance(n) + n:getDistance(p)
if dist < bestDist then
best, bestDist = dir, dist
end
end
return best
end
-- Return true if the given Position is a neighbor of this one, and false if
-- it is not.
function Position:isNeighbor(p)
local dx = p:getX() - self:getX()
local dy = p:getY() - self:getY()
return self ~= p and dx >= -1 and dx <= 1 and dy >= -1 and dy <= 1
end
-- Calculate the Position of a single neighbor in the given direction. The
-- given direction should be in Position.getDirections().
--
-- If cache is not nil, it is assumed to be an existing point object and is
-- recycled.
function Position:getNeighbor(dir, cache)
local x, y = self:unpack()
local offset = neighbors[dir]
x, y = x + offset[1], y + offset[2]
if cache ~= nil then
cache:pack(x, y)
return cache
else
return Position.new {x, y}
end
end
-- Generate a mapping between directions and neighboring positions. The keys
-- of the returned table are the directions in Position.getDirections(). The
-- values are the neighboring positions in the corresponding directions.
--
-- If cache is not nil, it is assumed to be a table previously returned from
-- this function. The table and its component Position objects are recycled.
function Position:getNeighbors(cache)
if cache == nil then
cache = {}
end
for dir in Position.getDirections() do
cache[dir] = self:getNeighbor(dir, cache[dir])
end
return cache
end
return Position
| agpl-3.0 |
ukoloff/rufus-lua-win | vendor/lua/lib/lua/luarocks/new_version.lua | 2 | 4519 |
--- Module implementing the LuaRocks "new_version" command.
-- Utility function that writes a new rockspec, updating data from a previous one.
module("luarocks.new_version", package.seeall)
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local download = require("luarocks.download")
local fetch = require("luarocks.fetch")
local persist = require("luarocks.persist")
local dir = require("luarocks.dir")
local fs = require("luarocks.fs")
help_summary = "Auto-write a rockspec for a new version of a rock."
help_arguments = "{<program>|<rockspec>} [<new_version>] [<new_url>]"
help = [[
This is a utility function that writes a new rockspec, updating data
from a previous one.
If a package name is given, it downloads the latest rockspec from the
default server. If a rockspec is given, it uses it instead.
If the version number is not given, it only increments the revision
number of the given (or downloaded) rockspec.
If a URL is given, it replaces the one from the old rockspec with the
given URL. If a URL is not given and a new version is given, it tries
to guess the new URL by replacing occurrences of the version number
in the URL or tag. It also tries to download the new URL to determine
the new MD5 checksum.
WARNING: it writes the new rockspec to the current directory,
overwriting the file if it already exists.
]]
local order = {"rockspec_format", "package", "version",
{ "source", { "url", "tag", "branch", "md5" } },
{ "description", {"summary", "detailed", "homepage", "license" } },
"supported_platforms", "dependencies", "external_dependencies",
{ "build", {"type", "modules", "copy_directories", "platforms"} },
"hooks"}
local function try_replace(tbl, field, old, new)
if not tbl[field] then
return false
end
local old_field = tbl[field]
local new_field = tbl[field]:gsub(old, new)
if new_field ~= old_field then
util.printout("Guessing new '"..field.."' field as "..new_field)
tbl[field] = new_field
return true
end
return false
end
local function check_url_and_update_md5(out_rs, out_name)
out_rs.source.md5 = nil
local file, temp_dir = fetch.fetch_url_at_temp_dir(out_rs.source.url, "luarocks-new-version-"..out_name)
if file then
util.printout("File successfully downloaded. Updating MD5 checksum...")
out_rs.source.md5 = fs.get_md5(file)
else
util.printerr("Warning: invalid URL - "..temp_dir)
end
end
function run(...)
local flags, input, version, url = util.parse_flags(...)
if not input then
return nil, "Missing arguments: expected program or rockspec. See help."
end
assert(type(input) == "string")
local filename = input
if not input:match(".rockspec$") then
local err
filename, err = download.download("rockspec", input)
if not input then
return nil, err
end
end
local valid_rs, err = fetch.load_rockspec(filename)
if not valid_rs then
return nil, err
end
local old_ver, old_rev = valid_rs.version:match("(.*)%-(%d+)$")
local new_ver, new_rev
if version then
new_ver, new_rev = version:match("(.*)%-(%d+)$")
new_rev = tonumber(new_rev)
if not new_rev then
new_ver = version
new_rev = 1
end
else
new_ver = old_ver
new_rev = tonumber(old_rev) + 1
end
local out_rs = persist.load_into_table(filename)
local out_name = out_rs.package:lower()
out_rs.version = new_ver.."-"..new_rev
if url then
out_rs.source.url = url
check_url_and_update_md5(out_rs, out_name)
else
if new_ver ~= old_ver then
local ok = try_replace(out_rs.source, "url", old_ver, new_ver)
if ok then
check_url_and_update_md5(out_rs, out_name)
else
ok = try_replace(out_rs.source, "tag", old_ver, new_ver)
if not ok then
return nil, "Failed to determine the location of the new version."
end
end
end
end
if out_rs.build and out_rs.build.type == "module" then
out_rs.build.type = "builtin"
end
local out_filename = out_name.."-"..new_ver.."-"..new_rev..".rockspec"
persist.save_from_table(out_filename, out_rs, order)
util.printout("Wrote "..out_filename)
local valid_out_rs, err = fetch.load_local_rockspec(out_filename)
if not valid_out_rs then
return nil, "Failed loading generated rockspec: "..err
end
return true
end
| mit |
filug/nodemcu-firmware | lua_modules/mpr121/mpr121.lua | 19 | 2055 | ---------------------------------------------------------------
-- MPR121 I2C module for NodeMCU
-- Based on code from: http://bildr.org/2011/05/mpr121_arduino/
-- Tiago Custódio <tiagocustodio1@gmail.com>
---------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
-- Default value for i2c communication
local id = 0
--device address
local devAddr = 0
--make it faster
local i2c = i2c
function M.setRegister(address, r, v)
i2c.start(id)
local ans = i2c.address(id, address, i2c.TRANSMITTER)
i2c.write(id, r)
i2c.write(id, v)
i2c.stop(id)
end
function M.init(address)
devAddr = address
M.setRegister(devAddr, 0x5E, 0x00) -- ELE_CFG
-- Section A - Controls filtering when data is > baseline.
M.setRegister(devAddr, 0x2B, 0x01) -- MHD_R
M.setRegister(devAddr, 0x2C, 0x01) -- NHD_R
M.setRegister(devAddr, 0x2D, 0x00) -- NCL_R
M.setRegister(devAddr, 0x2E, 0x00) -- FDL_R
-- Section B - Controls filtering when data is < baseline.
M.setRegister(devAddr, 0x2F, 0x01) -- MHD_F
M.setRegister(devAddr, 0x30, 0x01) -- NHD_F
M.setRegister(devAddr, 0x31, 0xFF) -- NCL_F
M.setRegister(devAddr, 0x32, 0x02) -- FDL_F
-- Section C - Sets touch and release thresholds for each electrode
for i = 0, 11 do
M.setRegister(devAddr, 0x41+(i*2), 0x06) -- ELE0_T
M.setRegister(devAddr, 0x42+(i*2), 0x0A) -- ELE0_R
end
-- Section D - Set the Filter Configuration - Set ESI2
M.setRegister(devAddr, 0x5D, 0x04) -- FIL_CFG
-- Section E - Electrode Configuration - Set 0x5E to 0x00 to return to standby mode
M.setRegister(devAddr, 0x5E, 0x0C) -- ELE_CFG
tmr.delay(50000) -- Delay to let the electrodes settle after config
end
function M.readTouchInputs()
i2c.start(id)
i2c.address(id, devAddr, i2c.RECEIVER)
local c = i2c.read(id, 2)
i2c.stop(id)
local LSB = tonumber(string.byte(c, 1))
local MSB = tonumber(string.byte(c, 2))
local touched = bit.lshift(MSB, 8) + LSB
local t = {}
for i = 0, 11 do
t[i+1] = bit.isset(touched, i) and 1 or 0
end
return t
end
return M
| mit |
thedraked/darkstar | scripts/zones/Al_Zahbi/npcs/Eumoa-Tajimoa.lua | 14 | 1039 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Eumoa-Tajimoa
-- Type: Standard NPC
-- @zone 48
-- @pos 19.275 -1 55.182
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00ef);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
NPLPackages/main | script/ide/System/Windows/Mouse.lua | 1 | 2713 | --[[
Title: Mouse
Author(s): LiXizhi
Date: 2015/4/23
Desc: Singleton object
The Mouse class provides mouse related events, methods and, properties which provide information regarding the state of the mouse.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/ide/System/Windows/Mouse.lua");
local Mouse = commonlib.gettable("System.Windows.Mouse");
Mouse:Capture(uiElement);
------------------------------------------------------------
]]
NPL.load("(gl)script/ide/System/Core/ToolBase.lua");
NPL.load("(gl)script/ide/math/Point.lua");
NPL.load("(gl)script/ide/System/Windows/Screen.lua");
local Screen = commonlib.gettable("System.Windows.Screen");
local Point = commonlib.gettable("mathlib.Point");
local Mouse = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), commonlib.gettable("System.Windows.Mouse"));
Mouse:Property("Name", "Mouse");
function Mouse:ctor()
end
-- Gets the element that has captured the mouse.
function Mouse:GetCapture()
return self.capturedElement;
end
-- When an element captures the mouse, it receives mouse input whether or not the cursor is within its borders.
-- To release mouse capture, call Capture passing nil as the element to capture.
-- @param element: if nil, it means release mouse capture.
function Mouse:Capture(element)
self.capturedElement = element;
end
-- Gets the state of the left button of the mouse. true if pressed.
function Mouse:LeftButton()
return ParaUI.IsMousePressed(0);
end
-- Gets the state of the right button of the mouse. true if pressed.
function Mouse:RightButton()
return ParaUI.IsMousePressed(1);
end
-- Gets the element the mouse pointer is directly over.
function Mouse:DirectlyOver()
-- TODO:
end
-- get Point object.
function Mouse:pos()
-- global pos of the mouse
return Point:new_from_pool(ParaUI.GetMousePosition());
end
-- return x, y in GUI screen coordinate
function Mouse:GetMousePosition()
return ParaUI.GetMousePosition()
end
-- return true if left/right mouse button should be swapped.
function Mouse:IsMouseButtonSwapped()
return Screen:GetGUIRoot():GetField("MouseButtonSwapped", false);
end
-- set if left/right mouse button should be swapped.
function Mouse:SetMouseButtonSwapped(bSwapped)
Screen:GetGUIRoot():SetField("MouseButtonSwapped", bSwapped==true);
end
-- if false, the left touch is left mouse button.
function Mouse:IsTouchButtonSwapped()
return Screen:GetGUIRoot():GetField("TouchButtonSwapped", false);
end
-- if false, the left touch is left mouse button.
function Mouse:SetTouchButtonSwapped(bSwapped)
Screen:GetGUIRoot():SetField("TouchButtonSwapped", bSwapped==true);
end
-- this is a singleton class
Mouse:InitSingleton(); | gpl-2.0 |
SnabbCo/snabbswitch | lib/ljsyscall/test/netbsd.lua | 5 | 9658 | -- BSD specific tests
local function init(S)
local helpers = require "test.helpers"
local types = S.types
local c = S.c
local abi = S.abi
local features = S.features
local util = S.util
local bit = require "syscall.bit"
local ffi = require "ffi"
local t, pt, s = types.t, types.pt, types.s
local assert = helpers.assert
local function fork_assert(cond, err, ...) -- if we have forked we need to fail in main thread not fork
if not cond then
print(tostring(err))
print(debug.traceback())
S.exit("failure")
end
if cond == true then return ... end
return cond, ...
end
local function assert_equal(...)
collectgarbage("collect") -- force gc, to test for bugs
return assert_equals(...)
end
local teststring = "this is a test string"
local size = 512
local buf = t.buffer(size)
local tmpfile = "XXXXYYYYZZZ4521" .. S.getpid()
local tmpfile2 = "./666666DDDDDFFFF" .. S.getpid()
local tmpfile3 = "MMMMMTTTTGGG" .. S.getpid()
local longfile = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" .. S.getpid()
local efile = "./tmpexXXYYY" .. S.getpid() .. ".sh"
local largeval = math.pow(2, 33) -- larger than 2^32 for testing
local mqname = "ljsyscallXXYYZZ" .. S.getpid()
local clean = function()
S.rmdir(tmpfile)
S.unlink(tmpfile)
S.unlink(tmpfile2)
S.unlink(tmpfile3)
S.unlink(longfile)
S.unlink(efile)
end
local test = {}
test.mount_netbsd_root = {
test_mount_kernfs = function()
assert(S.mkdir(tmpfile))
assert(S.mount("kernfs", tmpfile))
assert(S.unmount(tmpfile))
assert(S.rmdir(tmpfile))
end,
test_util_mount_kernfs = function()
assert(S.mkdir(tmpfile))
assert(util.mount{type = "kernfs", dir = tmpfile})
assert(S.unmount(tmpfile))
assert(S.rmdir(tmpfile))
end,
test_mount_tmpfs = function()
assert(S.mkdir(tmpfile))
local data = {ta_version = 1, ta_nodes_max=100, ta_size_max=1048576, ta_root_mode=helpers.octal("0700")}
assert(S.mount("tmpfs", tmpfile, 0, data))
assert(S.unmount(tmpfile))
assert(S.rmdir(tmpfile))
end,
}
test.network_utils_netbsd_root = {
test_ifcreate_lo = function()
local ifname = "lo9" .. tostring(S.getpid())
assert(util.ifcreate(ifname))
assert(util.ifdestroy(ifname))
end,
test_ifupdown_lo = function()
local ifname = "lo9" .. tostring(S.getpid())
assert(util.ifcreate(ifname))
local flags = assert(util.ifgetflags(ifname))
assert(bit.band(flags, c.IFF.UP) == 0)
assert(util.ifup(ifname))
local flags = assert(util.ifgetflags(ifname))
assert(bit.band(flags, c.IFF.UP) ~= 0)
assert(util.ifdown(ifname))
local flags = assert(util.ifgetflags(ifname))
assert(bit.band(flags, c.IFF.UP) == 0)
assert(util.ifdestroy(ifname))
end,
test_ifaddr_inet4 = function()
local ifname = "lo8" .. tostring(S.getpid())
assert(util.ifcreate(ifname))
assert(util.ifup(ifname))
assert(util.ifaddr_inet4(ifname, "127.1.0.1/24")) -- TODO fail gracefully if no ipv4 support
-- TODO need read functionality to test it worked correctly
assert(util.ifdown(ifname))
assert(util.ifdestroy(ifname))
end,
test_ifaddr_inet6 = function()
local ifname = "lo8" .. tostring(S.getpid())
assert(util.ifcreate(ifname))
assert(util.ifup(ifname))
assert(util.ifaddr_inet6(ifname, "fd97:fab9:44c2::1/48")) -- TODO this is my private registration (SIXXS), should be random
-- TODO need read functionality to test it worked correctly
assert(util.ifdown(ifname))
assert(util.ifdestroy(ifname))
end,
}
test.sockets_pipes_netbsd = {
test_nosigpipe = function()
local p1, p2 = assert(S.pipe2("nosigpipe"))
assert(p1:close())
local ok, err = p2:write("other end closed")
assert(not ok and err.PIPE, "should get EPIPE")
assert(p2:close())
end,
test_paccept = function()
local s = S.socket("unix", "seqpacket, nonblock, nosigpipe")
local sa = t.sockaddr_un(tmpfile)
assert(s:bind(sa))
assert(s:listen())
local sa = t.sockaddr_un()
local a, err = s:paccept(sa, nil, "alrm", "nonblock, nosigpipe")
assert(not a and err.AGAIN, "expect again: " .. tostring(err))
assert(s:close())
assert(S.unlink(tmpfile))
end,
--[[
test_inet_socket_read_paccept = function() -- triggers PR/48292
local ss = assert(S.socket("inet", "stream, nonblock"))
local sa = t.sockaddr_in(0, "loopback")
assert(ss:bind(sa))
local ba = assert(ss:getsockname())
assert(ss:listen())
local cs = assert(S.socket("inet", "stream")) -- client socket
local ok, err = cs:connect(ba)
local as = ss:paccept()
local ok, err = cs:connect(ba)
assert(ok or err.ISCONN);
assert(ss:block()) -- force accept to wait
as = as or assert(ss:paccept())
local fl = assert(as:fcntl("getfl"))
assert_equal(bit.band(fl, c.O.NONBLOCK), 0)
-- TODO commenting out next two lines is issue only with paccept not accept
local n = assert(cs:write("testing"))
assert(n == 7, "expect writev to write 7 bytes")
--
n = assert(as:read())
assert_equal(n, "testing")
assert(cs:close())
assert(as:close())
assert(ss:close())
end,
]]
}
test.misc_netbsd = {
teardown = clean,
--[[ -- should not be using major, minor as not defined over 32 bit, plus also ffs does not support
test_mknod_64bit_root = function()
local dev = t.device(1999875, 515)
assert(dev.dev > t.dev(0xffffffff))
assert(S.mknod(tmpfile, "fchr,0666", dev))
local stat = assert(S.stat(tmpfile))
assert(stat.ischr, "expect to be a character device")
assert_equal(stat.rdev.major, dev.major)
assert_equal(stat.rdev.minor, dev.minor)
assert_equal(stat.rdev.device, dev.device)
assert(S.unlink(tmpfile))
end,
]]
test_fsync_range = function()
local fd = assert(S.creat(tmpfile, "RWXU"))
assert(fd:sync_range("data", 0, 4096))
assert(S.unlink(tmpfile))
assert(fd:close())
end,
test_pollts = function()
local a, b = assert(S.socketpair("unix", "stream"))
local pev = t.pollfds{{fd = a, events = c.POLL.IN}}
local p = assert(S.pollts(pev, 0, nil))
assert_equal(p, 0) -- no events yet
for k, v in ipairs(pev) do
assert_equal(v.fd, a:getfd())
assert_equal(v.revents, 0)
end
assert(b:write(teststring))
local p = assert(S.pollts(pev, nil, "alrm"))
assert_equal(p, 1) -- 1 event
for k, v in ipairs(pev) do
assert_equal(v.fd, a:getfd())
assert(v.IN, "IN event now")
end
assert(a:read())
assert(b:close())
assert(a:close())
end,
}
--[[ -- need to do in a thread as cannot exit
test.misc_bsd_root = {
test_fchroot = function()
local fd = assert(S.open("/", "rdonly"))
assert(fd:chroot())
assert(fd:close())
end,
}
]]
test.ktrace = {
teardown = clean,
test_ktrace = function()
local fd = assert(S.open(tmpfile, "creat, trunc, rdwr", "0666"))
local pid = S.getpid()
local kfd = assert(S.kqueue())
local kevs = t.kevents{{fd = fd, filter = "vnode", flags = "add, enable, clear", fflags = "extend"}}
assert(kfd:kevent(kevs, nil))
collectgarbage()
collectgarbage("stop")
assert(S.ktrace(tmpfile, "set", "syscall, sysret", pid))
-- now do something that should be in trace
assert_equal(pid, S.getpid())
assert(S.ktrace(tmpfile, "clear", "syscall, sysret", pid))
S.nanosleep(0.05) -- can be flaky and only get one event otherwise, TODO not clear needed?
assert(kfd:kevent(nil, kevs)) -- block until extend
collectgarbage("restart")
local buf = t.buffer(4096)
local n = assert(fd:read(buf, 4096))
local syscall, sysret = {}, {} -- on real OS luajit may do some memory allocations so may be extra calls occasionally
for _, ktr in util.kdump(buf, n) do
assert_equal(ktr.pid, pid)
if ktr.typename == "SYSCALL" then
syscall[ktr.values.name] = true
elseif ktr.typename == "SYSRET" then
sysret[ktr.values.name] = true
if ktr.values.name == "getpid" then assert_equal(tonumber(ktr.values.retval), S.getpid()) end
end
end
assert(syscall.getpid, "expect call getpid")
assert(sysret.getpid, "expect return from getpid")
assert(S.unlink(tmpfile))
assert(fd:close())
end,
test_fktrace = function()
local p1, p2 = assert(S.pipe())
local pid = S.getpid()
assert(p2:ktrace("set", "syscall, sysret", pid))
-- now do something that should be in trace
assert_equal(pid, S.getpid())
local ok, err = S.open("/thisfiledoesnotexist", "rdonly")
local ok, err = S.ioctl(-1, "TIOCMGET")
assert(p2:ktrace("clear", "syscall, sysret", pid))
S.nanosleep(0.01) -- can be flaky and only get one event otherwise
local buf = t.buffer(4096)
local n = assert(p1:read(buf, 4096))
local syscall, sysret = {}, {}
for _, ktr in util.kdump(buf, n) do
assert_equal(ktr.pid, pid) assert_equal(ktr.pid, pid)
if ktr.typename == "SYSCALL" then
syscall[ktr.values.name] = true
elseif ktr.typename == "SYSRET" then
sysret[ktr.values.name] = true
if ktr.values.name == "open" then assert(ktr.values.error.NOENT) end
if ktr.values.name == "ioctl" then assert(ktr.values.error.BADF) end
end
end
assert(syscall.getpid and sysret.getpid, "expect getpid")
assert(syscall.open and sysret.open, "expect open")
assert(syscall.ioctl and sysret.ioctl, "expect open")
assert(p1:close())
assert(p2:close())
end,
}
test.ksem = {
test_ksem_init = function()
local sem = assert(S.ksem_init(3))
assert(S.ksem_destroy(sem))
end,
}
return test
end
return {init = init}
| apache-2.0 |
rjeli/luvit | tests/to-convert/test-utils.lua | 5 | 2455 | local utils = require('utils')
require('helper')
local Object = require('core').Object
local BindHelper = Object:extend()
function BindHelper:func1(arg1, callback, ...)
assert(self ~= nil)
callback(arg1)
end
function BindHelper:func2(arg1, arg2, callback)
assert(self ~= nil)
callback(arg1, arg2)
end
function BindHelper:func3(arg1, arg2, arg3, callback)
assert(self ~= nil)
callback(arg1, arg2, arg3)
end
local testObj = BindHelper:new()
local bound
bound = utils.bind(BindHelper.func1, testObj)
bound('hello world', function(arg1)
assert(arg1 == 'hello world')
end)
bound('hello world1', function(arg1)
assert(arg1 == 'hello world1')
end)
bound = utils.bind(BindHelper.func1, testObj, 'hello world')
bound(function(arg1)
assert(arg1 == 'hello world')
end)
bound(function(arg1)
assert(arg1 == 'hello world')
end)
bound(function(arg1)
assert(arg1 == 'hello world')
end)
bound = utils.bind(BindHelper.func2, testObj)
bound('hello', 'world', function(arg1, arg2)
assert(arg1 == 'hello')
assert(arg2 == 'world')
end)
bound('hello', 'world', function(arg1, arg2)
assert(arg1 == 'hello')
assert(arg2 == 'world')
end)
bound = utils.bind(BindHelper.func2, testObj, 'hello')
bound('world', function(arg1, arg2)
assert(arg1 == 'hello')
assert(arg2 == 'world')
end)
bound = utils.bind(BindHelper.func3, testObj)
bound('hello', 'world', '!', function(arg1, arg2, arg3)
assert(arg1 == 'hello')
assert(arg2 == 'world')
assert(arg3 == '!')
end)
bound = utils.bind(BindHelper.func3, testObj)
bound('hello', nil, '!', function(arg1, arg2, arg3)
assert(arg1 == 'hello')
assert(arg2 == nil)
assert(arg3 == '!')
end)
bound = utils.bind(BindHelper.func3, testObj, 'hello', 'world')
bound('!', function(arg1, arg2, arg3)
assert(arg1 == 'hello')
assert(arg2 == 'world')
assert(arg3 == '!')
end)
bound = utils.bind(BindHelper.func3, testObj, 'hello', nil)
bound('!', function(arg1, arg2, arg3)
assert(arg1 == 'hello')
assert(arg2 == nil)
assert(arg3 == '!')
end)
bound = utils.bind(BindHelper.func3, testObj, nil, 'world')
bound('!', function(arg1, arg2, arg3)
assert(arg1 == nil)
assert(arg2 == 'world')
assert(arg3 == '!')
end)
local tblA = { 1, 2, 3 }
local tblB = { tblA, 'test1', 'test2', { tblA } }
local s = utils.dump(tblB, 0, true)
assert(s == '{ { 1, 2, 3 }, "test1", "test2", { } }')
local Error = require('core').Error
local MyError = Error:extend()
assert(pcall(utils.dump, MyError))
| apache-2.0 |
mtroyka/Zero-K | scripts/chicken_roc.lua | 12 | 5362 | include "constants.lua"
--pieces
local body, head, tail, leftWing1, rightWing1, leftWing2, rightWing2 = piece("body","head","tail","lwing1","rwing1","lwing2","rwing2")
local leftThigh, leftKnee, leftShin, leftFoot, rightThigh, rightKnee, rightShin, rightFoot = piece("lthigh", "lknee", "lshin", "lfoot", "rthigh", "rknee", "rshin", "rfoot")
local lforearml,lbladel,rforearml,rbladel,lforearmu,lbladeu,rforearmu,rbladeu = piece("lforearml", "lbladel", "rforearml", "rbladel", "lforearmu", "lbladeu", "rforearmu", "rbladeu")
local spike1, spike2, spike3, firepoint, spore1, spore2, spore3 = piece("spike1", "spike2", "spike3", "firepoint", "spore1", "spore2", "spore3")
local smokePiece = {}
local turretIndex = {
}
--constants
local wingAngle = math.rad(40)
local wingSpeed = math.rad(120)
local tailAngle = math.rad(20)
local bladeExtendSpeed = math.rad(600)
local bladeRetractSpeed = math.rad(120)
local bladeAngle = math.rad(140)
--variables
local isMoving = false
local feet = true
--signals
local SIG_Aim = 1
local SIG_Aim2 = 2
local SIG_Fly = 16
--cob values
----------------------------------------------------------
local function RestoreAfterDelay()
Sleep(1000)
end
local function Fly()
Signal(SIG_Fly)
SetSignalMask(SIG_Fly)
while true do
Turn(leftWing1, z_axis, -wingAngle, wingSpeed)
Turn(rightWing1, z_axis, wingAngle, wingSpeed)
Turn(leftWing2, z_axis, -wingAngle/3, wingSpeed)
Turn(rightWing2, z_axis, wingAngle/3, wingSpeed)
Turn(tail, x_axis, tailAngle, math.rad(40))
Move(body, y_axis, -60, 45)
Sleep(0)
WaitForTurn(leftWing1, z_axis)
Turn(leftWing1, z_axis, wingAngle, wingSpeed)
Turn(rightWing1, z_axis, -wingAngle, wingSpeed)
Turn(leftWing2, z_axis, wingAngle/3, wingSpeed*2)
Turn(rightWing2, z_axis, -wingAngle/3, wingSpeed*2)
Turn(tail, x_axis, -tailAngle, math.rad(40))
Move(body, y_axis, 0, 45)
-- EmitSfx(body, 4096+5) --Queen Crush
Sleep(0)
WaitForTurn(leftWing1, z_axis)
end
end
local function StopFly()
Signal(SIG_Fly)
SetSignalMask(SIG_Fly)
Turn(leftWing1, z_axis, 0, wingSpeed)
Turn(rightWing1, z_axis, 0, wingSpeed)
end
local function Moving()
Signal(SIG_Fly)
SetSignalMask(SIG_Fly)
StartThread(Fly)
Turn(leftFoot, x_axis, math.rad(-20), math.rad(420))
Turn(rightFoot, x_axis, math.rad(-20), math.rad(420))
Turn(leftShin, x_axis, math.rad(-40), math.rad(420))
Turn(rightShin, x_axis, math.rad(-40), math.rad(420))
end
function script.StartMoving()
isMoving = true
StartThread(Moving)
end
function script.StopMoving()
isMoving = false
StartThread(StopFly)
end
function script.Create()
EmitSfx(body, 1026)
EmitSfx(head, 1026)
EmitSfx(tail, 1026)
EmitSfx(firepoint, 1026)
EmitSfx(leftWing1, 1026)
EmitSfx(rightWing1, 1026)
EmitSfx(spike1, 1026)
EmitSfx(spike2, 1026)
EmitSfx(spike3, 1026)
Turn(spore1, x_axis, math.rad(90))
Turn(spore2, x_axis, math.rad(90))
Turn(spore3, x_axis, math.rad(90))
end
function script.AimFromWeapon(weaponNum)
if weaponNum == 1 then return firepoint
elseif weaponNum == 2 then return spore1
elseif weaponNum == 3 then return spore2
elseif weaponNum == 4 then return spore3
--elseif weaponNum == 5 then return body
else return body end
end
function script.AimWeapon(weaponNum, heading, pitch)
if weaponNum == 1 then
Signal(SIG_Aim)
SetSignalMask(SIG_Aim)
Turn(head, y_axis, heading, math.rad(250))
Turn(head, x_axis, pitch, math.rad(200))
WaitForTurn(head, y_axis)
WaitForTurn(head, x_axis)
StartThread(RestoreAfterDelay)
return true
elseif weaponNum >= 2 and weaponNum <= 4 then return true
else return false
end
end
function script.QueryWeapon(weaponNum)
if weaponNum == 1 then return firepoint
elseif weaponNum == 2 then return spore1
elseif weaponNum == 3 then return spore2
elseif weaponNum == 4 then return spore3
--elseif weaponNum == 5 then
-- if feet then return leftFoot
-- else return rightFoot end
else return body end
end
function script.FireWeapon(weaponNum)
if weaponNum == 1 then
Turn(lforearmu, y_axis, -bladeAngle, bladeExtendSpeed)
Turn(lbladeu, y_axis, bladeAngle, bladeExtendSpeed)
Turn(lforearml, y_axis, -bladeAngle, bladeExtendSpeed)
Turn(lbladel, y_axis, bladeAngle, bladeExtendSpeed)
Turn(rforearmu, y_axis, bladeAngle, bladeExtendSpeed)
Turn(rbladeu, y_axis, -bladeAngle, bladeExtendSpeed)
Turn(rforearml, y_axis, bladeAngle, bladeExtendSpeed)
Turn(rbladel, y_axis, -bladeAngle, bladeExtendSpeed)
Sleep(500)
Turn(lforearmu, y_axis, 0, bladeRetractSpeed)
Turn(lbladeu, y_axis, 0, bladeRetractSpeed)
Turn(lforearml, y_axis, 0, bladeRetractSpeed)
Turn(lbladel, y_axis, 0, bladeRetractSpeed)
Turn(rforearmu, y_axis, 0, bladeRetractSpeed)
Turn(rbladeu, y_axis, 0, bladeRetractSpeed)
Turn(rforearml, y_axis, 0, bladeRetractSpeed)
Turn(rbladel, y_axis, 0, bladeRetractSpeed)
--WaitForTurn(lbladeu, y_axis)
end
return true
end
function script.Killed(recentDamage, maxHealth)
EmitSfx(body, 1025)
Explode(body, sfxFall)
Explode(head, sfxFall)
Explode(tail, sfxFall)
Explode(leftWing1, sfxFall)
Explode(rightWing1, sfxFall)
Explode(spike1, sfxFall)
Explode(spike2, sfxFall)
Explode(spike3, sfxFall)
Explode(leftThigh, sfxFall)
Explode(rightThigh, sfxFall)
Explode(leftShin, sfxFall)
Explode(rightShin, sfxFall)
end
function script.HitByWeapon(x, z, weaponID, damage)
EmitSfx(body, 1024)
--return 100
end
| gpl-2.0 |
SnabbCo/snabbswitch | lib/luajit/testsuite/test/lang/meta/index.lua | 6 | 1077 | do --- table 1
local t=setmetatable({}, {__index=function(t,k)
return 100-k
end})
for i=1,100 do assert(t[i] == 100-i) end
for i=1,100 do t[i] = i end
for i=1,100 do assert(t[i] == i) end
for i=1,100 do t[i] = nil end
for i=1,100 do assert(t[i] == 100-i) end
end
do --- table 2
local x
local t2=setmetatable({}, {__index=function(t,k)
x = k
end})
assert(t2[1] == nil)
assert(x == 1)
assert(t2.foo == nil)
assert(x == "foo")
end
do --- userdata +lua<5.2
local u = newproxy(true)
getmetatable(u).__index = { foo = u, bar = 42 }
local x = 0
for i=1,100 do
x = x + u.bar
u = u.foo
end
assert(x == 4200)
x = 0
for i=1,100 do
u = u.foo
x = x + u.bar
end
assert(x == 4200)
end
do --- string
local s = "foo"
local mt = debug.getmetatable(s)
debug.setmetatable(s, {__index = {s = s, len = string.len}})
local x = 0
local t = {}
for i=1,100 do
x = x + s:len()
s = s.s
t[s] = t -- Hash store with same type prevents hoisting
end
debug.setmetatable(s, mt)
assert(x == 300)
end
| apache-2.0 |
davidmilligan/LrRamp | ramp.lrdevplugin/Info.lua | 1 | 1275 | --[[--------------------------------------------------------------
Copyright (C) 2015 David Milligan
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.
----------------------------------------------------------------]]
return
{
LrSdkVersion = 6.0,
LrSdkMinimumVersion = 6.0,
LrToolkitIdentifier = 'org.ml.ramp',
LrPluginName = LOC "$$$/Ramp/PluginName=LrRamp",
LrPluginInfoUrl = "https://github.com/davidmilligan/LrRamp",
LrExportMenuItems =
{
title = "Ramp",
file = "Ramp.lua",
},
--LrInitPlugin = 'RampInit.lua',
LrPluginInfoProvider = "RampInfoProvider.lua",
VERSION = { major=1, minor=0, revision=0, build=0, },
}
| gpl-2.0 |
OpenNMT/OpenNMT | hooks/chartokenization.lua | 4 | 1223 | local unicode = require('tools.utils.unicode')
local myopt =
{
{
'-mode', 'conservative',
[[Define how aggressive should the tokenization be. `aggressive` only keeps sequences
of letters/numbers, `conservative` allows a mix of alphanumeric as in: "2,000", "E65",
"soft-landing", etc. `space` is doing space tokenization. `char` is doing character tokenization]],
{
enum = {'space', 'conservative', 'aggressive', 'char'}
}
}
}
local function declareOptsFn(cmd)
cmd:setCmdLineOptions(myopt, 'Tokenizer')
end
local function mytokenization(opt, line)
-- fancy tokenization, it has to return a table of tokens (possibly with features)
if opt.mode == "char" then
local tokens = {}
for v, c, _ in unicode.utf8_iter(line) do
if unicode.isSeparator(v) then
table.insert(tokens, '▁')
else
table.insert(tokens, c)
end
end
return tokens
end
end
local function mydetokenization(opt, words, _)
if opt.mode == "char" then
return table.concat(words, ''):gsub('▁', ' ')
end
end
return {
tokenize = mytokenization,
detokenize = mydetokenization,
hookName = function() return "chartok" end,
declareOpts = declareOptsFn
}
| mit |
mtroyka/Zero-K | LuaUI/Widgets/gui_spotter.lua | 11 | 8605 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: gui_spotter.lua
-- brief: Draws smoothed polygons under units
-- author: metuslucidium (Orig. Dave Rodgers (orig. TeamPlatter edited by TradeMark))
--
-- Copyright (C) 2012.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Spotter",
desc = "Draws smoothed polys using fast glDrawListAtUnit",
author = "Orig. by 'TradeMark' - mod. by 'metuslucidium'", --updated with options for zk (CarRepairer)
date = "01.12.2012",
license = "GNU GPL, v2 or later",
layer = 5,
enabled = false -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function UpdateDrawList() end
options_path = 'Settings/Graphics/Unit Visibility/Spotter'
options = {
showEnemyCircle = {
name = 'Show Circle Around Enemies',
desc = 'Show a hard circle rround enemy units',
type = 'bool',
value = true,
noHotkey = true,
OnChange = function(self)
UpdateDrawList()
end
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Automatically generated local definitions
local GL_LINE_LOOP = GL.LINE_LOOP
local GL_TRIANGLE_FAN = GL.TRIANGLE_FAN
local glBeginEnd = gl.BeginEnd
local glColor = gl.Color
local glCreateList = gl.CreateList
local glDeleteList = gl.DeleteList
local glDepthTest = gl.DepthTest
local glDrawListAtUnit = gl.DrawListAtUnit
local glLineWidth = gl.LineWidth
local glPolygonOffset = gl.PolygonOffset
local glVertex = gl.Vertex
local spDiffTimers = Spring.DiffTimers
local spGetAllUnits = Spring.GetAllUnits
local spGetGroundNormal = Spring.GetGroundNormal
local spGetSelectedUnits = Spring.GetSelectedUnits
local spGetTeamColor = Spring.GetTeamColor
local spGetTimer = Spring.GetTimer
local spGetUnitDefDimensions = Spring.GetUnitDefDimensions
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitRadius = Spring.GetUnitRadius
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitViewPosition = Spring.GetUnitViewPosition
local spIsUnitSelected = Spring.IsUnitSelected
local spIsUnitVisible = Spring.IsUnitVisible
local spSendCommands = Spring.SendCommands
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local myTeamID = Spring.GetLocalTeamID()
local realRadii = {}
local circleDivs = 65 -- how precise circle? octagon by default
local innersize = 0.7 -- circle scale compared to unit radius
local outersize = 1.4 -- outer fade size compared to circle scale (1 = no outer fade)
local circlePoly = {}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Creating polygons, this is run once widget starts, create quads for each team colour:
UpdateDrawList = function()
for _,team in ipairs(Spring.GetTeamList()) do
local r, g, b = spGetTeamColor(team)
local alpha = 0.5
local fadealpha = 0.2
if (r == b) and (r == g) then -- increased alphas for greys/b/w
alpha = 0.7
fadealpha = 0.4
end
--Spring.Echo("Team", team, "R G B", r, g, b, "Alphas", alpha, fadealpha)
circlePoly[team] = glCreateList(function()
-- inner:
glBeginEnd(GL.TRIANGLES, function()
local radstep = (2.0 * math.pi) / circleDivs
for i = 1, circleDivs do
local a1 = (i * radstep)
local a2 = ((i+1) * radstep)
glColor(r, g, b, alpha)
glVertex(0, 0, 0)
glColor(r, g, b, fadealpha)
glVertex(math.sin(a1), 0, math.cos(a1))
glVertex(math.sin(a2), 0, math.cos(a2))
end
end)
-- outer edge:
glBeginEnd(GL.QUADS, function()
local radstep = (2.0 * math.pi) / circleDivs
for i = 1, circleDivs do
local a1 = (i * radstep)
local a2 = ((i+1) * radstep)
glColor(r, g, b, fadealpha)
glVertex(math.sin(a1), 0, math.cos(a1))
glVertex(math.sin(a2), 0, math.cos(a2))
glColor(r, g, b, 0.0)
glVertex(math.sin(a2) * outersize, 0, math.cos(a2) * outersize)
glVertex(math.sin(a1) * outersize, 0, math.cos(a1) * outersize)
end
end)
-- 'enemy spotter' red-yellow 'rainbow' part
if options.showEnemyCircle.value and not ( Spring.AreTeamsAllied(myTeamID, team) ) then
-- inner:
glBeginEnd(GL.QUADS, function()
local radstep = (2.0 * math.pi) / circleDivs
for i = 1, circleDivs do
local a1 = (i * radstep)
local a2 = ((i+1) * radstep)
glColor( 1, 1, 0, 0 )
glVertex(math.sin(a1) * (outersize + 0.8), 0, math.cos(a1) * (outersize + 0.8))
glVertex(math.sin(a2) * (outersize + 0.8), 0, math.cos(a2) * (outersize + 0.8))
glColor( 1, 1, 0, 0.33 )
glVertex(math.sin(a2) * (outersize + 0.9), 0, math.cos(a2) * (outersize + 0.9))
glVertex(math.sin(a1) * (outersize + 0.9), 0, math.cos(a1) * (outersize + 0.9))
end
end)
-- outer edge:
glBeginEnd(GL.QUADS, function()
local radstep = (2.0 * math.pi) / circleDivs
for i = 1, circleDivs do
local a1 = (i * radstep)
local a2 = ((i+1) * radstep)
glColor( 1, 1, 0, 0.33 )
glVertex(math.sin(a1) * (outersize + 0.9), 0, math.cos(a1) * (outersize + 0.9))
glVertex(math.sin(a2) * (outersize + 0.9), 0, math.cos(a2) * (outersize + 0.9))
glColor( 1, 0, 0, 0.33 )
glVertex(math.sin(a2) * (outersize + 1.0), 0, math.cos(a2) * (outersize + 1.0))
glVertex(math.sin(a1) * (outersize + 1.0), 0, math.cos(a1) * (outersize + 1.0))
end
end)
glBeginEnd(GL.QUADS, function()
local radstep = (2.0 * math.pi) / circleDivs
for i = 1, circleDivs do
local a1 = (i * radstep)
local a2 = ((i+1) * radstep)
glColor( 1, 0, 0, 0.33 )
glVertex(math.sin(a1) * (outersize + 1.0), 0, math.cos(a1) * (outersize + 1.0))
glVertex(math.sin(a2) * (outersize + 1.0), 0, math.cos(a2) * (outersize + 1.0))
glColor( 1, 0, 0, 0 )
glVertex(math.sin(a2) * (outersize + 1.1), 0, math.cos(a2) * (outersize + 1.1))
glVertex(math.sin(a1) * (outersize + 1.1), 0, math.cos(a1) * (outersize + 1.1))
end
end)
end
end)
end
end
function widget:Shutdown()
glDeleteList(circlePolysFoe)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Retrieving radius:
local function GetUnitDefRealRadius(udid)
local radius = realRadii[udid]
if (radius) then return radius end
local ud = UnitDefs[udid]
if (ud == nil) then return nil end
local dims = spGetUnitDefDimensions(udid)
if (dims == nil) then return nil end
local scale = ud.hitSphereScale -- missing in 0.76b1+
scale = ((scale == nil) or (scale == 0.0)) and 1.0 or scale
radius = dims.radius / scale
realRadii[udid] = radius*innersize
return radius
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
UpdateDrawList()
end
--[[if (spIsUnitSelected (unitID)) then -- for debuggin' sizes/colours
Spring.Echo (radius)
end]]
-- Drawing:
function widget:DrawWorldPreUnit()
glDepthTest(true)
glPolygonOffset(-10000, -2) -- draw on top of water/map - sideeffect: will shine through terrain/mountains
for _,unitID in ipairs(Spring.GetVisibleUnits()) do
local team = spGetUnitTeam(unitID)
if (team) then
local radius = GetUnitDefRealRadius(spGetUnitDefID(unitID))
if (radius) then
if radius < 28 then
radius = radius + 5
end
glDrawListAtUnit(unitID, circlePoly[team], false, radius, 1.0, radius)
end
end
end
glColor(1,1,1,1)
end
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------- | gpl-2.0 |
mason-larobina/luakit | lib/adblock.lua | 1 | 18407 | --- Simple URI-based content filter.
--
-- This is a simple, fast ad blocker module that works by blocking requests to
-- domains that only serve advertisements. It does not currently do any form of
-- cosmetic ad blocking (i.e. element hiding with CSS).
--
-- See also: @ref{adblock_chrome}.
--
-- # Capabilities
--
-- * You can allow specific content to be loaded if it is inadvertently
-- blocked: simply add whitelisting rules formed by `@@` and the pattern to
-- allow.
-- * Supports multiple filter list files.
-- * Filter files can be enabled, disabled and reloaded from disk
-- without restarting luakit.
-- * A configuration chrome page is provided by @ref{adblock_chrome}.
--
-- # Usage
--
-- * Add `require "adblock"` and `require "adblock_chrome"` to your `config.rc`.
-- * Download AdblockPlus-compatible filter lists to the adblock directory.
-- Multiple lists are supported.
-- EasyList is the most popular Adblock Plus filter list, and can be
-- downloaded from [https://easylist.to/](https://easylist.to/).
-- * Filter lists downloaded to the adblock directory must have a
-- filename ending in `.txt` in order to be loaded.
-- * Filter lists need to be updated regularly (~weekly), use cron!
--
-- # Troubleshooting
--
-- If ad blocking is not working as expected, the easiest way to determine
-- what is happening is to set the appropriate log levels to `debug`:
--
-- If a filterlist is not being loaded for some reason, start luakit with
-- the following:
--
-- --log=lua/lib/adblock=debug
--
-- If a filterlist is not behaving correctly, by blocking too much or too
-- little, start luakit with the following:
--
-- --log=lua/lib/adblock_wm=debug
--
-- # Files and Directories
--
-- - All filterlists should be downloaded to the adblock data directory.
-- By default, this is the `adblock` sub-directory of the luakit data
-- directory. All filterlists must have a filename ending in `.txt`.
--
-- @module adblock
-- @author Chris van Dijk (quigybo) <quigybo@hotmail.com>
-- @author Mason Larobina (mason-l) <mason.larobina@gmail.com>
-- @author Plaque FCC <Reslayer@ya.ru>
-- @copyright 2010 Chris van Dijk <quigybo@hotmail.com>
-- @copyright 2010 Mason Larobina <mason.larobina@gmail.com>
-- @copyright 2012 Plaque FCC <Reslayer@ya.ru>
local webview = require("webview")
local window = require("window")
local lousy = require("lousy")
local util = lousy.util
local lfs = require("lfs")
local modes = require("modes")
local add_cmds = modes.add_cmds
local _M = {}
local adblock_wm = require_web_module("adblock_wm")
-- Adblock Plus compatible filter lists.
local adblock_dir = luakit.data_dir .. "/adblock/"
local filterfiles = {}
local subscriptions_file = adblock_dir .. "subscriptions"
--- The set of ad blocking subscriptions that are active.
-- @type table
-- @readonly
_M.subscriptions = {}
--- String patterns to filter URIs with.
-- @type table
-- @readonly
_M.rules = {}
--- Fitting for adblock.chrome.refresh_views()
-- @local
_M.refresh_views = function()
-- Dummy.
end
-- Detect files to read rules from
local function detect_files()
-- Create adblock directory if it doesn't exist
local curdir = lfs.currentdir()
if not lfs.chdir(adblock_dir) then
lfs.mkdir(adblock_dir)
else
lfs.chdir(curdir)
end
msg.verbose("searching for filter lists in %s", adblock_dir)
for filename in lfs.dir(adblock_dir) do
if string.find(filename, "%.txt$") then
msg.verbose("found filter list: " .. filename)
table.insert(filterfiles, filename)
end
end
msg.info("found " .. #filterfiles .. " filter list" .. (#filterfiles == 1 and "" or "s"))
end
local function get_abp_opts(s)
local opts = {}
local pos = string.find(s, "%$")
if pos then
local op = string.sub(s, pos+1)
s = string.sub(s, 1, pos-1)
for key in string.gmatch(op, "[^,]+") do
local val
local p = string.find(key, "=")
if p then
val = string.sub(key, p+1)
key = string.sub(key, 1, p-1)
end
local negative = false
if string.sub(key, 1, 1) == "~" then
negative = true
key = string.sub(key, 2)
end
if key == "domain" and val then
local domains = {}
for v in string.gmatch(val, "[^|]+") do
table.insert(domains, v)
end
if #domains > 0 then opts["domain"] = domains end
elseif key == "third-party" then
opts["third-party"] = not negative
else
opts["unknown"] = true
end
end
end
return s, opts
end
-- Convert Adblock Plus filter description to lua string pattern
-- See http://adblockplus.org/en/filters for more information
local abp_to_pattern = function (s)
-- Strip filter options
local opts
s, opts = get_abp_opts(s)
if opts and opts.unknown == true then return {} end -- Skip rules with unknown options
local domain = nil
if string.len(s) > 0 then
-- If this is matchable as a plain string, return early
local has_star = string.find(s, "*", 1, true)
local has_caret = string.find(s, "^", 1, true)
local domain_anchor = string.match(s, "^||")
if not has_star and not has_caret and not domain_anchor then
return {s}, opts, nil, true
end
-- Optimize for domain anchor rules
if string.match(s, "^||") then
-- Extract the domain from the pattern
local d = string.sub(s, 3)
d = string.gsub(d, "/.*", "")
d = string.gsub(d, "%^.*", "")
-- We don't bother with wildcard domains since they aren't frequent enough
if not string.find(d, "*") then
domain = d
end
end
-- Protect magic characters (^$()%.[]*+-?) not used by ABP (^$()[]*)
s = string.gsub(s, "([%%%.%+%-%?])", "%%%1")
-- Wildcards are globbing
s = string.gsub(s, "%*", "%.%*")
-- Caret is separator (anything but a letter, a digit, or one of the following:Â - . %)
s = string.gsub(s, "%^", "[^%%w%%-%%.%%%%]")
if domain_anchor then
local p = string.sub(s, 3) -- Clip off first two || characters
s = { "^https?://" .. p, "^https?://[^/]*%." .. p }
else
s = { s }
end
for k, v in ipairs(s) do
-- Pipe is anchor
v = string.gsub(v, "^|", "%^")
v = string.gsub(v, "|$", "%$")
-- Convert to lowercase ($match-case option is not honoured)
v = string.lower(v)
s[k] = v
end
else
s = {""}
end
return s, opts, domain, false
end
local add_unique_cached = function (pattern, opts, tab, cache_tab)
if cache_tab[pattern] then
return false
else
--cache_tab[pattern], tab[pattern] = true, pattern
cache_tab[pattern], tab[pattern] = true, opts
return true
end
end
local list_new = function ()
return {
patterns = {},
ad_patterns = {},
plain = {},
ad_plain = {},
domains = {},
length = 0,
ignored = 0,
}
end
local list_add = function(list, line, cache, pat_exclude)
local pats, opts, domain, plain = abp_to_pattern(line)
local contains_ad = string.find(line, "ad", 1, true)
for _, pat in ipairs(pats) do
local new
if plain then
local bucket = contains_ad and list.ad_plain or list.plain
new = add_unique_cached(pat, opts, bucket, cache)
elseif pat ~= "^http:" and pat ~= pat_exclude then
if domain then
if not list.domains[domain] then
list.domains[domain] = {}
end
new = add_unique_cached(pat, opts, list.domains[domain], cache)
else
local bucket = contains_ad and list.ad_patterns or list.patterns
new = add_unique_cached(pat, opts, bucket, cache)
end
end
if new then
list.length = list.length + 1
else
list.ignored = list.ignored + 1
end
end
end
-- Parses an Adblock Plus compatible filter list
local parse_abpfilterlist = function (filters_dir, filename, cache)
if os.exists(filters_dir .. filename) then
msg.verbose("loading filter list %s", filename)
else
msg.warn("error loading filter list (%s: no such file or directory)", filename)
end
filename = filters_dir .. filename
local white, black = list_new(), list_new()
for line in io.lines(filename) do
-- Ignore comments, header and blank lines
if line:match("^[![]") or line:match("^$") or line:match("^# ") or line:match("^#$") then
-- dammitwhydoesntluahaveacontinuestatement
-- Ignore element hiding
elseif line:match("##") or line:match("#@#") then
--icnt = icnt + 1
elseif line:match("^@@") then
list_add(white, string.sub(line, 3), cache.white)
else
list_add(black, line, cache.black, ".*")
end
end
local wlen, blen, icnt = white.length, black.length, white.ignored + black.ignored
return white, black, wlen, blen, icnt
end
--- Save the in-memory subscriptions to flatfile.
-- @tparam string file The destination file or the default location if nil.
local function write_subscriptions(file)
if not file then file = subscriptions_file end
assert(file and file ~= "", "Cannot write subscriptions to empty path")
local lines = {}
for _, filename in ipairs(filterfiles) do
local list = _M.subscriptions[filename]
local subs = { uri = list.uri, title = list.title, opts = table.concat(list.opts or {}, " "), }
local line = string.gsub("{title}\t{uri}\t{opts}", "{(%w+)}", subs)
table.insert(lines, line)
end
-- Write table to disk
local fh = io.open(file, "w")
fh:write(table.concat(lines, "\n"))
io.close(fh)
end
-- Remove options and add new ones to list
-- @param list_index Index of the list to modify
-- @param opt_ex Options to exclude
-- @param opt_inc Options to include
local function list_opts_modify(list_index, opt_ex, opt_inc)
assert(type(list_index) == "number", "list options modify: invalid list index")
assert(list_index > 0, "list options modify: index has to be > 0")
if not opt_ex then opt_ex = {} end
if not opt_inc then opt_inc = {} end
if type(opt_ex) == "string" then opt_ex = util.string.split(opt_ex) end
if type(opt_inc) == "string" then opt_inc = util.string.split(opt_inc) end
local list = util.table.values(_M.subscriptions)[list_index]
local opts = opt_inc
for _, opt in ipairs(list.opts) do
if not util.table.hasitem(opt_ex, opt) then
table.insert(opts, opt)
end
end
-- Manage list's rules
if util.table.hasitem(opt_inc, "Enabled") then
adblock_wm:emit_signal("list_set_enabled", list.title, true)
_M.refresh_views()
elseif util.table.hasitem(opt_inc, "Disabled") then
adblock_wm:emit_signal("list_set_enabled", list.title, false)
_M.refresh_views()
end
list.opts = opts
write_subscriptions()
end
--- Add a list to the in-memory lists table
local function add_list(uri, title, opts, replace, save_lists)
assert( (title ~= nil) and (title ~= ""), "adblock list add: no title given")
if not opts then opts = {} end
-- Create tags table from string
if type(opts) == "string" then opts = util.string.split(opts) end
if table.maxn(opts) == 0 then table.insert(opts, "Disabled") end
if not replace and _M.subscriptions[title] then
local list = _M.subscriptions[title]
-- Merge tags
for _, opt in ipairs(opts) do
if not util.table.hasitem(list, opt) then table.insert(list, opt) end
end
else
-- Insert new adblock list
_M.subscriptions[title] = { uri = uri, title = title, opts = opts }
end
-- Save by default
if save_lists ~= false then write_subscriptions() end
end
--- Load subscriptions from a flatfile to memory.
-- @tparam string file The subscriptions file or the default subscriptions location if nil.
local function read_subscriptions(file)
-- Find a subscriptions file
if not file then file = subscriptions_file end
if not os.exists(file) then
msg.info(string.format("subscriptions file '%s' doesn't exist", file))
return
end
-- Read lines into subscriptions data table
for line in io.lines(file) do
local title, uri, opts = unpack(util.string.split(line, "\t"))
if title ~= "" and os.exists(adblock_dir..title) then
add_list(uri, title, opts, false, false)
end
end
end
--- Load filter list files, and refresh any adblock pages that are open.
-- @tparam boolean reload `true` if all subscriptions already loaded
-- should be fully reloaded.
-- @tparam string single_list Single list file.
-- @tparam boolean no_sync `true` if subscriptions should not be synchronized to
-- the web process.
_M.load = function (reload, single_list, no_sync)
if reload then _M.subscriptions, filterfiles = {}, {} end
detect_files()
if not single_list then
read_subscriptions()
for _, filename in ipairs(filterfiles) do
local list = _M.subscriptions[filename]
if not list then
add_list(list and list.uri or "", filename, "Enabled", true, false)
end
end
write_subscriptions()
end
-- [re-]loading:
if reload then _M.rules = {} end
local filters_dir = adblock_dir
local filterfiles_loading
if single_list and not reload then
filterfiles_loading = { single_list }
else
filterfiles_loading = filterfiles
end
local rules_cache = {
black = {},
white = {}
} -- This cache should let us avoid unnecessary filters duplication.
for _, filename in ipairs(filterfiles_loading) do
local white, black, wlen, blen, icnt = parse_abpfilterlist(filters_dir, filename, rules_cache)
local list = _M.subscriptions[filename]
if not util.table.hasitem(_M.rules, list) then
_M.rules[filename] = list
end
list.title, list.white, list.black, list.ignored = filename, wlen or 0, blen or 0, icnt or 0
list.whitelist, list.blacklist = white or {}, black or {}
end
if not no_sync and not single_list then
adblock_wm:emit_signal("update_rules", _M.rules)
end
_M.refresh_views()
end
--- Enable or disable an adblock filter list.
-- @tparam number|string a The number of the list to enable or disable.
-- @tparam boolean enabled `true` to enable, `false` to disable.
function _M.list_set_enabled(a, enabled)
if enabled then
list_opts_modify(tonumber(a), "Disabled", "Enabled")
else
list_opts_modify(tonumber(a), "Enabled", "Disabled")
end
end
local page_whitelist = {}
--- Whitelist accessing a blocked domain for the current session.
-- @tparam string domain The domain to whitelist.
_M.whitelist_domain_access = function (domain)
if lousy.util.table.hasitem(page_whitelist, domain) then return end
table.insert(page_whitelist, domain)
adblock_wm:emit_signal("update_page_whitelist", page_whitelist)
end
local new_web_extension_created
webview.add_signal("init", function (view)
webview.modify_load_block(view, "adblock", _M.enabled)
view:add_signal("web-extension-loaded", function (v)
if not new_web_extension_created then
webview.modify_load_block(v, "adblock", false)
end
new_web_extension_created = nil
end)
-- if adblocking is disabled, unblock the tab as soon as it's switched to
local function unblock(vv)
if not _M.enabled then
webview.modify_load_block(vv, "adblock", false)
end
vv:remove_signal("switched-page", unblock)
end
view:add_signal("switched-page", unblock)
end)
adblock_wm:add_signal("rules_updated", function (_, web_process_id)
for _, ww in pairs(window.bywidget) do
for _, v in pairs(ww.tabs.children) do
if v.web_process_id == web_process_id then
webview.modify_load_block(v, "adblock", false)
end
end
end
end)
luakit.add_signal("web-extension-created", function (view)
new_web_extension_created = true
adblock_wm:emit_signal(view, "update_rules", _M.rules)
for name, list in pairs(_M.rules) do
local enabled = util.table.hasitem(list.opts, "Enabled")
adblock_wm:emit_signal(view, "list_set_enabled", name, enabled)
end
end)
-- Add commands.
add_cmds({
{ ":adblock-reload, :abr", "Reload adblock filters.", function (w)
_M.load(true)
w:notify("adblock: Reloading filters complete.")
end },
{ ":adblock-list-enable, :able", "Enable an adblock filter list.",
function (_, o) _M.list_set_enabled(o.arg, true) end },
{ ":adblock-list-disable, :abld", "Disable an adblock filter list.",
function (_, o) _M.list_set_enabled(o.arg, false) end },
{ ":adblock-enable, :abe", "Enable ad blocking.",
function () _M.enabled = true end },
{ ":adblock-disable, :abd", "Disable ad blocking.",
function () _M.enabled = false end },
})
-- Initialise module
_M.load(nil, nil, true)
--- @property enabled
-- Whether ad blocking is enabled. Modifying this value will modify adblock
-- state; setting it to `true` will enable ad blocking, while setting it to
-- `false` will disable ad blocking.
-- @readwrite
-- @default true
-- @type boolean
local wrapped = { enabled = true }
local mt = {
__index = wrapped,
__newindex = function (_, k, v)
if k == "enabled" then
assert(type(v) == "boolean", "property 'enabled' must be boolean")
wrapped.enabled = v
adblock_wm:emit_signal("enable", v)
_M.refresh_views()
end
end,
}
return setmetatable(_M, mt)
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
thedraked/darkstar | scripts/zones/Buburimu_Peninsula/npcs/Hieroglyphics.lua | 7 | 2551 | -----------------------------------
-- Area: Buburimu_Peninsula
-- NPC: Hieroglyphics
-- Dynamis Buburimu_Dunes Enter
-- @pos 117 -10 133 172 118
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/globals/missions");
require("scripts/zones/Buburimu_Peninsula/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasCompletedMission(COP,DARKNESS_NAMED) or FREE_COP_DYNAMIS == 1) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if (checkFirstDyna(player,8)) then
player:startEvent(0x002B);
elseif (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaBuburimu]UniqueID")) then
player:startEvent(0x0016,8,0,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
--printf("dayRemaining : %u",dayRemaining );
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,8);
end
else
player:messageSpecial(MYSTERIOUS_VOICE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("finishRESULT: %u",option);
if (csid == 0x0021) then
if (checkFirstDyna(player,8)) then
player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 256);
end
elseif (csid == 0x0016 and option == 0) then
player:setPos(155,-1,-169,170,0x28);
end
end; | gpl-3.0 |
mamaddeveloper/7894 | plugins/savef.lua | 1 | 1101 | local function savefile(extra, success, result)
local msg = extra.msg
local name = extra.name
local adress = extra.adress
local receiver = get_receiver(msg)
if success then
local file = './'..adress..'/'..name..''
print('File saving to:', result)
os.rename(result, file)
print('File moved to:', file)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function run(msg,matches)
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
local adress = matches[2]
local name = matches[3]
if matches[1] == "file" and matches[2] and matches[3] and is_sudo(msg) then
load_document(msg.reply_id, savefile, {msg=msg,name=name,adress=adress})
return 'File '..name..' has been saved in: \n./'..adress
end
if not is_sudo(msg) then
return "only for sudo!"
end
end
end
return {
patterns = {
"^[!/#]([Ff]ile) (.*) (.*)$",
"^([Ff]ile) (.*) (.*)$"
},
run = run,
} | gpl-2.0 |
bjornbytes/lust | lust.lua | 1 | 5780 | -- lust v0.1.0 - Lua test framework
-- https://github.com/bjornbytes/lust
-- MIT LICENSE
local lust = {}
lust.level = 0
lust.passes = 0
lust.errors = 0
lust.befores = {}
lust.afters = {}
local red = string.char(27) .. '[31m'
local green = string.char(27) .. '[32m'
local normal = string.char(27) .. '[0m'
local function indent(level) return string.rep('\t', level or lust.level) end
function lust.nocolor()
red, green, normal = '', '', ''
return lust
end
function lust.describe(name, fn)
print(indent() .. name)
lust.level = lust.level + 1
fn()
lust.befores[lust.level] = {}
lust.afters[lust.level] = {}
lust.level = lust.level - 1
end
function lust.it(name, fn)
for level = 1, lust.level do
if lust.befores[level] then
for i = 1, #lust.befores[level] do
lust.befores[level][i](name)
end
end
end
local success, err = pcall(fn)
if success then lust.passes = lust.passes + 1
else lust.errors = lust.errors + 1 end
local color = success and green or red
local label = success and 'PASS' or 'FAIL'
print(indent() .. color .. label .. normal .. ' ' .. name)
if err then
print(indent(lust.level + 1) .. red .. err .. normal)
end
for level = 1, lust.level do
if lust.afters[level] then
for i = 1, #lust.afters[level] do
lust.afters[level][i](name)
end
end
end
end
function lust.before(fn)
lust.befores[lust.level] = lust.befores[lust.level] or {}
table.insert(lust.befores[lust.level], fn)
end
function lust.after(fn)
lust.afters[lust.level] = lust.afters[lust.level] or {}
table.insert(lust.afters[lust.level], fn)
end
-- Assertions
local function isa(v, x)
if type(x) == 'string' then
return type(v) == x,
'expected ' .. tostring(v) .. ' to be a ' .. x,
'expected ' .. tostring(v) .. ' to not be a ' .. x
elseif type(x) == 'table' then
if type(v) ~= 'table' then
return false,
'expected ' .. tostring(v) .. ' to be a ' .. tostring(x),
'expected ' .. tostring(v) .. ' to not be a ' .. tostring(x)
end
local seen = {}
local meta = v
while meta and not seen[meta] do
if meta == x then return true end
seen[meta] = true
meta = getmetatable(meta) and getmetatable(meta).__index
end
return false,
'expected ' .. tostring(v) .. ' to be a ' .. tostring(x),
'expected ' .. tostring(v) .. ' to not be a ' .. tostring(x)
end
error('invalid type ' .. tostring(x))
end
local function has(t, x)
for k, v in pairs(t) do
if v == x then return true end
end
return false
end
local function strict_eq(t1, t2)
if type(t1) ~= type(t2) then return false end
if type(t1) ~= 'table' then return t1 == t2 end
for k, _ in pairs(t1) do
if not strict_eq(t1[k], t2[k]) then return false end
end
for k, _ in pairs(t2) do
if not strict_eq(t2[k], t1[k]) then return false end
end
return true
end
local paths = {
[''] = { 'to', 'to_not' },
to = { 'have', 'equal', 'be', 'exist', 'fail' },
to_not = { 'have', 'equal', 'be', 'exist', 'fail', chain = function(a) a.negate = not a.negate end },
a = { test = isa },
an = { test = isa },
be = { 'a', 'an', 'truthy',
test = function(v, x)
return v == x,
'expected ' .. tostring(v) .. ' and ' .. tostring(x) .. ' to be equal',
'expected ' .. tostring(v) .. ' and ' .. tostring(x) .. ' to not be equal'
end
},
exist = {
test = function(v)
return v ~= nil,
'expected ' .. tostring(v) .. ' to exist',
'expected ' .. tostring(v) .. ' to not exist'
end
},
truthy = {
test = function(v)
return v,
'expected ' .. tostring(v) .. ' to be truthy',
'expected ' .. tostring(v) .. ' to not be truthy'
end
},
equal = {
test = function(v, x)
return strict_eq(v, x),
'expected ' .. tostring(v) .. ' and ' .. tostring(x) .. ' to be exactly equal',
'expected ' .. tostring(v) .. ' and ' .. tostring(x) .. ' to not be exactly equal'
end
},
have = {
test = function(v, x)
if type(v) ~= 'table' then
error('expected ' .. tostring(v) .. ' to be a table')
end
return has(v, x),
'expected ' .. tostring(v) .. ' to contain ' .. tostring(x),
'expected ' .. tostring(v) .. ' to not contain ' .. tostring(x)
end
},
fail = {
test = function(v)
return not pcall(v),
'expected ' .. tostring(v) .. ' to fail',
'expected ' .. tostring(v) .. ' to not fail'
end
}
}
function lust.expect(v)
local assertion = {}
assertion.val = v
assertion.action = ''
assertion.negate = false
setmetatable(assertion, {
__index = function(t, k)
if has(paths[rawget(t, 'action')], k) then
rawset(t, 'action', k)
local chain = paths[rawget(t, 'action')].chain
if chain then chain(t) end
return t
end
return rawget(t, k)
end,
__call = function(t, ...)
if paths[t.action].test then
local res, err, nerr = paths[t.action].test(t.val, ...)
if assertion.negate then
res = not res
err = nerr or err
end
if not res then
error(err or 'unknown failure', 2)
end
end
end
})
return assertion
end
function lust.spy(target, name, run)
local spy = {}
local subject
local function capture(...)
table.insert(spy, {...})
return subject(...)
end
if type(target) == 'table' then
subject = target[name]
target[name] = capture
else
run = name
subject = target or function() end
end
setmetatable(spy, {__call = function(_, ...) return capture(...) end})
if run then run() end
return spy
end
lust.test = lust.it
lust.paths = paths
return lust
| mit |
X-Coder/wire | lua/entities/gmod_wire_cd_lock.lua | 10 | 2953 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire CD Lock"
ENT.WireDebugName = "CD Lock"
if CLIENT then return end -- No more client
//Time after losing one disk to search for another
local NEW_DISK_WAIT_TIME = 2
local DISK_IN_SOCKET_CONSTRAINT_POWER = 5000
local DISK_IN_ATTACH_RANGE = 16
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.Const = nil
self.Disk = nil
self.DisableLinking = 0
self.Inputs = Wire_CreateInputs(self, { "Disable" })
self.Outputs = Wire_CreateOutputs(self, { "Locked" })
self:NextThink(CurTime() + 0.25)
end
function ENT:TriggerInput(iname, value)
if (iname == "Disable") then
self.DisableLinking = value
if (value >= 1) and (self.Const) then
self.Const:Remove()
//self.NoCollideConst:Remove()
self.Const = nil
self.Disk.Lock = nil
self.Disk = nil
//self.NoCollideConst = nil
Wire_TriggerOutput(self, "Locked", 0)
self:NextThink(CurTime() + NEW_DISK_WAIT_TIME)
end
end
end
function ENT:Think()
self.BaseClass.Think(self)
// If we were undiskged, reset the disk and socket to accept new ones.
if (self.Const) and (not self.Const:IsValid()) then
self.Const = nil
self.Disk.Lock = nil
self.Disk = nil
self.NoCollideConst = nil
Wire_TriggerOutput(self, "Locked", 0)
self:NextThink(CurTime() + NEW_DISK_WAIT_TIME) //Give time before next grabbing a disk.
return true
else
if (self.DisableLinking < 1) and (self.Disk == nil) then
// Find entities near us
local lockCenter = self:LocalToWorld(Vector(0, 0, 0))
local local_ents = ents.FindInSphere(lockCenter, DISK_IN_ATTACH_RANGE)
for key, disk in pairs(local_ents) do
// If we find a disk, try to attach it to us
if (disk:IsValid() && disk:GetClass() == "gmod_wire_cd_disk") then
if (disk.Lock == nil) then
self:AttachDisk(disk)
end
end
end
end
end
self:NextThink(CurTime() + 0.25)
end
function ENT:AttachDisk(disk)
//Position disk
local min = disk:OBBMins()
local max = disk:OBBMaxs()
local newpos = self:LocalToWorld(Vector(0, 0, 0))
local lockAng = self:GetAngles()
disk:SetPos(newpos)
disk:SetAngles(lockAng)
self.NoCollideConst = constraint.NoCollide(self, disk, 0, 0)
if (not self.NoCollideConst) then
Wire_TriggerOutput(self, "Locked", 0)
return
end
//Constrain together
self.Const = constraint.Weld(self, disk, 0, 0, DISK_IN_SOCKET_CONSTRAINT_POWER, true)
if (not self.Const) then
self.NoCollideConst:Remove()
self.NoCollideConst = nil
Wire_TriggerOutput(self, "Locked", 0)
return
end
//Prepare clearup incase one is removed
disk:DeleteOnRemove(self.Const)
self:DeleteOnRemove(self.Const)
self.Const:DeleteOnRemove(self.NoCollideConst)
disk.Lock = self
self.Disk = disk
Wire_TriggerOutput(self, "Locked", 1)
end
duplicator.RegisterEntityClass("gmod_wire_cd_lock", WireLib.MakeWireEnt, "Data")
| gpl-3.0 |
jhasse/wxFormBuilder | build/premake/4.3/tests/test_targets.lua | 9 | 7216 | --
-- tests/test_targets.lua
-- Automated test suite for premake.gettarget()
-- Copyright (c) 2008, 2009 Jason Perkins and the Premake project
--
T.targets = { }
local cfg
function T.targets.setup()
cfg = { }
cfg.basedir = "."
cfg.location = "."
cfg.targetdir = "../bin"
cfg.language = "C++"
cfg.project = { name = "MyProject" }
cfg.flags = { }
cfg.objectsdir = "obj"
cfg.platform = "Native"
end
--
-- Path Style Name Style Example Environment
-- ---------- ---------- -------------------
-- windows windows VStudio with MSC
-- posix posix GMake with GCC
-- windows posix VStudio for PS3
-- posix windows GMake for .NET
--
--
-- ConsoleApp tests
--
function T.targets.ConsoleApp_Build_WindowsNames()
cfg.kind = "ConsoleApp"
result = premake.gettarget(cfg, "build", "posix", "windows", "macosx")
test.isequal([[../bin/MyProject.exe]], result.fullpath)
end
function T.targets.ConsoleApp_Build_PosixNames_OnWindows()
cfg.kind = "ConsoleApp"
result = premake.gettarget(cfg, "build", "posix", "posix", "windows")
test.isequal([[../bin/MyProject.exe]], result.fullpath)
end
function T.targets.ConsoleApp_Build_PosixNames_OnLinux()
cfg.kind = "ConsoleApp"
result = premake.gettarget(cfg, "build", "posix", "posix", "linux")
test.isequal([[../bin/MyProject]], result.fullpath)
end
function T.targets.ConsoleApp_Build_PosixNames_OnMacOSX()
cfg.kind = "ConsoleApp"
result = premake.gettarget(cfg, "build", "posix", "posix", "macosx")
test.isequal([[../bin/MyProject]], result.fullpath)
end
function T.targets.ConsoleApp_Build_PS3Names()
cfg.kind = "ConsoleApp"
result = premake.gettarget(cfg, "build", "posix", "PS3", "macosx")
test.isequal([[../bin/MyProject.elf]], result.fullpath)
end
--
-- WindowedApp tests
--
function T.targets.WindowedApp_Build_WindowsNames()
cfg.kind = "WindowedApp"
result = premake.gettarget(cfg, "build", "posix", "windows", "macosx")
test.isequal([[../bin/MyProject.exe]], result.fullpath)
end
function T.targets.WindowedApp_Build_PosixNames_OnWindows()
cfg.kind = "WindowedApp"
result = premake.gettarget(cfg, "build", "posix", "posix", "windows")
test.isequal([[../bin/MyProject.exe]], result.fullpath)
end
function T.targets.WindowedApp_Build_PosixNames_OnLinux()
cfg.kind = "WindowedApp"
result = premake.gettarget(cfg, "build", "posix", "posix", "linux")
test.isequal([[../bin/MyProject]], result.fullpath)
end
function T.targets.WindowedApp_Build_PosixNames_OnMacOSX()
cfg.kind = "WindowedApp"
result = premake.gettarget(cfg, "build", "posix", "posix", "macosx")
test.isequal([[../bin/MyProject.app/Contents/MacOS/MyProject]], result.fullpath)
end
function T.targets.WindowedApp_Build_PS3Names()
cfg.kind = "WindowedApp"
result = premake.gettarget(cfg, "build", "posix", "PS3", "macosx")
test.isequal([[../bin/MyProject.elf]], result.fullpath)
end
--
-- SharedLib tests
--
function T.targets.SharedLib_Build_WindowsNames()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "build", "posix", "windows", "macosx")
test.isequal([[../bin/MyProject.dll]], result.fullpath)
end
function T.targets.SharedLib_Link_WindowsNames()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "link", "posix", "windows", "macosx")
test.isequal([[../bin/MyProject.lib]], result.fullpath)
end
function T.targets.SharedLib_Build_PosixNames_OnWindows()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "build", "posix", "posix", "windows")
test.isequal([[../bin/MyProject.dll]], result.fullpath)
end
function T.targets.SharedLib_Link_PosixNames_OnWindows()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "link", "posix", "posix", "windows")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.SharedLib_Build_PosixNames_OnLinux()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "build", "posix", "posix", "linux")
test.isequal([[../bin/libMyProject.so]], result.fullpath)
end
function T.targets.SharedLib_Link_PosixNames_OnLinux()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "link", "posix", "posix", "linux")
test.isequal([[../bin/libMyProject.so]], result.fullpath)
end
function T.targets.SharedLib_Build_PosixNames_OnMacOSX()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "build", "posix", "posix", "macosx")
test.isequal([[../bin/libMyProject.dylib]], result.fullpath)
end
function T.targets.SharedLib_Link_PosixNames_OnMacOSX()
cfg.kind = "SharedLib"
result = premake.gettarget(cfg, "link", "posix", "posix", "macosx")
test.isequal([[../bin/libMyProject.dylib]], result.fullpath)
end
--
-- StaticLib tests
--
function T.targets.StaticLib_Build_WindowsNames()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "build", "posix", "windows", "macosx")
test.isequal([[../bin/MyProject.lib]], result.fullpath)
end
function T.targets.StaticLib_Link_WindowsNames()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "link", "posix", "windows", "macosx")
test.isequal([[../bin/MyProject.lib]], result.fullpath)
end
function T.targets.StaticLib_Build_PosixNames_OnWindows()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "build", "posix", "posix", "windows")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.StaticLib_Link_PosixNames_OnWindows()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "link", "posix", "posix", "windows")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.StaticLib_Build_PosixNames_OnLinux()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "build", "posix", "posix", "linux")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.StaticLib_Link_PosixNames_OnLinux()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "link", "posix", "posix", "linux")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.StaticLib_Build_PosixNames_OnMacOSX()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "build", "posix", "posix", "macosx")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.StaticLib_Link_PosixNames_OnMacOSX()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "link", "posix", "posix", "macosx")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.StaticLib_Build_PosixNames_OnPS3()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "build", "posix", "PS3", "macosx")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
function T.targets.StaticLib_Link_PosixNames_OnPS3()
cfg.kind = "StaticLib"
result = premake.gettarget(cfg, "link", "posix", "PS3", "macosx")
test.isequal([[../bin/libMyProject.a]], result.fullpath)
end
--
-- Windows path tests
--
function T.targets.WindowsPaths()
cfg.kind = "ConsoleApp"
result = premake.gettarget(cfg, "build", "windows", "windows", "linux")
test.isequal([[..\bin]], result.directory)
test.isequal([[..\bin\MyProject.exe]], result.fullpath)
end | gpl-2.0 |
SnabbCo/snabbswitch | src/program/snabbvmx/lwaftr/setup.lua | 7 | 20675 | module(..., package.seeall)
local PcapFilter = require("apps.packet_filter.pcap_filter").PcapFilter
local V4V6 = require("apps.lwaftr.V4V6").V4V6
local VhostUser = require("apps.vhost.vhost_user").VhostUser
local basic_apps = require("apps.basic.basic_apps")
local bt = require("apps.lwaftr.binding_table")
local config = require("core.config")
local ethernet = require("lib.protocol.ethernet")
local ipv4_echo = require("apps.ipv4.echo")
local ipv4_fragment = require("apps.ipv4.fragment")
local ipv4_reassemble = require("apps.ipv4.reassemble")
local ipv6_echo = require("apps.ipv6.echo")
local ipv6_fragment = require("apps.ipv6.fragment")
local ipv6_reassemble = require("apps.ipv6.reassemble")
local lib = require("core.lib")
local lwaftr = require("apps.lwaftr.lwaftr")
local lwutil = require("apps.lwaftr.lwutil")
local constants = require("apps.lwaftr.constants")
local nh_fwd = require("apps.lwaftr.nh_fwd")
local pci = require("lib.hardware.pci")
local raw = require("apps.socket.raw")
local tap = require("apps.tap.tap")
local pcap = require("apps.pcap.pcap")
local yang = require("lib.yang.yang")
local fatal, file_exists = lwutil.fatal, lwutil.file_exists
local dir_exists, nic_exists = lwutil.dir_exists, lwutil.nic_exists
local yesno = lib.yesno
local function net_exists (pci_addr)
local devices="/sys/class/net"
return dir_exists(("%s/%s"):format(devices, pci_addr))
end
local function subset (keys, conf)
local ret = {}
for k,_ in pairs(keys) do ret[k] = conf[k] end
return ret
end
local function load_driver (pciaddr)
local device_info = pci.device_info(pciaddr)
return require(device_info.driver).driver, device_info.rx, device_info.tx
end
local function load_virt (c, nic_id, lwconf, interface)
-- Validate the lwaftr and split the interfaces into global and instance.
local device, id, queue = lwutil.parse_instance(lwconf)
local gexternal_interface = lwconf.softwire_config.external_interface
local ginternal_interface = lwconf.softwire_config.internal_interface
local iexternal_interface = queue.external_interface
local iinternal_interface = queue.internal_interface
assert(type(interface) == 'table')
assert(nic_exists(interface.pci), "Couldn't find NIC: "..interface.pci)
local driver, rx, tx = assert(load_driver(interface.pci))
print("Different VLAN tags: load two virtual interfaces")
print(("%s ether %s"):format(nic_id, interface.mac_address))
local v4_nic_name, v6_nic_name = nic_id..'_v4', nic_id..'v6'
local v4_mtu = external_interface.mtu + constants.ethernet_header_size
if iexternal_interface.vlan_tag then
v4_mtu = v4_mtu + 4
end
print(("Setting %s interface MTU to %d"):format(v4_nic_name, v4_mtu))
config.app(c, v4_nic_name, driver, {
pciaddr = interface.pci,
vmdq = true, -- Needed to enable MAC filtering/stamping.
vlan = interface.vlan and interface.vlan.v4_vlan_tag,
macaddr = ethernet:ntop(iexternal_interface.mac),
ring_buffer_size = interface.ring_buffer_size,
mtu = v4_mtu })
local v6_mtu = ginternal_interface.mtu + constants.ethernet_header_size
if iinternal_interface.vlan_tag then
v6_mtu = v6_mtu + 4
end
print(("Setting %s interface MTU to %d"):format(v6_nic_name, v6_mtu))
config.app(c, v6_nic_name, driver, {
pciaddr = interface.pci,
vmdq = true, -- Needed to enable MAC filtering/stamping.
vlan = interface.vlan and interface.vlan.v6_vlan_tag,
macaddr = ethernet:ntop(iinternal_interface.mac),
ring_buffer_size = interface.ring_buffer_size,
mtu = v6_mtu})
local v4_in, v4_out = v4_nic_name.."."..rx, v4_nic_name.."."..tx
local v6_in, v6_out = v6_nic_name.."."..rx, v6_nic_name.."."..tx
return v4_in, v4_out, v6_in, v6_out
end
local function load_phy (c, nic_id, interface)
assert(type(interface) == 'table')
local vlan = interface.vlan and tonumber(interface.vlan)
local chain_input, chain_output
if nic_exists(interface.pci) then
local driver, rx, tx = load_driver(interface.pci)
vlan = interface.vlan and tonumber(interface.vlan)
print(("%s network ether %s mtu %d"):format(nic_id, interface.mac_address, interface.mtu))
if vlan then
print(("%s vlan %d"):format(nic_id, vlan))
end
config.app(c, nic_id, driver, {
pciaddr = interface.pci,
vmdq = true, -- Needed to enable MAC filtering/stamping.
vlan = vlan,
macaddr = interface.mac_address,
ring_buffer_size = interface.ring_buffer_size,
mtu = interface.mtu})
chain_input, chain_output = nic_id.."."..rx, nic_id.."."..tx
elseif net_exists(interface.pci) then
print(("%s network interface %s mtu %d"):format(nic_id, interface.pci, interface.mtu))
if vlan then
print(("WARNING: VLAN not supported over %s. %s vlan %d"):format(interface.pci, nic_id, vlan))
end
config.app(c, nic_id, raw.RawSocket, interface.pci)
chain_input, chain_output = nic_id .. ".rx", nic_id .. ".tx"
else
print(("Couldn't find device info for PCI address '%s'"):format(interface.pci))
if not interface.mirror_id then
fatal("Neither PCI nor tap interface given")
end
print(("Using tap interface '%s' instead"):format(interface.mirror_id))
config.app(c, nic_id, tap.Tap, interface.mirror_id)
print(("Running VM via tap interface '%s'"):format(interface.mirror_id))
interface.mirror_id = nil -- Hack to avoid opening again as mirror port.
print(("SUCCESS %s"):format(chain_input))
chain_input, chain_output = nic_id .. ".input", nic_id .. ".output"
end
return chain_input, chain_output
end
local function requires_splitter (internal_interface, external_interface)
if not internal_interface.vlan_tag then return true end
return internal_interface.vlan_tag == external_interface.vlan_tag
end
function lwaftr_app(c, conf, lwconf, sock_path)
assert(type(conf) == 'table')
assert(type(lwconf) == 'table')
-- Validate the lwaftr and split the interfaces into global and instance.
local device, id, queue = lwutil.parse_instance(lwconf)
local gexternal_interface = lwconf.softwire_config.external_interface
local ginternal_interface = lwconf.softwire_config.internal_interface
local iexternal_interface = queue.external_interface
local iinternal_interface = queue.internal_interface
local external_interface = lwconf.softwire_config.external_interface
local internal_interface = lwconf.softwire_config.internal_interface
print(("Hairpinning: %s"):format(yesno(ginternal_interface.hairpinning)))
local virt_id = "vm_" .. conf.interface.id
local phy_id = "nic_" .. conf.interface.id
local chain_input, chain_output
local v4_input, v4_output, v6_input, v6_output
local use_splitter = requires_splitter(iinternal_interface, iexternal_interface)
if not use_splitter then
v4_input, v4_output, v6_input, v6_output =
load_virt(c, phy_id, lwconf, conf.interface)
else
chain_input, chain_output = load_phy(c, phy_id, conf.interface)
end
if conf.ipv4_interface or conf.ipv6_interface then
if use_splitter then
local mirror_id = conf.interface.mirror_id
if mirror_id then
print(("Mirror port %s found"):format(mirror_id))
config.app(c, "Mirror", tap.Tap, mirror_id)
config.app(c, "Sink", basic_apps.Sink)
config.link(c, "nic_v4v6.mirror -> Mirror.input")
config.link(c, "Mirror.output -> Sink.input")
end
config.app(c, "nic_v4v6", V4V6, { description = "nic_v4v6",
mirror = mirror_id and true or false})
config.link(c, chain_output .. " -> nic_v4v6.input")
config.link(c, "nic_v4v6.output -> " .. chain_input)
v4_output, v6_output = "nic_v4v6.v4", "nic_v4v6.v6"
v4_input, v6_input = "nic_v4v6.v4", "nic_v4v6.v6"
end
end
if conf.ipv6_interface then
conf.ipv6_interface.mac_address = conf.interface.mac_address
print(("IPv6 fragmentation and reassembly: %s"):format(yesno(
conf.ipv6_interface.fragmentation)))
if conf.ipv6_interface.fragmentation then
local mtu = conf.ipv6_interface.mtu or internal_interface.mtu
config.app(c, "reassemblerv6", ipv6_reassemble.Reassembler, {
max_concurrent_reassemblies =
ginternal_interface.reassembly.max_packets,
max_fragments_per_reassembly =
ginternal_interface.reassembly.max_fragments_per_packet
})
config.app(c, "fragmenterv6", ipv6_fragment.Fragmenter, {
mtu = mtu,
})
config.link(c, v6_output .. " -> reassemblerv6.input")
config.link(c, "fragmenterv6.output -> " .. v6_input)
v6_input, v6_output = "fragmenterv6.input", "reassemblerv6.output"
end
if conf.ipv6_interface.ipv6_ingress_filter then
local filter = conf.ipv6_interface.ipv6_ingress_filter
print(("IPv6 ingress filter: '%s'"):format(filter))
config.app(c, "ingress_filterv6", PcapFilter, { filter = filter })
config.link(c, v6_output .. " -> ingress_filterv6.input")
v6_output = "ingress_filterv6.output"
end
if conf.ipv6_interface.ipv6_egress_filter then
local filter = conf.ipv6_interface.ipv6_egress_filter
print(("IPv6 egress filter: '%s'"):format(filter))
config.app(c, "egress_filterv6", PcapFilter, { filter = filter })
config.link(c, "egress_filterv6.output -> " .. v6_input)
v6_input = "egress_filterv6.input"
end
end
if conf.ipv4_interface then
conf.ipv4_interface.mac_address = conf.interface.mac_address
print(("IPv4 fragmentation and reassembly: %s"):format(yesno(
conf.ipv4_interface.fragmentation)))
if conf.ipv4_interface.fragmentation then
local mtu = conf.ipv4_interface.mtu or gexternal_interface.mtu
config.app(c, "reassemblerv4", ipv4_reassemble.Reassembler, {
max_concurrent_reassemblies =
gexternal_interface.reassembly.max_packets,
max_fragments_per_reassembly =
gexternal_interface.reassembly.max_fragments_per_packet
})
config.app(c, "fragmenterv4", ipv4_fragment.Fragmenter, {
mtu = mtu
})
config.link(c, v4_output .. " -> reassemblerv4.input")
config.link(c, "fragmenterv4.output -> " .. v4_input)
v4_input, v4_output = "fragmenterv4.input", "reassemblerv4.output"
end
if conf.ipv4_interface.ipv4_ingress_filter then
local filter = conf.ipv4_interface.ipv4_ingress_filter
print(("IPv4 ingress filter: '%s'"):format(filter))
config.app(c, "ingress_filterv4", PcapFilter, { filter = filter })
config.link(c, v4_output .. " -> ingress_filterv4.input")
v4_output = "ingress_filterv4.output"
end
if conf.ipv4_interface.ipv4_egress_filter then
local filter = conf.ipv4_interface.ipv4_egress_filter
print(("IPv4 egress filter: '%s'"):format(filter))
config.app(c, "egress_filterv4", PcapFilter, { filter = filter })
config.link(c, "egress_filterv4.output -> " .. v4_input)
v4_input = "egress_filterv4.input"
end
end
if conf.ipv4_interface and conf.ipv6_interface then
print("lwAFTR service: enabled")
config.app(c, "nh_fwd6", nh_fwd.nh_fwd6,
subset(nh_fwd.nh_fwd6.config, conf.ipv6_interface))
config.link(c, v6_output .. " -> nh_fwd6.wire")
config.link(c, "nh_fwd6.wire -> " .. v6_input)
v6_input, v6_output = "nh_fwd6.vm", "nh_fwd6.vm"
config.app(c, "nh_fwd4", nh_fwd.nh_fwd4,
subset(nh_fwd.nh_fwd4.config, conf.ipv4_interface))
config.link(c, v4_output .. " -> nh_fwd4.wire")
config.link(c, "nh_fwd4.wire -> " .. v4_input)
v4_input, v4_output = "nh_fwd4.vm", "nh_fwd4.vm"
config.app(c, "lwaftr", lwaftr.LwAftr, lwconf)
config.link(c, "nh_fwd6.service -> lwaftr.v6")
config.link(c, "lwaftr.v6 -> nh_fwd6.service")
config.link(c, "nh_fwd4.service -> lwaftr.v4")
config.link(c, "lwaftr.v4 -> nh_fwd4.service")
-- Add a special hairpinning queue to the lwaftr app.
config.link(c, "lwaftr.hairpin_out -> lwaftr.hairpin_in")
else
print("lwAFTR service: disabled (v6 or v4 interface config missing)")
end
if conf.ipv4_interface or conf.ipv6_interface then
config.app(c, "vm_v4v6", V4V6, { description = "vm_v4v6",
mirror = false })
config.link(c, v6_output .. " -> vm_v4v6.v6")
config.link(c, "vm_v4v6.v6 -> " .. v6_input)
config.link(c, v4_output .. " -> vm_v4v6.v4")
config.link(c, "vm_v4v6.v4 -> " .. v4_input)
chain_input, chain_output = "vm_v4v6.input", "vm_v4v6.output"
end
if sock_path then
local socket_path = sock_path:format(conf.interface.id)
config.app(c, virt_id, VhostUser, { socket_path = socket_path })
config.link(c, virt_id .. ".tx -> " .. chain_input)
config.link(c, chain_output .. " -> " .. virt_id .. ".rx")
else
config.app(c, "DummyVhost", basic_apps.Sink)
config.link(c, "DummyVhost" .. ".tx -> " .. chain_input)
config.link(c, chain_output .. " -> " .. "DummyVhost" .. ".rx")
print("Running without VM (no vHostUser sock_path set)")
end
end
function passthrough(c, conf, sock_path)
assert(type(conf) == 'table')
io.write("lwAFTR service: disabled ")
print("(either empty binding_table or v6 or v4 interface config missing)")
local virt_id = "vm_" .. conf.interface.id
local phy_id = "nic_" .. conf.interface.id
local chain_input, chain_output = load_phy(c, phy_id, conf.interface)
if sock_path then
local socket_path = sock_path:format(conf.interface.id)
config.app(c, virt_id, VhostUser, { socket_path = socket_path })
config.link(c, virt_id .. ".tx -> " .. chain_input)
config.link(c, chain_output .. " -> " .. virt_id .. ".rx")
else
config.app(c, "DummyVhost", basic_apps.Sink)
config.link(c, "DummyVhost" .. ".tx -> " .. chain_input)
config.link(c, chain_output .. " -> " .. "DummyVhost" .. ".rx")
print("Running without VM (no vHostUser sock_path set)")
end
end
function load_conf (conf_filename)
local function load_lwaftr_config (conf, conf_filename)
local filename = conf.lwaftr
if not file_exists(filename) then
filename = lib.dirname(conf_filename).."/"..filename
end
return yang.load_configuration(filename,
{schema_name=lwaftr.LwAftr.yang_schema})
end
local conf = dofile(conf_filename)
return conf, load_lwaftr_config(conf, conf_filename)
end
local function lwaftr_app_check (c, conf, lwconf, sources, sinks)
assert(type(conf) == "table")
assert(type(lwconf) == "table")
local external_interface = lwconf.softwire_config.external_interface
local internal_interface = lwconf.softwire_config.internal_interface
local v4_src, v6_src = unpack(sources)
local v4_sink, v6_sink = unpack(sinks)
if conf.ipv6_interface then
if conf.ipv6_interface.fragmentation then
local mtu = conf.ipv6_interface.mtu or internal_interface.mtu
config.app(c, "reassemblerv6", ipv6_reassemble.Reassembler, {
max_concurrent_reassemblies =
internal_interface.reassembly.max_packets,
max_fragments_per_reassembly =
internal_interface.reassembly.max_fragments_per_packet
})
config.app(c, "fragmenterv6", ipv6_fragment.Fragmenter, {
mtu = mtu,
})
config.link(c, v6_src .. " -> reassemblerv6.input")
config.link(c, "fragmenterv6.output -> " .. v6_sink)
v6_src, v6_sink = "reassemblerv6.output", "fragmenterv6.input"
end
if conf.ipv6_interface.ipv6_ingress_filter then
local filter = conf.ipv6_interface.ipv6_ingress_filter
config.app(c, "ingress_filterv6", PcapFilter, { filter = filter })
config.link(c, v6_src .. " -> ingress_filterv6.input")
v6_src = "ingress_filterv6.output"
end
if conf.ipv6_interface.ipv6_egress_filter then
local filter = conf.ipv6_interface.ipv6_egress_filter
config.app(c, "egress_filterv6", PcapFilter, { filter = filter })
config.link(c, "egress_filterv6.output -> " .. v6_sink)
v6_sink = "egress_filterv6.input"
end
end
if conf.ipv4_interface then
if conf.ipv4_interface.fragmentation then
local mtu = conf.ipv4_interface.mtu or external_interface.mtu
config.app(c, "reassemblerv4", ipv4_reassemble.Reassembler, {
max_concurrent_reassemblies =
external_interface.reassembly.max_packets,
max_fragments_per_reassembly =
external_interface.reassembly.max_fragments_per_packet
})
config.app(c, "fragmenterv4", ipv4_fragment.Fragmenter, {
mtu = mtu
})
config.link(c, v4_src .. " -> reassemblerv4.input")
config.link(c, "fragmenterv4.output -> " .. v4_sink)
v4_src, v4_sink = "reassemblerv4.output", "fragmenterv4.input"
end
if conf.ipv4_interface.ipv4_ingress_filter then
local filter = conf.ipv4_interface.ipv4_ingress_filter
config.app(c, "ingress_filterv4", PcapFilter, { filter = filter })
config.link(c, v4_src .. " -> ingress_filterv4.input")
v4_src = "ingress_filterv4.output"
end
if conf.ipv4_interface.ipv4_egress_filter then
local filter = conf.ipv4_interface.ipv4_egress_filter
config.app(c, "egress_filterv4", PcapFilter, { filter = filter })
config.link(c, "egress_filterv4.output -> " .. v4_sink)
v4_sink = "egress_filterv4.input"
end
end
if conf.ipv4_interface and conf.ipv6_interface then
config.app(c, "nh_fwd6", nh_fwd.nh_fwd6,
subset(nh_fwd.nh_fwd6.config, conf.ipv6_interface))
config.link(c, v6_src.." -> nh_fwd6.wire")
config.link(c, "nh_fwd6.wire -> "..v6_sink)
config.app(c, "nh_fwd4", nh_fwd.nh_fwd4,
subset(nh_fwd.nh_fwd4.config, conf.ipv4_interface))
config.link(c, v4_src.."-> nh_fwd4.wire")
config.link(c, "nh_fwd4.wire -> "..v4_sink)
config.app(c, "lwaftr", lwaftr.LwAftr, lwconf)
config.link(c, "nh_fwd6.service -> lwaftr.v6")
config.link(c, "lwaftr.v6 -> nh_fwd6.service")
config.link(c, "nh_fwd4.service -> lwaftr.v4")
config.link(c, "lwaftr.v4 -> nh_fwd4.service")
-- Add a special hairpinning queue to the lwaftr app.
config.link(c, "lwaftr.hairpin_out -> lwaftr.hairpin_in")
config.app(c, "vm_v4v6", V4V6, { description = "vm_v4v6",
mirror = false })
config.link(c, "nh_fwd6.vm -> vm_v4v6.v6")
config.link(c, "vm_v4v6.v6 -> nh_fwd6.vm")
config.link(c, "nh_fwd4.vm -> vm_v4v6.v4")
config.link(c, "vm_v4v6.v4 -> nh_fwd6.vm")
config.app(c, "DummyVhost", basic_apps.Sink)
config.link(c, "DummyVhost.tx -> vm_v4v6.input")
config.link(c, "vm_v4v6.output -> DummyVhost.rx")
end
end
function load_check(c, conf_filename, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap)
local conf, lwconf = load_conf(conf_filename)
config.app(c, "capturev4", pcap.PcapReader, inv4_pcap)
config.app(c, "capturev6", pcap.PcapReader, inv6_pcap)
config.app(c, "output_filev4", pcap.PcapWriter, outv4_pcap)
config.app(c, "output_filev6", pcap.PcapWriter, outv6_pcap)
if conf.vlan_tagging then
config.app(c, "untagv4", vlan.Untagger, { tag=conf.v4_vlan_tag })
config.app(c, "untagv6", vlan.Untagger, { tag=conf.v6_vlan_tag })
config.app(c, "tagv4", vlan.Tagger, { tag=conf.v4_vlan_tag })
config.app(c, "tagv6", vlan.Tagger, { tag=conf.v6_vlan_tag })
end
local sources = { "capturev4.output", "capturev6.output" }
local sinks = { "output_filev4.input", "output_filev6.input" }
if conf.vlan_tagging then
sources = { "untagv4.output", "untagv6.output" }
sinks = { "tagv4.input", "tagv6.input" }
config.link(c, "capturev4.output -> untagv4.input")
config.link(c, "capturev6.output -> untagv6.input")
config.link(c, "tagv4.output -> output_filev4.input")
config.link(c, "tagv6.output -> output_filev6.input")
end
lwaftr_app_check(c, conf, lwconf, sources, sinks)
end
| apache-2.0 |
thedraked/darkstar | scripts/zones/Cloister_of_Gales/bcnms/sugar-coated_directive.lua | 30 | 1808 | ----------------------------------------
-- Area: Cloister of Gales
-- BCNM: Sugar Coated Directive (ASA-4)
----------------------------------------
package.loaded["scripts/zones/Cloister_of_Gales/TextIDs"] = nil;
----------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Cloister_of_Gales/TextIDs");
----------------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompletedMission(ASA,SUGAR_COATED_DIRECTIVE)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:addExp(400);
player:setVar("ASA4_Emerald","1");
end
end; | gpl-3.0 |
mtroyka/Zero-K | gamedata/modularcomms/weapons/torpedo.lua | 17 | 1427 | local name = "commweapon_torpedo"
local weaponDef = {
name = [[Torpedo Launcher]],
areaOfEffect = 16,
avoidFriendly = false,
bouncerebound = 0.5,
bounceslip = 0.5,
burnblow = true,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
customParams = {
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[SWIM FIXEDWING LAND SUB SINK TURRET FLOAT SHIP GUNSHIP HOVER]],
slot = [[5]],
},
damage = {
default = 220,
subs = 220,
},
explosionGenerator = [[custom:TORPEDO_HIT]],
flightTime = 6,
groundbounce = 1,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
model = [[wep_t_longbolt.s3o]],
numbounce = 4,
noSelfDamage = true,
range = 330,
reloadtime = 3.5,
soundHit = [[explosion/wet/ex_underwater]],
soundStart = [[weapon/torpedo]],
startVelocity = 90,
tracks = true,
turnRate = 10000,
turret = true,
waterWeapon = true,
weaponAcceleration = 25,
weaponType = [[TorpedoLauncher]],
weaponVelocity = 140,
}
return name, weaponDef
| gpl-2.0 |
thedraked/darkstar | scripts/globals/weaponskills/keen_edge.lua | 25 | 1370 | -----------------------------------
-- Keen Edge
-- Great Axe weapon skill
-- Skill level: 150
-- Delivers a single hit attack. Chance of params.critical varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Shadow Gorget.
-- Aligned with the Shadow Belt.
-- Element: None
-- Modifiers: STR:35%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.3; params.crit200 = 0.6; params.crit300 = 0.9;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
mtroyka/Zero-K | units/benzcom1.lua | 2 | 5837 | unitDef = {
unitname = [[benzcom1]],
name = [[Siege Commander]],
description = [[Standoff Combat Commander, Builds at 10 m/s]],
acceleration = 0.18,
activateWhenBuilt = true,
autoHeal = 5,
brakeRate = 0.375,
buildCostEnergy = 1200,
buildCostMetal = 1200,
buildDistance = 128,
builder = true,
buildoptions = {
},
buildPic = [[benzcom.png]],
buildTime = 1200,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[45 54 45]],
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
--description_de = [[Schwerer Kampfkommandant, Baut mit 10 M/s]],
helptext = [[The Siege Commander is optimized for pummeling the enemy from a distance. Its low speed and armor leave it vulnerable in a knife fight.]],
--helptext_de = [[Der Battle Commander verbindet Feuerkraft mit starker Panzerung, auf Kosten der Geschwindigkeit und seiner Unterstützungsausrüstung. Seine Standardwaffe ist eine randalierende Kanone, während seine Spezialwaffen Streubomben in einer Linie abfeuern.]],
level = [[1]],
statsname = [[benzcom1]],
soundok = [[heavy_bot_move]],
soundselect = [[bot_select]],
soundbuild = [[builder_start]],
commtype = [[5]],
},
energyMake = 6,
energyStorage = 500,
energyUse = 0,
explodeAs = [[ESTOR_BUILDINGEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[commander1]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
losEmitHeight = 40,
maxDamage = 2250,
maxSlope = 36,
maxVelocity = 1.25,
maxWaterDepth = 5000,
metalMake = 4,
metalStorage = 500,
minCloakDistance = 75,
movementClass = [[AKBOT2]],
noChaseCategory = [[TERRAFORM SATELLITE FIXEDWING GUNSHIP HOVER SHIP SWIM SUB LAND FLOAT SINK]],
objectName = [[benzcom1.s3o]],
script = [[benzcom.lua]],
seismicSignature = 16,
selfDestructAs = [[ESTOR_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:RAIDMUZZLE]],
[[custom:LEVLRMUZZLE]],
[[custom:RAIDMUZZLE]],
},
},
showNanoSpray = false,
showPlayerName = true,
sightDistance = 500,
sonarDistance = 300,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
terraformSpeed = 600,
turnRate = 1148,
upright = true,
workerTime = 10,
weapons = {
[1] = {
def = [[FAKELASER]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
[5] = {
def = [[ASSAULT_CANNON]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
FAKELASER = {
name = [[Fake Laser]],
areaOfEffect = 12,
beamTime = 0.1,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 0,
subs = 0,
},
edgeEffectiveness = 0.99,
explosionGenerator = [[custom:flash1green]],
fireStarter = 70,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
laserFlareSize = 5.53,
minIntensity = 1,
range = 360,
reloadtime = 0.11,
rgbColor = [[0 1 0]],
soundStart = [[weapon/laser/pulse_laser3]],
soundTrigger = true,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 5.53,
tolerance = 10000,
turret = true,
weaponType = [[BeamLaser]],
},
ASSAULT_CANNON = {
name = [[Assault Cannon]],
areaOfEffect = 32,
craterBoost = 1,
craterMult = 3,
damage = {
default = 360,
planes = 360,
subs = 18,
},
explosionGenerator = [[custom:INGEBORG]],
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
myGravity = 0.25,
range = 360,
reloadtime = 2,
soundHit = [[weapon/cannon/cannon_hit2]],
soundStart = [[weapon/cannon/medplasma_fire]],
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 300,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[benzcom1_wreck.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ benzcom1 = unitDef })
| gpl-2.0 |
thedraked/darkstar | scripts/zones/Misareaux_Coast/Zone.lua | 4 | 1649 | -----------------------------------
--
-- Zone: Misareaux_Coast (25)
--
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local vwnpc = {16879985,16879986,16879987};
SetVoidwatchNPC(vwnpc);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(567.624,-20,280.775,120);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
MonkeyFirst/Urho3D | Source/ThirdParty/toluapp/src/bin/lua/container.lua | 28 | 17414 | -- tolua: container abstract class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: $
-- 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.
-- table to store namespaced typedefs/enums in global scope
global_typedefs = {}
global_enums = {}
-- Container class
-- Represents a container of features to be bound
-- to lua.
classContainer =
{
curr = nil,
}
classContainer.__index = classContainer
setmetatable(classContainer,classFeature)
-- output tags
function classContainer:decltype ()
push(self)
local i=1
while self[i] do
self[i]:decltype()
i = i+1
end
pop()
end
-- write support code
function classContainer:supcode ()
if not self:check_public_access() then
return
end
push(self)
local i=1
while self[i] do
if self[i]:check_public_access() then
self[i]:supcode()
end
i = i+1
end
pop()
end
function classContainer:hasvar ()
local i=1
while self[i] do
if self[i]:isvariable() then
return 1
end
i = i+1
end
return 0
end
-- Internal container constructor
function _Container (self)
setmetatable(self,classContainer)
self.n = 0
self.typedefs = {tolua_n=0}
self.usertypes = {}
self.enums = {tolua_n=0}
self.lnames = {}
return self
end
-- push container
function push (t)
t.prox = classContainer.curr
classContainer.curr = t
end
-- pop container
function pop ()
--print("name",classContainer.curr.name)
--foreach(classContainer.curr.usertypes,print)
--print("______________")
classContainer.curr = classContainer.curr.prox
end
-- get current namespace
function getcurrnamespace ()
return getnamespace(classContainer.curr)
end
-- append to current container
function append (t)
return classContainer.curr:append(t)
end
-- append typedef to current container
function appendtypedef (t)
return classContainer.curr:appendtypedef(t)
end
-- append usertype to current container
function appendusertype (t)
return classContainer.curr:appendusertype(t)
end
-- append enum to current container
function appendenum (t)
return classContainer.curr:appendenum(t)
end
-- substitute typedef
function applytypedef (mod,type)
return classContainer.curr:applytypedef(mod,type)
end
-- check if is type
function findtype (type)
local t = classContainer.curr:findtype(type)
return t
end
-- check if is typedef
function istypedef (type)
return classContainer.curr:istypedef(type)
end
-- get fulltype (with namespace)
function fulltype (t)
local curr = classContainer.curr
while curr do
if curr then
if curr.typedefs and curr.typedefs[t] then
return curr.typedefs[t]
elseif curr.usertypes and curr.usertypes[t] then
return curr.usertypes[t]
end
end
curr = curr.prox
end
return t
end
-- checks if it requires collection
function classContainer:requirecollection (t)
push(self)
local i=1
local r = false
while self[i] do
r = self[i]:requirecollection(t) or r
i = i+1
end
pop()
return r
end
-- get namesapce
function getnamespace (curr)
local namespace = ''
while curr do
if curr and
( curr.classtype == 'class' or curr.classtype == 'namespace')
then
namespace = (curr.original_name or curr.name) .. '::' .. namespace
--namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- get namespace (only namespace)
function getonlynamespace ()
local curr = classContainer.curr
local namespace = ''
while curr do
if curr.classtype == 'class' then
return namespace
elseif curr.classtype == 'namespace' then
namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- check if is enum
function isenum (type)
return classContainer.curr:isenum(type)
end
-- append feature to container
function classContainer:append (t)
self.n = self.n + 1
self[self.n] = t
t.parent = self
end
-- append typedef
function classContainer:appendtypedef (t)
local namespace = getnamespace(classContainer.curr)
self.typedefs.tolua_n = self.typedefs.tolua_n + 1
self.typedefs[self.typedefs.tolua_n] = t
self.typedefs[t.utype] = namespace .. t.utype
global_typedefs[namespace..t.utype] = t
t.ftype = findtype(t.type) or t.type
--print("appending typedef "..t.utype.." as "..namespace..t.utype.." with ftype "..t.ftype)
append_global_type(namespace..t.utype)
if t.ftype and isenum(t.ftype) then
global_enums[namespace..t.utype] = true
end
end
-- append usertype: return full type
function classContainer:appendusertype (t)
local container
if t == (self.original_name or self.name) then
container = self.prox
else
container = self
end
local ft = getnamespace(container) .. t
container.usertypes[t] = ft
_usertype[ft] = ft
return ft
end
-- append enum
function classContainer:appendenum (t)
local namespace = getnamespace(classContainer.curr)
self.enums.tolua_n = self.enums.tolua_n + 1
self.enums[self.enums.tolua_n] = t
global_enums[namespace..t.name] = t
end
-- determine lua function name overload
function classContainer:overload (lname)
if not self.lnames[lname] then
self.lnames[lname] = 0
else
self.lnames[lname] = self.lnames[lname] + 1
end
return format("%02d",self.lnames[lname])
end
-- applies typedef: returns the 'the facto' modifier and type
function classContainer:applytypedef (mod,type)
if global_typedefs[type] then
--print("found typedef "..global_typedefs[type].type)
local mod1, type1 = global_typedefs[type].mod, global_typedefs[type].ftype
local mod2, type2 = applytypedef(mod.." "..mod1, type1)
--return mod2 .. ' ' .. mod1, type2
return mod2, type2
end
do return mod,type end
end
-- check if it is a typedef
function classContainer:istypedef (type)
local env = self
while env do
if env.typedefs then
local i=1
while env.typedefs[i] do
if env.typedefs[i].utype == type then
return type
end
i = i+1
end
end
env = env.parent
end
return nil
end
function find_enum_var(var)
if tonumber(var) then return var end
local c = classContainer.curr
while c do
local ns = getnamespace(c)
for k,v in pairs(_global_enums) do
if match_type(var, v, ns) then
return v
end
end
if c.base and c.base ~= '' then
c = _global_classes[c:findtype(c.base)]
else
c = nil
end
end
return var
end
-- check if is a registered type: return full type or nil
function classContainer:findtype (t)
t = string.gsub(t, "=.*", "")
if _basic[t] then
return t
end
local _,_,em = string.find(t, "([&%*])%s*$")
t = string.gsub(t, "%s*([&%*])%s*$", "")
p = self
while p and type(p)=='table' do
local st = getnamespace(p)
for i=_global_types.n,1,-1 do -- in reverse order
if match_type(t, _global_types[i], st) then
return _global_types[i]..(em or "")
end
end
if p.base and p.base ~= '' and p.base ~= t then
--print("type is "..t..", p is "..p.base.." self.type is "..self.type.." self.name is "..self.name)
p = _global_classes[p:findtype(p.base)]
else
p = nil
end
end
return nil
end
function append_global_type(t, class)
_global_types.n = _global_types.n +1
_global_types[_global_types.n] = t
_global_types_hash[t] = 1
if class then append_class_type(t, class) end
end
function append_class_type(t,class)
if _global_classes[t] then
class.flags = _global_classes[t].flags
class.lnames = _global_classes[t].lnames
if _global_classes[t].base and (_global_classes[t].base ~= '') then
class.base = _global_classes[t].base or class.base
end
end
_global_classes[t] = class
class.flags = class.flags or {}
end
function match_type(childtype, regtype, st)
--print("findtype "..childtype..", "..regtype..", "..st)
local b,e = string.find(regtype, childtype, -string.len(childtype), true)
if b then
if e == string.len(regtype) and
(b == 1 or (string.sub(regtype, b-1, b-1) == ':' and
string.sub(regtype, 1, b-1) == string.sub(st, 1, b-1))) then
return true
end
end
return false
end
function findtype_on_childs(self, t)
local tchild
if self.classtype == 'class' or self.classtype == 'namespace' then
for k,v in ipairs(self) do
if v.classtype == 'class' or v.classtype == 'namespace' then
if v.typedefs and v.typedefs[t] then
return v.typedefs[t]
elseif v.usertypes and v.usertypes[t] then
return v.usertypes[t]
end
tchild = findtype_on_childs(v, t)
if tchild then return tchild end
end
end
end
return nil
end
function classContainer:isenum (type)
if global_enums[type] then
return type
else
return false
end
local basetype = gsub(type,"^.*::","")
local env = self
while env do
if env.enums then
local i=1
while env.enums[i] do
if env.enums[i].name == basetype then
return true
end
i = i+1
end
end
env = env.parent
end
return false
end
methodisvirtual = false -- a global
-- parse chunk
function classContainer:doparse (s)
--print ("parse "..s)
-- try the parser hook
do
local sub = parser_hook(s)
if sub then
return sub
end
end
-- try the null statement
do
local b,e,code = string.find(s, "^%s*;")
if b then
return strsub(s,e+1)
end
end
-- try empty verbatim line
do
local b,e,code = string.find(s, "^%s*$\n")
if b then
return strsub(s,e+1)
end
end
-- try Lua code
do
local b,e,code = strfind(s,"^%s*(%b\1\2)")
if b then
Code(strsub(code,2,-2))
return strsub(s,e+1)
end
end
-- try C code
do
local b,e,code = strfind(s,"^%s*(%b\3\4)")
if b then
code = '{'..strsub(code,2,-2)..'\n}\n'
Verbatim(code,'r') -- verbatim code for 'r'egister fragment
return strsub(s,e+1)
end
end
-- try C code for preamble section
do
local b,e,code = string.find(s, "^%s*(%b\5\6)")
if b then
code = string.sub(code, 2, -2).."\n"
Verbatim(code, '')
return string.sub(s, e+1)
end
end
-- try default_property directive
do
local b,e,ptype = strfind(s, "^%s*TOLUA_PROPERTY_TYPE%s*%(+%s*([^%)%s]*)%s*%)+%s*;?")
if b then
if not ptype or ptype == "" then
ptype = "default"
end
self:set_property_type(ptype)
return strsub(s, e+1)
end
end
-- try protected_destructor directive
do
local b,e = string.find(s, "^%s*TOLUA_PROTECTED_DESTRUCTOR%s*;?")
if b then
if self.set_protected_destructor then
self:set_protected_destructor(true)
end
return strsub(s, e+1)
end
end
-- try 'extern' keyword
do
local b,e = string.find(s, "^%s*extern%s+")
if b then
-- do nothing
return strsub(s, e+1)
end
end
-- try 'virtual' keyworkd
do
local b,e = string.find(s, "^%s*virtual%s+")
if b then
methodisvirtual = true
return strsub(s, e+1)
end
end
-- try labels (public, private, etc)
do
local b,e = string.find(s, "^%s*%w*%s*:[^:]")
if b then
return strsub(s, e) -- preserve the [^:]
end
end
-- try module
do
local b,e,name,body = strfind(s,"^%s*module%s%s*([_%w][_%w]*)%s*(%b{})%s*")
if b then
_curr_code = strsub(s,b,e)
Module(name,body)
return strsub(s,e+1)
end
end
-- try namesapce
do
local b,e,name,body = strfind(s,"^%s*namespace%s%s*([_%w][_%w]*)%s*(%b{})%s*;?")
if b then
_curr_code = strsub(s,b,e)
Namespace(name,body)
return strsub(s,e+1)
end
end
-- try define
do
local b,e,name = strfind(s,"^%s*#define%s%s*([^%s]*)[^\n]*\n%s*")
if b then
_curr_code = strsub(s,b,e)
Define(name)
return strsub(s,e+1)
end
end
-- try enumerates
do
local b,e,name,body,varname = strfind(s,"^%s*enum%s+(%S*)%s*(%b{})%s*([^%s;]*)%s*;?%s*")
if b then
--error("#Sorry, declaration of enums and variables on the same statement is not supported.\nDeclare your variable separately (example: '"..name.." "..varname..";')")
_curr_code = strsub(s,b,e)
Enumerate(name,body,varname)
return strsub(s,e+1)
end
end
-- do
-- local b,e,name,body = strfind(s,"^%s*enum%s+(%S*)%s*(%b{})%s*;?%s*")
-- if b then
-- _curr_code = strsub(s,b,e)
-- Enumerate(name,body)
-- return strsub(s,e+1)
-- end
-- end
do
local b,e,body,name = strfind(s,"^%s*typedef%s+enum[^{]*(%b{})%s*([%w_][^%s]*)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Enumerate(name,body)
return strsub(s,e+1)
end
end
-- try operator
do
local b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:<>,]-%s+operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
if not b then
-- try inline
b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:<>,]-%s+operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)[%s\n]*%b{}%s*;?%s*")
end
if not b then
-- try cast operator
b,e,decl,kind,arg,const = strfind(s, "^%s*(operator)%s+([%w_:%d<>%*%&%s]+)%s*(%b())%s*(c?o?n?s?t?)");
if b then
local _,ie = string.find(s, "^%s*%b{}", e+1)
if ie then
e = ie
end
end
end
if b then
_curr_code = strsub(s,b,e)
Operator(decl,kind,arg,const)
return strsub(s,e+1)
end
end
-- try function
do
--local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w])%s*(%b())%s*(c?o?n?s?t?)%s*=?%s*0?%s*;%s*")
local b,e,decl,arg,const,virt = strfind(s,"^%s*([^%(\n]+)%s*(%b())%s*(c?o?n?s?t?)%s*(=?%s*0?)%s*;%s*")
if not b then
-- try function with template
b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w]%b<>)%s*(%b())%s*(c?o?n?s?t?)%s*=?%s*0?%s*;%s*")
end
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
end
if not b then
-- try function pointer
b,e,decl,arg,const = strfind(s,"^%s*([^%(;\n]+%b())%s*(%b())%s*;%s*")
if b then
decl = string.gsub(decl, "%(%s*%*([^%)]*)%s*%)", " %1 ")
end
end
if b then
if virt and string.find(virt, "[=0]") then
if self.flags then
self.flags.pure_virtual = true
end
end
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try inline function
do
local b,e,decl,arg,const = strfind(s,"^%s*([^%(\n]+)%s*(%b())%s*(c?o?n?s?t?)[^;{]*%b{}%s*;?%s*")
--local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w>])%s*(%b())%s*(c?o?n?s?t?)[^;]*%b{}%s*;?%s*")
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?).-%b{}%s*;?%s*")
end
if b then
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try class
do
local b,e,name,base,body
base = '' body = ''
b,e,name = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*;") -- dummy class
local dummy = false
if not b then
b,e,name = strfind(s,"^%s*struct%s*([_%w][_%w@]*)%s*;") -- dummy struct
if not b then
b,e,name,base,body = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*([^{]-)%s*(%b{})%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*struct%s+([_%w][_%w@]*)%s*([^{]-)%s*(%b{})%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*union%s*([_%w][_%w@]*)%s*([^{]-)%s*(%b{})%s*")
if not b then
base = ''
b,e,body,name = strfind(s,"^%s*typedef%s%s*struct%s%s*[_%w]*%s*(%b{})%s*([_%w][_%w@]*)%s*;")
end
end
end
else dummy = 1 end
else dummy = 1 end
if b then
if base ~= '' then
base = string.gsub(base, "^%s*:%s*", "")
base = string.gsub(base, "%s*public%s*", "")
base = split(base, ",")
--local b,e
--b,e,base = strfind(base,".-([_%w][_%w<>,:]*)$")
else
base = {}
end
_curr_code = strsub(s,b,e)
Class(name,base,body)
if not dummy then
varb,vare,varname = string.find(s, "^%s*([_%w]+)%s*;", e+1)
if varb then
Variable(name.." "..varname)
e = vare
end
end
return strsub(s,e+1)
end
end
-- try typedef
do
local b,e,types = strfind(s,"^%s*typedef%s%s*(.-)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Typedef(types)
return strsub(s,e+1)
end
end
-- try variable
do
local b,e,decl = strfind(s,"^%s*([_%w][_@%s%w%d%*&:<>,]*[_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
local list = split_c_tokens(decl, ",")
Variable(list[1])
if list.n > 1 then
local _,_,type = strfind(list[1], "(.-)%s+([^%s]*)$");
local i =2;
while list[i] do
Variable(type.." "..list[i])
i=i+1
end
end
--Variable(decl)
return strsub(s,e+1)
end
end
-- try string
do
local b,e,decl = strfind(s,"^%s*([_%w]?[_%s%w%d]-char%s+[_@%w%d]*%s*%[%s*%S+%s*%])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Variable(decl)
return strsub(s,e+1)
end
end
-- try array
do
local b,e,decl = strfind(s,"^%s*([_%w][][_@%s%w%d%*&:<>]*[]_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Array(decl)
return strsub(s,e+1)
end
end
-- no matching
if gsub(s,"%s%s*","") ~= "" then
_curr_code = s
error("#parse error")
else
return ""
end
end
function classContainer:parse (s)
--self.curr_member_access = nil
while s ~= '' do
s = self:doparse(s)
methodisvirtual = false
end
end
-- property types
function get_property_type()
return classContainer.curr:get_property_type()
end
function classContainer:set_property_type(ptype)
ptype = string.gsub(ptype, "^%s*", "")
ptype = string.gsub(ptype, "%s*$", "")
self.property_type = ptype
end
function classContainer:get_property_type()
return self.property_type or (self.parent and self.parent:get_property_type()) or "default"
end
| mit |
mtroyka/Zero-K | LuaUI/Widgets/unit_voice.lua | 12 | 3543 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Voice Assistant",
desc = "",
author = "quantum",
date = "Dec 2011",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local factories = {}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function EnableVoiceCommandOptions(unitDef)
for _, buildOptionID in ipairs(unitDef.buildOptions) do
local buildOptionDef = UnitDefs[buildOptionID]
Spring.Echo("!transmitlobby @voice@buildUnit@add;"..buildOptionDef.name..";"..buildOptionDef.humanName) -- zklobby listens to this
end
Spring.Echo("!transmitlobby @voice@buildUnit@reload")
end
local function DisableVoiceCommandOptions(unitDef)
for _, buildOptionID in ipairs(unitDef.buildOptions) do
local buildOptionDef = UnitDefs[buildOptionID]
Spring.Echo("!transmitlobby @voice@buildUnit@remove;"..buildOptionDef.name) -- zklobby listens to this
end
Spring.Echo("!transmitlobby @voice@buildUnit@reload")
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
-- make the widget work after for /luaui reload
for i, unitID in ipairs(Spring.GetAllUnits()) do
widget:UnitFinished(unitID, Spring.GetUnitDefID(unitID), Spring.GetUnitTeam(unitID))
end
end
function widget:VoiceCommand(commandName, voiceCommandParams)
if commandName == "buildUnit" then
-- todo: don't send to factories that can't build the unit
for unitID in pairs(factories) do
local builtUnitID = UnitDefNames[voiceCommandParams.unit].id
for i=1, voiceCommandParams.number do
-- todo: send large build orders with "shift" and "ctrl" to reduce network usage
Spring.GiveOrderToUnit(unitID, -builtUnitID, {}, voiceCommandParams.insert and {"alt"} or {})
end
if voiceCommandParams["repeat"] then
Spring.GiveOrderToUnit(unitID, CMD.REPEAT, {1}, {})
end
end
end
end
-- todo: take into account factories given to me
function widget:UnitFinished(unitID, unitDefID, unitTeam)
local myTeamID = Spring.GetMyTeamID()
if unitTeam ~= myTeamID then
return
end
local unitDef = UnitDefs[unitDefID]
if unitDef and unitDef.isFactory then
factories[unitID] = true
if Spring.GetTeamUnitDefCount(myTeamID, unitDefID) < 2 then -- if this is the first factory of this type
EnableVoiceCommandOptions(unitDef)
end
end
end
-- todo: take into account factories given to allies
function widget:UnitDestroyed(unitID, unitDefID)
local myTeamID = Spring.GetMyTeamID()
if factories[unitID] then
if Spring.GetTeamUnitDefCount(myTeamID, unitDefID) < 2 then -- if this is the last factory of this type
factories[unitID] = nil
DisableVoiceCommandOptions(UnitDefs[unitDefID])
end
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
thedraked/darkstar | scripts/globals/abilities/pets/attachments/tension_spring.lua | 27 | 1089 | -----------------------------------
-- Attachment: Tension Spring
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onUseAbility
-----------------------------------
function onEquip(pet)
pet:addMod(MOD_ATTP, 3)
pet:addMod(MOD_RATTP, 3)
end
function onUnequip(pet)
pet:delMod(MOD_ATTP, 3)
pet:addMod(MOD_RATTP, 3)
end
function onManeuverGain(pet,maneuvers)
if (maneuvers == 1) then
pet:addMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 2) then
pet:addMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 3) then
pet:addMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
end
end
function onManeuverLose(pet,maneuvers)
if (maneuvers == 1) then
pet:delMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 2) then
pet:delMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 3) then
pet:delMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
end
end
| gpl-3.0 |
thedraked/darkstar | scripts/zones/Caedarva_Mire/npcs/qm1.lua | 30 | 1329 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: ??? (Spawn Verdelet(ZNM T2))
-- @pos 417 -19 -69 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Caedarva_Mire/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local mobID = 17101202;
if (trade:hasItemQty(2599,1) and trade:getItemCount() == 1) then -- Trade Mint Drop
if (GetMobAction(mobID) == ACTION_NONE) then
player:tradeComplete();
SpawnMob(mobID):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
mtroyka/Zero-K | LuaUI/Widgets/unit_building_starter.lua | 12 | 2690 | -- $Id$
function widget:GetInfo()
return {
name = "Building Starter",
desc = "v2 Hold Q to queue a building to be started and not continued.",
author = "Google Frog",
date = "Dec 13, 2008",
license = "GNU GPL, v2 or later",
layer = 5,
enabled = true -- loaded by default?
}
end
local buildings = {}
local numBuildings = 0
local team = Spring.GetMyTeamID()
include("keysym.h.lua")
local CMD_REMOVE = CMD.REMOVE
-- Speedups
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spGetTeamUnits = Spring.GetTeamUnits
local spGetCommandQueue = Spring.GetCommandQueue
local spGetUnitPosition = Spring.GetUnitPosition
local spGetKeyState = Spring.GetKeyState
local spGetSelectedUnits = Spring.GetSelectedUnits
local abs = math.abs
--
function widget:Initialize()
if (Spring.GetSpectatingState() or Spring.IsReplay()) and (not Spring.IsCheatingEnabled()) then
Spring.Echo("<Building Starter>: disabled for spectators")
widgetHandler:RemoveWidget()
end
end
function widget:CommandNotify(id, params, options)
if (id < 0) then
local ux = params[1]
local uz = params[3]
if (spGetKeyState(KEYSYMS.Q)) then
buildings[numBuildings] = { x = ux, z = uz}
numBuildings = numBuildings+1
else
for j, i in pairs(buildings) do
if (i.x) then
if (i.x == ux) and (i.z == uz) then
buildings[j] = nil
end
end
end
end
end
end
function CheckBuilding(ux,uz,ud)
for _, i in pairs(buildings) do
if (i.x) then
if (abs(i.x - ux) < 16) and (abs(i.z - uz) < 16) then
i.ud = ud
return true
end
end
end
return false
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
if (unitTeam ~= team) then
return
end
local units = spGetTeamUnits(team)
local ux, uy, uz = spGetUnitPosition(unitID)
if CheckBuilding(ux,uz,unitID) then
for _, unit_id in ipairs(units) do
local cQueue = spGetCommandQueue(unit_id, 1)
if cQueue and cQueue[1] then
local command = cQueue[1]
if command.id < 0 then
local cx = command.params[1]
local cz = command.params[3]
if (abs(cx-ux) < 16) and (abs(cz-uz) < 16) then
spGiveOrderToUnit(unit_id, CMD_REMOVE, {command.tag}, {} )
end
end
end
end
end
end
function widget:UnitFinished(unitID, unitDefID, unitTeam)
for j, i in ipairs(buildings) do
if (i.ud) then
buildings[j] = nil
end
end
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
for j, i in pairs(buildings) do
if (i.ud) then
buildings[j] = nil
end
end
end
| gpl-2.0 |
OpenNMT/OpenNMT | onmt/modules/JoinReplicateTable.lua | 8 | 4192 | local JoinReplicateTable, parent = torch.class('onmt.JoinReplicateTable', 'nn.Module')
function JoinReplicateTable:__init(dimensionReplicate, dimensionJoin, nInputDims)
parent.__init(self)
self.size = torch.LongStorage()
self.dimensionReplicate = dimensionReplicate
self.dimensionJoin = dimensionJoin
self.gradInput = {}
self.nInputDims = nInputDims
end
function JoinReplicateTable:_getPositiveDimensions(input)
local dimensionReplicate = self.dimensionReplicate
local dimensionJoin = self.dimensionJoin
if dimensionReplicate < 0 then
dimensionReplicate = input[1]:dim() + dimensionReplicate + 1
elseif self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimensionReplicate = dimensionReplicate + 1
end
if dimensionJoin < 0 then
dimensionJoin = input[1]:dim() + dimensionJoin + 1
elseif self.nInputDims and input[1]:dim()==(self.nInputDims+1) then
dimensionJoin = dimensionJoin + 1
end
return dimensionReplicate, dimensionJoin
end
function JoinReplicateTable:_replicate(input, dim, dryRun)
-- first replicate along dimensionReplicate, we assert all dimensions are the same but some can be one
local maxSize = 0
local hasOne = {}
for i = 1, #input do
local size = input[i]:size(dim)
assert(maxSize == 0 or size == maxSize or size == 1 or maxSize == 1, "incorrect tensor size for replicate dimension")
if size > maxSize then
maxSize = size
end
if size == 1 then
table.insert(hasOne, i)
end
end
-- remember strides to restore after joining operation
local memStrides = {}
if maxSize > 1 and #hasOne > 0 then
for i = 1, #hasOne do
local idx = hasOne[i]
local sz = input[idx]:size()
sz[dim] = maxSize
local st = input[idx]:stride()
memStrides[idx] = st[dim]
if not dryRun then
st[dim] = 0
input[idx]:set(input[idx]:storage(), input[idx]:storageOffset(), sz, st)
end
end
end
return memStrides
end
function JoinReplicateTable:_dereplicate(input, dim, memStrides)
for idx, stval in ipairs(memStrides) do
local sz = input[idx]:size()
sz[dim] = 1
local st = input[idx]:stride()
st[dim] = stval
input[idx]:set(input[idx]:storage(), input[idx]:storageOffset(), sz, st)
end
end
function JoinReplicateTable:updateOutput(input)
local dimensionReplicate, dimensionJoin = self:_getPositiveDimensions(input)
local memStrides = self:_replicate(input, dimensionReplicate)
for i=1,#input do
local currentOutput = input[i]
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[dimensionJoin] = self.size[dimensionJoin]
+ currentOutput:size(dimensionJoin)
end
end
self.output:resize(self.size)
local offset = 1
for i=1,#input do
local currentOutput = input[i]
self.output:narrow(dimensionJoin, offset,
currentOutput:size(dimensionJoin)):copy(currentOutput)
offset = offset + currentOutput:size(dimensionJoin)
end
self:_dereplicate(input, dimensionReplicate, memStrides)
return self.output
end
function JoinReplicateTable:updateGradInput(input, gradOutput)
local dimensionReplicate, dimensionJoin = self:_getPositiveDimensions(input)
local memStrides = self:_replicate(input, dimensionReplicate, true)
for i=1,#input do
if self.gradInput[i] == nil then
self.gradInput[i] = input[i].new()
end
self.gradInput[i]:resizeAs(input[i])
end
-- clear out invalid gradInputs
for i=#input+1, #self.gradInput do
self.gradInput[i] = nil
end
local offset = 1
for i=1,#input do
local currentOutput = input[i]
local currentGradInput = gradOutput:narrow(dimensionJoin, offset,
currentOutput:size(dimensionJoin))
if memStrides[i] then
-- sum along the replicated dimension
torch.sum(self.gradInput[i], currentGradInput, dimensionReplicate)
else
self.gradInput[i]:copy(currentGradInput)
end
offset = offset + currentOutput:size(dimensionJoin)
end
return self.gradInput
end
function JoinReplicateTable:type(type, tensorCache)
self.gradInput = {}
return parent.type(self, type, tensorCache)
end
| mit |
lyzardiar/RETools | PublicTools/bin/tools/bin/ios/x86/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.
}
| mit |
thedraked/darkstar | scripts/zones/Abyssea-Tahrongi/npcs/qm7.lua | 14 | 1376 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: qm7 (???)
-- Spawns Hedetet
-- @pos ? ? ? 45
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--[[
if (trade:hasItemQty(2921,1) and trade:hasItemQty(2948,1) and trade:getItemCount() == 2) then -- Player has all the required items.
if (GetMobAction(16961923) == ACTION_NONE) then -- Mob not already spawned from this
SpawnMob(16961923):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:tradeComplete();
end
end
]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(1010, 2921, 2948); -- Inform payer what items they need.
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
MonkeyFirst/Urho3D | bin/Data/LuaScripts/04_StaticScene.lua | 24 | 7000 | -- Static 3D scene example.
-- This sample demonstrates:
-- - Creating a 3D scene with static content
-- - Displaying the scene using the Renderer subsystem
-- - Handling keyboard and mouse input to move a freelook camera
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Hook up to the frame update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
-- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it
-- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
-- optimizing manner
scene_:CreateComponent("Octree")
-- Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple
-- plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger
-- (100 x 100 world units)
local planeNode = scene_:CreateChild("Plane")
planeNode.scale = Vector3(100.0, 1.0, 100.0)
local planeObject = planeNode:CreateComponent("StaticModel")
planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
-- Create a directional light to the world so that we can see something. The light scene node's orientation controls the
-- light direction we will use the SetDirection() function which calculates the orientation from a forward direction vector.
-- The light will use default settings (white light, no shadows)
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.6, -1.0, 0.8) -- The direction vector does not need to be normalized
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
-- Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a
-- quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains
-- LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll
-- see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the
-- same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the
-- scene.
local NUM_OBJECTS = 200
for i = 1, NUM_OBJECTS do
local mushroomNode = scene_:CreateChild("Mushroom")
mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)
mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
mushroomNode:SetScale(0.5 + Random(2.0))
local mushroomObject = mushroomNode:CreateComponent("StaticModel")
mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
end
-- Create a scene node for the camera, which we will move around
-- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode = scene_:CreateChild("Camera")
cameraNode:CreateComponent("Camera")
-- Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0, 5.0, 0.0)
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
-- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
-- use, but now we just use full screen and default render path configured in the engine command line options
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
local mouseMove = input.mouseMove
yaw = yaw +MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
-- Use the Translate() function (default local space) to move relative to the node's orientation.
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
| mit |
thedraked/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Wahraga.lua | 14 | 1201 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Wahraga
-- Guild Merchant: Alchemist Guild
-- @pos -76.836 -6.000 140.331 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(60425,8,23,5)) then
player:showText(npc,WAHRAGA_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
mamaddeveloper/7894 | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-2.0 |
thedraked/darkstar | scripts/globals/spells/battlefield_elegy.lua | 23 | 1594 | -----------------------------------------
-- Spell: Battlefield Elegy
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local duration = 120;
local power = 256;
local pCHR = caster:getStat(MOD_CHR);
local mCHR = target:getStat(MOD_CHR);
local dCHR = (pCHR - mCHR);
local resm = applyResistanceEffect(caster,spell,target,dCHR,SINGING_SKILL,0,EFFECT_ELEGY);
if (resm < 0.5) then
spell:setMsg(85); -- resist message
else
local iBoost = caster:getMod(MOD_ELEGY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost*10;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
-- Try to overwrite weaker elegy
if (target:addStatusEffect(EFFECT_ELEGY,power,0,duration)) then
spell:setMsg(237);
else
spell:setMsg(75); -- no effect
end
end
return EFFECT_ELEGY;
end; | gpl-3.0 |
NPLPackages/main | script/kids/3DMapSystemApp/mcml/test/test_pe_avatar.lua | 1 | 1168 | --[[
Title: test all mcml avatar tags
Author(s): WangTian
Date: 2008/3/16
Desc:
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemApp/mcml/test/test_pe_avatar.lua");
test_pe_avatar()
%TESTCASE{"test pe:avatar", func="test_pe_avatar"}%
-------------------------------------------------------
]]
NPL.load("(gl)script/kids/3DMapSystemApp/mcml/mcml.lua");
-- TODO: test
function test_pe_avatar()
local testString = [[
<pe:avatar uid = "6ea1ce24-bdf7-4893-a053-eb5fd2a74281" /pe:avatar>
]];
local mcmlNode = ParaXML.LuaXML_ParseString(testString);
if(mcmlNode) then
-- log(commonlib.serialize(mcmlNode));
Map3DSystem.mcml.buildclass(mcmlNode);
Map3DSystem.mcml_controls.create("test", mcmlNode, nil, _parent, 10, 10, 400, 400);
---- create a dialog with tab pages.
--_guihelper.ShowDialogBox("Test MCML renderer", nil, nil, 400, 400,
--function(_parent)
--Map3DSystem.mcml_controls.create("me", mcmlNode, nil, _parent, 10, 10, 400, 400)
--end,
--function(dialogResult)
--if(dialogResult == _guihelper.DialogResult.OK) then
--end
--return true;
--end);
end
end | gpl-2.0 |
ukoloff/rufus-lua-win | vendor/lua/lib/lua/luarocks/tools/patch.lua | 2 | 22316 | --- Patch utility to apply unified diffs.
--
-- http://lua-users.org/wiki/LuaPatch
--
-- (c) 2008 David Manura, Licensed under the same terms as Lua (MIT license).
-- Code is heavilly based on the Python-based patch.py version 8.06-1
-- Copyright (c) 2008 rainforce.org, MIT License
-- Project home: http://code.google.com/p/python-patch/ .
module("luarocks.tools.patch", package.seeall)
local fs = require("luarocks.fs")
local version = '0.1'
local io = io
local os = os
local string = string
local table = table
local format = string.format
-- logging
local debugmode = false
local function debug(s) end
local function info(s) end
local function warning(s) io.stderr:write(s .. '\n') end
-- Returns boolean whether string s2 starts with string s.
local function startswith(s, s2)
return s:sub(1, #s2) == s2
end
-- Returns boolean whether string s2 ends with string s.
local function endswith(s, s2)
return #s >= #s2 and s:sub(#s-#s2+1) == s2
end
-- Returns string s after filtering out any new-line characters from end.
local function endlstrip(s)
return s:gsub('[\r\n]+$', '')
end
-- Returns shallow copy of table t.
local function table_copy(t)
local t2 = {}
for k,v in pairs(t) do t2[k] = v end
return t2
end
-- Returns boolean whether array t contains value v.
local function array_contains(t, v)
for _,v2 in ipairs(t) do if v == v2 then return true end end
return false
end
local function exists(filename)
local fh = io.open(filename)
local result = fh ~= nil
if fh then fh:close() end
return result
end
local function isfile() return true end --FIX?
local function read_file(filename)
local fh, err, oserr = io.open(filename, 'rb')
if not fh then return fh, err, oserr end
local data, err, oserr = fh:read'*a'
fh:close()
if not data then return nil, err, oserr end
return data
end
local function write_file(filename, data)
local fh, err, oserr = io.open(filename 'wb')
if not fh then return fh, err, oserr end
local status, err, oserr = fh:write(data)
fh:close()
if not status then return nil, err, oserr end
return true
end
local function file_copy(src, dest)
local data, err, oserr = read_file(src)
if not data then return data, err, oserr end
local status, err, oserr = write_file(dest)
if not status then return status, err, oserr end
return true
end
local function string_as_file(s)
return {
at = 0,
str = s,
len = #s,
eof = false,
read = function(self, n)
if self.eof then return nil end
local chunk = self.str:sub(self.at, self.at+n)
self.at = self.at + n
if self.at > self.len then
self.eof = true
end
return chunk
end,
close = function(self)
self.eof = true
end,
}
end
--
-- file_lines(f) is similar to f:lines() for file f.
-- The main difference is that read_lines includes
-- new-line character sequences ("\n", "\r\n", "\r"),
-- if any, at the end of each line. Embedded "\0" are also handled.
-- Caution: The newline behavior can depend on whether f is opened
-- in binary or ASCII mode.
-- (file_lines - version 20080913)
--
local function file_lines(f)
local CHUNK_SIZE = 1024
local buffer = ""
local pos_beg = 1
return function()
local pos, chars
while 1 do
pos, chars = buffer:match('()([\r\n].)', pos_beg)
if pos or not f then
break
elseif f then
local chunk = f:read(CHUNK_SIZE)
if chunk then
buffer = buffer:sub(pos_beg) .. chunk
pos_beg = 1
else
f = nil
end
end
end
if not pos then
pos = #buffer
elseif chars == '\r\n' then
pos = pos + 1
end
local line = buffer:sub(pos_beg, pos)
pos_beg = pos + 1
if #line > 0 then
return line
end
end
end
local function match_linerange(line)
local m1, m2, m3, m4 = line:match("^@@ %-(%d+),(%d+) %+(%d+),(%d+)")
if not m1 then m1, m3, m4 = line:match("^@@ %-(%d+) %+(%d+),(%d+)") end
if not m1 then m1, m2, m3 = line:match("^@@ %-(%d+),(%d+) %+(%d+)") end
if not m1 then m1, m3 = line:match("^@@ %-(%d+) %+(%d+)") end
return m1, m2, m3, m4
end
function read_patch(filename, data)
-- define possible file regions that will direct the parser flow
local state = 'header'
-- 'header' - comments before the patch body
-- 'filenames' - lines starting with --- and +++
-- 'hunkhead' - @@ -R +R @@ sequence
-- 'hunkbody'
-- 'hunkskip' - skipping invalid hunk mode
local all_ok = true
local lineends = {lf=0, crlf=0, cr=0}
local files = {source={}, target={}, hunks={}, fileends={}, hunkends={}}
local nextfileno = 0
local nexthunkno = 0 --: even if index starts with 0 user messages
-- number hunks from 1
-- hunkinfo holds parsed values, hunkactual - calculated
local hunkinfo = {
startsrc=nil, linessrc=nil, starttgt=nil, linestgt=nil,
invalid=false, text={}
}
local hunkactual = {linessrc=nil, linestgt=nil}
info(format("reading patch %s", filename))
local fp
if data then
fp = string_as_file(data)
else
fp = filename == '-' and io.stdin or assert(io.open(filename, "rb"))
end
local lineno = 0
for line in file_lines(fp) do
lineno = lineno + 1
if state == 'header' then
if startswith(line, "--- ") then
state = 'filenames'
end
-- state is 'header' or 'filenames'
end
if state == 'hunkbody' then
-- skip hunkskip and hunkbody code until definition of hunkhead read
-- process line first
if line:match"^[- +\\]" or line:match"^[\r\n]*$" then
-- gather stats about line endings
local he = files.hunkends[nextfileno]
if endswith(line, "\r\n") then
he.crlf = he.crlf + 1
elseif endswith(line, "\n") then
he.lf = he.lf + 1
elseif endswith(line, "\r") then
he.cr = he.cr + 1
end
if startswith(line, "-") then
hunkactual.linessrc = hunkactual.linessrc + 1
elseif startswith(line, "+") then
hunkactual.linestgt = hunkactual.linestgt + 1
elseif startswith(line, "\\") then
-- nothing
else
hunkactual.linessrc = hunkactual.linessrc + 1
hunkactual.linestgt = hunkactual.linestgt + 1
end
table.insert(hunkinfo.text, line)
-- todo: handle \ No newline cases
else
warning(format("invalid hunk no.%d at %d for target file %s",
nexthunkno, lineno, files.target[nextfileno]))
-- add hunk status node
table.insert(files.hunks[nextfileno], table_copy(hunkinfo))
files.hunks[nextfileno][nexthunkno].invalid = true
all_ok = false
state = 'hunkskip'
end
-- check exit conditions
if hunkactual.linessrc > hunkinfo.linessrc or
hunkactual.linestgt > hunkinfo.linestgt
then
warning(format("extra hunk no.%d lines at %d for target %s",
nexthunkno, lineno, files.target[nextfileno]))
-- add hunk status node
table.insert(files.hunks[nextfileno], table_copy(hunkinfo))
files.hunks[nextfileno][nexthunkno].invalid = true
state = 'hunkskip'
elseif hunkinfo.linessrc == hunkactual.linessrc and
hunkinfo.linestgt == hunkactual.linestgt
then
table.insert(files.hunks[nextfileno], table_copy(hunkinfo))
state = 'hunkskip'
-- detect mixed window/unix line ends
local ends = files.hunkends[nextfileno]
if (ends.cr~=0 and 1 or 0) + (ends.crlf~=0 and 1 or 0) +
(ends.lf~=0 and 1 or 0) > 1
then
warning(format("inconsistent line ends in patch hunks for %s",
files.source[nextfileno]))
end
if debugmode then
local debuglines = {crlf=ends.crlf, lf=ends.lf, cr=ends.cr,
file=files.target[nextfileno], hunk=nexthunkno}
debug(format("crlf: %(crlf)d lf: %(lf)d cr: %(cr)d\t " ..
"- file: %(file)s hunk: %(hunk)d", debuglines))
end
end
-- state is 'hunkbody' or 'hunkskip'
end
if state == 'hunkskip' then
if match_linerange(line) then
state = 'hunkhead'
elseif startswith(line, "--- ") then
state = 'filenames'
if debugmode and #files.source > 0 then
debug(format("- %2d hunks for %s", #files.hunks[nextfileno],
files.source[nextfileno]))
end
end
-- state is 'hunkskip', 'hunkhead', or 'filenames'
end
local advance
if state == 'filenames' then
if startswith(line, "--- ") then
if array_contains(files.source, nextfileno) then
all_ok = false
warning(format("skipping invalid patch for %s",
files.source[nextfileno+1]))
table.remove(files.source, nextfileno+1)
-- double source filename line is encountered
-- attempt to restart from this second line
end
-- Accept a space as a terminator, like GNU patch does.
-- Breaks patches containing filenames with spaces...
-- FIXME Figure out what does GNU patch do in those cases.
local match = line:match("^--- ([^\t ]+)")
if not match then
all_ok = false
warning(format("skipping invalid filename at line %d", lineno+1))
state = 'header'
else
table.insert(files.source, match)
end
elseif not startswith(line, "+++ ") then
if array_contains(files.source, nextfileno) then
all_ok = false
warning(format("skipping invalid patch with no target for %s",
files.source[nextfileno+1]))
table.remove(files.source, nextfileno+1)
else
-- this should be unreachable
warning("skipping invalid target patch")
end
state = 'header'
else
if array_contains(files.target, nextfileno) then
all_ok = false
warning(format("skipping invalid patch - double target at line %d",
lineno+1))
table.remove(files.source, nextfileno+1)
table.remove(files.target, nextfileno+1)
nextfileno = nextfileno - 1
-- double target filename line is encountered
-- switch back to header state
state = 'header'
else
-- Accept a space as a terminator, like GNU patch does.
-- Breaks patches containing filenames with spaces...
-- FIXME Figure out what does GNU patch do in those cases.
local re_filename = "^%+%+%+ ([^ \t]+)"
local match = line:match(re_filename)
if not match then
all_ok = false
warning(format(
"skipping invalid patch - no target filename at line %d",
lineno+1))
state = 'header'
else
table.insert(files.target, match)
nextfileno = nextfileno + 1
nexthunkno = 0
table.insert(files.hunks, {})
table.insert(files.hunkends, table_copy(lineends))
table.insert(files.fileends, table_copy(lineends))
state = 'hunkhead'
advance = true
end
end
end
-- state is 'filenames', 'header', or ('hunkhead' with advance)
end
if not advance and state == 'hunkhead' then
local m1, m2, m3, m4 = match_linerange(line)
if not m1 then
if not array_contains(files.hunks, nextfileno-1) then
all_ok = false
warning(format("skipping invalid patch with no hunks for file %s",
files.target[nextfileno]))
end
state = 'header'
else
hunkinfo.startsrc = tonumber(m1)
hunkinfo.linessrc = tonumber(m2 or 1)
hunkinfo.starttgt = tonumber(m3)
hunkinfo.linestgt = tonumber(m4 or 1)
hunkinfo.invalid = false
hunkinfo.text = {}
hunkactual.linessrc = 0
hunkactual.linestgt = 0
state = 'hunkbody'
nexthunkno = nexthunkno + 1
end
-- state is 'header' or 'hunkbody'
end
end
if state ~= 'hunkskip' then
warning(format("patch file incomplete - %s", filename))
all_ok = false
-- os.exit(?)
else
-- duplicated message when an eof is reached
if debugmode and #files.source > 0 then
debug(format("- %2d hunks for %s", #files.hunks[nextfileno],
files.source[nextfileno]))
end
end
local sum = 0; for _,hset in ipairs(files.hunks) do sum = sum + #hset end
info(format("total files: %d total hunks: %d", #files.source, sum))
fp:close()
return files, all_ok
end
local function find_hunk(file, h, hno)
for fuzz=0,2 do
local lineno = h.startsrc
for i=0,#file do
local found = true
local location = lineno
local total = #h.text - fuzz
for l, hline in ipairs(h.text) do
if l > fuzz then
-- todo: \ No newline at the end of file
if startswith(hline, " ") or startswith(hline, "-") then
local line = file[lineno]
lineno = lineno + 1
if not line or #line == 0 then
found = false
break
end
if endlstrip(line) ~= endlstrip(hline:sub(2)) then
found = false
break
end
end
end
end
if found then
local offset = location - h.startsrc - fuzz
if offset ~= 0 then
warning(format("Hunk %d found at offset %d%s...", hno, offset, fuzz == 0 and "" or format(" (fuzz %d)", fuzz)))
end
h.startsrc = location
h.starttgt = h.starttgt + offset
for i=1,fuzz do
table.remove(h.text, 1)
table.remove(h.text, #h.text)
end
return true
end
lineno = i
end
end
return false
end
local function load_file(filename)
local fp = assert(io.open(filename))
local file = {}
local readline = file_lines(fp)
while true do
local line = readline()
if not line then break end
table.insert(file, line)
end
fp:close()
return file
end
local function find_hunks(file, hunks)
local matched = true
local lineno = 1
local hno = nil
for hno, h in ipairs(hunks) do
find_hunk(file, h, hno)
end
end
local function check_patched(file, hunks)
local matched = true
local lineno = 1
local hno = nil
local ok, err = pcall(function()
if #file == 0 then
error 'nomatch'
end
for hno, h in ipairs(hunks) do
-- skip to line just before hunk starts
if #file < h.starttgt then
error 'nomatch'
end
lineno = h.starttgt
for _, hline in ipairs(h.text) do
-- todo: \ No newline at the end of file
if not startswith(hline, "-") and not startswith(hline, "\\") then
local line = file[lineno]
lineno = lineno + 1
if #line == 0 then
error 'nomatch'
end
if endlstrip(line) ~= endlstrip(hline:sub(2)) then
warning(format("file is not patched - failed hunk: %d", hno))
error 'nomatch'
end
end
end
end
end)
if err == 'nomatch' then
matched = false
end
-- todo: display failed hunk, i.e. expected/found
return matched
end
local function patch_hunks(srcname, tgtname, hunks)
local src = assert(io.open(srcname, "rb"))
local tgt = assert(io.open(tgtname, "wb"))
local src_readline = file_lines(src)
-- todo: detect linefeeds early - in apply_files routine
-- to handle cases when patch starts right from the first
-- line and no lines are processed. At the moment substituted
-- lineends may not be the same at the start and at the end
-- of patching. Also issue a warning about mixed lineends
local srclineno = 1
local lineends = {['\n']=0, ['\r\n']=0, ['\r']=0}
for hno, h in ipairs(hunks) do
debug(format("processing hunk %d for file %s", hno, tgtname))
-- skip to line just before hunk starts
while srclineno < h.startsrc do
local line = src_readline()
-- Python 'U' mode works only with text files
if endswith(line, "\r\n") then
lineends["\r\n"] = lineends["\r\n"] + 1
elseif endswith(line, "\n") then
lineends["\n"] = lineends["\n"] + 1
elseif endswith(line, "\r") then
lineends["\r"] = lineends["\r"] + 1
end
tgt:write(line)
srclineno = srclineno + 1
end
for _,hline in ipairs(h.text) do
-- todo: check \ No newline at the end of file
if startswith(hline, "-") or startswith(hline, "\\") then
src_readline()
srclineno = srclineno + 1
else
if not startswith(hline, "+") then
src_readline()
srclineno = srclineno + 1
end
local line2write = hline:sub(2)
-- detect if line ends are consistent in source file
local sum = 0
for k,v in pairs(lineends) do if v > 0 then sum=sum+1 end end
if sum == 1 then
local newline
for k,v in pairs(lineends) do if v ~= 0 then newline = k end end
tgt:write(endlstrip(line2write) .. newline)
else -- newlines are mixed or unknown
tgt:write(line2write)
end
end
end
end
for line in src_readline do
tgt:write(line)
end
tgt:close()
src:close()
return true
end
local function strip_dirs(filename, strip)
if strip == nil then return filename end
for i=1,strip do
filename=filename:gsub("^[^/]*/", "")
end
return filename
end
function apply_patch(patch, strip)
local all_ok = true
local total = #patch.source
for fileno, filename in ipairs(patch.source) do
filename = strip_dirs(filename, strip)
local continue
local f2patch = filename
if not exists(f2patch) then
f2patch = strip_dirs(patch.target[fileno], strip)
f2patch = fs.absolute_name(f2patch)
if not exists(f2patch) then --FIX:if f2patch nil
warning(format("source/target file does not exist\n--- %s\n+++ %s",
filename, f2patch))
all_ok = false
continue = true
end
end
if not continue and not isfile(f2patch) then
warning(format("not a file - %s", f2patch))
all_ok = false
continue = true
end
if not continue then
filename = f2patch
info(format("processing %d/%d:\t %s", fileno, total, filename))
-- validate before patching
local hunks = patch.hunks[fileno]
local file = load_file(filename)
local hunkno = 1
local hunk = hunks[hunkno]
local hunkfind = {}
local hunkreplace = {}
local validhunks = 0
local canpatch = false
local hunklineno
local isbreak
local lineno = 0
find_hunks(file, hunks)
for _, line in ipairs(file) do
lineno = lineno + 1
local continue
if not hunk or lineno < hunk.startsrc then
continue = true
elseif lineno == hunk.startsrc then
hunkfind = {}
for _,x in ipairs(hunk.text) do
if x:sub(1,1) == ' ' or x:sub(1,1) == '-' then
hunkfind[#hunkfind+1] = endlstrip(x:sub(2))
end end
hunkreplace = {}
for _,x in ipairs(hunk.text) do
if x:sub(1,1) == ' ' or x:sub(1,1) == '+' then
hunkreplace[#hunkreplace+1] = endlstrip(x:sub(2))
end end
--pprint(hunkreplace)
hunklineno = 1
-- todo \ No newline at end of file
end
-- check hunks in source file
if not continue and lineno < hunk.startsrc + #hunkfind - 1 then
if endlstrip(line) == hunkfind[hunklineno] then
hunklineno = hunklineno + 1
else
debug(format("hunk no.%d doesn't match source file %s",
hunkno, filename))
-- file may be already patched, but check other hunks anyway
hunkno = hunkno + 1
if hunkno <= #hunks then
hunk = hunks[hunkno]
continue = true
else
isbreak = true; break
end
end
end
-- check if processed line is the last line
if not continue and lineno == hunk.startsrc + #hunkfind - 1 then
debug(format("file %s hunk no.%d -- is ready to be patched",
filename, hunkno))
hunkno = hunkno + 1
validhunks = validhunks + 1
if hunkno <= #hunks then
hunk = hunks[hunkno]
else
if validhunks == #hunks then
-- patch file
canpatch = true
isbreak = true; break
end
end
end
end
if not isbreak then
if hunkno <= #hunks then
warning(format("premature end of source file %s at hunk %d",
filename, hunkno))
all_ok = false
end
end
if validhunks < #hunks then
if check_patched(file, hunks) then
warning(format("already patched %s", filename))
else
warning(format("source file is different - %s", filename))
all_ok = false
end
end
if canpatch then
local backupname = filename .. ".orig"
if exists(backupname) then
warning(format("can't backup original file to %s - aborting",
backupname))
all_ok = false
else
assert(os.rename(filename, backupname))
if patch_hunks(backupname, filename, hunks) then
warning(format("successfully patched %s", filename))
assert(os.remove(backupname))
else
warning(format("error patching file %s", filename))
assert(file_copy(filename, filename .. ".invalid"))
warning(format("invalid version is saved to %s",
filename .. ".invalid"))
-- todo: proper rejects
assert(os.rename(backupname, filename))
all_ok = false
end
end
end
end -- if not continue
end -- for
-- todo: check for premature eof
return all_ok
end
| mit |
SnabbCo/snabbswitch | lib/ljsyscall/syscall/openbsd/constants.lua | 24 | 20467 | -- tables of constants for NetBSD
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string, select =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string, select
local abi = require "syscall.abi"
local h = require "syscall.helpers"
local bit = require "syscall.bit"
local version = require "syscall.openbsd.version".version
local octal, multiflags, charflags, swapflags, strflag, atflag, modeflags
= h.octal, h.multiflags, h.charflags, h.swapflags, h.strflag, h.atflag, h.modeflags
local ffi = require "ffi"
local function charp(n) return ffi.cast("char *", n) end
local c = {}
c.errornames = require "syscall.openbsd.errors"
c.STD = strflag {
IN_FILENO = 0,
OUT_FILENO = 1,
ERR_FILENO = 2,
IN = 0,
OUT = 1,
ERR = 2,
}
c.E = strflag {
PERM = 1,
NOENT = 2,
SRCH = 3,
INTR = 4,
IO = 5,
NXIO = 6,
["2BIG"] = 7,
NOEXEC = 8,
BADF = 9,
CHILD = 10,
DEADLK = 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,
AGAIN = 35,
INPROGRESS = 36,
ALREADY = 37,
NOTSOCK = 38,
DESTADDRREQ = 39,
MSGSIZE = 40,
PROTOTYPE = 41,
NOPROTOOPT = 42,
PROTONOSUPPORT= 43,
SOCKTNOSUPPORT= 44,
OPNOTSUPP = 45,
PFNOSUPPORT = 46,
AFNOSUPPORT = 47,
ADDRINUSE = 48,
ADDRNOTAVAIL = 49,
NETDOWN = 50,
NETUNREACH = 51,
NETRESET = 52,
CONNABORTED = 53,
CONNRESET = 54,
NOBUFS = 55,
ISCONN = 56,
NOTCONN = 57,
SHUTDOWN = 58,
TOOMANYREFS = 59,
TIMEDOUT = 60,
CONNREFUSED = 61,
LOOP = 62,
NAMETOOLONG = 63,
HOSTDOWN = 64,
HOSTUNREACH = 65,
NOTEMPTY = 66,
PROCLIM = 67,
USERS = 68,
DQUOT = 69,
STALE = 70,
REMOTE = 71,
BADRPC = 72,
BADRPC = 72,
RPCMISMATCH = 73,
PROGUNAVAIL = 74,
PROGMISMATCH = 75,
PROCUNAVAIL = 76,
NOLCK = 77,
NOSYS = 78,
FTYPE = 79,
AUTH = 80,
NEEDAUTH = 81,
IPSEC = 82,
NOATTR = 83,
ILSEQ = 84,
NOMEDIUM = 85,
MEDIUMTYPE = 86,
OVERFLOW = 87,
CANCELED = 88,
IDRM = 89,
NOMSG = 90,
NOTSUP = 91,
}
-- alternate names
c.EALIAS = {
WOULDBLOCK = c.E.AGAIN,
}
c.AF = strflag {
UNSPEC = 0,
LOCAL = 1,
INET = 2,
IMPLINK = 3,
PUP = 4,
CHAOS = 5,
ISO = 7,
ECMA = 8,
DATAKIT = 9,
CCITT = 10,
SNA = 11,
DECNET = 12,
DLI = 13,
LAT = 14,
HYLINK = 15,
APPLETALK = 16,
ROUTE = 17,
LINK = 18,
-- pseudo_AF_XTP 19
COIP = 20,
CNT = 21,
-- pseudo_AF_RTIP 22
IPX = 23,
INET6 = 24,
-- pseudo_AF_PIP 25
ISDN = 26,
NATM = 27,
ENCAP = 28,
SIP = 29,
KEY = 30,
-- pseudo_AF_HDRCMPLT 31
BLUETOOTH = 32,
MPLS = 33,
-- pseudo_AF_PFLOW 34
-- pseudo_AF_PIPEX 35
}
c.AF.UNIX = c.AF.LOCAL
c.AF.OSI = c.AF.ISO
c.AF.E164 = c.AF.ISDN
c.O = multiflags {
RDONLY = 0x0000,
WRONLY = 0x0001,
RDWR = 0x0002,
ACCMODE = 0x0003,
NONBLOCK = 0x0004,
APPEND = 0x0008,
SHLOCK = 0x0010,
EXLOCK = 0x0020,
ASYNC = 0x0040,
FSYNC = 0x0080,
SYNC = 0x0080,
NOFOLLOW = 0x0100,
CREAT = 0x0200,
TRUNC = 0x0400,
EXCL = 0x0800,
NOCTTY = 0x8000,
CLOEXEC = 0x10000,
DIRECTORY = 0x20000,
}
-- for pipe2, selected flags from c.O
c.OPIPE = multiflags {
NONBLOCK = 0x0004,
CLOEXEC = 0x10000,
}
-- sigaction, note renamed SIGACT from SIG_
c.SIGACT = strflag {
ERR = -1,
DFL = 0,
IGN = 1,
HOLD = 3,
}
c.SIG = strflag {
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,
URG = 16,
STOP = 17,
TSTP = 18,
CONT = 19,
CHLD = 20,
TTIN = 21,
TTOU = 22,
IO = 23,
XCPU = 24,
XFSZ = 25,
VTALRM = 26,
PROF = 27,
WINCH = 28,
INFO = 29,
USR1 = 30,
USR2 = 31,
THR = 32,
}
c.EXIT = strflag {
SUCCESS = 0,
FAILURE = 1,
}
c.OK = charflags {
F = 0,
X = 0x01,
W = 0x02,
R = 0x04,
}
c.MODE = modeflags {
SUID = octal('04000'),
SGID = octal('02000'),
STXT = octal('01000'),
RWXU = octal('00700'),
RUSR = octal('00400'),
WUSR = octal('00200'),
XUSR = octal('00100'),
RWXG = octal('00070'),
RGRP = octal('00040'),
WGRP = octal('00020'),
XGRP = octal('00010'),
RWXO = octal('00007'),
ROTH = octal('00004'),
WOTH = octal('00002'),
XOTH = octal('00001'),
}
c.SEEK = strflag {
SET = 0,
CUR = 1,
END = 2,
}
c.SOCK = multiflags {
STREAM = 1,
DGRAM = 2,
RAW = 3,
RDM = 4,
SEQPACKET = 5,
}
if version >= 201505 then
c.SOCK.NONBLOCK = 0x4000
c.SOCK.CLOEXEC = 0x8000
end
c.SOL = strflag {
SOCKET = 0xffff,
}
c.POLL = multiflags {
IN = 0x0001,
PRI = 0x0002,
OUT = 0x0004,
RDNORM = 0x0040,
RDBAND = 0x0080,
WRBAND = 0x0100,
ERR = 0x0008,
HUP = 0x0010,
NVAL = 0x0020,
}
c.POLL.WRNORM = c.POLL.OUT
c.AT_FDCWD = atflag {
FDCWD = -100,
}
c.AT = multiflags {
EACCESS = 0x01,
SYMLINK_NOFOLLOW = 0x02,
SYMLINK_FOLLOW = 0x04,
REMOVEDIR = 0x08,
}
c.S_I = modeflags {
FMT = octal('0170000'),
FSOCK = octal('0140000'),
FLNK = octal('0120000'),
FREG = octal('0100000'),
FBLK = octal('0060000'),
FDIR = octal('0040000'),
FCHR = octal('0020000'),
FIFO = octal('0010000'),
SUID = octal('0004000'),
SGID = octal('0002000'),
SVTX = octal('0001000'),
STXT = octal('0001000'),
RWXU = octal('00700'),
RUSR = octal('00400'),
WUSR = octal('00200'),
XUSR = octal('00100'),
RWXG = octal('00070'),
RGRP = octal('00040'),
WGRP = octal('00020'),
XGRP = octal('00010'),
RWXO = octal('00007'),
ROTH = octal('00004'),
WOTH = octal('00002'),
XOTH = octal('00001'),
}
c.S_I.READ = c.S_I.RUSR
c.S_I.WRITE = c.S_I.WUSR
c.S_I.EXEC = c.S_I.XUSR
c.PROT = multiflags {
NONE = 0x0,
READ = 0x1,
WRITE = 0x2,
EXEC = 0x4,
}
c.MAP = multiflags {
SHARED = 0x0001,
PRIVATE = 0x0002,
FILE = 0x0000,
FIXED = 0x0010,
ANON = 0x1000,
}
if version < 201411 then -- defined in 5.6 but as zero so no effect
c.MAP.RENAME = 0x0020
c.MAP.NORESERVE = 0x0040
c.MAP.HASSEMAPHORE = 0x0200
end
c.MCL = strflag {
CURRENT = 0x01,
FUTURE = 0x02,
}
-- flags to `msync'. - note was MS_ renamed to MSYNC_
c.MSYNC = multiflags {
ASYNC = 0x01,
SYNC = 0x02,
INVALIDATE = 0x04,
}
c.MADV = strflag {
NORMAL = 0,
RANDOM = 1,
SEQUENTIAL = 2,
WILLNEED = 3,
DONTNEED = 4,
SPACEAVAIL = 5,
FREE = 6,
}
c.IPPROTO = strflag {
IP = 0,
HOPOPTS = 0,
ICMP = 1,
IGMP = 2,
GGP = 3,
IPV4 = 4,
IPIP = 4,
TCP = 6,
EGP = 8,
PUP = 12,
UDP = 17,
IDP = 22,
TP = 29,
IPV6 = 41,
ROUTING = 43,
FRAGMENT = 44,
RSVP = 46,
GRE = 47,
ESP = 50,
AH = 51,
MOBILE = 55,
ICMPV6 = 58,
NONE = 59,
DSTOPTS = 60,
EON = 80,
ETHERIP = 97,
ENCAP = 98,
PIM = 103,
IPCOMP = 108,
CARP = 112,
MPLS = 137,
PFSYNC = 240,
RAW = 255,
}
c.SCM = multiflags {
RIGHTS = 0x01,
TIMESTAMP = 0x04,
}
c.F = strflag {
DUPFD = 0,
GETFD = 1,
SETFD = 2,
GETFL = 3,
SETFL = 4,
GETOWN = 5,
SETOWN = 6,
GETLK = 7,
SETLK = 8,
SETLKW = 9,
DUPFD_CLOEXEC= 10,
}
c.FD = multiflags {
CLOEXEC = 1,
}
-- note changed from F_ to FCNTL_LOCK
c.FCNTL_LOCK = strflag {
RDLCK = 1,
UNLCK = 2,
WRLCK = 3,
}
-- lockf, changed from F_ to LOCKF_
c.LOCKF = strflag {
ULOCK = 0,
LOCK = 1,
TLOCK = 2,
TEST = 3,
}
-- for flock (2)
c.LOCK = multiflags {
SH = 0x01,
EX = 0x02,
NB = 0x04,
UN = 0x08,
}
c.W = multiflags {
NOHANG = 1,
UNTRACED = 2,
CONTINUED = 8,
STOPPED = octal "0177",
}
if version < 201405 then
c.W.ALTSIG = 4
end
-- waitpid and wait4 pid
c.WAIT = strflag {
ANY = -1,
MYPGRP = 0,
}
c.MSG = multiflags {
OOB = 0x1,
PEEK = 0x2,
DONTROUTE = 0x4,
EOR = 0x8,
TRUNC = 0x10,
CTRUNC = 0x20,
WAITALL = 0x40,
DONTWAIT = 0x80,
BCAST = 0x100,
MCAST = 0x200,
NOSIGNAL = 0x400,
}
c.PC = strflag {
LINK_MAX = 1,
MAX_CANON = 2,
MAX_INPUT = 3,
NAME_MAX = 4,
PATH_MAX = 5,
PIPE_BUF = 6,
CHOWN_RESTRICTED = 7,
NO_TRUNC = 8,
VDISABLE = 9,
["2_SYMLINKS"] = 10,
ALLOC_SIZE_MIN = 11,
ASYNC_IO = 12,
FILESIZEBITS = 13,
PRIO_IO = 14,
REC_INCR_XFER_SIZE= 15,
REC_MAX_XFER_SIZE = 16,
REC_MIN_XFER_SIZE = 17,
REC_XFER_ALIGN = 18,
SYMLINK_MAX = 19,
SYNC_IO = 20,
TIMESTAMP_RESOLUTION = 21,
}
-- getpriority, setpriority flags
c.PRIO = strflag {
PROCESS = 0,
PGRP = 1,
USER = 2,
MIN = -20, -- TODO useful to have for other OSs
MAX = 20,
}
c.RUSAGE = strflag {
SELF = 0,
CHILDREN = -1,
THREAD = 1,
}
c.SOMAXCONN = 128
c.SO = strflag {
DEBUG = 0x0001,
ACCEPTCONN = 0x0002,
REUSEADDR = 0x0004,
KEEPALIVE = 0x0008,
DONTROUTE = 0x0010,
BROADCAST = 0x0020,
USELOOPBACK = 0x0040,
LINGER = 0x0080,
OOBINLINE = 0x0100,
REUSEPORT = 0x0200,
TIMESTAMP = 0x0800,
BINDANY = 0x1000,
SNDBUF = 0x1001,
RCVBUF = 0x1002,
SNDLOWAT = 0x1003,
RCVLOWAT = 0x1004,
SNDTIMEO = 0x1005,
RCVTIMEO = 0x1006,
ERROR = 0x1007,
TYPE = 0x1008,
NETPROC = 0x1020,
RTABLE = 0x1021,
PEERCRED = 0x1022,
SPLICE = 0x1023,
}
c.DT = strflag {
UNKNOWN = 0,
FIFO = 1,
CHR = 2,
DIR = 4,
BLK = 6,
REG = 8,
LNK = 10,
SOCK = 12,
}
c.IP = strflag {
OPTIONS = 1,
HDRINCL = 2,
TOS = 3,
TTL = 4,
RECVOPTS = 5,
RECVRETOPTS = 6,
RECVDSTADDR = 7,
RETOPTS = 8,
MULTICAST_IF = 9,
MULTICAST_TTL = 10,
MULTICAST_LOOP = 11,
ADD_MEMBERSHIP = 12,
DROP_MEMBERSHIP = 13,
PORTRANGE = 19,
AUTH_LEVEL = 20,
ESP_TRANS_LEVEL = 21,
ESP_NETWORK_LEVEL = 22,
IPSEC_LOCAL_ID = 23,
IPSEC_REMOTE_ID = 24,
IPSEC_LOCAL_CRED = 25,
IPSEC_REMOTE_CRED = 26,
IPSEC_LOCAL_AUTH = 27,
IPSEC_REMOTE_AUTH = 28,
IPCOMP_LEVEL = 29,
RECVIF = 30,
RECVTTL = 31,
MINTTL = 32,
RECVDSTPORT = 33,
PIPEX = 34,
RECVRTABLE = 35,
IPSECFLOWINFO = 36,
RTABLE = 0x1021,
DIVERTFL = 0x1022,
}
-- Baud rates just the identity function other than EXTA, EXTB TODO check
c.B = strflag {
}
c.CC = strflag {
VEOF = 0,
VEOL = 1,
VEOL2 = 2,
VERASE = 3,
VWERASE = 4,
VKILL = 5,
VREPRINT = 6,
VINTR = 8,
VQUIT = 9,
VSUSP = 10,
VDSUSP = 11,
VSTART = 12,
VSTOP = 13,
VLNEXT = 14,
VDISCARD = 15,
VMIN = 16,
VTIME = 17,
VSTATUS = 18,
}
c.IFLAG = multiflags {
IGNBRK = 0x00000001,
BRKINT = 0x00000002,
IGNPAR = 0x00000004,
PARMRK = 0x00000008,
INPCK = 0x00000010,
ISTRIP = 0x00000020,
INLCR = 0x00000040,
IGNCR = 0x00000080,
ICRNL = 0x00000100,
IXON = 0x00000200,
IXOFF = 0x00000400,
IXANY = 0x00000800,
IMAXBEL = 0x00002000,
}
c.OFLAG = multiflags {
OPOST = 0x00000001,
ONLCR = 0x00000002,
OXTABS = 0x00000004,
ONOEOT = 0x00000008,
OCRNL = 0x00000010,
OLCUC = 0x00000020,
ONOCR = 0x00000040,
ONLRET = 0x00000080,
}
c.CFLAG = multiflags {
CIGNORE = 0x00000001,
CSIZE = 0x00000300,
CS5 = 0x00000000,
CS6 = 0x00000100,
CS7 = 0x00000200,
CS8 = 0x00000300,
CSTOPB = 0x00000400,
CREAD = 0x00000800,
PARENB = 0x00001000,
PARODD = 0x00002000,
HUPCL = 0x00004000,
CLOCAL = 0x00008000,
CRTSCTS = 0x00010000,
MDMBUF = 0x00100000,
}
c.CFLAG.CRTS_IFLOW = c.CFLAG.CRTSCTS
c.CFLAG.CCTS_OFLOW = c.CFLAG.CRTSCTS
c.CFLAG.CHWFLOW = c.CFLAG.MDMBUF + c.CFLAG.CRTSCTS
c.LFLAG = multiflags {
ECHOKE = 0x00000001,
ECHOE = 0x00000002,
ECHOK = 0x00000004,
ECHO = 0x00000008,
ECHONL = 0x00000010,
ECHOPRT = 0x00000020,
ECHOCTL = 0x00000040,
ISIG = 0x00000080,
ICANON = 0x00000100,
ALTWERASE = 0x00000200,
IEXTEN = 0x00000400,
EXTPROC = 0x00000800,
TOSTOP = 0x00400000,
FLUSHO = 0x00800000,
NOKERNINFO = 0x02000000,
PENDIN = 0x20000000,
NOFLSH = 0x80000000,
}
c.TCSA = multiflags { -- this is another odd one, where you can have one flag plus SOFT
NOW = 0,
DRAIN = 1,
FLUSH = 2,
SOFT = 0x10,
}
-- tcflush(), renamed from TC to TCFLUSH
c.TCFLUSH = strflag {
IFLUSH = 1,
OFLUSH = 2,
IOFLUSH = 3,
}
-- termios - tcflow() and TCXONC use these. renamed from TC to TCFLOW
c.TCFLOW = strflag {
OOFF = 1,
OON = 2,
IOFF = 3,
ION = 4,
}
-- for chflags and stat. note these have no prefix
c.CHFLAGS = multiflags {
UF_NODUMP = 0x00000001,
UF_IMMUTABLE = 0x00000002,
UF_APPEND = 0x00000004,
UF_OPAQUE = 0x00000008,
SF_ARCHIVED = 0x00010000,
SF_IMMUTABLE = 0x00020000,
SF_APPEND = 0x00040000,
}
c.CHFLAGS.IMMUTABLE = c.CHFLAGS.UF_IMMUTABLE + c.CHFLAGS.SF_IMMUTABLE
c.CHFLAGS.APPEND = c.CHFLAGS.UF_APPEND + c.CHFLAGS.SF_APPEND
c.CHFLAGS.OPAQUE = c.CHFLAGS.UF_OPAQUE
c.TCP = strflag {
NODELAY = 0x01,
MAXSEG = 0x02,
MD5SIG = 0x04,
SACK_ENABLE = 0x08,
}
c.RB = multiflags {
AUTOBOOT = 0,
ASKNAME = 0x0001,
SINGLE = 0x0002,
NOSYNC = 0x0004,
HALT = 0x0008,
INITNAME = 0x0010,
DFLTROOT = 0x0020,
KDB = 0x0040,
RDONLY = 0x0080,
DUMP = 0x0100,
MINIROOT = 0x0200,
CONFIG = 0x0400,
TIMEBAD = 0x0800,
POWERDOWN = 0x1000,
SERCONS = 0x2000,
USERREQ = 0x4000,
}
-- kqueue
c.EV = multiflags {
ADD = 0x0001,
DELETE = 0x0002,
ENABLE = 0x0004,
DISABLE = 0x0008,
ONESHOT = 0x0010,
CLEAR = 0x0020,
SYSFLAGS = 0xF000,
FLAG1 = 0x2000,
EOF = 0x8000,
ERROR = 0x4000,
}
c.EVFILT = strflag {
READ = -1,
WRITE = -2,
AIO = -3,
VNODE = -4,
PROC = -5,
SIGNAL = -6,
TIMER = -7,
SYSCOUNT = 7,
}
c.NOTE = multiflags {
-- read and write
LOWAT = 0x0001,
-- vnode
DELETE = 0x0001,
WRITE = 0x0002,
EXTEND = 0x0004,
ATTRIB = 0x0008,
LINK = 0x0010,
RENAME = 0x0020,
REVOKE = 0x0040,
-- proc
EXIT = 0x80000000,
FORK = 0x40000000,
EXEC = 0x20000000,
PCTRLMASK = 0xf0000000,
PDATAMASK = 0x000fffff,
TRACK = 0x00000001,
TRACKERR = 0x00000002,
CHILD = 0x00000004,
}
c.ITIMER = strflag {
REAL = 0,
VIRTUAL = 1,
PROF = 2,
}
c.SA = multiflags {
ONSTACK = 0x0001,
RESTART = 0x0002,
RESETHAND = 0x0004,
NOCLDSTOP = 0x0008,
NODEFER = 0x0010,
NOCLDWAIT = 0x0020,
SIGINFO = 0x0040,
}
-- ipv6 sockopts
c.IPV6 = strflag {
UNICAST_HOPS = 4,
MULTICAST_IF = 9,
MULTICAST_HOPS = 10,
MULTICAST_LOOP = 11,
JOIN_GROUP = 12,
LEAVE_GROUP = 13,
PORTRANGE = 14,
--ICMP6_FILTER = 18, -- not namespaced as IPV6
CHECKSUM = 26,
V6ONLY = 27,
RTHDRDSTOPTS = 35,
RECVPKTINFO = 36,
RECVHOPLIMIT = 37,
RECVRTHDR = 38,
RECVHOPOPTS = 39,
RECVDSTOPTS = 40,
USE_MIN_MTU = 42,
RECVPATHMTU = 43,
PATHMTU = 44,
PKTINFO = 46,
HOPLIMIT = 47,
NEXTHOP = 48,
HOPOPTS = 49,
DSTOPTS = 50,
RTHDR = 51,
RECVTCLASS = 57,
TCLASS = 61,
DONTFRAG = 62,
}
if version < 201405 then
c.IPV6.SOCKOPT_RESERVED1 = 3
c.IPV6.FAITH = 29
end
c.CLOCK = strflag {
REALTIME = 0,
PROCESS_CPUTIME_ID = 2,
MONOTONIC = 3,
THREAD_CPUTIME_ID = 4,
}
if version < 201505 then
c.CLOCK.VIRTUAL = 1
end
if version >= 201505 then
c.CLOCK.UPTIME = 5
end
c.UTIME = strflag {
NOW = -2,
OMIT = -1,
}
c.PATH_MAX = 1024
c.CTL = strflag {
UNSPEC = 0,
KERN = 1,
VM = 2,
FS = 3,
NET = 4,
DEBUG = 5,
HW = 6,
MACHDEP = 7,
DDB = 9,
VFS = 10,
MAXID = 11,
}
c.KERN = strflag {
OSTYPE = 1,
OSRELEASE = 2,
OSREV = 3,
VERSION = 4,
MAXVNODES = 5,
MAXPROC = 6,
MAXFILES = 7,
ARGMAX = 8,
SECURELVL = 9,
HOSTNAME = 10,
HOSTID = 11,
CLOCKRATE = 12,
PROF = 16,
POSIX1 = 17,
NGROUPS = 18,
JOB_CONTROL = 19,
SAVED_IDS = 20,
BOOTTIME = 21,
DOMAINNAME = 22,
MAXPARTITIONS = 23,
RAWPARTITION = 24,
MAXTHREAD = 25,
NTHREADS = 26,
OSVERSION = 27,
SOMAXCONN = 28,
SOMINCONN = 29,
USERMOUNT = 30,
RND = 31,
NOSUIDCOREDUMP = 32,
FSYNC = 33,
SYSVMSG = 34,
SYSVSEM = 35,
SYSVSHM = 36,
ARND = 37,
MSGBUFSIZE = 38,
MALLOCSTATS = 39,
CPTIME = 40,
NCHSTATS = 41,
FORKSTAT = 42,
NSELCOLL = 43,
TTY = 44,
CCPU = 45,
FSCALE = 46,
NPROCS = 47,
MSGBUF = 48,
POOL = 49,
STACKGAPRANDOM = 50,
SYSVIPC_INFO = 51,
SPLASSERT = 54,
PROC_ARGS = 55,
NFILES = 56,
TTYCOUNT = 57,
NUMVNODES = 58,
MBSTAT = 59,
SEMINFO = 61,
SHMINFO = 62,
INTRCNT = 63,
WATCHDOG = 64,
EMUL = 65,
PROC = 66,
MAXCLUSTERS = 67,
EVCOUNT = 68,
TIMECOUNTER = 69,
MAXLOCKSPERUID = 70,
CPTIME2 = 71,
CACHEPCT = 72,
FILE = 73,
CONSDEV = 75,
NETLIVELOCKS = 76,
POOL_DEBUG = 77,
PROC_CWD = 78,
}
if version < 201405 then
c.KERN.FILE = 15
c.KERN.FILE2 = 73
end
if version >= 201411 then
c.KERN.PROC_NOBROADCASTKILL = 79
end
if version < 201505 then
c.KERN.VNODE = 13
c.KERN.USERCRYPTO = 52
c.KERN.CRYPTODEVALLOWSOFT = 53
c.KERN.USERASYMCRYPTO = 60
end
return c
| apache-2.0 |
mamaddeveloper/7894 | plugins/inf.lua | 1 | 31182 | local function get_rank_by_username(extra, success, result)
if success == 0 then
return send_large_msg(extra.receiver, lang_text('noUsernameFound'))
end
local rank = get_rank(result.peer_id, extra.chat_id)
send_large_msg(extra.receiver, lang_text('rank') .. reverse_rank_table[rank + 1])
end
local function get_rank_by_reply(extra, success, result)
local rank = get_rank(result.from.peer_id, result.to.peer_id)
send_large_msg(extra.receiver, lang_text('rank') .. reverse_rank_table[rank + 1])
end
local function callback_group_members(extra, success, result)
local i = 1
local chat_id = "chat#id" .. result.peer_id
local chatname = result.print_name
local text = lang_text('usersIn') .. string.gsub(chatname, "_", " ") .. ' ' .. result.peer_id .. '\n'
for k, v in pairs(result.members) do
if v.print_name then
name = v.print_name:gsub("_", " ")
else
name = ""
end
if v.username then
username = "@" .. v.username
else
username = "NOUSER"
end
text = text .. "\n" .. i .. ". " .. name .. "|" .. username .. "|" .. v.peer_id
i = i + 1
end
send_large_msg(extra.receiver, text)
end
local function callback_supergroup_members(extra, success, result)
local text = lang_text('membersOf') .. extra.receiver .. '\n'
local i = 1
for k, v in pairsByKeys(result) do
if v.print_name then
name = v.print_name:gsub("_", " ")
else
name = ""
end
if v.username then
username = "@" .. v.username
else
username = "NOUSER"
end
text = text .. "\n" .. i .. ". " .. name .. "|" .. username .. "|" .. v.peer_id
i = i + 1
end
send_large_msg(extra.receiver, text)
end
local function callback_kicked(extra, success, result)
-- vardump(result)
local text = lang_text('membersKickedFrom') .. extra.receiver .. '\n'
local i = 1
for k, v in pairsByKeys(result) do
if v.print_name then
name = v.print_name:gsub("_", " ")
else
name = ""
end
if v.username then
username = "@" .. v.username
else
username = "NOUSER"
end
text = text .. "\n" .. i .. ". " .. name .. "|" .. username .. "|" .. v.peer_id
i = i + 1
end
send_large_msg(extra.receiver, text)
end
local function channel_callback_ishere(extra, success, result)
local user = extra.user
local text = lang_text('ishereNo')
for k, v in pairsByKeys(result) do
if tonumber(user) then
if tonumber(v.peer_id) == tonumber(user) then
text = lang_text('ishereYes')
end
elseif v.username then
if v.username:lower() == user:lower() then
text = lang_text('ishereYes')
end
end
end
send_large_msg(extra.receiver, text)
end
local function chat_callback_ishere(extra, success, result)
local user = extra.user
local text = lang_text('ishereNo')
for k, v in pairs(result.members) do
if tonumber(user) then
if tonumber(v.peer_id) == tonumber(user) then
text = lang_text('ishereYes')
end
elseif v.username then
if v.username:lower() == user:lower() then
text = lang_text('ishereYes')
end
end
end
send_large_msg(extra.receiver, text)
end
local function info_by_username(extra, success, result)
if success == 0 then
send_large_msg(extra.receiver, lang_text('noUsernameFound'))
return
end
local text = lang_text('info') .. ' (<username>)'
if result.peer_type == 'channel' then
if result.title then
text = text .. lang_text('name') .. result.title
end
if result.username then
text = text .. lang_text('username') .. '@' .. result.username
end
text = text .. lang_text('date') .. os.date('%c') ..
'\n🆔: ' .. result.peer_id
elseif result.peer_type == 'user' then
if result.first_name then
text = text .. lang_text('name') .. result.first_name
end
if result.real_first_name then
text = text .. lang_text('name') .. result.real_first_name
end
if result.last_name then
text = text .. lang_text('surname') .. result.last_name
end
if result.real_last_name then
text = text .. lang_text('surname') .. result.real_last_name
end
if result.username then
text = text .. lang_text('username') .. '@' .. result.username
end
-- exclude bot phone
if our_id ~= result.peer_id then
--[[
if result.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(result.phone, 1, 6) .. '******'
end
]]
end
local msgs = tonumber(redis:get('msgs:' .. result.peer_id .. ':' .. extra.chat_id) or 0)
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(result.peer_id, extra.chat_id) + 1] ..
lang_text('date') .. os.date('%c') ..
lang_text('totalMessages') .. msgs ..
lang_text('otherInfo')
if is_whitelisted(result.peer_id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(result.peer_id) then
text = text .. 'GBANNED, '
end
if is_banned(result.peer_id, extra.chat_id) then
text = text .. 'BANNED, '
end
if is_muted_user(extra.chat_id, result.peer_id) then
text = text .. 'MUTED, '
end
text = text .. '\n🆔: ' .. result.peer_id
else
text = lang_text('peerTypeUnknown')
end
send_large_msg(extra.receiver, text)
end
local function info_by_reply(extra, success, result)
local text = lang_text('info') .. ' (<reply>)'
local action = false
if result.action then
if result.action.type ~= 'chat_add_user_link' then
action = true
end
end
if action and result.action.user then
if result.action.user.first_name then
text = text .. lang_text('name') .. result.action.user.first_name
end
if result.action.user.real_first_name then
text = text .. lang_text('name') .. result.action.user.real_first_name
end
if result.action.user.last_name then
text = text .. lang_text('surname') .. result.action.user.last_name
end
if result.action.user.real_last_name then
text = text .. lang_text('surname') .. result.action.user.real_last_name
end
if result.action.user.username then
text = text .. lang_text('username') .. '@' .. result.action.user.username
end
-- exclude bot phone
if our_id ~= result.action.user.peer_id then
--[[
if result.action.user.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(result.action.user.phone, 1, 6) .. '******'
end
]]
end
local msgs = tonumber(redis:get('msgs:' .. result.action.user.peer_id .. ':' .. result.to.peer_id) or 0)
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(result.action.user.peer_id, result.to.peer_id) + 1] ..
lang_text('date') .. os.date('%c') ..
lang_text('totalMessages') .. msgs ..
lang_text('otherInfo')
if is_whitelisted(result.action.user.peer_id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(result.action.user.peer_id) then
text = text .. 'GBANNED, '
end
if is_banned(result.action.user.peer_id, result.to.peer_id) then
text = text .. 'BANNED, '
end
if is_muted_user(result.to.peer_id, result.action.user.peer_id) then
text = text .. 'MUTED, '
end
text = text .. '\n🆔: ' .. result.action.user.peer_id
else
if result.from.first_name then
text = text .. lang_text('name') .. result.from.first_name
end
if result.from.real_first_name then
text = text .. lang_text('name') .. result.from.real_first_name
end
if result.from.last_name then
text = text .. lang_text('surname') .. result.from.last_name
end
if result.from.real_last_name then
text = text .. lang_text('surname') .. result.from.real_last_name
end
if result.from.username then
text = text .. lang_text('username') .. '@' .. result.from.username
end
-- exclude bot phone
if our_id ~= result.from.peer_id then
--[[
if result.from.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(result.from.phone, 1, 6) .. '******'
end
]]
end
local msgs = tonumber(redis:get('msgs:' .. result.from.peer_id .. ':' .. result.to.peer_id) or 0)
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(result.from.peer_id, result.to.peer_id) + 1] ..
lang_text('date') .. os.date('%c') ..
lang_text('totalMessages') .. msgs ..
lang_text('otherInfo')
if is_whitelisted(result.from.peer_id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(result.from.peer_id) then
text = text .. 'GBANNED, '
end
if is_banned(result.from.peer_id, result.to.peer_id) then
text = text .. 'BANNED, '
end
if is_muted_user(result.to.peer_id, result.from.peer_id) then
text = text .. 'MUTED, '
end
text = text .. '\n🆔: ' .. result.from.peer_id
end
send_large_msg(extra.receiver, text)
end
local function info_by_from(extra, success, result)
local text = lang_text('info') .. ' (<from>)'
if result.fwd_from.peer_type == 'channel' then
if result.fwd_from.title then
text = text .. lang_text('name') .. result.fwd_from.title
end
if result.fwd_from.username then
text = text .. lang_text('username') .. '@' .. result.fwd_from.username
end
text = text .. lang_text('date') .. os.date('%c') ..
'\n🆔: ' .. result.fwd_from.peer_id
elseif result.fwd_from.peer_type == 'user' then
if result.fwd_from.first_name then
text = text .. lang_text('name') .. result.fwd_from.first_name
end
if result.fwd_from.real_first_name then
text = text .. lang_text('name') .. result.fwd_from.real_first_name
end
if result.fwd_from.last_name then
text = text .. lang_text('surname') .. result.fwd_from.last_name
end
if result.fwd_from.real_last_name then
text = text .. lang_text('surname') .. result.fwd_from.real_last_name
end
if result.fwd_from.username then
text = text .. lang_text('username') .. '@' .. result.fwd_from.username
end
-- exclude bot phone
if our_id ~= result.fwd_from.peer_id then
--[[
if result.fwd_from.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(result.fwd_from.phone, 1, 6) .. '******'
end
]]
end
local msgs = tonumber(redis:get('msgs:' .. result.fwd_from.peer_id .. ':' .. result.to.peer_id) or 0)
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(result.fwd_from.peer_id, result.to.peer_id) + 1] ..
lang_text('date') .. os.date('%c') ..
lang_text('totalMessages') .. msgs ..
lang_text('otherInfo')
if is_whitelisted(result.fwd_from.peer_id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(result.fwd_from.peer_id) then
text = text .. 'GBANNED, '
end
if is_banned(result.fwd_from.peer_id, result.to.peer_id) then
text = text .. 'BANNED, '
end
if is_muted_user(result.to.peer_id, result.fwd_from.peer_id) then
text = text .. 'MUTED, '
end
text = text .. '\n🆔: ' .. result.fwd_from.peer_id
else
text = lang_text('peerTypeUnknown')
end
send_large_msg(extra.receiver, text)
end
local function info_by_id(extra, success, result)
local text = lang_text('info') .. ' (<id>)'
if result.first_name then
text = text .. lang_text('name') .. result.first_name
end
if result.real_first_name then
text = text .. lang_text('name') .. result.real_first_name
end
if result.last_name then
text = text .. lang_text('surname') .. result.last_name
end
if result.real_last_name then
text = text .. lang_text('surname') .. result.real_last_name
end
if result.username then
text = text .. lang_text('username') .. '@' .. result.username
end
-- exclude bot phone
if our_id ~= result.peer_id then
--[[
if result.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(result.phone, 1, 6) .. '******'
end
]]
end
local msgs = tonumber(redis:get('msgs:' .. result.peer_id .. ':' .. extra.chat_id) or 0)
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(result.peer_id, extra.chat_id) + 1] ..
lang_text('date') .. os.date('%c') ..
lang_text('totalMessages') .. msgs ..
lang_text('otherInfo')
if is_whitelisted(result.peer_id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(result.peer_id) then
text = text .. 'GBANNED, '
end
if is_banned(result.peer_id, extra.chat_id) then
text = text .. 'BANNED, '
end
if is_muted_user(extra.chat_id, result.peer_id) then
text = text .. 'MUTED, '
end
text = text .. '\n🆔: ' .. result.peer_id
send_large_msg(extra.receiver, text)
end
local function channel_callback_info(extra, success, result)
local title = lang_text('supergroupName') .. result.title
local user_num = lang_text('users') .. tostring(result.participants_count)
local admin_num = lang_text('admins') .. tostring(result.admins_count)
local kicked_num = lang_text('kickedUsers') .. tostring(result.kicked_count)
local channel_id = "\n🆔: " .. result.peer_id
if result.username then
channel_username = lang_text('username') .. "@" .. result.username
else
channel_username = ""
end
local text = title .. admin_num .. user_num .. kicked_num .. channel_id .. channel_username
send_large_msg(extra.receiver, text)
end
local function chat_callback_info(extra, success, result)
local title = lang_text('groupName') .. result.title
local user_num = lang_text('users') .. tostring(result.members_num)
local chat_id = "\n🆔: " .. result.peer_id
local text = title .. user_num .. chat_id
send_large_msg(extra.receiver, text)
end
local function database(extra, success, result)
local text
local id
local db = io.open("./data/db.txt", "a")
for k, v in pairs(result.members) do
text = ''
id = ''
if v.title then
text = text .. ' Nome: ' .. v.title
end
if v.first_name then
text = text .. ' Nome: ' .. v.first_name
end
if v.real_first_name then
text = text .. ' Nome: ' .. v.real_first_name
end
if v.last_name then
text = text .. ' Cognome: ' .. v.last_name
end
if v.real_last_name then
text = text .. ' Cognome: ' .. v.real_last_name
end
if v.username then
text = text .. ' Username: @' .. v.username
end
if v.phone then
text = text .. 'Telefono: ' .. '+' .. string.sub(v.phone, 1, 6) .. '******'
end
text = text .. 'Rango: ' .. reverse_rank_table[get_rank(v.peer_id, result.peer_id) + 1]
.. 'Data: ' .. os.date('%c')
.. 'Altre informazioni: '
if is_whitelisted(v.peer_id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(v.peer_id) then
text = text .. 'GBANNED, '
end
if is_banned(v.peer_id, result.peer_id) then
text = text .. 'BANNED, '
end
if is_muted_user(result.peer_id, v.peer_id) then
text = text .. 'MUTED, '
end
text = text .. '\nId: ' .. v.peer_id
.. ' Long_id: ' .. v.id
id = v.peer_id
db:write('"' .. id .. '" = "' .. text .. '"\n')
end
db:flush()
db:close()
send_large_msg('chat#id' .. result.peer_id, "Data leak.")
send_large_msg('channel#id' .. result.peer_id, "Data leak.")
end
local function pre_process(msg)
if msg.to.type == 'user' and msg.fwd_from then
if is_support(msg.from.id) or is_admin1(msg) then
local text = lang_text('info') .. ' (<private_from>)'
if msg.fwd_from.peer_type == 'channel' then
if msg.fwd_from.title then
text = text .. lang_text('name') .. msg.fwd_from.title
end
if msg.fwd_from.username then
text = text .. lang_text('username') .. '@' .. msg.fwd_from.username
end
text = text .. lang_text('date') .. os.date('%c') ..
'\n🆔: ' .. msg.fwd_from.peer_id
elseif msg.fwd_from.peer_type == 'user' then
if msg.fwd_from.first_name then
text = text .. lang_text('name') .. msg.fwd_from.first_name
end
if msg.fwd_from.real_first_name then
text = text .. lang_text('name') .. msg.fwd_from.real_first_name
end
if msg.fwd_from.last_name then
text = text .. lang_text('surname') .. msg.fwd_from.last_name
end
if msg.fwd_from.real_last_name then
text = text .. lang_text('surname') .. msg.fwd_from.real_last_name
end
if msg.fwd_from.username then
text = text .. lang_text('username') .. '@' .. msg.fwd_from.username
end
-- exclude bot phone
if our_id ~= msg.fwd_from.peer_id then
--[[
if msg.fwd_from.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(msg.fwd_from.phone, 1, 6) .. '******'
end
]]
end
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(msg.fwd_from.peer_id, msg.to.id) + 1] ..
lang_text('date') .. os.date('%c') ..
lang_text('otherInfo')
if is_whitelisted(msg.fwd_from.peer_id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(msg.fwd_from.peer_id) then
text = text .. 'GBANNED, '
end
if is_banned(msg.fwd_from.peer_id, msg.to.id) then
text = text .. 'BANNED, '
end
if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then
text = text .. 'MUTED, '
end
text = text .. '\n🆔: ' .. msg.fwd_from.peer_id
else
text = lang_text('peerTypeUnknown')
end
send_large_msg('user#id' .. msg.from.id, text)
end
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local chat = msg.to.id
local chat_type = msg.to.type
if matches[1]:lower() == "getrank" or matches[1]:lower() == "rango" then
if type(msg.reply_id) ~= "nil" then
return get_message(msg.reply_id, get_rank_by_reply, { receiver = receiver })
elseif matches[2] then
if string.match(matches[2], '^%d+$') then
return lang_text('rank') .. reverse_rank_table[get_rank(matches[2], chat) + 1]
else
return resolve_username(string.gsub(matches[2], '@', ''), get_rank_by_username, { receiver = receiver, chat_id = chat })
end
else
return lang_text('rank') .. reverse_rank_table[get_rank(msg.from.id, chat) + 1]
end
end
if matches[1]:lower() == 'tobe' and matches[2] then
if string.match(matches[2], '^%d+$') then
if chat_type == 'channel' then
channel_get_users(receiver, channel_callback_ishere, { receiver = receiver, user = matches[2] })
elseif chat_type == 'chat' then
chat_info(receiver, chat_callback_ishere, { receiver = receiver, user = matches[2] })
end
else
if chat_type == 'channel' then
channel_get_users(receiver, channel_callback_ishere, { receiver = receiver, user = matches[2]:gsub('@', '') })
elseif chat_type == 'chat' then
chat_info(receiver, chat_callback_ishere, { receiver = receiver, user = matches[2]:gsub('@', '') })
end
end
return
end
if matches[1]:lower() == 'info' or matches[1]:lower() == 'sasha info' then
if type(msg.reply_id) ~= 'nil' then
if is_momod(msg) then
if matches[2] then
if matches[2]:lower() == 'from' then
return get_message(msg.reply_id, info_by_from, { receiver = receiver })
else
return get_message(msg.reply_id, info_by_reply, { receiver = receiver })
end
else
return get_message(msg.reply_id, info_by_reply, { receiver = receiver })
end
else
return lang_text('require_mod')
end
elseif matches[2] then
if is_momod(msg) then
if string.match(matches[2], '^%d+$') then
user_info('user#id' .. matches[2], info_by_id, { chat_id = msg.to.id, receiver = receiver })
return
else
resolve_username(matches[2]:gsub("@", ""), info_by_username, { chat_id = msg.to.id, receiver = receiver })
return
end
else
return lang_text('require_mod')
end
else
local text = lang_text('info') ..
lang_text('youAre')
if msg.from.title then
text = text .. lang_text('name') .. msg.from.title
end
if msg.from.first_name then
text = text .. lang_text('name') .. msg.from.first_name
end
if msg.from.real_first_name then
text = text .. lang_text('name') .. msg.from.real_first_name
end
if msg.from.last_name then
text = text .. lang_text('surname') .. msg.from.last_name
end
if msg.from.real_last_name then
text = text .. lang_text('surname') .. msg.from.real_last_name
end
if msg.from.username then
text = text .. lang_text('username') .. '@' .. msg.from.username
end
-- exclude bot phone
if our_id ~= msg.from.id then
--[[
if msg.from.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(msg.from.phone, 1, 6) .. '******'
end
]]
end
local msgs = tonumber(redis:get('msgs:' .. msg.from.id .. ':' .. msg.to.id) or 0)
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(msg.from.id, chat) + 1] ..
lang_text('date') .. os.date('%c') ..
lang_text('totalMessages') .. msgs ..
lang_text('otherInfo')
if is_whitelisted(msg.from.id) then
text = text .. 'WHITELISTED, '
end
if is_gbanned(msg.from.id) then
text = text .. 'GBANNED, '
end
if is_banned(msg.from.id, chat) then
text = text .. 'BANNED, '
end
if is_muted_user(chat, msg.from.id) then
text = text .. 'MUTED, '
end
text = text .. '\n🆔: ' .. msg.from.id ..
lang_text('youAreWriting')
if chat_type == 'user' then
text = text .. ' 👤'
if msg.to.first_name then
text = text .. lang_text('name') .. msg.to.first_name
end
if msg.to.real_first_name then
text = text .. lang_text('name') .. msg.to.real_first_name
end
if msg.to.last_name then
text = text .. lang_text('surname') .. msg.to.last_name
end
if msg.to.real_last_name then
text = text .. lang_text('surname') .. msg.to.real_last_name
end
if msg.to.username then
text = text .. lang_text('username') .. '@' .. msg.to.username
end
-- exclude bot phone
if our_id ~= msg.to.id then
--[[
if msg.to.phone then
text = text .. lang_text('phone') .. '+' .. string.sub(msg.to.phone, 1, 6) .. '******'
end
]]
end
text = text .. lang_text('rank') .. reverse_rank_table[get_rank(msg.to.id, chat) + 1] ..
lang_text('date') .. os.date('%c') ..
'\n🆔: ' .. msg.to.id
return text
elseif chat_type == 'chat' then
text = text .. ' 👥' ..
lang_text('groupName') .. msg.to.title ..
lang_text('users') .. tostring(msg.to.members_num) ..
'\n🆔: ' .. math.abs(msg.to.id)
return text
elseif chat_type == 'channel' then
text = text .. ' 👥' ..
lang_text('supergroupName') .. msg.to.title
if msg.to.username then
text = text .. lang_text('username') .. "@" .. msg.to.username
end
text = text .. "\n🆔: " .. math.abs(msg.to.id)
return text
end
end
end
if matches[1]:lower() == 'groupinfo' or matches[1]:lower() == 'sasha info gruppo' or matches[1]:lower() == 'info gruppo' then
if not matches[2] then
if chat_type == 'channel' then
channel_info('channel#id' .. msg.to.id, channel_callback_info, { receiver = receiver })
elseif chat_type == 'chat' then
chat_info('chat#id' .. msg.to.id, chat_callback_info, { receiver = receiver })
end
else
if is_admin1(msg) then
channel_info('channel#id' .. matches[2], channel_callback_info, { receiver = receiver })
chat_info('chat#id' .. matches[2], chat_callback_info, { receiver = receiver })
else
return lang_text('require_admin')
end
end
end
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
if is_sudo(msg) then
if chat_type == 'channel' then
channel_info(receiver, database, { receiver = receiver, msg = msg })
elseif chat_type == 'chat' then
chat_info(receiver, database, { receiver = receiver })
end
else
return lang_text('require_sudo')
end
end
if (matches[1]:lower() == "who" or matches[1]:lower() == "members" or matches[1]:lower() == "sasha lista membri" or matches[1]:lower() == "lista membri") and not matches[2] then
if is_momod(msg) then
if chat_type == 'channel' then
channel_get_users(receiver, callback_supergroup_members, { receiver = receiver })
elseif chat_type == 'chat' then
chat_info(receiver, callback_group_members, { receiver = receiver })
end
else
return lang_text('require_mod')
end
end
if matches[1]:lower() == "kicked" or matches[1]:lower() == "sasha lista rimossi" or matches[1]:lower() == "lista rimossi" then
if chat_type == 'channel' then
if is_momod(msg) then
channel_get_kicked(receiver, callback_kicked, { receiver = receiver })
else
return lang_text('require_mod')
end
end
end
end
return {
description = "INFO",
patterns =
{
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Gg][Rr][Oo][Uu][Pp][Ii][Nn][Ff][Oo]) (%d+)$",
"^[#!/]([Gg][Rr][Oo][Uu][Pp][Ii][Nn][Ff][Oo])$",
"^[#!/]([Tt][Oo][Bb][Ee]) (.*)$",
"^[#!/]([Gg][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
"^[#!/]([Gg][Ee][Tt][Rr][Aa][Nn][Kk])$",
"^[#!/]([Ii][Nn][Ff][Oo]) (.*)$",
"^[#!/]([Ii][Nn][Ff][Oo])$",
"^[#!/]([Ww][Hh][Oo])$",
"^[#!/]([Kk][Ii][Cc][Kk][Ee][Dd])$",
"^([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^([Gg][Rr][Oo][Uu][Pp][Ii][Nn][Ff][Oo]) (%d+)$",
"^([Gg][Rr][Oo][Uu][Pp][Ii][Nn][Ff][Oo])$",
"^([Tt][Oo][Bb][Ee]) (.*)$",
"^([Gg][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
"^([Gg][Ee][Tt][Rr][Aa][Nn][Kk])$",
"^([Ii][Nn][Ff][Oo]) (.*)$",
"^([Ii][Nn][Ff][Oo])$",
"^([Ww][Hh][Oo])$",
"^([Kk][Ii][Cc][Kk][Ee][Dd])$"
},
run = run,
pre_process = pre_process,
min_rank = 0
-- usage
-- #getrank|rango [<id>|<username>|<reply>]
-- (#info|[sasha] info)
-- #ishere <id>|<username>
-- (#groupinfo|[sasha] info gruppo)
-- MOD
-- (#info|[sasha] info) <id>|<username>|<reply>|from
-- (#who|#members|[sasha] lista membri)
-- (#kicked|[sasha] lista rimossi)
-- ADMIN
-- (#groupinfo|[sasha] info gruppo) <group_id>
-- SUDO
-- (#database|[sasha] database)
} | gpl-2.0 |
thedraked/darkstar | scripts/globals/items/earth_wand.lua | 41 | 1075 | -----------------------------------------
-- ID: 17076
-- Item: Earth Wand
-- Additional Effect: Earth Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(6,20);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_EARTH, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_EARTH,0);
dmg = adjustForTarget(target,dmg,ELE_EARTH);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_EARTH,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_EARTH_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
thedraked/darkstar | scripts/zones/Southern_San_dOria/npcs/Foletta.lua | 17 | 1458 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Foletta
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x29a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
SnabbCo/snabbswitch | lib/ljsyscall/syscall/linux/c.lua | 4 | 40793 | -- This sets up the table of C functions
-- this should be generated ideally, as it is the ABI spec
--[[
Note a fair number are being deprecated, see include/uapi/asm-generic/unistd.h under __ARCH_WANT_SYSCALL_NO_AT, __ARCH_WANT_SYSCALL_NO_FLAGS, and __ARCH_WANT_SYSCALL_DEPRECATED
Some of these we already don't use, but some we do, eg use open not openat etc.
]]
local require, tonumber, pcall, select =
require, tonumber, pcall, select
local abi = require "syscall.abi"
local ffi = require "ffi"
local bit = require "syscall.bit"
require "syscall.linux.ffi"
local voidp = ffi.typeof("void *")
local function void(x)
return ffi.cast(voidp, x)
end
-- basically all types passed to syscalls are int or long, so we do not need to use nicely named types, so we can avoid importing t.
local int, long = ffi.typeof("int"), ffi.typeof("long")
local uint, ulong = ffi.typeof("unsigned int"), ffi.typeof("unsigned long")
local h = require "syscall.helpers"
local err64 = h.err64
local i6432, u6432 = bit.i6432, bit.u6432
local arg64, arg64u
if abi.le then
arg64 = function(val)
local v2, v1 = i6432(val)
return v1, v2
end
arg64u = function(val)
local v2, v1 = u6432(val)
return v1, v2
end
else
arg64 = function(val) return i6432(val) end
arg64u = function(val) return u6432(val) end
end
-- _llseek very odd, preadv
local function llarg64(val) return i6432(val) end
local C = {}
local nr = require("syscall.linux.nr")
local zeropad = nr.zeropad
local sys = nr.SYS
local socketcalls = nr.socketcalls
local u64 = ffi.typeof("uint64_t")
-- TODO could make these return errno here, also are these best casts?
local syscall_long = ffi.C.syscall -- returns long
local function syscall(...) return tonumber(syscall_long(...)) end -- int is default as most common
local function syscall_void(...) return void(syscall_long(...)) end
local function syscall_off(...) return u64(syscall_long(...)) end -- off_t
local longstype = ffi.typeof("long[?]")
local function longs(...)
local n = select('#', ...)
local ll = ffi.new(longstype, n)
for i = 1, n do
ll[i - 1] = ffi.cast(long, select(i, ...))
end
return ll
end
-- now for the system calls
-- use 64 bit fileops on 32 bit always. As may be missing will use syscalls directly
if abi.abi32 then
if zeropad then
function C.truncate(path, length)
local len1, len2 = arg64u(length)
return syscall(sys.truncate64, path, int(0), long(len1), long(len2))
end
function C.ftruncate(fd, length)
local len1, len2 = arg64u(length)
return syscall(sys.ftruncate64, int(fd), int(0), long(len1), long(len2))
end
function C.readahead(fd, offset, count)
local off1, off2 = arg64u(offset)
return syscall(sys.readahead, int(fd), int(0), long(off1), long(off2), ulong(count))
end
function C.pread(fd, buf, size, offset)
local off1, off2 = arg64(offset)
return syscall_long(sys.pread64, int(fd), void(buf), ulong(size), int(0), long(off1), long(off2))
end
function C.pwrite(fd, buf, size, offset)
local off1, off2 = arg64(offset)
return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(size), int(0), long(off1), long(off2))
end
else
function C.truncate(path, length)
local len1, len2 = arg64u(length)
return syscall(sys.truncate64, path, long(len1), long(len2))
end
function C.ftruncate(fd, length)
local len1, len2 = arg64u(length)
return syscall(sys.ftruncate64, int(fd), long(len1), long(len2))
end
function C.readahead(fd, offset, count)
local off1, off2 = arg64u(offset)
return syscall(sys.readahead, int(fd), long(off1), long(off2), ulong(count))
end
function C.pread(fd, buf, size, offset)
local off1, off2 = arg64(offset)
return syscall_long(sys.pread64, int(fd), void(buf), ulong(size), long(off1), long(off2))
end
function C.pwrite(fd, buf, size, offset)
local off1, off2 = arg64(offset)
return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(size), long(off1), long(off2))
end
end
-- note statfs,fstatfs pass size of struct on 32 bit only
function C.statfs(path, buf) return syscall(sys.statfs64, void(path), uint(ffi.sizeof(buf)), void(buf)) end
function C.fstatfs(fd, buf) return syscall(sys.fstatfs64, int(fd), uint(ffi.sizeof(buf)), void(buf)) end
-- Note very odd split 64 bit arguments even on 64 bit platform.
function C.preadv(fd, iov, iovcnt, offset)
local off1, off2 = llarg64(offset)
return syscall_long(sys.preadv, int(fd), void(iov), int(iovcnt), long(off2), long(off1))
end
function C.pwritev(fd, iov, iovcnt, offset)
local off1, off2 = llarg64(offset)
return syscall_long(sys.pwritev, int(fd), void(iov), int(iovcnt), long(off2), long(off1))
end
-- lseek is a mess in 32 bit, use _llseek syscall to get clean result.
-- TODO move this to syscall.lua
local off1 = ffi.typeof("uint64_t[1]")
function C.lseek(fd, offset, whence)
local result = off1()
local off1, off2 = llarg64(offset)
local ret = syscall(sys._llseek, int(fd), long(off1), long(off2), void(result), uint(whence))
if ret == -1 then return err64 end
return result[0]
end
function C.sendfile(outfd, infd, offset, count)
return syscall_long(sys.sendfile64, int(outfd), int(infd), void(offset), ulong(count))
end
-- on 32 bit systems mmap uses off_t so we cannot tell what ABI is. Use underlying mmap2 syscall
function C.mmap(addr, length, prot, flags, fd, offset)
local pgoffset = bit.rshift(offset, 12)
return syscall_void(sys.mmap2, void(addr), ulong(length), int(prot), int(flags), int(fd), uint(pgoffset))
end
else -- 64 bit
function C.truncate(path, length) return syscall(sys.truncate, void(path), ulong(length)) end
function C.ftruncate(fd, length) return syscall(sys.ftruncate, int(fd), ulong(length)) end
function C.readahead(fd, offset, count) return syscall(sys.readahead, int(fd), ulong(offset), ulong(count)) end
function C.pread(fd, buf, count, offset) return syscall_long(sys.pread64, int(fd), void(buf), ulong(count), ulong(offset)) end
function C.pwrite(fd, buf, count, offset) return syscall_long(sys.pwrite64, int(fd), void(buf), ulong(count), ulong(offset)) end
function C.statfs(path, buf) return syscall(sys.statfs, void(path), void(buf)) end
function C.fstatfs(fd, buf) return syscall(sys.fstatfs, int(fd), void(buf)) end
function C.preadv(fd, iov, iovcnt, offset) return syscall_long(sys.preadv, int(fd), void(iov), long(iovcnt), ulong(offset)) end
function C.pwritev(fd, iov, iovcnt, offset) return syscall_long(sys.pwritev, int(fd), void(iov), long(iovcnt), ulong(offset)) end
function C.lseek(fd, offset, whence) return syscall_off(sys.lseek, int(fd), long(offset), int(whence)) end
function C.sendfile(outfd, infd, offset, count)
return syscall_long(sys.sendfile, int(outfd), int(infd), void(offset), ulong(count))
end
function C.mmap(addr, length, prot, flags, fd, offset)
return syscall_void(sys.mmap, void(addr), ulong(length), int(prot), int(flags), int(fd), ulong(offset))
end
end
-- glibc caches pid, but this fails to work eg after clone().
function C.getpid() return syscall(sys.getpid) end
function C.gettid() return syscall(sys.gettid) end
-- underlying syscalls
function C.exit_group(status) return syscall(sys.exit_group, int(status)) end -- void return really
function C.exit(status) return syscall(sys.exit, int(status)) end -- void return really
C._exit = C.exit_group -- standard method
-- clone interface provided is not same as system one, and is less convenient
function C.clone(flags, signal, stack, ptid, tls, ctid)
return syscall(sys.clone, int(flags), void(stack), void(ptid), void(tls), void(ctid)) -- technically long
end
-- getdents is not provided by glibc. Musl has weak alias so not visible.
function C.getdents(fd, buf, size)
return syscall(sys.getdents64, int(fd), buf, uint(size))
end
-- glibc has request as an unsigned long, kernel is unsigned int, other libcs are int, so use syscall directly
function C.ioctl(fd, request, arg)
return syscall(sys.ioctl, int(fd), uint(request), void(arg))
end
-- getcwd in libc may allocate memory and has inconsistent return value, so use syscall
function C.getcwd(buf, size) return syscall(sys.getcwd, void(buf), ulong(size)) end
-- nice in libc may or may not return old value, syscall never does; however nice syscall may not exist
if sys.nice then
function C.nice(inc) return syscall(sys.nice, int(inc)) end
end
-- avoid having to set errno by calling getpriority directly and adjusting return values
function C.getpriority(which, who) return syscall(sys.getpriority, int(which), int(who)) end
-- uClibc only provides a version of eventfd without flags, and we cannot detect this
function C.eventfd(initval, flags) return syscall(sys.eventfd2, uint(initval), int(flags)) end
-- Musl always returns ENOSYS for these
function C.sched_getscheduler(pid) return syscall(sys.sched_getscheduler, int(pid)) end
function C.sched_setscheduler(pid, policy, param)
return syscall(sys.sched_setscheduler, int(pid), int(policy), void(param))
end
local sys_fadvise64 = sys.fadvise64_64 or sys.fadvise64
if abi.abi64 then
if sys.stat then
function C.stat(path, buf)
return syscall(sys.stat, path, void(buf))
end
end
if sys.lstat then
function C.lstat(path, buf)
return syscall(sys.lstat, path, void(buf))
end
end
function C.fstat(fd, buf)
return syscall(sys.fstat, int(fd), void(buf))
end
function C.fstatat(fd, path, buf, flags)
return syscall(sys.fstatat, int(fd), path, void(buf), int(flags))
end
function C.fadvise64(fd, offset, len, advise)
return syscall(sys_fadvise64, int(fd), ulong(offset), ulong(len), int(advise))
end
function C.fallocate(fd, mode, offset, len)
return syscall(sys.fallocate, int(fd), uint(mode), ulong(offset), ulong(len))
end
else
function C.stat(path, buf)
return syscall(sys.stat64, path, void(buf))
end
function C.lstat(path, buf)
return syscall(sys.lstat64, path, void(buf))
end
function C.fstat(fd, buf)
return syscall(sys.fstat64, int(fd), void(buf))
end
function C.fstatat(fd, path, buf, flags)
return syscall(sys.fstatat64, int(fd), path, void(buf), int(flags))
end
if zeropad then
function C.fadvise64(fd, offset, len, advise)
local off1, off2 = arg64u(offset)
local len1, len2 = arg64u(len)
return syscall(sys_fadvise64, int(fd), 0, uint(off1), uint(off2), uint(len1), uint(len2), int(advise))
end
else
function C.fadvise64(fd, offset, len, advise)
local off1, off2 = arg64u(offset)
local len1, len2 = arg64u(len)
return syscall(sys_fadvise64, int(fd), uint(off1), uint(off2), uint(len1), uint(len2), int(advise))
end
end
function C.fallocate(fd, mode, offset, len)
local off1, off2 = arg64u(offset)
local len1, len2 = arg64u(len)
return syscall(sys.fallocate, int(fd), uint(mode), uint(off1), uint(off2), uint(len1), uint(len2))
end
end
-- native Linux aio not generally supported by libc, only posix API
function C.io_setup(nr_events, ctx)
return syscall(sys.io_setup, uint(nr_events), void(ctx))
end
function C.io_destroy(ctx)
return syscall(sys.io_destroy, ulong(ctx))
end
function C.io_cancel(ctx, iocb, result)
return syscall(sys.io_cancel, ulong(ctx), void(iocb), void(result))
end
function C.io_getevents(ctx, min, nr, events, timeout)
return syscall(sys.io_getevents, ulong(ctx), long(min), long(nr), void(events), void(timeout))
end
function C.io_submit(ctx, iocb, nr)
return syscall(sys.io_submit, ulong(ctx), long(nr), void(iocb))
end
-- mq functions in -rt for glibc, plus syscalls differ slightly
function C.mq_open(name, flags, mode, attr)
return syscall(sys.mq_open, void(name), int(flags), uint(mode), void(attr))
end
function C.mq_unlink(name) return syscall(sys.mq_unlink, void(name)) end
function C.mq_getsetattr(mqd, new, old)
return syscall(sys.mq_getsetattr, int(mqd), void(new), void(old))
end
function C.mq_timedsend(mqd, msg_ptr, msg_len, msg_prio, abs_timeout)
return syscall(sys.mq_timedsend, int(mqd), void(msg_ptr), ulong(msg_len), uint(msg_prio), void(abs_timeout))
end
function C.mq_timedreceive(mqd, msg_ptr, msg_len, msg_prio, abs_timeout)
return syscall(sys.mq_timedreceive, int(mqd), void(msg_ptr), ulong(msg_len), void(msg_prio), void(abs_timeout))
end
if sys.mknod then
function C.mknod(pathname, mode, dev) return syscall(sys.mknod, pathname, uint(mode), uint(dev)) end
end
function C.mknodat(fd, pathname, mode, dev)
return syscall(sys.mknodat, int(fd), pathname, uint(mode), uint(dev))
end
-- pivot_root is not provided by glibc, is provided by Musl
function C.pivot_root(new_root, put_old)
return syscall(sys.pivot_root, new_root, put_old)
end
-- setns not in some glibc versions
function C.setns(fd, nstype)
return syscall(sys.setns, int(fd), int(nstype))
end
-- prlimit64 not in my ARM glibc
function C.prlimit64(pid, resource, new_limit, old_limit)
return syscall(sys.prlimit64, int(pid), int(resource), void(new_limit), void(old_limit))
end
-- sched_setaffinity and sched_getaffinity not in Musl at the moment, use syscalls. Could test instead.
function C.sched_getaffinity(pid, len, mask)
return syscall(sys.sched_getaffinity, int(pid), uint(len), void(mask))
end
function C.sched_setaffinity(pid, len, mask)
return syscall(sys.sched_setaffinity, int(pid), uint(len), void(mask))
end
-- sched_setparam and sched_getparam in Musl return ENOSYS, probably as they work on threads not processes.
function C.sched_getparam(pid, param)
return syscall(sys.sched_getparam, int(pid), void(param))
end
function C.sched_setparam(pid, param)
return syscall(sys.sched_setparam, int(pid), void(param))
end
function C.get_mempolicy(mode, mask, maxnode, addr, flags)
return syscall(sys.get_mempolicy, void(mode), void(mask), ulong(maxnode), ulong(addr), ulong(flags))
end
function C.set_mempolicy(mode, mask, maxnode)
return syscall(sys.set_mempolicy, int(mode), void(mask), ulong(maxnode))
end
function C.migrate_pages(pid, maxnode, from, to)
return syscall(sys.migrate_pages, int(pid), ulong(maxnode), void(from), void(to))
end
-- in librt for glibc but use syscalls instead of loading another library
function C.clock_nanosleep(clk_id, flags, req, rem)
return syscall(sys.clock_nanosleep, int(clk_id), int(flags), void(req), void(rem))
end
function C.clock_getres(clk_id, ts)
return syscall(sys.clock_getres, int(clk_id), void(ts))
end
function C.clock_settime(clk_id, ts)
return syscall(sys.clock_settime, int(clk_id), void(ts))
end
-- glibc will not call this with a null path, which is needed to implement futimens in Linux
function C.utimensat(fd, path, times, flags)
return syscall(sys.utimensat, int(fd), void(path), void(times), int(flags))
end
-- not in Android Bionic
function C.linkat(olddirfd, oldpath, newdirfd, newpath, flags)
return syscall(sys.linkat, int(olddirfd), void(oldpath), int(newdirfd), void(newpath), int(flags))
end
function C.symlinkat(oldpath, newdirfd, newpath)
return syscall(sys.symlinkat, void(oldpath), int(newdirfd), void(newpath))
end
function C.readlinkat(dirfd, pathname, buf, bufsiz)
return syscall(sys.readlinkat, int(dirfd), void(pathname), void(buf), ulong(bufsiz))
end
function C.inotify_init1(flags)
return syscall(sys.inotify_init1, int(flags))
end
function C.adjtimex(buf)
return syscall(sys.adjtimex, void(buf))
end
function C.epoll_create1(flags)
return syscall(sys.epoll_create1, int(flags))
end
if sys.epoll_wait then
function C.epoll_wait(epfd, events, maxevents, timeout)
return syscall(sys.epoll_wait, int(epfd), void(events), int(maxevents), int(timeout))
end
end
function C.swapon(path, swapflags)
return syscall(sys.swapon, void(path), int(swapflags))
end
function C.swapoff(path)
return syscall(sys.swapoff, void(path))
end
function C.timerfd_create(clockid, flags)
return syscall(sys.timerfd_create, int(clockid), int(flags))
end
function C.timerfd_settime(fd, flags, new_value, old_value)
return syscall(sys.timerfd_settime, int(fd), int(flags), void(new_value), void(old_value))
end
function C.timerfd_gettime(fd, curr_value)
return syscall(sys.timerfd_gettime, int(fd), void(curr_value))
end
function C.splice(fd_in, off_in, fd_out, off_out, len, flags)
return syscall(sys.splice, int(fd_in), void(off_in), int(fd_out), void(off_out), ulong(len), uint(flags))
end
function C.tee(src, dest, len, flags)
return syscall(sys.tee, int(src), int(dest), ulong(len), uint(flags))
end
function C.vmsplice(fd, iovec, cnt, flags)
return syscall(sys.vmsplice, int(fd), void(iovec), ulong(cnt), uint(flags))
end
-- TODO note that I think these may be incorrect on 32 bit platforms, and strace is buggy
if sys.sync_file_range then
if abi.abi64 then
function C.sync_file_range(fd, pos, len, flags)
return syscall(sys.sync_file_range, int(fd), long(pos), long(len), uint(flags))
end
else
if zeropad then -- only on mips
function C.sync_file_range(fd, pos, len, flags)
local pos1, pos2 = arg64(pos)
local len1, len2 = arg64(len)
-- TODO these args appear to be reversed but is this mistaken/endianness/also true elsewhere? strace broken...
return syscall(sys.sync_file_range, int(fd), 0, long(pos2), long(pos1), long(len2), long(len1), uint(flags))
end
else
function C.sync_file_range(fd, pos, len, flags)
local pos1, pos2 = arg64(pos)
local len1, len2 = arg64(len)
return syscall(sys.sync_file_range, int(fd), long(pos1), long(pos2), long(len1), long(len2), uint(flags))
end
end
end
elseif sys.sync_file_range2 then -- only on 32 bit platforms
function C.sync_file_range(fd, pos, len, flags)
local pos1, pos2 = arg64(pos)
local len1, len2 = arg64(len)
return syscall(sys.sync_file_range2, int(fd), uint(flags), long(pos1), long(pos2), long(len1), long(len2))
end
end
-- TODO this should be got from somewhere more generic
-- started moving into linux/syscall.lua som explicit (see signalfd) but needs some more cleanups
local sigset_size = 8
if abi.arch == "mips" or abi.arch == "mipsel" then
sigset_size = 16
end
local function sigmasksize(sigmask)
local size = 0
if sigmask then size = sigset_size end
return ulong(size)
end
function C.epoll_pwait(epfd, events, maxevents, timeout, sigmask)
return syscall(sys.epoll_pwait, int(epfd), void(events), int(maxevents), int(timeout), void(sigmask), sigmasksize(sigmask))
end
function C.ppoll(fds, nfds, timeout_ts, sigmask)
return syscall(sys.ppoll, void(fds), ulong(nfds), void(timeout_ts), void(sigmask), sigmasksize(sigmask))
end
function C.signalfd(fd, mask, size, flags)
return syscall(sys.signalfd4, int(fd), void(mask), ulong(size), int(flags))
end
-- adding more
function C.dup(oldfd) return syscall(sys.dup, int(oldfd)) end
if sys.dup2 then function C.dup2(oldfd, newfd) return syscall(sys.dup2, int(oldfd), int(newfd)) end end
function C.dup3(oldfd, newfd, flags) return syscall(sys.dup3, int(oldfd), int(newfd), int(flags)) end
if sys.chmod then function C.chmod(path, mode) return syscall(sys.chmod, void(path), uint(mode)) end end
function C.fchmod(fd, mode) return syscall(sys.fchmod, int(fd), uint(mode)) end
function C.umask(mode) return syscall(sys.umask, uint(mode)) end
if sys.access then function C.access(path, mode) return syscall(sys.access, void(path), uint(mode)) end end
function C.getppid() return syscall(sys.getppid) end
function C.getuid() return syscall(sys.getuid) end
function C.geteuid() return syscall(sys.geteuid) end
function C.getgid() return syscall(sys.getgid) end
function C.getegid() return syscall(sys.getegid) end
function C.getresuid(ruid, euid, suid) return syscall(sys.getresuid, void(ruid), void(euid), void(suid)) end
function C.getresgid(rgid, egid, sgid) return syscall(sys.getresgid, void(rgid), void(egid), void(sgid)) end
function C.setuid(id) return syscall(sys.setuid, uint(id)) end
function C.setgid(id) return syscall(sys.setgid, uint(id)) end
function C.setresuid(ruid, euid, suid) return syscall(sys.setresuid, uint(ruid), uint(euid), uint(suid)) end
function C.setresgid(rgid, egid, sgid) return syscall(sys.setresgid, uint(rgid), uint(egid), uint(sgid)) end
function C.setreuid(uid, euid) return syscall(sys.setreuid, uint(uid), uint(euid)) end
function C.setregid(gid, egid) return syscall(sys.setregid, uint(gid), uint(egid)) end
function C.flock(fd, operation) return syscall(sys.flock, int(fd), int(operation)) end
function C.getrusage(who, usage) return syscall(sys.getrusage, int(who), void(usage)) end
if sys.rmdir then function C.rmdir(path) return syscall(sys.rmdir, void(path)) end end
function C.chdir(path) return syscall(sys.chdir, void(path)) end
function C.fchdir(fd) return syscall(sys.fchdir, int(fd)) end
if sys.chown then function C.chown(path, owner, group) return syscall(sys.chown, void(path), uint(owner), uint(group)) end end
function C.fchown(fd, owner, group) return syscall(sys.fchown, int(fd), uint(owner), uint(group)) end
function C.lchown(path, owner, group) return syscall(sys.lchown, void(path), uint(owner), uint(group)) end
if sys.open then
function C.open(pathname, flags, mode) return syscall(sys.open, void(pathname), int(flags), uint(mode)) end
end
function C.openat(dirfd, pathname, flags, mode) return syscall(sys.openat, int(dirfd), void(pathname), int(flags), uint(mode)) end
if sys.creat then function C.creat(pathname, mode) return syscall(sys.creat, void(pathname), uint(mode)) end end
function C.close(fd) return syscall(sys.close, int(fd)) end
function C.read(fd, buf, count) return syscall_long(sys.read, int(fd), void(buf), ulong(count)) end
function C.write(fd, buf, count) return syscall_long(sys.write, int(fd), void(buf), ulong(count)) end
function C.readv(fd, iov, iovcnt) return syscall_long(sys.readv, int(fd), void(iov), long(iovcnt)) end
function C.writev(fd, iov, iovcnt) return syscall_long(sys.writev, int(fd), void(iov), long(iovcnt)) end
if sys.readlink then function C.readlink(path, buf, bufsiz) return syscall_long(sys.readlink, void(path), void(buf), ulong(bufsiz)) end end
if sys.rename then function C.rename(oldpath, newpath) return syscall(sys.rename, void(oldpath), void(newpath)) end end
function C.renameat(olddirfd, oldpath, newdirfd, newpath)
return syscall(sys.renameat, int(olddirfd), void(oldpath), int(newdirfd), void(newpath))
end
if sys.renameat2 then
function C.renameat2(olddirfd, oldpath, newdirfd, newpath, flags)
return syscall(sys.renameat2, int(olddirfd), void(oldpath), int(newdirfd), void(newpath), int(flags))
end
end
if sys.unlink then function C.unlink(pathname) return syscall(sys.unlink, void(pathname)) end end
function C.unlinkat(dirfd, pathname, flags) return syscall(sys.unlinkat, int(dirfd), void(pathname), int(flags)) end
function C.prctl(option, arg2, arg3, arg4, arg5)
return syscall(sys.prctl, int(option), ulong(arg2), ulong(arg3), ulong(arg4), ulong(arg5))
end
if abi.arch ~= "mips" and abi.arch ~= "mipsel" and sys.pipe then -- mips uses old style dual register return calling convention that we cannot use
function C.pipe(pipefd) return syscall(sys.pipe, void(pipefd)) end
end
function C.pipe2(pipefd, flags) return syscall(sys.pipe2, void(pipefd), int(flags)) end
function C.pause() return syscall(sys.pause) end
function C.remap_file_pages(addr, size, prot, pgoff, flags)
return syscall(sys.remap_file_pages, void(addr), ulong(size), int(prot), long(pgoff), int(flags))
end
if sys.fork then function C.fork() return syscall(sys.fork) end end
function C.kill(pid, sig) return syscall(sys.kill, int(pid), int(sig)) end
if sys.mkdir then function C.mkdir(pathname, mode) return syscall(sys.mkdir, void(pathname), uint(mode)) end end
function C.fsync(fd) return syscall(sys.fsync, int(fd)) end
function C.fdatasync(fd) return syscall(sys.fdatasync, int(fd)) end
function C.sync() return syscall(sys.sync) end
function C.syncfs(fd) return syscall(sys.syncfs, int(fd)) end
if sys.link then function C.link(oldpath, newpath) return syscall(sys.link, void(oldpath), void(newpath)) end end
if sys.symlink then function C.symlink(oldpath, newpath) return syscall(sys.symlink, void(oldpath), void(newpath)) end end
function C.epoll_ctl(epfd, op, fd, event) return syscall(sys.epoll_ctl, int(epfd), int(op), int(fd), void(event)) end
function C.uname(buf) return syscall(sys.uname, void(buf)) end
function C.getsid(pid) return syscall(sys.getsid, int(pid)) end
function C.getpgid(pid) return syscall(sys.getpgid, int(pid)) end
function C.setpgid(pid, pgid) return syscall(sys.setpgid, int(pid), int(pgid)) end
if sys.getpgrp then function C.getpgrp() return syscall(sys.getpgrp) end end
function C.setsid() return syscall(sys.setsid) end
function C.chroot(path) return syscall(sys.chroot, void(path)) end
function C.mount(source, target, filesystemtype, mountflags, data)
return syscall(sys.mount, void(source), void(target), void(filesystemtype), ulong(mountflags), void(data))
end
function C.umount(target) return syscall(sys.umount, void(target)) end
function C.umount2(target, flags) return syscall(sys.umount2, void(target), int(flags)) end
function C.listxattr(path, list, size) return syscall_long(sys.listxattr, void(path), void(list), ulong(size)) end
function C.llistxattr(path, list, size) return syscall_long(sys.llistxattr, void(path), void(list), ulong(size)) end
function C.flistxattr(fd, list, size) return syscall_long(sys.flistxattr, int(fd), void(list), ulong(size)) end
function C.setxattr(path, name, value, size, flags)
return syscall(sys.setxattr, void(path), void(name), void(value), ulong(size), int(flags))
end
function C.lsetxattr(path, name, value, size, flags)
return syscall(sys.lsetxattr, void(path), void(name), void(value), ulong(size), int(flags))
end
function C.fsetxattr(fd, name, value, size, flags)
return syscall(sys.fsetxattr, int(fd), void(name), void(value), ulong(size), int(flags))
end
function C.getxattr(path, name, value, size)
return syscall_long(sys.getxattr, void(path), void(name), void(value), ulong(size))
end
function C.lgetxattr(path, name, value, size)
return syscall_long(sys.lgetxattr, void(path), void(name), void(value), ulong(size))
end
function C.fgetxattr(fd, name, value, size)
return syscall_long(sys.fgetxattr, int(fd), void(name), void(value), ulong(size))
end
function C.removexattr(path, name) return syscall(sys.removexattr, void(path), void(name)) end
function C.lremovexattr(path, name) return syscall(sys.lremovexattr, void(path), void(name)) end
function C.fremovexattr(fd, name) return syscall(sys.fremovexattr, int(fd), void(name)) end
function C.inotify_add_watch(fd, pathname, mask) return syscall(sys.inotify_add_watch, int(fd), void(pathname), uint(mask)) end
function C.inotify_rm_watch(fd, wd) return syscall(sys.inotify_rm_watch, int(fd), int(wd)) end
function C.unshare(flags) return syscall(sys.unshare, int(flags)) end
function C.reboot(magic, magic2, cmd) return syscall(sys.reboot, int(magic), int(magic2), int(cmd)) end
function C.sethostname(name, len) return syscall(sys.sethostname, void(name), ulong(len)) end
function C.setdomainname(name, len) return syscall(sys.setdomainname, void(name), ulong(len)) end
function C.getitimer(which, curr_value) return syscall(sys.getitimer, int(which), void(curr_value)) end
function C.setitimer(which, new_value, old_value) return syscall(sys.setitimer, int(which), void(new_value), void(old_value)) end
function C.sched_yield() return syscall(sys.sched_yield) end
function C.acct(filename) return syscall(sys.acct, void(filename)) end
function C.munmap(addr, length) return syscall(sys.munmap, void(addr), ulong(length)) end
function C.faccessat(dirfd, path, mode, flags) return syscall(sys.faccessat, int(dirfd), void(path), uint(mode), int(flags)) end
function C.fchmodat(dirfd, path, mode, flags) return syscall(sys.fchmodat, int(dirfd), void(path), uint(mode), int(flags)) end
function C.mkdirat(dirfd, pathname, mode) return syscall(sys.mkdirat, int(dirfd), void(pathname), uint(mode)) end
function C.fchownat(dirfd, pathname, owner, group, flags)
return syscall(sys.fchownat, int(dirfd), void(pathname), uint(owner), uint(group), int(flags))
end
function C.setpriority(which, who, prio) return syscall(sys.setpriority, int(which), int(who), int(prio)) end
function C.sched_get_priority_min(policy) return syscall(sys.sched_get_priority_min, int(policy)) end
function C.sched_get_priority_max(policy) return syscall(sys.sched_get_priority_max, int(policy)) end
function C.sched_rr_get_interval(pid, tp) return syscall(sys.sched_rr_get_interval, int(pid), void(tp)) end
if sys.poll then function C.poll(fds, nfds, timeout) return syscall(sys.poll, void(fds), int(nfds), int(timeout)) end end
function C.msync(addr, length, flags) return syscall(sys.msync, void(addr), ulong(length), int(flags)) end
function C.madvise(addr, length, advice) return syscall(sys.madvise, void(addr), ulong(length), int(advice)) end
function C.mlock(addr, len) return syscall(sys.mlock, void(addr), ulong(len)) end
function C.munlock(addr, len) return syscall(sys.munlock, void(addr), ulong(len)) end
function C.mlockall(flags) return syscall(sys.mlockall, int(flags)) end
function C.munlockall() return syscall(sys.munlockall) end
function C.capget(hdrp, datap) return syscall(sys.capget, void(hdrp), void(datap)) end
function C.capset(hdrp, datap) return syscall(sys.capset, void(hdrp), void(datap)) end
function C.sysinfo(info) return syscall(sys.sysinfo, void(info)) end
function C.execve(filename, argv, envp) return syscall(sys.execve, void(filename), void(argv), void(envp)) end
function C.getgroups(size, list) return syscall(sys.getgroups, int(size), void(list)) end
function C.setgroups(size, list) return syscall(sys.setgroups, int(size), void(list)) end
function C.klogctl(tp, bufp, len) return syscall(sys.syslog, int(tp), void(bufp), int(len)) end
function C.sigprocmask(how, set, oldset)
return syscall(sys.rt_sigprocmask, int(how), void(set), void(oldset), sigmasksize(set or oldset))
end
function C.sigpending(set) return syscall(sys.rt_sigpending, void(set), sigmasksize(set)) end
function C.mremap(old_address, old_size, new_size, flags, new_address)
return syscall_void(sys.mremap, void(old_address), ulong(old_size), ulong(new_size), int(flags), void(new_address))
end
function C.nanosleep(req, rem) return syscall(sys.nanosleep, void(req), void(rem)) end
function C.wait4(pid, status, options, rusage) return syscall(sys.wait4, int(pid), void(status), int(options), void(rusage)) end
function C.waitid(idtype, id, infop, options, rusage)
return syscall(sys.waitid, int(idtype), uint(id), void(infop), int(options), void(rusage))
end
function C.settimeofday(tv, tz)
return syscall(sys.settimeofday, void(tv), void(tz))
end
function C.timer_create(clockid, sevp, timerid) return syscall(sys.timer_create, int(clockid), void(sevp), void(timerid)) end
function C.timer_settime(timerid, flags, new_value, old_value)
return syscall(sys.timer_settime, int(timerid), int(flags), void(new_value), void(old_value))
end
function C.timer_gettime(timerid, curr_value) return syscall(sys.timer_gettime, int(timerid), void(curr_value)) end
function C.timer_delete(timerid) return syscall(sys.timer_delete, int(timerid)) end
function C.timer_getoverrun(timerid) return syscall(sys.timer_getoverrun, int(timerid)) end
function C.vhangup() return syscall(sys.vhangup) end
-- only on some architectures
if sys.waitpid then
function C.waitpid(pid, status, options) return syscall(sys.waitpid, int(pid), void(status), int(options)) end
end
-- fcntl needs a cast as last argument may be int or pointer
local fcntl = sys.fcntl64 or sys.fcntl
function C.fcntl(fd, cmd, arg) return syscall(fcntl, int(fd), int(cmd), ffi.cast(long, arg)) end
function C.pselect(nfds, readfds, writefds, exceptfds, timeout, sigmask)
local size = 0
if sigmask then size = sigset_size end
local data = longs(void(sigmask), size)
return syscall(sys.pselect6, int(nfds), void(readfds), void(writefds), void(exceptfds), void(timeout), void(data))
end
-- need _newselect syscall on some platforms
local sysselect = sys._newselect or sys.select
if sysselect then
function C.select(nfds, readfds, writefds, exceptfds, timeout)
return syscall(sysselect, int(nfds), void(readfds), void(writefds), void(exceptfds), void(timeout))
end
end
-- missing on some platforms eg ARM
if sys.alarm then
function C.alarm(seconds) return syscall(sys.alarm, uint(seconds)) end
end
-- new system calls, may be missing TODO fix so is not
if sys.getrandom then
function C.getrandom(buf, count, flags) return syscall(sys.getrandom, void(buf), uint(count), uint(flags)) end
end
if sys.memfd_create then
function C.memfd_create(name, flags) return syscall(sys.memfd_create, void(name), uint(flags)) end
end
-- kernel sigaction structures actually rather different in Linux from libc ones
function C.sigaction(signum, act, oldact)
return syscall(sys.rt_sigaction, int(signum), void(act), void(oldact), ulong(sigset_size)) -- size is size of sigset field
end
-- in VDSO for many archs, so use ffi for speed; TODO read VDSO to find functions there, needs elf reader
if pcall(function(k) return ffi.C[k] end, "clock_gettime") then
C.clock_gettime = ffi.C.clock_gettime
else
function C.clock_gettime(clk_id, ts) return syscall(sys.clock_gettime, int(clk_id), void(ts)) end
end
C.gettimeofday = ffi.C.gettimeofday
--function C.gettimeofday(tv, tz) return syscall(sys.gettimeofday, void(tv), void(tz)) end
-- glibc does not provide getcpu; it is however VDSO
function C.getcpu(cpu, node, tcache) return syscall(sys.getcpu, void(cpu), void(node), void(tcache)) end
-- time is VDSO but not really performance critical; does not exist for some architectures
if sys.time then
function C.time(t) return syscall(sys.time, void(t)) end
end
-- bpf syscall that is only on Linux 3.19+
if sys.bpf then
function C.bpf(cmd, attr)
return syscall(sys.bpf, int(cmd), void(attr), u64(ffi.sizeof('union bpf_attr')))
end
end
if sys.perf_event_open then
function C.perf_event_open(attr, pid, cpu, group_fd, flags)
return syscall(sys.perf_event_open, void(attr), int(pid), int(cpu), int(group_fd), ulong(flags))
end
end
-- socketcalls
if not sys.socketcall then
function C.socket(domain, tp, protocol) return syscall(sys.socket, int(domain), int(tp), int(protocol)) end
function C.bind(sockfd, addr, addrlen) return syscall(sys.bind, int(sockfd), void(addr), uint(addrlen)) end
function C.connect(sockfd, addr, addrlen) return syscall(sys.connect, int(sockfd), void(addr), uint(addrlen)) end
function C.listen(sockfd, backlog) return syscall(sys.listen, int(sockfd), int(backlog)) end
function C.accept(sockfd, addr, addrlen)
return syscall(sys.accept, int(sockfd), void(addr), void(addrlen))
end
function C.getsockname(sockfd, addr, addrlen) return syscall(sys.getsockname, int(sockfd), void(addr), void(addrlen)) end
function C.getpeername(sockfd, addr, addrlen) return syscall(sys.getpeername, int(sockfd), void(addr), void(addrlen)) end
function C.socketpair(domain, tp, protocol, sv) return syscall(sys.socketpair, int(domain), int(tp), int(protocol), void(sv)) end
function C.send(sockfd, buf, len, flags) return syscall_long(sys.send, int(sockfd), void(buf), ulong(len), int(flags)) end
function C.recv(sockfd, buf, len, flags) return syscall_long(sys.recv, int(sockfd), void(buf), ulong(len), int(flags)) end
function C.sendto(sockfd, buf, len, flags, dest_addr, addrlen)
return syscall_long(sys.sendto, int(sockfd), void(buf), ulong(len), int(flags), void(dest_addr), uint(addrlen))
end
function C.recvfrom(sockfd, buf, len, flags, src_addr, addrlen)
return syscall_long(sys.recvfrom, int(sockfd), void(buf), ulong(len), int(flags), void(src_addr), void(addrlen))
end
function C.shutdown(sockfd, how) return syscall(sys.shutdown, int(sockfd), int(how)) end
function C.setsockopt(sockfd, level, optname, optval, optlen)
return syscall(sys.setsockopt, int(sockfd), int(level), int(optname), void(optval), uint(optlen))
end
function C.getsockopt(sockfd, level, optname, optval, optlen)
return syscall(sys.getsockopt, int(sockfd), int(level), int(optname), void(optval), void(optlen))
end
function C.sendmsg(sockfd, msg, flags) return syscall_long(sys.sendmsg, int(sockfd), void(msg), int(flags)) end
function C.recvmsg(sockfd, msg, flags) return syscall_long(sys.recvmsg, int(sockfd), void(msg), int(flags)) end
function C.accept4(sockfd, addr, addrlen, flags)
return syscall(sys.accept4, int(sockfd), void(addr), void(addrlen), int(flags))
end
function C.recvmmsg(sockfd, msgvec, vlen, flags, timeout)
return syscall(sys.recvmmsg, int(sockfd), void(msgvec), uint(vlen), int(flags), void(timeout))
end
function C.sendmmsg(sockfd, msgvec, vlen, flags)
return syscall(sys.sendmmsg, int(sockfd), void(msgvec), uint(vlen), int(flags))
end
else
function C.socket(domain, tp, protocol)
local args = longs(domain, tp, protocol)
return syscall(sys.socketcall, int(socketcalls.SOCKET), void(args))
end
function C.bind(sockfd, addr, addrlen)
local args = longs(sockfd, void(addr), addrlen)
return syscall(sys.socketcall, int(socketcalls.BIND), void(args))
end
function C.connect(sockfd, addr, addrlen)
local args = longs(sockfd, void(addr), addrlen)
return syscall(sys.socketcall, int(socketcalls.CONNECT), void(args))
end
function C.listen(sockfd, backlog)
local args = longs(sockfd, backlog)
return syscall(sys.socketcall, int(socketcalls.LISTEN), void(args))
end
function C.accept(sockfd, addr, addrlen)
local args = longs(sockfd, void(addr), void(addrlen))
return syscall(sys.socketcall, int(socketcalls.ACCEPT), void(args))
end
function C.getsockname(sockfd, addr, addrlen)
local args = longs(sockfd, void(addr), void(addrlen))
return syscall(sys.socketcall, int(socketcalls.GETSOCKNAME), void(args))
end
function C.getpeername(sockfd, addr, addrlen)
local args = longs(sockfd, void(addr), void(addrlen))
return syscall(sys.socketcall, int(socketcalls.GETPEERNAME), void(args))
end
function C.socketpair(domain, tp, protocol, sv)
local args = longs(domain, tp, protocol, void(sv))
return syscall(sys.socketcall, int(socketcalls.SOCKETPAIR), void(args))
end
function C.send(sockfd, buf, len, flags)
local args = longs(sockfd, void(buf), len, flags)
return syscall_long(sys.socketcall, int(socketcalls.SEND), void(args))
end
function C.recv(sockfd, buf, len, flags)
local args = longs(sockfd, void(buf), len, flags)
return syscall_long(sys.socketcall, int(socketcalls.RECV), void(args))
end
function C.sendto(sockfd, buf, len, flags, dest_addr, addrlen)
local args = longs(sockfd, void(buf), len, flags, void(dest_addr), addrlen)
return syscall_long(sys.socketcall, int(socketcalls.SENDTO), void(args))
end
function C.recvfrom(sockfd, buf, len, flags, src_addr, addrlen)
local args = longs(sockfd, void(buf), len, flags, void(src_addr), void(addrlen))
return syscall_long(sys.socketcall, int(socketcalls.RECVFROM), void(args))
end
function C.shutdown(sockfd, how)
local args = longs(sockfd, how)
return syscall(sys.socketcall, int(socketcalls.SHUTDOWN), void(args))
end
function C.setsockopt(sockfd, level, optname, optval, optlen)
local args = longs(sockfd, level, optname, void(optval), optlen)
return syscall(sys.socketcall, int(socketcalls.SETSOCKOPT), void(args))
end
function C.getsockopt(sockfd, level, optname, optval, optlen)
local args = longs(sockfd, level, optname, void(optval), void(optlen))
return syscall(sys.socketcall, int(socketcalls.GETSOCKOPT), void(args))
end
function C.sendmsg(sockfd, msg, flags)
local args = longs(sockfd, void(msg), flags)
return syscall_long(sys.socketcall, int(socketcalls.SENDMSG), void(args))
end
function C.recvmsg(sockfd, msg, flags)
local args = longs(sockfd, void(msg), flags)
return syscall_long(sys.socketcall, int(socketcalls.RECVMSG), void(args))
end
function C.accept4(sockfd, addr, addrlen, flags)
local args = longs(sockfd, void(addr), void(addrlen), flags)
return syscall(sys.socketcall, int(socketcalls.ACCEPT4), void(args))
end
function C.recvmmsg(sockfd, msgvec, vlen, flags, timeout)
local args = longs(sockfd, void(msgvec), vlen, flags, void(timeout))
return syscall(sys.socketcall, int(socketcalls.RECVMMSG), void(args))
end
function C.sendmmsg(sockfd, msgvec, vlen, flags)
local args = longs(sockfd, void(msgvec), vlen, flags)
return syscall(sys.socketcall, int(socketcalls.SENDMMSG), void(args))
end
end
return C
| apache-2.0 |
thedraked/darkstar | scripts/zones/Port_Bastok/npcs/Bagnobrok.lua | 17 | 1554 | -----------------------------------
-- Area: Port Bastok
-- NPC: Bagnobrok
-- Only sells when Bastok controls Movalpolos
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(MOVALPOLOS);
if (RegionOwner ~= NATION_BASTOK) then
player:showText(npc,BAGNOBROK_CLOSED_DIALOG);
else
player:showText(npc,BAGNOBROK_OPEN_DIALOG);
stock = {
0x0280, 11, --Copper Ore
0x1162, 694, --Coral Fungus
0x1117, 4032, --Danceshroom
0x0672, 6500, --Kopparnickel Ore
0x142D, 736 --Movalpolos Water
}
showShop(player,BASTOK,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
eduardoabinader/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 |
mtroyka/Zero-K | LuaRules/Configs/StartBoxes/Akilon Wastelands ZK v1.lua | 11 | 19588 | return {
[0] = {
boxes = {
{
{6950, 6435},
{6804, 6292},
{6794, 6284},
{6783, 6283},
{6781, 6294},
{6782, 6304},
{6779, 6315},
{6770, 6326},
{6761, 6336},
{6754, 6347},
{6743, 6354},
{6733, 6357},
{6722, 6359},
{6712, 6360},
{6702, 6360},
{6691, 6359},
{6681, 6359},
{6671, 6360},
{6660, 6362},
{6650, 6361},
{6640, 6362},
{6630, 6365},
{6619, 6367},
{6608, 6367},
{6598, 6367},
{6588, 6368},
{6578, 6370},
{6546, 6377},
{6536, 6381},
{6525, 6386},
{6516, 6396},
{6506, 6402},
{6496, 6412},
{6490, 6422},
{6481, 6432},
{6471, 6439},
{6461, 6445},
{6451, 6456},
{6446, 6467},
{6445, 6477},
{6444, 6495},
{6445, 6506},
{6445, 6516},
{6445, 6527},
{6444, 6537},
{6440, 6547},
{6432, 6557},
{6424, 6568},
{6414, 6577},
{6403, 6585},
{6394, 6595},
{6383, 6605},
{6378, 6616},
{6371, 6626},
{6367, 6637},
{6355, 6674},
{6349, 6686},
{6341, 6696},
{6331, 6707},
{6322, 6718},
{6313, 6728},
{6304, 6738},
{6294, 6748},
{6283, 6758},
{6273, 6767},
{6264, 6777},
{6258, 6788},
{6258, 6798},
{6256, 6808},
{6256, 6819},
{6256, 6830},
{6257, 6840},
{6256, 6851},
{6255, 6862},
{6255, 6873},
{6255, 6883},
{6256, 6895},
{6256, 6907},
{6256, 6919},
{6257, 6945},
{6257, 6956},
{6257, 6967},
{6252, 6977},
{6246, 6987},
{6239, 6997},
{6230, 7009},
{6219, 7020},
{6209, 7030},
{6199, 7038},
{6188, 7045},
{6182, 7055},
{6181, 7065},
{6178, 7075},
{6176, 7087},
{6173, 7098},
{6171, 7109},
{6169, 7119},
{6156, 7149},
{6148, 7159},
{6136, 7168},
{6123, 7179},
{6112, 7184},
{6105, 7195},
{6095, 7206},
{6084, 7217},
{6075, 7227},
{6065, 7236},
{6055, 7248},
{6044, 7260},
{6037, 7272},
{6029, 7283},
{6018, 7293},
{6009, 7303},
{6005, 7313},
{5998, 7324},
{5992, 7335},
{5991, 7346},
{5992, 7356},
{5992, 7366},
{5993, 7377},
{5993, 7387},
{5994, 7398},
{5994, 7408},
{5997, 7419},
{6001, 7430},
{6009, 7443},
{6014, 7454},
{6023, 7464},
{6029, 7475},
{6037, 7486},
{6043, 7497},
{6047, 7509},
{6050, 7520},
{6051, 7531},
{6054, 7542},
{6058, 7553},
{6063, 7563},
{6067, 7575},
{6074, 7586},
{6083, 7596},
{6093, 7603},
{6104, 7608},
{6114, 7614},
{6126, 7620},
{6138, 7622},
{6148, 7622},
{6160, 7622},
{6171, 7622},
{6183, 7621},
{6194, 7620},
{6205, 7620},
{6217, 7619},
{6229, 7619},
{6240, 7620},
{6251, 7620},
{6261, 7621},
{6271, 7619},
{6281, 7611},
{6290, 7601},
{6299, 7590},
{6305, 7579},
{6313, 7569},
{6323, 7562},
{6334, 7554},
{6345, 7550},
{6355, 7549},
{6365, 7547},
{6376, 7543},
{6382, 7533},
{6387, 7520},
{6387, 7510},
{6389, 7500},
{6391, 7489},
{6393, 7478},
{6398, 7468},
{6409, 7458},
{6420, 7451},
{6431, 7445},
{6442, 7442},
{6453, 7440},
{6463, 7437},
{6475, 7434},
{6488, 7434},
{6498, 7434},
{6510, 7433},
{6522, 7433},
{6534, 7433},
{6547, 7434},
{6559, 7438},
{6574, 7441},
{6587, 7445},
{6597, 7448},
{6623, 7450},
{6633, 7453},
{6644, 7456},
{6654, 7460},
{6666, 7469},
{6676, 7478},
{6685, 7489},
{6689, 7500},
{6693, 7514},
{6695, 7527},
{6695, 7537},
{6698, 7549},
{6700, 7560},
{6702, 7572},
{6704, 7584},
{6711, 7595},
{6719, 7607},
{6728, 7618},
{6738, 7628},
{6750, 7638},
{6760, 7649},
{6768, 7660},
{6778, 7671},
{6789, 7682},
{6799, 7694},
{6809, 7705},
{6818, 7716},
{6827, 7727},
{6833, 7737},
{6840, 7749},
{6847, 7760},
{6854, 7771},
{6860, 7781},
{6865, 7796},
{6872, 7807},
{6878, 7819},
{6887, 7829},
{6897, 7838},
{6909, 7847},
{6920, 7853},
{6931, 7859},
{6942, 7864},
{6952, 7865},
{6963, 7865},
{6974, 7865},
{6985, 7861},
{6995, 7856},
{7007, 7852},
{7018, 7852},
{7029, 7852},
{7040, 7856},
{7051, 7859},
{7062, 7859},
{7075, 7862},
{7088, 7864},
{7099, 7865},
{7110, 7868},
{7121, 7868},
{7132, 7868},
{7144, 7867},
{7155, 7863},
{7166, 7860},
{7178, 7856},
{7189, 7854},
{7200, 7849},
{7212, 7839},
{7221, 7828},
{7228, 7817},
{7238, 7807},
{7248, 7801},
{7259, 7796},
{7269, 7797},
{7280, 7803},
{7291, 7808},
{7305, 7815},
{7315, 7824},
{7325, 7834},
{7337, 7842},
{7347, 7846},
{7357, 7849},
{7368, 7852},
{7379, 7855},
{7390, 7853},
{7401, 7849},
{7412, 7848},
{7440, 7845},
{7451, 7843},
{7462, 7842},
{7473, 7842},
{7484, 7843},
{7494, 7846},
{7504, 7848},
{7515, 7851},
{7525, 7855},
{7536, 7858},
{7546, 7864},
{7556, 7870},
{7567, 7874},
{7583, 7884},
{7594, 7884},
{7605, 7883},
{7615, 7875},
{7624, 7864},
{7632, 7854},
{7641, 7844},
{7650, 7834},
{7656, 7824},
{7657, 7813},
{7657, 7802},
{7658, 7792},
{7666, 7762},
{7674, 7749},
{7684, 7739},
{7695, 7728},
{7706, 7722},
{7716, 7720},
{7729, 7720},
{7740, 7722},
{7750, 7725},
{7762, 7728},
{7773, 7733},
{7783, 7741},
{7791, 7752},
{7801, 7761},
{7812, 7757},
{7822, 7747},
{7847, 7717},
{7857, 7709},
{7868, 7700},
{7879, 7695},
{7889, 7692},
{7899, 7686},
{7905, 7675},
{7907, 7665},
{7907, 7654},
{7903, 7644},
{7901, 7633},
{7900, 7622},
{7903, 7592},
{7909, 7581},
{7919, 7572},
{7930, 7563},
{7940, 7556},
{7951, 7549},
{7962, 7546},
{7973, 7544},
{7983, 7542},
{7994, 7539},
{8005, 7532},
{8013, 7522},
{8017, 7512},
{8019, 7501},
{8021, 7490},
{8024, 7478},
{8026, 7467},
{8028, 7431},
{8029, 7420},
{8030, 7410},
{8036, 7399},
{8045, 7388},
{8053, 7377},
{8057, 7367},
{8058, 7355},
{8059, 7345},
{8059, 7333},
{8057, 7321},
{8053, 7310},
{8046, 7300},
{8039, 7290},
{8034, 7280},
{8027, 7268},
{8020, 7258},
{8014, 7248},
{7973, 7179},
{7969, 7169},
{7962, 7159},
{7960, 7148},
{7958, 7137},
{7957, 7126},
{7957, 7116},
{7959, 7104},
{7962, 7094},
{7968, 7083},
{7978, 7073},
{7988, 7061},
{7999, 7050},
{8010, 7042},
{8020, 7033},
{8029, 7021},
{8034, 7011},
{8039, 7001},
{8044, 6988},
{8048, 6978},
{8052, 6967},
{8054, 6956},
{8066, 6921},
{8067, 6910},
{8066, 6900},
{8065, 6889},
{8063, 6879},
{8056, 6869},
{8048, 6859},
{8037, 6848},
{8027, 6838},
{8018, 6828},
{8009, 6817},
{8003, 6806},
{7994, 6794},
{7986, 6783},
{7979, 6772},
{7975, 6761},
{7971, 6750},
{7966, 6738},
{7947, 6679},
{7940, 6668},
{7933, 6656},
{7928, 6646},
{7925, 6634},
{7917, 6622},
{7912, 6611},
{7910, 6600},
{7908, 6588},
{7906, 6578},
{7907, 6567},
{7907, 6554},
{7907, 6544},
{7910, 6532},
{7913, 6519},
{7917, 6509},
{7923, 6498},
{7929, 6487},
{7934, 6473},
{7938, 6463},
{7941, 6453},
{7946, 6441},
{7951, 6428},
{7957, 6418},
{7967, 6407},
{7976, 6397},
{7987, 6388},
{8007, 6374},
{8019, 6369},
{8030, 6366},
{8040, 6362},
{8050, 6359},
{8055, 6348},
{8045, 6340},
{8034, 6333},
{8024, 6326},
{8013, 6317},
{8003, 6309},
{7993, 6300},
{7982, 6289},
{7971, 6279},
{7962, 6268},
{7952, 6257},
{7941, 6248},
{7913, 6227},
{7903, 6221},
{7893, 6216},
{7883, 6209},
{7872, 6203},
{7862, 6195},
{7852, 6203},
{7845, 6213},
{7836, 6223},
{7825, 6230},
{7814, 6236},
{7804, 6242},
{7793, 6248},
{7782, 6250},
{7771, 6253},
{7761, 6253},
{7750, 6253},
{7739, 6252},
{7729, 6251},
{7717, 6245},
{7706, 6240},
{7695, 6233},
{7684, 6228},
{7674, 6221},
{7664, 6214},
{7652, 6204},
{7642, 6195},
{7633, 6184},
{7625, 6173},
{7617, 6162},
{7609, 6151},
{7604, 6137},
{7600, 6127},
{7588, 6111},
{7576, 6107},
{7565, 6097},
{7555, 6091},
{7544, 6083},
{7533, 6075},
{7521, 6067},
{7510, 6059},
{7499, 6052},
{7488, 6050},
{7478, 6048},
{7467, 6045},
{7455, 6041},
{7444, 6038},
{7433, 6034},
{7421, 6032},
{7410, 6028},
{7400, 6023},
{7390, 6014},
{7380, 6006},
{7369, 5996},
{7361, 5985},
{7354, 5972},
{7348, 5962},
{7340, 5951},
{7329, 5932},
{7318, 5924},
{7306, 5918},
{7295, 5910},
{7284, 5904},
{7273, 5899},
{7261, 5891},
{7252, 5881},
{7244, 5871},
{7234, 5859},
{7226, 5849},
{7218, 5839},
{7212, 5828},
{7209, 5816},
{7206, 5806},
{7196, 5798},
{7185, 5796},
{7174, 5802},
{7164, 5807},
{7159, 5817},
{7158, 5828},
{7159, 5839},
{7162, 5849},
{7168, 5861},
{7175, 5872},
{7184, 5883},
{7192, 5894},
{7201, 5905},
{7211, 5916},
{7221, 5925},
{7231, 5936},
{7241, 5949},
{7250, 5959},
{7269, 5980},
{7278, 5991},
{7287, 6003},
{7294, 6013},
{7302, 6023},
{7308, 6036},
{7311, 6046},
{7313, 6058},
{7315, 6070},
{7315, 6080},
{7315, 6091},
{7311, 6102},
{7307, 6114},
{7302, 6125},
{7297, 6136},
{7288, 6147},
{7039, 6417},
{7030, 6427},
{7018, 6434},
{7007, 6442},
{6995, 6445},
{6985, 6447},
{6974, 6446},
{6956, 6439},
},
},
startpoints = {
{7300, 7300},
},
nameLong = "South-East",
nameShort = "SE",
},
[1] = {
boxes = {
{
{1013, 2302},
{929, 2202},
{923, 2192},
{920, 2181},
{920, 2171},
{922, 2160},
{925, 2149},
{934, 2139},
{945, 2133},
{957, 2125},
{1256, 1815},
{1267, 1809},
{1278, 1806},
{1289, 1805},
{1299, 1808},
{1309, 1818},
{1386, 1892},
{1397, 1899},
{1407, 1893},
{1408, 1883},
{1408, 1873},
{1408, 1863},
{1411, 1852},
{1419, 1842},
{1429, 1834},
{1440, 1827},
{1450, 1821},
{1461, 1817},
{1473, 1812},
{1484, 1810},
{1494, 1809},
{1504, 1807},
{1515, 1805},
{1580, 1795},
{1592, 1793},
{1603, 1790},
{1613, 1785},
{1624, 1783},
{1635, 1781},
{1646, 1780},
{1660, 1777},
{1671, 1776},
{1682, 1776},
{1693, 1776},
{1704, 1776},
{1715, 1772},
{1723, 1761},
{1719, 1750},
{1716, 1739},
{1712, 1729},
{1710, 1719},
{1707, 1647},
{1712, 1629},
{1725, 1612},
{1825, 1536},
{1873, 1502},
{1889, 1486},
{1898, 1475},
{1903, 1464},
{1908, 1453},
{1912, 1442},
{1917, 1431},
{1922, 1421},
{1927, 1410},
{1930, 1398},
{1932, 1387},
{1933, 1377},
{1934, 1366},
{1930, 1355},
{1926, 1345},
{1921, 1334},
{1912, 1323},
{1901, 1312},
{1891, 1303},
{1884, 1293},
{1880, 1282},
{1878, 1270},
{1879, 1259},
{1880, 1248},
{1883, 1238},
{1888, 1227},
{1898, 1217},
{1981, 1154},
{2039, 1121},
{2063, 1114},
{2073, 1109},
{2080, 1099},
{2085, 1088},
{2087, 1078},
{2088, 1067},
{2089, 1055},
{2089, 1044},
{2086, 1033},
{2085, 1023},
{2085, 1012},
{2090, 991},
{2095, 981},
{2106, 971},
{2116, 964},
{2182, 922},
{2192, 915},
{2199, 903},
{2200, 893},
{2199, 883},
{2192, 872},
{2182, 864},
{2175, 854},
{2173, 842},
{2171, 832},
{2170, 822},
{2165, 808},
{2155, 800},
{2144, 792},
{2134, 785},
{2123, 778},
{2113, 774},
{2103, 771},
{2092, 766},
{2082, 756},
{2071, 746},
{2067, 736},
{2065, 726},
{2064, 715},
{2061, 705},
{2058, 694},
{2055, 629},
{2051, 619},
{2044, 608},
{2034, 604},
{2024, 603},
{2014, 603},
{2004, 601},
{1992, 599},
{1982, 597},
{1971, 593},
{1960, 588},
{1928, 569},
{1918, 565},
{1908, 563},
{1897, 563},
{1888, 573},
{1885, 584},
{1882, 594},
{1878, 605},
{1846, 649},
{1796, 702},
{1785, 711},
{1774, 717},
{1764, 723},
{1756, 734},
{1749, 744},
{1745, 755},
{1739, 765},
{1730, 775},
{1720, 783},
{1710, 788},
{1699, 794},
{1688, 799},
{1677, 801},
{1667, 803},
{1655, 805},
{1645, 806},
{1635, 808},
{1624, 808},
{1613, 808},
{1602, 806},
{1591, 803},
{1581, 799},
{1570, 795},
{1559, 791},
{1549, 787},
{1537, 782},
{1524, 775},
{1514, 770},
{1504, 764},
{1493, 754},
{1485, 743},
{1475, 732},
{1470, 720},
{1467, 708},
{1465, 697},
{1453, 641},
{1447, 631},
{1441, 620},
{1434, 610},
{1429, 599},
{1422, 588},
{1417, 578},
{1410, 567},
{1403, 556},
{1396, 546},
{1387, 534},
{1377, 526},
{1365, 516},
{1354, 508},
{1343, 499},
{1332, 492},
{1300, 464},
{1290, 453},
{1282, 443},
{1276, 432},
{1272, 421},
{1269, 411},
{1267, 400},
{1265, 390},
{1263, 379},
{1260, 368},
{1255, 357},
{1251, 347},
{1248, 336},
{1242, 325},
{1236, 314},
{1230, 303},
{1222, 293},
{1212, 284},
{1202, 282},
{1191, 284},
{1186, 295},
{1181, 306},
{1175, 317},
{1168, 327},
{1162, 337},
{1152, 347},
{1140, 358},
{1129, 366},
{1119, 374},
{1107, 381},
{1096, 388},
{1086, 394},
{1075, 402},
{1064, 407},
{1054, 412},
{1044, 416},
{1033, 418},
{1021, 422},
{1008, 424},
{995, 425},
{985, 426},
{973, 426},
{963, 425},
{952, 424},
{942, 422},
{931, 421},
{921, 418},
{911, 416},
{871, 396},
{859, 388},
{849, 380},
{838, 372},
{828, 366},
{818, 363},
{808, 357},
{798, 352},
{785, 346},
{775, 342},
{765, 340},
{754, 337},
{742, 337},
{732, 337},
{722, 337},
{712, 337},
{701, 336},
{690, 332},
{679, 331},
{666, 330},
{655, 330},
{644, 340},
{635, 351},
{630, 361},
{629, 372},
{628, 382},
{628, 392},
{626, 404},
{625, 415},
{619, 426},
{613, 436},
{608, 446},
{596, 453},
{586, 455},
{574, 459},
{562, 462},
{551, 465},
{540, 467},
{528, 471},
{517, 475},
{505, 478},
{493, 483},
{483, 489},
{471, 494},
{459, 497},
{448, 502},
{437, 506},
{425, 507},
{415, 506},
{403, 499},
{393, 491},
{383, 485},
{372, 477},
{362, 468},
{352, 474},
{349, 484},
{349, 494},
{350, 505},
{350, 516},
{350, 526},
{350, 536},
{351, 547},
{352, 557},
{351, 567},
{350, 578},
{346, 589},
{338, 599},
{330, 610},
{321, 620},
{308, 629},
{298, 637},
{287, 641},
{277, 644},
{267, 647},
{257, 650},
{246, 652},
{235, 654},
{225, 656},
{214, 663},
{203, 673},
{194, 684},
{184, 694},
{181, 704},
{180, 715},
{180, 725},
{179, 737},
{179, 749},
{181, 760},
{186, 770},
{191, 781},
{195, 797},
{196, 808},
{196, 819},
{193, 830},
{188, 841},
{182, 851},
{174, 862},
{163, 872},
{152, 880},
{142, 888},
{134, 898},
{129, 909},
{124, 919},
{120, 929},
{115, 940},
{114, 951},
{118, 962},
{119, 972},
{125, 1004},
{125, 1014},
{126, 1026},
{126, 1037},
{126, 1047},
{128, 1057},
{131, 1068},
{137, 1079},
{142, 1089},
{148, 1102},
{151, 1112},
{155, 1122},
{160, 1133},
{161, 1152},
{163, 1163},
{166, 1174},
{166, 1185},
{165, 1197},
{164, 1208},
{163, 1218},
{163, 1229},
{163, 1239},
{163, 1249},
{167, 1259},
{175, 1269},
{183, 1280},
{190, 1291},
{197, 1301},
{203, 1312},
{206, 1322},
{209, 1332},
{211, 1343},
{212, 1354},
{214, 1366},
{215, 1377},
{216, 1388},
{217, 1400},
{218, 1410},
{218, 1420},
{217, 1430},
{215, 1440},
{214, 1451},
{217, 1462},
{227, 1473},
{238, 1479},
{255, 1487},
{268, 1495},
{279, 1504},
{288, 1515},
{293, 1525},
{300, 1537},
{303, 1547},
{306, 1565},
{306, 1577},
{307, 1587},
{308, 1598},
{314, 1609},
{318, 1621},
{322, 1631},
{327, 1642},
{330, 1652},
{331, 1664},
{331, 1674},
{328, 1685},
{326, 1696},
{315, 1707},
{305, 1718},
{299, 1729},
{264, 1751},
{255, 1761},
{245, 1769},
{239, 1780},
{249, 1791},
{261, 1799},
{271, 1807},
{282, 1815},
{291, 1825},
{298, 1837},
{300, 1848},
{303, 1861},
{304, 1873},
{307, 1884},
{310, 1895},
{314, 1945},
{316, 1955},
{319, 1966},
{320, 1976},
{320, 1987},
{320, 1998},
{318, 2009},
{315, 2019},
{326, 2017},
{336, 2008},
{346, 2002},
{356, 1999},
{367, 1997},
{377, 1995},
{387, 1991},
{398, 1990},
{408, 1986},
{420, 1977},
{431, 1969},
{442, 1963},
{453, 1960},
{463, 1959},
{474, 1958},
{484, 1958},
{497, 1960},
{509, 1961},
{519, 1962},
{529, 1964},
{540, 1966},
{553, 1971},
{565, 1977},
{575, 1986},
{585, 1997},
{594, 2008},
{599, 2019},
{603, 2029},
{605, 2040},
{606, 2052},
{606, 2062},
{606, 2074},
{617, 2080},
{627, 2081},
{638, 2083},
{648, 2085},
{659, 2085},
{669, 2088},
{680, 2091},
{690, 2094},
{700, 2097},
{711, 2093},
{720, 2081},
{730, 2071},
{749, 2059},
{762, 2059},
{775, 2059},
{786, 2059},
{798, 2057},
{809, 2057},
{819, 2058},
{829, 2062},
{840, 2068},
{851, 2074},
{859, 2084},
{863, 2094},
{866, 2105},
{868, 2117},
{869, 2128},
{869, 2139},
{864, 2150},
{856, 2160},
{845, 2169},
{835, 2177},
{824, 2186},
{816, 2196},
{822, 2206},
{899, 2274},
{906, 2284},
{910, 2296},
{914, 2307},
{918, 2317},
{922, 2327},
{926, 2338},
{932, 2348},
{941, 2358},
{951, 2367},
{962, 2376},
{973, 2386},
{982, 2396},
{989, 2406},
{999, 2417},
{1009, 2427},
{1019, 2435},
{1022, 2425},
{1031, 2415},
{1037, 2405},
{1048, 2395},
{1059, 2386},
{1069, 2376},
{1068, 2366},
{1062, 2354},
{1055, 2343},
{1044, 2333},
{1033, 2323},
{1019, 2310},
},
},
startpoints = {
{800, 800},
},
nameLong = "North-West",
nameShort = "NW",
},
},
{ 2 }
| gpl-2.0 |
ukoloff/rufus-lua-win | vendor/lua/lib/lua/logging/file.lua | 3 | 1493 | -------------------------------------------------------------------------------
-- Saves logging information in a file
--
-- @author Thiago Costa Ponte (thiago@ideais.com.br)
--
-- @copyright 2004-2011 Kepler Project
--
-------------------------------------------------------------------------------
require"logging"
local lastFileNameDatePattern
local lastFileHandler
local openFileLogger = function (filename, datePattern)
local filename = string.format(filename, os.date(datePattern))
if (lastFileNameDatePattern ~= filename) then
local f = io.open(filename, "a")
if (f) then
f:setvbuf ("line")
lastFileNameDatePattern = filename
lastFileHandler = f
return f
else
return nil, string.format("file `%s' could not be opened for writing", filename)
end
else
return lastFileHandler
end
end
function logging.file(filename, datePattern, logPattern)
if type(filename) ~= "string" then
filename = "lualogging.log"
end
return logging.new( function(self, level, message)
local f, msg = openFileLogger(filename, datePattern)
if not f then
return nil, msg
end
local s = logging.prepareLogMsg(logPattern, os.date(), level, message)
f:write(s)
return true
end
)
end
return logging.file
| mit |
thedraked/darkstar | scripts/zones/Dragons_Aery/mobs/Fafnir.lua | 12 | 1849 | -----------------------------------
-- Area: Dragons Aery
-- HNM: Fafnir
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then
GetNPCByID(17408033):setStatus(STATUS_DISAPPEAR);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:addTitle(FAFNIR_SLAYER);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local Fafnir = mob:getID();
local Nidhogg = mob:getID()+1;
local ToD = GetServerVariable("[POP]Nidhogg");
local kills = GetServerVariable("[PH]Nidhogg");
local popNow = (math.random(1,5) == 3 or kills > 6);
if (LandKingSystem_HQ ~= 1 and ToD <= os.time(t) and popNow == true) then
-- 0 = timed spawn, 1 = force pop only, 2 = BOTH
if (LandKingSystem_NQ == 0) then
DeterMob(Fafnir, true);
end
DeterMob(Nidhogg, false);
UpdateNMSpawnPoint(Nidhogg);
GetMobByID(Nidhogg):setRespawnTime(math.random(75600,86400));
else
if (LandKingSystem_NQ ~= 1) then
UpdateNMSpawnPoint(Fafnir);
mob:setRespawnTime(math.random(75600,86400));
SetServerVariable("[PH]Nidhogg", kills + 1);
end
end
if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then
GetNPCByID(17408033):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME);
end
end;
| gpl-3.0 |
thedraked/darkstar | scripts/zones/Windurst_Woods/npcs/Wani_Casdohry.lua | 17 | 1310 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Wani Casdohry
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING);
if (TwinstoneBonding == QUEST_COMPLETED) then
player:startEvent(0x01ec,0,13360);
elseif (TwinstoneBonding == QUEST_ACCEPTED) then
player:startEvent(0x01e9,0,13360);
else
player:startEvent(0x01a9);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
thedraked/darkstar | scripts/zones/West_Ronfaure/npcs/Doladepaiton_RK.lua | 14 | 3332 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Doladepaiton, R.K.
-- Type: Outpost Conquest Guards
-- @pos -448 -19 -214 100
-------------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
--------------------------------------
require("scripts/globals/conquest");
require("scripts/zones/West_Ronfaure/TextIDs");
local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = RONFAURE;
local csid = 0x7ffb;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
thedraked/darkstar | scripts/zones/Bastok_Markets/npcs/Pavel.lua | 30 | 1775 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Pavel
-- Involved in Quest: Stamp Hunt
-- @pos -349.798 -10.002 -181.296 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
local StampHunt = player:getQuestStatus(BASTOK,STAMP_HUNT);
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,14) == false) then
player:startEvent(0x01af);
elseif (StampHunt == QUEST_ACCEPTED and player:getMaskBit(player:getVar("StampHunt_Mask"),2) == false) then
player:startEvent(0x00e3);
else
player:startEvent(0x0080);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x01af) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",14,true);
elseif (csid == 0x00e3) then
player:setMaskBit(player:getVar("StampHunt_Mask"),"StampHunt_Mask",2,true);
end
end;
| gpl-3.0 |
alalazo/wesnoth | data/multiplayer/scenarios/2p_Dark_Forecast.lua | 2 | 17082 |
local helper = wesnoth.require("helper")
local _ = wesnoth.textdomain 'wesnoth-multiplayer'
local T = helper.set_wml_tag_metatable {}
local on_event = wesnoth.require("on_event")
local random_spawns = {
{
{"Heavy Infantryman", "Shock Trooper", "Iron Mauler", "none"},
{"Elvish Fighter", "Elvish Hero", "more", "Elvish Champion"},
{"Goblin Spearman", "more", "more", "more"},
{"Goblin Spearman", "Goblin Rouser", "none", "none"},
{"Elvish Fighter", "Elvish Captain", "Elvish Marshal", "none"},
},
{
{"Mage", "Red Mage", "Silver Mage", "none"},
{"Footpad", "Outlaw", "more", "none"},
{"Drake Fighter", "Drake Warrior", "Drake Blademaster", "none"},
{"Walking Corpse", "more", "more", "more"},
},
{
{"Merman Hunter", "Merman Spearman", "Merman Entangler", "none"},
{"Naga Fighter", "Naga Warrior", "Naga Myrmidon", "none"},
{"Spearman", "Pikeman", "none", "Halberdier"},
},
{
{"Elvish Shaman", "Elvish Druid", "Elvish Shyde", "Elvish Sylph"},
{"Drake Burner", "Fire Drake", "Inferno Drake", "Armageddon Drake"},
{"Skeleton", "Revenant", "more", "Draug"},
},
{
{"Giant Mudcrawler", "Sea Serpent", "none", "none"},
{"Mudcrawler", "more", "Giant Mudcrawler", "more"},
},
{
{"Ghoul", "Necrophage", "more", "none"},
{"Elvish Archer", "Elvish Marksman", "none", "Elvish Sharpshooter"},
{"Elvish Archer", "Elvish Ranger", "Elvish Avenger", "none"},
{"Drake Clasher", "Drake Thrasher", "more", "Drake Enforcer"},
},
{
{"Skeleton Archer", "Bone Shooter", "more", "Banebow"},
{"Fencer", "Duelist", "none", "Master at Arms"},
{"Drake Glider", "Sky Drake", "Hurricane Drake", "none"},
},
{
{"Merman Fighter", "Merman Warrior", "more", "Merman Triton"},
{"Dark Adept", "Dark Sorcerer", "Necromancer", "none"},
{"Elvish Scout", "Elvish Rider", "more", "none"},
},
{
{"Wose", "Elder Wose", "Ancient Wose", "none"},
{"Orcish Archer", "Orcish Crossbowman", "Orcish Slurbow", "none"},
{"Saurian Skirmisher", "more", "Saurian Ambusher", "more"},
},
{
{"Orcish Grunt", "Orcish Warrior", "more", "none"},
{"Vampire Bat", "Blood Bat", "more", "none"},
{"Dwarvish Thunderer", "Dwarvish Thunderguard", "none", "none"},
{"Peasant", "more", "more", "more"},
{"Woodsman", "more", "Sergeant", "Orcish Ruler"},
},
{
{"Dwarvish Guardsman", "Dwarvish Stalwart", "none", "none"},
{"Bowman", "Longbowman", "more", "Master Bowman"},
{"Troll Whelp", "Troll", "Troll Warrior", "none"},
},
{
{"Orcish Assassin", "Orcish Slayer", "more", "none"},
{"Cavalryman", "Dragoon", "more", "Cavalier"},
{"Saurian Augur", "Saurian Soothsayer", "none", "none"},
},
{
{"Wolf Rider", "Goblin Pillager", "more", "none"},
{"Ghost", "Shadow", "more", "more"},
{"Sergeant", "Lieutenant", "General", "Grand Marshal"},
},
{
{"Gryphon Rider", "none", "more", "none"},
{"Thief", "Rogue", "more", "Assassin"},
},
{
{"Dwarvish Fighter", "Dwarvish Steelclad", "more", "Dwarvish Lord"},
{"Poacher", "Trapper", "more", "none"},
{"Cuttle Fish", "more", "more", "none"},
},
{
{"Walking Corpse", "more", "more", "more"},
{"Mage", "White Mage", "Mage of Light", "none"},
{"Thug", "Bandit", "more", "none"},
},
}
local function get_spawn_types(num_units, max_gold, unit_pool)
local gold_left = max_gold
local units_left = num_units
local current_types = {}
while gold_left > 0 and units_left > 0 do
local unit_group = wesnoth.random(#unit_pool)
local unit_rank = 1
local unit_type = wesnoth.unit_types[unit_pool[unit_group][unit_rank]]
table.insert(current_types, { group = unit_group, type = unit_type})
gold_left = gold_left - unit_type.cost
units_left = units_left - 1
end
-- Upgrade units, eigher by replacing them with better units or by duplicating them.
for next_rank = 2,4 do
local next_types = {}
for i,v in ipairs(current_types) do
local advanceto = unit_pool[v.group][next_rank] or ""
local unit_type = wesnoth.unit_types[advanceto]
if unit_type then
local upgrade_cost = math.ceil((unit_type.cost - v.type.cost) * 1.25)
if gold_left >= upgrade_cost then
gold_left = gold_left - upgrade_cost
table.insert(next_types, { group = v.group, type = unit_type})
else
table.insert(next_types, { group = v.group, type = v.type})
end
elseif advanceto == "more" then
local upgrade_cost = v.type.cost + 2
if gold_left >= upgrade_cost then
gold_left = gold_left - upgrade_cost
table.insert(next_types, { group = v.group, type = v.type})
end
table.insert(next_types, { group = v.group, type = v.type})
else
table.insert(next_types, { group = v.group, type = v.type})
end
end
current_types = next_types
end
--spend remaining gold
local min_cost = 100
for i,v in ipairs(unit_pool) do
min_cost = math.min(min_cost, wesnoth.unit_types[v[1]].cost)
end
while gold_left >= min_cost do
local possible_groups = {}
for i,v in ipairs(unit_pool) do
local unit_type = wesnoth.unit_types[v[1]]
if unit_type.cost <= gold_left then
table.insert(possible_groups, { group = i, type = unit_type})
end
end
local index = wesnoth.random(#possible_groups)
table.insert(current_types, possible_groups[index])
gold_left = gold_left - possible_groups[index].type.cost
end
local res = {}
for i,v in ipairs(current_types) do
table.insert(res, v.type.id)
end
return res
end
-- creates the 'timed_spawn' wml array.
-- @a num_spawns: the total number of times units get spawned
-- @a interval: the number of turns between 2 spawns
-- @a base_gold_amount, gold_increment: used to cauculate the amount of gold available for each timed spawn
-- @a units_amount, gold_per_unit_amount: used to cauculate the number of units spawned in each timed spawn
local function create_timed_spaws(interval, num_spawns, base_gold_amount, gold_increment, units_amount, gold_per_unit_amount)
local configure_gold_factor = ((wesnoth.get_variable("enemey_gold_factor") or 0) + 100)/100
local random_spawn_numbers = {}
for i = 1, #random_spawns do
table.insert(random_spawn_numbers, i)
end
helper.shuffle(random_spawn_numbers)
local final_turn = math.ceil(((num_spawns - 1) * interval + 40 + wesnoth.random(2,4))/2)
local end_spawns = 0
for spawn_number = 1, num_spawns do
local turn = 3 + (spawn_number - 1) * interval
local gold = base_gold_amount + (turn - 3) * gold_increment
if spawn_number > 1 then
-- foruma taken from original Dark forecast, TODO: find easier formula.
local unit_gold = (turn - 3) * gold_increment + math.min(wesnoth.random(base_gold_amount), wesnoth.random(base_gold_amount))
local gold_per_unit = gold_per_unit_amount + turn / 1.5
local units = unit_gold / gold_per_unit + units_amount + wesnoth.random(-1, 2)
if wesnoth.random(5) == 5 then
units = units - 1
end
-- end complicated formula
turn = turn + wesnoth.random(-1, 1)
-- reduce gold and units for spawns after the final spawn
if turn >= final_turn then
units = units / (end_spawns + 3)
gold = gold / (end_spawns + 4)
end_spawns = end_spawns + 1
-- we only want two spawns after the final turn.
if end_spawns > 2 then
break
end
end
wesnoth.set_variable(string.format("timed_spawn[%d]", spawn_number - 1), {
units = math.ceil(units),
turn = turn,
gold = helper.round(gold * configure_gold_factor),
pool_num = random_spawn_numbers[spawn_number],
})
else
wesnoth.set_variable(string.format("timed_spawn[%d]", spawn_number - 1), {
units = units_amount + 1,
turn = turn,
gold = gold,
pool_num = random_spawn_numbers[spawn_number],
})
end
end
wesnoth.set_variable("final_turn", final_turn)
end
-- @a unittypes: a array of strings
-- @a x,y: the location where to spawn the units on the map.
local function place_units(unittypes, x, y)
for i,v in ipairs(unittypes) do
local u = wesnoth.create_unit { type = v, generate_name = true, side = 2 }
u:add_modification("object", {
T.effect {
apply_to = "movement_costs",
replace = true,
T.movement_costs {
flat = 1,
sand = 2,
forest = 2,
impassable = 3,
unwalkable = 3,
deep_water = 3,
}
}
})
-- give the unit less moves on its first turn.
u.status.slowed = true
u:add_modification("object", {
duration = "turn end",
T.effect {
apply_to = "movement",
increase = "-50%",
}
})
local dst_x, dst_y = wesnoth.find_vacant_tile(x, y, u)
u:to_map(dst_x, dst_y)
end
end
local function final_spawn()
local spawns_left = wesnoth.get_variable("fixed_spawn.length")
if spawns_left == 0 then
return
end
local spawn_index = wesnoth.random(spawns_left) - 1
local spawn = wesnoth.get_variable(string.format("fixed_spawn[%d]", spawn_index))
wesnoth.set_variable(string.format("fixed_spawn[%d]", spawn_index))
local types = {}
for tag in helper.child_range(spawn, "type") do
table.insert(types, tag.type)
end
place_units(types, spawn.x, spawn.y)
end
-- convert all 'veteran' units from side 2 to the more agressive side 1
-- this must happen before the new units are created from spawns.
on_event("new turn", function()
for i, unit in ipairs(wesnoth.get_units { side = 2 }) do
unit.side = 1
end
end)
on_event("prestart", function()
local leaders = wesnoth.get_units { side = "3,4", canrecruit= true}
if #leaders < 2 then
create_timed_spaws(5, 11, 50, 5, 4, 21)
else
create_timed_spaws(4, 11, 90, 4, 5, 23)
end
end)
-- the regular spawns:
-- when they appear is defined in the 'timed_spawn' wml array. which is created at prestart
-- which unit types get spawned is defined in the 'main_spawn' wml array which is also spawned at prestart
on_event("new turn", function()
local next_spawn = wesnoth.get_variable("timed_spawn[0]")
if wesnoth.current.turn ~= next_spawn.turn then
return
end
wesnoth.set_variable("timed_spawn[0]")
local unit_types = get_spawn_types(next_spawn.units, next_spawn.gold, random_spawns[next_spawn.pool_num])
local spawn_areas = {{"3-14", "15"}, {"1", "4-13"}, {"2-13", "1"}, {"1", "2-15"}}
local spawn_area = spawn_areas[wesnoth.random(#spawn_areas)]
local locations_in_area = wesnoth.get_locations { x = spawn_area[1], y = spawn_area[2], radius=1, include_borders=false }
local chosen_location = locations_in_area[wesnoth.random(#locations_in_area)]
place_units(unit_types, chosen_location[1], chosen_location[2])
end)
-- on turn 'final_turn' the first 'final spawn' appears
on_event("new turn", function()
if wesnoth.current.turn ~= wesnoth.get_variable("final_turn") then
return
end
wesnoth.wml_actions.music {
name = "battle.ogg",
ms_before = 200,
immediate = true,
append = true,
}
final_spawn()
wesnoth.game_config.last_turn = wesnoth.current.turn + 12
wesnoth.wml_actions.message {
side="3,4",
canrecruit=true,
message= _ "The last and most powerful of these creatures are almost upon us. I feel that if we can finish them off in time, we shall be victorious.",
}
end)
-- after the first final spawn, spawn a new final spawn every 1 or 2 turns.
on_event("new turn", function()
if wesnoth.current.turn ~= wesnoth.get_variable("next_final_spawn") then
return
end
final_spawn()
wesnoth.set_variable("next_final_spawn", wesnoth.current.turn + wesnoth.random(1,2))
end)
-- The victory condition: win when there are no enemy unit after the first final spawn appeared.
on_event("die", function()
if wesnoth.current.turn < wesnoth.get_variable("final_turn") then
return
end
if wesnoth.wml_conditionals.have_unit { side = "1,2"} then
return
end
wesnoth.wml_actions.music {
name = "victory.ogg",
play_once = true,
immediate = true,
}
wesnoth.wml_actions.message {
speaker = "narrator",
message = _"The screams and pleas for mercy are finally silenced, as you remove your blood soaked blade from the last of the rebels. There will be no more resistance from the local scum. Your reign has finally earned stability.",
image ="wesnoth-icon.png",
}
wesnoth.wml_actions.endlevel {
result = "victory",
}
end)
-- initilize the 'fixed_spawn' and 'main_spawn'
on_event("prestart", function()
local fixed_spawn = function(x, y, ...)
local res = { x = x, y = y }
for i,v in ipairs {...} do
table.insert(res, T.type { type = v })
end
return res
end
helper.set_variable_array("fixed_spawn", {
fixed_spawn(1, 15, "Fire Dragon", "Gryphon Master", "Hurricane Drake"),
fixed_spawn(5, 1, "Yeti", "Elvish Druid", "Elvish Druid"),
fixed_spawn(1, 7, "Lich", "Walking Corpse", "Walking Corpse", "Walking Corpse", "Ghoul", "Soulless", "Walking Corpse", "Walking Corpse", "Walking Corpse"),
fixed_spawn(11, 15, "Elvish Champion", "Dwarvish Stalwart", "Dwarvish Stalwart", "Orcish Slayer"),
})
end)
-------------------------------------------------------------------------------
-------------------------- Weather events -------------------------------------
-------------------------------------------------------------------------------
-- The weather evens are complateleey unrelated to the spawn events.
local function get_weather_duration(max_duration)
local res = wesnoth.random(2)
while res < max_duration and wesnoth.random(2) == 2 do
res = res + 1
end
return res
end
-- initilize the weather_event wml array which defines at which turns the weather changes.
on_event("prestart", function()
local turn = wesnoth.random(4,6)
local event_num = 0
local weather_to_dispense = {
{ turns_left = 10, id = "drought"},
{ turns_left = 12, id = "heavy rain"},
{ turns_left = 9, id = "snowfall"},
}
local clear_turns_left = 22
local heavy_snowfall_turns_left = 6
while turn < 55 and #weather_to_dispense > 0 do
-- pick a random weather except 'clear' and 'heavy snow'
local index = wesnoth.random(#weather_to_dispense)
local num_turns = get_weather_duration(weather_to_dispense[index].turns_left)
local weather_id = weather_to_dispense[index].id
weather_to_dispense[index].turns_left = weather_to_dispense[index].turns_left - num_turns
if weather_to_dispense[index].turns_left <= 0 then
table.remove(weather_to_dispense, index)
end
wesnoth.set_variable(string.format("weather_event[%d]", event_num), {
turn = turn,
weather_id = weather_id,
})
event_num = event_num + 1
turn = turn + num_turns
-- Second snow happens half the time.
if weather_id == "snowfall" and heavy_snowfall_turns_left >= 0 and wesnoth.random(2) == 2 then
num_turns = get_weather_duration(heavy_snowfall_turns_left)
wesnoth.set_variable(string.format("weather_event[%d]", event_num), {
turn = turn,
weather_id = "heavy snowfall",
})
event_num = event_num + 1
turn = turn + num_turns
heavy_snowfall_turns_left = heavy_snowfall_turns_left - num_turns
end
-- Go back to clear weather.
num_turns = get_weather_duration(clear_turns_left)
wesnoth.set_variable(string.format("weather_event[%d]", event_num), {
turn = turn,
weather_id = "clear",
})
event_num = event_num + 1
turn = turn + num_turns
clear_turns_left = clear_turns_left - num_turns
end
end)
local function weather_alert(text, red, green, blue)
wesnoth.wml_actions.print {
text = text,
duration = 120,
size = 26,
red = red,
green = green,
blue = blue,
}
end
local function weather_map(name)
wesnoth.wml_actions.terrain_mask {
mask = wesnoth.read_file(name),
x = 1,
y = 1,
border = true,
}
wesnoth.redraw {}
end
-- change weather at side 3 turns, TODO: consider the case that side 3 is empty.
on_event("side 3 turn", function()
-- get next weather event
local weather_event = wesnoth.get_variable("weather_event[0]")
if wesnoth.current.turn ~= weather_event.turn then
return
end
-- remove the to-be-consumed weather event from the todo list.
wesnoth.set_variable("weather_event[0]")
if weather_event.weather_id == "clear" then
weather_map("multiplayer/maps/Dark_Forecast_basic.map")
wesnoth.wml_actions.sound {
name = "magic-holy-miss-2.ogg",
}
weather_alert(_"Clear Weather", 221, 253, 171)
elseif weather_event.weather_id == "drought" then
weather_map ("multiplayer/maps/Dark_Forecast_drought.map")
wesnoth.wml_actions.sound {
name = "gryphon-shriek-1.ogg",
}
weather_alert(_"Drought", 251, 231, 171)
elseif weather_event.weather_id == "heavy rain" then
weather_map("multiplayer/maps/Dark_Forecast_rain.map")
wesnoth.wml_actions.sound {
name = "magic-faeriefire-miss.ogg",
}
wesnoth.wml_actions.delay {
time = 250,
}
wesnoth.wml_actions.sound {
name = "ambient/ship.ogg",
}
weather_alert(_"Heavy Rains", 174, 220, 255)
elseif weather_event.weather_id == "snowfall" then
weather_map("multiplayer/maps/Dark_Forecast_firstsnow.map")
wesnoth.wml_actions.sound {
name = "wail.wav",
}
weather_alert(_"Snowfall", 229, 243, 241)
elseif weather_event.weather_id == "heavy snowfall" then
weather_map("multiplayer/maps/Dark_Forecast_secondsnow.map")
wesnoth.wml_actions.sound {
name = "bat-flapping.wav",
}
weather_alert(_"Heavy Snowfall", 224, 255, 251)
else
error("unknown weather '" .. tostring(weather_event.weather_id) .. "'")
end
end)
| gpl-2.0 |
thedraked/darkstar | scripts/zones/Buburimu_Peninsula/Zone.lua | 4 | 4569 | -----------------------------------
--
-- Zone: Buburimu_Peninsula (118)
--
-----------------------------------
package.loaded[ "scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/zones/Buburimu_Peninsula/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/zone");
require("scripts/globals/conquest");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 847, 45, DIGREQ_NONE },
{ 887, 1, DIGREQ_NONE },
{ 893, 53, DIGREQ_NONE },
{ 17395, 98, DIGREQ_NONE },
{ 738, 3, DIGREQ_NONE },
{ 888, 195, DIGREQ_NONE },
{ 4484, 47, DIGREQ_NONE },
{ 17397, 66, DIGREQ_NONE },
{ 641, 134, DIGREQ_NONE },
{ 885, 12, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 845, 125, DIGREQ_BURROW },
{ 843, 1, DIGREQ_BURROW },
{ 844, 64, DIGREQ_BURROW },
{ 1845, 34, DIGREQ_BURROW },
{ 838, 7, DIGREQ_BURROW },
{ 880, 34, DIGREQ_BORE },
{ 902, 5, DIGREQ_BORE },
{ 886, 3, DIGREQ_BORE },
{ 867, 3, DIGREQ_BORE },
{ 864, 21, DIGREQ_BORE },
{ 1587, 19, DIGREQ_BORE },
{ 1586, 9, DIGREQ_BORE },
{ 866, 2, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17261199,17261200};
SetFieldManual(manuals);
local vwnpc = {17261213,17261214,17261215};
SetVoidwatchNPC(vwnpc);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( -276.529, 16.403, -324.519, 14);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0003;
elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 0x0005; -- zone 4 buburimu no update (north)
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0003) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 0x0005) then
if (player:getPreviousZone() == 213 or player:getPreviousZone() == 249) then
player:updateEvent(0,0,0,0,0,7);
elseif (player:getPreviousZone() == 198) then
player:updateEvent(0,0,0,0,0,6);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0003) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end; | gpl-3.0 |
pexcn/openwrt | extra-master/packages/xunlei/files/usr/lib/lua/luci/model/cbi/xunlei.lua | 11 | 9499 | local fs = require "nixio.fs"
local util = require "nixio.util"
local running=(luci.sys.call("pidof EmbedThunderManager > /dev/null") == 0)
local button=""
local xunleiinfo=""
local tblXLInfo={}
local detailInfo = "<br />启动后会看到类似如下信息:<br /><br />[ 0, 1, 1, 0, “7DHS94”,1, “201_2.1.3.121”, “shdixang”, 1 ]<br /><br />其中有用的几项为:<br /><br />第一项: 0表示返回结果成功;<br /><br />第二项: 1表示检测网络正常,0表示检测网络异常;<br /><br />第四项: 1表示已绑定成功,0表示未绑定;<br /><br />第五项: 未绑定的情况下,为绑定的需要的激活码;<br /><br />第六项: 1表示磁盘挂载检测成功,0表示磁盘挂载检测失败。"
if running then
xunleiinfo = luci.sys.exec("wget http://localhost:9000/getsysinfo -O - 2>/dev/null")
--upinfo = luci.sys.exec("wget -qO- http://dl.lazyzhu.com/file/Thunder/Xware/latest 2>/dev/null")
button = " " .. translate("运行状态:") .. xunleiinfo
m = Map("xunlei", translate("Xware"), translate("迅雷远程下载 正在运行...") .. button)
string.gsub(string.sub(xunleiinfo, 2, -2),'[^,]+',function(w) table.insert(tblXLInfo, w) end)
detailInfo = [[<p>启动信息:]] .. xunleiinfo .. [[</p>]]
if tonumber(tblXLInfo[1]) == 0 then
detailInfo = detailInfo .. [[<p>状态正常</p>]]
else
detailInfo = detailInfo .. [[<p style="color:red">执行异常</p>]]
end
if tonumber(tblXLInfo[2]) == 0 then
detailInfo = detailInfo .. [[<p style="color:red">网络异常</p>]]
else
detailInfo = detailInfo .. [[<p>网络正常</p>]]
end
if tonumber(tblXLInfo[4]) == 0 then
detailInfo = detailInfo .. [[<p>未绑定]].. [[ 激活码:]].. tblXLInfo[5] ..[[</p>]]
else
detailInfo = detailInfo .. [[<p>已绑定</p>]]
end
if tonumber(tblXLInfo[6]) == 0 then
detailInfo = detailInfo .. [[<p style="color:red">磁盘挂载检测失败</p>]]
else
detailInfo = detailInfo .. [[<p>磁盘挂载检测成功</p>]]
end
else
m = Map("xunlei", translate("Xware"), translate("[迅雷远程下载 尚未启动]"))
end
-----------
--Xware--
-----------
s = m:section(TypedSection, "xunlei", translate("Xware 设置"))
s.anonymous = true
s:tab("basic", translate("Settings"))
enable = s:taboption("basic", Flag, "enable", translate("启用 迅雷远程下载"))
enable.rmempty = false
local devices = {}
util.consume((fs.glob("/mnt/sd??*")), devices)
device = s:taboption("basic", Value, "device", translate("挂载点"), translate("<br />迅雷程序下载目录所在的“挂载点”。"))
for i, dev in ipairs(devices) do
device:value(dev)
end
if nixio.fs.access("/etc/config/xunlei") then
device.titleref = luci.dispatcher.build_url("admin", "system", "fstab")
end
file = s:taboption("basic", Value, "file", translate("迅雷程序安装路径"), translate("<br />迅雷程序安装路径,例如:/mnt/sda1,将会安装在/mnt/sda1/xunlei 下。"))
for i, dev in ipairs(devices) do
file:value(dev)
end
upinfo = luci.sys.exec("cat /tmp/etc/xlver")
op = s:taboption("basic", Button, "upxlast", translate("查看更新."),translate("<strong><font color=\"red\">当前最新版:</font></strong>") .. upinfo)
op.inputstyle = "apply"
op.write = function(self, section)
opstatus = (luci.sys.exec("/etc/xware/xlatest" %{ self.option }) == 0)
if opstatus then
self.inputstyle = "apply"
end
luci.model.uci.cursor()
end
up = s:taboption("basic", Flag, "up", translate("升级迅雷远程下载"), translate("<script type=\"text/javascript\"></script><input type=\"button\" class=\"cbi-button cbi-button-apply\" value=\"查看更新.\" onclick=\"window.open('http://dl.lazyzhu.com/file/Thunder/Xware/latest')\" />"))
up.rmempty = false
zurl = s:taboption("basic", Value, "url", translate("地址"), translate("自定义迅雷远程下载地址。默认:http://dl.lazyzhu.com/file/Thunder/Xware"))
zurl.rmempty = false
zurl:value("http://dl.lazyzhu.com/file/Thunder/Xware")
zversion = s:taboption("basic", Flag, "zversion", translate("自定义版本"), translate("自定义迅雷远程下载版本。"))
zversion.rmempty = false
zversion:depends("up",1)
ver = s:taboption("basic", Value, "ver", translate("版本号"), translate("自定义迅雷远程下载版本号。"))
ver:depends("zversion",1)
ver:value("1.0.11")
ver:value("1.0.27")
ver:value("1.0.28")
ver:value("1.0.29")
ver:value("1.0.30")
vod = s:taboption("basic", Flag, "vod", translate("删除迅雷VOD服务器"), translate("删除迅雷VOD服务器。"))
vod.rmempty = false
xwareup = s:taboption("basic", Value, "xware", translate("Xware 程序版本:"),translate("<br />ar71xx系列的选择默认版本,其他型号的路由根据CPU选择。"))
xwareup.rmempty = false
xwareup:value("Xware_mipseb_32_uclibc.tar.gz", translate("Xware_mipseb_32_uclibc.tar.gz"))
xwareup:value("Xware_mipsel_32_uclibc.tar.gz", translate("Xware_mipsel_32_uclibc.tar.gz"))
xwareup:value("Xware_x86_32_glibc.tar.gz", translate("Xware_x86_32_glibc.tar.gz"))
xwareup:value("Xware_x86_32_uclibc.tar.gz", translate("Xware_x86_32_uclibc.tar.gz"))
xwareup:value("Xware_pogoplug.tar.gz", translate("Xware_pogoplug.tar.gz"))
xwareup:value("Xware_armeb_v6j_uclibc.tar.gz", translate("Xware_armeb_v6j_uclibc.tar.gz"))
xwareup:value("Xware_armeb_v7a_uclibc.tar.gz", translate("Xware_armeb_v7a_uclibc.tar.gz"))
xwareup:value("Xware_armel_v5t_uclibc.tar.gz", translate("Xware_armel_v5t_uclibc.tar.gz"))
xwareup:value("Xware_armel_v5te_android.tar.gz", translate("Xware_armel_v5te_android.tar.gz"))
xwareup:value("Xware_armel_v5te_glibc.tar.gz", translate("Xware_armel_v5te_glibc.tar.gz"))
xwareup:value("Xware_armel_v6j_uclibc.tar.gz", translate("Xware_armel_v6j_uclibc.tar.gz"))
xwareup:value("Xware_armel_v7a_uclibc.tar.gz", translate("Xware_armel_v7a_uclibc.tar.gz"))
xwareup:value("Xware_asus_rt_ac56u.tar.gz", translate("Xware_asus_rt_ac56u.tar.gz"))
xwareup:value("Xware_cubieboard.tar.gz", translate("Xware_cubieboard.tar.gz"))
xwareup:value("Xware_iomega_cloud.tar.gz", translate("Xware_iomega_cloud.tar.gz"))
xwareup:value("Xware_my_book_live.tar.gz", translate("Xware_my_book_live.tar.gz"))
xwareup:value("Xware_netgear_6300v2.tar.gz", translate("Xware_netgear_6300v2.tar.gz"))
s:taboption("basic", DummyValue,"opennewwindow" ,translate("<br /><p align=\"justify\"><script type=\"text/javascript\"></script><input type=\"button\" class=\"cbi-button cbi-button-apply\" value=\"获取启动信息\" onclick=\"window.open('http://'+window.location.host+':9000/getsysinfo')\" /></p>"), detailInfo)
s:taboption("basic", DummyValue,"opennewwindow" ,translate("<br /><p align=\"justify\"><script type=\"text/javascript\"></script><input type=\"button\" class=\"cbi-button cbi-button-apply\" value=\"迅雷远程下载页面\" onclick=\"window.open('http://yuancheng.xunlei.com')\" /></p>"), translate("将激活码填进网页即可绑定。"))
s:taboption("basic", DummyValue,"opennewwindow" ,translate("<br /><p align=\"justify\"><script type=\"text/javascript\"></script><input type=\"button\" class=\"cbi-button cbi-button-apply\" value=\"迅雷论坛\" onclick=\"window.open('http://luyou.xunlei.com/forum-51-1.html')\" /></p>"))
s:tab("editconf_mounts", translate("挂载点配置"))
editconf_mounts = s:taboption("editconf_mounts", Value, "_editconf_mounts",
translate("挂载点配置(一般情况下只需填写你的挂载点目录即可)"),
translate("Comment Using #"))
editconf_mounts.template = "cbi/tvalue"
editconf_mounts.rows = 20
editconf_mounts.wrap = "off"
function editconf_mounts.cfgvalue(self, section)
return fs.readfile("/tmp/etc/thunder_mounts.cfg") or ""
end
function editconf_mounts.write(self, section, value1)
if value1 then
value1 = value1:gsub("\r\n?", "\n")
fs.writefile("/tmp/thunder_mounts.cfg", value1)
if (luci.sys.call("cmp -s /tmp/thunder_mounts.cfg /tmp/etc/thunder_mounts.cfg") == 1) then
fs.writefile("/tmp/etc/thunder_mounts.cfg", value1)
end
fs.remove("/tmp/thunder_mounts.cfg")
end
end
s:tab("editconf_etm", translate("Xware 配置"))
editconf_etm = s:taboption("editconf_etm", Value, "_editconf_etm",
translate("Xware 配置:"),
translate("注释用“ ; ”"))
editconf_etm.template = "cbi/tvalue"
editconf_etm.rows = 20
editconf_etm.wrap = "off"
function editconf_etm.cfgvalue(self, section)
return fs.readfile("/tmp/etc/etm.cfg") or ""
end
function editconf_etm.write(self, section, value2)
if value2 then
value2 = value2:gsub("\r\n?", "\n")
fs.writefile("/tmp/etm.cfg", value2)
if (luci.sys.call("cmp -s /tmp/etm.cfg /tmp/etc/etm.cfg") == 1) then
fs.writefile("/tmp/etc/etm.cfg", value2)
end
fs.remove("/tmp/etm.cfg")
end
end
s:tab("editconf_download", translate("下载配置"))
editconf_download = s:taboption("editconf_download", Value, "_editconf_download",
translate("下载配置"),
translate("注释用“ ; ”"))
editconf_download.template = "cbi/tvalue"
editconf_download.rows = 20
editconf_download.wrap = "off"
function editconf_download.cfgvalue(self, section)
return fs.readfile("/tmp/etc/download.cfg") or ""
end
function editconf_download.write(self, section, value3)
if value3 then
value3 = value3:gsub("\r\n?", "\n")
fs.writefile("/tmp/download.cfg", value3)
if (luci.sys.call("cmp -s /tmp/download.cfg /tmp/etc/download.cfg") == 1) then
fs.writefile("/tmp/etc/download.cfg", value3)
end
fs.remove("/tmp/download.cfg")
end
end
return m
| gpl-2.0 |
ukoloff/rufus-lua-win | vendor/lua/lib/lua/oil/corba/services/event/ProxyPushConsumer.lua | 7 | 3053 | local oil = require "oil"
local oo = require "oil.oo"
local assert = require "oil.assert"
module("oil.corba.services.event.ProxyPushConsumer", oo.class)
-- Proxies are in one of three states: disconnected, connected, or destroyed.
-- Push/pull operations are only valid in the connected state.
function __init(class, admin)
assert.results(admin)
return oo.rawnew(class, {
admin = admin,
connected = false,
push_supplier = nil
})
end
-- A supplier communicates event data to the consumer by invoking the push
-- operation and passing the event data as a parameter.
function push(self, data)
if not self.connected then
assert.exception{"IDL:omg.org/CosEventComm/Disconnected:1.0"}
end
local channel = self.admin.channel
local event = channel.event_factory:create(data)
channel.event_queue:enqueue(event)
end
-- A nil object reference may be passed to the connect_push_supplier operation.
-- If so a channel cannot invoke the disconnect_push_supplier operation on the
-- supplier. The supplier may be disconnected from the channel without being
-- informed. If a nonnil reference is passed to connect_push_supplier, the
-- implementation calls disconnect_push_supplier via that reference when the
-- ProxyPushConsumer is destroyed.
--
-- If the ProxyPushConsumer is already connected to a PushSupplier, then the
-- AlreadyConnected exception is raised.
function connect_push_supplier(self, push_supplier)
if self.connected then
assert.exception{"IDL:omg.org/CosEventChannelAdmin/AlreadyConnected:1.0"}
end
self.push_supplier = push_supplier
self.admin:add_push_supplier(self, push_supplier)
self.connected = true
end
-- The disconnect_push_consumer operation terminates the event communication.
-- It releases resources used at the consumer to support the event
-- communication. The PushConsumer object reference is disposed. Calling
-- disconnect_push_consumer causes the implementation to call the
-- disconnect_push_supplier operation on the corresponding PushSupplier
-- interface (if that interface is known).
--
-- Calling a disconnect operation on a consumer or supplier interface may cause
-- a call to the corresponding disconnect operation on the connected supplier
-- or consumer. Implementations must take care to avoid infinite recursive
-- calls to these disconnect operations. If a consumer or supplier has received
-- a disconnect call and subsequently receives another disconnect call, it shall
-- raise a CORBA::OBJECT_NOT_EXIST exception.
function disconnect_push_consumer(self)
if not self.connected then
assert.exception{"IDL:omg.org/CORBA/OBJECT_NOT_EXIST:1.0"}
end
self.connected = false
if self.push_supplier then -- supplier may be nil
self.admin:rem_push_supplier(self, push_supplier)
oil.pcall(self.push_supplier.disconnect_push_supplier, self.push_supplier)
self.push_supplier = nil
end
end
| mit |
thedraked/darkstar | scripts/zones/The_Shrouded_Maw/mobs/Diabolos.lua | 23 | 9084 | -----------------------------------
-- Area: The Shrouded Maw
-- MOB: Diabolos
-----------------------------------
-- TODO: CoP Diabolos
-- 1) Make the diremites in the pit all aggro said player that falls into region. Should have a respawn time of 10 seconds.
-- 2) Diremites also shouldnt follow you back to the fight area if you make it there. Should despawn and respawn instantly if all players
-- make it back to the Diabolos floor area.
-- 3) ANIMATION Packet ids for instance 2 and 3 are wrong (needs guesswork). Sounds working.
-- TODO: Diabolos Prime
-- Note: Diabolos Prime fight drops all tiles at once.
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local DiabolosID = 16818177;
local DiabolosHPP = ((mob:getHP()/mob:getMaxHP())*100);
if (mob:getID() == DiabolosID) then
local TileOffset = 16818258;
if (DiabolosHPP < 10 and GetNPCByID(TileOffset):getAnimation() == 9) then
GetNPCByID(TileOffset):setAnimation(8); -- Floor opens
SendEntityVisualPacket(TileOffset, "byc1"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 20 and GetNPCByID(TileOffset+1):getAnimation() == 9) then
GetNPCByID(TileOffset+1):setAnimation(8);
SendEntityVisualPacket(TileOffset+1, "byc2"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+1, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 30 and GetNPCByID(TileOffset+2):getAnimation() == 9) then
GetNPCByID(TileOffset+2):setAnimation(8);
SendEntityVisualPacket(TileOffset+2, "byc3"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+2, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 40 and GetNPCByID(TileOffset+3):getAnimation() == 9) then
GetNPCByID(TileOffset+3):setAnimation(8);
SendEntityVisualPacket(TileOffset+3, "byc4"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+3, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 50 and GetNPCByID(TileOffset+4):getAnimation() == 9) then
GetNPCByID(TileOffset+4):setAnimation(8);
SendEntityVisualPacket(TileOffset+4, "byc5"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+4, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 65 and GetNPCByID(TileOffset+5):getAnimation() == 9) then
GetNPCByID(TileOffset+5):setAnimation(8);
SendEntityVisualPacket(TileOffset+5, "byc6"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+5, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 75 and GetNPCByID(TileOffset+6):getAnimation() == 9) then
GetNPCByID(TileOffset+6):setAnimation(8);
SendEntityVisualPacket(TileOffset+6, "byc7"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+6, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 90 and GetNPCByID(TileOffset+7):getAnimation() == 9) then
GetNPCByID(TileOffset+7):setAnimation(8);
SendEntityVisualPacket(TileOffset+7, "byc8"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+7, "s123"); -- Tile dropping sound
end
elseif (mob:getID() == DiabolosID+7) then
local TileOffset = 16818266;
if (DiabolosHPP < 10 and GetNPCByID(TileOffset):getAnimation() == 9) then
GetNPCByID(TileOffset):setAnimation(8);
SendEntityVisualPacket(TileOffset, "bya1"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 20 and GetNPCByID(TileOffset+1):getAnimation() == 9) then
GetNPCByID(TileOffset+1):setAnimation(8);
SendEntityVisualPacket(TileOffset+1, "bya2"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+1, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 30 and GetNPCByID(TileOffset+2):getAnimation() == 9) then
GetNPCByID(TileOffset+2):setAnimation(8);
SendEntityVisualPacket(TileOffset+2, "bya3"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+2, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 40 and GetNPCByID(TileOffset+3):getAnimation() == 9) then
GetNPCByID(TileOffset+3):setAnimation(8);
SendEntityVisualPacket(TileOffset+3, "bya4"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+3, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 50 and GetNPCByID(TileOffset+4):getAnimation() == 9) then
GetNPCByID(TileOffset+4):setAnimation(8);
SendEntityVisualPacket(TileOffset+4, "bya5"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+4, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 65 and GetNPCByID(TileOffset+5):getAnimation() == 9) then
GetNPCByID(TileOffset+5):setAnimation(8);
SendEntityVisualPacket(TileOffset+5, "bya6"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+5, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 75 and GetNPCByID(TileOffset+6):getAnimation() == 9) then
GetNPCByID(TileOffset+6):setAnimation(8);
SendEntityVisualPacket(TileOffset+6, "bya7"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+6, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 90 and GetNPCByID(TileOffset+7):getAnimation() == 9) then
GetNPCByID(TileOffset+7):setAnimation(8);
SendEntityVisualPacket(TileOffset+7, "bya8"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+7, "s123"); -- Tile dropping sound
end
elseif (mob:getID() == DiabolosID+14) then
local TileOffset = 16818274;
if (DiabolosHPP < 10 and GetNPCByID(TileOffset):getAnimation() == 9) then
GetNPCByID(TileOffset):setAnimation(8);
SendEntityVisualPacket(TileOffset, "byY1"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 20 and GetNPCByID(TileOffset+1):getAnimation() == 9) then
GetNPCByID(TileOffset+1):setAnimation(8);
SendEntityVisualPacket(TileOffset+1, "byY2"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+1, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 30 and GetNPCByID(TileOffset+2):getAnimation() == 9) then
GetNPCByID(TileOffset+2):setAnimation(8);
SendEntityVisualPacket(TileOffset+2, "byY3"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+2, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 40 and GetNPCByID(TileOffset+3):getAnimation() == 9) then
GetNPCByID(TileOffset+3):setAnimation(8);
SendEntityVisualPacket(TileOffset+3, "byY4"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+3, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 50 and GetNPCByID(TileOffset+4):getAnimation() == 9) then
GetNPCByID(TileOffset+4):setAnimation(8);
SendEntityVisualPacket(TileOffset+4, "byY5"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+4, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 65 and GetNPCByID(TileOffset+5):getAnimation() == 9) then
GetNPCByID(TileOffset+5):setAnimation(8);
SendEntityVisualPacket(TileOffset+5, "byY6"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+5, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 75 and GetNPCByID(TileOffset+6):getAnimation() == 9) then
GetNPCByID(TileOffset+6):setAnimation(8);
SendEntityVisualPacket(TileOffset+6, "byY7"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+6, "s123"); -- Tile dropping sound
elseif (DiabolosHPP < 90 and GetNPCByID(TileOffset+7):getAnimation() == 9) then
GetNPCByID(TileOffset+7):setAnimation(8);
SendEntityVisualPacket(TileOffset+7, "byY8"); -- Animation for floor dropping
SendEntityVisualPacket(TileOffset+7, "s123"); -- Tile dropping sound
end
end
end; | gpl-3.0 |
X-Coder/wire | lua/wire/client/wire_expression2_editor.lua | 3 | 58934 | local Editor = {}
-- ----------------------------------------------------------------------
-- Fonts
-- ----------------------------------------------------------------------
local defaultFont
if system.IsWindows() then
defaultFont = "Courier New"
elseif system.IsOSX() then
defaultFont = "Monaco"
else
defaultFont = "DejaVu Sans Mono"
end
Editor.FontConVar = CreateClientConVar("wire_expression2_editor_font", defaultFont, true, false)
Editor.FontSizeConVar = CreateClientConVar("wire_expression2_editor_font_size", 16, true, false)
Editor.BlockCommentStyleConVar = CreateClientConVar("wire_expression2_editor_block_comment_style", 1, true, false)
Editor.NewTabOnOpen = CreateClientConVar("wire_expression2_new_tab_on_open", "1", true, false)
Editor.ops_sync_subscribe = CreateClientConVar("wire_expression_ops_sync_subscribe",0,true,false)
Editor.Fonts = {}
-- Font Description
-- Windows
Editor.Fonts["Courier New"] = "Windows standard font"
Editor.Fonts["DejaVu Sans Mono"] = ""
Editor.Fonts["Consolas"] = ""
Editor.Fonts["Fixedsys"] = ""
Editor.Fonts["Lucida Console"] = ""
-- Mac
Editor.Fonts["Monaco"] = "Mac standard font"
surface.CreateFont("DefaultBold", {
font = "defaultbold",
size = 12,
weight = 700,
antialias = true,
additive = false,
})
Editor.CreatedFonts = {}
function Editor:SetEditorFont(editor)
if not self.CurrentFont then
self:ChangeFont(self.FontConVar:GetString(), self.FontSizeConVar:GetInt())
return
end
editor.CurrentFont = self.CurrentFont
editor.FontWidth = self.FontWidth
editor.FontHeight = self.FontHeight
end
function Editor:ChangeFont(FontName, Size)
if not FontName or FontName == "" or not Size then return end
-- If font is not already created, create it.
if not self.CreatedFonts[FontName .. "_" .. Size] then
local fontTable =
{
font = FontName,
size = Size,
weight = 400,
antialias = false,
additive = false,
}
surface.CreateFont("Expression2_" .. FontName .. "_" .. Size, fontTable)
fontTable.weight = 700
surface.CreateFont("Expression2_" .. FontName .. "_" .. Size .. "_Bold", fontTable)
self.CreatedFonts[FontName .. "_" .. Size] = true
end
self.CurrentFont = "Expression2_" .. FontName .. "_" .. Size
surface.SetFont(self.CurrentFont)
self.FontWidth, self.FontHeight = surface.GetTextSize(" ")
for i = 1, self:GetNumTabs() do
self:SetEditorFont(self:GetEditor(i))
end
end
------------------------------------------------------------------------
-- Colors
------------------------------------------------------------------------
local colors = {
-- Table copied from TextEditor, used for saving colors to convars.
["directive"] = Color(240, 240, 160), -- yellow
["number"] = Color(240, 160, 160), -- light red
["function"] = Color(160, 160, 240), -- blue
["notfound"] = Color(240, 96, 96), -- dark red
["variable"] = Color(160, 240, 160), -- light green
["string"] = Color(128, 128, 128), -- grey
["keyword"] = Color(160, 240, 240), -- turquoise
["operator"] = Color(224, 224, 224), -- white
["comment"] = Color(128, 128, 128), -- grey
["ppcommand"] = Color(240, 96, 240), -- purple
["typename"] = Color(240, 160, 96), -- orange
["constant"] = Color(240, 160, 240), -- pink
["userfunction"] = Color(102, 122, 102), -- dark grayish-green
["dblclickhighlight"] = Color(0, 100, 0) -- dark green
}
local colors_defaults = {}
local colors_convars = {}
for k, v in pairs(colors) do
colors_defaults[k] = Color(v.r, v.g, v.b) -- Copy to save defaults
colors_convars[k] = CreateClientConVar("wire_expression2_editor_color_" .. k, v.r .. "_" .. v.g .. "_" .. v.b, true, false)
end
function Editor:LoadSyntaxColors()
for k, v in pairs(colors_convars) do
local r, g, b = v:GetString():match("(%d+)_(%d+)_(%d+)")
local def = colors_defaults[k]
colors[k] = Color(tonumber(r) or def.r, tonumber(g) or def.g, tonumber(b) or def.b)
end
for i = 1, self:GetNumTabs() do
self:GetEditor(i):SetSyntaxColors(colors)
end
end
function Editor:SetSyntaxColor(colorname, colr)
if not colors[colorname] then return end
colors[colorname] = colr
RunConsoleCommand("wire_expression2_editor_color_" .. colorname, colr.r .. "_" .. colr.g .. "_" .. colr.b)
for i = 1, self:GetNumTabs() do
self:GetEditor(i):SetSyntaxColor(colorname, colr)
end
end
------------------------------------------------------------------------
local invalid_filename_chars = {
["*"] = "",
["?"] = "",
[">"] = "",
["<"] = "",
["|"] = "",
["\\"] = "",
['"'] = "",
[" "] = "_",
}
-- overwritten commands
function Editor:Init()
-- don't use any of the default DFrame UI components
for _, v in pairs(self:GetChildren()) do v:Remove() end
self.Title = ""
self.subTitle = ""
self.LastClick = 0
self.GuiClick = 0
self.SimpleGUI = false
self.Location = ""
self.C = {}
self.Components = {}
-- Load border colors, position, & size
self:LoadEditorSettings()
local fontTable = {
font = "default",
size = 11,
weight = 300,
antialias = false,
additive = false,
}
surface.CreateFont("E2SmallFont", fontTable)
self.logo = surface.GetTextureID("vgui/e2logo")
self:InitComponents()
self:LoadSyntaxColors()
-- This turns off the engine drawing
self:SetPaintBackgroundEnabled(false)
self:SetPaintBorderEnabled(false)
self:SetV(false)
self:InitShutdownHook()
end
local size = CreateClientConVar("wire_expression2_editor_size", "800_600", true, false)
local pos = CreateClientConVar("wire_expression2_editor_pos", "-1_-1", true, false)
function Editor:LoadEditorSettings()
-- Position & Size
local w, h = size:GetString():match("(%d+)_(%d+)")
w = tonumber(w)
h = tonumber(h)
self:SetSize(w, h)
local x, y = pos:GetString():match("(%-?%d+)_(%-?%d+)")
x = tonumber(x)
y = tonumber(y)
if x == -1 and y == -1 then
self:Center()
else
self:SetPos(x, y)
end
if x < 0 or y < 0 or x + w > ScrW() or x + h > ScrH() then -- If the editor is outside the screen, reset it
local width, height = math.min(surface.ScreenWidth() - 200, 800), math.min(surface.ScreenHeight() - 200, 620)
self:SetPos((surface.ScreenWidth() - width) / 2, (surface.ScreenHeight() - height) / 2)
self:SetSize(width, height)
self:SaveEditorSettings()
end
end
function Editor:SaveEditorSettings()
-- Position & Size
local w, h = self:GetSize()
RunConsoleCommand("wire_expression2_editor_size", w .. "_" .. h)
local x, y = self:GetPos()
RunConsoleCommand("wire_expression2_editor_pos", x .. "_" .. y)
end
function Editor:PaintOver()
local w, h = self:GetSize()
surface.SetFont("DefaultBold")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(10, 6)
surface.DrawText(self.Title .. self.subTitle)
--[[
if(self.E2) then
surface.SetTexture(self.logo)
surface.SetDrawColor( 255, 255, 255, 128 )
surface.DrawTexturedRect( w-148, h-158, 128, 128)
end
]] --
surface.SetDrawColor(255, 255, 255, 255)
surface.SetTextPos(0, 0)
surface.SetFont("Default")
return true
end
function Editor:PerformLayout()
local w, h = self:GetSize()
for i = 1, #self.Components do
local c = self.Components[i]
local c_x, c_y, c_w, c_h = c.Bounds.x, c.Bounds.y, c.Bounds.w, c.Bounds.h
if (c_x < 0) then c_x = w + c_x end
if (c_y < 0) then c_y = h + c_y end
if (c_w < 0) then c_w = w + c_w - c_x end
if (c_h < 0) then c_h = h + c_h - c_y end
c:SetPos(c_x, c_y)
c:SetSize(c_w, c_h)
end
end
function Editor:OnMousePressed(mousecode)
if mousecode ~= 107 then return end -- do nothing if mouseclick is other than left-click
if not self.pressed then
self.pressed = true
self.p_x, self.p_y = self:GetPos()
self.p_w, self.p_h = self:GetSize()
self.p_mx = gui.MouseX()
self.p_my = gui.MouseY()
self.p_mode = self:getMode()
if self.p_mode == "drag" then
if self.GuiClick > CurTime() - 0.2 then
self:fullscreen()
self.pressed = false
self.GuiClick = 0
else
self.GuiClick = CurTime()
end
end
end
end
function Editor:OnMouseReleased(mousecode)
if mousecode ~= 107 then return end -- do nothing if mouseclick is other than left-click
self.pressed = false
end
function Editor:Think()
if self.fs then return end
if self.pressed then
if not input.IsMouseDown(MOUSE_LEFT) then -- needs this if you let go of the mouse outside the panel
self.pressed = false
end
local movedX = gui.MouseX() - self.p_mx
local movedY = gui.MouseY() - self.p_my
if self.p_mode == "drag" then
local x = self.p_x + movedX
local y = self.p_y + movedY
if (x < 10 and x > -10) then x = 0 end
if (y < 10 and y > -10) then y = 0 end
if (x + self.p_w < surface.ScreenWidth() + 10 and x + self.p_w > surface.ScreenWidth() - 10) then x = surface.ScreenWidth() - self.p_w end
if (y + self.p_h < surface.ScreenHeight() + 10 and y + self.p_h > surface.ScreenHeight() - 10) then y = surface.ScreenHeight() - self.p_h end
self:SetPos(x, y)
end
if self.p_mode == "sizeBR" then
local w = self.p_w + movedX
local h = self.p_h + movedY
if (self.p_x + w < surface.ScreenWidth() + 10 and self.p_x + w > surface.ScreenWidth() - 10) then w = surface.ScreenWidth() - self.p_x end
if (self.p_y + h < surface.ScreenHeight() + 10 and self.p_y + h > surface.ScreenHeight() - 10) then h = surface.ScreenHeight() - self.p_y end
if (w < 300) then w = 300 end
if (h < 200) then h = 200 end
self:SetSize(w, h)
end
if self.p_mode == "sizeR" then
local w = self.p_w + movedX
if (w < 300) then w = 300 end
self:SetWide(w)
end
if self.p_mode == "sizeB" then
local h = self.p_h + movedY
if (h < 200) then h = 200 end
self:SetTall(h)
end
end
if not self.pressed then
local cursor = "arrow"
local mode = self:getMode()
if (mode == "sizeBR") then cursor = "sizenwse"
elseif (mode == "sizeR") then cursor = "sizewe"
elseif (mode == "sizeB") then cursor = "sizens"
end
if cursor ~= self.cursor then
self.cursor = cursor
self:SetCursor(self.cursor)
end
end
local x, y = self:GetPos()
local w, h = self:GetSize()
if w < 518 then w = 518 end
if h < 200 then h = 200 end
if x < 0 then x = 0 end
if y < 0 then y = 0 end
if x + w > surface.ScreenWidth() then x = surface.ScreenWidth() - w end
if y + h > surface.ScreenHeight() then y = surface.ScreenHeight() - h end
if y < 0 then y = 0 end
if x < 0 then x = 0 end
if w > surface.ScreenWidth() then w = surface.ScreenWidth() end
if h > surface.ScreenHeight() then h = surface.ScreenHeight() end
self:SetPos(x, y)
self:SetSize(w, h)
end
-- special functions
function Editor:fullscreen()
if self.fs then
self:SetPos(self.preX, self.preY)
self:SetSize(self.preW, self.preH)
self.fs = false
else
self.preX, self.preY = self:GetPos()
self.preW, self.preH = self:GetSize()
self:SetPos(0, 0)
self:SetSize(surface.ScreenWidth(), surface.ScreenHeight())
self.fs = true
end
end
function Editor:getMode()
local x, y = self:GetPos()
local w, h = self:GetSize()
local ix = gui.MouseX() - x
local iy = gui.MouseY() - y
if (ix < 0 or ix > w or iy < 0 or iy > h) then return end -- if the mouse is outside the box
if (iy < 22) then
return "drag"
end
if (iy > h - 10) then
if (ix > w - 20) then return "sizeBR" end
return "sizeB"
end
if (ix > w - 10) then
if (iy > h - 20) then return "sizeBR" end
return "sizeR"
end
end
function Editor:addComponent(panel, x, y, w, h)
assert(not panel.Bounds)
panel.Bounds = { x = x, y = y, w = w, h = h }
self.Components[#self.Components + 1] = panel
return panel
end
-- TODO: Fix this function
local function extractNameFromCode(str)
return str:match("@name ([^\r\n]+)")
end
local function getPreferredTitles(Line, code)
local title
local tabtext
local str = Line
if str and str ~= "" then
title = str
tabtext = str
end
local str = extractNameFromCode(code)
if str and str ~= "" then
if not title then
title = str
end
tabtext = str
end
return title, tabtext
end
function Editor:GetLastTab() return self.LastTab end
function Editor:SetLastTab(Tab) self.LastTab = Tab end
function Editor:GetActiveTab() return self.C.TabHolder:GetActiveTab() end
function Editor:GetNumTabs() return #self.C.TabHolder.Items end
function Editor:SetActiveTab(val)
if self:GetActiveTab() == val then
val:GetPanel():RequestFocus()
return
end
self:SetLastTab(self:GetActiveTab())
if isnumber(val) then
self.C.TabHolder:SetActiveTab(self.C.TabHolder.Items[val].Tab)
self:GetCurrentEditor():RequestFocus()
elseif val and val:IsValid() then
self.C.TabHolder:SetActiveTab(val)
val:GetPanel():RequestFocus()
end
if self.E2 then self:Validate() end
-- Editor subtitle and tab text
local title, tabtext = getPreferredTitles(self:GetChosenFile(), self:GetCode())
if title then self:SubTitle("Editing: " .. title) else self:SubTitle() end
if tabtext then
if self:GetActiveTab():GetText() ~= tabtext then
self:GetActiveTab():SetText(tabtext)
self.C.TabHolder.tabScroller:InvalidateLayout()
end
end
end
function Editor:GetActiveTabIndex()
local tab = self:GetActiveTab()
for k, v in pairs(self.C.TabHolder.Items) do
if tab == v.Tab then
return k
end
end
return -1
end
function Editor:SetActiveTabIndex(index)
local tab = self.C.TabHolder.Items[index].Tab
if not tab then return end
self:SetActiveTab(tab)
end
local function extractNameFromFilePath(str)
local found = str:reverse():find("/", 1, true)
if found then
return str:Right(found - 1)
else
return str
end
end
function Editor:SetSyntaxColorLine(func)
self.SyntaxColorLine = func
for i = 1, self:GetNumTabs() do
self:GetEditor(i).SyntaxColorLine = func
end
end
function Editor:GetSyntaxColorLine() return self.SyntaxColorLine end
local old
function Editor:FixTabFadeTime()
if old ~= nil then return end -- It's already being fixed
local old = self.C.TabHolder:GetFadeTime()
self.C.TabHolder:SetFadeTime(0)
timer.Simple(old, function() self.C.TabHolder:SetFadeTime(old) old = nil end)
end
function Editor:CreateTab(chosenfile)
local editor = vgui.Create("Expression2Editor")
editor.parentpanel = self
local sheet = self.C.TabHolder:AddSheet(extractNameFromFilePath(chosenfile), editor)
self:SetEditorFont(editor)
editor.chosenfile = chosenfile
sheet.Tab.OnMousePressed = function(pnl, keycode, ...)
if keycode == MOUSE_MIDDLE then
--self:FixTabFadeTime()
self:CloseTab(pnl)
return
elseif keycode == MOUSE_RIGHT then
local menu = DermaMenu()
menu:AddOption("Close", function()
--self:FixTabFadeTime()
self:CloseTab(pnl)
end)
menu:AddOption("Close all others", function()
self:FixTabFadeTime()
self:SetActiveTab(pnl)
for i = self:GetNumTabs(), 1, -1 do
if self.C.TabHolder.Items[i] ~= sheet then
self:CloseTab(i)
end
end
end)
menu:AddSpacer()
menu:AddOption("Save", function()
self:FixTabFadeTime()
local old = self:GetLastTab()
self:SetActiveTab(pnl)
self:SaveFile(self:GetChosenFile(), true)
self:SetActiveTab(self:GetLastTab())
self:SetLastTab(old)
end)
menu:AddOption("Save As", function()
self:FixTabFadeTime()
local old = self:GetLastTab()
self:SetActiveTab(pnl)
self:SaveFile(self:GetChosenFile(), false, true)
self:SetActiveTab(self:GetLastTab())
self:SetLastTab(old)
end)
menu:AddOption("Reload", function()
self:FixTabFadeTime()
local old = self:GetLastTab()
self:SetActiveTab(pnl)
self:LoadFile(editor.chosenfile, false)
self:SetActiveTab(self:GetLastTab())
self:SetLastTab(old)
end)
menu:AddSpacer()
menu:AddOption("Copy file path to clipboard", function()
if editor.chosenfile and editor.chosenfile ~= "" then
SetClipboardText(editor.chosenfile)
end
end)
menu:AddOption("Copy all file paths to clipboard", function()
local str = ""
for i = 1, self:GetNumTabs() do
local chosenfile = self:GetEditor(i).chosenfile
if chosenfile and chosenfile ~= "" then
str = str .. chosenfile .. ";"
end
end
str = str:sub(1, -2)
SetClipboardText(str)
end)
menu:Open()
return
end
self:SetActiveTab(pnl)
end
editor.OnTextChanged = function(panel)
timer.Create("e2autosave", 5, 1, function()
self:AutoSave()
end)
end
editor.OnShortcut = function(_, code)
if code == KEY_S then
self:SaveFile(self:GetChosenFile())
if self.E2 then self:Validate() end
else
local mode = GetConVar("wire_expression2_autocomplete_controlstyle"):GetInt()
local enabled = GetConVar("wire_expression2_autocomplete"):GetBool()
if mode == 1 and enabled then
if code == KEY_B then
self:Validate(true)
elseif code == KEY_SPACE then
local ed = self:GetCurrentEditor()
if (ed.AC_Panel and ed.AC_Panel:IsVisible()) then
ed:AC_Use(ed.AC_Suggestions[1])
end
end
elseif code == KEY_SPACE then
self:Validate(true)
end
end
end
editor:RequestFocus()
local func = self:GetSyntaxColorLine()
if func ~= nil then -- it's a custom syntax highlighter
editor.SyntaxColorLine = func
else -- else it's E2's syntax highlighter
editor:SetSyntaxColors(colors)
end
self:OnTabCreated(sheet) -- Call a function that you can override to do custom stuff to each tab.
return sheet
end
function Editor:OnTabCreated(sheet) end
-- This function is made to be overwritten
function Editor:GetNextAvailableTab()
local activetab = self:GetActiveTab()
for k, v in pairs(self.C.TabHolder.Items) do
if v.Tab and v.Tab:IsValid() and v.Tab ~= activetab then
return v.Tab
end
end
end
function Editor:NewTab()
local sheet = self:CreateTab("generic")
self:SetActiveTab(sheet.Tab)
if self.E2 then
self:NewScript(true)
end
end
function Editor:CloseTab(_tab)
local activetab, sheetindex
if _tab then
if isnumber(_tab) then
local temp = self.C.TabHolder.Items[_tab]
if temp then
activetab = temp.Tab
sheetindex = _tab
else
return
end
else
activetab = _tab
-- Find the sheet index
for k, v in pairs(self.C.TabHolder.Items) do
if activetab == v.Tab then
sheetindex = k
break
end
end
end
else
activetab = self:GetActiveTab()
-- Find the sheet index
for k, v in pairs(self.C.TabHolder.Items) do
if activetab == v.Tab then
sheetindex = k
break
end
end
end
self:AutoSave()
-- There's only one tab open, no need to actually close any tabs
if self:GetNumTabs() == 1 then
activetab:SetText("generic")
self.C.TabHolder:InvalidateLayout()
self:NewScript(true)
return
end
-- Find the panel (for the scroller)
local tabscroller_sheetindex
for k, v in pairs(self.C.TabHolder.tabScroller.Panels) do
if v == activetab then
tabscroller_sheetindex = k
break
end
end
self:FixTabFadeTime()
if activetab == self:GetActiveTab() then -- We're about to close the current tab
if self:GetLastTab() and self:GetLastTab():IsValid() then -- If the previous tab was saved
if activetab == self:GetLastTab() then -- If the previous tab is equal to the current tab
local othertab = self:GetNextAvailableTab() -- Find another tab
if othertab and othertab:IsValid() then -- If that other tab is valid, use it
self:SetActiveTab(othertab)
self:SetLastTab()
else -- Reset the current tab (backup)
self:GetActiveTab():SetText("generic")
self.C.TabHolder:InvalidateLayout()
self:NewScript(true)
return
end
else -- Change to the previous tab
self:SetActiveTab(self:GetLastTab())
self:SetLastTab()
end
else -- If the previous tab wasn't saved
local othertab = self:GetNextAvailableTab() -- Find another tab
if othertab and othertab:IsValid() then -- If that other tab is valid, use it
self:SetActiveTab(othertab)
else -- Reset the current tab (backup)
self:GetActiveTab():SetText("generic")
self.C.TabHolder:InvalidateLayout()
self:NewScript(true)
return
end
end
end
self:OnTabClosed(activetab) -- Call a function that you can override to do custom stuff to each tab.
activetab:GetPanel():Remove()
activetab:Remove()
table.remove(self.C.TabHolder.Items, sheetindex)
table.remove(self.C.TabHolder.tabScroller.Panels, tabscroller_sheetindex)
self.C.TabHolder.tabScroller:InvalidateLayout()
local w, h = self.C.TabHolder:GetSize()
self.C.TabHolder:SetSize(w + 1, h) -- +1 so it updates
end
function Editor:OnTabClosed(sheet) end
-- This function is made to be overwritten
-- initialization commands
function Editor:InitComponents()
self.Components = {}
self.C = {}
local function PaintFlatButton(panel, w, h)
if not (panel:IsHovered() or panel:IsDown()) then return end
derma.SkinHook("Paint", "Button", panel, w, h)
end
local DMenuButton = vgui.RegisterTable({
Init = function(panel)
panel:SetText("")
panel:SetSize(24, 20)
panel:Dock(LEFT)
end,
Paint = PaintFlatButton,
DoClick = function(panel)
local name = panel:GetName()
local f = name and name ~= "" and self[name] or nil
if f then f(self) end
end
}, "DButton")
-- addComponent( panel, x, y, w, h )
-- if x, y, w, h is minus, it will stay relative to right or buttom border
self.C.Close = self:addComponent(vgui.Create("DButton", self), -45-4, 0, 45, 22) -- Close button
self.C.Inf = self:addComponent(vgui.CreateFromTable(DMenuButton, self), -45-4-26, 0, 24, 22) -- Info button
self.C.ConBut = self:addComponent(vgui.CreateFromTable(DMenuButton, self), -45-4-24-26, 0, 24, 22) -- Control panel open/close
self.C.Divider = vgui.Create("DHorizontalDivider", self)
self.C.Browser = vgui.Create("wire_expression2_browser", self.C.Divider) -- Expression browser
self.C.MainPane = vgui.Create("DPanel", self.C.Divider)
self.C.Menu = vgui.Create("DPanel", self.C.MainPane)
self.C.Val = vgui.Create("Button", self.C.MainPane) -- Validation line
self.C.TabHolder = vgui.Create("DPropertySheet", self.C.MainPane)
self.C.Btoggle = vgui.CreateFromTable(DMenuButton, self.C.Menu) -- Toggle Browser being shown
self.C.Sav = vgui.CreateFromTable(DMenuButton, self.C.Menu) -- Save button
self.C.NewTab = vgui.CreateFromTable(DMenuButton, self.C.Menu, "NewTab") -- New tab button
self.C.CloseTab = vgui.CreateFromTable(DMenuButton, self.C.Menu, "CloseTab") -- Close tab button
self.C.Reload = vgui.CreateFromTable(DMenuButton, self.C.Menu) -- Reload tab button
self.C.SaE = vgui.Create("DButton", self.C.Menu) -- Save & Exit button
self.C.SavAs = vgui.Create("DButton", self.C.Menu) -- Save As button
self.C.Control = self:addComponent(vgui.Create("Panel", self), -350, 52, 342, -32) -- Control Panel
self.C.Credit = self:addComponent(vgui.Create("DTextEntry", self), -160, 52, 150, 150) -- Credit box
self:CreateTab("generic")
-- extra component options
self.C.Divider:SetLeft(self.C.Browser)
self.C.Divider:SetRight(self.C.MainPane)
self.C.Divider:Dock(FILL)
self.C.Divider:SetDividerWidth(4)
self.C.Divider:SetCookieName("wire_expression2_editor_divider")
local DoNothing = function() end
self.C.MainPane.Paint = DoNothing
--self.C.Menu.Paint = DoNothing
self.C.Menu:Dock(TOP)
self.C.TabHolder:Dock(FILL)
self.C.Val:Dock(BOTTOM)
self.C.TabHolder:SetPadding(1)
self.C.Menu:SetHeight(24)
self.C.Menu:DockPadding(2,2,2,2)
self.C.Val:SetHeight(22)
self.C.SaE:SetSize(80, 20)
self.C.SaE:Dock(RIGHT)
self.C.SavAs:SetSize(51, 20)
self.C.SavAs:Dock(RIGHT)
self.C.Inf:Dock(NODOCK)
self.C.ConBut:Dock(NODOCK)
self.C.Close:SetText("r")
self.C.Close:SetFont("Marlett")
self.C.Close.DoClick = function(btn) self:Close() end
self.C.ConBut:SetImage("icon16/wrench.png")
self.C.ConBut:SetText("")
self.C.ConBut.Paint = PaintFlatButton
self.C.ConBut.DoClick = function() self.C.Control:SetVisible(not self.C.Control:IsVisible()) end
self.C.Inf:SetImage("icon16/information.png")
self.C.Inf.Paint = PaintFlatButton
self.C.Inf.DoClick = function(btn)
self.C.Credit:SetVisible(not self.C.Credit:IsVisible())
end
self.C.Sav:SetImage("icon16/disk.png")
self.C.Sav.DoClick = function(button) self:SaveFile(self:GetChosenFile()) end
self.C.Sav:SetToolTip( "Save" )
self.C.NewTab:SetImage("icon16/page_white_add.png")
self.C.NewTab.DoClick = function(button) self:NewTab() end
self.C.NewTab:SetToolTip( "New tab" )
self.C.CloseTab:SetImage("icon16/page_white_delete.png")
self.C.CloseTab.DoClick = function(button) self:CloseTab() end
self.C.CloseTab:SetToolTip( "Close tab" )
self.C.Reload:SetImage("icon16/page_refresh.png")
self.C.Reload:SetToolTip( "Refresh file" )
self.C.Reload.DoClick = function(button)
self:LoadFile(self:GetChosenFile(), false)
end
self.C.SaE:SetText("Save and Exit")
self.C.SaE.DoClick = function(button) self:SaveFile(self:GetChosenFile(), true) end
self.C.SavAs:SetText("Save As")
self.C.SavAs.DoClick = function(button) self:SaveFile(self:GetChosenFile(), false, true) end
self.C.Browser:AddRightClick(self.C.Browser.filemenu, 4, "Save to", function()
Derma_Query("Overwrite this file?", "Save To",
"Overwrite", function()
self:SaveFile(self.C.Browser.File.FileDir)
end,
"Cancel")
end)
self.C.Browser.OnFileOpen = function(_, filepath, newtab)
self:Open(filepath, nil, newtab)
end
self.C.Val:SetText(" Click to validate...")
self.C.Val.UpdateColours = function(button, skin)
return button:SetTextStyleColor(skin.Colours.Button.Down)
end
self.C.Val.SetBGColor = function(button, r, g, b, a)
self.C.Val.bgcolor = Color(r, g, b, a)
end
self.C.Val.bgcolor = Color(255, 255, 255)
self.C.Val.Paint = function(button)
local w, h = button:GetSize()
draw.RoundedBox(1, 0, 0, w, h, button.bgcolor)
if button.Hovered then draw.RoundedBox(0, 1, 1, w - 2, h - 2, Color(0, 0, 0, 128)) end
end
self.C.Val.OnMousePressed = function(panel, btn)
if btn == MOUSE_RIGHT then
local menu = DermaMenu()
menu:AddOption("Copy to clipboard", function()
SetClipboardText(self.C.Val:GetValue():sub(4))
end)
menu:Open()
else
self:Validate(true)
end
end
self.C.Btoggle:SetImage("icon16/application_side_contract.png")
function self.C.Btoggle.DoClick(button)
if button.hide then
self.C.Divider:LoadCookies()
else
self.C.Divider:SetLeftWidth(0)
end
button:InvalidateLayout()
end
local oldBtoggleLayout = self.C.Btoggle.PerformLayout
function self.C.Btoggle.PerformLayout(button)
oldBtoggleLayout(button)
if self.C.Divider:GetLeftWidth() > 0 then
button.hide = false
button:SetImage("icon16/application_side_contract.png")
else
button.hide = true
button:SetImage("icon16/application_side_expand.png")
end
end
self.C.Credit:SetTextColor(Color(0, 0, 0, 255))
self.C.Credit:SetText("\t\tCREDITS\n\n\tEditor by: \tSyranide and Shandolum\n\n\tTabs (and more) added by Divran.\n\n\tFixed for GMod13 By Ninja101") -- Sure why not ;)
self.C.Credit:SetMultiline(true)
self.C.Credit:SetVisible(false)
self:InitControlPanel(self.C.Control) -- making it seperate for better overview
self.C.Control:SetVisible(false)
if self.E2 then self:Validate() end
end
function Editor:AutoSave()
local buffer = self:GetCode()
if self.savebuffer == buffer or buffer == defaultcode or buffer == "" then return end
self.savebuffer = buffer
file.Write(self.Location .. "/_autosave_.txt", buffer)
end
function Editor:AddControlPanelTab(label, icon, tooltip)
local frame = self.C.Control
local panel = vgui.Create("DPanel")
local ret = frame.TabHolder:AddSheet(label, panel, icon, false, false, tooltip)
local old = ret.Tab.OnMousePressed
function ret.Tab.OnMousePressed(...)
timer.Simple(0.1,function() frame:ResizeAll() end) -- timers solve everything
old(...)
end
ret.Panel:SetBackgroundColor(Color(96, 96, 96, 255))
return ret
end
function Editor:InitControlPanel(frame)
local C = self.C.Control
-- Add a property sheet to hold the tabs
local tabholder = vgui.Create("DPropertySheet", frame)
tabholder:SetPos(2, 4)
frame.TabHolder = tabholder
-- They need to be resized one at a time... dirty fix incoming (If you know of a nicer way to do this, don't hesitate to fix it.)
local function callNext(t, n)
local obj = t[n]
local pnl = obj[1]
if pnl and pnl:IsValid() then
local x, y = obj[2], obj[3]
pnl:SetPos(x, y)
local w, h = pnl:GetParent():GetSize()
local wofs, hofs = w - x * 2, h - y * 2
pnl:SetSize(wofs, hofs)
end
n = n + 1
if n <= #t then
timer.Simple(0, function() callNext(t, n) end)
end
end
function frame:ResizeAll()
timer.Simple(0, function()
callNext(self.ResizeObjects, 1)
end)
end
-- Resize them at the right times
local old = frame.SetSize
function frame:SetSize(...)
self:ResizeAll()
old(self, ...)
end
local old = frame.SetVisible
function frame:SetVisible(...)
self:ResizeAll()
old(self, ...)
end
-- Function to add more objects to resize automatically
frame.ResizeObjects = {}
function frame:AddResizeObject(...)
self.ResizeObjects[#self.ResizeObjects + 1] = { ... }
end
-- Our first object to auto resize is the tabholder. This sets it to position 2,4 and with a width and height offset of w-4, h-8.
frame:AddResizeObject(tabholder, 2, 4)
-- ------------------------------------------- EDITOR TAB
local sheet = self:AddControlPanelTab("Editor", "icon16/wrench.png", "Options for the editor itself.")
-- WINDOW BORDER COLORS
local dlist = vgui.Create("DPanelList", sheet.Panel)
dlist.Paint = function() end
frame:AddResizeObject(dlist, 4, 4)
dlist:EnableVerticalScrollbar(true)
-- Color Mixer PANEL - Houses label, combobox, mixer, reset button & reset all button.
local mixPanel = vgui.Create( "panel" )
mixPanel:SetTall( 240 )
dlist:AddItem( mixPanel )
do
-- Label
local label = vgui.Create( "DLabel", mixPanel )
label:Dock( TOP )
label:SetText( "Syntax Colors" )
label:SizeToContents()
-- Dropdown box of convars to change ( affects editor colors )
local box = vgui.Create( "DComboBox", mixPanel )
box:Dock( TOP )
box:SetValue( "Color feature" )
local active = nil
-- Mixer
local mixer = vgui.Create( "DColorMixer", mixPanel )
mixer:Dock( FILL )
mixer:SetPalette( true )
mixer:SetAlphaBar( true )
mixer:SetWangs( true )
mixer.ValueChanged = function ( _, clr )
self:SetSyntaxColor( active, clr )
end
for k, _ in pairs( colors_convars ) do
box:AddChoice( k )
end
box.OnSelect = function ( self, index, value, data )
-- DComboBox doesn't have a method for getting active value ( to my knowledge )
-- Therefore, cache it, we're in a local scope so we're fine.
active = value
mixer:SetColor( colors[ active ] or Color( 255, 255, 255 ) )
end
-- Reset ALL button
local rAll = vgui.Create( "DButton", mixPanel )
rAll:Dock( BOTTOM )
rAll:SetText( "Reset ALL to Default" )
rAll.DoClick = function ()
for k, v in pairs( colors_defaults ) do
self:SetSyntaxColor( k, v )
end
mixer:SetColor( colors_defaults[ active ] )
end
-- Reset to default button
local reset = vgui.Create( "DButton", mixPanel )
reset:Dock( BOTTOM )
reset:SetText( "Set to Default" )
reset.DoClick = function ()
self:SetSyntaxColor( active, colors_defaults[ active ] )
mixer:SetColor( colors_defaults[ active ] )
end
-- Select a convar to be displayed automatically
box:ChooseOptionID( 1 )
end
--- - FONTS
local FontLabel = vgui.Create("DLabel")
dlist:AddItem(FontLabel)
FontLabel:SetText("Font: Font Size:")
FontLabel:SizeToContents()
FontLabel:SetPos(10, 0)
local temp = vgui.Create("Panel")
temp:SetTall(25)
dlist:AddItem(temp)
local FontSelect = vgui.Create("DComboBox", temp)
-- dlist:AddItem( FontSelect )
FontSelect.OnSelect = function(panel, index, value)
if value == "Custom..." then
Derma_StringRequestNoBlur("Enter custom font:", "", "", function(value)
self:ChangeFont(value, self.FontSizeConVar:GetInt())
RunConsoleCommand("wire_expression2_editor_font", value)
end)
else
value = value:gsub(" %b()", "") -- Remove description
self:ChangeFont(value, self.FontSizeConVar:GetInt())
RunConsoleCommand("wire_expression2_editor_font", value)
end
end
for k, v in pairs(self.Fonts) do
FontSelect:AddChoice(k .. (v ~= "" and " (" .. v .. ")" or ""))
end
FontSelect:AddChoice("Custom...")
FontSelect:SetSize(240 - 50 - 4, 20)
local FontSizeSelect = vgui.Create("DComboBox", temp)
FontSizeSelect.OnSelect = function(panel, index, value)
value = value:gsub(" %b()", "")
self:ChangeFont(self.FontConVar:GetString(), tonumber(value))
RunConsoleCommand("wire_expression2_editor_font_size", value)
end
for i = 11, 26 do
FontSizeSelect:AddChoice(i .. (i == 16 and " (Default)" or ""))
end
FontSizeSelect:SetPos(FontSelect:GetWide() + 4, 0)
FontSizeSelect:SetSize(50, 20)
local label = vgui.Create("DLabel")
dlist:AddItem(label)
label:SetText("Auto completion options")
label:SizeToContents()
local AutoComplete = vgui.Create("DCheckBoxLabel")
dlist:AddItem(AutoComplete)
AutoComplete:SetConVar("wire_expression2_autocomplete")
AutoComplete:SetText("Auto Completion")
AutoComplete:SizeToContents()
AutoComplete:SetTooltip("Enable/disable auto completion in the E2 editor.")
local AutoCompleteExtra = vgui.Create("DCheckBoxLabel")
dlist:AddItem(AutoCompleteExtra)
AutoCompleteExtra:SetConVar("wire_expression2_autocomplete_moreinfo")
AutoCompleteExtra:SetText("More Info (for AC)")
AutoCompleteExtra:SizeToContents()
AutoCompleteExtra:SetTooltip("Enable/disable additional information for auto completion.")
local label = vgui.Create("DLabel")
dlist:AddItem(label)
label:SetText("Auto completion control style")
label:SizeToContents()
local AutoCompleteControlOptions = vgui.Create("DComboBox")
dlist:AddItem(AutoCompleteControlOptions)
local modes = {}
modes["Default"] = { 0, "Current mode:\nTab/CTRL+Tab to choose item;\nEnter/Space to use;\nArrow keys to abort." }
modes["Visual C# Style"] = { 1, "Current mode:\nCtrl+Space to use the top match;\nArrow keys to choose item;\nTab/Enter/Space to use;\nCode validation hotkey (ctrl+space) moved to ctrl+b." }
modes["Scroller"] = { 2, "Current mode:\nMouse scroller to choose item;\nMiddle mouse to use." }
modes["Scroller w/ Enter"] = { 3, "Current mode:\nMouse scroller to choose item;\nEnter to use." }
modes["Eclipse Style"] = { 4, "Current mode:\nEnter to use top match;\nTab to enter auto completion menu;\nArrow keys to choose item;\nEnter to use;\nSpace to abort." }
-- modes["Qt Creator Style"] = { 6, "Current mode:\nCtrl+Space to enter auto completion menu;\nSpace to abort; Enter to use top match." } <-- probably wrong. I'll check about adding Qt style later.
for k, v in pairs(modes) do
AutoCompleteControlOptions:AddChoice(k)
end
modes[0] = modes["Default"][2]
modes[1] = modes["Visual C# Style"][2]
modes[2] = modes["Scroller"][2]
modes[3] = modes["Scroller w/ Enter"][2]
modes[4] = modes["Eclipse Style"][2]
AutoCompleteControlOptions:SetToolTip(modes[GetConVar("wire_expression2_autocomplete_controlstyle"):GetInt()])
AutoCompleteControlOptions.OnSelect = function(panel, index, value)
panel:SetToolTip(modes[value][2])
RunConsoleCommand("wire_expression2_autocomplete_controlstyle", modes[value][1])
end
local HighightOnUse = vgui.Create("DCheckBoxLabel")
dlist:AddItem(HighightOnUse)
HighightOnUse:SetConVar("wire_expression2_autocomplete_highlight_after_use")
HighightOnUse:SetText("Highlight word after AC use.")
HighightOnUse:SizeToContents()
HighightOnUse:SetTooltip("Enable/Disable highlighting of the entire word after using auto completion.\nIn E2, this is only for variables/constants, not functions.")
local label = vgui.Create("DLabel")
dlist:AddItem(label)
label:SetText("Other options")
label:SizeToContents()
local NewTabOnOpen = vgui.Create("DCheckBoxLabel")
dlist:AddItem(NewTabOnOpen)
NewTabOnOpen:SetConVar("wire_expression2_new_tab_on_open")
NewTabOnOpen:SetText("New tab on open")
NewTabOnOpen:SizeToContents()
NewTabOnOpen:SetTooltip("Enable/disable loaded files opening in a new tab.\nIf disabled, loaded files will be opened in the current tab.")
local SaveTabsOnClose = vgui.Create("DCheckBoxLabel")
dlist:AddItem(SaveTabsOnClose)
SaveTabsOnClose:SetConVar("wire_expression2_editor_savetabs")
SaveTabsOnClose:SetText("Save tabs on close")
SaveTabsOnClose:SizeToContents()
SaveTabsOnClose:SetTooltip("Save the currently opened tab file paths on shutdown.\nOnly saves tabs whose files are saved.")
local OpenOldTabs = vgui.Create("DCheckBoxLabel")
dlist:AddItem(OpenOldTabs)
OpenOldTabs:SetConVar("wire_expression2_editor_openoldtabs")
OpenOldTabs:SetText("Open old tabs on load")
OpenOldTabs:SizeToContents()
OpenOldTabs:SetTooltip("Open the tabs from the last session on load.\nOnly tabs whose files were saved before disconnecting from the server are stored.")
local DisplayCaretPos = vgui.Create("DCheckBoxLabel")
dlist:AddItem(DisplayCaretPos)
DisplayCaretPos:SetConVar("wire_expression2_editor_display_caret_pos")
DisplayCaretPos:SetText("Show Caret Position")
DisplayCaretPos:SizeToContents()
DisplayCaretPos:SetTooltip("Shows the position of the caret.")
local HighlightOnDoubleClick = vgui.Create("DCheckBoxLabel")
dlist:AddItem(HighlightOnDoubleClick)
HighlightOnDoubleClick:SetConVar("wire_expression2_editor_highlight_on_double_click")
HighlightOnDoubleClick:SetText("Highlight copies of selected word")
HighlightOnDoubleClick:SizeToContents()
HighlightOnDoubleClick:SetTooltip("Find all identical words and highlight them after a double-click.")
local WorldClicker = vgui.Create("DCheckBoxLabel")
dlist:AddItem(WorldClicker)
WorldClicker:SetConVar("wire_expression2_editor_worldclicker")
WorldClicker:SetText("Enable Clicking Outside Editor")
WorldClicker:SizeToContents()
function WorldClicker.OnChange(pnl, bVal)
self:GetParent():SetWorldClicker(bVal)
end
--------------------------------------------- EXPRESSION 2 TAB
local sheet = self:AddControlPanelTab("Expression 2", "icon16/computer.png", "Options for Expression 2.")
local dlist = vgui.Create("DPanelList", sheet.Panel)
dlist.Paint = function() end
frame:AddResizeObject(dlist, 2, 2)
dlist:EnableVerticalScrollbar(true)
local label = vgui.Create("DLabel")
dlist:AddItem(label)
label:SetText("Clientside expression 2 options")
label:SizeToContents()
local AutoIndent = vgui.Create("DCheckBoxLabel")
dlist:AddItem(AutoIndent)
AutoIndent:SetConVar("wire_expression2_autoindent")
AutoIndent:SetText("Auto indenting")
AutoIndent:SizeToContents()
AutoIndent:SetTooltip("Enable/disable auto indenting.")
local Concmd = vgui.Create("DCheckBoxLabel")
dlist:AddItem(Concmd)
Concmd:SetConVar("wire_expression2_concmd")
Concmd:SetText("concmd")
Concmd:SizeToContents()
Concmd:SetTooltip("Allow/disallow the E2 from running console commands on you.")
local label = vgui.Create("DLabel")
dlist:AddItem(label)
label:SetText("Concmd whitelist")
label:SizeToContents()
local ConcmdWhitelist = vgui.Create("DTextEntry")
dlist:AddItem(ConcmdWhitelist)
ConcmdWhitelist:SetConVar("wire_expression2_concmd_whitelist")
ConcmdWhitelist:SetToolTip("Separate the commands with commas.")
local label = vgui.Create("DLabel")
dlist:AddItem(label)
label:SetText("Expression 2 block comment style")
label:SizeToContents()
local BlockCommentStyle = vgui.Create("DComboBox")
dlist:AddItem(BlockCommentStyle)
local modes = {}
modes["New (alt 1)"] = {
0, [[Current mode:
#[
Text here
Text here
]#]]
}
modes["New (alt 2)"] = {
1, [[Current mode:
#[Text here
Text here]# ]]
}
modes["Old"] = {
2, [[Current mode:
#Text here
#Text here]]
}
for k, v in pairs(modes) do
BlockCommentStyle:AddChoice(k)
end
modes[0] = modes["New (alt 1)"][2]
modes[1] = modes["New (alt 2)"][2]
modes[2] = modes["Old"][2]
BlockCommentStyle:SetToolTip(modes[self.BlockCommentStyleConVar:GetInt()])
BlockCommentStyle.OnSelect = function(panel, index, value)
panel:SetToolTip(modes[value][2])
RunConsoleCommand("wire_expression2_editor_block_comment_style", modes[value][1])
end
local ops_sync_checkbox = vgui.Create("DCheckBoxLabel")
dlist:AddItem(ops_sync_checkbox)
ops_sync_checkbox:SetConVar("wire_expression_ops_sync_subscribe")
ops_sync_checkbox:SetText("ops/cpu usage syncing for remote uploader (Admin only)")
ops_sync_checkbox:SizeToContents()
ops_sync_checkbox:SetTooltip("Opt into live ops/cpu usage for all E2s on the server via the remote uploader tab. If you're not admin, this checkbox does nothing.")
-- ------------------------------------------- REMOTE UPDATER TAB
local sheet = self:AddControlPanelTab("Remote Updater", "icon16/world.png", "Manage your E2s from far away.")
local dlist = vgui.Create("DPanelList", sheet.Panel)
dlist.Paint = function() end
frame:AddResizeObject(dlist, 2, 2)
dlist:EnableVerticalScrollbar(true)
dlist:SetSpacing(2)
local dlist2 = vgui.Create("DPanelList")
dlist:AddItem(dlist2)
dlist2:EnableVerticalScrollbar(true)
-- frame:AddResizeObject( dlist2, 2,2 )
-- dlist2:SetTall( 444 )
dlist2:SetSpacing(1)
local painted = 0
local opened = false
dlist2.Paint = function() painted = SysTime() + 0.05 end
timer.Create( "wire_expression2_ops_sync_check", 0, 0, function()
if painted > SysTime() and not opened then
opened = true
if Editor.ops_sync_subscribe:GetBool() then RunConsoleCommand("wire_expression_ops_sync","1") end
elseif painted < SysTime() and opened then
opened = false
RunConsoleCommand("wire_expression_ops_sync","0")
end
end)
local UpdateList = vgui.Create("DButton")
UpdateList:SetText("Update List (Show only yours)")
dlist:AddItem(UpdateList)
UpdateList.DoClick = function(pnl, showall)
local E2s = ents.FindByClass("gmod_wire_expression2")
dlist2:Clear()
local size = 0
for k, v in pairs(E2s) do
local ply = v:GetNWEntity("player", NULL)
if IsValid(ply) and ply == LocalPlayer() or showall then
local nick
if not ply or not ply:IsValid() then nick = "Unknown" else nick = ply:Nick() end
local name = v:GetNWString("name", "generic")
local singleline = string.match( name, "(.-)\n" )
if singleline then name = singleline .. "..." end
local max = 20
if #name > max then name = string.sub(name,1,max) .. "..." end
local panel = vgui.Create("DPanel")
panel:SetTall((LocalPlayer():IsAdmin() and 74 or 47))
panel.Paint = function(panel)
local w, h = panel:GetSize()
draw.RoundedBox(1, 0, 0, w, h, Color(65, 105, 255, 100))
end
dlist2:AddItem(panel)
size = size + panel:GetTall() + 1
local label = vgui.Create("DLabel", panel)
local idx = v:EntIndex()
local str = string.format("Name: %s\nEntity ID: '%d'\nOwner: %s",name,idx,nick)
if LocalPlayer():IsAdmin() then
str = string.format("Name: %s\nEntity ID: '%d'\n%i ops, %i%% %s\ncpu time: %ius\nOwner: %s",name,idx,0,0,"",0,nick)
end
label:SetText(str)
label:SizeToContents()
label:SetWide(280)
label:SetWrap(true)
label:SetPos(4, 4)
label:SetTextColor(Color(255, 255, 255, 255))
if LocalPlayer():IsAdmin() then
local hardquota = GetConVar("wire_expression2_quotahard")
local softquota = GetConVar("wire_expression2_quotasoft")
function label:Think()
if not IsValid(v) then
label.Think = function() end
return
end
local data = v:GetOverlayData()
if data then
local prfbench = data.prfbench
local prfcount = data.prfcount
local timebench = data.timebench
local e2_hardquota = hardquota:GetInt()
local e2_softquota = softquota:GetInt()
local hardtext = (prfcount / e2_hardquota > 0.33) and "(+" .. tostring(math.Round(prfcount / e2_hardquota * 100)) .. "%)" or ""
label:SetText(string.format("Name: %s\nEntity ID: '%d'\n%i ops, %i%% %s\ncpu time: %ius\nOwner: %s",name,idx,prfbench,prfbench / e2_softquota * 100,hardtext,timebench*1000000,nick))
end
end
end
local btn = vgui.Create("DButton", panel)
btn:SetText("Upload")
btn:SetSize(57, 18)
timer.Simple(0, function() btn:SetPos(panel:GetWide() - btn:GetWide() * 2 - 6, 4) end)
btn.DoClick = function(pnl)
WireLib.Expression2Upload(v)
end
local btn = vgui.Create("DButton", panel)
btn:SetText("Download")
btn:SetSize(57, 18)
timer.Simple(0, function() btn:SetPos(panel:GetWide() - btn:GetWide() - 4, 4) end)
btn.DoClick = function(pnl)
RunConsoleCommand("wire_expression_requestcode", v:EntIndex())
end
local btn = vgui.Create("DButton", panel)
btn:SetText("Halt execution")
btn:SetSize(75, 18)
timer.Simple(0, function() btn:SetPos(panel:GetWide() - btn:GetWide() - 4, 24) end)
btn.DoClick = function(pnl)
RunConsoleCommand("wire_expression_forcehalt", v:EntIndex())
end
local btn2 = vgui.Create("DButton", panel)
btn2:SetText("Reset")
btn2:SetSize(39, 18)
timer.Simple(0, function() btn2:SetPos(panel:GetWide() - btn2:GetWide() - btn:GetWide() - 6, 24) end)
btn2.DoClick = function(pnl)
RunConsoleCommand("wire_expression_reset", v:EntIndex())
end
end
end
dlist2:SetTall(size + 2)
dlist:InvalidateLayout()
end
local UpdateList2 = vgui.Create("DButton")
UpdateList2:SetText("Update List (Show all)")
dlist:AddItem(UpdateList2)
UpdateList2.DoClick = function(pnl) UpdateList:DoClick(true) end
end
-- used with color-circles
function Editor:TranslateValues(panel, x, y)
x = x - 0.5
y = y - 0.5
local angle = math.atan2(x, y)
local length = math.sqrt(x * x + y * y)
length = math.Clamp(length, 0, 0.5)
x = 0.5 + math.sin(angle) * length
y = 0.5 + math.cos(angle) * length
panel:SetHue(math.deg(angle) + 270)
panel:SetSaturation(length * 2)
panel:SetRGB(HSVToColor(panel:GetHue(), panel:GetSaturation(), 1))
panel:SetFrameColor()
return x, y
end
-- options
-- code1 contains the code that is not to be marked
local code1 = "@name \n@inputs \n@outputs \n@persist \n@trigger \n\n"
-- code2 contains the code that is to be marked, so it can simply be overwritten or deleted.
local code2 = [[#[
Shoutout to Expression Advanced 2! Have you tried it yet?
You should try it. It's a hundred times faster than E2
and has more features. http://goo.gl/sZcyN9
A new preprocessor command, @autoupdate has been added.
See the wiki for more info.
Documentation and examples are available at:
http://wiki.wiremod.com/wiki/Expression_2
The community is available at http://www.wiremod.com
]#]]
local defaultcode = code1 .. code2 .. "\n"
function Editor:NewScript(incurrent)
if not incurrent and self.NewTabOnOpen:GetBool() then
self:NewTab()
else
self:AutoSave()
self:ChosenFile()
-- Set title
self:GetActiveTab():SetText("generic")
self.C.TabHolder:InvalidateLayout()
if self.E2 then
-- add both code1 and code2 to the editor
self:SetCode(defaultcode)
local ed = self:GetCurrentEditor()
-- mark only code2
ed.Start = ed:MovePosition({ 1, 1 }, code1:len())
ed.Caret = ed:MovePosition({ 1, 1 }, defaultcode:len())
else
self:SetCode("")
end
end
end
local wire_expression2_editor_savetabs = CreateClientConVar("wire_expression2_editor_savetabs", "1", true, false)
local id = 0
function Editor:InitShutdownHook()
id = id + 1
-- save code when shutting down
hook.Add("ShutDown", "wire_expression2_ShutDown" .. id, function()
-- if wire_expression2_editor == nil then return end
local buffer = self:GetCode()
if buffer == defaultcode then return end
file.Write(self.Location .. "/_shutdown_.txt", buffer)
if wire_expression2_editor_savetabs:GetBool() then
self:SaveTabs()
end
end)
end
function Editor:SaveTabs()
local strtabs = ""
local tabs = {}
for i=1, self:GetNumTabs() do
local chosenfile = self:GetEditor(i).chosenfile
if chosenfile and chosenfile ~= "" and not tabs[chosenfile] then
strtabs = strtabs .. chosenfile .. ";"
tabs[chosenfile] = true -- Prevent duplicates
end
end
strtabs = strtabs:sub(1, -2)
file.Write(self.Location .. "/_tabs_.txt", strtabs)
end
local wire_expression2_editor_openoldtabs = CreateClientConVar("wire_expression2_editor_openoldtabs", "1", true, false)
function Editor:OpenOldTabs()
if not file.Exists(self.Location .. "/_tabs_.txt", "DATA") then return end
-- Read file
local tabs = file.Read(self.Location .. "/_tabs_.txt")
if not tabs or tabs == "" then return end
-- Explode around ;
tabs = string.Explode(";", tabs)
if not tabs or #tabs == 0 then return end
-- Temporarily remove fade time
self:FixTabFadeTime()
local is_first = true
for k, v in pairs(tabs) do
if v and v ~= "" then
if (file.Exists(v, "DATA")) then
-- Open it in a new tab
self:LoadFile(v, true)
-- If this is the first loop, close the initial tab.
if (is_first) then
timer.Simple(0, function()
self:CloseTab(1)
end)
is_first = false
end
end
end
end
end
function Editor:Validate(gotoerror)
if self.EditorType == "E2" then
local errors = wire_expression2_validate(self:GetCode())
if not errors then
self.C.Val:SetBGColor(0, 110, 20, 255)
self.C.Val:SetText(" Validation successful")
return true
end
if gotoerror then
local row, col = errors:match("at line ([0-9]+), char ([0-9]+)$")
if not row then
row, col = errors:match("at line ([0-9]+)$"), 1
end
if row then self:GetCurrentEditor():SetCaret({ tonumber(row), tonumber(col) }) end
end
self.C.Val:SetBGColor(110, 0, 20, 255)
self.C.Val:SetText(" " .. errors)
elseif self.EditorType == "CPU" or self.EditorType == "GPU" or self.EditorType == "SPU" then
self.C.Val:SetBGColor(64, 64, 64, 180)
self.C.Val:SetText(" Recompiling...")
CPULib.Validate(self, self:GetCode(), self:GetChosenFile())
end
return true
end
function Editor:SetValidatorStatus(text, r, g, b, a)
self.C.Val:SetBGColor(r or 0, g or 180, b or 0, a or 180)
self.C.Val:SetText(" " .. text)
end
function Editor:SubTitle(sub)
if not sub then self.subTitle = ""
else self.subTitle = " - " .. sub
end
end
local wire_expression2_editor_worldclicker = CreateClientConVar("wire_expression2_editor_worldclicker", "0", true, false)
function Editor:SetV(bool)
if bool then
self:MakePopup()
self:InvalidateLayout(true)
if self.E2 then self:Validate() end
end
self:SetVisible(bool)
self:SetKeyBoardInputEnabled(bool)
self:GetParent():SetWorldClicker(wire_expression2_editor_worldclicker:GetBool() and bool) -- Enable this on the background so we can update E2's without closing the editor
if CanRunConsoleCommand() then
RunConsoleCommand("wire_expression2_event", bool and "editor_open" or "editor_close")
if not e2_function_data_received and bool then -- Request the E2 functions
RunConsoleCommand("wire_expression2_sendfunctions")
end
end
end
function Editor:GetChosenFile()
return self:GetCurrentEditor().chosenfile
end
function Editor:ChosenFile(Line)
self:GetCurrentEditor().chosenfile = Line
if Line then
self:SubTitle("Editing: " .. Line)
else
self:SubTitle()
end
end
function Editor:FindOpenFile(FilePath)
for i = 1, self:GetNumTabs() do
local ed = self:GetEditor(i)
if ed.chosenfile == FilePath then
return ed
end
end
end
function Editor:ExtractName()
if not self.E2 then self.savefilefn = "filename" return end
local code = self:GetCode()
local name = extractNameFromCode(code)
if name and name ~= "" then
Expression2SetName(name)
self.savefilefn = name
else
Expression2SetName(nil)
self.savefilefn = "filename"
end
end
function Editor:SetCode(code)
self:GetCurrentEditor():SetText(code)
self.savebuffer = self:GetCode()
if self.E2 then self:Validate() end
self:ExtractName()
end
function Editor:GetEditor(n)
if self.C.TabHolder.Items[n] then
return self.C.TabHolder.Items[n].Panel
end
end
function Editor:GetCurrentEditor()
return self:GetActiveTab():GetPanel()
end
function Editor:GetCode()
return self:GetCurrentEditor():GetValue()
end
function Editor:Open(Line, code, forcenewtab)
if self:IsVisible() and not Line and not code then self:Close() end
self:SetV(true)
if self.chip then
self.C.SaE:SetText("Upload & Exit")
else
self.C.SaE:SetText("Save and Exit")
end
if code then
if not forcenewtab then
for i = 1, self:GetNumTabs() do
if self:GetEditor(i).chosenfile == Line then
self:SetActiveTab(i)
self:SetCode(code)
return
elseif self:GetEditor(i):GetValue() == code then
self:SetActiveTab(i)
return
end
end
end
local title, tabtext = getPreferredTitles(Line, code)
local tab
if self.NewTabOnOpen:GetBool() or forcenewtab then
tab = self:CreateTab(tabtext).Tab
else
tab = self:GetActiveTab()
tab:SetText(tabtext)
self.C.TabHolder:InvalidateLayout()
end
self:SetActiveTab(tab)
self:ChosenFile()
self:SetCode(code)
if Line then self:SubTitle("Editing: " .. Line) end
return
end
if Line then self:LoadFile(Line, forcenewtab) return end
end
function Editor:SaveFile(Line, close, SaveAs)
self:ExtractName()
if close and self.chip then
if not self:Validate(true) then return end
WireLib.Expression2Upload(self.chip, self:GetCode())
self:Close()
return
end
if not Line or SaveAs or Line == self.Location .. "/" .. ".txt" then
local str
if self.C.Browser.File then
str = self.C.Browser.File.FileDir -- Get FileDir
if str and str ~= "" then -- Check if not nil
-- Remove "expression2/" or "cpuchip/" etc
local n, _ = str:find("/", 1, true)
str = str:sub(n + 1, -1)
if str and str ~= "" then -- Check if not nil
if str:Right(4) == ".txt" then -- If it's a file
str = string.GetPathFromFilename(str):Left(-2) -- Get the file path instead
if not str or str == "" then
str = nil
end
end
else
str = nil
end
else
str = nil
end
end
Derma_StringRequestNoBlur("Save to New File", "", (str ~= nil and str .. "/" or "") .. self.savefilefn,
function(strTextOut)
strTextOut = string.gsub(strTextOut, ".", invalid_filename_chars)
self:SaveFile(self.Location .. "/" .. strTextOut .. ".txt", close)
end)
return
end
file.Write(Line, self:GetCode())
local panel = self.C.Val
timer.Simple(0, function() panel.SetText(panel, " Saved as " .. Line) end)
surface.PlaySound("ambient/water/drip3.wav")
if not self.chip then self:ChosenFile(Line) end
if close then
if self.E2 then
GAMEMODE:AddNotify("Expression saved as " .. Line .. ".", NOTIFY_GENERIC, 7)
else
GAMEMODE:AddNotify("Source code saved as " .. Line .. ".", NOTIFY_GENERIC, 7)
end
self:Close()
end
end
function Editor:LoadFile(Line, forcenewtab)
if not Line or file.IsDir(Line, "DATA") then return end
local f = file.Open(Line, "r", "DATA")
if not f then
ErrorNoHalt("Erroring opening file: " .. Line)
else
local str = f:Read(f:Size()) or ""
f:Close()
self:AutoSave()
if not forcenewtab then
for i = 1, self:GetNumTabs() do
if self:GetEditor(i).chosenfile == Line then
self:SetActiveTab(i)
if forcenewtab ~= nil then self:SetCode(str) end
return
elseif self:GetEditor(i):GetValue() == str then
self:SetActiveTab(i)
return
end
end
end
if not self.chip then
local title, tabtext = getPreferredTitles(Line, str)
local tab
if self.NewTabOnOpen:GetBool() or forcenewtab then
tab = self:CreateTab(tabtext).Tab
else
tab = self:GetActiveTab()
tab:SetText(tabtext)
self.C.TabHolder:InvalidateLayout()
end
self:SetActiveTab(tab)
self:ChosenFile(Line)
end
self:SetCode(str)
end
end
function Editor:Close()
timer.Stop("e2autosave")
self:AutoSave()
self:Validate()
self:ExtractName()
self:SetV(false)
self.chip = false
self:SaveEditorSettings()
end
function Editor:Setup(nTitle, nLocation, nEditorType)
self.Title = nTitle
self.Location = nLocation
self.EditorType = nEditorType
self.C.Browser:Setup(nLocation)
local syntaxHighlighters = {
CPU = self:GetCurrentEditor().CPUGPUSyntaxColorLine,
GPU = self:GetCurrentEditor().CPUGPUSyntaxColorLine,
SPU = self:GetCurrentEditor().CPUGPUSyntaxColorLine,
E2 = nil, -- the E2 highlighter is used by default
[""] = function(self, row) return { { self.Rows[row], { Color(255, 255, 255, 255), false } } } end
}
local helpModes = {
CPU = E2Helper.UseCPU,
GPU = E2Helper.UseCPU,
SPU = E2Helper.UseCPU,
E2 = E2Helper.UseE2
}
local syntaxHighlighter = syntaxHighlighters[nEditorType or ""]
if syntaxHighlighter then self:SetSyntaxColorLine(syntaxHighlighter) end
local helpMode = helpModes[nEditorType or ""]
if helpMode then -- Add "E2Helper" button
local E2Help = vgui.Create("Button", self.C.Menu)
E2Help:SetSize(58, 20)
E2Help:Dock(RIGHT)
E2Help:SetText("E2Helper")
E2Help.DoClick = function()
E2Helper.Show()
helpMode(nEditorType)
E2Helper.Update()
end
self.C.E2Help = E2Help
end
local useValidator = nEditorType ~= nil
local useSoundBrowser = nEditorType == "SPU" or nEditorType == "E2"
local useDebugger = nEditorType == "CPU"
if not useValidator then
self.C.Val:SetVisible(false)
end
if useSoundBrowser then -- Add "Sound Browser" button
local SoundBrw = vgui.Create("Button", self.C.Menu)
SoundBrw:SetSize(85, 20)
SoundBrw:Dock(RIGHT)
SoundBrw:SetText("Sound Browser")
SoundBrw.DoClick = function() RunConsoleCommand("wire_sound_browser_open") end
self.C.SoundBrw = SoundBrw
end
if useDebugger then
-- Add "step forward" button
local DebugForward = self:addComponent(vgui.Create("Button", self), -306, 31, -226, 20)
DebugForward:SetText("Step Forward")
DebugForward.Font = "E2SmallFont"
DebugForward.DoClick = function()
local currentPosition = CPULib.Debugger.PositionByPointer[CPULib.Debugger.Variables.IP]
if currentPosition then
local linePointers = CPULib.Debugger.PointersByLine[currentPosition.Line .. ":" .. currentPosition.File]
if linePointers then -- Run till end of line
RunConsoleCommand("wire_cpulib_debugstep", linePointers[2])
else -- Run just once
RunConsoleCommand("wire_cpulib_debugstep")
end
else -- Run just once
RunConsoleCommand("wire_cpulib_debugstep")
end
-- Reset interrupt text
CPULib.InterruptText = nil
end
self.C.DebugForward = DebugForward
-- Add "reset" button
local DebugReset = self:addComponent(vgui.Create("Button", self), -346, 31, -306, 20)
DebugReset:SetText("Reset")
DebugReset.DoClick = function()
RunConsoleCommand("wire_cpulib_debugreset")
-- Reset interrupt text
CPULib.InterruptText = nil
end
self.C.DebugReset = DebugReset
-- Add "run" button
local DebugRun = self:addComponent(vgui.Create("Button", self), -381, 31, -346, 20)
DebugRun:SetText("Run")
DebugRun.DoClick = function() RunConsoleCommand("wire_cpulib_debugrun") end
self.C.DebugRun = DebugRun
end
if nEditorType == "E2" then
self.E2 = true
self:NewScript(true) -- insert default code
end
if wire_expression2_editor_openoldtabs:GetBool() then
self:OpenOldTabs()
end
self:InvalidateLayout()
end
vgui.Register("Expression2EditorFrame", Editor, "DFrame")
| gpl-3.0 |
thedraked/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/npcs/HomePoint#1.lua | 14 | 1294 | -----------------------------------
-- Area: Grand Palace of Hu'Xzoi
-- NPC: HomePoint#3
-- @pos -12 0.5 -288 34
-----------------------------------
package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 88);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
thedraked/darkstar | scripts/globals/spells/poisonga_ii.lua | 26 | 1132 | -----------------------------------------
-- Spell: Poisonga II
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_POISON;
local duration = 120;
local pINT = caster:getStat(MOD_INT);
local mINT = target:getStat(MOD_INT);
local dINT = (pINT - mINT);
local power = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 15 + 1;
if power > 15 then
power = 15;
end
local resist = applyResistanceEffect(caster,spell,target,dINT,ENFEEBLING_MAGIC_SKILL,0,effect);
if (resist == 1 or resist == 0.5) then -- effect taken
duration = duration * resist;
if (target:addStatusEffect(effect,power,3,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else -- resist entirely.
spell:setMsg(85);
end
return effect;
end; | gpl-3.0 |
wrxck/mattata | plugins/setlmgtfy.lua | 2 | 1086 | --[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local setlmgtfy = {}
local mattata = require('mattata')
local redis = require('libs.redis')
function setlmgtfy:init()
setlmgtfy.commands = mattata.commands(self.info.username):command('setlmgtfy'):command('sl').table
setlmgtfy.help = '/setlmgtfy <response text> - Sets the response text for the LMGTFY plugin. Alias: /sl.'
end
function setlmgtfy:on_message(message)
if not mattata.is_group_admin(message.chat.id, message.from.id) or message.chat.type == 'private' then
return false
end
local input = mattata.input(message.text)
if not input or input:len() > 128 then
return mattata.send_reply(message, 'Please specify some text to reply to the user with. No longer than 128 characters please!')
end
redis:set('chat:' .. message.chat.id .. ':lmgtfy', input)
return mattata.send_reply(message, 'Successfully set that text as the LMGTFY response!')
end
return setlmgtfy | mit |
robert00s/koreader | plugins/newsdownloader.koplugin/lib/xml.lua | 14 | 17777 | ---
-- Overview:
-- =========
--
-- This module provides a non-validating XML stream parser in Lua.
--
-- Features:
-- =========
--
-- * Tokenises well-formed XML (relatively robustly)
-- * Flexible handler based event API (see below)
-- * Parses all XML Infoset elements - ie.
-- - Tags
-- - Text
-- - Comments
-- - CDATA
-- - XML Decl
-- - Processing Instructions
-- - DOCTYPE declarations
-- * Provides limited well-formedness checking
-- (checks for basic syntax & balanced tags only)
-- * Flexible whitespace handling (selectable)
-- * Entity Handling (selectable)
--
-- Limitations:
-- ============
--
-- * Non-validating
-- * No charset handling
-- * No namespace support
-- * Shallow well-formedness checking only (fails
-- to detect most semantic errors)
--
-- API:
-- ====
--
-- The parser provides a partially object-oriented API with
-- functionality split into tokeniser and handler components.
--
-- The handler instance is passed to the tokeniser and receives
-- callbacks for each XML element processed (if a suitable handler
-- function is defined). The API is conceptually similar to the
-- SAX API but implemented differently.
--
-- The following events are generated by the tokeniser
--
-- handler:start - Start Tag
-- handler:end - End Tag
-- handler:text - Text
-- handler:decl - XML Declaration
-- handler:pi - Processing Instruction
-- handler:comment - Comment
-- handler:dtd - DOCTYPE definition
-- handler:cdata - CDATA
--
-- The function prototype for all the callback functions is
--
-- callback(val,attrs,start,end)
--
-- where attrs is a table and val/attrs are overloaded for
-- specific callbacks - ie.
--
-- Callback val attrs (table)
-- -------- --- -------------
-- start name { attributes (name=val).. }
-- end name nil
-- text <text> nil
-- cdata <text> nil
-- decl "xml" { attributes (name=val).. }
-- pi pi name { attributes (if present)..
-- _text = <PI Text>
-- }
-- comment <text> nil
-- dtd root element { _root = <Root Element>,
-- _type = SYSTEM|PUBLIC,
-- _name = <name>,
-- _uri = <uri>,
-- _internal = <internal dtd>
-- }
--
-- (start & end provide the character positions of the start/end
-- of the element)
--
-- XML data is passed to the parser instance through the 'parse'
-- method (Note: must be passed a single string currently)
--
-- Options
-- =======
--
-- Parser options are controlled through the 'self.options' table.
-- Available options are -
--
-- * stripWS
--
-- Strip non-significant whitespace (leading/trailing)
-- and do not generate events for empty text elements
--
-- * expandEntities
--
-- Expand entities (standard entities + single char
-- numeric entities only currently - could be extended
-- at runtime if suitable DTD parser added elements
-- to table (see obj._ENTITIES). May also be possible
-- to expand multibyre entities for UTF-8 only
--
-- * errorHandler
--
-- Custom error handler function
--
-- NOTE: Boolean options must be set to 'nil' not '0'
--
-- Usage
-- =====
--
-- Create a handler instance -
--
-- h = { start = function(t,a,s,e) .... end,
-- end = function(t,a,s,e) .... end,
-- text = function(t,a,s,e) .... end,
-- cdata = text }
--
-- (or use predefined handler - see handler.lua)
--
-- Create parser instance -
--
-- p = xmlParser(h)
--
-- Set options -
--
-- p.options.xxxx = nil
--
-- Parse XML data -
--
-- xmlParser:parse("<?xml... ")
-- License:
-- ========
--
-- This code is freely distributable under the terms of the Lua license
-- (http://www.lua.org/copyright.html)
--
-- History
-- =======
-- Added parameter parseAttributes (boolean) in xmlParser.parse method
-- If true (default value), tag attributtes are parsed.
-- by Manoel Campos da Silva Filho
-- http://manoelcampos.com
-- http://about.me/manoelcampos
--
-- $Id: xml.lua,v 1.1.1.1 2001/11/28 06:11:33 paulc Exp $
--
-- $Log: xml.lua,v $
-- Revision 1.1.1.1 2001/11/28 06:11:33 paulc
-- Initial Import
--
--@author Paul Chakravarti (paulc@passtheaardvark.com)<p/>
---Parses a XML string
--@param handler Handler object to be used to convert the XML string
--to another formats. @see handler.lua
local xmlParser = function(handler)
local obj = {}
-- Public attributes
obj.options = {
stripWS = 1,
expandEntities = 1,
errorHandler = function(err,pos)
error(string.format("%s [char=%d]\n",
err or "Parse Error",pos))
end,
}
-- Public methods
obj.parse = function(self, str, parseAttributes)
if parseAttributes == nil then
parseAttributes = true
end
self._handler.parseAttributes = parseAttributes
local match,endmatch,pos = 0,0,1
local text,endt1,endt2,tagstr,tagname,attrs,starttext,endtext
local errstart,errend,extstart,extend
while match do
-- Get next tag (first pass - fix exceptions below)
match,endmatch,text,endt1,tagstr,endt2 = string.find(str,self._XML,pos)
if not match then
if string.find(str, self._WS,pos) then
-- No more text - check document complete
if #self._stack ~= 0 then
self:_err(self._errstr.incompleteXmlErr,pos)
else
break
end
else
-- Unparsable text
self:_err(self._errstr.xmlErr,pos)
end
end
-- Handle leading text
starttext = match
endtext = match + string.len(text) - 1
match = match + string.len(text)
text = self:_parseEntities(self:_stripWS(text))
if text ~= "" and self._handler.text then
self._handler:text(text,nil,match,endtext)
end
-- Test for tag type
if string.find(string.sub(tagstr,1,5),"?xml%s") then
-- XML Declaration
match,endmatch,text = string.find(str,self._PI,pos)
if not match then
self:_err(self._errstr.declErr,pos)
end
if match ~= 1 then
-- Must be at start of doc if present
self:_err(self._errstr.declStartErr,pos)
end
tagname,attrs = self:_parseTag(text)
-- TODO: Check attributes are valid
-- Check for version (mandatory)
if attrs.version == nil then
self:_err(self._errstr.declAttrErr,pos)
end
if self._handler.decl then
self._handler:decl(tagname,attrs,match,endmatch)
end
elseif string.sub(tagstr,1,1) == "?" then
-- Processing Instruction
match,endmatch,text = string.find(str,self._PI,pos)
if not match then
self:_err(self._errstr.piErr,pos)
end
if self._handler.pi then
-- Parse PI attributes & text
tagname,attrs = self:_parseTag(text)
local pi = string.sub(text,string.len(tagname)+1)
if pi ~= "" then
if attrs then
attrs._text = pi
else
attrs = { _text = pi }
end
end
self._handler:pi(tagname,attrs,match,endmatch)
end
elseif string.sub(tagstr,1,3) == "!--" then
-- Comment
match,endmatch,text = string.find(str,self._COMMENT,pos)
if not match then
self:_err(self._errstr.commentErr,pos)
end
if self._handler.comment then
text = self:_parseEntities(self:_stripWS(text))
self._handler:comment(text,next,match,endmatch)
end
elseif string.sub(tagstr,1,8) == "!DOCTYPE" then
-- DTD
match,endmatch,attrs = self:_parseDTD(string,pos)
if not match then
self:_err(self._errstr.dtdErr,pos)
end
if self._handler.dtd then
self._handler:dtd(attrs._root,attrs,match,endmatch)
end
elseif string.sub(tagstr,1,8) == "![CDATA[" then
-- CDATA
match,endmatch,text = string.find(str,self._CDATA,pos)
if not match then
self:_err(self._errstr.cdataErr,pos)
end
if self._handler.cdata then
self._handler:cdata(text,nil,match,endmatch)
end
else
-- Normal tag
-- Need check for embedded '>' in attribute value and extend
-- match recursively if necessary eg. <tag attr="123>456">
while 1 do
errstart,errend = string.find(tagstr,self._ATTRERR1)
if errend == nil then
errstart,errend = string.find(tagstr,self._ATTRERR2)
if errend == nil then
break
end
end
extstart,extend,endt2 = string.find(str,self._TAGEXT,endmatch+1)
tagstr = tagstr .. string.sub(string,endmatch,extend-1)
if not match then
self:_err(self._errstr.xmlErr,pos)
end
endmatch = extend
end
-- Extract tagname/attrs
tagname,attrs = self:_parseTag(tagstr)
if (endt1=="/") then
-- End tag
if self._handler.endtag then
if attrs then
-- Shouldnt have any attributes in endtag
self:_err(string.format("%s (/%s)",
self._errstr.endTagErr,
tagname)
,pos)
end
if table.remove(self._stack) ~= tagname then
self:_err(string.format("%s (/%s)",
self._errstr.unmatchedTagErr,
tagname)
,pos)
end
self._handler:endtag(tagname,nil,match,endmatch)
end
else
-- Start Tag
table.insert(self._stack,tagname)
if self._handler.starttag then
self._handler:starttag(tagname,attrs,match,endmatch)
end
--TODO: Tags com fechamento automático estão sendo
--retornadas como uma tabela, o que complica
--para a app NCLua tratar isso. É preciso
--fazer com que seja retornado um campo string vazio.
-- Self-Closing Tag
if (endt2=="/") then
table.remove(self._stack)
if self._handler.endtag then
self._handler:endtag(tagname,nil,match,endmatch)
end
end
end
end
pos = endmatch + 1
end
end
-- Private attribures/functions
obj._handler = handler
obj._stack = {}
obj._XML = '^([^<]*)<(%/?)([^>]-)(%/?)>'
obj._ATTR1 = '([%w-:_]+)%s*=%s*"(.-)"'
obj._ATTR2 = '([%w-:_]+)%s*=%s*\'(.-)\''
obj._CDATA = '<%!%[CDATA%[(.-)%]%]>'
obj._PI = '<%?(.-)%?>'
obj._COMMENT = '<!%-%-(.-)%-%->'
obj._TAG = '^(.-)%s.*'
obj._LEADINGWS = '^%s+'
obj._TRAILINGWS = '%s+$'
obj._WS = '^%s*$'
obj._DTD1 = '<!DOCTYPE%s+(.-)%s+(SYSTEM)%s+["\'](.-)["\']%s*(%b[])%s*>'
obj._DTD2 = '<!DOCTYPE%s+(.-)%s+(PUBLIC)%s+["\'](.-)["\']%s+["\'](.-)["\']%s*(%b[])%s*>'
obj._DTD3 = '<!DOCTYPE%s+(.-)%s*(%b[])%s*>'
obj._DTD4 = '<!DOCTYPE%s+(.-)%s+(SYSTEM)%s+["\'](.-)["\']%s*>'
obj._DTD5 = '<!DOCTYPE%s+(.-)%s+(PUBLIC)%s+["\'](.-)["\']%s+["\'](.-)["\']%s*>'
obj._ATTRERR1 = '=%s*"[^"]*$'
obj._ATTRERR2 = '=%s*\'[^\']*$'
obj._TAGEXT = '(%/?)>'
obj._ENTITIES = { ["<"] = "<",
[">"] = ">",
["&"] = "&",
["""] = '"',
["'"] = "'",
["&#(%d+);"] = function (x)
local d = tonumber(x)
if d >= 0 and d < 256 then
return string.char(d)
else
return "&#"..d..";"
end
end,
["&#x(%x+);"] = function (x)
local d = tonumber(x,16)
if d >= 0 and d < 256 then
return string.char(d)
else
return "&#x"..x..";"
end
end,
}
obj._err = function(self,err,pos)
if self.options.errorHandler then
self.options.errorHandler(err,pos)
end
end
obj._errstr = { xmlErr = "Error Parsing XML",
declErr = "Error Parsing XMLDecl",
declStartErr = "XMLDecl not at start of document",
declAttrErr = "Invalid XMLDecl attributes",
piErr = "Error Parsing Processing Instruction",
commentErr = "Error Parsing Comment",
cdataErr = "Error Parsing CDATA",
dtdErr = "Error Parsing DTD",
endTagErr = "End Tag Attributes Invalid",
unmatchedTagErr = "Unbalanced Tag",
incompleteXmlErr = "Incomplete XML Document",
}
obj._stripWS = function(self,s)
if self.options.stripWS then
s = string.gsub(s,'^%s+','')
s = string.gsub(s,'%s+$','')
end
return s
end
obj._parseEntities = function(self,s)
if self.options.expandEntities then
--for k,v in self._ENTITIES do
for k,v in pairs(self._ENTITIES) do
--print (k, v)
s = string.gsub(s,k,v)
end
end
return s
end
obj._parseDTD = function(self,s,pos)
-- match,endmatch,root,type,name,uri,internal
local m,e,r,t,n,u,i
m,e,r,t,u,i = string.find(s,self._DTD1,pos)
if m then
return m,e,{_root=r,_type=t,_uri=u,_internal=i}
end
m,e,r,t,n,u,i = string.find(s,self._DTD2,pos)
if m then
return m,e,{_root=r,_type=t,_name=n,_uri=u,_internal=i}
end
m,e,r,i = string.find(s,self._DTD3,pos)
if m then
return m,e,{_root=r,_internal=i}
end
m,e,r,t,u = string.find(s,self._DTD4,pos)
if m then
return m,e,{_root=r,_type=t,_uri=u}
end
m,e,r,t,n,u = string.find(s,self._DTD5,pos)
if m then
return m,e,{_root=r,_type=t,_name=n,_uri=u}
end
return nil
end
---Parses a string representing a tag
--@param s String containing tag text
--@return Returns a string containing the tagname and a table attrs
--containing the atributtes of tag
obj._parseTag = function(self,s)
local attrs = {}
local tagname = string.gsub(s,self._TAG,'%1')
string.gsub(s,self._ATTR1,function (k,v)
attrs[string.lower(k)]=self:_parseEntities(v)
attrs._ = 1
end)
string.gsub(s,self._ATTR2,function (k,v)
attrs[string.lower(k)]=self:_parseEntities(v)
attrs._ = 1
end)
if attrs._ then
attrs._ = nil
else
attrs = nil
end
return tagname,attrs
end
return obj
end
return { xmlParser = xmlParser }
| agpl-3.0 |
tianxiawuzhei/cocos-quick-lua | quick/samples/coinflip/src/app/MyApp.lua | 8 | 1055 |
require("cocos.init")
require("config")
require("framework.init")
require("framework.shortcodes")
require("framework.cc.init")
local MyApp = class("MyApp", cc.mvc.AppBase)
function MyApp:ctor()
MyApp.super.ctor(self)
self.objects_ = {}
end
function MyApp:run()
cc.FileUtils:getInstance():addSearchPath("res/")
display.addSpriteFrames(GAME_TEXTURE_DATA_FILENAME, GAME_TEXTURE_IMAGE_FILENAME)
-- preload all sounds
for k, v in pairs(GAME_SFX) do
audio.preloadSound(v)
end
self:enterMenuScene()
end
function MyApp:enterMenuScene()
self:enterScene("MenuScene", nil, "fade", 0.6, display.COLOR_WHITE)
end
function MyApp:enterMoreGamesScene()
self:enterScene("MoreGamesScene", nil, "fade", 0.6, display.COLOR_WHITE)
end
function MyApp:enterChooseLevelScene()
self:enterScene("ChooseLevelScene", nil, "fade", 0.6, display.COLOR_WHITE)
end
function MyApp:playLevel(levelIndex)
self:enterScene("PlayLevelScene", {levelIndex}, "fade", 0.6, display.COLOR_WHITE)
end
appInstance = MyApp
return MyApp
| mit |
arventwei/WioEngine | Tools/jamplus/src/luaplus/Src/Modules/xavante/src/codeweb/codeWeb.lua | 1 | 2563 | -----------------------------------------------------------------------------
-- Xavante CodeWeb
--
-- Author: Javier Guerra
-- Copyright (c) 2005 Kepler Project
-----------------------------------------------------------------------------
local prep = require "cgilua.prep"
local httpd = require "xavante.httpd"
local _M = {}
-- Adds a module as a website;
-- each public function is registered as a page handler
-- host,urlpath : where to insert the handlers
-- m : table with functions, a module
-- register_as_tree: if true, each handler is registered as a directory too
function _M.addModule (host, urlpath, m, register_as_tree)
if m.__main then
httpd.addHandler (host, urlpath, m.__main)
end
for k,v in pairs (m) do
if type (k) == "string" and
string.sub (k,1,1) ~= "_" and
type (v) == "function"
then
local pth = urlpath.."/"..k
httpd.addHandler (host, pth, v)
if register_as_tree then
httpd.addHandler (host, pth.."/", v)
httpd.addHandler (host, pth.."/*", v)
end
end
end
end
-- Builds a handler from a template
-- the template (loaded from file 'fname') uses LuaPage syntax
-- and is converted to a function in the form: "function (req,res,...)"
-- if env is a table, the resulting function uses it as environment
-- if it's a function, it's environment is used
-- if it's a number, it select's the environment from the call stack
-- if ommited, 1 is implied, (the calling function's environment)
function _M.load_cw (fname, env)
env = env or 1
if type (env) == "function" then
env = getfenv (env)
elseif type (env) == "number" then
env = getfenv (env+1)
end
local fh = assert (io.open (fname))
local prog = fh:read("*a")
fh:close()
prep.setoutfunc ("res:send_data")
prog = prep.translate (prog, "file "..fname)
prog = "return function (req,res,...)\n" .. prog .. "\nend"
if prog then
local f, err = loadstring (prog, "@"..fname)
if f then
local f_cw = f()
if env then setfenv (f_cw, env) end
return f_cw
else
error (err)
end
end
end
| mit |
mqmaker/witi-openwrt | package/ramips/ui/luci-mtk/src/modules/admin-mini/luasrc/model/cbi/mini/network.lua | 82 | 6273 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local wa = require "luci.tools.webadmin"
local sys = require "luci.sys"
local fs = require "nixio.fs"
local has_pptp = fs.access("/usr/sbin/pptp")
local has_pppoe = fs.glob("/usr/lib/pppd/*/rp-pppoe.so")()
local network = luci.model.uci.cursor_state():get_all("network")
local netstat = sys.net.deviceinfo()
local ifaces = {}
for k, v in pairs(network) do
if v[".type"] == "interface" and k ~= "loopback" then
table.insert(ifaces, v)
end
end
m = Map("network", translate("Network"))
s = m:section(Table, ifaces, translate("Status"))
s.parse = function() end
s:option(DummyValue, ".name", translate("Network"))
hwaddr = s:option(DummyValue, "_hwaddr",
translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"), translate("Hardware Address"))
function hwaddr.cfgvalue(self, section)
local ix = self.map:get(section, "ifname") or ""
local mac = fs.readfile("/sys/class/net/" .. ix .. "/address")
if not mac then
mac = luci.util.exec("ifconfig " .. ix)
mac = mac and mac:match(" ([A-F0-9:]+)%s*\n")
end
if mac and #mac > 0 then
return mac:upper()
end
return "?"
end
s:option(DummyValue, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
s:option(DummyValue, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
txrx = s:option(DummyValue, "_txrx",
translate("Traffic"), translate("transmitted / received"))
function txrx.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][1]
rx = rx and wa.byte_format(tonumber(rx)) or "-"
local tx = netstat and netstat[ix] and netstat[ix][9]
tx = tx and wa.byte_format(tonumber(tx)) or "-"
return string.format("%s / %s", tx, rx)
end
errors = s:option(DummyValue, "_err",
translate("Errors"), translate("TX / RX"))
function errors.cfgvalue(self, section)
local ix = self.map:get(section, "ifname")
local rx = netstat and netstat[ix] and netstat[ix][3]
local tx = netstat and netstat[ix] and netstat[ix][11]
rx = rx and tostring(rx) or "-"
tx = tx and tostring(tx) or "-"
return string.format("%s / %s", tx, rx)
end
s = m:section(NamedSection, "lan", "interface", translate("Local Network"))
s.addremove = false
s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway") .. translate(" (optional)"))
gw.rmempty = true
dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server") .. translate(" (optional)"))
dns.rmempty = true
s = m:section(NamedSection, "wan", "interface", translate("Internet Connection"))
s.addremove = false
p = s:option(ListValue, "proto", translate("Protocol"))
p.override_values = true
p:value("none", "disabled")
p:value("static", translate("manual"))
p:value("dhcp", translate("automatic"))
if has_pppoe then p:value("pppoe", "PPPoE") end
if has_pptp then p:value("pptp", "PPTP") end
function p.write(self, section, value)
-- Always set defaultroute to PPP and use remote dns
-- Overwrite a bad variable behaviour in OpenWrt
if value == "pptp" or value == "pppoe" then
self.map:set(section, "peerdns", "1")
self.map:set(section, "defaultroute", "1")
end
return ListValue.write(self, section, value)
end
if not ( has_pppoe and has_pptp ) then
p.description = translate("You need to install \"ppp-mod-pppoe\" for PPPoE or \"pptp\" for PPtP support")
end
ip = s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
ip:depends("proto", "static")
nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm:depends("proto", "static")
gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway"))
gw:depends("proto", "static")
gw.rmempty = true
dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server"))
dns:depends("proto", "static")
dns.rmempty = true
usr = s:option(Value, "username", translate("Username"))
usr:depends("proto", "pppoe")
usr:depends("proto", "pptp")
pwd = s:option(Value, "password", translate("Password"))
pwd.password = true
pwd:depends("proto", "pppoe")
pwd:depends("proto", "pptp")
-- Allow user to set MSS correction here if the UCI firewall is installed
-- This cures some cancer for providers with pre-war routers
if fs.access("/etc/config/firewall") then
mssfix = s:option(Flag, "_mssfix",
translate("Clamp Segment Size"), translate("Fixes problems with unreachable websites, submitting forms or other unexpected behaviour for some ISPs."))
mssfix.rmempty = false
function mssfix.cfgvalue(self)
local value
m.uci:foreach("firewall", "forwarding", function(s)
if s.src == "lan" and s.dest == "wan" then
value = s.mtu_fix
end
end)
return value
end
function mssfix.write(self, section, value)
m.uci:foreach("firewall", "forwarding", function(s)
if s.src == "lan" and s.dest == "wan" then
m.uci:set("firewall", s[".name"], "mtu_fix", value)
m:chain("firewall")
end
end)
end
end
kea = s:option(Flag, "keepalive", translate("automatically reconnect"))
kea:depends("proto", "pppoe")
kea:depends("proto", "pptp")
kea.rmempty = true
kea.enabled = "10"
cod = s:option(Value, "demand", translate("disconnect when idle for"), "s")
cod:depends("proto", "pppoe")
cod:depends("proto", "pptp")
cod.rmempty = true
srv = s:option(Value, "server", translate("<abbr title=\"Point-to-Point Tunneling Protocol\">PPTP</abbr>-Server"))
srv:depends("proto", "pptp")
srv.rmempty = true
return m
| gpl-2.0 |
NSAKEY/prosody-modules | mod_mam/mod_mam.lua | 7 | 8099 | -- XEP-0313: Message Archive Management for Prosody
-- Copyright (C) 2011-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local xmlns_mam = "urn:xmpp:mam:0";
local xmlns_delay = "urn:xmpp:delay";
local xmlns_forward = "urn:xmpp:forward:0";
local st = require "util.stanza";
local rsm = module:require "rsm";
local get_prefs = module:require"mamprefs".get;
local set_prefs = module:require"mamprefs".set;
local prefs_to_stanza = module:require"mamprefsxml".tostanza;
local prefs_from_stanza = module:require"mamprefsxml".fromstanza;
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local dataform = require "util.dataforms".new;
local host = module.host;
local rm_load_roster = require "core.rostermanager".load_roster;
local getmetatable = getmetatable;
local function is_stanza(x)
return getmetatable(x) == st.stanza_mt;
end
local tostring = tostring;
local time_now = os.time;
local m_min = math.min;
local timestamp, timestamp_parse = require "util.datetime".datetime, require "util.datetime".parse;
local default_max_items, max_max_items = 20, module:get_option_number("max_archive_query_results", 50);
local global_default_policy = module:get_option("default_archive_policy", false);
if global_default_policy ~= "roster" then
global_default_policy = module:get_option_boolean("default_archive_policy", global_default_policy);
end
local archive_store = "archive2";
local archive = module:open_store(archive_store, "archive");
if not archive or archive.name == "null" then
module:log("error", "Could not open archive storage");
return
elseif not archive.find then
module:log("error", "mod_%s does not support archiving, switch to mod_storage_sql2", archive._provided_by);
return
end
-- Handle prefs.
module:hook("iq/self/"..xmlns_mam..":prefs", function(event)
local origin, stanza = event.origin, event.stanza;
local user = origin.username;
if stanza.attr.type == "get" then
local prefs = prefs_to_stanza(get_prefs(user));
local reply = st.reply(stanza):add_child(prefs);
return origin.send(reply);
else -- type == "set"
local new_prefs = stanza:get_child("prefs", xmlns_mam);
local prefs = prefs_from_stanza(new_prefs);
local ok, err = set_prefs(user, prefs);
if not ok then
return origin.send(st.error_reply(stanza, "cancel", "internal-server-error", "Error storing preferences: "..tostring(err)));
end
return origin.send(st.reply(stanza));
end
end);
local query_form = dataform {
{ name = "FORM_TYPE"; type = "hidden"; value = xmlns_mam; };
{ name = "with"; type = "jid-single"; };
{ name = "start"; type = "text-single" };
{ name = "end"; type = "text-single"; };
};
-- Serve form
module:hook("iq-get/self/"..xmlns_mam..":query", function(event)
local origin, stanza = event.origin, event.stanza;
return origin.send(st.reply(stanza):add_child(query_form:form()));
end);
-- Handle archive queries
module:hook("iq-set/self/"..xmlns_mam..":query", function(event)
local origin, stanza = event.origin, event.stanza;
local query = stanza.tags[1];
local qid = query.attr.queryid;
-- Search query parameters
local qwith, qstart, qend;
local form = query:get_child("x", "jabber:x:data");
if form then
local err;
form, err = query_form:data(form);
if err then
return origin.send(st.error_reply(stanza, "modify", "bad-request", select(2, next(err))))
end
qwith, qstart, qend = form["with"], form["start"], form["end"];
qwith = qwith and jid_bare(qwith); -- dataforms does jidprep
end
if qstart or qend then -- Validate timestamps
local vstart, vend = (qstart and timestamp_parse(qstart)), (qend and timestamp_parse(qend))
if (qstart and not vstart) or (qend and not vend) then
origin.send(st.error_reply(stanza, "modify", "bad-request", "Invalid timestamp"))
return true
end
qstart, qend = vstart, vend;
end
module:log("debug", "Archive query, id %s with %s from %s until %s)",
tostring(qid), qwith or "anyone", qstart or "the dawn of time", qend or "now");
-- RSM stuff
local qset = rsm.get(query);
local qmax = m_min(qset and qset.max or default_max_items, max_max_items);
local reverse = qset and qset.before or false;
local before, after = qset and qset.before, qset and qset.after;
if type(before) ~= "string" then before = nil; end
-- Load all the data!
local data, err = archive:find(origin.username, {
start = qstart; ["end"] = qend; -- Time range
with = qwith;
limit = qmax;
before = before; after = after;
reverse = reverse;
total = true;
});
if not data then
return origin.send(st.error_reply(stanza, "cancel", "internal-server-error", err));
end
local count = err;
origin.send(st.reply(stanza))
local msg_reply_attr = { to = stanza.attr.from, from = stanza.attr.to };
-- Wrap it in stuff and deliver
local fwd_st, first, last;
for id, item, when in data do
fwd_st = st.message(msg_reply_attr)
:tag("result", { xmlns = xmlns_mam, queryid = qid, id = id })
:tag("forwarded", { xmlns = xmlns_forward })
:tag("delay", { xmlns = xmlns_delay, stamp = timestamp(when) }):up();
if not is_stanza(item) then
item = st.deserialize(item);
end
item.attr.xmlns = "jabber:client";
fwd_st:add_child(item);
if not first then first = id; end
last = id;
origin.send(fwd_st);
end
-- That's all folks!
module:log("debug", "Archive query %s completed", tostring(qid));
if reverse then first, last = last, first; end
return origin.send(st.message(msg_reply_attr)
:tag("fin", { xmlns = xmlns_mam, queryid = qid })
:add_child(rsm.generate {
first = first, last = last, count = count }));
end);
local function has_in_roster(user, who)
local roster = rm_load_roster(user, host);
module:log("debug", "%s has %s in roster? %s", user, who, roster[who] and "yes" or "no");
return roster[who];
end
local function shall_store(user, who)
-- TODO Cache this?
local prefs = get_prefs(user);
local rule = prefs[who];
module:log("debug", "%s's rule for %s is %s", user, who, tostring(rule))
if rule ~= nil then
return rule;
else -- Below could be done by a metatable
local default = prefs[false];
module:log("debug", "%s's default rule is %s", user, tostring(default))
if default == nil then
default = global_default_policy;
module:log("debug", "Using global default rule, %s", tostring(default))
end
if default == "roster" then
return has_in_roster(user, who);
end
return default;
end
end
-- Handle messages
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type or "normal";
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to or orig_from;
-- Stanza without 'to' are treated as if it was to their own bare jid
-- We don't store messages of these types
if orig_type == "error"
or orig_type == "headline"
or orig_type == "groupchat"
-- or that don't have a <body/>
or not stanza:get_child("body")
-- or if hints suggest we shouldn't
or stanza:get_child("no-permanent-store", "urn:xmpp:hints")
or stanza:get_child("no-store", "urn:xmpp:hints") then
module:log("debug", "Not archiving stanza: %s (content)", stanza:top_tag());
return;
end
-- Whos storage do we put it in?
local store_user = c2s and origin.username or jid_split(orig_to);
-- And who are they chatting with?
local with = jid_bare(c2s and orig_to or orig_from);
-- Check with the users preferences
if shall_store(store_user, with) then
module:log("debug", "Archiving stanza: %s", stanza:top_tag());
-- And stash it
local ok, id = archive:append(store_user, nil, time_now(), with, stanza);
else
module:log("debug", "Not archiving stanza: %s (prefs)", stanza:top_tag());
end
end
local function c2s_message_handler(event)
return message_handler(event, true);
end
-- Stanzas sent by local clients
module:hook("pre-message/bare", c2s_message_handler, 2);
module:hook("pre-message/full", c2s_message_handler, 2);
-- Stanszas to local clients
module:hook("message/bare", message_handler, 2);
module:hook("message/full", message_handler, 2);
module:add_feature(xmlns_mam);
| mit |
bizkut/BudakJahat | Rotations/Old/old_BalanceFengshen.lua | 1 | 24893 | local rotationName = "Fengshen"
---------------
--- Toggles ---
---------------
local function createToggles() -- Define custom toggles
-- Rotation Button
RotationModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of targets in range.", highlight = 1, icon = br.player.spell.solarWrath },
[2] = { mode = "Sing", value = 2 , overlay = "Single Target Rotation", tip = "Single target rotation used.", highlight = 1, icon = br.player.spell.starsurge }
};
CreateButton("Rotation",1,0)
-- Cooldown Button
CooldownModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.celestialAlignment },
[2] = { mode = "On", value = 1 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.celestialAlignment },
[3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.celestialAlignment }
};
CreateButton("Cooldown",2,0)
-- Defensive Button
DefensiveModes = {
[1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.barkskin },
[2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.barkskin }
};
CreateButton("Defensive",3,0)
-- Interrupt Button
InterruptModes = {
[1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.solarBeam },
[2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.solarBeam }
};
CreateButton("Interrupt",4,0)
-- Starsurge AstralPower Button
StarsurgeAstralPowerModes = {
[1] = { mode = "40", value = 1 , overlay = "Astral Power to 40 Cast Starsurge", tip = "Astral Power to 40 Cast Starsurge", highlight = 1, icon = br.player.spell.starsurge },
[2] = { mode = "90", value = 2 , overlay = "Astral Power to 90 Cast Starsurge", tip = "Astral Power to 90 Cast Starsurge", highlight = 1, icon = br.player.spell.starfall }
};
CreateButton("StarsurgeAstralPower",5,0)
end
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
local section
-- General Options
section = br.ui:createSection(br.ui.window.profile, "General")
-- Farm Mode
br.ui:createCheckbox(section, "Farm Mode")
-- Pre-Pull Timer
br.ui:createSpinner(section, "Pre-Pull Timer", 2.5, 0, 10, 0.5, "|cffFFFFFFSet to desired time to start Pre-Pull (DBM Required). Min: 1 / Max: 10 / Interval: 1")
-- Travel Shapeshifts
br.ui:createCheckbox(section,"Auto Shapeshifts","|cff15FF00Enables|cffFFFFFF/|cffD60000Disables |cffFFFFFFAuto Shapeshifting to form for situation|cffFFBB00.")
-- Auto Soothe
br.ui:createCheckbox(section, "Auto Soothe")
-- Revive
br.ui:createCheckbox(section, "Revive")
-- Starfall priority
br.ui:createSpinner(section, "Starfall priority", 5, 0, 10, 1, "","|cffFFFFFFMinimum Starfall priority Targets")
-- Starfall
br.ui:createSpinner(section, "Starfall", 3, 0, 10, 1, "","|cffFFFFFFMinimum Starfall Targets")
-- Innervate
br.ui:createDropdown(section, "Innervate",br.dropOptions.Toggle,1, "","Set hotkey to use Innervate on Mouseover")
br.ui:checkSectionState(section)
-- Defensive Options
section = br.ui:createSection(br.ui.window.profile, "Defensive")
br.ui:createSpinner(section, "Potion/Healthstone", 20, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinner(section, "Renewal", 25, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinner(section, "Barkskin", 60, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinner(section, "inCombat Regrowth", 30, 0, 100, 5, "Health Percent to Cast At")
br.ui:createSpinner(section, "OOC Regrowth", 80, 0, 100, 5, "Health Percent to Cast At")
br.ui:createDropdown(section, "Rebirth", {"|cff00FF00Target","|cffFF0000Mouseover","|cffFFBB00Any"}, 1, "|cffFFFFFFTarget to cast on")
br.ui:createDropdown(section, "Remove Corruption", {"|cff00FF00Player Only","|cffFFFF00Selected Target","|cffFFFFFFPlayer and Target","|cffFF0000Mouseover Target","|cffFFFFFFAny"}, 3, "","|ccfFFFFFFTarget to Cast On")
br.ui:checkSectionState(section)
-- Interrupts Options
section = br.ui:createSection(br.ui.window.profile, "Interrupts")
br.ui:createCheckbox(section, "Solar Beam")
br.ui:createCheckbox(section, "Mighty Bash")
br.ui:createSpinner(section, "InterruptAt", 50, 0, 100, 5, "","|cffFFBB00Cast Percentage to use at.")
br.ui:checkSectionState(section)
-- Cooldown Options
section = br.ui:createSection(br.ui.window.profile, "Cooldown")
br.ui:createDropdown(section,"Trinkets 1", {"|cffFFFFFFNormal","|cffFFFFFFGround"}, 1, "","|cffFFFFFFSelect Trinkets mode.")
br.ui:createDropdown(section,"Trinkets 2", {"|cffFFFFFFNormal","|cffFFFFFFGround"}, 1, "","|cffFFFFFFSelect Trinkets mode.")
br.ui:createCheckbox(section,"Racial")
br.ui:createCheckbox(section,"Warrior of Elune")
br.ui:createCheckbox(section,"Incarnation")
br.ui:createCheckbox(section,"Celestial Alignment")
br.ui:createCheckbox(section,"Fury of Elune")
br.ui:createCheckbox(section,"Force of Nature")
br.ui:checkSectionState(section)
end
optionTable = {{
[1] = "Rotation Options",
[2] = rotationOptions,
}}
return optionTable
end
----------------
--- ROTATION ---
----------------
local function runRotation()
-- if br.timer:useTimer("debugBalance", 0.1) then
--Print("Running: "..rotationName)
---------------
--- Toggles --- -- List toggles here in order to update when pressed
---------------
UpdateToggle("Rotation",0.25)
UpdateToggle("Cooldown",0.25)
UpdateToggle("Defensive",0.25)
UpdateToggle("Interrupt",0.25)
UpdateToggle("StarsurgeAstralPower",0.25)
br.player.mode.rotation = br.data.settings[br.selectedSpec].toggles["Rotation"]
br.player.mode.starsurgeAstralPower = br.data.settings[br.selectedSpec].toggles["StarsurgeAstralPower"]
--------------
--- Locals ---
--------------
local buff = br.player.buff
local cast = br.player.cast
local deadtar, attacktar, hastar, playertar = deadtar or UnitIsDeadOrGhost("target"), attacktar or UnitCanAttack("target", "player"), hastar or GetObjectExists("target"), UnitIsPlayer("target")
local resable = UnitIsPlayer("target") and UnitIsDeadOrGhost("target") and GetUnitIsFriend("target","player") and UnitInRange("target")
local debuff = br.player.debuff
local enemies = br.player.enemies
local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), isMoving("player") ~= false or br.player.moving
local gcd = br.player.gcd
local inCombat = isInCombat("player")
local inInstance = br.player.instance=="party"
local inRaid = br.player.instance=="raid"
local level = br.player.level
local lowestHP = br.friend[1].unit
local mode = br.player.mode
local php = br.player.health
local power, powmax, powgen, powerDeficit = br.player.power.mana.amount, br.player.power.mana.max(), br.player.power.mana.regen(), br.player.power.mana.deficit()
local pullTimer = br.DBM:getPulltimer()
local racial = br.player.getRacial()
local spell = br.player.spell
local talent = br.player.talent
local ttd = getTTD
local units = br.player.units
local trait = br.player.traits
local race = br.player.race
-- Balance Locals
local astralPower = br.player.power.astralPower.amount()
local astralPowerDeficit = br.player.power.astralPower.deficit()
local travel = br.player.buff.travelForm.exists()
local flight = br.player.buff.flightForm.exists()
local chicken = br.player.buff.moonkinForm.exists()
local cat = br.player.buff.catForm.exists()
local bear = br.player.buff.bearForm.exists()
local noform = GetShapeshiftForm()==0
local hasteAmount = 1/(1+(GetHaste()/100))
local latency = getLatency()
local starfallPlacement = "playerGround"
local starfallAstralPower = 50
local starfallRadius = 12
units.get(40)
enemies.get(8,"target")
enemies.get(12,"target")
enemies.get(15,"target")
enemies.get(45, "player", true)
enemies.get(45)
if leftCombat == nil then leftCombat = GetTime() end
if profileStop == nil then profileStop = false end
local function FutureAstralPower()
if isCastingSpell() then
return astralPower
else
if isCastingSpell(spell.newMoon) then
return astralPower + 10
elseif isCastingSpell(spell.halfMoon) then
return astralPower + 20
elseif isCastingSpell(spell.fullMoon) then
return astralPower + 40
elseif isCastingSpell(spell.stellarFlare) then
return astralPower + 8
elseif isCastingSpell(spell.solarWrath) then
return astralPower + 8
elseif isCastingSpell(spell.lunarStrike) then
return astralPower + 12
else
return astralPower
end
end
end
if talent.stellarDrift then
starfallRadius = 15
end
if talent.soulOfTheForest then
starfallAstralPower = 40
end
if mode.starsurgeAstralPower == 1 then
starsurgeAstralPower = 40
elseif mode.starsurgeAstralPower == 2 then
starsurgeAstralPower = starfallAstralPower + 40
end
if isChecked("Farm Mode") and not travel then
for i = 1, #enemies.yards45nc do
local thisUnit = enemies.yards45nc[i]
if not UnitExists("target") or not getFacing("player","target") or UnitIsDeadOrGhost("target") then
if getFacing("player",thisUnit) then
TargetUnit(thisUnit)
end
if not inCombat then
if castSpell(thisUnit,spell.moonfire,true,false,false,true,false,true,true,false) then return true end
end
end
end
end
--------------------
--- Action Lists ---
--------------------
local function actionList_OOC()
-- Pre-Pull Timer
if isChecked("Pre-Pull Timer") then
if PullTimerRemain() <= getOptionValue("Pre-Pull Timer") then
if cast.solarWrath() then return true end
end
end
-- Revive
if isChecked("Revive") and not moving and resable then
if cast.revive("target","dead") then return true end
end
-- Regrowth
if isChecked("OOC Regrowth") and not moving and php <= getValue("OOC Regrowth") then
if cast.regrowth("player") then return true end
end
if isChecked("Auto Shapeshifts") then
-- Flight Form
if IsFlyableArea() and ((not (isInDraenor() or isInLegion())) or isKnown(191633)) and not swimming and falling > 1 and level>=58 then
if cast.travelForm("player") then return true end
end
-- Travel Form
if not inCombat and swimming and not travel and not hastar and not deadtar and not buff.prowl.exists() then
if cast.travelForm("player") then return true end
end
if not inCombat and moving and not travel and not IsMounted() and not IsIndoors() then
if cast.travelForm("player") then return true end
end
-- Cat Form
if cast.able.travelForm() and not cat and not IsMounted() then
-- Cat Form when not swimming or flying or stag and not in combat
if not inCombat and moving and not swimming and not flying and not travel and not isValidUnit("target") then
if cast.catForm("player") then return true end
end
end
end
end
local function actionList_main()
-- Innervate
if isChecked("Innervate") and SpecificToggle("Innervate") and not GetCurrentKeyBoardFocus() then
if cast.innervate("mouseover") then return true end
end
-- Rebirth
if isChecked("Rebirth") and not moving then
if getOptionValue("Rebirth") == 1
and UnitIsPlayer("target") and UnitIsDeadOrGhost("target") and GetUnitIsFriend("target","player") then
if cast.rebirth("target","dead") then return true end
end
if getOptionValue("Rebirth") == 2
and UnitIsPlayer("mouseover") and UnitIsDeadOrGhost("mouseover") and GetUnitIsFriend("mouseover","player") then
if cast.rebirth("mouseover","dead") then return true end
end
if getOptionValue("Rebirth") == 3 then
for i =1, #br.friend do
if UnitIsPlayer(br.friend[i].unit) and UnitIsDeadOrGhost(br.friend[i].unit) and GetUnitIsFriend(br.friend[i].unit,"player") then
if cast.rebirth(br.friend[i].unit,"dead") then return true end
end
end
end
end
-- Make sure we're in moonkin form if we're not in another form
if not chicken then
if cast.moonkinForm() then return true end
end
-- Defensive
if useDefensive() then
--Potion or Stone
if isChecked("Potion/Healthstone") and php <= getValue("Potion/Healthstone") then
if canUseItem(5512) then
useItem(5512)
elseif canUseItem(getHealthPot()) then
useItem(getHealthPot())
end
end
-- Renewal
if isChecked("Renewal") and cast.able.renewal() and php <= getValue("Renewal") then
if cast.renewal("player") then return end
end
-- Barkskin
if isChecked("Barkskin") and cast.able.barkskin() and php <= getValue("Barkskin") then
if cast.barkskin() then return end
end
-- Regrowth
if isChecked("inCombat Regrowth") and not moving and php <= getValue("inCombat Regrowth") then
if cast.regrowth("player") then return true end
end
-- Remove Corruption
if isChecked("Remove Corruption") and cast.able.removeCorruption() then
if getOptionValue("Remove Corruption")==1 then
if canDispel("player",spell.removeCorruption) then
if cast.removeCorruption("player") then return true end
end
elseif getOptionValue("Remove Corruption")==2 then
if canDispel("target",spell.removeCorruption) then
if cast.removeCorruption("target") then return true end
end
elseif getOptionValue("Remove Corruption")==3 then
if canDispel("player",spell.removeCorruption) or canDispel("target",spell.removeCorruption) then
if cast.removeCorruption("target") then return true end
end
elseif getOptionValue("Remove Corruption")==4 then
if canDispel("mouseover",spell.removeCorruption) then
if cast.removeCorruption("mouseover") then return true end
end
elseif getOptionValue("Remove Corruption")==5 then
for i = 1, #br.friend do
if canDispel(br.friend[i].unit,spell.removeCorruption) then
if cast.removeCorruption(br.friend[i].unit) then return true end
end
end
end
end
end
-- Interrupts
if useInterrupts() then
for i = 1, #enemies.yards45 do
local thisUnit = enemies.yards45[i]
if canInterrupt(thisUnit,getValue("InterruptAt")) then
-- Solar Beam
if isChecked("Solar Beam") and cast.able.solarBeam() then
if cast.solarBeam(thisUnit) then return end
end
-- Mighty Bash
if isChecked("Mighty Bash") and talent.mightyBash and cast.able.mightyBash() and getDistance(thisUnit) <= 10 then
if cast.mightyBash(thisUnit) then return true end
end
end
end
end
if isChecked("Auto Soothe") and cast.able.soothe() then
for i=1, #enemies.yards45 do
local thisUnit = enemies.yards45[i]
if canDispel(thisUnit, spell.soothe) then
if cast.soothe(thisUnit) then return true end
end
end
end
-- Cooldowns
if useCDs() then
-- Trinkets
if isChecked("Trinkets 1") and canUseItem(13) then
if getOptionValue("Trinkets 1") == 1 then
if useItem(13) then return true end
elseif getOptionValue("Trinkets 1") == 2 then
if useItemGround("target",13,40,0,nil) then return true end
end
end
if isChecked("Trinkets 2") and canUseItem(14) then
if getOptionValue("Trinkets 2") == 1 then
if useItem(14) then return true end
elseif getOptionValue("Trinkets 2") == 2 then
if useItemGround("target",14,40,0,nil) then return true end
end
end
-- Racial
if isChecked("Racial") and cast.able.racial() and (buff.celestialAlignment.exists() or buff.incarnationChoseOfElune.exists() and (race == "Orc" or race == "Troll" or race == "LightforgedDraenei")) then
if cast.racial() then return end
end
-- Warrior of Elune
if isChecked("Warrior of Elune") and cast.able.warriorOfElune() and talent.warriorOfElune then
if cast.warriorOfElune("player") then return true end
end
-- Incarnation
if isChecked("Incarnation") and cast.able.incarnationChoseOfElune() and talent.incarnationChoseOfElune and (FutureAstralPower() >= 40) then
if cast.incarnationChoseOfElune("player") then return true end
end
-- Celestial Alignment
if isChecked("Celestial Alignment") and not talent.incarnationChoseOfElune and cast.able.celestialAlignment() and (FutureAstralPower() >= 40) then
if cast.celestialAlignment("player") then return true end
end
-- Fury of Elune
if isChecked("Fury of Elune") and talent.furyOfElune and cast.able.furyOfElune() then
if cast.furyOfElune("target") then return true end
end
-- Force of Nature
if isChecked("Force of Nature") and not moving and talent.forceOfNature and cast.able.forceOfNature() then
if cast.forceOfNature("best") then return true end
end
end
if mode.rotation ~= 2 and isChecked("Starfall priority") and not moving and (not buff.starlord.exists() or buff.starlord.remain() >= 4) and FutureAstralPower() >= starfallAstralPower then
if cast.starfall("best", false, getValue("Starfall priority"), starfallRadius) then return true end
end
if FutureAstralPower() >= 95 and getFacing("player", "target") then
if cast.starsurge() then return true end
end
-- Apply Moonfire and Sunfire to all targets that will live longer than six seconds
if mode.rotation ~= 2 then
for i = 1, #enemies.yards45 do
local thisUnit = enemies.yards45[i]
if astralPowerDeficit >= 7 and debuff.sunfire.remain(thisUnit) < 5.4 and ttd(thisUnit) > 5.4 and (not buff.celestialAlignment.exists() and not buff.incarnationChoseOfElune.exists() or not cast.last.sunfire()) then
if castSpell(thisUnit,spell.sunfire,true,false,false,true,false,true,true,false) then return true end
elseif astralPowerDeficit >= 7 and debuff.moonfire.remain(thisUnit) < 6.6 and ttd(thisUnit) > 6.6 and (not buff.celestialAlignment.exists() and not buff.incarnationChoseOfElune.exists() or not cast.last.moonfire()) then
if castSpell(thisUnit,spell.moonfire,true,false,false,true,false,true,true,false) then return true end
elseif talent.stellarFlare and astralPowerDeficit >= 12 and debuff.stellarFlare.remain(thisUnit) < 7.2 and ttd(thisUnit) > 7.2 and (not buff.celestialAlignment.exists() and not buff.incarnationChoseOfElune.exists() or not cast.last.stellarFlare()) then
if castSpell(thisUnit,spell.stellarFlare,true,false,false,true,false,true,true,false) then return true end
end
end
end
if mode.rotation == 2 then
if astralPowerDeficit >= 7 and debuff.sunfire.remain("target") < 5.4 and ttd("target") > 5.4 and (not buff.celestialAlignment.exists() and not buff.incarnationChoseOfElune.exists() or not cast.last.sunfire()) then
if cast.sunfire("target") then return true end
elseif astralPowerDeficit >= 7 and debuff.moonfire.remain("target") < 6.6 and ttd("target") > 6.6 and (not buff.celestialAlignment.exists() and not buff.incarnationChoseOfElune.exists() or not cast.last.moonfire()) then
if cast.moonfire("target") then return true end
elseif astralPowerDeficit >= 12 and debuff.stellarFlare.remain("target") < 7.2 and ttd("target") > 7.2 and (not buff.celestialAlignment.exists() and not buff.incarnationChoseOfElune.exists() or not cast.last.stellarFlare()) then
if cast.stellarFlare("target") then return true end
end
end
-- Rotations
if not moving and not isChecked("Farm Mode") then
if astralPowerDeficit >= 16 and (buff.lunarEmpowerment.stack() == 3 or (#enemies.yards8t < 3 and astralPower >= 40 and buff.lunarEmpowerment.stack() == 2 and buff.solarEmpowerment.stack() == 2)) then
if cast.lunarStrike() then return true end
end
if astralPowerDeficit >= 12 and buff.solarEmpowerment.stack() == 3 then
if cast.solarWrath() then return true end
end
end
if mode.rotation ~= 2 and isChecked("Starfall") and not moving and (not buff.starlord.exists() or buff.starlord.remain() >= 4) and FutureAstralPower() >= starfallAstralPower then
if cast.starfall("best", false, getValue("Starfall"), starfallRadius) then return true end
end
if getFacing("player", "target") and (#enemies.yards45 < getValue("Starfall") or mode.rotation == 2) and (not buff.starlord.exists() or buff.starlord.remain() >= 4 or (gcd * (FutureAstralPower() / starsurgeAstralPower)) > ttd()) and FutureAstralPower() >= starsurgeAstralPower then
if cast.starsurge() then return true end
end
if not isChecked("Farm Mode") then
if talent.newMoon and not moving then
if astralPowerDeficit > 10 + (getCastTime(spell.newMoon) / 1.5) then
if cast.newMoon() then return true end
end
if astralPowerDeficit > 20 + (getCastTime(spell.halfMoon) / 1.5) then
if cast.halfMoon() then return true end
end
if astralPowerDeficit > 40 + (getCastTime(spell.fullMoon) / 1.5) then
if cast.fullMoon() then return true end
end
end
if buff.warriorOfElune.exists() or buff.owlkinFrenzy.exists() then
if cast.lunarStrike() then return true end
end
if not moving and #enemies.yards8t >= 2 then
-- Cleave situation: prioritize lunar strike empower > solar wrath empower > lunar strike
if buff.lunarEmpowerment.exists() and not (buff.lunarEmpowerment.stack() == 1 and isCastingSpell(spell.lunarStrike)) then
if cast.lunarStrike() then return true end
end
if buff.solarEmpowerment.exists() and not (buff.solarEmpowerment.stack() == 1 and isCastingSpell(spell.solarWrath)) then
if cast.solarWrath() then return true end
end
if cast.able.solarWrath() then
if cast.lunarStrike() then return true end
end
elseif not moving then
-- ST situation: prioritize solar wrath empower > lunar strike empower > solar wrath
if buff.solarEmpowerment.exists() and not (buff.solarEmpowerment.stack() == 1 and isCastingSpell(spell.solarWrath)) then
if cast.solarWrath() then return true end
end
if buff.lunarEmpowerment.exists() and not (buff.lunarEmpowerment.stack() == 1 and isCastingSpell(spell.lunarStrike)) then
if cast.lunarStrike() then return true end
end
if cast.able.solarWrath() then
if cast.solarWrath() then return true end
end
end
end
if moving or not getFacing("player", "target") then
if castSpell("target",spell.moonfire,true,false,false,true,false,true,true,false) then return true end
end
end
-----------------
--- Rotations ---
-----------------
-- Pause
if pause() or mode.rotation == 4 or buff.shadowmeld.exists() or buff.prowl.exists() then
return true
else
---------------------------------
--- Out Of Combat - Rotations ---
---------------------------------
if not inCombat then
if actionList_OOC() then return end
end -- End Out of Combat Rotation
-----------------------------
--- In Combat - Rotations ---
-----------------------------
if inCombat and not travel then
if actionList_main() then return end
end -- End In Combat Rotation
end -- Pause
-- end -- End Timer
end -- End runRotation
--local id = 102
local id = 0
if br.rotations[id] == nil then br.rotations[id] = {} end
tinsert(br.rotations[id],{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation,
})
| gpl-3.0 |
onerain88/SLuaLib | build/luajit-2.1.0/src/jit/dis_arm.lua | 78 | 19363 | ----------------------------------------------------------------------------
-- LuaJIT ARM disassembler module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- It disassembles most user-mode ARMv7 instructions
-- NYI: Advanced SIMD and VFP instructions.
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local concat = table.concat
local bit = require("bit")
local band, bor, ror, tohex = bit.band, bit.bor, bit.ror, bit.tohex
local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
------------------------------------------------------------------------------
-- Opcode maps
------------------------------------------------------------------------------
local map_loadc = {
shift = 8, mask = 15,
[10] = {
shift = 20, mask = 1,
[0] = {
shift = 23, mask = 3,
[0] = "vmovFmDN", "vstmFNdr",
_ = {
shift = 21, mask = 1,
[0] = "vstrFdl",
{ shift = 16, mask = 15, [13] = "vpushFdr", _ = "vstmdbFNdr", }
},
},
{
shift = 23, mask = 3,
[0] = "vmovFDNm",
{ shift = 16, mask = 15, [13] = "vpopFdr", _ = "vldmFNdr", },
_ = {
shift = 21, mask = 1,
[0] = "vldrFdl", "vldmdbFNdr",
},
},
},
[11] = {
shift = 20, mask = 1,
[0] = {
shift = 23, mask = 3,
[0] = "vmovGmDN", "vstmGNdr",
_ = {
shift = 21, mask = 1,
[0] = "vstrGdl",
{ shift = 16, mask = 15, [13] = "vpushGdr", _ = "vstmdbGNdr", }
},
},
{
shift = 23, mask = 3,
[0] = "vmovGDNm",
{ shift = 16, mask = 15, [13] = "vpopGdr", _ = "vldmGNdr", },
_ = {
shift = 21, mask = 1,
[0] = "vldrGdl", "vldmdbGNdr",
},
},
},
_ = {
shift = 0, mask = 0 -- NYI ldc, mcrr, mrrc.
},
}
local map_vfps = {
shift = 6, mask = 0x2c001,
[0] = "vmlaF.dnm", "vmlsF.dnm",
[0x04000] = "vnmlsF.dnm", [0x04001] = "vnmlaF.dnm",
[0x08000] = "vmulF.dnm", [0x08001] = "vnmulF.dnm",
[0x0c000] = "vaddF.dnm", [0x0c001] = "vsubF.dnm",
[0x20000] = "vdivF.dnm",
[0x24000] = "vfnmsF.dnm", [0x24001] = "vfnmaF.dnm",
[0x28000] = "vfmaF.dnm", [0x28001] = "vfmsF.dnm",
[0x2c000] = "vmovF.dY",
[0x2c001] = {
shift = 7, mask = 0x1e01,
[0] = "vmovF.dm", "vabsF.dm",
[0x0200] = "vnegF.dm", [0x0201] = "vsqrtF.dm",
[0x0800] = "vcmpF.dm", [0x0801] = "vcmpeF.dm",
[0x0a00] = "vcmpzF.d", [0x0a01] = "vcmpzeF.d",
[0x0e01] = "vcvtG.dF.m",
[0x1000] = "vcvt.f32.u32Fdm", [0x1001] = "vcvt.f32.s32Fdm",
[0x1800] = "vcvtr.u32F.dm", [0x1801] = "vcvt.u32F.dm",
[0x1a00] = "vcvtr.s32F.dm", [0x1a01] = "vcvt.s32F.dm",
},
}
local map_vfpd = {
shift = 6, mask = 0x2c001,
[0] = "vmlaG.dnm", "vmlsG.dnm",
[0x04000] = "vnmlsG.dnm", [0x04001] = "vnmlaG.dnm",
[0x08000] = "vmulG.dnm", [0x08001] = "vnmulG.dnm",
[0x0c000] = "vaddG.dnm", [0x0c001] = "vsubG.dnm",
[0x20000] = "vdivG.dnm",
[0x24000] = "vfnmsG.dnm", [0x24001] = "vfnmaG.dnm",
[0x28000] = "vfmaG.dnm", [0x28001] = "vfmsG.dnm",
[0x2c000] = "vmovG.dY",
[0x2c001] = {
shift = 7, mask = 0x1e01,
[0] = "vmovG.dm", "vabsG.dm",
[0x0200] = "vnegG.dm", [0x0201] = "vsqrtG.dm",
[0x0800] = "vcmpG.dm", [0x0801] = "vcmpeG.dm",
[0x0a00] = "vcmpzG.d", [0x0a01] = "vcmpzeG.d",
[0x0e01] = "vcvtF.dG.m",
[0x1000] = "vcvt.f64.u32GdFm", [0x1001] = "vcvt.f64.s32GdFm",
[0x1800] = "vcvtr.u32FdG.m", [0x1801] = "vcvt.u32FdG.m",
[0x1a00] = "vcvtr.s32FdG.m", [0x1a01] = "vcvt.s32FdG.m",
},
}
local map_datac = {
shift = 24, mask = 1,
[0] = {
shift = 4, mask = 1,
[0] = {
shift = 8, mask = 15,
[10] = map_vfps,
[11] = map_vfpd,
-- NYI cdp, mcr, mrc.
},
{
shift = 8, mask = 15,
[10] = {
shift = 20, mask = 15,
[0] = "vmovFnD", "vmovFDn",
[14] = "vmsrD",
[15] = { shift = 12, mask = 15, [15] = "vmrs", _ = "vmrsD", },
},
},
},
"svcT",
}
local map_loadcu = {
shift = 0, mask = 0, -- NYI unconditional CP load/store.
}
local map_datacu = {
shift = 0, mask = 0, -- NYI unconditional CP data.
}
local map_simddata = {
shift = 0, mask = 0, -- NYI SIMD data.
}
local map_simdload = {
shift = 0, mask = 0, -- NYI SIMD load/store, preload.
}
local map_preload = {
shift = 0, mask = 0, -- NYI preload.
}
local map_media = {
shift = 20, mask = 31,
[0] = false,
{ --01
shift = 5, mask = 7,
[0] = "sadd16DNM", "sasxDNM", "ssaxDNM", "ssub16DNM",
"sadd8DNM", false, false, "ssub8DNM",
},
{ --02
shift = 5, mask = 7,
[0] = "qadd16DNM", "qasxDNM", "qsaxDNM", "qsub16DNM",
"qadd8DNM", false, false, "qsub8DNM",
},
{ --03
shift = 5, mask = 7,
[0] = "shadd16DNM", "shasxDNM", "shsaxDNM", "shsub16DNM",
"shadd8DNM", false, false, "shsub8DNM",
},
false,
{ --05
shift = 5, mask = 7,
[0] = "uadd16DNM", "uasxDNM", "usaxDNM", "usub16DNM",
"uadd8DNM", false, false, "usub8DNM",
},
{ --06
shift = 5, mask = 7,
[0] = "uqadd16DNM", "uqasxDNM", "uqsaxDNM", "uqsub16DNM",
"uqadd8DNM", false, false, "uqsub8DNM",
},
{ --07
shift = 5, mask = 7,
[0] = "uhadd16DNM", "uhasxDNM", "uhsaxDNM", "uhsub16DNM",
"uhadd8DNM", false, false, "uhsub8DNM",
},
{ --08
shift = 5, mask = 7,
[0] = "pkhbtDNMU", false, "pkhtbDNMU",
{ shift = 16, mask = 15, [15] = "sxtb16DMU", _ = "sxtab16DNMU", },
"pkhbtDNMU", "selDNM", "pkhtbDNMU",
},
false,
{ --0a
shift = 5, mask = 7,
[0] = "ssatDxMu", "ssat16DxM", "ssatDxMu",
{ shift = 16, mask = 15, [15] = "sxtbDMU", _ = "sxtabDNMU", },
"ssatDxMu", false, "ssatDxMu",
},
{ --0b
shift = 5, mask = 7,
[0] = "ssatDxMu", "revDM", "ssatDxMu",
{ shift = 16, mask = 15, [15] = "sxthDMU", _ = "sxtahDNMU", },
"ssatDxMu", "rev16DM", "ssatDxMu",
},
{ --0c
shift = 5, mask = 7,
[3] = { shift = 16, mask = 15, [15] = "uxtb16DMU", _ = "uxtab16DNMU", },
},
false,
{ --0e
shift = 5, mask = 7,
[0] = "usatDwMu", "usat16DwM", "usatDwMu",
{ shift = 16, mask = 15, [15] = "uxtbDMU", _ = "uxtabDNMU", },
"usatDwMu", false, "usatDwMu",
},
{ --0f
shift = 5, mask = 7,
[0] = "usatDwMu", "rbitDM", "usatDwMu",
{ shift = 16, mask = 15, [15] = "uxthDMU", _ = "uxtahDNMU", },
"usatDwMu", "revshDM", "usatDwMu",
},
{ --10
shift = 12, mask = 15,
[15] = {
shift = 5, mask = 7,
"smuadNMS", "smuadxNMS", "smusdNMS", "smusdxNMS",
},
_ = {
shift = 5, mask = 7,
[0] = "smladNMSD", "smladxNMSD", "smlsdNMSD", "smlsdxNMSD",
},
},
false, false, false,
{ --14
shift = 5, mask = 7,
[0] = "smlaldDNMS", "smlaldxDNMS", "smlsldDNMS", "smlsldxDNMS",
},
{ --15
shift = 5, mask = 7,
[0] = { shift = 12, mask = 15, [15] = "smmulNMS", _ = "smmlaNMSD", },
{ shift = 12, mask = 15, [15] = "smmulrNMS", _ = "smmlarNMSD", },
false, false, false, false,
"smmlsNMSD", "smmlsrNMSD",
},
false, false,
{ --18
shift = 5, mask = 7,
[0] = { shift = 12, mask = 15, [15] = "usad8NMS", _ = "usada8NMSD", },
},
false,
{ --1a
shift = 5, mask = 3, [2] = "sbfxDMvw",
},
{ --1b
shift = 5, mask = 3, [2] = "sbfxDMvw",
},
{ --1c
shift = 5, mask = 3,
[0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", },
},
{ --1d
shift = 5, mask = 3,
[0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", },
},
{ --1e
shift = 5, mask = 3, [2] = "ubfxDMvw",
},
{ --1f
shift = 5, mask = 3, [2] = "ubfxDMvw",
},
}
local map_load = {
shift = 21, mask = 9,
{
shift = 20, mask = 5,
[0] = "strtDL", "ldrtDL", [4] = "strbtDL", [5] = "ldrbtDL",
},
_ = {
shift = 20, mask = 5,
[0] = "strDL", "ldrDL", [4] = "strbDL", [5] = "ldrbDL",
}
}
local map_load1 = {
shift = 4, mask = 1,
[0] = map_load, map_media,
}
local map_loadm = {
shift = 20, mask = 1,
[0] = {
shift = 23, mask = 3,
[0] = "stmdaNR", "stmNR",
{ shift = 16, mask = 63, [45] = "pushR", _ = "stmdbNR", }, "stmibNR",
},
{
shift = 23, mask = 3,
[0] = "ldmdaNR", { shift = 16, mask = 63, [61] = "popR", _ = "ldmNR", },
"ldmdbNR", "ldmibNR",
},
}
local map_data = {
shift = 21, mask = 15,
[0] = "andDNPs", "eorDNPs", "subDNPs", "rsbDNPs",
"addDNPs", "adcDNPs", "sbcDNPs", "rscDNPs",
"tstNP", "teqNP", "cmpNP", "cmnNP",
"orrDNPs", "movDPs", "bicDNPs", "mvnDPs",
}
local map_mul = {
shift = 21, mask = 7,
[0] = "mulNMSs", "mlaNMSDs", "umaalDNMS", "mlsDNMS",
"umullDNMSs", "umlalDNMSs", "smullDNMSs", "smlalDNMSs",
}
local map_sync = {
shift = 20, mask = 15, -- NYI: brackets around N. R(D+1) for ldrexd/strexd.
[0] = "swpDMN", false, false, false,
"swpbDMN", false, false, false,
"strexDMN", "ldrexDN", "strexdDN", "ldrexdDN",
"strexbDMN", "ldrexbDN", "strexhDN", "ldrexhDN",
}
local map_mulh = {
shift = 21, mask = 3,
[0] = { shift = 5, mask = 3,
[0] = "smlabbNMSD", "smlatbNMSD", "smlabtNMSD", "smlattNMSD", },
{ shift = 5, mask = 3,
[0] = "smlawbNMSD", "smulwbNMS", "smlawtNMSD", "smulwtNMS", },
{ shift = 5, mask = 3,
[0] = "smlalbbDNMS", "smlaltbDNMS", "smlalbtDNMS", "smlalttDNMS", },
{ shift = 5, mask = 3,
[0] = "smulbbNMS", "smultbNMS", "smulbtNMS", "smulttNMS", },
}
local map_misc = {
shift = 4, mask = 7,
-- NYI: decode PSR bits of msr.
[0] = { shift = 21, mask = 1, [0] = "mrsD", "msrM", },
{ shift = 21, mask = 3, "bxM", false, "clzDM", },
{ shift = 21, mask = 3, "bxjM", },
{ shift = 21, mask = 3, "blxM", },
false,
{ shift = 21, mask = 3, [0] = "qaddDMN", "qsubDMN", "qdaddDMN", "qdsubDMN", },
false,
{ shift = 21, mask = 3, "bkptK", },
}
local map_datar = {
shift = 4, mask = 9,
[9] = {
shift = 5, mask = 3,
[0] = { shift = 24, mask = 1, [0] = map_mul, map_sync, },
{ shift = 20, mask = 1, [0] = "strhDL", "ldrhDL", },
{ shift = 20, mask = 1, [0] = "ldrdDL", "ldrsbDL", },
{ shift = 20, mask = 1, [0] = "strdDL", "ldrshDL", },
},
_ = {
shift = 20, mask = 25,
[16] = { shift = 7, mask = 1, [0] = map_misc, map_mulh, },
_ = {
shift = 0, mask = 0xffffffff,
[bor(0xe1a00000)] = "nop",
_ = map_data,
}
},
}
local map_datai = {
shift = 20, mask = 31, -- NYI: decode PSR bits of msr. Decode imm12.
[16] = "movwDW", [20] = "movtDW",
[18] = { shift = 0, mask = 0xf00ff, [0] = "nopv6", _ = "msrNW", },
[22] = "msrNW",
_ = map_data,
}
local map_branch = {
shift = 24, mask = 1,
[0] = "bB", "blB"
}
local map_condins = {
[0] = map_datar, map_datai, map_load, map_load1,
map_loadm, map_branch, map_loadc, map_datac
}
-- NYI: setend.
local map_uncondins = {
[0] = false, map_simddata, map_simdload, map_preload,
false, "blxB", map_loadcu, map_datacu,
}
------------------------------------------------------------------------------
local map_gpr = {
[0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc",
}
local map_cond = {
[0] = "eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc",
"hi", "ls", "ge", "lt", "gt", "le", "al",
}
local map_shift = { [0] = "lsl", "lsr", "asr", "ror", }
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local pos = ctx.pos
local extra = ""
if ctx.rel then
local sym = ctx.symtab[ctx.rel]
if sym then
extra = "\t->"..sym
elseif band(ctx.op, 0x0e000000) ~= 0x0a000000 then
extra = "\t; 0x"..tohex(ctx.rel)
end
end
if ctx.hexdump > 0 then
ctx.out(format("%08x %s %-5s %s%s\n",
ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
else
ctx.out(format("%08x %-5s %s%s\n",
ctx.addr+pos, text, concat(operands, ", "), extra))
end
ctx.pos = pos + 4
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
end
-- Format operand 2 of load/store opcodes.
local function fmtload(ctx, op, pos)
local base = map_gpr[band(rshift(op, 16), 15)]
local x, ofs
local ext = (band(op, 0x04000000) == 0)
if not ext and band(op, 0x02000000) == 0 then
ofs = band(op, 4095)
if band(op, 0x00800000) == 0 then ofs = -ofs end
if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end
ofs = "#"..ofs
elseif ext and band(op, 0x00400000) ~= 0 then
ofs = band(op, 15) + band(rshift(op, 4), 0xf0)
if band(op, 0x00800000) == 0 then ofs = -ofs end
if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end
ofs = "#"..ofs
else
ofs = map_gpr[band(op, 15)]
if ext or band(op, 0xfe0) == 0 then
elseif band(op, 0xfe0) == 0x60 then
ofs = format("%s, rrx", ofs)
else
local sh = band(rshift(op, 7), 31)
if sh == 0 then sh = 32 end
ofs = format("%s, %s #%d", ofs, map_shift[band(rshift(op, 5), 3)], sh)
end
if band(op, 0x00800000) == 0 then ofs = "-"..ofs end
end
if ofs == "#0" then
x = format("[%s]", base)
elseif band(op, 0x01000000) == 0 then
x = format("[%s], %s", base, ofs)
else
x = format("[%s, %s]", base, ofs)
end
if band(op, 0x01200000) == 0x01200000 then x = x.."!" end
return x
end
-- Format operand 2 of vector load/store opcodes.
local function fmtvload(ctx, op, pos)
local base = map_gpr[band(rshift(op, 16), 15)]
local ofs = band(op, 255)*4
if band(op, 0x00800000) == 0 then ofs = -ofs end
if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end
if ofs == 0 then
return format("[%s]", base)
else
return format("[%s, #%d]", base, ofs)
end
end
local function fmtvr(op, vr, sh0, sh1)
if vr == "s" then
return format("s%d", 2*band(rshift(op, sh0), 15)+band(rshift(op, sh1), 1))
else
return format("d%d", band(rshift(op, sh0), 15)+band(rshift(op, sh1-4), 16))
end
end
-- Disassemble a single instruction.
local function disass_ins(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
local op = bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0)
local operands = {}
local suffix = ""
local last, name, pat
local vr
ctx.op = op
ctx.rel = nil
local cond = rshift(op, 28)
local opat
if cond == 15 then
opat = map_uncondins[band(rshift(op, 25), 7)]
else
if cond ~= 14 then suffix = map_cond[cond] end
opat = map_condins[band(rshift(op, 25), 7)]
end
while type(opat) ~= "string" do
if not opat then return unknown(ctx) end
opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._
end
name, pat = match(opat, "^([a-z0-9]*)(.*)")
if sub(pat, 1, 1) == "." then
local s2, p2 = match(pat, "^([a-z0-9.]*)(.*)")
suffix = suffix..s2
pat = p2
end
for p in gmatch(pat, ".") do
local x = nil
if p == "D" then
x = map_gpr[band(rshift(op, 12), 15)]
elseif p == "N" then
x = map_gpr[band(rshift(op, 16), 15)]
elseif p == "S" then
x = map_gpr[band(rshift(op, 8), 15)]
elseif p == "M" then
x = map_gpr[band(op, 15)]
elseif p == "d" then
x = fmtvr(op, vr, 12, 22)
elseif p == "n" then
x = fmtvr(op, vr, 16, 7)
elseif p == "m" then
x = fmtvr(op, vr, 0, 5)
elseif p == "P" then
if band(op, 0x02000000) ~= 0 then
x = ror(band(op, 255), 2*band(rshift(op, 8), 15))
else
x = map_gpr[band(op, 15)]
if band(op, 0xff0) ~= 0 then
operands[#operands+1] = x
local s = map_shift[band(rshift(op, 5), 3)]
local r = nil
if band(op, 0xf90) == 0 then
if s == "ror" then s = "rrx" else r = "#32" end
elseif band(op, 0x10) == 0 then
r = "#"..band(rshift(op, 7), 31)
else
r = map_gpr[band(rshift(op, 8), 15)]
end
if name == "mov" then name = s; x = r
elseif r then x = format("%s %s", s, r)
else x = s end
end
end
elseif p == "L" then
x = fmtload(ctx, op, pos)
elseif p == "l" then
x = fmtvload(ctx, op, pos)
elseif p == "B" then
local addr = ctx.addr + pos + 8 + arshift(lshift(op, 8), 6)
if cond == 15 then addr = addr + band(rshift(op, 23), 2) end
ctx.rel = addr
x = "0x"..tohex(addr)
elseif p == "F" then
vr = "s"
elseif p == "G" then
vr = "d"
elseif p == "." then
suffix = suffix..(vr == "s" and ".f32" or ".f64")
elseif p == "R" then
if band(op, 0x00200000) ~= 0 and #operands == 1 then
operands[1] = operands[1].."!"
end
local t = {}
for i=0,15 do
if band(rshift(op, i), 1) == 1 then t[#t+1] = map_gpr[i] end
end
x = "{"..concat(t, ", ").."}"
elseif p == "r" then
if band(op, 0x00200000) ~= 0 and #operands == 2 then
operands[1] = operands[1].."!"
end
local s = tonumber(sub(last, 2))
local n = band(op, 255)
if vr == "d" then n = rshift(n, 1) end
operands[#operands] = format("{%s-%s%d}", last, vr, s+n-1)
elseif p == "W" then
x = band(op, 0x0fff) + band(rshift(op, 4), 0xf000)
elseif p == "T" then
x = "#0x"..tohex(band(op, 0x00ffffff), 6)
elseif p == "U" then
x = band(rshift(op, 7), 31)
if x == 0 then x = nil end
elseif p == "u" then
x = band(rshift(op, 7), 31)
if band(op, 0x40) == 0 then
if x == 0 then x = nil else x = "lsl #"..x end
else
if x == 0 then x = "asr #32" else x = "asr #"..x end
end
elseif p == "v" then
x = band(rshift(op, 7), 31)
elseif p == "w" then
x = band(rshift(op, 16), 31)
elseif p == "x" then
x = band(rshift(op, 16), 31) + 1
elseif p == "X" then
x = band(rshift(op, 16), 31) - last + 1
elseif p == "Y" then
x = band(rshift(op, 12), 0xf0) + band(op, 0x0f)
elseif p == "K" then
x = "#0x"..tohex(band(rshift(op, 4), 0x0000fff0) + band(op, 15), 4)
elseif p == "s" then
if band(op, 0x00100000) ~= 0 then suffix = "s"..suffix end
else
assert(false)
end
if x then
last = x
if type(x) == "number" then x = "#"..x end
operands[#operands+1] = x
end
end
return putop(ctx, name..suffix, operands)
end
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
ctx.pos = ofs
ctx.rel = nil
while ctx.pos < stop do disass_ins(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = addr or 0
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 8
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 16 then return map_gpr[r] end
return "d"..(r-16)
end
-- Public module functions.
return {
create = create,
disass = disass,
regname = regname
}
| mit |
tianxiawuzhei/cocos-quick-lua | quick/framework/cc/ui/UIStretch.lua | 19 | 3491 |
--[[
Copyright (c) 2011-2014 chukong-inc.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--------------------------------
-- @module UIStretch
--[[--
quick 拉伸控件
]]
local UIStretch = class("UIStretch")
-- start --
--------------------------------
-- quick 拉伸控件
-- @function [parent=#UIStretch] new
-- end --
function UIStretch:ctor()
cc(self):addComponent("components.ui.LayoutProtocol"):exportMethods()
self:setLayoutSizePolicy(display.AUTO_SIZE, display.AUTO_SIZE)
self.position_ = {x = 0, y = 0}
self.anchorPoint_ = display.ANCHOR_POINTS[display.CENTER]
end
-- start --
--------------------------------
-- 得到位置信息
-- @function [parent=#UIStretch] getPosition
-- @return number#number x
-- @return number#number y
-- end --
function UIStretch:getPosition()
return self.position_.x, self.position_.y
end
-- start --
--------------------------------
-- 得到x位置信息
-- @function [parent=#UIStretch] getPositionX
-- @return number#number x
-- end --
function UIStretch:getPositionX()
return self.position_.x
end
-- start --
--------------------------------
-- 得到y位置信息
-- @function [parent=#UIStretch] getPositionY
-- @return number#number y
-- end --
function UIStretch:getPositionY()
return self.position_.y
end
-- start --
--------------------------------
-- 设置位置信息
-- @function [parent=#UIStretch] setPosition
-- @param number x x的位置
-- @param number y y的位置
-- end --
function UIStretch:setPosition(x, y)
self.position_.x, self.position_.y = x, y
end
-- start --
--------------------------------
-- 设置x位置信息
-- @function [parent=#UIStretch] setPositionX
-- @param number x x的位置
-- end --
function UIStretch:setPositionX(x)
self.position_.x = x
end
-- start --
--------------------------------
-- 设置y位置信息
-- @function [parent=#UIStretch] setPositionY
-- @param number y y的位置
-- end --
function UIStretch:setPositionY(y)
self.position_.y = y
end
-- start --
--------------------------------
-- 得到锚点位置信息
-- @function [parent=#UIStretch] getAnchorPoint
-- @return table#table 位置信息
-- end --
function UIStretch:getAnchorPoint()
return self.anchorPoint_
end
-- start --
--------------------------------
-- 设置锚点位置
-- @function [parent=#UIStretch] setAnchorPoint
-- @param ap 锚点
-- end --
function UIStretch:setAnchorPoint(ap)
self.anchorPoint_ = ap
end
return UIStretch
| mit |
stanfordhpccenter/soleil-x | testcases/legacy/taylor_with_smaller_particles/taylor_green_vortex_4096_2048_2048.lua | 1 | 4172 | -- This is a Lua config file for the Soleil code.
return {
xnum = 4096, -- number of cells in the x-direction
ynum = 2048, -- number of cells in the y-direction
znum = 2048, -- number of cells in the z-direction
-- if you increase the cell number and the calculation diverges
-- right away, decrease the time step on the next line
delta_time = 1.0e-4,
-- Control max iterations here. Set to a very high number if
-- you want to run the full calculation (it will stop once
-- it hits the 20.0 second max time set below)
max_iter = 20,
-- Output options. All output is off by default, but we
-- will need to turn it on to check results/make visualizations
consoleFrequency = 5, -- Iterations between console output of statistics
wrtRestart = 'OFF',
wrtVolumeSolution = 'OFF',
wrt1DSlice = 'OFF',
wrtParticleEvolution = 'OFF',
particleEvolutionIndex = 0,
outputEveryTimeSteps = 50,
restartEveryTimeSteps = 50,
-------------------------------------------
--[ SHOULD NOT NEED TO MODIFY BELOW HERE]--
-------------------------------------------
-- Flow Initialization Options --
initCase = 'TaylorGreen3DVortex', -- Uniform, Restart, TaylorGreen2DVortex, TaylorGreen3DVortex
initParams = {1.0,100.0,2.0,0.0,0.0}, -- for TGV: first three are density, pressure, velocity
bodyForce = {0,0.0,0}, -- body force in x, y, z
turbForcing = 'OFF', -- Turn turbulent forcing on or off
turbForceCoeff = 0.0, -- Turbulent linear forcing coefficient (f = A*rho*u)
restartIter = 10000,
-- Grid Options -- PERIODICITY
origin = {0.0, 0.0, 0.0}, -- spatial origin of the computational domain
xWidth = 6.283185307179586,
yWidth = 6.283185307179586,
zWidth = 6.283185307179586,
-- BCs on each boundary: 'periodic,' 'symmetry,' or 'wall'
xBCLeft = 'periodic',
xBCLeftVel = {0.0, 0.0, 0.0},
xBCLeftTemp = 0.0,
xBCRight = 'periodic',
xBCRightVel = {0.0, 0.0, 0.0},
xBCRightTemp = 0.0,
yBCLeft = 'periodic',
yBCLeftVel = {0.0, 0.0, 0.0},
yBCLeftTemp = 0.0,
yBCRight = 'periodic',
yBCRightVel = {0.0, 0.0, 0.0},
yBCRightTemp = 0.0,
zBCLeft = 'periodic',
zBCLeftVel = {0.0, 0.0, 0.0},
zBCLeftTemp = 0.0,
zBCRight = 'periodic',
zBCRightVel = {0.0, 0.0, 0.0},
zBCRightTemp = 0.0,
--Time Integration Options --
cfl = 1.0, -- Negative CFL implies that we will used fixed delta T
final_time = 20.00001,
--- File Output Options --
headerFrequency = 200000,
outputFormat = 'Tecplot', --Tecplot or Python
-- Fluid Options --
gasConstant = 20.4128,
gamma = 1.4,
viscosity_model = 'PowerLaw', -- Constant, PowerLaw, Sutherland
constant_visc = 0.004491, -- Value for a constant viscosity [kg/m/s]
powerlaw_visc_ref = 0.00044,
powerlaw_temp_ref = 1.0,
prandtl = 0.7,
suth_visc_ref = 1.716E-5, -- Sutherland's Law reference viscosity [kg/m/s]
suth_temp_ref = 273.15, -- Sutherland's Law reference temperature [K]
suth_s_ref = 110.4, -- Sutherland's Law S constant [K]
-- Particle Options --
-- completely disable particles, including all data
modeParticles = 'ON',
initParticles = 'Uniform', -- 'Random' or 'Restart'
restartParticleIter = 0,
particleType = 'Free', -- Fixed or Free
twoWayCoupling = 'OFF', -- ON or OFF
num = 1024000000,
restitutionCoefficient = 1.0,
convectiveCoefficient = 0.7, -- W m^-2 K^-1
heatCapacity = 0.7, -- J Kg^-1 K^-1
initialTemperature = 20, -- K
density = 8900, -- kg/m^3
diameter_mean = 5e-3, -- m
diameter_maxDeviation = 1e-3, -- m, for statistical distribution
bodyForceParticles = {0.0,0.0,0.0},
absorptivity = 1.0, -- Equal to emissivity in thermal equilibrium
maximum_num = 1024000000, -- upper bound on particles with insertion
insertion_rate = 0, -- per face and per time step
insertion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ
deletion_mode = {0,0,0,0,0,0}, --bool, MinX MaxX MinY MaxY MinZ MaxZ
-- (Kirchhoff law of thermal radiation)
-- Radiation Options --
radiationType = 'Algebraic', -- ON or OFF
radiationIntensity = 1e3,
zeroAvgHeatSource = 'OFF'
}
| gpl-2.0 |
mqmaker/witi-openwrt | package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_system/system.lua | 37 | 5651 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
require("luci.fs")
require("luci.config")
local m, s, o
local has_ntpd = luci.fs.access("/usr/sbin/ntpd")
m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone."))
m:chain("luci")
s = m:section(TypedSection, "system", translate("System Properties"))
s.anonymous = true
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("logging", translate("Logging"))
s:tab("language", translate("Language and Style"))
--
-- System Properties
--
o = s:taboption("general", DummyValue, "_systime", translate("Local Time"))
o.template = "admin_system/clock_status"
o = s:taboption("general", Value, "hostname", translate("Hostname"))
o.datatype = "hostname"
function o.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
o = s:taboption("general", ListValue, "zonename", translate("Timezone"))
o:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
o:value(zone[1])
end
function o.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
local timezone = lookup_zone(value) or "GMT0"
self.map.uci:set("system", section, "timezone", timezone)
luci.fs.writefile("/etc/TZ", timezone .. "\n")
end
--
-- Logging
--
o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB")
o.optional = true
o.placeholder = 16
o.datatype = "uinteger"
o = s:taboption("logging", Value, "log_ip", translate("External system log server"))
o.optional = true
o.placeholder = "0.0.0.0"
o.datatype = "ip4addr"
o = s:taboption("logging", Value, "log_port", translate("External system log server port"))
o.optional = true
o.placeholder = 514
o.datatype = "port"
o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level"))
o:value(8, translate("Debug"))
o:value(7, translate("Info"))
o:value(6, translate("Notice"))
o:value(5, translate("Warning"))
o:value(4, translate("Error"))
o:value(3, translate("Critical"))
o:value(2, translate("Alert"))
o:value(1, translate("Emergency"))
o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level"))
o.default = 8
o:value(5, translate("Debug"))
o:value(8, translate("Normal"))
o:value(9, translate("Warning"))
--
-- Langauge & Style
--
o = s:taboption("language", ListValue, "_lang", translate("Language"))
o:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then
o:value(k, v)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "lang")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "lang", value)
end
o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
o:value(v, k)
end
end
function o.cfgvalue(...)
return m.uci:get("luci", "main", "mediaurlbase")
end
function o.write(self, section, value)
m.uci:set("luci", "main", "mediaurlbase", value)
end
--
-- NTP
--
if has_ntpd then
-- timeserver setup was requested, create section and reload page
if m:formvalue("cbid.system._timeserver._enable") then
m.uci:section("system", "timeserver", "ntp",
{
server = { "0.openwrt.pool.ntp.org", "1.openwrt.pool.ntp.org", "2.openwrt.pool.ntp.org", "3.openwrt.pool.ntp.org" }
}
)
m.uci:save("system")
luci.http.redirect(luci.dispatcher.build_url("admin/system", arg[1]))
return
end
local has_section = false
m.uci:foreach("system", "timeserver",
function(s)
has_section = true
return false
end)
if not has_section then
s = m:section(TypedSection, "timeserver", translate("Time Synchronization"))
s.anonymous = true
s.cfgsections = function() return { "_timeserver" } end
x = s:option(Button, "_enable")
x.title = translate("Time Synchronization is not configured yet.")
x.inputtitle = translate("Set up Time Synchronization")
x.inputstyle = "apply"
else
s = m:section(TypedSection, "timeserver", translate("Time Synchronization"))
s.anonymous = true
s.addremove = false
o = s:option(Flag, "enable", translate("Enable NTP client"))
o.rmempty = false
function o.cfgvalue(self)
return luci.sys.init.enabled("sysntpd")
and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == self.enabled then
luci.sys.init.enable("sysntpd")
luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null")
else
luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null")
luci.sys.init.disable("sysntpd")
end
end
o = s:option(Flag, "enable_server", translate("Provide NTP server"))
o:depends("enable", "1")
o = s:option(DynamicList, "server", translate("NTP server candidates"))
o.datatype = "host"
o:depends("enable", "1")
-- retain server list even if disabled
function o.remove() end
end
end
return m
| gpl-2.0 |
bizkut/BudakJahat | Rotations/Priest/Holy/Blank.lua | 1 | 8783 | local rotationName = "None" -- Change to name of profile listed in options drop down
---------------
--- Toggles ---
---------------
local function createToggles() -- Define custom toggles
-- Rotation Button
RotationModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "Swaps between Single and Multiple based on number of #enemies.yards8 in range.", highlight = 0, icon = br.player.spell.whirlwind },
[2] = { mode = "Mult", value = 2 , overlay = "Multiple Target Rotation", tip = "Multiple target rotation used.", highlight = 0, icon = br.player.spell.bladestorm },
[3] = { mode = "Sing", value = 3 , overlay = "Single Target Rotation", tip = "Single target rotation used.", highlight = 0, icon = br.player.spell.furiousSlash },
[4] = { mode = "Off", value = 4 , overlay = "DPS Rotation Disabled", tip = "Disable DPS Rotation", highlight = 0, icon = br.player.spell.enragedRegeneration}
};
CreateButton("Rotation",1,0)
-- Cooldown Button
CooldownModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "Automatic Cooldowns - Boss Detection.", highlight = 1, icon = br.player.spell.battleCry },
[2] = { mode = "On", value = 2 , overlay = "Cooldowns Enabled", tip = "Cooldowns used regardless of target.", highlight = 0, icon = br.player.spell.battleCry },
[3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "No Cooldowns will be used.", highlight = 0, icon = br.player.spell.battleCry }
};
CreateButton("Cooldown",2,0)
-- Defensive Button
DefensiveModes = {
[1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "Includes Defensive Cooldowns.", highlight = 1, icon = br.player.spell.enragedRegeneration },
[2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "No Defensives will be used.", highlight = 0, icon = br.player.spell.enragedRegeneration }
};
CreateButton("Defensive",3,0)
-- Interrupt Button
InterruptModes = {
[1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "Includes Basic Interrupts.", highlight = 1, icon = br.player.spell.pummel },
[2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "No Interrupts will be used.", highlight = 0, icon = br.player.spell.pummel }
};
CreateButton("Interrupt",4,0)
end
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
-----------------------
--- GENERAL OPTIONS --- -- Define General Options
-----------------------
section = br.ui:createSection(br.ui.window.profile, "General")
br.ui:checkSectionState(section)
------------------------
--- COOLDOWN OPTIONS --- -- Define Cooldown Options
------------------------
section = br.ui:createSection(br.ui.window.profile, "Cooldowns")
br.ui:checkSectionState(section)
-------------------------
--- DEFENSIVE OPTIONS --- -- Define Defensive Options
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Defensive")
br.ui:checkSectionState(section)
-------------------------
--- INTERRUPT OPTIONS --- -- Define Interrupt Options
-------------------------
section = br.ui:createSection(br.ui.window.profile, "Interrupts")
-- Interrupt Percentage
br.ui:createSpinner(section, "InterruptAt", 0, 0, 95, 5, "|cffFFBB00Cast Percentage to use at.")
br.ui:checkSectionState(section)
----------------------
--- TOGGLE OPTIONS --- -- Degine Toggle Options
----------------------
section = br.ui:createSection(br.ui.window.profile, "Toggle Keys")
-- Single/Multi Toggle
br.ui:createDropdown(section, "Rotation Mode", br.dropOptions.Toggle, 4)
--Cooldown Key Toggle
br.ui:createDropdown(section, "Cooldown Mode", br.dropOptions.Toggle, 3)
--Defensive Key Toggle
br.ui:createDropdown(section, "Defensive Mode", br.dropOptions.Toggle, 6)
-- Interrupts Key Toggle
br.ui:createDropdown(section, "Interrupt Mode", br.dropOptions.Toggle, 6)
-- Pause Toggle
br.ui:createDropdown(section, "Pause Mode", br.dropOptions.Toggle, 6)
br.ui:checkSectionState(section)
end
optionTable = {{
[1] = "Rotation Options",
[2] = rotationOptions,
}}
return optionTable
end
----------------
--- ROTATION ---
----------------
local function runRotation()
if br.timer:useTimer("debugFury", 0.1) then --change "debugFury" to "debugSpec" (IE: debugFire)
--Print("Running: "..rotationName)
---------------
--- Toggles --- -- List toggles here in order to update when pressed
---------------
UpdateToggle("Rotation",0.25)
UpdateToggle("Cooldown",0.25)
UpdateToggle("Defensive",0.25)
UpdateToggle("Interrupt",0.25)
--------------
--- Locals ---
--------------
local artifact = br.player.artifact
local buff = br.player.buff
local cast = br.player.cast
local combatTime = getCombatTime()
local cd = br.player.cd
local charges = br.player.charges
local debuff = br.player.debuff
local enemies = br.player.enemies
local falling, swimming, flying, moving = getFallTime(), IsSwimming(), IsFlying(), GetUnitSpeed("player")>0
local gcd = br.player.gcd
local healPot = getHealthPot()
local inCombat = br.player.inCombat
local inInstance = br.player.instance=="party"
local inRaid = br.player.instance=="raid"
local level = br.player.level
local lowestHP = br.friend[1].unit
local mode = br.player.ui.mode
local perk = br.player.perk
local php = br.player.health
local power, powmax, powgen = br.player.power, br.player.powerMax, br.player.powerRegen
local pullTimer = br.DBM:getPulltimer()
local race = br.player.race
local racial = br.player.getRacial()
local spell = br.player.spell
local talent = br.player.talent
local ttm = br.player.timeToMax
local units = br.player.units
if leftCombat == nil then leftCombat = GetTime() end
if profileStop == nil then profileStop = false end
--------------------
--- Action Lists ---
--------------------
-----------------
--- Rotations ---
-----------------
-- Pause
if pause() or (UnitExists("target") and (UnitIsDeadOrGhost("target") or not UnitCanAttack("target", "player"))) or mode.rotation == 4 then
return true
else
---------------------------------
--- Out Of Combat - Rotations ---
---------------------------------
if not inCombat and GetObjectExists("target") and not UnitIsDeadOrGhost("target") and UnitCanAttack("target", "player") then
print("No up to date rotation found for this spec.")
end -- End Out of Combat Rotation
-----------------------------
--- In Combat - Rotations ---
-----------------------------
if inCombat then
print("No up to date rotation found for this spec.")
end -- End In Combat Rotation
end -- Pause
end -- End Timer
end -- End runRotation
--local id = 257 --Change to the spec id profile is for.
local id = 0
if br.rotations[id] == nil then br.rotations[id] = {} end
tinsert(br.rotations[id],{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation,
}) | gpl-3.0 |
philanc/plc | test/test_poly1305.lua | 1 | 2348 | -- Copyright (c) 2015 Phil Leblanc -- see LICENSE file
------------------------------------------------------------
local bin = require "plc.bin" -- used for hex conversions
-- test poly1305.lua
local poly = require "plc.poly1305"
local test_poly_auth = function ()
-- "nacl" test vector
local naclkey = string.char(
0xee,0xa6,0xa7,0x25,0x1c,0x1e,0x72,0x91,
0x6d,0x11,0xc2,0xcb,0x21,0x4d,0x3c,0x25,
0x25,0x39,0x12,0x1d,0x8e,0x23,0x4e,0x65,
0x2d,0x65,0x1f,0xa4,0xc8,0xcf,0xf8,0x80
)
local naclmsg = string.char(
0x8e,0x99,0x3b,0x9f,0x48,0x68,0x12,0x73,
0xc2,0x96,0x50,0xba,0x32,0xfc,0x76,0xce,
0x48,0x33,0x2e,0xa7,0x16,0x4d,0x96,0xa4,
0x47,0x6f,0xb8,0xc5,0x31,0xa1,0x18,0x6a,
0xc0,0xdf,0xc1,0x7c,0x98,0xdc,0xe8,0x7b,
0x4d,0xa7,0xf0,0x11,0xec,0x48,0xc9,0x72,
0x71,0xd2,0xc2,0x0f,0x9b,0x92,0x8f,0xe2,
0x27,0x0d,0x6f,0xb8,0x63,0xd5,0x17,0x38,
0xb4,0x8e,0xee,0xe3,0x14,0xa7,0xcc,0x8a,
0xb9,0x32,0x16,0x45,0x48,0xe5,0x26,0xae,
0x90,0x22,0x43,0x68,0x51,0x7a,0xcf,0xea,
0xbd,0x6b,0xb3,0x73,0x2b,0xc0,0xe9,0xda,
0x99,0x83,0x2b,0x61,0xca,0x01,0xb6,0xde,
0x56,0x24,0x4a,0x9e,0x88,0xd5,0xf9,0xb3,
0x79,0x73,0xf6,0x22,0xa4,0x3d,0x14,0xa6,
0x59,0x9b,0x1f,0x65,0x4c,0xb4,0x5a,0x74,
0xe3,0x55,0xa5
)
local naclmac = string.char(
0xf3,0xff,0xc7,0x70,0x3f,0x94,0x00,0xe5,
0x2a,0x7d,0xfb,0x4b,0x3d,0x33,0x05,0xd9
)
local mac = poly.auth(naclmsg, naclkey)
assert (mac == naclmac)
-- "wrap" test vector
-- generates a final value of (2^130 - 2) == 3
local wrapkey = string.char(
0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
)
local wrapmsg = string.char(
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
)
local wrapmac = string.char(
0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
)
mac = poly.auth(wrapmsg, wrapkey)
assert (mac == wrapmac)
-- rfc 7539 test vector
local rfcmsg = "Cryptographic Forum Research Group"
local rfckey = bin.hextos(
"85d6be7857556d337f4452fe42d506a80103808afb0db2fd4abff6af4149f51b")
local rfcmac = bin.hextos("a8061dc1305136c6c22b8baf0c0127a9")
mac = poly.auth(rfcmsg, rfckey)
assert (mac == rfcmac)
end
test_poly_auth()
print("test_poly1305: ok")
| mit |
kracwarlock/dp | xplog.lua | 7 | 3959 | ------------------------------------------------------------------------
--[[ XpLog ]]--
-- Interface, Composite of CollectionQueries
------------------------------------------------------------------------
local XpLog = torch.class("dp.XpLog")
XpLog.isXpLog = true
function XpLog:__init(...)
local args, name = xlua.unpack(
{... or {}},
'XpLog', nil,
{arg='name', type='string | number'}
)
self._entries = {}
self._collections = {}
end
function XpLog:collection(collection_name)
local collection = self._collections[collection_name]
if not collection then
collection = self:createCollection(collection_name)
self._collections[collection_name] = collection
end
if not collection then
print"Query:collection() Warning : collection not found"
end
return collection
end
function XpLog:collections(collection_names, separator)
if type(collection_names) == 'string' then
collection_names = _.split(collection_names, separator or ',')
end
return _.map(
collection_names,
function(c) return self:collection(c) end
)
end
function XpLog:entry(xp_id)
local entry = self._entries[xp_id]
if not entry then
entry = self:createEntry(xp_id)
self._entries[xp_id] = entry
end
return entry
end
function XpLog:createEntry(xp_id)
end
------------------------------------------------------------------------
--[[ XpLogEntry ]]--
------------------------------------------------------------------------
local XpLogEntry = torch.class("dp.XpLogEntry")
XpLogEntry.isXpLogEntry = true
function XpLogEntry:__init(...)
local args, id = xlua.unpack(
{... or {}},
'XpLogEntry', nil,
{arg='id', type='string | number', req=true}
)
self._id = id
self._reports = {}
self._dirty = true
end
function XpLogEntry:report(report_epoch)
local report = self._reports[report_epoch]
if (not report) then
self:sync()
return self._reports[report_epoch]
end
return report
end
function XpLogEntry:sync(...)
if self:dirty() then
self:refresh(...)
collectgarbage()
end
end
function XpLogEntry:refresh(...)
end
function XpLogEntry:dirty()
return self._dirty
end
function XpLogEntry:reports()
self:sync()
return self._reports
end
function XpLogEntry:hyperReport()
return self._hyper_report
end
function XpLogEntry:reportChannel(channel, reports)
reports = reports or self:reports()
if type(channel) == 'string' then
channel = _.split(channel, ':')
end
return table.channelValues(reports, channel), reports
end
function XpLogEntry:_plotReportChannel(...)
local args, channels, curve_names, x_name, y_name, hloc, vloc
= xlua.unpack(
{... or {}},
'XpLogEntry:plotReportChannel', nil,
{arg='channels', type='string | table', req=true},
{arg='curve_names', type='string | table'},
{arg='x_name', type='string', default='epoch'},
{arg='y_name', type='string'},
{arg='hloc', type='string', default='right'},
{arg='vloc', type='string', default='bottom'}
)
if type(channels) == 'string' then
channels = _.split(channels, ',')
end
if type(curve_names) == 'string' then
curve_names = _.split(curve_names, ',')
end
curve_names = curve_names or channels
local reports = self:reports()
local x = torch.Tensor(_.keys(reports))
local curves = {}
for i,channel in ipairs(channels) do
local values = self:reportChannel(channel, reports)
table.insert(
curves, { curve_names[i], x, torch.Tensor(values), '-' }
)
end
require 'gnuplot'
--gnuplot.xlabel(x_name)
--gnuplot.ylabel(y_name)
--gnuplot.movelegend(hloc,vloc)
return curves, x_name, y_name, x
end
function XpLogEntry:plotReportChannel(...)
local curves, x_name, y_name, x = self:_plotReportChannel(...)
if x:nElement() > 1 then
gnuplot.plot(unpack(curves))
end
end
| bsd-3-clause |
robert00s/koreader | frontend/apps/reader/modules/readerrolling.lua | 1 | 19487 | local Device = require("device")
local InputContainer = require("ui/widget/container/inputcontainer")
local Event = require("ui/event")
local ReaderPanning = require("apps/reader/modules/readerpanning")
local UIManager = require("ui/uimanager")
local logger = require("logger")
local _ = require("gettext")
local Input = Device.input
local Screen = Device.screen
--[[
Rolling is just like paging in page-based documents except that
sometimes (in scroll mode) there is no concept of page number to indicate
current progress.
There are three kind of progress measurements for credocuments.
1. page number (in page mode)
2. progress percentage (in scroll mode)
3. xpointer (in document dom structure)
We found that the first two measurements are not suitable for keeping a
record of the real progress. For example, when switching screen orientation
from portrait to landscape, or switching view mode from page to scroll, the
internal xpointer should not be used as the view dimen/mode is changed and
crengine's pagination mechanism will find a closest xpointer for the new view.
So if we change the screen orientation or view mode back, we cannot find the
original place since the internal xpointer is changed, which is counter-
intuitive as users didn't goto any other page.
The solution is that we keep a record of the internal xpointer and only change
it in explicit page turning. And use that xpointer for non-page-turning
rendering.
--]]
local ReaderRolling = InputContainer:new{
pan_rate = 30, -- default 30 ops, will be adjusted in readerui
old_doc_height = nil,
old_page = nil,
current_pos = 0,
inverse_reading_order = false,
-- only used for page view mode
current_page= nil,
doc_height = nil,
xpointer = nil,
panning_steps = ReaderPanning.panning_steps,
show_overlap_enable = nil,
overlap = 20,
}
function ReaderRolling:init()
if Device:hasKeyboard() or Device:hasKeys() then
self.key_events = {
GotoNextView = {
{ Input.group.PgFwd },
doc = "go to next view",
event = "GotoViewRel", args = 1
},
GotoPrevView = {
{ Input.group.PgBack },
doc = "go to previous view",
event = "GotoViewRel", args = -1
},
MoveUp = {
{ "Up" },
doc = "move view up",
event = "Panning", args = {0, -1}
},
MoveDown = {
{ "Down" },
doc = "move view down",
event = "Panning", args = {0, 1}
},
GotoFirst = {
{"1"}, doc = "go to start", event = "GotoPercent", args = 0},
Goto11 = {
{"2"}, doc = "go to 11%", event = "GotoPercent", args = 11},
Goto22 = {
{"3"}, doc = "go to 22%", event = "GotoPercent", args = 22},
Goto33 = {
{"4"}, doc = "go to 33%", event = "GotoPercent", args = 33},
Goto44 = {
{"5"}, doc = "go to 44%", event = "GotoPercent", args = 44},
Goto55 = {
{"6"}, doc = "go to 55%", event = "GotoPercent", args = 55},
Goto66 = {
{"7"}, doc = "go to 66%", event = "GotoPercent", args = 66},
Goto77 = {
{"8"}, doc = "go to 77%", event = "GotoPercent", args = 77},
Goto88 = {
{"9"}, doc = "go to 88%", event = "GotoPercent", args = 88},
GotoLast = {
{"0"}, doc = "go to end", event = "GotoPercent", args = 100},
}
end
table.insert(self.ui.postInitCallback, function()
self.doc_height = self.ui.document.info.doc_height
self.old_doc_height = self.doc_height
end)
self.ui.menu:registerToMainMenu(self)
end
function ReaderRolling:onReadSettings(config)
local last_xp = config:readSetting("last_xpointer")
local last_per = config:readSetting("last_percent")
if last_xp then
self.xpointer = last_xp
self.setupXpointer = function()
self:_gotoXPointer(self.xpointer)
-- we have to do a real jump in self.ui.document._document to
-- update status information in CREngine.
self.ui.document:gotoXPointer(self.xpointer)
end
-- we read last_percent just for backward compatibility
-- FIXME: remove this branch with migration script
elseif last_per then
self.setupXpointer = function()
self:_gotoPercent(last_per)
-- _gotoPercent calls _gotoPos, which only updates self.current_pos
-- and self.view.
-- we need to do a real pos change in self.ui.document._document
-- to update status information in CREngine.
self.ui.document:gotoPos(self.current_pos)
-- _gotoPercent already calls gotoPos, so no need to emit
-- PosUpdate event in scroll mode
if self.view.view_mode == "page" then
self.ui:handleEvent(
Event:new("PageUpdate", self.ui.document:getCurrentPage()))
end
self.xpointer = self.ui.document:getXPointer()
end
else
self.setupXpointer = function()
self.xpointer = self.ui.document:getXPointer()
if self.view.view_mode == "page" then
self.ui:handleEvent(Event:new("PageUpdate", 1))
end
end
end
self.show_overlap_enable = config:readSetting("show_overlap_enable")
if self.show_overlap_enable == nil then
self.show_overlap_enable = DSHOWOVERLAP
end
self.inverse_reading_order = config:readSetting("inverse_reading_order") or false
end
function ReaderRolling:onSaveSettings()
-- remove last_percent config since its deprecated
self.ui.doc_settings:saveSetting("last_percent", nil)
self.ui.doc_settings:saveSetting("last_xpointer", self.xpointer)
self.ui.doc_settings:saveSetting("percent_finished", self:getLastPercent())
self.ui.doc_settings:saveSetting("show_overlap_enable", self.show_overlap_enable)
self.ui.doc_settings:saveSetting("inverse_reading_order", self.inverse_reading_order)
end
function ReaderRolling:onReaderReady()
self:setupTouchZones()
self.setupXpointer()
end
function ReaderRolling:setupTouchZones()
self.ges_events = {}
self.onGesture = nil
if not Device:isTouchDevice() then return end
local forward_zone = {
ratio_x = DTAP_ZONE_FORWARD.x, ratio_y = DTAP_ZONE_FORWARD.y,
ratio_w = DTAP_ZONE_FORWARD.w, ratio_h = DTAP_ZONE_FORWARD.h,
}
local backward_zone = {
ratio_x = DTAP_ZONE_BACKWARD.x, ratio_y = DTAP_ZONE_BACKWARD.y,
ratio_w = DTAP_ZONE_BACKWARD.w, ratio_h = DTAP_ZONE_BACKWARD.h,
}
local forward_double_tap_zone = {
ratio_x = DDOUBLE_TAP_ZONE_NEXT_CHAPTER.x, ratio_y = DDOUBLE_TAP_ZONE_NEXT_CHAPTER.y,
ratio_w = DDOUBLE_TAP_ZONE_NEXT_CHAPTER.w, ratio_h = DDOUBLE_TAP_ZONE_NEXT_CHAPTER.h,
}
local backward_double_tap_zone = {
ratio_x = DDOUBLE_TAP_ZONE_PREV_CHAPTER.x, ratio_y = DDOUBLE_TAP_ZONE_PREV_CHAPTER.y,
ratio_w = DDOUBLE_TAP_ZONE_PREV_CHAPTER.w, ratio_h = DDOUBLE_TAP_ZONE_PREV_CHAPTER.h,
}
if self.inverse_reading_order then
forward_zone.ratio_x = 1 - forward_zone.ratio_x - forward_zone.ratio_w
backward_zone.ratio_x = 1 - backward_zone.ratio_x - backward_zone.ratio_w
forward_double_tap_zone.ratio_x =
1 - forward_double_tap_zone.ratio_x - forward_double_tap_zone.ratio_w
backward_double_tap_zone.ratio_x =
1 - backward_double_tap_zone.ratio_x - backward_double_tap_zone.ratio_w
end
self.ui:registerTouchZones({
{
id = "tap_forward",
ges = "tap",
screen_zone = forward_zone,
handler = function() return self:onTapForward() end
},
{
id = "tap_backward",
ges = "tap",
screen_zone = backward_zone,
handler = function() return self:onTapBackward() end
},
{
id = "double_tap_forward",
ges = "double_tap",
screen_zone = forward_double_tap_zone,
handler = function() return self:onDoubleTapForward() end
},
{
id = "double_tap_backward",
ges = "double_tap",
screen_zone = backward_double_tap_zone,
handler = function() return self:onDoubleTapBackward() end
},
{
id = "rolling_swipe",
ges = "swipe",
screen_zone = {
ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1,
},
handler = function(ges) return self:onSwipe(nil, ges) end
},
{
id = "rolling_pan",
ges = "pan",
rate = self.pan_rate,
screen_zone = {
ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1,
},
handler = function(ges) return self:onPan(nil, ges) end
},
})
end
function ReaderRolling:getLastProgress()
return self.xpointer
end
function ReaderRolling:addToMainMenu(menu_items)
-- FIXME: repeated code with page overlap menu for readerpaging
-- needs to keep only one copy of the logic as for the DRY principle.
-- The difference between the two menus is only the enabled func.
local page_overlap_menu = {
{
text_func = function()
return self.show_overlap_enable and _("Disable") or _("Enable")
end,
callback = function()
self.show_overlap_enable = not self.show_overlap_enable
if not self.show_overlap_enable then
self.view:resetDimArea()
end
end
},
}
for _, menu_entry in ipairs(self.view:genOverlapStyleMenu()) do
table.insert(page_overlap_menu, menu_entry)
end
menu_items.page_overlap = {
text = _("Page overlap"),
enabled_func = function() return self.view.view_mode ~= "page" end,
sub_item_table = page_overlap_menu,
}
end
function ReaderRolling:getLastPercent()
if self.view.view_mode == "page" then
if self.old_page then
return self.current_page / self.old_page
else
return nil
end
else
-- FIXME: the calculated percent is not accurate in "scroll" mode.
return self.ui.document:getPosFromXPointer(
self.ui.document:getXPointer()) / self.doc_height
end
end
function ReaderRolling:onTapForward()
self:onGotoViewRel(1)
return true
end
function ReaderRolling:onTapBackward()
self:onGotoViewRel(-1)
return true
end
function ReaderRolling:onSwipe(_, ges)
if ges.direction == "north" then
self:onGotoViewRel(1)
elseif ges.direction == "south" then
self:onGotoViewRel(-1)
elseif ges.direction == "west" then
if self.inverse_reading_order then
self:onGotoViewRel(-1)
else
self:onGotoViewRel(1)
end
elseif ges.direction == "east" then
if self.inverse_reading_order then
self:onGotoViewRel(1)
else
self:onGotoViewRel(-1)
end
else
-- update footer (time & battery)
self.view.footer:updateFooter()
-- trigger full refresh
UIManager:setDirty(nil, "full")
end
end
function ReaderRolling:onPan(_, ges)
if self.view.view_mode == "scroll" then
if ges.direction == "north" then
self:_gotoPos(self.current_pos + ges.distance)
elseif ges.direction == "south" then
self:_gotoPos(self.current_pos - ges.distance)
end
end
return true
end
function ReaderRolling:onPosUpdate(new_pos)
self.current_pos = new_pos
self:updateBatteryState()
end
function ReaderRolling:onPageUpdate(new_page)
self.current_page = new_page
self:updateBatteryState()
end
function ReaderRolling:onResume()
self:updateBatteryState()
end
function ReaderRolling:onDoubleTapForward()
local visible_page_count = self.ui.document:getVisiblePageCount()
local pageno = self.current_page + (visible_page_count > 1 and 1 or 0)
self:onGotoPage(self.ui.toc:getNextChapter(pageno, 0))
return true
end
function ReaderRolling:onDoubleTapBackward()
local pageno = self.current_page
self:onGotoPage(self.ui.toc:getPreviousChapter(pageno, 0))
return true
end
function ReaderRolling:onNotCharging()
self:updateBatteryState()
end
function ReaderRolling:onGotoPercent(percent)
logger.dbg("goto document offset in percent:", percent)
self:_gotoPercent(percent)
self.xpointer = self.ui.document:getXPointer()
return true
end
function ReaderRolling:onGotoPage(number)
if number then
self:_gotoPage(number)
end
self.xpointer = self.ui.document:getXPointer()
return true
end
function ReaderRolling:onGotoRelativePage(number)
if number then
self:_gotoPage(self.current_page + number)
end
self.xpointer = self.ui.document:getXPointer()
return true
end
function ReaderRolling:onGotoXPointer(xp)
self:_gotoXPointer(xp)
self.xpointer = xp
return true
end
function ReaderRolling:getBookLocation()
return self.xpointer
end
function ReaderRolling:onRestoreBookLocation(saved_location)
return self:onGotoXPointer(saved_location)
end
function ReaderRolling:onGotoViewRel(diff)
logger.dbg("goto relative screen:", diff, ", in mode: ", self.view.view_mode)
if self.view.view_mode == "scroll" then
local pan_diff = diff * self.ui.dimen.h
if self.show_overlap_enable then
if pan_diff > self.overlap then
pan_diff = pan_diff - self.overlap
elseif pan_diff < -self.overlap then
pan_diff = pan_diff + self.overlap
end
end
local old_pos = self.current_pos
self:_gotoPos(self.current_pos + pan_diff)
if diff > 0 and old_pos == self.current_pos then
self.ui:handleEvent(Event:new("EndOfBook"))
end
elseif self.view.view_mode == "page" then
local page_count = self.ui.document:getVisiblePageCount()
local old_page = self.current_page
self:_gotoPage(self.current_page + diff*page_count)
if diff > 0 and old_page == self.current_page then
self.ui:handleEvent(Event:new("EndOfBook"))
end
end
self.xpointer = self.ui.document:getXPointer()
return true
end
function ReaderRolling:onPanning(args, _)
--@TODO disable panning in page view_mode? 22.12 2012 (houqp)
local _, dy = unpack(args)
self:_gotoPos(self.current_pos + dy * self.panning_steps.normal)
self.xpointer = self.ui.document:getXPointer()
return true
end
function ReaderRolling:onZoom()
--@TODO re-read doc_height info after font or lineheight changes 05.06 2012 (houqp)
self:updatePos()
end
--[[
remember to signal this event when the document has been zoomed,
font has been changed, or line height has been changed.
Note that xpointer should not be changed.
--]]
function ReaderRolling:onUpdatePos()
UIManager:scheduleIn(0.1, function () self:updatePos() end)
return true
end
function ReaderRolling:updatePos()
-- reread document height
self.ui.document:_readMetadata()
-- update self.current_pos if the height of document has been changed.
local new_height = self.ui.document.info.doc_height
local new_page = self.ui.document.info.number_of_pages
if self.old_doc_height ~= new_height or self.old_page ~= new_page then
if self.old_page then
self:_gotoXPointer(self.xpointer)
end
self.old_doc_height = new_height
self.old_page = new_page
self.ui:handleEvent(Event:new("UpdateToc"))
end
UIManager:setDirty(self.view.dialog, "partial")
end
--[[
switching screen mode should not change current page number
--]]
function ReaderRolling:onChangeViewMode()
self.ui.document:_readMetadata()
self.old_doc_height = self.ui.document.info.doc_height
local old_page = self.old_page
self.old_page = self.ui.document.info.number_of_pages
self.ui:handleEvent(Event:new("UpdateToc"))
if self.xpointer and old_page then
self:_gotoXPointer(self.xpointer)
elseif self.xpointer == nil then
table.insert(self.ui.postInitCallback, function()
self:_gotoXPointer(self.xpointer)
end)
end
return true
end
function ReaderRolling:onRedrawCurrentView()
if self.view.view_mode == "page" then
self.ui:handleEvent(Event:new("PageUpdate", self.current_page))
else
self.ui:handleEvent(Event:new("PosUpdate", self.current_pos))
end
return true
end
function ReaderRolling:onSetDimensions(dimen)
self.ui.document:setViewDimen(Screen:getSize())
end
function ReaderRolling:onChangeScreenMode(mode)
self.ui:handleEvent(Event:new("SetScreenMode", mode))
self.ui.document:setViewDimen(Screen:getSize())
self:onChangeViewMode()
self:onUpdatePos()
end
--[[
PosUpdate event is used to signal other widgets that pos has been changed.
--]]
function ReaderRolling:_gotoPos(new_pos)
if new_pos == self.current_pos then return end
if new_pos < 0 then new_pos = 0 end
if new_pos > self.doc_height then new_pos = self.doc_height end
-- adjust dim_area according to new_pos
if self.view.view_mode ~= "page" and self.show_overlap_enable then
local panned_step = new_pos - self.current_pos
self.view.dim_area.x = 0
self.view.dim_area.h = self.ui.dimen.h - math.abs(panned_step)
self.view.dim_area.w = self.ui.dimen.w
if panned_step < 0 then
self.view.dim_area.y = self.ui.dimen.h - self.view.dim_area.h
elseif panned_step > 0 then
self.view.dim_area.y = 0
end
end
self.ui:handleEvent(Event:new("PosUpdate", new_pos))
end
function ReaderRolling:_gotoPercent(new_percent)
self:_gotoPos(new_percent * self.doc_height / 10000)
end
function ReaderRolling:_gotoPage(new_page)
self.ui.document:gotoPage(new_page)
self.ui:handleEvent(Event:new("PageUpdate", self.ui.document:getCurrentPage()))
end
function ReaderRolling:_gotoXPointer(xpointer)
if self.view.view_mode == "page" then
self:_gotoPage(self.ui.document:getPageFromXPointer(xpointer))
else
self:_gotoPos(self.ui.document:getPosFromXPointer(xpointer))
end
end
--[[
currently we don't need to get page links on each page/pos update
since we can check link on the fly when tapping on the screen
--]]
function ReaderRolling:updatePageLink()
logger.dbg("update page link")
local links = self.ui.document:getPageLinks()
self.view.links = links
end
function ReaderRolling:updateBatteryState()
logger.dbg("update battery state")
if self.view.view_mode == "page" then
local powerd = Device:getPowerDevice()
-- -1 is CR_BATTERY_STATE_CHARGING @ crengine/crengine/include/lvdocview.h
local state = powerd:isCharging() and -1 or powerd:getCapacity()
if state then
self.ui.document:setBatteryState(state)
end
end
end
return ReaderRolling
| agpl-3.0 |
silverhammermba/awesome | lib/menubar/utils.lua | 3 | 11022 | ---------------------------------------------------------------------------
--- Utility module for menubar
--
-- @author Antonio Terceiro
-- @copyright 2009, 2011-2012 Antonio Terceiro, Alexander Yakushev
-- @release @AWESOME_VERSION@
-- @module menubar.utils
---------------------------------------------------------------------------
-- Grab environment
local io = io
local table = table
local ipairs = ipairs
local string = string
local screen = screen
local awful_util = require("awful.util")
local theme = require("beautiful")
local lgi = require("lgi")
local gio = lgi.Gio
local glib = lgi.GLib
local wibox = require("wibox")
local debug = require("gears.debug")
local utils = {}
-- NOTE: This icons/desktop files module was written according to the
-- following freedesktop.org specifications:
-- Icons: http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-0.11.html
-- Desktop files: http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.0.html
-- Options section
--- Terminal which applications that need terminal would open in.
utils.terminal = 'xterm'
--- The default icon for applications that don't provide any icon in
-- their .desktop files.
local default_icon = nil
--- Name of the WM for the OnlyShownIn entry in the .desktop file.
utils.wm_name = "awesome"
-- Private section
local all_icon_sizes = {
'128x128' ,
'96x96',
'72x72',
'64x64',
'48x48',
'36x36',
'32x32',
'24x24',
'22x22',
'16x16'
}
--- List of supported icon formats.
local icon_formats = { "png", "xpm", "svg" }
--- Check whether the icon format is supported.
-- @param icon_file Filename of the icon.
-- @return true if format is supported, false otherwise.
local function is_format_supported(icon_file)
for _, f in ipairs(icon_formats) do
if icon_file:match('%.' .. f) then
return true
end
end
return false
end
local icon_lookup_path = nil
--- Get a list of icon lookup paths.
-- @treturn table A list of directories, without trailing slash.
local function get_icon_lookup_path()
if not icon_lookup_path then
local add_if_readable = function(t, path)
if awful_util.dir_readable(path) then
table.insert(t, path)
end
end
icon_lookup_path = {}
local icon_theme_paths = {}
local icon_theme = theme.icon_theme
local paths = glib.get_system_data_dirs()
table.insert(paths, 1, glib.get_user_data_dir())
table.insert(paths, 1, glib.build_filenamev({glib.get_home_dir(),
'.icons'}))
for _,dir in ipairs(paths) do
local icons_dir = glib.build_filenamev({dir, 'icons'})
if awful_util.dir_readable(icons_dir) then
if icon_theme then
add_if_readable(icon_theme_paths,
glib.build_filenamev({icons_dir,
icon_theme}))
end
-- Fallback theme.
add_if_readable(icon_theme_paths,
glib.build_filenamev({icons_dir, 'hicolor'}))
end
end
for _, icon_theme_directory in ipairs(icon_theme_paths) do
for _, size in ipairs(all_icon_sizes) do
add_if_readable(icon_lookup_path,
glib.build_filenamev({icon_theme_directory,
size, 'apps'}))
end
end
for _,dir in ipairs(paths)do
-- lowest priority fallbacks
add_if_readable(icon_lookup_path,
glib.build_filenamev({dir, 'pixmaps'}))
add_if_readable(icon_lookup_path,
glib.build_filenamev({dir, 'icons'}))
end
end
return icon_lookup_path
end
--- Lookup an icon in different folders of the filesystem.
-- @tparam string icon_file Short or full name of the icon.
-- @treturn string|boolean Full name of the icon, or false on failure.
function utils.lookup_icon_uncached(icon_file)
if not icon_file or icon_file == "" then
return false
end
if icon_file:sub(1, 1) == '/' and is_format_supported(icon_file) then
-- If the path to the icon is absolute and its format is
-- supported, do not perform a lookup.
return awful_util.file_readable(icon_file) and icon_file or nil
else
for _, directory in ipairs(get_icon_lookup_path()) do
if is_format_supported(icon_file) and
awful_util.file_readable(directory .. "/" .. icon_file) then
return directory .. "/" .. icon_file
else
-- Icon is probably specified without path and format,
-- like 'firefox'. Try to add supported extensions to
-- it and see if such file exists.
for _, format in ipairs(icon_formats) do
local possible_file = directory .. "/" .. icon_file .. "." .. format
if awful_util.file_readable(possible_file) then
return possible_file
end
end
end
end
return false
end
end
local lookup_icon_cache = {}
--- Lookup an icon in different folders of the filesystem (cached).
-- @param icon Short or full name of the icon.
-- @return full name of the icon.
function utils.lookup_icon(icon)
if not lookup_icon_cache[icon] and lookup_icon_cache[icon] ~= false then
lookup_icon_cache[icon] = utils.lookup_icon_uncached(icon)
end
return lookup_icon_cache[icon] or default_icon
end
--- Parse a .desktop file.
-- @param file The .desktop file.
-- @return A table with file entries.
function utils.parse_desktop_file(file)
local program = { show = true, file = file }
local desktop_entry = false
-- Parse the .desktop file.
-- We are interested in [Desktop Entry] group only.
for line in io.lines(file) do
if line:find("^%s*#") then
-- Skip comments.
(function() end)() -- I haven't found a nice way to silence luacheck here
elseif not desktop_entry and line == "[Desktop Entry]" then
desktop_entry = true
else
if line:sub(1, 1) == "[" and line:sub(-1) == "]" then
-- A declaration of new group - stop parsing
break
end
-- Grab the values
for key, value in line:gmatch("(%w+)%s*=%s*(.+)") do
program[key] = value
end
end
end
-- In case [Desktop Entry] was not found
if not desktop_entry then return nil end
-- In case the (required) 'Name' entry was not found
if not program.Name or program.Name == '' then return nil end
-- Don't show program if NoDisplay attribute is false
if program.NoDisplay and string.lower(program.NoDisplay) == "true" then
program.show = false
end
-- Only show the program if there is no OnlyShowIn attribute
-- or if it's equal to utils.wm_name
if program.OnlyShowIn ~= nil and not program.OnlyShowIn:match(utils.wm_name) then
program.show = false
end
-- Look up for a icon.
if program.Icon then
program.icon_path = utils.lookup_icon(program.Icon)
end
-- Split categories into a table. Categories are written in one
-- line separated by semicolon.
if program.Categories then
program.categories = {}
for category in program.Categories:gmatch('[^;]+') do
table.insert(program.categories, category)
end
end
if program.Exec then
-- Substitute Exec special codes as specified in
-- http://standards.freedesktop.org/desktop-entry-spec/1.1/ar01s06.html
if program.Name == nil then
program.Name = '['.. file:match("([^/]+)%.desktop$") ..']'
end
local cmdline = program.Exec:gsub('%%c', program.Name)
cmdline = cmdline:gsub('%%[fuFU]', '')
cmdline = cmdline:gsub('%%k', program.file)
if program.icon_path then
cmdline = cmdline:gsub('%%i', '--icon ' .. program.icon_path)
else
cmdline = cmdline:gsub('%%i', '')
end
if program.Terminal == "true" then
cmdline = utils.terminal .. ' -e ' .. cmdline
end
program.cmdline = cmdline
end
return program
end
--- Parse a directory with .desktop files recursively.
-- @tparam string dir_path The directory path.
-- @tparam function callback Will be fired when all the files were parsed
-- with the resulting list of menu entries as argument.
-- @tparam table callback.programs Paths of found .desktop files.
function utils.parse_dir(dir_path, callback)
local function parser(dir, programs)
local f = gio.File.new_for_path(dir)
-- Except for "NONE" there is also NOFOLLOW_SYMLINKS
local query = gio.FILE_ATTRIBUTE_STANDARD_NAME .. "," .. gio.FILE_ATTRIBUTE_STANDARD_TYPE
local enum, err = f:async_enumerate_children(query, gio.FileQueryInfoFlags.NONE)
if not enum then
debug.print_error(err)
return
end
local files_per_call = 100 -- Actual value is not that important
while true do
local list, enum_err = enum:async_next_files(files_per_call)
if enum_err then
debug.print_error(enum_err)
return
end
for _, info in ipairs(list) do
local file_type = info:get_file_type()
local file_path = enum:get_child(info):get_path()
if file_type == 'REGULAR' then
local program = utils.parse_desktop_file(file_path)
if program then
table.insert(programs, program)
end
elseif file_type == 'DIRECTORY' then
parser(file_path, programs)
end
end
if #list == 0 then
break
end
end
enum:async_close()
end
gio.Async.start(function()
local result = {}
parser(dir_path, result)
callback(result)
end)()
end
--- Compute textbox width.
-- @tparam wibox.widget.textbox textbox Textbox instance.
-- @tparam number|screen s Screen
-- @treturn int Text width.
function utils.compute_textbox_width(textbox, s)
s = screen[s or mouse.screen]
local w, _ = textbox:get_preferred_size(s)
return w
end
--- Compute text width.
-- @tparam str text Text.
-- @tparam number|screen s Screen
-- @treturn int Text width.
function utils.compute_text_width(text, s)
return utils.compute_textbox_width(wibox.widget.textbox(awful_util.escape(text)), s)
end
return utils
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
shangwuhencc/shogun | examples/undocumented/lua_modular/evaluation_contingencytableevaluation_modular.lua | 21 | 1809 | require 'modshogun'
require 'load'
ground_truth = load_labels('../data/label_train_twoclass.dat')
math.randomseed(17)
predicted = {}
for i = 1, #ground_truth do
table.insert(predicted, math.random())
end
parameter_list = {{ground_truth,predicted}}
function evaluation_contingencytableevaluation_modular(ground_truth, predicted)
ground_truth_labels = modshogun.BinaryLabels(ground_truth)
predicted_labels = modshogun.BinaryLabels(predicted)
base_evaluator = modshogun.ContingencyTableEvaluation()
base_evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.AccuracyMeasure()
accuracy = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.ErrorRateMeasure()
errorrate = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.BALMeasure()
bal = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.WRACCMeasure()
wracc = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.F1Measure()
f1 = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.CrossCorrelationMeasure()
crosscorrelation = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.RecallMeasure()
recall = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.PrecisionMeasure()
precision = evaluator:evaluate(predicted_labels,ground_truth_labels)
evaluator = modshogun.SpecificityMeasure()
specificity = evaluator:evaluate(predicted_labels,ground_truth_labels)
return accuracy, errorrate, bal, wracc, f1, crosscorrelation, recall, precision, specificity
end
if debug.getinfo(3) == nill then
print 'ContingencyTableEvaluation'
evaluation_contingencytableevaluation_modular(unpack(parameter_list[1]))
end
| gpl-3.0 |
cshore/luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk/dialplan_out.lua | 68 | 3021 | -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local ast = require("luci.asterisk")
local function find_outgoing_contexts(uci)
local c = { }
local h = { }
-- uci:foreach("asterisk", "dialplan",
-- function(s)
-- if not h[s['.name']] then
-- c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] }
-- h[s['.name']] = true
-- end
-- end)
uci:foreach("asterisk", "dialzone",
function(s)
if not h[s['.name']] then
c[#c+1] = { s['.name'], "Dialzone: %s" % s['.name'] }
h[s['.name']] = true
end
end)
return c
end
local function find_incoming_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "sip",
function(s)
if s.context and not h[s.context] and
uci:get_bool("asterisk", s['.name'], "provider")
then
c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context }
h[s.context] = true
end
end)
return c
end
local function find_trunks(uci)
local t = { }
uci:foreach("asterisk", "sip",
function(s)
if uci:get_bool("asterisk", s['.name'], "provider") then
t[#t+1] = {
"SIP/%s" % s['.name'],
"SIP: %s" % s['.name']
}
end
end)
uci:foreach("asterisk", "iax",
function(s)
t[#t+1] = {
"IAX/%s" % s['.name'],
"IAX: %s" % s.extension or s['.name']
}
end)
return t
end
--[[
dialzone {name} - Outgoing zone.
uses - Outgoing line to use: TYPE/Name
match (list) - Number to match
countrycode - The effective country code of this dialzone
international (list) - International prefix to match
localzone - dialzone for local numbers
addprefix - Prexix required to dial out.
localprefix - Prefix for a local call
]]
--
-- SIP dialzone configuration
--
if arg[1] then
cbimap = Map("asterisk", "Edit Dialplan Entry")
entry = cbimap:section(NamedSection, arg[1])
back = entry:option(DummyValue, "_overview", "Back to dialplan overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans")
desc = entry:option(Value, "description", "Description")
function desc.cfgvalue(self, s, ...)
return Value.cfgvalue(self, s, ...) or s
end
match = entry:option(DynamicList, "match", "Number matches")
intl = entry:option(DynamicList, "international", "Intl. prefix matches (optional)")
trunk = entry:option(MultiValue, "uses", "Used trunk")
for _, v in ipairs(find_trunks(cbimap.uci)) do
trunk:value(unpack(v))
end
aprefix = entry:option(Value, "addprefix", "Add prefix to dial out (optional)")
--ast.idd.cbifill(aprefix)
ccode = entry:option(Value, "countrycode", "Effective countrycode (optional)")
ast.cc.cbifill(ccode)
lzone = entry:option(ListValue, "localzone", "Dialzone for local numbers")
lzone:value("", "no special treatment of local numbers")
for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do
lzone:value(unpack(v))
end
lprefix = entry:option(Value, "localprefix", "Prefix for local calls (optional)")
return cbimap
end
| apache-2.0 |
tianxiawuzhei/cocos-quick-lua | quick/welcome/src/app/scenes/WelcomeScene.lua | 1 | 21357 | local scheduler = require(cc.PACKAGE_NAME .. ".scheduler")
local WelcomeScene = class("WelcomeScene", function()
return display.newScene("WelcomeScene")
end)
function WelcomeScene:ctor()
local bg = cc.LayerColor:create(cc.c4b(56, 56, 56, 255))
self:addChild(bg)
-- self:createTitleBar(bg)
self:createLogo(bg)
self:createTabWidget(bg)
self:createCopyright(bg)
end
local function stripPath(path, maxLen)
local l = string.len(path)
if l <= maxLen then
return path
else
local arr = string.split(path, device.directorySeparator)
-- return arr[#arr - 1]
return "... " .. string.sub(path, l - maxLen)
end
end
function WelcomeScene:createLogo(node)
display.newSprite("#Logo.png")
:align(display.LEFT_TOP, display.left + 48, display.top - 24)
:addTo(node)
local label = cc.ui.UILabel.new({
UILabelType = 2,
text = __VERSION__,
size = 30,
color = display.COLOR_WHITE,
x = 138,
y = display.top - 55,
})
label:align(display.LEFT_CENTER)
node:addChild(label)
end
function WelcomeScene:createButtons(node)
local top = display.top - 140
local buttonWidth = 170
local buttonHeight = 48
local padding = 120
local images = {
normal = "#ButtonNormal.png",
pressed = "#ButtonPressed.png",
disabled = "#ButtonDisabled.png",
}
cc.ui.UIPushButton.new(images, {scale9 = true})
:setButtonSize(buttonWidth, buttonHeight)
:setButtonLabel("normal", cc.ui.UILabel.new({
UILabelType = 2,
text = "捐赠",
size = 18,
}))
:pos(display.width-padding, display.top - 55)
:addTo(node)
:onButtonClicked(function()
device.openURL("http://tairan.com/engines-download")
end)
cc.ui.UIPushButton.new(images, {scale9 = true})
:setButtonSize(buttonWidth, buttonHeight)
:setButtonLabel("normal", cc.ui.UILabel.new({
UILabelType = 2,
text = "打开",
size = 18,
}))
:pos(display.width-padding, top)
:addTo(node)
:onButtonClicked(function()
local projectConfig = ProjectConfig:new()
local argumentVector = vector_string_:new_local()
local index = self.localProjectListView_:getCurrentIndex()
if index > 0 then
local arguments = cc.player.settings.PLAYER_OPEN_RECENTS[index].args
for _,v in ipairs(arguments) do
argumentVector:push_back(v)
end
projectConfig:parseCommandLine(argumentVector)
PlayerProtocol:getInstance():openNewPlayerWithProjectConfig(projectConfig)
end
end)
top = top - 68
cc.ui.UIPushButton.new({normal="#RedButtonNormal.png", pressed="#RedButtonPressed.png", disabled = "#ButtonDisabled.png",}, {scale9 = true})
:setButtonSize(buttonWidth, buttonHeight)
:setButtonLabel("normal", cc.ui.UILabel.new({
UILabelType = 2,
text = "移除",
size = 18,
}))
:pos(display.width-padding, top)
:addTo(node)
:onButtonClicked(function()
local index = self.localProjectListView_:getCurrentIndex()
self.localProjectListView_:removeCurrentItem()
if index > 0 then
table.remove(cc.player.settings.PLAYER_OPEN_RECENTS, index)
cc.player:saveSetting()
end
local listCount = self.localProjectListView_:getItemCount()
if index > listCount then
index = listCount
end
self.localProjectListView_:setCurrentIndex(index)
end)
top = top - 248
cc.ui.UIPushButton.new(images, {scale9 = true})
:setButtonSize(buttonWidth, buttonHeight)
:setButtonLabel("normal", cc.ui.UILabel.new({
UILabelType = 2,
text = "新建项目",
size = 18,
}))
:pos(display.width-padding, top)
:addTo(node)
:onButtonClicked(function()
require("app.scenes.CreateProjectUI"):new()
:addTo(self)
end)
top = top - 68
cc.ui.UIPushButton.new(images, {scale9 = true})
:setButtonSize(buttonWidth, buttonHeight)
:setButtonLabel("normal", cc.ui.UILabel.new({
UILabelType = 2,
text = "导入项目",
size = 18,
}))
:pos(display.width-padding, top)
:addTo(node)
:onButtonClicked(function()
require("app.scenes.OpenProjectUI"):new()
:addTo(self)
end)
local label = zq.UIText.new()
-- label:setGlobalStrokeWidth(3)
label:setGlobalStrokeColor(zq.intToc3b(0xff0000))
-- label:setLayoutWidth(70)
label:setRichText("<font color=#ff0000>红色</font>黄色<font color=#00ff00 size=20 underline=true>绿色\n\r换行</font>", zq.intToc3b(0xffeba7), 20, true)
label:setPosition(800, 350)
self:addChild(label)
-- label:enableDebugDrawRect(true, zq.intToc3b(0x000000))
end
function WelcomeScene:createListItem(icon, title, path)
local container = display.newNode()
container:setContentSize(40*16, 90)
container.path = path
-- icon
cc.ui.UIImage.new(icon, {scale9 = false})
:setLayoutSize(48, 48)
:pos(20, 20)
:addTo(container)
-- title
title = title:splitBySep('/')
local titleLabel = cc.ui.UILabel.new({
text = title[#title],
size = 26,
color = display.COLOR_WHITE})
titleLabel:align(display.LEFT_CENTER, 80, 50)
titleLabel:addTo(container)
-- path
cc.ui.UILabel.new({
text = stripPath(path, 80),
size = 12,
color = display.COLOR_WHITE,
})
:align(display.LEFT_CENTER, 80,15)
:addTo(container)
display.newLine(
{{70, 1}, {40*16 -10, 1}},
{borderColor = cc.c4f(0, 0, 0, 1.0)})
:addTo(container)
return container
end
function WelcomeScene:createTabWidget(node)
self.tabWidget = {}
self.tabWidget.headers_ = {}
self.tabWidget.widgets_ = {}
self:createOpenRecents(cc.player.settings.PLAYER_OPEN_RECENTS, node)
self:createButtons(node)
self:createSamples(node)
self:createHeaders(node)
self:createUrlLinks(node)
function self.tabWidget.setCurrentIndex(index)
self.tabWidget.currentWidget.header:setButtonSelected(false)
if self.tabWidget.currentWidget.widget then
self.tabWidget.currentWidget.widget:setVisible(false)
end
self.tabWidget.currentWidget = {
index = index,
header = self.tabWidget.headers_[index],
widget = self.tabWidget.widgets_[index],
}
self.tabWidget.currentWidget.header:setButtonSelected(true)
if self.tabWidget.currentWidget.widget then
if self.tabWidget.currentWidget.widget.hasItemLoaded == false then
self:loadSampleItems()
self.tabWidget.currentWidget.widget.hasItemLoaded = true
end
if self.tabWidget.currentWidget.widget.hasItemLoaded1 == false then
self:loadLinkItems()
self.tabWidget.currentWidget.widget.hasItemLoaded1 = true
end
self.tabWidget.currentWidget.widget:setVisible(true)
end
end
local index = (#cc.player.settings.PLAYER_OPEN_RECENTS < 1 and 2) or 1 or (#cc.player.settings.PLAYER_OPEN_RECENTS < 1 and 3)
self.tabWidget.setCurrentIndex(index)
end
-- 我的项目
function WelcomeScene:createOpenRecents(recents, node)
local localProjectListView = require("app.scenes.ListViewEx").new {
bg = "#TabButtonSelected.png",
viewRect = cc.rect(0,0, 40*17, 388),
direction = cc.ui.UIScrollView.DIRECTION_VERTICAL,
scrollbarImgV = "#ScrollBarHandler.png",
}
:addTo(node)
localProjectListView:setPosition(40, 92)
-- hightlight item
local bgItem = cc.ui.UIImage.new("#ItemSelected.png", {scale9 = true})
bgItem:setLayoutSize(40*16-20, 87)
bgItem:pos(36, 5)
local highlightNode = display.newNode()
highlightNode:setVisible(false)
highlightNode:pos(0, 0)
highlightNode:addChild(bgItem)
localProjectListView:setHighlightNode(highlightNode)
localProjectListView:setTouchSwallowEnabled(true)
-- add items
for i,v in ipairs(recents) do
local container = self:createListItem("#Logo.png", v.title, v.title)
local item = localProjectListView:newItem()
item:addContent(container)
item:setItemSize(40*16, 96)
localProjectListView:addItem(item)
end
localProjectListView:reload()
localProjectListView:setCurrentIndex(1)
self.tabWidget.widgets_[#self.tabWidget.widgets_ +1] = localProjectListView
self.localProjectListView_ = localProjectListView
end
function WelcomeScene:createHeaders(node)
local left = display.left + 130
local top = display.top - 136
local buttonWidth = 150
local buttonHeight = 48
local images = {
on = "#TabButtonSelected.png",
off = "#TabButtonNormal.png",
}
local headers = {{title="我的项目",widget=self.localProjectListView_},
{title="示例",widget=self.lvGrid},
{title="社区动态",widget=self.linkGrid}
}
for i,v in ipairs(headers) do
local header =
cc.ui.UICheckBoxButton.new(images, {scale9 = true})
:setButtonLabel(cc.ui.UILabel.new({text = v.title, size = 18}))
:setButtonSize(buttonWidth, buttonHeight)
:setButtonLabelAlignment(display.CENTER)
:pos(left, top)
header.index = i
header.widget = v.widget
header:onButtonClicked(function()
self.tabWidget.setCurrentIndex(header.index)
end)
node:addChild(header)
self.tabWidget.headers_[#self.tabWidget.headers_+1] = header
left = left + 170
end
self.tabWidget.currentWidget = {index = 1,
header = self.tabWidget.headers_[1],
widget = self.tabWidget.widgets_[1]}
self.tabWidget.currentWidget.header:setButtonSelected(true)
end
function WelcomeScene:createCopyright(node)
local bg = cc.LayerColor:create(cc.c4b(83, 83, 83, 255))
bg:setContentSize(cc.size(display.width, 48))
node:addChild(bg)
local label = cc.ui.UILabel.new({
UILabelType = 2,
text = "Copyright (c) 2015 tairan.com, Powered by Quick-Cocos2dx-Community",
size = 15,
color = cc.c3b(128, 128, 128),
x = 48,
y = display.bottom + 24,
})
label:align(display.LEFT_CENTER)
node:addChild(label)
label = cc.ui.UILabel.new({
UILabelType = 2,
text = "QQ群:190864188",
size = 15,
color = cc.c3b(128, 128, 128),
x = display.width - 38,
y = display.bottom + 24,
})
label:setAnchorPoint(1, 0.5)
node:addChild(label)
end
function WelcomeScene:createTitleBar(node)
local bar = display.newNode()
bar:pos(0, display.height - 28)
node:addChild(bar)
cc.ui.UIPushButton.new("#SettingsIcon.png", {scale9 = true})
:pos(display.width-48, 0)
:addTo(bar)
:onButtonClicked(function()
print("open settings")
end)
cc.ui.UILabel.new({
text = "0",
align = cc.ui.TEXT_ALIGN_LEFT,
color = cc.c3b(255,255,255,255),
size = 18,
})
:align(display.LEFT_TOP, display.width-80, 10)
:addTo(bar)
cc.ui.UIPushButton.new("#MessagesIcon.png", {scale9 = true})
:pos(display.width-48*2, 0)
:addTo(bar)
:onButtonClicked(function()
print("show message here")
end)
cc.ui.UILabel.new({
text = stripPath("<user>", 9),
color = cc.c3b(255,255,255,255),
size = 18,
})
:align(display.LEFT_TOP, display.width-170, 10)
:addTo(bar)
cc.ui.UIPushButton.new("#UserIcon.png", {scale9 = true})
:pos(display.width-48*4, 0)
:addTo(bar)
:onButtonClicked(function()
print("user icon")
end)
end
-- 示例
function WelcomeScene:createSamples(node)
self.samples = dofile(cc.player.quickRootPath .. "quick/samples/samples.lua")
self.lvGrid = cc.ui.UIListView.new {
bg = "#TabButtonSelected.png",
bgScale9 = true,
viewRect = cc.rect(0,0, 40*17, 40*9+28),
direction = cc.ui.UIScrollView.DIRECTION_VERTICAL,
scrollbarImgV = "#ScrollBarHandler.png"}
self.lvGrid:onTouch(function(event)
if not event.listView:isItemInViewRect(event.itemPos) then
return
end
local listView = event.listView
if "clicked" == event.name then
self.lvGrid.currentItem = event.item
end
end)
self.lvGrid:setPosition(40, 92)
self.lvGrid:setTouchSwallowEnabled(true)
self.lvGrid:setVisible(false)
self.lvGrid:addTo(node)
self.lvGrid.hasItemLoaded = false
self.tabWidget.widgets_[#self.tabWidget.widgets_ +1] = self.lvGrid
end
function WelcomeScene:loadSampleItems()
for i=1,#self.samples,3 do
local item = self.lvGrid:newItem()
local content = display.newNode()
local left = 20
local lenght = i + 2
if lenght > #self.samples then lenght = #self.samples end
for k=i,lenght do
local sample = self.samples[k]
self:createOneSampleUI(sample, item)
:addTo(content)
:pos(left, 0)
left = left + 220
end
content:setContentSize(40*17, 190)
item:addContent(content)
item:setItemSize(40*17, 190)
self.lvGrid:addItem(item)
end
self.lvGrid:reload()
end
--社区动态
function WelcomeScene:createUrlLinks(node)
self.myLinks = dofile(cc.player.quickRootPath .. "quick/welcome/src/articles.lua")
self.linkGrid = cc.ui.UIListView.new {
bg = "#TabButtonSelected.png",
bgScale9 = true,
viewRect = cc.rect(0,0, 40*17, 40*9+28),
direction = cc.ui.UIScrollView.DIRECTION_VERTICAL,
scrollbarImgV = "#ScrollBarHandler.png"
}
self.linkGrid:setTouchSwallowEnabled(true)
self.linkGrid:onTouch(function(event)
if not event.listView:isItemInViewRect(event.itemPos) then
return
end
local listView = event.listView
if "clicked" == event.name then
-- self.linkGrid.currentItem = event.item
end
end)
self.linkGrid:setPosition(40, 92)
self.linkGrid:setTouchSwallowEnabled(true)
self.linkGrid:setVisible(false)
self.linkGrid:addTo(node)
self.linkGrid.hasItemLoaded1 = false
self.tabWidget.widgets_[#self.tabWidget.widgets_ +1] = self.linkGrid
end
function WelcomeScene:loadLinkItems()
for i=1,#self.myLinks,1 do
local item = self.linkGrid:newItem()
local content = display.newNode()
local left = 20
local myLink = self.myLinks[i]
local k = i%2
local color = {
-- cc.c3b(70,201,11),
cc.c3b(230,120,0),
cc.c3b(230,120,0)
}
self:createOneLink(myLink, color[k+1])
:addTo(content)
:pos(left, 0)
content:setContentSize(40*17, 170)
item:addContent(content)
item:setItemSize(40*17, 170)
self.linkGrid:addItem(item)
end
self.linkGrid:reload()
end
function WelcomeScene:createOneLink(sample, colorVal)
local node = display.newNode()
-- 标题
local label = cc.ui.UILabel.new({
UILabelType = 2,
text = sample.title,
align = cc.ui.TEXT_ALIGNMENT_CENTER,
color = cc.c3b(176,202,235),
size = 16,
})
label:setAnchorPoint(0.5, 1.0)
label:setPosition(425, 160)
label:setLayoutSize(40*16, 70)
label:addTo(node)
-- URL按钮和图片
local demoImage = "#ItemSelected.png"
local button = cc.ui.UIPushButton.new(demoImage, {scale9 = true})
button.isTouchMoved_ = false
button:setTouchSwallowEnabled(false)
button:pos(100, 85)
button:setButtonSize(190, 140)
local image = display.newSprite(sample.image)
:addTo(button)
image:enableDebugDrawRect(true, true)
button:addNodeEventListener(cc.NODE_TOUCH_EVENT, function ( event )
local name, x, y = event.name, event.x, event.y
if event.name == "began" then
if zq.touch.checkTouch(button, cc.rect(-95, -70, 190, 140), cc.p(x, y)) then
image:setScale(1.1)
return true
end
return false
elseif event.name == "moved" then
image:setScale(1.0)
button.isTouchMoved_ = true
elseif event.name == "ended" then
if button.isTouchMoved_ == false then
image:setScale(1.0)
device.openURL(sample.path)
end
button.isTouchMoved_ = false
else
image:setScale(1.0)
end
end)
button:addTo(node)
-- 简单表述
local label2 = cc.ui.UILabel.new({
UILabelType = 2,
text = sample.description,
align = cc.ui.TEXT_ALIGNMENT_CENTER,
color = colorVal,
size = 14,
})
label2:setAnchorPoint(0, 1.0)
label2:setPosition(210, 130)
label2:setLayoutSize(40*16, 70)
label2:addTo(node)
-- 分割线
display.newLine(
{{0, 1}, {40*16 - 0, 1}},
{borderColor = cc.c4f(0.5, 0.5, 0.6, 0.8)})
:addTo(node)
return node
end
function WelcomeScene:createOneSampleUI(sample, item)
local node = display.newNode()
self:createDemoTitle(sample)
:addTo(node)
self:createDemoDescription(sample)
:addTo(node)
local button = self:createDemoButton(sample)
button.listItem = item
button:addTo(node)
return node
end
function WelcomeScene:createDemoTitle(sample)
local label = cc.ui.UILabel.new({
UILabelType = 2,
text = sample.title,
align = cc.ui.TEXT_ALIGNMENT_CENTER,
color = cc.c3b(144,144,144),
size = 14,
})
label:setAnchorPoint(0.5, 0.5)
label:setPosition(100, 160)
return label
end
function WelcomeScene:createDemoDescription(sample)
local title = sample.description
local color = cc.c3b(50,144,144)
local sampleAbsPath = cc.player.quickRootPath .. "quick/" .. sample.path
if not cc.FileUtils:getInstance():isDirectoryExist(sampleAbsPath) then
title = title .. " (unfinished)"
color = cc.c3b(255,0,0)
end
local label = cc.ui.UILabel.new({
UILabelType = 2,
text = title,
align = cc.ui.TEXT_ALIGNMENT_CENTER,
color = color,
size = 12,
})
label:setAnchorPoint(0.5, 0.5)
label:setPosition(100, 145)
return label
end
function WelcomeScene:createDemoButton(sample)
local demoImage = sample.image or "#ItemSelected.png"
local button = cc.ui.UIPushButton.new(demoImage, {scale9 = true})
button.isTouchMoved_ = false
button:setTouchSwallowEnabled(false)
button:pos(100, 65)
button:setButtonSize(188, 130)
button:addNodeEventListener(cc.NODE_TOUCH_EVENT, function ( event )
local name, x, y = event.name, event.x, event.y
if event.name == "began" then
if zq.touch.checkTouch(button, cc.rect(-94, -65, 188, 130), cc.p(x, y)) then
return true
end
return false
elseif event.name == "moved" then
button.isTouchMoved_ = true
elseif event.name == "ended" then
if button.isTouchMoved_ == false then
self:openProjectWithPath(sample.path)
end
button.isTouchMoved_ = false
end
end)
return button
end
function WelcomeScene:openProjectWithPath(path)
local configPath = cc.player.quickRootPath .. "quick/" .. path .. "/src/config.lua"
local projectConfig = ProjectConfig:new()
projectConfig:setProjectDir(cc.player.quickRootPath .. "quick/" .. path)
if cc.FileUtils:getInstance():isFileExist(configPath) then
local data = ""
for line in io.lines(configPath) do
if string.find(line, "CONFIG_SCREEN_WIDTH") then
data = data .. line .. ',\n'
elseif string.find(line, "CONFIG_SCREEN_HEIGHT") then
data = data .. line .. ',\n'
elseif string.find(line, "CONFIG_SCREEN_ORIENTATION") then
data = data .. line .. ',\n'
end
end
local config = assert(loadstring("local settings = {" .. data .. "} return settings"))()
local with = tonumber(config.CONFIG_SCREEN_WIDTH)
local height = tonumber(config.CONFIG_SCREEN_HEIGHT)
projectConfig:setProjectDir(cc.player.quickRootPath .. "quick/" .. path)
projectConfig:setFrameSize(with, height)
-- screen direction
if config.CONFIG_SCREEN_ORIENTATION == "portrait" then
projectConfig:changeFrameOrientationToPortait()
else
projectConfig:changeFrameOrientationToLandscape()
end
end
PlayerProtocol:getInstance():openNewPlayerWithProjectConfig(projectConfig)
end
return WelcomeScene
| mit |
NSAKEY/prosody-modules | mod_captcha_registration/util/dataforms.lua | 33 | 6601 | -- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local setmetatable = setmetatable;
local pairs, ipairs = pairs, ipairs;
local tostring, type, next = tostring, type, next;
local t_concat = table.concat;
local st = require "util.stanza";
local jid_prep = require "util.jid".prep;
module "dataforms"
local xmlns_forms = 'jabber:x:data';
local form_t = {};
local form_mt = { __index = form_t };
function new(layout)
return setmetatable(layout, form_mt);
end
function form_t.form(layout, data, formtype)
local form = st.stanza("x", { xmlns = xmlns_forms, type = formtype or "form" });
if layout.title then
form:tag("title"):text(layout.title):up();
end
if layout.instructions then
form:tag("instructions"):text(layout.instructions):up();
end
for n, field in ipairs(layout) do
local field_type = field.type or "text-single";
-- Add field tag
form:tag("field", { type = field_type, var = field.name, label = field.label });
local value = (data and data[field.name]) or field.value;
if value then
-- Add value, depending on type
if field_type == "hidden" then
if type(value) == "table" then
-- Assume an XML snippet
form:tag("value")
:add_child(value)
:up();
else
form:tag("value"):text(tostring(value)):up();
end
elseif field_type == "boolean" then
form:tag("value"):text((value and "1") or "0"):up();
elseif field_type == "fixed" then
form:tag("value"):text(value):up();
elseif field_type == "jid-multi" then
for _, jid in ipairs(value) do
form:tag("value"):text(jid):up();
end
elseif field_type == "jid-single" then
form:tag("value"):text(value):up();
elseif field_type == "text-single" or field_type == "text-private" then
form:tag("value"):text(value):up();
elseif field_type == "text-multi" then
-- Split into multiple <value> tags, one for each line
for line in value:gmatch("([^\r\n]+)\r?\n*") do
form:tag("value"):text(line):up();
end
elseif field_type == "list-single" then
local has_default = false;
for _, val in ipairs(value) do
if type(val) == "table" then
form:tag("option", { label = val.label }):tag("value"):text(val.value):up():up();
if val.default and (not has_default) then
form:tag("value"):text(val.value):up();
has_default = true;
end
else
form:tag("option", { label= val }):tag("value"):text(tostring(val)):up():up();
end
end
elseif field_type == "list-multi" then
for _, val in ipairs(value) do
if type(val) == "table" then
form:tag("option", { label = val.label }):tag("value"):text(val.value):up():up();
if val.default then
form:tag("value"):text(val.value):up();
end
else
form:tag("option", { label= val }):tag("value"):text(tostring(val)):up():up();
end
end
elseif field_type == "media" then
form:tag("media", { xmlns = "urn:xmpp:media-element" });
for _, val in ipairs(value) do
form:tag("uri", { type = val.type }):text(val.uri):up()
end
form:up();
end
end
if field.required then
form:tag("required"):up();
end
-- Jump back up to list of fields
form:up();
end
return form;
end
local field_readers = {};
function form_t.data(layout, stanza)
local data = {};
local errors = {};
for _, field in ipairs(layout) do
local tag;
for field_tag in stanza:childtags() do
if field.name == field_tag.attr.var then
tag = field_tag;
break;
end
end
if not tag then
if field.required then
errors[field.name] = "Required value missing";
end
else
local reader = field_readers[field.type];
if reader then
data[field.name], errors[field.name] = reader(tag, field.required);
end
end
end
if next(errors) then
return data, errors;
end
return data;
end
field_readers["text-single"] =
function (field_tag, required)
local data = field_tag:get_child_text("value");
if data and #data > 0 then
return data
elseif required then
return nil, "Required value missing";
end
end
field_readers["text-private"] =
field_readers["text-single"];
field_readers["jid-single"] =
function (field_tag, required)
local raw_data = field_tag:get_child_text("value")
local data = jid_prep(raw_data);
if data and #data > 0 then
return data
elseif raw_data then
return nil, "Invalid JID: " .. raw_data;
elseif required then
return nil, "Required value missing";
end
end
field_readers["jid-multi"] =
function (field_tag, required)
local result = {};
local err = {};
for value_tag in field_tag:childtags("value") do
local raw_value = value_tag:get_text();
local value = jid_prep(raw_value);
result[#result+1] = value;
if raw_value and not value then
err[#err+1] = ("Invalid JID: " .. raw_value);
end
end
if #result > 0 then
return result, (#err > 0 and t_concat(err, "\n") or nil);
elseif required then
return nil, "Required value missing";
end
end
field_readers["list-multi"] =
function (field_tag, required)
local result = {};
for value in field_tag:childtags("value") do
result[#result+1] = value:get_text();
end
if #result > 0 then
return result;
elseif required then
return nil, "Required value missing";
end
end
field_readers["text-multi"] =
function (field_tag, required)
local data, err = field_readers["list-multi"](field_tag, required);
if data then
data = t_concat(data, "\n");
end
return data, err;
end
field_readers["list-single"] =
field_readers["text-single"];
local boolean_values = {
["1"] = true, ["true"] = true,
["0"] = false, ["false"] = false,
};
field_readers["boolean"] =
function (field_tag, required)
local raw_value = field_tag:get_child_text("value");
local value = boolean_values[raw_value ~= nil and raw_value];
if value ~= nil then
return value;
elseif raw_value then
return nil, "Invalid boolean representation";
elseif required then
return nil, "Required value missing";
end
end
field_readers["hidden"] =
function (field_tag)
return field_tag:get_child_text("value");
end
field_readers["media"] = field_readers["text-single"]
return _M;
--[=[
Layout:
{
title = "MUC Configuration",
instructions = [[Use this form to configure options for this MUC room.]],
{ name = "FORM_TYPE", type = "hidden", required = true };
{ name = "field-name", type = "field-type", required = false };
}
--]=]
| mit |
maciejmiklas/NodeMCUUtils | src/wlan.lua | 3 | 1599 | require "log"
wlan = {
ssid = "SSID not set",
max_queue_size = 4
}
local online = false
local callback_queue = {}
local off_reason = nil
local function on_online(ev, info)
online = true
off_reason = nil
if log.is_info then
log.info("WLAN ON:", info.ip, "/", info.netmask, ",gw:", info.gw)
end
-- execute callback waitnitg in queue
local clb = table.remove(callback_queue)
while clb ~= nil do
local _, err = pcall(clb)
if err ~= nil then
if log.is_error then
log.error(err)
end
end
clb = table.remove(callback_queue)
end
end
local function on_offline(ev, info)
online = false
if info.reason ~= off_reason then
log.warn("Wlan OFF:", info.reason)
off_reason = info.reason
end
end
function wlan.setup(ssid, password)
wifi.sta.on("disconnected", on_offline)
wifi.sta.on("got_ip", on_online)
wlan.ssid = ssid
wlan.pwd = password
wifi.mode(wifi.STATION)
wifi.start()
wifi.sta.config(wlan)
end
-- this method can be executed multiple times. It will queue all callbacks untill it gets
-- WiFi connection
function wlan.execute(callback)
if online then
local _, err = pcall(callback)
if err ~= nil then
if log.is_error then
log.error(err)
end
end
return
end
if table.getn(callback_queue) < wlan.max_queue_size then
table.insert(callback_queue, callback)
else
if log.is_warn then log.warn("WLAN queue full") end
end
end | apache-2.0 |
czlc/skynet | lualib/skynet/sharemap.lua | 30 | 1503 | local stm = require "skynet.stm"
local sprotoloader = require "sprotoloader"
local sproto = require "sproto"
local setmetatable = setmetatable
local sharemap = {}
function sharemap.register(protofile)
-- use global slot 0 for type define
sprotoloader.register(protofile, 0)
end
local sprotoobj
local function loadsp()
if sprotoobj == nil then
sprotoobj = sprotoloader.load(0)
end
return sprotoobj
end
function sharemap:commit()
self.__obj(sprotoobj:encode(self.__typename, self.__data))
end
function sharemap:copy()
return stm.copy(self.__obj)
end
function sharemap.writer(typename, obj)
local sp = loadsp()
obj = obj or {}
local stmobj = stm.new(sp:encode(typename,obj))
local ret = {
__typename = typename,
__obj = stmobj,
__data = obj,
commit = sharemap.commit,
copy = sharemap.copy,
}
return setmetatable(ret, { __index = obj, __newindex = obj })
end
local function decode(msg, sz, self)
local data = self.__data
for k in pairs(data) do
data[k] = nil
end
return sprotoobj:decode(self.__typename, msg, sz, data)
end
function sharemap:update()
return self.__obj(decode, self)
end
function sharemap.reader(typename, stmcpy)
local sp = loadsp()
local stmobj = stm.newcopy(stmcpy)
local _, data = stmobj(function(msg, sz)
return sp:decode(typename, msg, sz)
end)
local obj = {
__typename = typename,
__obj = stmobj,
__data = data,
update = sharemap.update,
}
return setmetatable(obj, { __index = data, __newindex = error })
end
return sharemap
| mit |
interfaceware/iguana-web-apps | shared/csv/writer.lua | 1 | 1830 | local csv = {}
local function escape(V)
V = V:rxsub('\"', '""')
return V
end
-- This is for a JSON based file
function csv.formatHeaders(R)
local Headers = ''
for K, V in pairs(R) do
if type(V) == 'string' or type(V) == 'number' then
Headers = Headers .. '"'..K..'",'
end
end
Headers = Headers:sub(1, #Headers-1)
return Headers
end
-- This is for a JSON based file
function csv.formatLine(R)
local Line = ''
for K,V in pairs(R) do
if type(V) == 'string' then
Line = Line .. '"'..escape(V)..'",'
elseif type(V) == 'number' then
Line = Line ..V..","
end
end
Line = Line:sub(1, #Line-1)
return Line
end
function csv.formatCsv(T)
if #T == 0 then
return ''
end
local Headers = ''
for i=1, #T[1] do
Headers = Headers .. '"'..T[1][i]:nodeName()..'",'
end
-- Get rid of the trailing ,
Headers = Headers:sub(1, #Headers-1)
trace(Headers)
local Data = Headers.."\n"
for i=1, #T do
local Line = ''
local Row = T[i]
for j=1, #Row do
local CType = Row[j]:nodeType()
if CType == 'string' then
Line = Line..'"'..escape(Row[j]:nodeValue())..'",'
else -- for datetime, integer, double
Line = Line..Row[j]:nodeValue()..","
end
end
trace(Line)
-- strip trailing ,
Line = Line:sub(1, #Line-1)
Data = Data..Line .."\n"
end
trace(Data)
return Data
end
-- We write to a temp file and rename it *after* we have finished writing the data.
function csv.writeFileAtomically(Name,Content)
local FileNameTemp = Name..".tmp"
local F = io.open(FileNameTemp, "w")
F:write(Content)
F:close()
-- Atomically rename file once we are done!
os.rename(FileNameTemp, Name)
end
return csv | mit |
silverhammermba/awesome | tests/examples/awful/placement/resize_to_mouse.lua | 3 | 2158 | --DOC_HIDE_ALL
local awful = {placement = require("awful.placement")}
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
screen._setup_grid(64, 48, {4, 4, 4, 4}, {workarea_sides=0})
local function test_touch_mouse(c)
local coords = mouse.coords()
return c:geometry().x == coords.x or c:geometry().y == coords.y
or c:geometry().x+c:geometry().width+2*c.border_width == coords.x
or c:geometry().y+c:geometry().height+2*c.border_width == coords.y
end
for s=1, 8 do
local scr = screen[s]
local x, y = scr.geometry.x, scr.geometry.y
local c = client.gen_fake{x = x+22, y = y+16, width=20, height=15, screen=scr}
assert(client.get()[s] == c)
end
for s=9, 16 do
local scr = screen[s]
local x, y = scr.geometry.x, scr.geometry.y
local c = client.gen_fake{x = x+10, y = y+10, width=44, height=28, screen=scr}
assert(client.get()[s] == c)
end
local function move_corsor(s, x, y)
local sg = screen[s].geometry
mouse.coords {x=sg.x+x,y=sg.y+y}
end
local all_coords_out = {
top_left = {10, 10},
top = {32, 10},
top_right = {60, 10},
right = {60, 20},
bottom_right = {60, 40},
bottom = {32, 40},
bottom_left = {10, 40},
left = {10, 29},
}
local all_coords_in = {
top_left = {20, 18},
top = {32, 18},
top_right = {44, 18},
right = {44, 24},
bottom_right = {44, 34},
bottom = {32, 34},
bottom_left = {20, 34},
left = {32, 24},
}
-- Top left
local s = 1
for k, v in pairs(all_coords_out) do
move_corsor(s, unpack(v))
assert(client.get()[s].screen == screen[s])
awful.placement.resize_to_mouse(client.get()[s], {include_sides=true})
mouse.push_history()
assert(test_touch_mouse(client.get()[s]), k)
s = s + 1
end
for k, v in pairs(all_coords_in) do
move_corsor(s, unpack(v))
assert(client.get()[s].screen == screen[s])
awful.placement.resize_to_mouse(client.get()[s], {include_sides=true})
mouse.push_history()
assert(test_touch_mouse(client.get()[s]), k)
s = s + 1
end
| gpl-2.0 |
NSAKEY/prosody-modules | mod_tcpproxy/mod_tcpproxy.lua | 31 | 3923 | local st = require "util.stanza";
local xmlns_ibb = "http://jabber.org/protocol/ibb";
local xmlns_tcp = "http://prosody.im/protocol/tcpproxy";
local host_attr, port_attr = xmlns_tcp.."\1host", xmlns_tcp.."\1port";
local base64 = require "util.encodings".base64;
local b64, unb64 = base64.encode, base64.decode;
local host = module.host;
local open_connections = {};
local function new_session(jid, sid, conn)
if not open_connections[jid] then
open_connections[jid] = {};
end
open_connections[jid][sid] = conn;
end
local function close_session(jid, sid)
if open_connections[jid] then
open_connections[jid][sid] = nil;
if next(open_connections[jid]) == nil then
open_connections[jid] = nil;
end
return true;
end
end
function proxy_component(origin, stanza)
local ibb_tag = stanza.tags[1];
if (not (stanza.name == "iq" and stanza.attr.type == "set")
and stanza.name ~= "message")
or
(not (ibb_tag)
or ibb_tag.attr.xmlns ~= xmlns_ibb) then
if stanza.attr.type ~= "error" then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
end
return;
end
if ibb_tag.name == "open" then
-- Starting a new stream
local to_host, to_port = ibb_tag.attr[host_attr], ibb_tag.attr[port_attr];
local jid, sid = stanza.attr.from, ibb_tag.attr.sid;
if not (to_host and to_port) then
return origin.send(st.error_reply(stanza, "modify", "bad-request", "No host/port specified"));
elseif not sid or sid == "" then
return origin.send(st.error_reply(stanza, "modify", "bad-request", "No sid specified"));
elseif ibb_tag.attr.stanza ~= "message" then
return origin.send(st.error_reply(stanza, "modify", "bad-request", "Only 'message' stanza transport is supported"));
end
local conn, err = socket.tcp();
if not conn then
return origin.send(st.error_reply(stanza, "wait", "resource-constraint", err));
end
conn:settimeout(0);
local success, err = conn:connect(to_host, to_port);
if not success and err ~= "timeout" then
return origin.send(st.error_reply(stanza, "wait", "remote-server-not-found", err));
end
local listener,seq = {}, 0;
function listener.onconnect(conn)
origin.send(st.reply(stanza));
end
function listener.onincoming(conn, data)
origin.send(st.message({to=jid,from=host})
:tag("data", {xmlns=xmlns_ibb,seq=seq,sid=sid})
:text(b64(data)));
seq = seq + 1;
end
function listener.ondisconnect(conn, err)
origin.send(st.message({to=jid,from=host})
:tag("close", {xmlns=xmlns_ibb,sid=sid}));
close_session(jid, sid);
end
conn = server.wrapclient(conn, to_host, to_port, listener, "*a" );
new_session(jid, sid, conn);
elseif ibb_tag.name == "data" then
local conn = open_connections[stanza.attr.from][ibb_tag.attr.sid];
if conn then
local data = unb64(ibb_tag:get_text());
if data then
conn:write(data);
else
return origin.send(
st.error_reply(stanza, "modify", "bad-request", "Invalid data (base64?)")
);
end
else
return origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
end
elseif ibb_tag.name == "close" then
if close_session(stanza.attr.from, ibb_tag.attr.sid) then
origin.send(st.reply(stanza));
else
return origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
end
end
end
local function stanza_handler(event)
proxy_component(event.origin, event.stanza);
return true;
end
module:hook("iq/bare", stanza_handler, -1);
module:hook("message/bare", stanza_handler, -1);
module:hook("presence/bare", stanza_handler, -1);
module:hook("iq/full", stanza_handler, -1);
module:hook("message/full", stanza_handler, -1);
module:hook("presence/full", stanza_handler, -1);
module:hook("iq/host", stanza_handler, -1);
module:hook("message/host", stanza_handler, -1);
module:hook("presence/host", stanza_handler, -1);
require "core.componentmanager".register_component(host, function() end); -- COMPAT Prosody 0.7
| mit |
ZeroK-RTS/Zero-K-Infrastructure | Benchmarker/Benchmarks/games/path_test.sdd/Luaui/Widgets/cmd_path_test_creator.lua | 12 | 4474 | function widget:GetInfo()
return {
name = "Path test creator",
desc = "allows to easily create path test configs",
author = "BD",
license = "WTFPL",
layer = 0,
enabled = true
}
end
local TEST_PATH = "pathTests"
local mapModString = Game.mapName .. "-".. Game.modShortName .. " " .. Game.modVersion
local configFilePath = TEST_PATH .. "/config/" .. mapModString .. ".lua"
local GetSelectedUnits = Spring.GetSelectedUnits
local GetUnitCommands = Spring.GetUnitCommands
local GetUnitPosition = Spring.GetUnitPosition
local GetUnitDefID = Spring.GetUnitDefID
local RequestPath = Spring.RequestPath
local GetUnitTeam = Spring.GetUnitTeam
local SendCommands = Spring.SendCommands
local GiveOrderToUnit = Spring.GiveOrderToUnit
local Echo = Spring.Echo
local CMD_MOVE = CMD.MOVE
local CMD_FIRE_STATE = CMD.FIRE_STATE
local max = math.max
local ceil = math.ceil
local testScheduled = {}
include("savetable.lua")
function sqDist(posA,posB)
return (posA[1]-posB[1])^2+(posA[2]-posB[2])^2+(posA[3]-posB[3])^2
end
local function getPathDist(startPos,endPos, moveType, radius)
local path = RequestPath(moveType or 1, startPos[1],startPos[2],startPos[3],endPos[1],endPos[2],endPos[3], radius)
if not path then --startpoint is blocked
startPos,endPos = endPos,startPos
local path = RequestPath(moveType or 1, startPos[1],startPos[2],startPos[3],endPos[1],endPos[2],endPos[3], radius)
if not path then
return --if startpoint and endpoint is blocked path is not calculated
end
end
local dist = 0
local xyzs, iii = path.GetPathWayPoints(path)
for i,pxyz in ipairs(xyzs) do
local endPos = pxyz
dist = dist + sqDist(endPos,startPos)^0.5
startPos = endPos
end
return dist
end
function addTest(_,_,params)
local distTollerance = params[1] or 25
local nextTestDelay = params[2]
local arrivalTimeout = params[3]
local testEntry = {}
local maxSelfdTime = 0
testEntry.unitList = {}
testEntry.delayToNextTest = 0
for unitIndex, unitID in ipairs(GetSelectedUnits()) do
local unitPos = {GetUnitPosition(unitID)}
local unitDefID = GetUnitDefID(unitID)
local unitQueue = GetUnitCommands(unitID)
local unitDef = UnitDefs[unitDefID]
local teamID = GetUnitTeam(unitID)
local moveType, radius, speed,selfDTime = unitDef.moveData.id, unitDef.radius, unitDef.speed or 0, unitDef.selfDCountdown*30
local previousPos = unitPos
local donTProcess = false
local distance = 0
local destinations = {}
if unitQueue then
for pos, command in ipairs(unitQueue) do
if command.id == CMD_MOVE then
local wayPointPos = command.params
for _, coord in ipairs(wayPointPos) do
coord = ceil(coord)
end
distance = distance + (getPathDist(previousPos,wayPointPos, moveType, radius) or 0 )
previousPos = wayPointPos
table.insert(destinations,wayPointPos)
end
end
end
for _, coord in ipairs(unitPos) do
coord = ceil(coord)
end
local unitEntry = {}
unitEntry.unitName = UnitDefs[unitDefID].name
unitEntry.startCoordinates = unitPos
unitEntry.maxTargetDist = distTollerance
unitEntry.maxTravelTime = arrivalTimeout or ceil(distance / speed * 30 * 2)
unitEntry.destinationCoordinates = destinations
unitEntry.teamID = teamID
testEntry.delayToNextTest = nextTestDelay or max(testEntry.delayToNextTest,selfDTime*2.2)
table.insert(testEntry.unitList,unitEntry)
end
table.insert(testScheduled,testEntry)
--save result table to a file
table.save( testScheduled, LUAUI_DIRNAME .. "/" .. configFilePath )
Echo("added test " .. #testScheduled)
end
function deleteTest(_,_,params)
local index = tonumber(params[1])
if not index then
Echo("invalid test id")
return
end
if testScheduled[index] then
Echo("deleted test " .. index)
testScheduled[index] = nil
--save result table to a file
table.save( testScheduled, LUAUI_DIRNAME .. "/" .. configFilePath )
end
end
function file_exists(name)
local f = io.open(name,"r")
if f then
io.close(f)
return true
else
return false
end
end
function widget:UnitCreated(unitID,unitDefID, unitTeam)
--set hold fire
GiveOrderToUnit(unitID,CMD_FIRE_STATE,{0},{})
end
function widget:Initialize()
if file_exists(LUAUI_DIRNAME .. "/" .. configFilePath) then
testScheduled = include(configFilePath)
end
widgetHandler:AddAction("addpathtest", addTest, nil, "t")
widgetHandler:AddAction("delpathtest", deleteTest, nil, "t")
SendCommands({"cheat 1","godmode 1","globallos","spectator"})
end
| gpl-3.0 |
Ashkan7150/hydra_api | plugins/anti_spam.lua | 191 | 5291 | --An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Save stats on Redis
if msg.to.type == 'channel' then
-- User is on channel
local hash = 'channel:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
if msg.to.type == 'user' then
-- User is on chat
local hash = 'PM:'..msg.from.id
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is on or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
local chat = msg.to.id
local whitelist = "whitelist"
local is_whitelisted = redis:sismember(whitelist, user)
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
if is_whitelisted == true then
return msg
end
local receiver = get_receiver(msg)
if msg.to.type == 'user' then
local max_msg = 7 * 1
print(msgs)
if msgs >= max_msg then
print("Pass2")
send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.")
savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.")
block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private
end
end
if kicktable[user] == true then
return
end
delete_msg(msg.id, ok_cb, false)
kick_user(user, chat)
local username = msg.from.username
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", "")
if msg.to.type == 'chat' or msg.to.type == 'channel' then
if username then
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Flooding is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked")
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Flooding is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nStatus: User kicked")
end
end
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
if msg.from.username ~= nil then
username = msg.from.username
else
username = "---"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
local GBan_log = 'GBan_log'
local GBan_log = data[tostring(GBan_log)]
for k,v in pairs(GBan_log) do
log_SuperGroup = v
gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)"
--send it to log group/channel
send_large_msg(log_SuperGroup, gban_text)
end
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
ShieldTeams/oldsdp | plugins/anti_spam.lua | 191 | 5291 | --An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Save stats on Redis
if msg.to.type == 'channel' then
-- User is on channel
local hash = 'channel:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
if msg.to.type == 'user' then
-- User is on chat
local hash = 'PM:'..msg.from.id
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is on or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
local chat = msg.to.id
local whitelist = "whitelist"
local is_whitelisted = redis:sismember(whitelist, user)
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
if is_whitelisted == true then
return msg
end
local receiver = get_receiver(msg)
if msg.to.type == 'user' then
local max_msg = 7 * 1
print(msgs)
if msgs >= max_msg then
print("Pass2")
send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.")
savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.")
block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private
end
end
if kicktable[user] == true then
return
end
delete_msg(msg.id, ok_cb, false)
kick_user(user, chat)
local username = msg.from.username
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", "")
if msg.to.type == 'chat' or msg.to.type == 'channel' then
if username then
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Flooding is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked")
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Flooding is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nStatus: User kicked")
end
end
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
if msg.from.username ~= nil then
username = msg.from.username
else
username = "---"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
local GBan_log = 'GBan_log'
local GBan_log = data[tostring(GBan_log)]
for k,v in pairs(GBan_log) do
log_SuperGroup = v
gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)"
--send it to log group/channel
send_large_msg(log_SuperGroup, gban_text)
end
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| agpl-3.0 |
pkulchenko/ZeroBraneEduPack | common-samples/demo.lua | 1 | 2494 | local common = require("common")
-- Imploding and expoloding strings
local t = common.stringExplode("The brown fox jumps over the lazy dog !"," ")
table.insert(t, 5, "high")
common.logStatus("Result: "..common.stringImplode(t, " "))
-- Add pure time delay without opening a turtle window via "wait"
common.timeDelay(5)
--[[
This lets you chose what to return even if the values are booleans,
which is not properly handled via (A and B or C), though in the
output arguments you can still chose what expression to return
Arguments:
1) A condition to check (optional)
2) Value if the condition is true (optional)
3) Value if the condition is false (optional)
]]
common.logStatus("Bool: "..tostring(common.getPick(t~=nil, false, true)))
common.timeDelay(5)
for i = 1, 10 do
--[[
The random number/string generation seed creator has
protected call can be invoked every second. That way
it can take randomization to the maximum by reverting the
number and using the the seconds for triggering the most significant bits
The function randomGetNumber arguments:
1) Print logs (optional)
]]
common.randomSetSeed(true)
--[[
As you know according to lua random number generation manual,
the first 2 or 3 numbers are not that "random" as requested.
That's why we have to call the random generator some couple of
times before returning the actual value
The function randomGetNumber arguments:
1) Lower limit for the "math.random" function (optional)
2) Upper limit for the "math.random" function (optional)
3) Dummy invoke times of "math.random" to generate the actual number (optional)
The function "randomGetString" arguments:
1) How long the generated string must be (optional) (0 for empty string)
2) Controls the "randomGetNumber" third parameter when generating an index
]]
local n = common.randomGetNumber(100)
local s = common.randomGetString(80)
common.logStatus(("ID: %4d <%s> #%d"):format(i, s, n))
common.logStatus(("ID: %4d Random number in [0 , 1 ]: %f"):format(i, common.randomGetNumber()))
common.logStatus(("ID: %4d Random number in [1 , 40]: %d"):format(i, common.randomGetNumber(40)))
common.logStatus(("ID: %4d Random number in [50, 60]: %d"):format(i, common.randomGetNumber(50, 60)))
common.logStatus(("ID: %4d Random number with 3 dummy calls in [50, 60]: %f"):format(i, common.randomGetNumber(50, 60, 3)))
common.timeDelay(0.1)
end
common.timeDelay()
| mit |
hfjgjfg/shatel | plugins/Chat.lua | 5 | 1625 | local function run(msg)
if msg.text == "hi" then
return "Hello bb"
end
if msg.text == "Hi" then
return "Hello honey"
end
if msg.text == "Hello" then
return "Hi bb"
end
if msg.text == "hello" then
return "Hi honey"
end
if msg.text == "Salam" then
return "Salam aleykom"
end
if msg.text == "salam" then
return "va aleykol asalam"
end
if msg.text == "zac" then
return "nagaeidm"
end
if msg.text == "Zac" then
return "nagaeidm"
end
if msg.text == "ZAC" then
return "nagaeidm"
end
if msg.text == "shatel?" then
return "Yes?"
end
if msg.text == "Shatel" then
return "What?"
end
if msg.text == "bot" then
return "hum?"
end
if msg.text == "Bot" then
return "Huuuum?"
end
if msg.text == "?" then
return "Hum??"
end
if msg.text == "Bye" then
return "Babay"
end
if msg.text == "bye" then
return "Bye Bye"
end
if msg.text == "amir" then
return "ba babaeim chikar dari?"
end
if msg.text == "Amir" then
return "kir"
end
if msg.text == "black wolf" then
return "bokone namose hame etehada :D"
end
if msg.text == "Black wolf" then
return "kir to namose badkhah BW :D"
end
if msg.text == "BLACK WOLF" then
return "We Come Back Soon..."
end
if msg.text == "mahyar" then
return "kos amt :D"
end
if msg.text == "Mahyar" then
return "Ba Amom Chikar Dari?"
end
end
return {
description = "Chat With Robot Server",
usage = "chat with robot",
patterns = {
"^[Hh]i$",
"^[Hh]ello$",
"^[Zz]ac$",
"^zac$",
"^[Bb]ot$",
"^[Sh]hatel$",
"^[Bb]ye$",
"^?$",
"^[Ss]alam$",
"^[Aa]mir",
"^[Bb]lack wolf$",
"^[B]LACK WOLF",
"^[Mm]ahyar"
},
run = run,
--privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
sohrab96/cyrax | plugins/admin.lua | 95 | 10643 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
--Function to add log supergroup
local function logadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local GBan_log = 'GBan_log'
if not data[tostring(GBan_log)] then
data[tostring(GBan_log)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(GBan_log)][tostring(msg.to.id)] = msg.to.peer_id
save_data(_config.moderation.data, data)
local text = 'Log_SuperGroup has has been set!'
reply_msg(msg.id,text,ok_cb,false)
return
end
--Function to remove log supergroup
local function logrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local GBan_log = 'GBan_log'
if not data[tostring(GBan_log)] then
data[tostring(GBan_log)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(GBan_log)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local text = 'Log_SuperGroup has has been removed!'
reply_msg(msg.id,text,ok_cb,false)
return
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairsByKeys(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function reload_plugins( )
plugins = {}
return load_plugins()
end
local function run(msg,matches)
local receiver = get_receiver(msg)
local group = msg.to.id
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if not is_admin1(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
local text = "Message From "..(msg.from.username or msg.from.last_name).."\n\nMessage : "..matches[3]
send_large_msg("user#id"..matches[2],text)
return "Message has been sent"
end
if matches[1] == "pmblock" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "pmunblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
if not is_sudo(msg) then-- Sudo only
return
end
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
if not is_sudo(msg) then-- Sudo only
return
end
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "addcontact" and is_sudo(msg) then
phone = matches[2]
first_name = matches[3]
last_name = matches[4]
add_contact(phone, first_name, last_name, ok_cb, false)
return "User With Phone +"..matches[2].." has been added"
end
if matches[1] == "sendcontact" and is_sudo(msg) then
phone = matches[2]
first_name = matches[3]
last_name = matches[4]
send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false)
end
if matches[1] == "mycontact" and is_sudo(msg) then
if not msg.from.phone then
return "I must Have Your Phone Number!"
end
phone = msg.from.phone
first_name = (msg.from.first_name or msg.from.phone)
last_name = (msg.from.last_name or msg.from.id)
send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false)
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent a group dialog list with both json and text format to your private messages"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
if matches[1] == "sync_gbans" then
if not is_sudo(msg) then-- Sudo only
return
end
local url = "http://seedteam.org/Teleseed/Global_bans.json"
local SEED_gbans = http.request(url)
local jdat = json:decode(SEED_gbans)
for k,v in pairs(jdat) do
redis:hset('user:'..v, 'print_name', k)
banall_user(v)
print(k, v.." Globally banned")
end
end
if matches[1] == 'reload' then
receiver = get_receiver(msg)
reload_plugins(true)
post_msg(receiver, "Reloaded!", ok_cb, false)
return "Reloaded!"
end
--[[*For Debug*
if matches[1] == "vardumpmsg" and is_admin1(msg) then
local text = serpent.block(msg, {comment=false})
send_large_msg("channel#id"..msg.to.id, text)
end]]
if matches[1] == 'updateid' then
local data = load_data(_config.moderation.data)
local long_id = data[tostring(msg.to.id)]['long_id']
if not long_id then
data[tostring(msg.to.id)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
return "Updated ID"
end
end
if matches[1] == 'addlog' and not matches[2] then
if is_log_group(msg) then
return "Already a Log_SuperGroup"
end
print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup")
logadd(msg)
end
if matches[1] == 'remlog' and not matches[2] then
if not is_log_group(msg) then
return "Not a Log_SuperGroup"
end
print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") removed")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup")
logrem(msg)
end
return
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^[#!/](pm) (%d+) (.*)$",
"^[#!/](import) (.*)$",
"^[#!/](pmunblock) (%d+)$",
"^[#!/](pmblock) (%d+)$",
"^[#!/](markread) (on)$",
"^[#!/](markread) (off)$",
"^[#!/](setbotphoto)$",
"^[#!/](contactlist)$",
"^[#!/](dialoglist)$",
"^[#!/](delcontact) (%d+)$",
"^[#!/](addcontact) (.*) (.*) (.*)$",
"^[#!/](sendcontact) (.*) (.*) (.*)$",
"^[#!/](mycontact)$",
"^[#/!](reload)$",
"^[#/!](updateid)$",
"^[#/!](sync_gbans)$",
"^[#/!](addlog)$",
"^[#/!](remlog)$",
"%[(photo)%]",
},
run = run,
pre_process = pre_process
}
--By @imandaneshi :)
--https://github.com/SEEDTEAM/TeleSeed/blob/test/plugins/admin.lua
---Modified by @Rondoozle for supergroups
| gpl-2.0 |
rickvanbodegraven/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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.