content stringlengths 5 1.05M |
|---|
return {
name = "Glowstone",
desc = "Provides light",
sprite = 'glowstone',
usage = 'equipment',
equipment = {light = {radius = 32}}
}
|
dofile("base.lua")
--dofile("lavaflood.lua")
|
require 'nvim-tree'.setup {
git = {
enable = true,
ignore = true,
}
}
|
local EquipSlots = require("api.EquipSlots")
local Assert = require("api.test.Assert")
local Item = require("api.Item")
function test_EquipSlots_iter_all_body_parts__blocked()
local equip = EquipSlots:new { "elona.hand", "elona.neck" }
Assert.eq(2, equip:iter_all_body_parts():length())
Assert.eq(0, equip:iter_equipped_body_parts():length())
local item = Item.create("elona.dagger", nil, nil, {ownerless=true})
Assert.is_truthy(equip:equip(item))
Assert.eq(2, equip:iter_all_body_parts():length())
Assert.eq(1, equip:iter_equipped_body_parts():length())
equip:set_body_part_blocked("elona.hand", true)
Assert.eq(1, equip:iter_all_body_parts():length())
Assert.eq(0, equip:iter_equipped_body_parts():length())
item = Item.create("elona.engagement_amulet", nil, nil, {ownerless=true})
Assert.is_truthy(equip:equip(item))
Assert.eq(1, equip:iter_all_body_parts():length())
Assert.eq(1, equip:iter_equipped_body_parts():length())
equip:set_body_part_blocked("elona.hand", false)
Assert.eq(2, equip:iter_all_body_parts():length())
Assert.eq(2, equip:iter_equipped_body_parts():length())
end
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local config = require "game.config"
local math_random = math.random
local table_insert = table.insert
local _M = {}
_M.data = {
arsen = config.template.arsen,
rand1 = {},
box ={},
}
_M.box_type = {8,15,20,24}
_M.interval_time = 5400 --1.5小时会自动恢复1次
_M.arsen_max_n_num = 5
function _M:get_box_rand(id)
if not self.data.box[id] then
self.data.box[id] = {}
self.data.box[id].n = 0
self.data.box[id].rewards = self.data.arsen[id].boxreward
for i,v in pairs(self.data.box[id].rewards) do
self.data.box[id].n = self.data.box[id].n + v[1]
end
end
return self.data.box[id]
end
function _M:get_box(id)
local rand_data = self:get_box_rand(id)
-- [[10,[20025,20026,20027,20028,20029,20030,20031,20032,20033,20034,20035,20036],1],[990,[20021,20022,20023,20024],1]]
local r1 = math_random(1,rand_data.n)
local idx = 0
for i,v in ipairs(rand_data.rewards) do
if r1 < v[1] then
idx = i
break;
end
r1 = r1 - v[1]
end
if idx == 0 then return false end
local r2 = math_random(1,#rand_data.rewards[idx][2])
return { [ rand_data.rewards[idx][2][r2] ] = rand_data.rewards[idx][3] }
end
function _M:get_box_type(pos)
return self.data.arsen[pos].quality
end
function _M:get_rand_rand1(id)
if not self.data.rand1[id] then
self.data.rand1[id] = {}
self.data.rand1[id].n = 0
self.data.rand1[id].rewards = self.data.arsen[id].stagereward
for i,v in pairs(self.data.rand1[id].rewards) do
self.data.rand1[id].n = self.data.rand1[id].n + v[1]
end
end
return self.data.rand1[id]
end
function _M:challeng_one_reward(pos)
if not self.data.arsen[pos] or not self.data.arsen[pos].reward then return false end
local r1 = math_random(1,#self.data.arsen[pos].reward[1])
return self.data.arsen[pos].reward[1][r1],self.data.arsen[pos].reward[2]
end
function _M:challeng_one(id)
local rand1_data = self:get_rand_rand1(id)
local r1 = math_random(1,rand1_data.n)
local idx = 0
for i,v in pairs(rand1_data.rewards) do
if r1 < v[1] then
idx = i
break;
end
r1 = r1 - v[1]
end
if idx == 0 then return false end
local rand2_data = rand1_data.rewards[idx][2]
--[ [[21009,21010,21011,21012],5,1000]]
local idall ={}
local num = {}
local pro = {}
local numall = 0
for i,v in pairs(rand2_data) do
table_insert(idall,v[1])
table_insert(num,v[2])
table_insert(pro,v[3])
numall = numall + v[3]
end
local r2 = math_random(1,numall)
local idx2 = 0
for i,v in ipairs(pro) do
if r2 < v then
idx2 = i
break;
end
r2 = r2 - v
end
if idx2 == 0 then return false end
--local rand3_data = rand2_data[idx2]
--[ [21009,21010,21011,21012],5,1000]
local r3 = math_random(1,#rand2_data[idx2][1])
return rand2_data[idx2][1][r3] or rand1_data.rewards[1][2][1][1][1] ,rand2_data[idx2][2] or rand1_data.rewards[1][2][1][2]
end
function _M:get_profit(pos,count)
local profit = {}
local profitadd ={}
for i=1,count do
local profitone = {}
local id,num = self:challeng_one(pos)
profit[id] = (profit[id] or 0) + num
profitone[id] = (profitone[id] or 0) + num
local id,num = self:challeng_one_reward(pos)
if id >0 and num >0 then
profit[id] = (profit[id] or 0) + num
profitone[id] = (profitone[id] or 0) + num
end
table_insert(profitadd,profitone)
end
return profit,profitadd
end
function _M:check_challenge_level(pos,level)
return self.data.arsen[pos].level <= level
end
function _M:get_box_need_count(pos,g_num)
return self.data.arsen[pos].times[1] + self.data.arsen[pos].times[2] * g_num
end
function _M:get_buy_num_cost(buy_num,num)
--return self.data.buy_cost[buy_num+1].cost
return {[config.resource.diamond] = 30 * num}
end
function _M:get_max_buy(vip)
if not vip then vip = 0 end
return 5
--return self.data.buy_cost[vip].arsen_max_b_mum or 5
end
function _M:get_max_num(vip)
if not vip then vip = 0 end
return 5
--return self.data.buy_cost[vip].arsen_max_n_num or 5
end
return _M |
-- Copyright (c) ESX Brasil
--
-- All rights reserved.
--
-- Even if 'All rights reserved' is very clear :
--
-- You shall not use any piece of this software in a commercial product / service
-- You shall not resell this software
-- You shall not provide any facility to install this particular software in a commercial product / service
-- If you redistribute this software, you must link to ORIGINAL repository at https://github.com/ESX-Brasil
-- This copyright should appear in every part of the project code
--
-- Website: www.esxbrasil.Website
-- Forum: forum.esxbrasil.website
fx_version 'adamant'
game 'gta5'
description 'ESXBrasil Tabacjob'
version '1.1.2'
client_scripts {
'@es_extended/locale.lua',
'locales/br.lua',
'locales/en.lua',
'config.lua',
'client/main.lua'
}
server_scripts {
'@es_extended/locale.lua',
'locales/br.lua',
'locales/en.lua',
'config.lua',
'server/main.lua'
}
|
-- Use a protected call so we don't error out on first use
local status_ok, _ = pcall(require, "treesitter-context")
if not status_ok then
return
end
require'treesitter-context'.setup{
enable = true, -- Enable this plugin (Can be enabled/disabled later via commands)
throttle = true, -- Throttles plugin updates (may improve performance)
}
vim.cmd("let &fcs='eob: '")
|
local modem = peripheral.wrap("right")
local ch = 50001
modem.open(ch)
local function log(rch, msg)
print(msg)
-- rch does not work for some reason (it's nil don't know why)
modem.transmit(ch+1, ch, msg)
end
local function checkFuel(rch)
if turtle.getFuelLevel() == 0 then
log(rch, "Out of fuel!")
return false
end
return true
end
local function move(rch, dir)
if not checkFuel() then return false end
if turtle[dir]() then
log(rch, "FUEL: "..turtle.getFuelLevel())
else
log(rch, "Failed to move "..dir)
end
end
local function turn(rch, dir)
if not turtle["turn"..dir]() then
log(rch, "Failed to turn "..dir)
end
end
local function attack(rch)
local f, u, d = turtle.attack(), turtle.attackUp(), turtle.attackDown()
if f or u or d then
log(rch, "Hit!")
else
log(rch, "No hit")
end
end
local function refuel(rch)
if turtle.refuel() then
log(rch, "Now at "..turtle.getFuelLevel().." fuel")
else
log(
rch,
"Couldn't do it. Either full "
..turtle.getFuelLevel()
.." or you gotta stick a fuel item in slot 1"
)
end
end
while true do
local event, side, _ch, rch, msg, dist = os.pullEvent("modem_message")
rch = ch + 1
if msg == '^' then move(rch, "forward")
elseif msg == 'v' then move(rch, "backward")
elseif msg == '<' then turn(rch, "Left")
elseif msg == '>' then turn(rch, "Right")
elseif msg == 'atk' then attack(rch)
elseif msg == 'up' then move(rch, "up")
elseif msg == 'down' then move(rch, "down")
elseif msg == 'refuel' then refuel(rch)
end
end
|
local lu = require("test.luaunit")
local Effect = require("reactivity.effect")
local track, trigger, ITERATE_KEY, effect,stop = Effect.track, Effect.trigger, Effect.ITERATE_KEY, Effect.effect, Effect.stop
local TriggerOpTypes = require("reactivity.operations.TriggerOpTypes")
local Reactive = require("reactivity.reactive")
local computed = require("reactivity.computed").computed
local TrackOpTypes = require("reactivity.operations.TrackOpTypes")
local reactive,markRaw = Reactive.reactive, Reactive.markRaw
local Ref = require("reactivity.ref")(Reactive)
local ref = Ref.ref
describe(
"reactivity/effect",
function()
it(
"should run the passed function once (wrapped by a effect)",
function()
local fnSpy =
lu.createSpy(
function()
end
)
effect(fnSpy)
lu.assertEquals(#fnSpy.calls, 1)
end
)
it(
"should observe basic properties",
function()
local dummy = nil
local counter = reactive({num = 0})
effect(
function()
dummy = counter.num
end
)
lu.assertEquals(dummy, 0)
counter.num = 7
lu.assertEquals(dummy, 7)
end
)
it(
"should observe multiple properties",
function()
local dummy = nil
local counter = reactive({num1 = 0, num2 = 0})
effect(
function()
dummy = counter.num1 + counter.num1 + counter.num2
end
)
lu.assertEquals(dummy, 0)
counter.num2 = 7
counter.num1 = counter.num2
lu.assertEquals(dummy, 21)
end
)
it(
"should handle multiple effects",
function()
local dummy1 = nil
local dummy2 = nil
local counter = reactive({num = 0})
effect(
function()
dummy1 = counter.num
end
)
effect(
function()
dummy2 = counter.num
end
)
lu.assertEquals(dummy1, 0)
lu.assertEquals(dummy2, 0)
counter.num = counter.num + 1
lu.assertEquals(dummy1, 1)
lu.assertEquals(dummy2, 1)
end
)
it(
"should observe nested properties",
function()
local dummy = nil
local counter = reactive({nested = {num = 0}})
effect(
function()
dummy = counter.nested.num
end
)
lu.assertEquals(dummy, 0)
counter.nested.num = 8
lu.assertEquals(dummy, 8)
end
)
it(
"should observe delete operations",
function()
local dummy = nil
local obj = reactive({prop = "value"})
effect(
function()
dummy = obj.prop
end
)
lu.assertEquals(dummy, "value")
obj.prop = nil
lu.assertEquals(dummy, nil)
end
)
it(
"should observe has operations",
function()
local dummy = nil
local obj = reactive({prop = "value"})
effect(
function()
dummy = obj["prop"] ~= nil
end
)
lu.assertEquals(dummy, true)
obj.prop = nil
lu.assertEquals(dummy, false)
obj.prop = 12
lu.assertEquals(dummy, true)
end
)
-- it('should observe properties on the prototype chain', function()
-- local dummy = nil
-- local counter = reactive({num=0})
-- local parentCounter = reactive({num=2})
-- setmetatable(toRaw(counter), {__index = function(self, key)
-- return parentCounter[key]
-- end})
-- -- Object:setPrototypeOf(counter, parentCounter)
-- effect(function()
-- dummy = counter.num
-- end
-- )
-- lu.assertEquals(dummy, 0)
-- counter.num = nil
-- lu.assertEquals(dummy, 2)
-- parentCounter.num = 4
-- lu.assertEquals(dummy, 4)
-- counter.num = 3
-- lu.assertEquals(dummy, 3)
-- end
-- )
-- it('should observe has operations on the prototype chain', function()
-- local dummy = nil
-- local counter = reactive({num=0})
-- local parentCounter = reactive({num=2})
-- Object:setPrototypeOf(counter, parentCounter)
-- effect(function()
-- dummy = counter['num']
-- end
-- )
-- lu.assertEquals(dummy, true)
-- counter.num = nil
-- lu.assertEquals(dummy, true)
-- parentCounter.num = nil
-- lu.assertEquals(dummy, false)
-- counter.num = 3
-- lu.assertEquals(dummy, true)
-- end
-- )
-- it('should observe inherited property accessors', function()
-- local dummy = nil
-- local parentDummy = nil
-- local hiddenValue = nil
-- local obj = reactive({})
-- local parent = reactive({prop=function(value)
-- hiddenValue = value
-- end
-- , prop=function()
-- return hiddenValue
-- end
-- })
-- Object:setPrototypeOf(obj, parent)
-- effect(function()
-- dummy = obj.prop
-- end
-- )
-- effect(function()
-- parentDummy = parent.prop
-- end
-- )
-- lu.assertEquals(dummy, nil)
-- lu.assertEquals(parentDummy, nil)
-- obj.prop = 4
-- lu.assertEquals(dummy, 4)
-- parent.prop = 2
-- lu.assertEquals(dummy, 2)
-- lu.assertEquals(parentDummy, 2)
-- end
-- )
it(
"should observe function call chains",
function()
local dummy = nil
local counter = reactive({num = 0})
local function getNum()
return counter.num
end
effect(
function()
dummy = getNum()
end
)
lu.assertEquals(dummy, 0)
counter.num = 2
lu.assertEquals(dummy, 2)
end
)
it(
"should observe iteration",
function()
local dummy = nil
local list = reactive({"Hello"})
effect(
function()
dummy = table.concat(list, " ")
end
)
lu.assertEquals(dummy, "Hello")
table.insert(list, "World!")
lu.assertEquals(dummy, "Hello World!")
table.remove(list, 1)
lu.assertEquals(dummy, "World!")
end
)
it(
"should observe implicit array length changes",
function()
local dummy = nil
local list = reactive({"Hello"})
effect(
function()
dummy = table.concat(list, " ")
end
)
lu.assertEquals(dummy, "Hello")
list[2] = "World!"
lu.assertEquals(dummy, "Hello World!")
list[3] = "Hello!"
lu.assertEquals(dummy, "Hello World! Hello!")
end
)
it(
"should observe sparse array mutations",
function()
local dummy = nil
local list = reactive({})
list[1] = "World!"
effect(
function()
dummy = table.concat(list, " ")
end
)
lu.assertEquals(dummy, "World!")
list[2] = "Hello"
lu.assertEquals(dummy, "World! Hello")
table.remove(list)
lu.assertEquals(dummy, "World!")
end
)
it(
"should observe enumeration",
function()
local dummy = 0
local numbers = reactive({num1 = 3})
effect(
function()
dummy = 0
for key in pairs(numbers) do
-- [ts2lua]numbers下标访问可能不正确
dummy = dummy + numbers[key]
end
end
)
lu.assertEquals(dummy, 3)
numbers.num2 = 4
lu.assertEquals(dummy, 7)
numbers.num1 = nil
lu.assertEquals(dummy, 4)
end
)
it(
"should observe symbol keyed properties",
function()
local key = {"symbol keyed prop"}
local dummy = nil
local hasDummy = nil
local obj = reactive({[key] = "value"})
effect(
function()
-- [ts2lua]obj下标访问可能不正确
dummy = obj[key]
end
)
effect(
function()
hasDummy = obj[key] ~= nil
end
)
lu.assertEquals(dummy, "value")
lu.assertEquals(hasDummy, true)
-- [ts2lua]obj下标访问可能不正确
obj[key] = "newValue"
lu.assertEquals(dummy, "newValue")
-- [ts2lua]obj下标访问可能不正确
obj[key] = nil
lu.assertEquals(dummy, nil)
lu.assertEquals(hasDummy, false)
end
)
it(
"should not observe well-known symbol keyed properties",
function()
local key = {"isConcatSpreadable"}
local dummy = nil
local array = reactive({})
effect(
function()
-- [ts2lua]array下标访问可能不正确
dummy = array[key]
end
)
-- [ts2lua]array下标访问可能不正确
lu.assertEquals(array[key], nil)
lu.assertEquals(dummy, nil)
-- [ts2lua]array下标访问可能不正确
array[key] = true
-- [ts2lua]array下标访问可能不正确
lu.assertEquals(array[key], true)
lu.assertEquals(dummy, true)
end
)
it(
"should observe function valued properties",
function()
local oldFunc = function()
return 1
end
local newFunc = function()
return 2
end
local dummy = nil
local obj = reactive({func = oldFunc})
effect(
function()
dummy = obj.func
end
)
lu.assertEquals(dummy, oldFunc)
obj.func = newFunc
lu.assertEquals(dummy, newFunc)
end
)
it(
"should observe chained getters relying on this",
function()
local obj =
reactive(
{
a = 1,
b = computed(
function(self)
return self.a
end
)
}
)
local dummy = nil
local ef =
effect(
function()
dummy = obj.b
end
)
lu.assertEquals(dummy, 1)
obj.a = obj.a + 1
lu.assertEquals(dummy, 2)
end
)
it(
"should observe methods relying on this",
function()
local obj =
reactive(
{
a = 1,
b = function(self)
return self.a
end
}
)
local dummy = nil
effect(
function()
dummy = obj:b()
end
)
lu.assertEquals(dummy, 1)
obj.a = obj.a + 1
lu.assertEquals(dummy, 2)
end
)
it(
"should not observe set operations without a value change",
function()
local hasDummy = nil
local getDummy = nil
local obj = reactive({prop = "value"})
local getSpy =
lu.createSpy(
function()
getDummy = obj.prop
end
)
local hasSpy =
lu.createSpy(
function()
hasDummy = obj["prop"] ~= nil
end
)
effect(getSpy)
effect(hasSpy)
lu.assertEquals(getDummy, "value")
lu.assertEquals(hasDummy, true)
obj.prop = "value"
getSpy.toHaveBeenCalledTimes(1)
hasSpy.toHaveBeenCalledTimes(1)
lu.assertEquals(getDummy, "value")
lu.assertEquals(hasDummy, true)
end
)
-- it(
-- "should not observe raw mutations",
-- function()
-- local dummy = nil
-- local obj = reactive({})
-- effect(
-- function()
-- dummy = toRaw(obj).prop
-- end
-- )
-- lu.assertEquals(dummy, nil)
-- obj.prop = "value"
-- lu.assertEquals(dummy, nil)
-- end
-- )
-- it(
-- "should not be triggered by raw mutations",
-- function()
-- local dummy = nil
-- local obj = reactive({})
-- effect(
-- function()
-- dummy = obj.prop
-- end
-- )
-- lu.assertEquals(dummy, nil)
-- toRaw(obj).prop = "value"
-- lu.assertEquals(dummy, nil)
-- end
-- )
-- it(
-- "should not be triggered by inherited raw setters",
-- function()
-- local dummy = nil
-- local parentDummy = nil
-- local hiddenValue = nil
-- local obj = reactive({})
-- local parent =
-- reactive(
-- {
-- prop = function(value)
-- hiddenValue = value
-- end,
-- prop = function()
-- return hiddenValue
-- end
-- }
-- )
-- Object:setPrototypeOf(obj, parent)
-- effect(
-- function()
-- dummy = obj.prop
-- end
-- )
-- effect(
-- function()
-- parentDummy = parent.prop
-- end
-- )
-- lu.assertEquals(dummy, nil)
-- lu.assertEquals(parentDummy, nil)
-- toRaw(obj).prop = 4
-- lu.assertEquals(dummy, nil)
-- lu.assertEquals(parentDummy, nil)
-- end
-- )
it(
"should avoid implicit infinite recursive loops with itself",
function()
local counter = reactive({num = 0})
local counterSpy =
lu.createSpy(
function()
counter.num = counter.num + 1
end
)
effect(counterSpy)
lu.assertEquals(counter.num, 1)
counterSpy.toHaveBeenCalledTimes(1)
counter.num = 4
lu.assertEquals(counter.num, 5)
counterSpy.toHaveBeenCalledTimes(2)
end
)
it(
"should allow explicitly recursive raw function loops",
function()
local counter = reactive({num = 0})
local numSpy
numSpy =
lu.createSpy(
function()
counter.num = counter.num + 1
if counter.num < 10 then
numSpy()
end
end
)
effect(numSpy)
lu.assertEquals(counter.num, 10)
numSpy.toHaveBeenCalledTimes(10)
end
)
it(
"should avoid infinite loops with other effects",
function()
local nums = reactive({num1 = 0, num2 = 1})
local spy1 =
lu.createSpy(
function()
nums.num1 = nums.num2
end
)
local spy2 =
lu.createSpy(
function()
nums.num2 = nums.num1
end
)
effect(spy1)
effect(spy2)
lu.assertEquals(nums.num1, 1)
lu.assertEquals(nums.num2, 1)
spy1.toHaveBeenCalledTimes(1)
spy2.toHaveBeenCalledTimes(1)
nums.num2 = 4
lu.assertEquals(nums.num1, 4)
lu.assertEquals(nums.num2, 4)
spy1.toHaveBeenCalledTimes(2)
spy2.toHaveBeenCalledTimes(2)
nums.num1 = 10
lu.assertEquals(nums.num1, 10)
lu.assertEquals(nums.num2, 10)
spy1.toHaveBeenCalledTimes(3)
spy2.toHaveBeenCalledTimes(3)
end
)
it(
"should return a new reactive version of the function",
function()
local function greet()
return "Hello World"
end
local effect1 = effect(greet)
local effect2 = effect(greet)
lu.assertEquals(type(effect1), "table")
lu.assertEquals(type(effect2), "table")
lu.assertNotEquals(effect1, greet)
lu.assertNotEquals(effect1, effect2)
end
)
it(
"should discover new branches while running automatically",
function()
local dummy = nil
local obj = reactive({prop = "value", run = false})
local conditionalSpy =
lu.createSpy(
function()
-- [ts2lua]lua中0和空字符串也是true,此处obj.run需要确认
dummy = (obj.run and {obj.prop} or {"other"})[1]
end
)
effect(conditionalSpy)
lu.assertEquals(dummy, "other")
conditionalSpy.toHaveBeenCalledTimes(1)
obj.prop = "Hi"
lu.assertEquals(dummy, "other")
conditionalSpy.toHaveBeenCalledTimes(1)
obj.run = true
lu.assertEquals(dummy, "Hi")
conditionalSpy.toHaveBeenCalledTimes(2)
obj.prop = "World"
lu.assertEquals(dummy, "World")
conditionalSpy.toHaveBeenCalledTimes(3)
end
)
it(
"should discover new branches when running manually",
function()
local dummy = nil
local run = false
local obj = reactive({prop = "value"})
local runner =
effect(
function()
-- [ts2lua]lua中0和空字符串也是true,此处run需要确认
dummy = (run and {obj.prop} or {"other"})[1]
end
)
lu.assertEquals(dummy, "other")
runner()
lu.assertEquals(dummy, "other")
run = true
runner()
lu.assertEquals(dummy, "value")
obj.prop = "World"
lu.assertEquals(dummy, "World")
end
)
it(
"should not be triggered by mutating a property, which is used in an inactive branch",
function()
local dummy = nil
local obj = reactive({prop = "value", run = true})
local conditionalSpy =
lu.createSpy(
function()
-- [ts2lua]lua中0和空字符串也是true,此处obj.run需要确认
dummy = (obj.run and {obj.prop} or {"other"})[1]
end
)
effect(conditionalSpy)
lu.assertEquals(dummy, "value")
conditionalSpy.toHaveBeenCalledTimes(1)
obj.run = false
lu.assertEquals(dummy, "other")
conditionalSpy.toHaveBeenCalledTimes(2)
obj.prop = "value2"
lu.assertEquals(dummy, "other")
conditionalSpy.toHaveBeenCalledTimes(2)
end
)
it(
"should not double wrap if the passed function is a effect",
function()
local runner =
effect(
function()
end
)
local otherRunner = effect(runner)
lu.assertNotEquals(runner, otherRunner)
lu.assertEquals(runner.raw, otherRunner.raw)
end
)
it(
"should not run multiple times for a single mutation",
function()
local dummy = nil
local obj = reactive({})
local fnSpy =
lu.createSpy(
function()
for key in pairs(obj) do
-- [ts2lua]obj下标访问可能不正确
dummy = obj[key]
end
dummy = obj.prop
end
)
effect(fnSpy)
fnSpy.toHaveBeenCalledTimes(1)
obj.prop = 16
lu.assertEquals(dummy, 16)
fnSpy.toHaveBeenCalledTimes(2)
end
)
it(
"should allow nested effects",
function()
local nums = reactive({num1 = 0, num2 = 1, num3 = 2})
local dummy = {}
local childSpy =
lu.createSpy(
function()
dummy.num1 = nums.num1
end
)
local childeffect = effect(childSpy)
local parentSpy =
lu.createSpy(
function()
dummy.num2 = nums.num2
childeffect()
dummy.num3 = nums.num3
end
)
effect(parentSpy)
lu.assertEquals(dummy, {num1 = 0, num2 = 1, num3 = 2})
parentSpy.toHaveBeenCalledTimes(1)
childSpy.toHaveBeenCalledTimes(2)
nums.num1 = 4
lu.assertEquals(dummy, {num1 = 4, num2 = 1, num3 = 2})
parentSpy.toHaveBeenCalledTimes(1)
childSpy.toHaveBeenCalledTimes(3)
nums.num2 = 10
lu.assertEquals(dummy, {num1 = 4, num2 = 10, num3 = 2})
parentSpy.toHaveBeenCalledTimes(2)
childSpy.toHaveBeenCalledTimes(4)
nums.num3 = 7
lu.assertEquals(dummy, {num1 = 4, num2 = 10, num3 = 7})
parentSpy.toHaveBeenCalledTimes(3)
childSpy.toHaveBeenCalledTimes(5)
end
)
-- it(
-- "should observe json methods",
-- function()
-- local dummy = {}
-- local obj = reactive({})
-- effect(
-- function()
-- dummy = JSON:parse(JSON:stringify(obj))
-- end
-- )
-- obj.a = 1
-- lu.assertEquals(dummy.a, 1)
-- end
-- )
it(
"should observe class method invocations",
function()
local Model = {name = "Model"}
function Model:__new__()
self.count = 0
end
function Model:inc()
self.count = self.count + 1
end
Model:__new__()
local model = reactive(Model)
local dummy = nil
effect(
function()
dummy = model.count
end
)
lu.assertEquals(dummy, 0)
model:inc()
lu.assertEquals(dummy, 1)
end
)
it(
"lazy",
function()
local obj = reactive({foo = 1})
local dummy = nil
local runner =
effect(
function()
dummy = obj.foo
return dummy
end,
{lazy = true}
)
lu.assertEquals(dummy, nil)
lu.assertEquals(runner(), 1)
lu.assertEquals(dummy, 1)
obj.foo = 2
lu.assertEquals(dummy, 2)
end
)
it(
"scheduler",
function()
local runner = nil
local dummy = nil
local scheduler =
lu.createSpy(
function(_runner)
runner = _runner
end
)
local obj = reactive({foo = 1})
effect(
function()
dummy = obj.foo
end,
{scheduler = scheduler}
)
scheduler.toHaventBeenCalled()
lu.assertEquals(dummy, 1)
obj.foo = obj.foo + 1
scheduler.toHaveBeenCalledTimes(1)
lu.assertEquals(dummy, 1)
runner()
lu.assertEquals(dummy, 2)
end
)
it(
"events: onTrack",
function()
local events = {}
local dummy = nil
local onTrack =
lu.createSpy(
function(...)
table.insert(events, {...})
end
)
local obj = reactive({foo = 1, bar = 2})
local runner =
effect(
function()
dummy = obj.foo
dummy = obj["bar"] ~= nil
dummy = {}
for k, v in pairs(obj) do
table.insert(dummy, k)
end
end,
{onTrack = onTrack}
)
lu.assertTableContains(dummy, "foo")
lu.assertTableContains(dummy, "bar")
onTrack.toHaveBeenCalledTimes(3)
lu.assertEquals(
events,
{
{runner, obj, TrackOpTypes.GET, "foo"},
{runner, obj, TrackOpTypes.GET, "bar"},
{runner, obj, TrackOpTypes.ITERATE, ITERATE_KEY}
}
)
end
)
it(
"events: onTrigger",
function()
local events = {}
local dummy = nil
local onTrigger =
lu.createSpy(
function(...)
table.insert(events, {...})
end
)
local obj = reactive({foo = 1})
local runner =
effect(
function()
dummy = obj.foo
end,
{onTrigger = onTrigger}
)
obj.foo = obj.foo + 1
lu.assertEquals(dummy, 2)
onTrigger.toHaveBeenCalledTimes(1)
lu.assertEquals(
events[0 + 1],
{
runner,
obj,
TriggerOpTypes.SET,
"foo",
2,
1
}
)
obj.foo = nil
lu.assertEquals(dummy, nil)
onTrigger.toHaveBeenCalledTimes(2)
lu.assertEquals(
events[1 + 1],
{ runner, obj, TriggerOpTypes.DELETE, "foo", nil, 2}
)
end
)
it(
"stop",
function()
local dummy = nil
local obj = reactive({prop = 1})
local runner =
effect(
function()
dummy = obj.prop
end
)
obj.prop = 2
lu.assertEquals(dummy, 2)
stop(runner)
obj.prop = 3
lu.assertEquals(dummy, 2)
runner()
lu.assertEquals(dummy, 3)
end
)
it(
"stop with scheduler",
function()
local dummy = nil
local obj = reactive({prop = 1})
local queue = {}
local runner =
effect(
function()
dummy = obj.prop
end,
{
scheduler = function(e)
table.insert(queue, e)
end
}
)
obj.prop = 2
lu.assertEquals(dummy, 1)
lu.assertEquals(#queue, 1)
stop(runner)
for _, e in ipairs(queue) do
e()
end
lu.assertEquals(dummy, 1)
end
)
it(
"events: onStop",
function()
local onStop = lu.createSpy()
local runner =
effect(
function()
end,
{onStop = onStop}
)
stop(runner)
onStop.toHaveBeenCalled()
end
)
it(
"stop: a stopped effect is nested in a normal effect",
function()
local dummy = nil
local obj = reactive({prop = 1})
local runner =
effect(
function()
dummy = obj.prop
end
)
stop(runner)
obj.prop = 2
lu.assertEquals(dummy, 1)
effect(
function()
runner()
end
)
lu.assertEquals(dummy, 2)
obj.prop = 3
lu.assertEquals(dummy, 3)
end
)
it(
"markRaw",
function()
local obj = reactive({foo = markRaw({prop = 0})})
local dummy = nil
effect(
function()
dummy = obj.foo.prop
end
)
lu.assertEquals(dummy, 0)
obj.foo.prop = obj.foo.prop + 1
lu.assertEquals(dummy, 0)
obj.foo = {prop = 1}
lu.assertEquals(dummy, 1)
end
)
it(
"should not be trigger when the value and the old value both are NaN",
function()
local obj = reactive({foo = 0/0})
local fnSpy =
lu.createSpy(
function()
return obj.foo
end
)
effect(fnSpy)
obj.foo = 0/0
fnSpy.toHaveBeenCalledTimes(2)
end
)
it(
"should trigger all effects when array length is set 0",
function()
local observed = reactive({1})
local dummy = nil
local record = nil
effect(
function()
dummy = #observed
end
)
effect(
function()
record = observed[1]
end
)
lu.assertEquals(dummy, 1)
lu.assertEquals(record, 1)
observed[1 + 1] = 2
lu.assertEquals(observed[1 + 1], 2)
table.insert(observed, 1, 3)
lu.assertEquals(dummy, 3)
lu.assertEquals(record, 3)
for i,v in pairs(observed) do
observed[i] = nil
end
lu.assertEquals(dummy, 0)
lu.assertIsNil(record)
end
)
it(
"should handle self dependency mutations",
function()
local count = ref(0)
effect(
function()
count.value = count.value + 1
end
)
lu.assertEquals(count.value, 1)
count.value = 10
lu.assertEquals(count.value, 11)
end
)
end
)
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:29' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local function IsSoundEnabled()
return tonumber(GetSetting(SETTING_TYPE_AUDIO, AUDIO_SETTING_SOUND_ENABLED)) ~= 0
end
local ZO_OptionsPanel_Audio_ControlData =
{
--Audio
[SETTING_TYPE_AUDIO] =
{
--Options_Audio_MasterVolume
[AUDIO_SETTING_AUDIO_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_AUDIO_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_MASTER_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_MASTER_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_ALL) end,
},
--Options_Audio_MusicEnabled
[AUDIO_SETTING_MUSIC_ENABLED] =
{
controlType = OPTIONS_CHECKBOX,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_MUSIC_ENABLED,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_MUSIC_ENABLED,
tooltipText = SI_AUDIO_OPTIONS_MUSIC_ENABLED_TOOLTIP,
events = {[true] = "MusicEnabled_On", [false] = "MusicEnabled_Off",},
gamepadHasEnabledDependencies = true,
},
--Options_Audio_MusicVolume
[AUDIO_SETTING_MUSIC_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_MUSIC_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_MUSIC_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_MUSIC_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
eventCallbacks =
{
["MusicEnabled_On"] = ZO_Options_SetOptionActive,
["MusicEnabled_Off"] = ZO_Options_SetOptionInactive,
},
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_MUSIC) end,
gamepadIsEnabledCallback = function()
return tonumber(GetSetting(SETTING_TYPE_AUDIO, AUDIO_SETTING_MUSIC_ENABLED)) ~= 0
end,
},
--Options_Audio_SoundEnabled
[AUDIO_SETTING_SOUND_ENABLED] =
{
controlType = OPTIONS_CHECKBOX,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_SOUND_ENABLED,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_SOUND_ENABLED,
tooltipText = SI_AUDIO_OPTIONS_SOUND_ENABLED_TOOLTIP,
events = {[true] = "SoundEnabled_On", [false] = "SoundEnabled_Off",},
gamepadHasEnabledDependencies = true,
},
--Options_Audio_AmbientVolume
[AUDIO_SETTING_AMBIENT_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_AMBIENT_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_AMBIENT_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_AMBIENT_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
eventCallbacks =
{
["SoundEnabled_On"] = ZO_Options_SetOptionActive,
["SoundEnabled_Off"]= ZO_Options_SetOptionInactive,
},
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_AMBIENT) end,
gamepadIsEnabledCallback = IsSoundEnabled,
},
--Options_Audio_SFXVolume
[AUDIO_SETTING_SFX_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_SFX_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_SFX_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_SFX_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
eventCallbacks =
{
["SoundEnabled_On"] = ZO_Options_SetOptionActive,
["SoundEnabled_Off"]= ZO_Options_SetOptionInactive,
},
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_SFX) end,
gamepadIsEnabledCallback = IsSoundEnabled,
},
--Options_Audio_FootstepsVolume
[AUDIO_SETTING_FOOTSTEPS_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_FOOTSTEPS_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_FOOTSTEPS_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_FOOTSTEPS_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
eventCallbacks =
{
["SoundEnabled_On"] = ZO_Options_SetOptionActive,
["SoundEnabled_Off"]= ZO_Options_SetOptionInactive,
},
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_FOOTSTEPS) end,
gamepadIsEnabledCallback = IsSoundEnabled,
},
--Options_Audio_VOVolume
[AUDIO_SETTING_VO_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_VO_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_VO_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_VO_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
eventCallbacks =
{
["SoundEnabled_On"] = ZO_Options_SetOptionActive,
["SoundEnabled_Off"]= ZO_Options_SetOptionInactive,
},
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_VO) end,
gamepadIsEnabledCallback = IsSoundEnabled,
},
--Options_Audio_UISoundVolume
[AUDIO_SETTING_UI_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_UI_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_UI_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_UI_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
eventCallbacks =
{
["SoundEnabled_On"] = ZO_Options_SetOptionActive,
["SoundEnabled_Off"]= ZO_Options_SetOptionInactive,
},
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_UI) end,
gamepadIsEnabledCallback = IsSoundEnabled,
},
--Options_Audio_VideoSoundVolume
[AUDIO_SETTING_VIDEO_VOLUME] =
{
controlType = OPTIONS_SLIDER,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_VIDEO_VOLUME,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_VIDEO_VOLUME,
tooltipText = SI_AUDIO_OPTIONS_VIDEO_VOLUME_TOOLTIP,
minValue = 0,
maxValue = 100,
showValue = true,
eventCallbacks =
{
["SoundEnabled_On"] = ZO_Options_SetOptionActive,
["SoundEnabled_Off"]= ZO_Options_SetOptionInactive,
},
onReleasedHandler = function() PlaySound(SOUNDS.VOLUME_DING_VIDEO) end,
gamepadIsEnabledCallback = IsSoundEnabled,
},
--Options_Audio_BackgroundAudio
[AUDIO_SETTING_BACKGROUND_AUDIO] =
{
controlType = OPTIONS_CHECKBOX,
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_BACKGROUND_AUDIO,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_BACKGROUND_AUDIO,
tooltipText = SI_AUDIO_OPTIONS_BACKGROUND_AUDIO_TOOLTIP,
exists = ZO_IsPCOrHeronUI,
},
--Options_Audio_VoiceChatVolume
[AUDIO_SETTING_VOICE_CHAT_VOLUME] =
{
system = SETTING_TYPE_AUDIO,
settingId = AUDIO_SETTING_VOICE_CHAT_VOLUME,
controlType = OPTIONS_SLIDER,
panel = SETTING_PANEL_DEBUG,
text = SI_GAMEPAD_AUDIO_OPTIONS_VOICECHAT_VOLUME,
minValue = 40,
maxValue = 75,
exists = IsConsoleUI,
},
},
--Subtitles
[SETTING_TYPE_SUBTITLES] =
{
--Options_Audio_SubtitlesEnabledForNPCs
[SUBTITLE_SETTING_ENABLED_FOR_NPCS] =
{
controlType = OPTIONS_CHECKBOX,
system = SETTING_TYPE_SUBTITLES,
settingId = SUBTITLE_SETTING_ENABLED_FOR_NPCS,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_NPC_SUBTITLES_ENABLED,
tooltipText = SI_AUDIO_OPTIONS_NPC_SUBTITLES_ENABLED_TOOLTIP,
exists = ZO_IsIngameUI,
},
--Options_Audio_SubtitlesEnabledForVideos
[SUBTITLE_SETTING_ENABLED_FOR_VIDEOS] =
{
controlType = OPTIONS_CHECKBOX,
system = SETTING_TYPE_SUBTITLES,
settingId = SUBTITLE_SETTING_ENABLED_FOR_VIDEOS,
panel = SETTING_PANEL_AUDIO,
text = SI_AUDIO_OPTIONS_VIDEO_SUBTITLES_ENABLED,
tooltipText = SI_AUDIO_OPTIONS_VIDEO_SUBTITLES_ENABLED_TOOLTIP,
},
},
}
ZO_SharedOptions.AddTableToPanel(SETTING_PANEL_AUDIO, ZO_OptionsPanel_Audio_ControlData) |
local att = {}
att.name = "am_4borebs"
att.displayName = "Standard Slugs"
att.displayNameShort = "Slugs"
att.statModifiers = {DamageMult = 11,
AimSpreadMult = -.2}
if CLIENT then
att.displayIcon = surface.GetTextureID("atts/slugrounds")
end
function att:attachFunc()
self.Shots = 1
self:unloadWeapon()
end
function att:detachFunc()
self.Shots = self.Shots_Orig
self:unloadWeapon()
end
CustomizableWeaponry:registerAttachment(att) |
ENT.Base = "base_point"
ENT.Type = "point"
--entity functions
function ENT:Initialize() GAMEMODE.PropSpawnStartPoint = self:GetPos() end |
-- MATTER SERIALIZER OBJECT --
-- Create the Matter Serializer base object --
MS = {
ent = nil,
animID = 0,
active = false,
consumption = _mfMSEnergyDrainPerUpdate,
updateTick = 60,
lastUpdate = 0,
dataNetwork = nil,
GCNID = 0,
RCNID = 0,
selectedInv = 0
}
-- Constructor --
function MS:new(object)
if object == nil then return end
local t = {}
local mt = {}
setmetatable(t, mt)
mt.__index = MS
t.ent = object
UpSys.addObj(t)
return t
end
-- Reconstructor --
function MS:rebuild(object)
if object == nil then return end
local mt = {}
mt.__index = MS
setmetatable(object, mt)
end
-- Destructor --
function MS:remove()
-- Destroy the Animation --
rendering.destroy(self.animID)
-- Remove from the Update System --
UpSys.removeObj(self)
end
-- Is valid --
function MS:valid()
if self.ent ~= nil and self.ent.valid then return true end
return false
end
-- Update --
function MS:update()
-- Set the lastUpdate variable --
self.lastUpdate = game.tick
-- Check the Validity --
if self:valid() == false then
self:remove()
return
end
-- Check if the Entity is inside a Green Circuit Network --
if self.ent.get_circuit_network(defines.wire_type.green) ~= nil and self.ent.get_circuit_network(defines.wire_type.green).valid == true then
self.GCNID = self.ent.get_circuit_network(defines.wire_type.green).network_id
else
self.GCNID = 0
end
-- Check if the Entity is inside a Red Circuit Network --
if self.ent.get_circuit_network(defines.wire_type.red) ~= nil and self.ent.get_circuit_network(defines.wire_type.red).valid == true then
self.RCNID = self.ent.get_circuit_network(defines.wire_type.red).network_id
else
self.RCNID = 0
end
-- Check if the Matter Serializer is linked with a live Data Network --
local active = false
self.dataNetwork = nil
for k, obj in pairs(global.dataNetworkTable) do
if obj:isLinked(self) == true then
self.dataNetwork = obj
if obj:isLive() == true then
active = true
else
active = false
end
end
end
self:setActive(active)
-- Update the Inventory --
if self.active == true then
self:updateInv()
end
end
function MS:updateInv()
-- Get the Local Inventory --
local inv = self.ent.get_inventory(defines.inventory.chest)
-- Itinerate the Inventory --
for item, count in pairs(inv.get_contents()) do
-- Check the targeted Inventory --
local dataInv = self.selectedInv
if self.selectedInv == 0 then
dataInv = self.dataNetwork.dataCenter.invObj
end
-- Check the Data Inventory --
if dataInv == nil or getmetatable(dataInv) == nil then return end
-- Add Items to the Data Inventory --
local amountAdded = dataInv:addItem(item, count)
-- Remove Items from the local Inventory --
if amountAdded > 0 then
inv.remove({name=item, count=amountAdded})
end
end
end
-- Tooltip Infos --
function MS:getTooltipInfos(GUI)
-- Create the Data Network label --
local DNText = {"", {"gui-description.DataNetwork"}, ": ", {"gui-description.Unknow"}}
if self.dataNetwork ~= nil then
if self.dataNetwork:isLive() == true then
DNText = {"", {"gui-description.DataNetwork"}, ": ", self.dataNetwork.ID}
else
DNText = {"", {"gui-description.DataNetwork"}, ": ", {"gui-description.Invalid"}}
end
end
local dataNetworkL = GUI.add{type="label"}
dataNetworkL.style.font = "LabelFont"
dataNetworkL.caption = DNText
dataNetworkL.style.font_color = {155, 0, 168}
-- Create the text and style variables --
local text = ""
local style = {}
-- Check if the Data Storage is linked with a Data Center --
if self.dataNetwork ~= nil and getmetatable(self.dataNetwork) ~= nil and self.dataNetwork.dataCenter ~= nil and self.dataNetwork.dataCenter:valid() == true then
text = {"", {"gui-description.LinkedTo"}, ": ", self.dataNetwork.dataCenter.invObj.name}
style = {92, 232, 54}
else
text = {"gui-description.Unlinked"}
style = {231, 5, 5}
end
-- Create the Link label --
local link = GUI.add{type="label"}
link.style.font = "LabelFont"
link.caption = text
link.style.font_color = style
-- Create the Inventory Selection --
if self.dataNetwork ~= nil and self.dataNetwork.dataCenter ~= nil and self.dataNetwork.dataCenter:valid() == true and self.dataNetwork.dataCenter.invObj.isII == true then
-- Create the targeted Inventory label --
local targetLabel = GUI.add{type="label", caption={"", {"gui-description.MSTarget"}, ":"}}
targetLabel.style.top_margin = 7
targetLabel.style.font = "LabelFont"
targetLabel.style.font_color = {108, 114, 229}
local invs = {self.dataNetwork.dataCenter.invObj.name or {"gui-description.Any"}}
local selectedIndex = 1
local i = 1
for k, deepStorage in pairs(global.deepStorageTable) do
if deepStorage ~= nil then
i = i + 1
invs[k+1] = {"", {"gui-description.DS"}, " ", tostring(deepStorage.ID)}
if self.selectedInv == deepStorage then
selectedIndex = i
end
end
end
if selectedIndex ~= nil and selectedIndex > table_size(invs) then selectedIndex = nil end
local invSelection = GUI.add{type="list-box", name="MS" .. self.ent.unit_number, items=invs, selected_index=selectedIndex}
invSelection.style.width = 70
end
end
-- Change the Targeted Inventory --
function MS:changeInventory(ID)
-- Check the ID --
if ID == nil then self.selectedInv = nil end
-- Select the Inventory --
self.selectedInv = nil
for k, deepStorage in pairs(global.deepStorageTable) do
if deepStorage ~= nil and deepStorage:valid() == true then
if ID == deepStorage.ID then
self.selectedInv = deepStorage
end
end
end
end
-- Set Active --
function MS:setActive(set)
self.active = set
if set == true then
-- Create the Animation if it doesn't exist --
if self.animID == 0 then
self.animID = rendering.draw_animation{animation="MatterSerializerA", target={self.ent.position.x,self.ent.position.y-0.35}, surface=self.ent.surface}
end
else
-- Destroy the Animation --
rendering.destroy(self.animID)
self.animID = 0
end
end
|
--[[
军师设置
]]
local THIS_MODULE = ...
local AdviserSet = class("AdviserSet", require("app.main.modules.ui.FrameBase"),
require("app.main.modules.uiwidget.UIWidgetFocusable"))
--[[
构造函数
config
params 额外参数
name 名称
csb csb文件
widgets 组件表
bindings 绑定表
]]
function AdviserSet:ctor(config)
self:setup(config)
self:retain()
end
-- 析构函数
function AdviserSet:dtor()
self:delete()
self:release()
end
-- 重新初始化所有组件
function AdviserSet:reinitWidgets()
self.wg_rolelist:setVisible(false)
end
--[[
打开窗口
team 设置队伍
]]
function AdviserSet:OnOpen(team)
self:reinitWidgets()
local updateRoleList = nil
updateRoleList = function (option)
local roles = team:getRoles()
local adviser = team:getAdviser()
local roleitems = {}
for i,role in ipairs(roles) do
roleitems[i] = {
name = role:isDead() and (":" .. role:getName()) or role:getName(),
adviser = (adviser==role),
onTrigger = function()
local extvars = {
select = role:getName()
}
if adviser == role then
team:setAdviserID("0")
updateRoleList({
pageindex = self.wg_rolelist:getPageIndex(),
selindex = self.wg_rolelist:getSelectIndex(),
})
uiMgr:openUI("message",{
autoclose = true,
texts = gameMgr:getStrings("RELIEVE_ADVISER", extvars),
onComplete = function() self:closeFrame() end
})
elseif not role:isDead() and role:getIntellect() >= dbMgr.configs.advintmin then
team:setAdviserID(role:getID())
updateRoleList({
pageindex = self.wg_rolelist:getPageIndex(),
selindex = self.wg_rolelist:getSelectIndex(),
})
uiMgr:openUI("message",{
autoclose = true,
texts = gameMgr:getStrings("APPOINT_ADVISER", extvars),
onComplete = function() self:closeFrame() end
})
else
uiMgr:openUI("message",{
autoclose = true,
texts = gameMgr:getStrings("NOT_APPOINT_ADVISER", extvars),
})
end
end
}
end
self.wg_rolelist:sizeToRows(#roleitems)
self.wg_rolelist:updateParams(table.merge({
items = roleitems,
listener = {
cancel = function()
self:closeFrame()
end
}
},option))
end
updateRoleList()
self:setFocusWidget(self.wg_rolelist)
end
-- 关闭窗口
function AdviserSet:OnClose()
self:clearFocusWidgets()
end
-- 获得焦点回调
function AdviserSet:onGetFocus()
self:OnWidgetGetFocus()
end
-- 失去焦点回调
function AdviserSet:onLostFocus()
self:OnWidgetLostFocus()
end
-- 输入处理
function AdviserSet:onControlKey(keycode)
self:onWidgetControlKey(keycode)
end
return AdviserSet
|
CreateListCategory( "ControlPoints", "<insert description>" )
CreateListFunction( "SetAllControlPointsNeutral", "Makes all control points neutral. I.e. they will no longer belong to any player." )
function SetAllControlPointsNeutral()
GE_SetAllNeutral()
end
CreateListFunction( "SetAllControlPointsTo", "Make all control points belong to the specified player." )
CreateListArgument( "playerID", "int", "ID of player. Default gets player ID from unit selection.", true )
function SetAllControlPointsTo( playerID )
playerID = playerID or GE_GetSelectedPlayer()
GE_SetAllBelongTo( playerID )
end
CreateListFunction( "SetAllControlPointsNeutralThatBelongTo", "Make all of a specified players control points neutral. I.e. they will no longer belong to any player." )
CreateListArgument( "playerID", "int", "ID of player. Default gets player ID from unit selection.", true )
function SetAllControlPointsNeutralThatBelongTo( playerID )
playerID = playerID or GE_GetSelectedPlayer()
GE_SetAllNeutralThatBelongTo( playerID )
end
CreateListFunction( "SetControlPointNeutral", "Make the specified control point neutral. I.e. it will no longer belong to any player." )
CreateListArgument( "entityID", "int", "EntityID of control point. Default gets entity ID from unit selection.", true )
function SetControlPointNeutral( entityID )
entityID = entityID or GE_GetSelectedEntity()
GE_SetNeutral( entityID )
end
CreateListFunction( "SetControlPointTo", "Make the specified control point belong to the specified player." )
CreateListArgument( "playerID", "int", "ID of player the control point now should belong to. Default gets player ID of the local player.", true )
CreateListArgument( "entityID", "int", "EntityID of control point. Default gets entity ID from unit selection.", true )
function SetControlPointTo( playerID, entityID )
entityID = entityID or GE_GetSelectedEntity()
playerID = playerID or g_LocalPlayerID
GE_SetSetBelongTo( playerID, entityID )
end |
require "auth/auth_commons"
function cache_insert_loc(mountpoint, username, publish_acl, subscribe_acl)
type_assert(mountpoint, "string", "mountpoint")
type_assert(username, "string", "username")
type_assert(publish_acl, {"table", "nil"}, "publish_acl")
type_assert(subscribe_acl, {"table", "nil"}, "subscribe_acl")
validate_acls_loc(publish_acl)
validate_acls_loc(subscribe_acl)
auth_cache.insert(mountpoint, username, username, publish_acl, subscribe_acl)
end
function validate_acls_loc(acls)
if acls ~= nil then
for i, acl in ipairs(acls) do
for k, v in pairs(acl) do
type_assert(k, "string", "acl key")
if k == "modifiers" then
type_assert(v, "table", "acl modifiers")
-- TODO validate modifier types
elseif k == "pattern" then
type_assert(v, "string", "acl pattern")
else
type_assert(v, {"string", "number", "boolean"}, "acl value")
end
end
end
end
end
function auth_on_register(reg)
if reg.username ~= nil and reg.password ~= nil then
results = mysql.execute(pool,
[[SELECT publish_acl, subscribe_acl
FROM vmq_auth_acl
WHERE
username=? AND
password=]]..mysql.hash_method(),
reg.username,
reg.password)
if #results == 1 then
row = results[1]
publish_acl = json.decode(row.publish_acl)
subscribe_acl = json.decode(row.subscribe_acl)
cache_insert_loc(
reg.mountpoint,
reg.username,
publish_acl,
subscribe_acl
)
return true
else
return false
end
end
end
pool = "auth_mysql"
config = {
pool_id = pool
}
mysql.ensure_pool(config)
hooks = {
auth_on_register = auth_on_register,
auth_on_publish = auth_on_publish,
auth_on_subscribe = auth_on_subscribe,
on_unsubscribe = on_unsubscribe,
on_client_gone = on_client_gone,
on_client_offline = on_client_offline,
on_session_expired = on_session_expired,
auth_on_register_m5 = auth_on_register_m5,
auth_on_publish_m5 = auth_on_publish_m5,
auth_on_subscribe_m5 = auth_on_subscribe_m5,
} |
------------------------------------------------------------------------
--- @file ethernet.lua
--- @brief Ethernet protocol utility.
--- Utility functions for the mac_address and ethernet_header structs
--- Includes:
--- - Ethernet constants
--- - Mac address utility
--- - Ethernet header utility
--- - Definition of ethernet packets
------------------------------------------------------------------------
local ffi = require "ffi"
require "utils"
require "proto.template"
local initHeader = initHeader
local ntoh, hton = ntoh, hton
local ntoh16, hton16 = ntoh16, hton16
local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift
local istype = ffi.istype
local format = string.format
------------------------------------------------------------------------
---- Ethernet constants
------------------------------------------------------------------------
--- Ethernet protocol constants
local eth = {}
--- EtherType for IP4
eth.TYPE_IP = 0x0800
--- EtherType for Arp
eth.TYPE_ARP = 0x0806
--- EtherType for IP6
eth.TYPE_IP6 = 0x86dd
--- EtherType for Ptp
eth.TYPE_PTP = 0x88f7
--- EtherType for Allreduce
eth.TYPE_ALLREDUCE = 0xAAAA
eth.TYPE_8021Q = 0x8100
--- EtherType for LACP (Actually, 'Slow Protocols')
eth.TYPE_LACP = 0x8809
--- Special addresses
--- Ethernet broadcast address
eth.BROADCAST = "ff:ff:ff:ff:ff:ff"
--- Invalid null address
eth.NULL = "00:00:00:00:00:00"
------------------------------------------------------------------------
---- Mac addresses
------------------------------------------------------------------------
-- struct
ffi.cdef[[
union __attribute__((__packed__)) mac_address {
uint8_t uint8[6];
uint64_t uint64[0]; // for efficient reads
};
]]
--- Module for mac_address struct
local macAddr = {}
macAddr.__index = macAddr
local macAddrType = ffi.typeof("union mac_address")
--- Retrieve the MAC address.
--- @return Address as number
function macAddr:get()
return tonumber(bit.band(self.uint64[0], 0xFFFFFFFFFFFFULL))
end
--- Set the MAC address.
--- @param addr Address as number
function macAddr:set(addr)
addr = addr or 0
self.uint8[0] = bit.band(addr, 0xFF)
self.uint8[1] = bit.band(bit.rshift(addr, 8), 0xFF)
self.uint8[2] = bit.band(bit.rshift(addr, 16), 0xFF)
self.uint8[3] = bit.band(bit.rshift(addr, 24), 0xFF)
self.uint8[4] = bit.band(bit.rshift(addr + 0ULL, 32ULL), 0xFF)
self.uint8[5] = bit.band(bit.rshift(addr + 0ULL, 40ULL), 0xFF)
end
--- Set the MAC address.
--- @param mac Address in string format.
function macAddr:setString(mac)
self:set(parseMacAddress(mac, true))
end
--- Test equality of two MAC addresses.
--- @param lhs Address in 'union mac_address' format.
--- @param rhs Address in 'union mac_address' format.
--- @return true if equal, false otherwise.
function macAddr.__eq(lhs, rhs)
local isMAC = istype(macAddrType, lhs) and istype(macAddrType, rhs)
for i = 0, 5 do
isMAC = isMAC and lhs.uint8[i] == rhs.uint8[i]
end
return isMAC
end
--- Retrieve the string representation of a MAC address.
--- @return Address in string format.
function macAddr:getString()
return ("%02x:%02x:%02x:%02x:%02x:%02x"):format(
self.uint8[0], self.uint8[1], self.uint8[2],
self.uint8[3], self.uint8[4], self.uint8[5]
)
end
----------------------------------------------------------------------------
---- Ethernet header
----------------------------------------------------------------------------
eth.default = {}
-- definition of the header format
eth.default.headerFormat = [[
union mac_address dst;
union mac_address src;
uint16_t type;
]]
--- Variable sized member
eth.default.headerVariableMember = nil
eth.vlan = {}
-- definition of the header format
eth.vlan.headerFormat = [[
union mac_address dst;
union mac_address src;
uint16_t vlan_id;
uint16_t vlan_tag;
uint16_t type;
]]
--- Variable sized member
eth.vlan.headerVariableMember = nil
eth.qinq = {}
-- definition of the header format
eth.qinq.headerFormat = [[
union mac_address dst;
union mac_address src;
uint16_t outer_vlan_id;
uint16_t outer_vlan_tag;
uint16_t inner_vlan_id;
uint16_t inner_vlan_tag;
uint16_t type;
]]
--- Variable sized member
eth.qinq.headerVariableMember = nil
eth.defaultType = "default"
--- Module for ethernet_header struct
local etherHeader = initHeader()
local etherVlanHeader = initHeader()
local etherQinQHeader = initHeader()
etherHeader.__index = etherHeader
etherVlanHeader.__index = etherVlanHeader
etherQinQHeader.__index = etherQinQHeader
--- Set the destination MAC address.
--- @param addr Address as number
function etherHeader:setDst(addr)
self.dst:set(addr)
end
etherVlanHeader.setDst = etherHeader.setDst
etherQinQHeader.setDst = etherHeader.setDst
--- Retrieve the destination MAC address.
--- @return Address as number
function etherHeader:getDst(addr)
return self.dst:get()
end
etherVlanHeader.getDst = etherHeader.getDst
etherQinQHeader.getDst = etherHeader.getDst
--- Set the source MAC address.
--- @param addr Address as number
function etherHeader:setSrc(addr)
self.src:set(addr)
end
etherVlanHeader.setSrc = etherHeader.setSrc
etherQinQHeader.setSrc = etherHeader.setSrc
--- Retrieve the source MAC address.
--- @return Address as number
function etherHeader:getSrc(addr)
return self.src:get()
end
etherVlanHeader.getSrc = etherHeader.getSrc
etherQinQHeader.getSrc = etherHeader.getSrc
--- Set the destination MAC address.
--- @param str Address in string format.
function etherHeader:setDstString(str)
self.dst:setString(str)
end
etherVlanHeader.setDstString = etherHeader.setDstString
etherQinQHeader.setDstString = etherHeader.setDstString
--- Retrieve the destination MAC address.
--- @return Address in string format.
function etherHeader:getDstString()
return self.dst:getString()
end
etherVlanHeader.getDstString = etherHeader.getDstString
etherQinQHeader.getDstString = etherHeader.getDstString
--- Set the source MAC address.
--- @param str Address in string format.
function etherHeader:setSrcString(str)
self.src:setString(str)
end
etherVlanHeader.setSrcString = etherHeader.setSrcString
etherQinQHeader.setSrcString = etherHeader.setSrcString
--- Retrieve the source MAC address.
--- @return Address in string format.
function etherHeader:getSrcString()
return self.src:getString()
end
etherVlanHeader.getSrcString = etherHeader.getSrcString
etherQinQHeader.getSrcString = etherHeader.getSrcString
--- Set the EtherType.
--- @param int EtherType as 16 bit integer.
function etherHeader:setType(int)
int = int or eth.TYPE_IP
self.type = hton16(int)
end
etherVlanHeader.setType = etherHeader.setType
etherQinQHeader.setType = etherHeader.setType
--- Retrieve the EtherType.
--- @return EtherType as 16 bit integer.
function etherHeader:getType()
return hton16(self.type)
end
etherVlanHeader.getType = etherHeader.getType
etherQinQHeader.getType = etherHeader.getType
function etherVlanHeader:getVlanTag()
return bit.band(hton16(self.vlan_tag), 0xFFF)
end
--- Set the full vlan tag, including the PCP and DEI bits (upper 4 bits)
function etherVlanHeader:setVlanTag(int)
self.vlan_tag = hton16(int)
end
function etherQinQHeader:getInnerVlanTag()
return bit.band(hton16(self.inner_vlan_tag), 0xFFF)
end
--- Set the full inner vlan tag, including the PCP and DEI bits (upper 4 bits)
function etherQinQHeader:setInnerVlanTag(int)
int = int or 0
self.inner_vlan_tag = hton16(int)
end
function etherQinQHeader:getOuterVlanTag()
return bit.band(hton16(self.outer_vlan_tag), 0xFFF)
end
--- Set the full outer vlan tag, including the PCP and DEI bits (upper 4 bits)
function etherQinQHeader:setOuterVlanTag(int)
int = int or 0
self.outer_vlan_tag = hton16(int)
end
function etherQinQHeader:getOuterVlanId()
return hton16(self.outer_vlan_tag)
end
--- Set the outer vlan id
function etherQinQHeader:setOuterVlanId(int)
int = int or 0x8100
self.outer_vlan_id = hton16(int)
end
--- Retrieve the ether type.
--- @return EtherType as string.
function etherHeader:getTypeString()
local type = self:getType()
local cleartext = ""
if type == eth.TYPE_IP then
cleartext = "(IP4)"
elseif type == eth.TYPE_IP6 then
cleartext = "(IP6)"
elseif type == eth.TYPE_ARP then
cleartext = "(ARP)"
elseif type == eth.TYPE_ALLREDUCE then
cleartext = "(ALLREDUCE)"
elseif type == eth.TYPE_PTP then
cleartext = "(PTP)"
elseif type == eth.TYPE_LACP then
cleartext = "(LACP)"
elseif type == eth.TYPE_8021Q then
cleartext = "(VLAN)"
else
cleartext = "(unknown)"
end
return format("0x%04x %s", type, cleartext)
end
etherVlanHeader.getTypeString = etherHeader.getTypeString
etherQinQHeader.getTypeString = etherHeader.getTypeString
--- Set all members of the ethernet header.
--- Per default, all members are set to default values specified in the respective set function.
--- Optional named arguments can be used to set a member to a user-provided value. \n
--- Exemplary invocations:
--- @code
--- fill() --- only default values
--- fill{ ethSrc="12:23:34:45:56:67", ethType=0x137 } --- default value for ethDst; ethSrc and ethType user-specified
--- @endcode
--- @param args Table of named arguments. Available arguments: Src, Dst, Type
--- @param pre Prefix for namedArgs. Default 'eth'.
function etherHeader:fill(args, pre)
args = args or {}
pre = pre or "eth"
local src = pre .. "Src"
local dst = pre .. "Dst"
args[src] = args[src] or "01:02:03:04:05:06"
args[dst] = args[dst] or "07:08:09:0a:0b:0c"
-- addresses can be either a string, a mac_address ctype or a device/queue object
if type(args[src]) == "string" then
self:setSrcString(args[src])
elseif istype(macAddrType, args[src]) then
self.src = args[src]
elseif type(args[src]) == 'number' then
self:setSrc(args[src])
elseif type(args[src]) == "table" and args[src].id then
self:setSrcString((args[src].dev or args[src]):getMacString())
end
if type(args[dst]) == "string" then
self:setDstString(args[dst])
elseif istype(macAddrType, args[dst]) then
self.dst = args[dst]
elseif type(args[dst]) == 'number' then
self:setDst(args[dst])
elseif type(args[dst]) == "table" and args[dst].id then
self:setDstString((args[dst].dev or args[dst]):getMacString())
end
self:setType(args[pre .. "Type"])
end
function etherVlanHeader:fill(args, pre)
self.vlan_id = 0x0081
local vlanTag = args[pre .. "Vlan"] or 1
self:setVlanTag(vlanTag)
etherHeader.fill(self, args, pre)
end
function etherQinQHeader:fill(args, pre)
local innerVlanTag = args[pre .. "innerVlanTag"] or 0
local outerVlanId = args[pre .. "outerVlanId"] or 0x8100
local outerVlanTag = args[pre .. "outerVlanTag"] or 0
self.inner_vlan_id = hton16(0x8100)
self:setInnerVlanTag(innerVlanTag)
self:setOuterVlanId(outerVlanId)
self:setOuterVlanTag(outerVlanTag)
etherHeader.fill(self, args, pre)
end
--- Retrieve the values of all members.
--- @param pre Prefix for namedArgs. Default 'eth'.
--- @return Table of named arguments. For a list of arguments see "See Also".
--- @see etherHeader:fill
function etherHeader:get(pre)
pre = pre or "eth"
local args = {}
args[pre .. "Src"] = self:getSrcString()
args[pre .. "Dst"] = self:getDstString()
args[pre .. "Type"] = self:getType()
return args
end
function etherVlanHeader:get(pre)
pre = pre or "eth"
local args = etherHeader.get(self, pre)
args[pre .. "Vlan"] = self:getVlanTag()
return args
end
function etherQinQHeader:get(pre)
pre = pre or "eth"
local args = etherHeader.get(self, pre)
args[pre .. "outerVlanId"] = self:getOuterVlanId()
args[pre .. "outerVlanTag"] = self:getOuterVlanTag()
args[pre .. "innerVlanTag"] = self:getInnerVlanTag()
return args
end
--- Retrieve the values of all members.
--- @return Values in string format.
function etherHeader:getString()
return "ETH " .. self:getSrcString() .. " > " .. self:getDstString() .. " type " .. self:getTypeString()
end
function etherVlanHeader:getString()
return "ETH " .. self:getSrcString() .. " > " .. self:getDstString() .. " vlan " .. self:getVlanTag() .. " type " .. self:getTypeString()
end
function etherQinQHeader:getString()
return "ETH " .. self:getSrcString() .. " > " .. self:getDstString() .. " outerVlan " .. self:getOuterVlanTag() .. " innerVlan " .. self:getInnerVlanTag() .. " type " .. self:getTypeString()
end
-- Maps headers to respective types.
-- This list should be extended whenever a new type is added to 'Ethernet constants'.
local mapNameType = {
ip4 = eth.TYPE_IP,
ip6 = eth.TYPE_IP6,
arp = eth.TYPE_ARP,
allreduce = eth.TYPE_ALLREDUCE,
ptp = eth.TYPE_PTP,
lacp = eth.TYPE_LACP,
}
--- Resolve which header comes after this one (in a packet).
--- For instance: in tcp/udp based on the ports.
--- This function must exist and is only used when get/dump is executed on
--- an unknown (mbuf not yet casted to e.g. tcpv6 packet) packet (mbuf)
--- @return String next header (e.g. 'eth', 'ip4', nil)
function etherHeader:resolveNextHeader()
local type = self:getType()
for name, _type in pairs(mapNameType) do
if type == _type then
return name
end
end
return nil
end
etherVlanHeader.resolveNextHeader = etherHeader.resolveNextHeader
etherQinQHeader.resolveNextHeader = etherHeader.resolveNextHeader
--- Change the default values for namedArguments (for fill/get).
--- This can be used to for instance calculate a length value based on the total packet length.
--- See proto/ip4.setDefaultNamedArgs as an example.
--- This function must exist and is only used by packet.fill.
--- @param pre The prefix used for the namedArgs, e.g. 'eth'
--- @param namedArgs Table of named arguments (see See Also)
--- @param nextHeader The header following after this header in a packet
--- @param accumulatedLength The so far accumulated length for previous headers in a packet
--- @return Table of namedArgs
--- @see etherHeader:fill
function etherHeader:setDefaultNamedArgs(pre, namedArgs, nextHeader, accumulatedLength)
-- only set Type
if not namedArgs[pre .. "Type"] then
for name, type in pairs(mapNameType) do
if nextHeader == name then
namedArgs[pre .. "Type"] = type
break
end
end
end
if nextHeader == "lacp" then
namedArgs[pre .. "Dst"] = "01:80:c2:00:00:02"
end
return namedArgs
end
etherVlanHeader.setDefaultNamedArgs = etherHeader.setDefaultNamedArgs
etherQinQHeader.setDefaultNamedArgs = etherHeader.setDefaultNamedArgs
function etherHeader:getSubType()
if self:getType() == eth.TYPE_8021Q then
return "vlan"
else
return "default"
end
end
function etherVlanHeader:getSubType()
return "vlan"
end
function etherQinQHeader:getSubType()
return "qinq"
end
----------------------------------------------------------------------------------
---- Metatypes
----------------------------------------------------------------------------------
ffi.metatype("union mac_address", macAddr)
eth.default.metatype = etherHeader
eth.vlan.metatype = etherVlanHeader
eth.qinq.metatype = etherQinQHeader
return eth
|
local fs = _G.fs
local shell = _ENV.shell
if not fs.exists('.mbs') then
print('Installing MBS')
--shell.run('mbs download')
end
print('Initializing MBS')
--shell.run('mbs startup')
|
object_mobile_som_treasure_hunter_merc = object_mobile_som_shared_treasure_hunter_merc:new {
}
ObjectTemplates:addTemplate(object_mobile_som_treasure_hunter_merc, "object/mobile/som/treasure_hunter_merc.iff")
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
-- each agent should pull a different lever...
require 'nn'
require 'cunn'
require 'cudnn'
require 'paths'
function get_reward(batchids,acts)
local R = torch.zeros(batchids[-1])
for s = 2, batchids:size(1) do
local n = batchids[s] - batchids[s-1]
local b = acts:sub(batchids[s-1]+1,batchids[s])
local sb,sv = b:sort(1)
sb = sb:squeeze()
local c = sb[1]
local r = 0
for t = 2, n do
if sb[t] ~= c then
r = r + 1
c = sb[t]
end
end
R:sub(batchids[s-1]+1,batchids[s]):fill(r/(n-1))
end
return R
end
function make_batch(opts,T,Y)
T[1]:uniform():mul(opts.nagents):ceil()
local u = T[1]:float()
local y = u:clone()
for s = 2, batchids:size(1) do
local n = batchids[s] - batchids[s-1]
local tval, pre_tid = u:sub(batchids[s-1]+1,batchids[s]):sort(1)
local _,tid = pre_tid:sort()
y:sub(batchids[s-1]+1,batchids[s]):copy(tid)
end
Y:copy(y)
return T,Y
end
local cmd = torch.CmdLine()
cmd:option('--apg', 10) --models per game
cmd:option('--nagents', 500) --total number of agents
cmd:option('--nlevers', 10) --number of levers
cmd:option('--maxiter', 1000000)
cmd:option('--hdim', 20)
cmd:option('--slayers_depth', 1)
cmd:option('--nlayer', 2)
cmd:option('--batchsize', 64)
cmd:option('--verbose', 500)
cmd:option('--lr', .05)
cmd:option('--reward_only', false) -- if false, use supervision instead of reward
cmd:option('--comm', false)
cmd:option('--equal_bags', true)
cmd:option('--anneal', 1000000)
cmd:option('--clip', -1)
cmd:option('--savedir','')
cmd:option('--save',false)
cmd:option('--recurrent',false)
cmd:option('--logpath', '')
opts = cmd:parse(arg or {})
opts.mdim = opts.hdim
print(opts)
batchids = torch.LongTensor(opts.batchsize+1)
batchids[1] = 0
for s = 1, opts.batchsize do
if opts.equal_bags then
batchids[s+1] = batchids[s] + opts.apg
else
batchids[s+1] = batchids[s] + torch.random(opts.apg-1)+1
end
end
N = batchids[-1]
T = {}
T[1] = torch.rand(N):mul(opts.nagents):ceil()
T[2] = torch.zeros(N,opts.hdim)
T[3] = torch.zeros(N,opts.hdim)
T[4] = torch.ones(N)
T[5] = batchids:clone()
Y = torch.zeros(N)
for s =1, 5 do
T[s] = T[s]:cuda()
end
Y = Y:cuda()
model = paths.dofile('conv_model.lua')
lgrad = torch.zeros(T[1]:size(1),opts.nlevers)
grad = lgrad:clone()
grad= grad:cuda()
crit = nn.ClassNLLCriterion()
crit = crit:cuda()
P, dF = model:getParameters()
er = 0
tr = 0
baseline = 0
logfile = opts.logpath .. 'levers_apg' .. opts.apg .. '_nagents' .. opts.nagents ..
'_nlev' .. opts.nlevers .. '_hdim' .. opts.hdim ..
'_nl' .. opts.nlayer .. '_lr' .. opts.lr .. '_RO' .. tostring(opts.reward_only) ..
'_comm' .. tostring(opts.comm) .. '_clp' .. opts.clip .. '.txt'
if opts.logpath ~= '' then
F = io.open(logfile,'w')
end
for s = 1, opts.maxiter do
make_batch(opts,T,Y)
model:zeroGradParameters()
out = model:forward(T)
acts = torch.multinomial(torch.exp(out),1):squeeze()
acts = torch.round(acts)
R = get_reward(batchids,acts:float())
tr = tr + R:mean()
baseline = .99*baseline + .01*R:mean()
R:add(-baseline)
R:mul(-1)
if opts.reward_only then
lgrad:zero()
for t = 1, grad:size(1) do
lgrad[t][acts[t]] = R[t]
end
grad:copy(lgrad)
model:backward(T, grad)
else
er = er + crit:forward(out,Y)
model:backward(T, crit:backward(out,Y))
end
step = (s - 1 + opts.anneal)/opts.anneal
dt = math.max(opts.lr*(1/step), .00001*opts.lr)
if opts.clip > 0 then
if dF:norm() > opts.clip then dF:div(dF:norm()):mul(opts.clip) end
end
P:add(-dt,dF)
if s% opts.verbose == 1 then
if not opts.reward_only then
print('iteration ' .. s .. ' dt ' .. dt .. ' crit ' .. er/opts.verbose .. ' reward ' .. tr/opts.verbose)
er = 0
else
print('iteration ' .. s .. ' dt ' .. dt .. ' reward ' .. tr/opts.verbose)
end
if opts.logpath ~= '' then
F:write(tr/opts.verbose .. '\n')
F:flush()
end
tr = 0
if opts.save then
torch.save(opts.savedir .. 'model.th',model)
end
end
end
if opts.logpath ~= '' then
F:close()
end
|
local class = require 'middleclass'
local anim8 = require 'anim8'
local Vector = require 'Vector'
local resources = require 'littletanks.resources'
local TankChassis = require 'littletanks.TankChassis'
local SimpleTankChassis = class('littletanks.SimpleTankChassis', TankChassis)
function SimpleTankChassis.static:initializeStatic()
if self.initializedStatic then
return
end
local image = resources['littletanks/entities.png']
self.image = image
local grid = anim8.newGrid(16, 16, image:getDimensions())
self.animationPresets = {
[0] = { frames = grid:getFrames(1,1, 2,1), turretAttachmentPoint = Vector(0, 0) },
[45] = { frames = grid:getFrames(1,2, 2,2), turretAttachmentPoint = Vector(0, 0) },
[90] = { frames = grid:getFrames(1,3, 2,3), turretAttachmentPoint = Vector(0, 0) },
[135] = { frames = grid:getFrames(1,4, 2,4), turretAttachmentPoint = Vector(0, 0) },
[180] = { frames = grid:getFrames(1,5, 2,5), turretAttachmentPoint = Vector(0, 0) }
}
self.initializedStatic = true
end
function SimpleTankChassis:initialize()
TankChassis.initialize(self)
SimpleTankChassis:initializeStatic()
self:setAnimation(0)
end
function SimpleTankChassis:update( timeDelta, tank )
TankChassis.update(self, timeDelta)
--self.animation:setDurations()
self.animation:update(timeDelta * tank:getVelocity():length())
end
function SimpleTankChassis:draw()
local xScale = 1
if self.flipImage then
xScale = -1
end
self.animation:draw(self.image, -8*xScale, -8, 0, xScale, 1)
end
function SimpleTankChassis:onTankRotation( angle )
local angleInDegree = math.deg(angle)
local animationName = math.abs(angleInDegree)
local flipImage = angle < 0
self:setAnimation(animationName)
self.flipImage = flipImage
end
function SimpleTankChassis:setAnimation( name )
local preset = self.animationPresets[name]
self.animation = anim8.newAnimation(preset.frames, 0.1)
self.turretAttachmentPoint = preset.turretAttachmentPoint
end
return SimpleTankChassis
|
object_tangible_meatlump_event_meatlump_container_01_06 = object_tangible_meatlump_event_shared_meatlump_container_01_06:new {
}
ObjectTemplates:addTemplate(object_tangible_meatlump_event_meatlump_container_01_06, "object/tangible/meatlump/event/meatlump_container_01_06.iff")
|
local utils = require('utils')
require('formatter').setup({
logging = false,
filetype = {
-- npm install -g prettier
javascript = {
function()
return {
exe = 'prettier',
args = { '--stdin-filepath', vim.api.nvim_buf_get_name(0), '--single-quote' },
stdin = true,
}
end,
},
-- https://github.com/johnnymorganz/stylua
-- cargo install stylua
-- use `-- stylua: ignore` to ignore parts of a file (ignore start, ignore end for blocks)
lua = {
function()
return {
exe = 'stylua',
args = {
'--config-path',
utils.joinPath(rv.nvimPath, 'misc', 'stylua.toml'),
'-',
},
stdin = true,
}
end,
},
-- go fmt
go = {
function()
return {
exe = 'gofmt',
args = { '-s' },
stdin = true,
}
end,
},
-- Rustfmt
rust = {
function()
return {
exe = 'rustfmt',
args = { '--emit=stdout' },
stdin = true,
}
end,
},
},
})
|
--[[
Retries a failed job by moving it back to the wait queue.
Input:
KEYS[1] 'active',
KEYS[2] 'wait'
KEYS[3] jobId
ARGV[1] pushCmd
ARGV[2] jobId
ARGV[3] token
Events:
'prefix:added'
Output:
0 - OK
-1 - Missing key
-2 - Job Not locked
]]
if redis.call("EXISTS", KEYS[3]) == 1 then
-- Check for job lock
if ARGV[3] ~= "0" then
local lockKey = KEYS[3] .. ':lock'
local lock = redis.call("GET", lockKey)
if redis.call("GET", lockKey) ~= ARGV[3] then
return -2
end
end
redis.call("LREM", KEYS[1], 0, ARGV[2])
redis.call(ARGV[1], KEYS[2], ARGV[2])
return 0
else
return -1
end
|
local json = require('json')
local Snowflake = require('containers/abstract/Snowflake')
local Color = require('utils/Color')
local Permissions = require('utils/Permissions')
local Resolver = require('client/Resolver')
local FilteredIterable = require('iterables/FilteredIterable')
local format = string.format
local insert, sort = table.insert, table.sort
local min, max, floor = math.min, math.max, math.floor
local huge = math.huge
local Role, get = require('class')('Role', Snowflake)
function Role:__init(data, parent)
Snowflake.__init(self, data, parent)
self.client._role_map[self._id] = parent
end
function Role:_modify(payload)
local data, err = self.client._api:modifyGuildRole(self._parent._id, self._id, payload)
if data then
self:_load(data)
return true
else
return false, err
end
end
function Role:delete()
local data, err = self.client._api:deleteGuildRole(self._parent._id, self._id)
if data then
local cache = self._parent._roles
if cache then
cache:_delete(self._id)
end
return true
else
return false, err
end
end
local function sorter(a, b)
if a.position == b.position then
return tonumber(a.id) < tonumber(b.id)
else
return a.position < b.position
end
end
local function getSortedRoles(self)
local guild = self._parent
local id = self._parent._id
local ret = {}
for role in guild.roles:iter() do
if role._id ~= id then
insert(ret, {id = role._id, position = role._position})
end
end
sort(ret, sorter)
return ret
end
local function setSortedRoles(self, roles)
local id = self._parent._id
insert(roles, {id = id, position = 0})
local data, err = self.client._api:modifyGuildRolePositions(id, roles)
if data then
return true
else
return false, err
end
end
function Role:moveDown(n)
n = tonumber(n) or 1
if n < 0 then
return self:moveDown(-n)
end
local roles = getSortedRoles(self)
local new = huge
for i = #roles, 1, -1 do
local v = roles[i]
if v.id == self._id then
new = max(1, i - floor(n))
v.position = new
elseif i >= new then
v.position = i + 1
else
v.position = i
end
end
return setSortedRoles(self, roles)
end
function Role:moveUp(n)
n = tonumber(n) or 1
if n < 0 then
return self:moveUp(-n)
end
local roles = getSortedRoles(self)
local new = -huge
for i = 1, #roles do
local v = roles[i]
if v.id == self._id then
new = min(i + floor(n), #roles)
v.position = new
elseif i <= new then
v.position = i - 1
else
v.position = i
end
end
return setSortedRoles(self, roles)
end
function Role:setName(name)
return self:_modify({name = name or json.null})
end
function Role:setColor(color)
color = color and Resolver.color(color)
return self:_modify({color = color or json.null})
end
function Role:setPermissions(permissions)
permissions = permissions and Resolver.permissions(permissions)
return self:_modify({permissions = permissions or json.null})
end
function Role:hoist()
return self:_modify({hoist = true})
end
function Role:unhoist()
return self:_modify({hoist = false})
end
function Role:enableMentioning()
return self:_modify({mentionable = true})
end
function Role:disableMentioning()
return self:_modify({mentionable = false})
end
function Role:enablePermissions(...)
local permissions = self:getPermissions()
permissions:enable(...)
return self:setPermissions(permissions)
end
function Role:disablePermissions(...)
local permissions = self:getPermissions()
permissions:disable(...)
return self:setPermissions(permissions)
end
function Role:enableAllPermissions()
local permissions = self:getPermissions()
permissions:enableAll()
return self:setPermissions(permissions)
end
function Role:disableAllPermissions()
local permissions = self:getPermissions()
permissions:disableAll()
return self:setPermissions(permissions)
end
function Role:getColor()
return Color(self._color)
end
function Role:getPermissions()
return Permissions(self._permissions)
end
function get.hoisted(self)
return self._hoist
end
function get.mentionable(self)
return self._mentionable
end
function get.managed(self)
return self._managed
end
function get.name(self)
return self._name
end
function get.position(self)
return self._position
end
function get.color(self)
return self._color
end
function get.permissions(self)
return self._permissions
end
function get.mentionString(self)
return format('<@&%s>', self._id)
end
function get.guild(self)
return self._parent
end
function get.members(self)
if not self._members then
self._members = FilteredIterable(self._parent._members, function(m)
return m:hasRole(self)
end)
end
return self._members
end
function get.emojis(self)
if not self._emojis then
self._emojis = FilteredIterable(self._parent._emojis, function(e)
return e:hasRole(self)
end)
end
return self._emojis
end
return Role
|
local status_ok, null_ls = pcall(require, 'null-ls')
if not status_ok then
return false
end
local diagnostics = null_ls.builtins.diagnostics
local code_actions = null_ls.builtins.code_actions
local formatting = null_ls.builtins.formatting
local M = {}
function M.setup(opts)
null_ls.setup {
debug = true,
on_attach = opts.on_attach,
sources = {
code_actions.xo,
diagnostics.xo,
diagnostics.shellcheck,
formatting.stylua,
formatting.prettier,
},
}
end
return M
|
items = { ["panaea"] = { ["value"] = 3000, ["weight"] = 0.3, ["volume"] = 0.025 },
["ichor"] = { ["value"] = 1800, ["weight"] = 0.2, ["volume"] = 0.015 },
["gold"] = { ["value"] = 2500, ["weight"] = 2.0, ["volume"] = 0.002 }
}
max_weight = 25
max_volume = 0.25
max_num_items = {}
for i in pairs( items ) do
max_num_items[i] = math.floor( math.min( max_weight / items[i].weight, max_volume / items[i].volume ) )
end
best = { ["value"] = 0.0, ["weight"] = 0.0, ["volume"] = 0.0 }
best_amounts = {}
for i = 1, max_num_items["panaea"] do
for j = 1, max_num_items["ichor"] do
for k = 1, max_num_items["gold"] do
current = { ["value"] = i*items["panaea"]["value"] + j*items["ichor"]["value"] + k*items["gold"]["value"],
["weight"] = i*items["panaea"]["weight"] + j*items["ichor"]["weight"] + k*items["gold"]["weight"],
["volume"] = i*items["panaea"]["volume"] + j*items["ichor"]["volume"] + k*items["gold"]["volume"]
}
if current.value > best.value and current.weight <= max_weight and current.volume <= max_volume then
best = { ["value"] = current.value, ["weight"] = current.weight, ["volume"] = current.volume }
best_amounts = { ["panaea"] = i, ["ichor"] = j, ["gold"] = k }
end
end
end
end
print( "Maximum value:", best.value )
for k, v in pairs( best_amounts ) do
print( k, v )
end
|
function chowla(n)
local sum = 0
local i = 2
local j = 0
while i * i <= n do
if n % i == 0 then
j = math.floor(n / i)
sum = sum + i
if i ~= j then
sum = sum + j
end
end
i = i + 1
end
return sum
end
function sieve(limit)
-- True denotes composite, false denotes prime.
-- Only interested in odd numbers >= 3
local c = {}
local i = 3
while i * 3 < limit do
if not c[i] and (chowla(i) == 0) then
local j = 3 * i
while j < limit do
c[j] = true
j = j + 2 * i
end
end
i = i + 2
end
return c
end
function main()
for i = 1, 37 do
print(string.format("chowla(%d) = %d", i, chowla(i)))
end
local count = 1
local limit = math.floor(1e7)
local power = 100
local c = sieve(limit)
local i = 3
while i < limit do
if not c[i] then
count = count + 1
end
if i == power - 1 then
print(string.format("Count of primes up to %10d = %d", power, count))
power = power * 10
end
i = i + 2
end
count = 0
limit = 350000000
local k = 2
local kk = 3
local p = 0
i = 2
while true do
p = k * kk
if p > limit then
break
end
if chowla(p) == p - 1 then
print(string.format("%10d is a number that is perfect", p))
count = count + 1
end
k = kk + 1
kk = kk + k
i = i + 1
end
print(string.format("There are %d perfect numbers <= 35,000,000", count))
end
main()
|
include "./vendor/premake/premake-customization/solution_items.lua"
workspace ("VOEngine")
configurations {"Debug","Release"}
architecture "x64"
startproject "Sandbox"
outputDir = "%{cfg.system}-%{cfg.architecture}-%{cfg.buildcfg}"
group ""
include "VOEngine"
include "Sandbox"
include "VOEngine/vendor/GLFW" |
if not modules then modules = { } end modules ['font-imp-ligatures'] = {
version = 1.001,
comment = "companion to font-ini.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
local lpegmatch = lpeg.match
local utfsplit = utf.split
local settings_to_array = utilities.parsers.settings_to_array
local fonts = fonts
local otf = fonts.handlers.otf
local registerotffeature = otf.features.register
local addotffeature = otf.addfeature
-- This is a quick and dirty hack.
local lookups = { }
local protect = { }
local revert = { }
local zwjchar = 0x200C
local zwj = { zwjchar }
addotffeature {
name = "blockligatures",
type = "chainsubstitution",
nocheck = true, -- because there is no 0x200C in the font
prepend = true, -- make sure we do it early
future = true, -- avoid nilling due to no steps yet
lookups = {
{
type = "multiple",
data = lookups,
},
},
data = {
rules = protect,
}
}
addotffeature {
name = "blockligatures",
type = "chainsubstitution",
nocheck = true, -- because there is no 0x200C in the font
append = true, -- this is done late
overload = false, -- we don't want to overload the previous definition
lookups = {
{
type = "ligature",
data = lookups,
},
},
data = {
rules = revert,
}
}
registerotffeature {
name = 'blockligatures',
description = 'block certain ligatures',
}
local splitter = lpeg.splitat(":")
local function blockligatures(str)
local t = settings_to_array(str)
for i=1,#t do
local ti = t[i]
local before, current, after = lpegmatch(splitter,ti)
if current and after then -- before is returned when no match
-- experimental joke
if before then
before = utfsplit(before)
for i=1,#before do
before[i] = { before[i] }
end
end
if current then
current = utfsplit(current)
end
if after then
after = utfsplit(after)
for i=1,#after do
after[i] = { after[i] }
end
end
else
before = nil
current = utfsplit(ti)
after = nil
end
if #current > 1 then
local one = current[1]
local two = current[2]
lookups[one] = { one, zwjchar }
local one = { one }
local two = { two }
local new = #protect + 1
protect[new] = {
before = before,
current = { one, two },
after = after,
lookups = { 1 }, -- not shared !
}
revert[new] = {
-- before = before,
current = { one, zwj },
-- after = { two, unpack(after) },
after = { two },
lookups = { 1 }, -- not shared !
}
end
end
end
-- blockligatures("\0\0")
otf.helpers.blockligatures = blockligatures
-- blockligatures("fi,ff")
-- blockligatures("fl")
-- blockligatures("u:fl:age")
if context then
interfaces.implement {
name = "blockligatures",
arguments = "string",
actions = blockligatures,
}
end
|
local GridUI = include("lib/libgrid_ui")
local Button = include("lib/button")
local Fader = include("lib/fader")
local Rect = include("lib/rect")
local GroupButtons = include("lib/group_button")
local ControlSpec = require 'controlspec'
local Formatters = require 'formatters'
local inspect = include("lib/inspect")
local g = grid.connect()
local gridui = GridUI.new {grid = g}
function init()
local button1 = Button {
x = 1,
y = 1,
action = function(options) print("I'm button 1: " .. options.val) end
}
local button2 = Button {
x = 3,
y = 3,
width = 2,
height = 2,
momentary = 1,
action = function(options)
if options.val == 1 then
print("I'm button 2 " .. options.control.id ..
" and I'm turning off button 1")
button1:set(false)
end
end
}
gridui:add(button1)
gridui:add(button2)
gridui:add(Rect {
x = 5,
y = 5,
width = 4,
height = 4,
stroke_brightness = 13,
fill_brightness = 8
})
gridui:add(Fader {
x = 1,
y = 5,
width = 4,
height = 2,
value = 1.0,
direction = "right"
})
gridui:add(Fader {
x = 5,
y = 1,
width = 4,
height = 2,
direction = "left"
})
local gb = GroupButtons.new {
x = 10,
y = 1,
width = 2,
height = 2,
momentary = false,
columns = 3,
rows = 2,
action = function(options)
print("I'm a grid button: " .. options.group_position.x .. "/" ..
options.group_position.y .. ": " .. options.val)
end
}
gridui:add(gb)
local gb_unique = GroupButtons.new {
x = 10,
y = 6,
width = 1,
height = 1,
momentary = true,
columns = 4,
rows = 1,
action = function(options)
for i = 1, 4 do
if i == options.group_position.index then
options.group:set_index_level(i, 10)
else
options.group:set_index_level(i, 4)
end
end
end
}
gridui:add(gb_unique)
local gb_range = GroupButtons.new {
x = 10,
y = 8,
width = 1,
height = 1,
momentary = true,
columns = 6,
rows = 1,
action = function(options)
if options.group:get_pressed_count() == 2 then
local minmax = options.group:get_pressed_min_max()
print(inspect(minmax))
for i = 1, 6 do
if i >= minmax.min and i <= minmax.max then
options.group:set_index_level(i, 10)
else
options.group:set_index_level(i, 4)
end
end
end
end
}
gridui:add(gb_range)
params:add{
type = 'control',
id = 'loop_index',
name = 'Dim',
controlspec = ControlSpec.new(0, 1, 'lin', 0.05, 100, '%'),
formatter = Formatters.percentage,
action = function(value)
gridui:set_dim(value)
gridui:update()
end
}
end
function redraw()
screen.clear()
gridui:draw_on_screen()
screen.update()
end |
package("cmake")
set_kind("binary")
set_homepage("https://cmake.org")
set_description("A cross-platform family of tool designed to build, test and package software")
if is_host("macosx") then
add_urls("https://cmake.org/files/v$(version).tar.gz", {version = function (version)
return table.concat(table.slice((version):split('%.'), 1, 2), '.') .. "/cmake-" .. version .. (version:ge("3.20") and "-macos-universal" or "-Darwin-x86_64")
end})
add_urls("https://github.com/Kitware/CMake/releases/download/v$(version).tar.gz", {version = function (version)
return version .. "/cmake-" .. version .. (version:ge("3.20") and "-macos-universal" or "-Darwin-x86_64")
end})
add_versions("3.11.4", "2b5eb705f036b1906a5e0bce996e9cd56d43d73bdee8318ece3e5ce31657b812")
add_versions("3.15.4", "adfbf611d21daa83b9bf6d85ab06a455e481b63a38d6e1270d563b03d4e5f829")
add_versions("3.18.4", "9d27049660474cf134ab46fa0e0db771b263313fcb8ba82ee8b2d1a1a62f8f20")
add_versions("3.21.0", "c1c6f19dfc9c658a48b5aed22806595b2337bb3aedb71ab826552f74f568719f")
add_versions("3.22.1", "9ba46ce69d524f5bcdf98076a6b01f727604fb31cf9005ec03dea1cf16da9514")
elseif is_host("linux") and os.arch() == "x86_64" then
add_urls("https://cmake.org/files/v$(version)-x86_64.tar.gz", {version = function (version)
return table.concat(table.slice((version):split('%.'), 1, 2), '.') .. "/cmake-" .. version .. (version:ge("3.20") and "-linux" or "-Linux")
end})
add_urls("https://github.com/Kitware/CMake/releases/download/v$(version)-x86_64.tar.gz", {version = function (version)
return version .. "/cmake-" .. version .. (version:ge("3.20") and "-linux" or "-Linux")
end})
add_versions("3.11.4", "6dab016a6b82082b8bcd0f4d1e53418d6372015dd983d29367b9153f1a376435")
add_versions("3.15.4", "7c2b17a9be605f523d71b99cc2e5b55b009d82cf9577efb50d4b23056dee1109")
add_versions("3.18.4", "149e0cee002e59e0bb84543cf3cb099f108c08390392605e944daeb6594cbc29")
add_versions("3.21.0", "d54ef6909f519740bc85cec07ff54574cd1e061f9f17357d9ace69f61c6291ce")
add_versions("3.22.1", "73565c72355c6652e9db149249af36bcab44d9d478c5546fd926e69ad6b43640")
elseif is_host("windows") then
if os.arch() == "x64" then
add_urls("https://cmake.org/files/v$(version).zip", {excludes = {"*/doc/*"}, version = function (version)
return table.concat(table.slice((version):split('%.'), 1, 2), '.') .. "/cmake-" .. version .. (version:ge("3.20") and "-windows-x86_64" or "-win64-x64")
end})
add_urls("https://github.com/Kitware/CMake/releases/download/v$(version).zip", {excludes = {"*/doc/*"}, version = function (version)
return version .. "/cmake-" .. version .. (version .. (version:ge("3.20") and "-windows-x86_64" or "-win64-x64"))
end})
add_versions("3.11.4", "d3102abd0ded446c898252b58857871ee170312d8e7fd5cbff01fbcb1068a6e5")
add_versions("3.15.4", "5bb49c0274800c38833e515a01af75a7341db68ea82c71856bb3cf171d2068be")
add_versions("3.18.4", "a932bc0c8ee79f1003204466c525b38a840424d4ae29f9e5fb88959116f2407d")
add_versions("3.21.0", "c7b88c907a753f4ec86e43ddc89f91f70bf1b011859142f7f29e6d51ea4abb3c")
add_versions("3.22.1", "35fbbb7d9ffa491834bbc79cdfefc6c360088a3c9bf55c29d111a5afa04cdca3")
else
add_urls("https://cmake.org/files/v$(version)-win32-x86.zip", {excludes = {"*/doc/*"}, version = function (version)
return table.concat(table.slice((version):split('%.'), 1, 2), '.') .. "/cmake-" .. version .. (version:ge("3.20") and "-windows-i386" or "-win32-x86")
end})
add_urls("https://github.com/Kitware/CMake/releases/download/v$(version).zip", {excludes = {"*/doc/*"}, version = function (version)
return version .. "/cmake-" .. version .. (version .. (version:ge("3.20") and "-windows-i386" or "-win32-x86"))
end})
add_versions("3.11.4", "b068001ff879f86e704977c50a8c5917e4b4406c66242366dba2674abe316579")
add_versions("3.15.4", "19c2bfd26c4de4d8046dd5ad6de95b57a2556559ec81b13b94e63ea4ae49b3f2")
add_versions("3.18.4", "4c519051853686927f87df99669ada3ff15a3086535a7131892febd7c6e2f122")
add_versions("3.21.0", "11ee86b7f9799724fc16664c63e308bfe3fbc22c9df8ef4955ad4b248f3e680b")
add_versions("3.22.1", "f53494e3b35e5a1177ad55c28763eb5bb45772c1d80778c0f96c45ce4376b6e8")
end
else
add_urls("https://github.com/Kitware/CMake/releases/download/v$(version)/cmake-$(version).tar.gz")
add_versions("3.18.4", "597c61358e6a92ecbfad42a9b5321ddd801fc7e7eca08441307c9138382d4f77")
add_versions("3.21.0", "4a42d56449a51f4d3809ab4d3b61fd4a96a469e56266e896ce1009b5768bd2ab")
add_versions("3.22.1", "0e998229549d7b3f368703d20e248e7ee1f853910d42704aa87918c213ea82c0")
end
if is_plat("mingw") and is_subhost("msys") then
add_extsources("pacman::cmake")
elseif is_plat("linux") then
add_extsources("pacman::cmake", "apt::cmake")
elseif is_plat("macosx") then
add_extsources("brew::cmake")
end
on_install("@macosx", function (package)
os.cp("CMake.app/Contents/bin", package:installdir())
os.cp("CMake.app/Contents/share", package:installdir())
end)
on_install("@linux|x86_64", "@windows", "@msys", "@cygwin", function (package)
os.cp("bin", package:installdir())
os.cp("share", package:installdir())
end)
on_install("@bsd", function (package)
os.vrunv("sh", {"./bootstrap", "--prefix=" .. package:installdir()})
import("package.tools.make").install(package)
end)
on_test(function (package)
os.vrun("cmake --version")
end)
|
-- General
modName = "RealisticOres"
modRoot = "__" .. modName .. "__"
-- Colors
mainColors = {
iron = {r=0.615, g=0.320, b=0.247},
copper = {r=0.356, g=0.608, b=0.530},
uranium = {r=0.718, g=0.761, b=0.200}
}
-- Settings names
oreNames = {"iron", "copper", "uranium"}
local oreSetting_none = "none"
local oreSetting_patches = "patches"
local oreSetting_items = "items"
local oreSetting_all = "all"
oreSettingValues = {oreSetting_none, oreSetting_patches, oreSetting_items, oreSetting_all}
defaultOreSettingValue = oreSetting_all
local settingNamePrefix = modName .. "-"
function getOreSettingName(oreName)
return settingNamePrefix .. oreName
end
uraniumGlowSettingName = settingNamePrefix .. "uraniumGlow"
angelsInfiniteOresSettingName = settingNamePrefix .. "angelsInfiniteOres"
deadlocksStackingBeltboxesSettingName = settingNamePrefix .. "deadlocksStackingBeltboxes"
simpleCompressSettingName = settingNamePrefix .. "simpleCompress"
miningDronesSettingName = settingNamePrefix .. "miningDrones"
oldOreSettingName = settingNamePrefix .. "oldOre"
-- Settings utils
function getOreSettings()
return {
iron = settings.startup[getOreSettingName("iron")].value,
copper = settings.startup[getOreSettingName("copper")].value,
uranium = settings.startup[getOreSettingName("uranium")].value
}
end
function patchesEnabled(oreSetting)
return oreSetting == oreSetting_patches or oreSetting == oreSetting_all
end
function itemsEnabled(oreSetting)
return oreSetting == oreSetting_items or oreSetting == oreSetting_all
end
|
local SCANCODE = {
-- UNKNOWN = 0,
A = 4,
B = 5,
C = 6,
D = 7,
E = 8,
F = 9,
G = 10,
H = 11,
I = 12,
J = 13,
K = 14,
L = 15,
M = 16,
N = 17,
O = 18,
P = 19,
Q = 20,
R = 21,
S = 22,
T = 23,
U = 24,
V = 25,
W = 26,
X = 27,
Y = 28,
Z = 29,
NUM_1 = 30,
NUM_2 = 31,
NUM_3 = 32,
NUM_4 = 33,
NUM_5 = 34,
NUM_6 = 35,
NUM_7 = 36,
NUM_8 = 37,
NUM_9 = 38,
NUM_0 = 39,
RETURN = 40,
ESCAPE = 41,
BACKSPACE = 42,
TAB = 43,
SPACE = 44,
MINUS = 45,
EQUALS = 46,
LEFTBRACKET = 47,
RIGHTBRACKET = 48,
BACKSLASH = 49,
NONUSHASH = 50,
SEMICOLON = 51,
APOSTROPHE = 52,
GRAVE = 53,
COMMA = 54,
PERIOD = 55,
SLASH = 56,
CAPSLOCK = 57,
F1 = 58,
F2 = 59,
F3 = 60,
F4 = 61,
F5 = 62,
F6 = 63,
F7 = 64,
F8 = 65,
F9 = 66,
F10 = 67,
F11 = 68,
F12 = 69,
PRINTSCREEN = 70,
SCROLLLOCK = 71,
PAUSE = 72,
INSERT = 73,
HOME = 74,
PAGEUP = 75,
DELETE = 76,
END = 77,
PAGEDOWN = 78,
RIGHT = 79,
LEFT = 80,
DOWN = 81,
UP = 82,
NUMLOCKCLEAR = 83,
KP_DIVIDE = 84,
KP_MULTIPLY = 85,
KP_MINUS = 86,
KP_PLUS = 87,
KP_ENTER = 88,
KP_1 = 89,
KP_2 = 90,
KP_3 = 91,
KP_4 = 92,
KP_5 = 93,
KP_6 = 94,
KP_7 = 95,
KP_8 = 96,
KP_9 = 97,
KP_0 = 98,
KP_PERIOD = 99,
NONUSBACKSLASH = 100,
APPLICATION = 101,
POWER = 102,
KP_EQUALS = 103,
F13 = 104,
F14 = 105,
F15 = 106,
F16 = 107,
F17 = 108,
F18 = 109,
F19 = 110,
F20 = 111,
F21 = 112,
F22 = 113,
F23 = 114,
F24 = 115,
EXECUTE = 116,
HELP = 117,
MENU = 118,
SELECT = 119,
STOP = 120,
AGAIN = 121,
UNDO = 122,
CUT = 123,
COPY = 124,
PASTE = 125,
FIND = 126,
MUTE = 127,
VOLUMEUP = 128,
VOLUMEDOWN = 129,
AUDIONEXT = 258,
AUDIOPREV = 259,
AUDIOSTOP = 260,
AUDIOPLAY = 261,
AUDIOMUTE = 262,
MEDIASELECT = 263,
WWW = 264,
MAIL = 265,
CALCULATOR = 266,
COMPUTER = 267,
AC_SEARCH = 268,
AC_HOME = 269,
AC_BACK = 270,
AC_FORWARD = 271,
AC_STOP = 272,
AC_REFRESH = 273,
AC_BOOKMARKS = 274,
BRIGHTNESSDOWN = 275,
BRIGHTNESSUP = 276,
DISPLAYSWITCH = 277,
KBDILLUMTOGGLE = 278,
KBDILLUMDOWN = 279,
KBDILLUMUP = 280,
EJECT = 281,
SLEEP = 282,
APP1 = 283,
APP2 = 284,
AUDIOREWIND = 285,
AUDIOFASTFORWARD = 286,
-- NUM_SCANCODES = 512
}
return SCANCODE
|
local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_FIREDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_RED)
combat:setArea(createCombatArea(AREA_CIRCLE6X6))
function onTargetCreature(creature, target)
creature:addDamageCondition(target, CONDITION_FIRE, DAMAGELIST_VARYING_PERIOD, 10, {8, 10}, 20)
end
combat:setCallback(CALLBACK_PARAM_TARGETCREATURE, "onTargetCreature")
function onCastSpell(creature, variant)
return combat:execute(creature, variant)
end
|
-- Rename a file or directory.
-- Invoke the script with a 'source' parameter containing the full path to the
-- file/folder to rename, and a 'name' parameter containing the new name (without path).
-- Mind that URL length for these Lua scripts is limited to about 155 bytes (at
-- least on the version of the firmware I'm currently using), so this script cannot
-- be used with very deep directory trees or ridiculously long names.
-- Due to another quirk of the Lua server routine, spaces in file names are to be avoided,
-- although they should work for sensible file names.
-- Part of FlashAir Fancy Web Interface by Dr. Lex
-- Released under BSD 2-Clause License. See other files for license details.
function urldecode(s)
local s = s:gsub('+', ' ')
:gsub('%%(%x%x)', function(h)
return string.char(tonumber(h, 16))
end)
return s
end
function parsequery(s)
local ans = {}
for k,v in s:gmatch('([^&=]-)=([^&=]+)' ) do
ans[ k ] = urldecode(v)
end
return ans
end
function filename(s)
return string.gsub(s, "^.*/", "")
end
function printHttp(s)
print("HTTP/1.1 200 OK")
print("Content-Type: text/plain")
print("")
print(s)
end
argm = arg[1]
if argm == nil then
argm = ""
else
-- Annoying: the query string gets split up by whitespace. This workaround allows
-- to rename things with spaces as long as there are no two consecutive spaces.
argm = table.concat(arg, " ")
end
-- For some reason there is a newline at the end of argm: zap it.
queryFields = parsequery(string.gsub(argm, "\n$", ""))
if queryFields.source == nil then
printHttp("ERROR: Missing parameter 'source'")
return
end
if queryFields.name == nil then
printHttp("ERROR: Missing parameter 'name'")
return
end
name = queryFields.name
source = queryFields.source
if lfs.attributes(source) == nil then
printHttp("ERROR: source file '" .. source .. "' does not exist")
return
end
dir = source:match("(.*/)")
-- Invoking fa.rename with a string concatenation makes the script go boom, therefore copy to separate variables. Don't ask me why.
targetPath = dir .. name
-- Avoid pointless operations, this would append '(1)' to the filename.
if source ~= targetPath then
-- os.rename does not work and the alternative fa.rename has no return value, hence success of the operation must be tested separately
fa.rename(source, targetPath)
if lfs.attributes(targetPath) == nil then
printHttp("ERROR: failed to rename '" .. source .. "' to '" .. name .. "'")
return
end
end
printHttp("SUCCESS")
|
local tag = "MWP"
local PLAYER = FindMetaTable("Player")
PLAYER._Give = PLAYER._Give or PLAYER.Give
function PLAYER:Give(class, ...)
self._mwp_allowpickup = true
self:_Give(class, ...)
self._mwp_allowpickup = false
end
hook.Add("PlayerCanPickupWeapon", tag, function(ply, wep)
local trace = ply:GetEyeTrace()
if ply:HasWeapon(wep:GetClass()) or (ply:KeyDown(IN_USE) and trace.Entity == wep) then
ply._mwp_allowpickup = true
end
if ply._mwp_allowpickup then
timer.Simple(0, function()
ply._mwp_allowpickup = false
end)
end
return ply._mwp_allowpickup
end)
|
function CDOTA_BaseNPC:UnitHasSlotForItem(itemname, bBackpack)
if self.HasRoomForItem then
return self:HasRoomForItem(itemname, bBackpack, true) ~= 4
else
for i = 0, bBackpack and DOTA_STASH_SLOT_6 or DOTA_ITEM_SLOT_9 do
local item = self:GetItemInSlot(i)
if not IsValidEntity(item) or (item:GetAbilityName() == itemname and item:IsStackable()) then
return true
end
end
return false
end
end
function FillSlotsWithDummy(unit, bNoStash)
for i = 0, bNoStash and DOTA_ITEM_SLOT_9 or DOTA_STASH_SLOT_6 do
local current_item = unit:GetItemInSlot(i)
if not current_item then
unit:AddItemByName("item_dummy")
end
end
end
function ClearSlotsFromDummy(unit, bNoStash)
for i = 0, bNoStash and DOTA_ITEM_SLOT_9 or DOTA_STASH_SLOT_6 do
local current_item = unit:GetItemInSlot(i)
if current_item and current_item:GetAbilityName() == "item_dummy" then
unit:RemoveItem(current_item)
UTIL_Remove(current_item)
end
end
end
function SetAllItemSlotsLocked(unit, locked, bNoStash)
for i = 0, bNoStash and DOTA_ITEM_SLOT_9 or DOTA_STASH_SLOT_6 do
local current_item = unit:GetItemInSlot(i)
if current_item then
if locked or not current_item.player_locked then
current_item.auto_lock_order = true
ExecuteOrderFromTable({
UnitIndex = unit:GetEntityIndex(),
OrderType = DOTA_UNIT_ORDER_SET_ITEM_COMBINE_LOCK,
AbilityIndex = current_item:GetEntityIndex(),
TargetIndex = locked and 1 or 0,
Queue = false
})
end
end
end
end
function swap_to_item(unit, srcItem, newItem)
FillSlotsWithDummy(unit)
if unit:HasItemInInventory(srcItem:GetName()) then
unit:RemoveItem(srcItem)
unit:AddItem(newItem)
end
ClearSlotsFromDummy(unit)
end
function FindItemInInventoryByName(unit, itemname, searchStash, onlyStash, ignoreBackpack)
local lastSlot = ignoreBackpack and DOTA_ITEM_SLOT_6 or DOTA_ITEM_SLOT_9
local startSlot = 0
if searchStash then lastSlot = DOTA_STASH_SLOT_6 end
if onlyStash then startSlot = DOTA_STASH_SLOT_1 end
for slot = startSlot, lastSlot do
local item = unit:GetItemInSlot(slot)
if item and item:GetAbilityName() == itemname then
return item
end
end
end
function CDOTA_Item:SpendCharge(amount)
local newCharges = self:GetCurrentCharges() - (amount or 1)
if newCharges <= 0 then
UTIL_Remove(self)
else
self:SetCurrentCharges(newCharges)
end
end
|
function EFFECT:Init(data)
local pos = data:GetOrigin()
local emitter = ParticleEmitter(pos)
local color = data:GetStart()
local smokesprnum=math.random(1,16)
local smokespr="particle/smokesprites_00"
if (smokesprnum>9) then
smokespr=smokespr..smokesprnum
else
smokespr=smokespr.."0"..smokesprnum
end
for i=1,20 do
local particle=emitter:Add(smokespr,pos)
particle:SetVelocity(Vector(math.Rand(-1,1),math.Rand(-1,1),math.Rand(-1,1))*math.Rand(150,200))
particle:SetDieTime(math.Rand(3,8))
particle:SetEndAlpha(0)
particle:SetCollide(true)
particle:SetDieTime(10)
particle:SetStartAlpha(math.Rand(200,255))
particle:SetEndSize(math.Rand(200,300))
particle:SetStartSize(math.Rand(100,150))
particle:SetRoll(math.Rand(0,360))
particle:SetRollDelta(math.Rand(-0.2,0.2))
particle:SetColor(color.r,color.g,color.b)
particle:SetGravity(Vector(0,0,math.Rand(1,10)))
particle:SetAirResistance(100)
end
emitter:Finish()
end
function EFFECT:Think()
return false
end
function EFFECT:Render()
end
|
object_mobile_selonian_female_27 = object_mobile_shared_selonian_female_27:new {
}
ObjectTemplates:addTemplate(object_mobile_selonian_female_27, "object/mobile/selonian_female_27.iff")
|
-- Persistent Data
local multiRefObjects = {
} -- multiRefObjects
local obj1 = {
["DatabaseTemplate"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/database";
["extension"] = 7;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/database/src/controllers/DatabaseTemplate.css";
};
["DatabaseNavigation"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/database";
["extension"] = 7;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/database/src/widgets/DatabaseNavigation.css";
};
["style"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/baseline";
["extension"] = 2;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/baseline/src/widgets/style.css";
};
["EditorTemplate"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor";
["extension"] = 5;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor/src/controllers/EditorTemplate.css";
};
["Cart"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/widgets/checkout/Cart.css";
};
["HorizontalNavigation"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop";
["extension"] = 8;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/shop/src/widgets/catalog/HorizontalNavigation.css";
};
["DatabaseHeader"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/database";
["extension"] = 7;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/database/src/widgets/DatabaseHeader.css";
};
["EditorHeader"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor";
["extension"] = 5;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor/src/widgets/EditorHeader.css";
};
["RepositoryTemplate"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/repository";
["extension"] = 6;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/repository/src/controllers/RepositoryTemplate.css";
};
["EditorNavigation"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor";
["extension"] = 5;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/editor/src/widgets/EditorNavigation.css";
};
["Popup"] = {
[1] = {
["octopusHostDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions";
["extensionDir"] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/baseline";
["extension"] = 2;
};
[2] = "/data/Project/octopus_orig/bin/unix/../../sites/extensions/baseline/src/widgets/popup/Popup.css";
};
}
return obj1
|
--[[
Copyright (c) 2013 David Young dayoung@goliathdesigns.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
]]
require "LuaTest"
local moduleName = "VectorTest";
LuaTest_AddTest(
moduleName, "Addition1", function()
local vector = Vector.new() + 2;
AssertEqual(2, vector.x);
AssertEqual(2, vector.y);
AssertEqual(2, vector.z);
end
);
LuaTest_AddTest(
moduleName, "Addition2", function()
local vector = 2 + Vector.new();
AssertNil(vector);
end
);
LuaTest_AddTest(
moduleName, "Addition3", function()
local vector = Vector.new(1, 2, 3) + Vector.new(1, 2, 3);
AssertEqual(2, vector.x);
AssertEqual(4, vector.y);
AssertEqual(6, vector.z);
end
);
LuaTest_AddTest(
moduleName, "Assignment", function()
local vector = Vector.new();
vector.x = 10;
vector.y = 5;
vector.z = 1;
AssertEqual(10, vector.x);
AssertEqual(5, vector.y);
AssertEqual(1, vector.z);
end
);
LuaTest_AddTest(
moduleName, "Constructor1", function()
local vector = Vector.new();
AssertEqual(0, vector.x);
AssertEqual(0, vector.y);
AssertEqual(0, vector.z);
end
);
LuaTest_AddTest(
moduleName, "Constructor2", function()
local vector = Vector.new(10);
AssertEqual(10, vector.x);
AssertEqual(10, vector.y);
AssertEqual(10, vector.z);
end
);
LuaTest_AddTest(
moduleName, "Constructor3", function()
local vector = Vector.new(1, 2, 3);
AssertEqual(1, vector.x);
AssertEqual(2, vector.y);
AssertEqual(3, vector.z);
end
);
LuaTest_AddTest(
moduleName, "CopyConstructor", function()
local expectedVector = Vector.new(10);
local vector = Vector.new(expectedVector);
AssertEqual(expectedVector.x, vector.x);
AssertEqual(expectedVector.y, vector.y);
AssertEqual(expectedVector.z, vector.z);
AssertEqual(10, vector.x);
AssertEqual(10, vector.y);
AssertEqual(10, vector.z);
end
);
LuaTest_AddTest(
moduleName, "Subtraction1", function()
local vector = Vector.new(1, 2, 3) - 2;
AssertEqual(-1, vector.x);
AssertEqual(0, vector.y);
AssertEqual(1, vector.z);
end
);
LuaTest_AddTest(
moduleName, "Subtraction2", function()
local vector = 2 - Vector.new(1, 2, 3);
AssertNil(vector);
end
);
LuaTest_AddTest(
moduleName, "Subtraction3", function()
local vector = Vector.new(1, 2, 3) - Vector.new(5, 7, 1);
AssertEqual(-4, vector.x);
AssertEqual(-5, vector.y);
AssertEqual(2, vector.z);
end
);
function Sandbox_TestVector()
local vector2Mul1 = vector2 * 2;
local vector2Mul2 = vector2 * vector2;
local vector2Mul3 = 2 * vector2; -- should be nil
local vector2Div1 = vector2 / 2;
local veoctr2Div2 = vector2 / vector2;
local vector2Div3 = 2 / vector2; -- should be nil
local vector2Neg1 = -vector2;
local vector2Eq1 = vector2 == vector3;
local vector2Eq2 = Vector.new(10) == vector2;
local vector2Eq3 = vector4 == vector2;
local vector2Neq1 = vector2 ~= vector3;
local vector2Neq2 = Vector.new(10) ~= vector2;
local vector2Neq3 = vector4 ~= vector2;
local vector2String = tostring(vector2);
return;
end
|
--[[------------------------------------------------------
lk.Process
----------
A Process is just a lk.Patch with network connectivity
through the use of an lk.Service.
--]]------------------------------------------------------
local lib = {type='lk.Process'}
lib.__index = lib
lk.Process = lib
-- lk.Process inherits from lk.Patch
--setmetatable(lib, lk.Patch)
setmetatable(lib, {
-- new method
__call = function(lib, name)
local self = lk.Patch(name)
local opts = {
callback = function(...)
return self:callback(...)
end,
registration_callback = function(reg, service)
if Lubyk.zone .. ':' .. name ~= service.name then
printf("Existing process '%s'. Quit.", name)
sched:quit()
else
self:start()
end
end,
}
self.service = lk.Service(Lubyk.zone .. ':' .. self.name, opts)
return self
end})
--- All code is in lk.Patch (Patch.lua)
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Forcer"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Forcer"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
self:NetworkVar( "Bool", 0, "ShowBeam" )
self:NetworkVar( "Bool", 1, "BeamHighlight" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Force = 0
self.OffsetForce = 0
self.Velocity = 0
self.Inputs = WireLib.CreateInputs( self, { "Force", "OffsetForce", "Velocity", "Length" } )
self:Setup(0, 100, true, false)
end
function ENT:Setup( Force, Length, ShowBeam, Reaction )
self.ForceMul = Force or 1
self.Reaction = Reaction or false
if Length then self:SetBeamLength(Length) end
if ShowBeam ~= nil then self:SetShowBeam(ShowBeam) end
self:ShowOutput()
end
function ENT:TriggerInput( name, value )
if (name == "Force") then
self.Force = value
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "OffsetForce") then
self.OffsetForce = value
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "Velocity") then
self.Velocity = math.Clamp(value,-100000,100000)
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "Length") then
self:SetBeamLength(math.Round(value))
self:ShowOutput()
end
end
function ENT:Think()
if self.Force == 0 and self.OffsetForce == 0 and self.Velocity == 0 then return end
local Forward = self:GetUp()
local BeamOrigin = self:GetPos() + Forward * self:OBBMaxs().z
local trace = util.TraceLine {
start = BeamOrigin,
endpos = BeamOrigin + self:GetBeamLength() * Forward,
filter = self
}
if not IsValid(trace.Entity) then return end
if not gamemode.Call( "GravGunPunt", self:GetPlayer(), trace.Entity ) then return end
if trace.Entity:GetMoveType() == MOVETYPE_VPHYSICS then
local phys = trace.Entity:GetPhysicsObject()
if not IsValid(phys) then return end
if self.Force ~= 0 then phys:ApplyForceCenter( Forward * self.Force * self.ForceMul ) end
if self.OffsetForce ~= 0 then phys:ApplyForceOffset( Forward * self.OffsetForce * self.ForceMul, trace.HitPos ) end
if self.Velocity ~= 0 then phys:SetVelocityInstantaneous( Forward * self.Velocity ) end
else
if self.Velocity ~= 0 then trace.Entity:SetVelocity( Forward * self.Velocity ) end
end
if self.Reaction and IsValid(self:GetPhysicsObject()) and (self.Force + self.OffsetForce ~= 0) then
self:GetPhysicsObject():ApplyForceCenter( Forward * -(self.Force + self.OffsetForce) * self.ForceMul )
end
self:NextThink( CurTime() )
return true
end
function ENT:ShowOutput()
self:SetOverlayText(
"Center Force = "..math.Round(self.ForceMul * self.Force)..
"\nOffset Force = "..math.Round(self.ForceMul * self.OffsetForce)..
"\nVelocity = "..math.Round(self.Velocity)..
"\nLength = " .. math.Round(self:GetBeamLength())
)
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.ForceMul = self.ForceMul
info.Reaction = self.Reaction
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self:Setup( info.ForceMul, info.Length, info.ShowBeam, info.Reaction )
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
end
--Moves old "A" input to new "Force" input for older saves
WireLib.AddInputAlias( "A", "Force" )
duplicator.RegisterEntityClass("gmod_wire_forcer", WireLib.MakeWireEnt, "Data", "Force", "Length", "ShowBeam", "Reaction")
|
return function ()
describe("Checkbox", function()
it("should boot", function()
local Icon = require(script.Parent)
expect(Icon).to.be.ok()
end)
it("should construct", function()
local Icon = require(script.Parent)
local icon = Icon.new({})
expect(icon).never.to.equal(nil)
icon:Destroy()
end)
end)
end |
--
-- Content
--
--- A content window for each tab.
--- Responsible for rendering the editor.
Content = {}
Content.__index = Content
--- The starting y position of the tab.
Content.startY = 3
--- The width of a tab in spaces
Content.tabWidth = 2
--- Create a new content window.
function Content.new(...)
local self = setmetatable({}, Content)
self:setup(...)
return self
end
function Content:setup()
local w, h = term.native().getSize()
self.height = h - Content.startY + 1
self.width = w
self.win = window.create(term.native(), 1, Content.startY, self.width, self.height, false)
self.editor = Editor.new({""}, self.width, self.height)
self.path = nil
self.highlighter = SyntaxHighlighter.new()
self:updateSyntaxHighlighting("")
end
--- Open a set of lines
function Content:open(path, lines)
self.path = path
self.editor = Editor.new(lines, self.width, self.height)
self:updateSyntaxHighlighting("")
end
--- Set the file currently being edited in this tab.
--- Discards the current file and all changes and replaces it.
--- Returns nil on success and a string error message on failure.
function Content:edit(path)
if fs.isDir(path) then
Panel.error("Couldn't open file.", "", "Cannot edit a", "directory.")
elseif fs.exists(path) then
local lines, err = File.load(path)
if lines then
self:open(path, lines)
else
Popup.errorPopup("Failed to open file", err)
end
else
self:open(path, {""})
end
end
--- Save the contents of the editor.
function Content:save(path)
if not self.path then
self.path = path
end
if not path then
path = self.path
end
if not path then
Popup.errorPopup("No path specified to save to!")
end
local err = File.save(self.editor.lines, path)
if err then
Popup.errorPopup("Failed to save file", err)
end
end
--- Returns the name of the file being edited.
function Content:name()
if not self.path then
return "untitled"
else
return fs.getName(self.path)
end
end
--- Returns true if the content is unedited
function Content:isUnedited()
return self.path == nil and #self.editor.lines == 1 and self.editor.lines[1]:len() == 0
end
--- Shows the content window's window, redrawing it over the existing screen space
--- and restoring the cursor to its original position in the window.
function Content:show()
term.redirect(self.win)
self.win.setVisible(true)
self:draw()
self:restoreCursor()
end
--- Hides the window.
function Content:hide()
self.win.setVisible(false)
end
--- Sets the cursor position to that defined by the editor.
function Content:restoreCursor()
local x, y = self.editor:cursorPosition()
term.redirect(self.win)
term.setCursorPos(x, y)
term.setTextColor(Theme["editor text"])
term.setCursorBlink(true)
end
--- Renders a whole line - gutter and text.
--- Does not redirect to the terminal.
function Content:drawLine(y)
term.setBackgroundColor(Theme["editor background"])
term.setCursorPos(1, y)
term.clearLine()
self:drawText(y)
self:drawGutter(y)
end
--- Renders the gutter on a single line.
function Content:drawGutter(y)
if y == self.editor.cursor.y then
term.setBackgroundColor(Theme["gutter background focused"])
term.setTextColor(Theme["gutter text focused"])
else
term.setBackgroundColor(Theme["gutter background"])
term.setTextColor(Theme["gutter text"])
end
local size = self.editor:gutterSize()
local lineNumber = tostring(y + self.editor.scroll.y)
local padding = string.rep(" ", size - lineNumber:len() - 1)
lineNumber = padding .. lineNumber .. Theme["gutter separator"]
term.setCursorPos(1, y)
term.write(lineNumber)
end
--- Renders the text for a single line.
function Content:drawText(y)
local absoluteY = y + self.editor.scroll.y
local data = self.highlighter:data(absoluteY, self.editor.scroll.x, self.width)
term.setBackgroundColor(Theme["editor background"])
term.setTextColor(Theme["editor text"])
term.setCursorPos(self.editor:gutterSize() + 1, y)
for _, item in pairs(data) do
if item.kind == "text" then
-- Render some text
term.write(item.data)
elseif item.kind == "color" then
-- Set the current text color
local index = item.data
if index == "text" then
index = "editor text"
end
term.setTextColor(Theme[index])
end
end
end
--- Fully redraws the editor.
function Content:draw()
term.redirect(self.win)
-- Clear
term.setBackgroundColor(Theme["editor background"])
term.clear()
-- Iterate over each line
local lineCount = math.min(#self.editor.lines, self.height)
for y = 1, lineCount do
self:drawText(y)
self:drawGutter(y)
end
-- Restore the cursor position
self:restoreCursor()
end
--- Updates the screen based off what the editor says needs redrawing.
function Content:updateDirty()
local dirty = self.editor:dirty()
if dirty then
if dirty == "full" then
self:draw()
else
term.redirect(self.win)
for _, data in pairs(dirty) do
if data.kind == "gutter" then
self:drawGutter(data.data)
elseif data.kind == "line" then
self:drawLine(data.data)
end
end
end
self.editor:clearDirty()
end
end
--- Updates the syntax highlighter.
--- Triggers an update of the mapped data if character is non-nil,
--- and a full redraw if character is one of the full redraw triggers.
function Content:updateSyntaxHighlighting(character)
if character then
self.highlighter:update(self.editor.lines)
-- Trigger a full redraw if a mapped character was typed (ie. affects
-- the highlighting on other lines).
if SyntaxHighlighter.fullRedrawTriggers:find(character, 1, true) then
self.editor:setDirty("full")
end
end
end
--- Called when a key event occurs.
function Content:key(key)
if key == keys.up then
self.editor:moveCursorUp()
elseif key == keys.down then
self.editor:moveCursorDown()
elseif key == keys.left then
self.editor:moveCursorLeft()
elseif key == keys.right then
self.editor:moveCursorRight()
elseif key == keys.backspace then
local character = self.editor:backspace()
self:updateSyntaxHighlighting(character)
elseif key == keys.tab then
for i = 1, Content.tabWidth do
self.editor:insertCharacter(" ")
end
self:updateSyntaxHighlighting(" ")
elseif key == keys.enter then
self.editor:insertNewline()
self:updateSyntaxHighlighting("\n")
end
end
--- Called when a char event occurs.
function Content:char(character)
self.editor:insertCharacter(character)
self:updateSyntaxHighlighting(character)
end
--- Called when an event occurs.
function Content:event(event)
if event[1] == "char" then
self:char(event[2])
elseif event[1] == "key" then
self:key(event[2])
elseif event[1] == "mouse_click" or event[1] == "mouse_drag" then
self.editor:moveCursorToRelative(event[3] - self.editor:gutterSize(), event[4])
return true
end
self:updateDirty()
self:restoreCursor()
return false
end
|
local M = {}
local function serialize(obj)
local lua = ""
local t = type(obj)
if t == "number" then
lua = lua .. obj
elseif t == "boolean" then
lua = lua .. tostring(obj)
elseif t == "string" then
lua = lua .. string.format("%q", obj)
elseif t == "table" then
lua = lua .. "{\n"
for k, v in pairs(obj) do
lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
end
local metatable = getmetatable(obj)
if metatable ~= nil and type(metatable.__index) == "table" then
for k, v in pairs(metatable.__index) do
lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
end
end
lua = lua .. "}"
elseif t == "nil" then
return "nil"
elseif t == "userdata" then
return "userdata"
elseif t == "function" then
return "function"
else
error("can not serialize a " .. t .. " type.")
end
return lua
end
function M.print(...)
local t = {...}
local ret = {}
for _,v in pairs(t) do
table.insert(ret, serialize(v))
end
print(table.concat(ret, ", "))
end
function M.split(str, delimiter)
if str == nil or str == '' or delimiter == nil then
return nil
end
local result = {}
for match in (str..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match)
end
return result
end
function M.hex(str)
local len = #str
local ret = ""
for i=1,len do
local c = tonumber(str:byte(i))
local cstr = string.format("%02X ", c)
ret = ret .. cstr
end
print(ret)
end
return M |
vtest = 1
mtest = 1
ptest = 1
local _ip = require "vyacht-ip"
local vy = require "vyacht"
local bus = require "ubus"
_uci_real = cursor or _uci_real or uci.cursor()
vubus = bus.connect()
function test_validAddress(ip, valid)
iparr, prefix = _ip.IPv4AddressToArray(ip)
if valid then
assert((iparr ~= nil) and (prefix ~= null))
else
assert((iparr == nil) and (prefix == null))
end
end
function test_validIP(ip, valid)
assert(_ip.IPv4ValidIP(ip) == valid)
end
function test_validPrefix(prefix, valid)
assert(_ip.IPv4ValidPrefix(prefix) == valid)
end
function test_addressToAddressAndPrefix(address)
local ip, prefix = _ip.IPv4ToIPAndPrefix(address)
if prefix == nil and ip == nil then
prefix = ""
ip = ""
end
print("address= " .. address .. ", ip = " .. ip .. ", prefix= " .. prefix)
end
test_addressToAddressAndPrefix("192.168.1.1")
test_addressToAddressAndPrefix("192.168.1.1/33")
test_addressToAddressAndPrefix("sadsadsa/ds")
test_addressToAddressAndPrefix(".......")
function test_addressToAddressAndPrefix(address)
local ip, prefix = _ip.IPv4ToIPAndPrefix(address)
if prefix == nil and ip == nil then
prefix = ""
ip = ""
end
print("address= " .. address .. ", ip = " .. ip .. ", prefix= " .. prefix)
end
function testNetmaskValue(prefix)
print("prefix = " .. prefix .. ", mask= " .. _ip.getNetmask(prefix))
end
function testNetmask(prefix)
local ip = _ip.getNetmask(prefix)
if ip == nil then
print("prefix = " .. prefix .. " is nil")
end
print("prefix = " .. prefix .. ", mask= " .. string.format("%i.%i.%i.%i", ip[1], ip[2], ip[3], ip[4]))
end
test_addressToAddressAndPrefix("192.168.1.1")
test_addressToAddressAndPrefix("192.168.1.1/33")
test_addressToAddressAndPrefix("sadsadsa/ds")
test_addressToAddressAndPrefix(".......")
test_validAddress("192.168.1.1", true)
test_validAddress("192.168.1.1", true)
test_validAddress("192.1.1", false)
test_validAddress("192.168..1", false)
test_validAddress("192.168.256.1", false)
test_validAddress("192.168.-11.1", false)
test_validAddress("192.168.11.1/24", true)
test_validAddress("192.168.11.1/0", true)
test_validAddress("192.168.11.1/33", false)
test_validAddress("sumpf", false)
test_validAddress("sadhjjsad.asdsad.aasd.sss/sd", false)
test_validAddress("........./.", false)
test_validAddress("..../.", false)
test_validIP("192.168.1.1", true)
test_validIP("192.168.1.1", true)
test_validIP("192.1.1", false)
test_validIP("192.168..1", false)
test_validIP("192.168.256.1", false)
test_validIP("192.168.-11.1", false)
test_validIP("192.168.11.1", true)
test_validIP("sumpf", false)
test_validIP("sadhjjsad.asdsad.aasd.sss", false)
test_validIP(".........", false)
test_validPrefix(0, true)
test_validPrefix(14, true)
test_validPrefix(-1, false)
test_validPrefix(33, false)
test_validPrefix("0", true)
test_validPrefix("14", true)
test_validPrefix("-1", false)
test_validPrefix("33", false)
assert( 1 == _ip.getHosts(32))
assert( 2 == _ip.getHosts(31))
assert( 256 == _ip.getHosts(24))
assert( 262144 == _ip.getHosts(14))
assert(2147483648 == _ip.getHosts(1))
assert(4294967296 == _ip.getHosts(0))
function testInRange(testIp, testPrefix, rangeIp, prefix, valid)
if _ip.IPv4InRange(testIp, testPrefix, rangeIp, prefix) then
assert(valid)
else
assert(valid ~= true)
end
end
testNetmask(32)
testNetmask(31)
testNetmask(24)
testNetmask(14)
testNetmask(1)
testNetmask(0)
testInRange("192.168.10.1", "24", "192.168.10.148", "24", true)
testInRange("192.168.10.1", "32", "192.168.10.148", "24", true)
testInRange("192.168.9.1", "24", "192.168.10.148", "24", false)
testInRange("192.168.9.1", "16", "192.168.10.148", "16", true)
testInRange("1.1.1.1", "32", "192.168.10.148", "1", false)
testInRange("1.1.1.1", "32", "192.168.10.148", "0", true)
vy.changeEthernetAddress("192.168.10.1", "eth01", "lan1")
vy.changeEthernetAddress("192.168.10.1", "eth02", "lan2")
vy.changeEthernetAddress("192.168.10.1", "eth0.1", "lan1")
vy.changeEthernetAddress("192.168.10.1", "eth0.2", "lan2")
vy.changeEthernetAddress("192.168.10.1/32", "eth0.2", "lan2")
vy.changeEthernetAddress("192.168.10.1/33", "eth0.2", "lan2")
vy.changeEthernetAddress("192.168..1/32", "eth0.2", "lan2")
vy.changeEthernetAddress("192.168.10.1/32", "radio0", "wifi")
vy.changeEthernetAddress("192.168.10.1/32", "eth0.2", "lan2")
vy.changeEthernetAddress("192.168.9.1/16", "eth0.2", "lan2")
vy.changeEthernetAddress("192.168.9.1/24", "eth0.2", "lan2")
print("-- changing wan")
vy.changeWan("192.168.10.1", "eth0.2", "wan", "lan2")
vy.changeWan("192.168.10.1", "eth0.2", "lan", "wan")
vy.changeWan("192.168.2.1", "eth0.2", "lan", "wan")
local start, limit = vy.dhcpHostsFromPrefix(24)
print("start = %s, limit = %s" % {start, limit})
assert(start == 100 and limit == 125)
start, limit = vy.dhcpHostsFromPrefix(30)
print("start = %s, limit = %s" % {start, limit})
assert(start == 1 and limit == 3)
|
--[[
TODO log levels
-1, instant error()
0 off
1, print and log
2, log only
3, warn log only
4, info log only
]]
function doDebug(msg, alert)
local level = MOD.config.get("LOGLEVEL", 1)
if level == 0 and not alert then return end
if (level >= 1 or alert) and type(msg) == "table" then
MOD.logfile.log("vvvvvvvvvvvvvvvvvvvvvvv--Begin Serpent Block--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
MOD.logfile.log(serpent.block(msg, {comment=false}))
MOD.logfile.log("^^^^^^^^^^^^^^^^^^^^^^^--End Serpent Block--^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
else
MOD.logfile.log(tostring(msg))
end
if (level >= 2 or alert) and game then
game.print(MOD.IF .. ":" .. table.tostring(msg))
end
end
doDebug("vvvvvvvvvvvvvvvvvvvvvvv--Begin Logging--vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv") --Start the debug log with a header
|
-- Copyright 2016-2021 Alejandro Baez (https://keybase.io/baez). See LICENSE.
-- PICO-8 lexer.
-- http://www.lexaloffle.com/pico-8.php
local lexer = require('lexer')
local token, word_match = lexer.token, lexer.word_match
local P, S = lpeg.P, lpeg.S
local lex = lexer.new('pico8')
-- Whitespace
lex:add_rule('whitespace', token(lexer.WHITESPACE, lexer.space^1))
-- Keywords
lex:add_rule('keyword', token(lexer.KEYWORD, word_match[[
__lua__ __gfx__ __gff__ __map__ __sfx__ __music__
]]))
-- Identifiers
lex:add_rule('identifier', token(lexer.IDENTIFIER, lexer.word))
-- Comments
lex:add_rule('comment', token(lexer.COMMENT, lexer.to_eol('//', true)))
-- Numbers
lex:add_rule('number', token(lexer.NUMBER, lexer.integer))
-- Operators
lex:add_rule('operator', token(lexer.OPERATOR, S('_')))
-- Embed Lua into PICO-8.
local lua = lexer.load('lua')
local lua_start_rule = token('pico8_tag', '__lua__')
local lua_end_rule = token('pico8_tag', '__gfx__' )
lex:embed(lua, lua_start_rule, lua_end_rule)
lex:add_style('pico8_tag', lexer.styles.embedded)
return lex
|
local SpatialSoftMax, parent = torch.class('cudnn.SpatialSoftMax', 'nn.Module')
local errcheck = cudnn.errcheck
function SpatialSoftMax:__init(fast)
parent.__init(self)
if fast then
self.algorithm = 'CUDNN_SOFTMAX_FAST'
else
self.algorithm = 'CUDNN_SOFTMAX_ACCURATE'
end
end
function SpatialSoftMax:createIODescriptors(input)
self.mode = self.mode or 'CUDNN_SOFTMAX_MODE_CHANNEL'
-- after converting from nn use accurate
self.algorithm = self.algorithm or 'CUDNN_SOFTMAX_ACCURATE'
self.iSize = self.iSize or torch.LongStorage(4):fill(0)
local batch = true
local singleDim = false
if input:dim() == 1 then
singleDim = true
batch = false
input = input:view(1, input:size(1), 1, 1)
elseif input:dim() == 2 then
singleDim = true
input = input:view(input:size(1), input:size(2), 1, 1)
elseif input:dim() == 3 then
input = input:view(1, input:size(1), input:size(2), input:size(3))
batch = false
end
assert(input:dim() == 4 and input:isContiguous());
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
self.iSize = input:size()
self.output:resizeAs(input)
self.iDesc = cudnn.toDescriptor(input)
self.oDesc = cudnn.toDescriptor(self.output)
if not singleDim and not batch then
self.output = self.output:view(self.output:size(2),
self.output:size(3),
self.output:size(4))
elseif singleDim and not batch then
self.output = self.output:view(self.output:size(2))
elseif singleDim and batch then
self.output = self.output:view(self.output:size(1), self.output:size(2))
end
end
end
local one = torch.FloatTensor({1});
local zero = torch.FloatTensor({0});
function SpatialSoftMax:updateOutput(input)
self:createIODescriptors(input)
errcheck('cudnnSoftmaxForward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.iDesc[0], input:data(),
zero:data(),
self.oDesc[0], self.output:data());
return self.output
end
function SpatialSoftMax:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
self:createIODescriptors(input)
errcheck('cudnnSoftmaxBackward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.oDesc[0], self.output:data(),
self.oDesc[0], gradOutput:data(),
zero:data(),
self.iDesc[0], self.gradInput:data());
return self.gradInput
end
function SpatialSoftMax:clearDesc()
self.iDesc = nil
self.oDesc = nil
end
function SpatialSoftMax:write(f)
self:clearDesc()
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
function SpatialSoftMax:clearState()
self:clearDesc()
nn.utils.clear(self, '_gradOutput')
return parent.clearState(self)
end
|
--[[
Copyright 2014-2016 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[lit-meta
name = "luvit/resource"
version = "2.1.0"
license = "Apache 2"
homepage = "https://github.com/luvit/luvit/blob/master/deps/resource.lua"
description = "Utilities for loading relative resources"
dependencies = {
"creationix/pathjoin@2.0.0"
}
tags = {"luvit", "relative", "resource"}
]]
local pathJoin = require('pathjoin').pathJoin
local bundle = require('luvi').bundle
local uv = require('uv')
local function getPath()
local caller = debug.getinfo(2, "S").source
if caller:sub(1,1) == "@" then
return caller:sub(2)
elseif caller:sub(1, 7) == "bundle:" then
return caller
end
error("Unknown file path type: " .. caller)
end
local function getDir()
local caller = debug.getinfo(2, "S").source
if caller:sub(1,1) == "@" then
return pathJoin(caller:sub(2), "..")
elseif caller:sub(1, 7) == "bundle:" then
return "bundle:" .. pathJoin(caller:sub(8), "..")
end
error("Unknown file path type: " .. caller)
end
local function innerResolve(path, resolveOnly)
local caller = debug.getinfo(2, "S").source
if caller:sub(1,1) == "@" then
path = pathJoin(caller:sub(2), "..", path)
if resolveOnly then return path end
local fd = assert(uv.fs_open(path, "r", 420))
local stat = assert(uv.fs_fstat(fd))
local data = assert(uv.fs_read(fd, stat.size, 0))
uv.fs_close(fd)
return data, path
elseif caller:sub(1, 7) == "bundle:" then
path = pathJoin(caller:sub(8), "..", path)
if resolveOnly then return path end
return bundle.readfile(path), "bundle:" .. path
end
end
local function resolve(path)
return innerResolve(path, true)
end
local function load(path)
return innerResolve(path, false)
end
local function getProp(self, key)
if key == "path" then return getPath() end
if key == "dir" then return getDir() end
end
return setmetatable({
resolve = resolve,
load = load,
}, { __index = getProp })
|
print "Guess a number"
math.randomseed(os.time())
rnd = math.random()
number = math.random( 100 )
count = 0
while true do
print("What is the number you propose ?")
answer = io.read("*n")
count = count + 1
print("Your answer is : " .. answer)
if answer < number then
print("Your answer is too low")
elseif answer > number then
print("Your answer is too high")
else
print("Congrats, you guess it in " .. count .. " tries")
print("The number was, as you guessed, " .. number)
break
end
print("Try to guess again")
end |
--type location = {0, 0}
DefineStartLocationLoc = function(a, b)
DefineStartLocation(a, b[1], b[2])
end
GetStartLocationLoc = function(i)
local loc = jass.GetStartLocationLoc(i)
local p = {GetLocationX(loc), GetLocationY(loc)}
RemoveLocation(loc)
return p
end
GroupEnumUnitsInRangeOfLoc = function(g, loc, r, f)
GroupEnumUnitsInRange(g, loc[1], loc[2], r, f)
end
GroupEnumUnitsInRangeOfLocCounted = function(g, loc, r, f, c)
GroupEnumUnitsInRangeCounted(g, loc[1], loc[2], r, f, c)
end
GroupPointOrderLoc = function(g, o, loc)
return GroupPointOrder(g, o, loc[1], loc[2])
end
GroupPointOrderByIdLoc = function(g, i, loc)
return GroupPointOrderById(g, i, loc[1], loc[2])
end
RectFromLoc = function(l1, l2)
return Rect(l1[1], l1[2], l2[1], l2[2])
end
SetRectFromLoc = function(r, l1, l2)
SetRect(r, l1[1], l1[2], l2[1], l2[2])
end
MoveRectToLoc = function(r, loc)
MoveRectTo(r, loc[1], loc[2])
end
RegionAddCellAtLoc = function(r, l)
RegionAddCell(r, l[1], l[2])
end
RegionClearCellAtLoc = function(r, l)
RegionClearCell(r, l[1], l[2])
end
Location = function(x, y)
return {x, y}
end
RemoveLocation = function(loc)
loc = nil
end
MoveLocation = function(loc, x, y)
loc[1] = x
loc[2] = y
end
GetLocationX = function(loc)
return loc[1]
end
GetLocationY = function(loc)
return loc[2]
end
local locZ = jass.Location(0, 0)
GetLocationZ = function(loc)
jass.MoveLocation(locZ, loc[1], loc[2])
return jass.GetLocationZ(locZ)
end
IsLocationInRegion = function(r, loc)
return IsPointInRegion(r, loc[1], loc[2])
end
GetOrderPointLoc = function()
return {GetOrderPointX(), GetOrderPointY()}
end
GetSpellTargetLoc = function()
return {GetSpellTargetX(), GetSpellTargetY()}
end
CreateUnitAtLoc = function(p, i, l, f)
return CreateUnit(p, i, l[1], l[2], f)
end
CreateUnitAtLocByName = function(p, n, l, f)
return CreateUnitByName(p, n, l[1], l[2], f)
end
SetUnitPositionLoc = function(u, l)
SetUnitPosition(u, l[1], l[2])
end
ReviveHeroLoc = function(u, l, b)
return ReviveHero(u, l[1], l[2], b)
end
GetUnitLoc = function(u)
return {GetUnitX(u), GetUnitY(u)}
end
GetUnitRallyPoint = function(u)
local loc = jass.GetUnitRallyPoint(u)
local p = {jass.GetLocationX(loc), jass.GetLocationY(loc)}
RemoveLocation(loc)
return p
end
IsUnitInRangeLoc = function(u, l ,d)
return IsUnitInRangeXY(u, l[1], l[2], d)
end
IssuePointOrderLoc = function(u, o, l)
return IssuePointOrder(u, o, l[1], l[2])
end
IssuePointOrderByIdLoc = function(u, i, l)
return IssuePointOrderById(u, i, l[1], l[2])
end
IsLocationVisibleToPlayer = function(l, p)
return IsVisibleToPlayer(l[1], l[2], p)
end
IsLocationFoggedToPlayer = function(l, p)
return IsFoggedToPlayer(l[1], l[2], p)
end
IsLocationMaskedToPlayer = function(l, p)
return IsMaskedToPlayer(l[1], l[2], p)
end
SetFogStateRadiusLoc = function(p, s, l, r, b)
SetFogStateRadius(p, s, l[1], l[2], r, b)
end
CreateFogModifierRadiusLoc = function(p, s, l, r, b1, b2)
return CreateFogModifierRadius(p, s, l[1], l[2], r, b1, b2)
end
CameraSetupGetDestPositionLoc = function(c)
return {CameraSetupGetDestPositionX(c), CameraSetupGetDestPositionY(c)}
end
GetCameraTargetPositionLoc = function()
return {GetCameraTargetPositionX(), GetCameraTargetPositionY()}
end
GetCameraEyePositionLoc = function()
return {GetCameraEyePositionX(), GetCameraEyePositionY()}
end
AddSpecialEffectLoc = function(s, l)
return AddSpecialEffect(s, l[1], l[2])
end
AddSpellEffectLoc = function(s, t, l)
return AddSpellEffect(s, t, l[1], l[2])
end
AddSpellEffectByIdLoc = function(i, t, l)
return AddSpellEffectById(i, t, l[1], l[2])
end
SetBlightLoc = function(p, l, r, b)
SetBlight(p, l[1], l[2], r, b)
end
--JAPI
GetUnitState = japi.GetUnitState
SetUnitState = japi.SetUnitState
UNIT_STATE_BASE_ATTACK = ConvertUnitState(0x12)
UNIT_STATE_ADD_ATTACK = ConvertUnitState(0x13)
UNIT_STATE_MIN_ATTACK = ConvertUnitState(0x14)
UNIT_STATE_MAX_ATTACK = ConvertUnitState(0x15)
UNIT_STATE_ATTACK_RANGE = ConvertUnitState(0x16)
UNIT_STATE_DEFENCE = ConvertUnitState(0x20)
--修改
--数学相关
Sin = function(deg)
return math.sin(math.rad(deg))
end
SinBJ = Sin
Cos = function(deg)
return math.cos(math.rad(deg))
end
CosBJ = Cos
Tan = function(deg)
return math.tan(math.rad(deg))
end
TanBJ = Tan
Asin = function(deg)
return math.deg(math.asin(deg))
end
AsinBJ = Asin
Acos = function(deg)
return math.deg(math.acos(deg))
end
AcosBJ = Acos
Atan = function(deg)
return math.deg(math.atan(deg))
end
AtanBJ = Atan
Atan2 = function(y, x)
return math.deg(math.atan2(y, x))
end
Atan2BJ = Atan2
bj_DEGTORAD = 1
bj_RADTODEG = 1
SquareRoot = math.sqrt
--重载所有计时器相关的函数
do
local timerTable = {} --用来存放没有引用的计时器
local timerCount = 0 --表示空闲计时器的计数
local count = 0 --正在运行的计时器计数
--创建计时器
CreateTimer = function()
local t
if timerCount == 0 then
--没有空闲计时器,新建
t = jass.CreateTimer()
else
t = timerTable[timerCount]
timerCount = timerCount - 1 --空闲timer计数
end
local timer = {t} --用table把timer包起来
timerTable[t] = timer --记录该timer所使用的table
count = count + 1
if count > 500 then
Debug("<DEBUG>正在运行的计时器计数:" .. count)
end
return timer
end
--删除计时器
DestroyTimer = function(timer)
if timer == nil then return end
local t = timer[1]
if not t then return end --如果table内没有timer就返回
jass.PauseTimer(t) --暂停timer,并不摧毁它
timerCount = timerCount + 1 --空闲timer计数
timerTable[timerCount] = t --把timer放入空闲timer组中
timerTable[t] = nil --释放timer所使用的table
timer[1] = nil --将table内的timer移除,因为外部依然是使用table来指向timer的,因此可以避免反复删除同一个timer造成的错误
count = count - 1
end
--暂停计时器
PauseTimer = function(timer)
local t = timer[1]
if not t then return end
jass.PauseTimer(t)
end
--启动计时器
TimerStart = function(timer, r, b, func)
local t = timer[1]
if not t then return end
timer[2] = r
timer[3] = b
timer[4] = func
jass.TimerStart(t, r, b, func)
end
--重新启动计时器
TimerRestart = function(timer)
local t, r, b, func = timer[1], timer[2], timer[3], timer[4]
if not t or not r then return end
jass.TimerStart(t, r, b, func)
end
--获取到期计时器
GetExpiredTimer = function()
return timerTable[jass.GetExpiredTimer()] --找到这个timer的table
end
TimerGetElapsed = function(timer)
return jass.TimerGetElapsed(timer[1])
end
TimerGetRemaining = function(timer)
return jass.TimerGetRemaining(timer[1])
end
TimerGetTimeout = function(timer)
return jass.TimerGetTimeout(timer[1])
end
ResumeTimer = TimerRestart
end
--创建闪电效果
AddLightningEx = function(name, b, x1, y1, z1, x2, y2, z2)
local l = jass.AddLightningEx(name, false, x1, y1, z1, x2, y2, z2)
if b and not IsVisibleToPlayer(x1, y1, SELFP) and not IsVisibleToPlayer(x2, y2, SELFP) then
SetLightningColor(l, 1, 1, 1, 0)
end
return l
end
MoveLightningEx = function(l, b, x1, y1, z1, x2, y2, z2)
if b then
local r, g, b = 1, 1, 1
if IsVisibleToPlayer(x1, y1, SELFP) or IsVisibleToPlayer(x2, y2, SELFP) then
SetLightningColor(l, r, g, b, 1)
else
SetLightningColor(l, r, g, b, 0)
end
end
return jass.MoveLightningEx(l, false, x1, y1, z1, x2, y2, z2)
end
--自定义默认值
Or = function(a, b, c)
if a == b then
return c
end
return a
end
--重置技能冷却
do
UnitResetCooldown = function(u)
local skills = Mark(u, "技能")
if skills then
for _, this in pairs(skills) do
local ab = japi.EXGetUnitAbility(this.unit, this.id)
local cd = japi.EXGetAbilityState(ab, 1)
if cd > 0 and cd < 3600 then
japi.EXSetAbilityState(ab, 1, 0)
end
end
else
jass.UnitResetCooldown(u)
end
end
end
--获得经验值
AddHeroXP = function(u, xp, b, r)
local data = {unit = u, xp = xp, oxp = xp, reason = r or "杀敌"}
toEvent("获得经验", data)
jass.AddHeroXP(data.unit, data.xp, b)
end
|
require("modules/dsp/luafft/luafft")
require("modules/util/string_operations")
require("modules/util/stats")
abs = math.abs
new = complex.new --required for using the FFT function.
UpdateSpectrum = false
beatslog = table
beat = table
log_fft = false
show_beats = not log_fft
--Song =
--beats_file =
--sample_counter =
--sum_beats = 0
function devide(list, factor)
for i,v in ipairs(list) do list[i] = list[i] * factor end
-- This function multiplies every value in the list of frequencies for a given constant.Think of it as a sensibility setting.
end
function love.load()
SoundData = love.sound.newSoundData(Song) --You need to load the song both to obtain it's data AND play it.
Size = 1024 --The amount of frequencies to obtain as result of the FFT process.
Frequency = 44100 --The sampling rate of the song, in Hz
length = Size / Frequency -- The size of each frequency range of the final generated FFT values.
Music = love.audio.newSource(Song)
Music:play()
Window = love.window.setMode(1024, 768, {resizable=true, vsync=true})
if(log_fft) then
fftlog = love.filesystem.newFile(Song .. ".beats")
fftlog:open("w")
end
if(show_beats) then
beatslog = table
for line in love.filesystem.lines(beats_file) do
table.insert(beatslog, line)
end
end
beat_timer = {}
beat_timer[1] = love.timer.getTime()
beat_timer[2] = beat_timer[1]
beat_timer[3] = beat_timer[1]
beat_timer[4] = beat_timer[1]
bpm = {}
bpm[1] = {}
bpm[1][1] = 0
bpm[2] = {}
bpm[2][1] = 0
bpm[3] = {}
bpm[3][1] = 0
bpm[4] = {}
bpm[4][1] = 0
new_beat_timer = {}
beat_timer_delta = {}
mode_bpm = {}
mode_bpm[1] = {}
mode_bpm[1][2] = 0
mode_bpm[2] = {}
mode_bpm[2][2] = 0
mode_bpm[3] = {}
mode_bpm[3][2] = 0
mode_bpm[4] = {}
mode_bpm[4][2] = 0
bpm_all = {}
mode_bpm_all = 0
mean_bpm_all = 0
flip = true
end
function love.update()
ScreenSizeW = love.graphics.getWidth() --gets screen dimensions.
ScreenSizeH = love.graphics.getHeight() --gets screen dimensions.
local MusicPos = Music:tell( "samples" ) --Returns the current sample being played by the engine.
local MusicSize = SoundData:getSampleCount() --Obtain the size of the song in samples, so you can keep track of when it's gonna end.
-- if MusicPos >= MusicSize - 1536 then love.audio.rewind(Music) end --Rewinds the song when the music is almost over.
local List = {} --We'll fill this with sample information.
for i= MusicPos, MusicPos + (Size-1) do
CopyPos = i
if i + 2048 > MusicSize then i = MusicSize/2 end --Make sure you stop trying to copy stuff when the song is *almost* over, or you'll wind up getting access errors!
List[#List+1] = new(SoundData:getSample(i*2), 0) --Copies every sample to the list, which will be fed for the FFT calculation engine.
-- In this case, we're fetching the Right channel samples, hence the "i*2". For the left channel, use "i*2+1". If it's a mono music, use "i*2" and you should be good.
-- The "new" function used above is for generating complex numbers. The FFT function only works if given a table of complex values, and it returns a table of this kind.
end
spectrum = fft(List, false) --runs your list through the FFT analyzer. Returns a table of complex values, all properly processed for your usage.
--An FFT converts audio from a time space to a frequency space, so you can analyze the volume level in each one of it's frequency bands.
devide(spectrum, 10) --Multiply all obtained FFT freq infos by 10.
if(log_fft) then
sample_fft = ""
for i = 1, #spectrum/8 do
sample_fft = sample_fft .. spectrum[i]:abs()*0.7 .. " "
end
love.filesystem.append(Song .. ".fft", sample_fft .. "\n")
end
if(show_beats and flip) then
--sum_beats = 0
--print(sample_counter)
sample_counter = sample_counter + 1
if(sample_counter>0) then
current_beats = beatslog[sample_counter]:split(' ')
number_of_freqs = #current_beats
beat = {}
for i, v in ipairs(current_beats) do
if v == 'NA' then
beat[i] = 0
else
beat[i] = 1
new_beat_timer[i] = love.timer.getTime()
beat_timer_delta[i] = new_beat_timer[i] - beat_timer[i]
table.insert(bpm[i], 60000 / (beat_timer_delta[i] * 1000))
beat_timer[i] = new_beat_timer[i]
mode_bpm[i] = mode(bpm[i])
table.insert(bpm_all,bpm[i][#bpm[i]])
--print(bpm[i][2])
--sum_beats = sum_beats + v
end
end
if(#bpm_all > 1) then
mode_bpm_all = mode(bpm_all)[2]
--mean_bpm_all = 0
--for j, w in ipairs(bpm_all) do
-- mean_bpm_all = mean_bpm_all + w
--end
--mean_bpm_all = mean_bpm_all / #bpm_all
end
end
end
flip = not flip
UpdateSpectrum = true --Tells the draw function it already has data to draw
end
function love.draw()
if UpdateSpectrum then
--for i = 1, #spectrum/8 do --In case you want to show only a part of the list, you can use #spec/(amount of bars). Setting this to 1 will render all bars processed.
-- love.graphics.rectangle("line", i*7, ScreenSizeH, 7, -1*(spectrum[i]:abs()*0.7)) --iterate over the list, and draws a rectangle for each band value.
-- love.graphics.print("@ "..math.floor((i)/length).."Hz "..math.floor(spectrum[i]:abs()*0.7), ScreenSizeW-90,(12*i)) --prints the frequency and it's current value on the screen.
-- love.graphics.print(CopyPos, 0, 0) --Current position being analyzed.
-- love.graphics.print(SoundData:getSampleCount(), 0, 20) --Current size of song in samples.
--
--end
print(mode_bpm_all)
love.graphics.print(mode_bpm_all, 0, 0)
if(show_beats and sample_counter > 0) then
for i, v in ipairs(beat) do
--sum = 0
--for j, w in ipairs(bpm[i]) do
-- sum = sum + w
--end
--sum = sum / #bpm[i]
--love.graphics.print(sum, i*200, 100)
love.graphics.print(mode_bpm[i][2], i*200, i*25)
love.graphics.rectangle("fill", 100+(i-1)*(ScreenSizeW-100)/#beat, ScreenSizeH/4, 200*v, 400*v)
end
end
--love.graphics.rectangle("fill", (ScreenSizeW-100)/2, ScreenSizeH/2, 100*sum_beats, 200*sum_beats)
end
end |
-- {steamID, points, source}
local players = {}
-- {steamID}
local waiting = {}
-- {steamID}
local connecting = {}
-- Points initiaux (prioritaires ou négatifs)
local prePoints = Config.Points;
-- Emojis pour la loterie
local EmojiList = Config.EmojiList
local pCards = {}
local buttonCreate = {}
local IdentifierTables = {
{table = "users", column = "identifier"},
{table = "user_accounts", column = "identifier"},
{table = "user_inventory", column = "identifier"},
{table = "user_licenses", column = "owner"},
{table = "characters", column = "identifier"},
{table = "billing", column = "identifier"},
{table = "rented_vehicles", column = "owner"},
{table = "addon_account_data", column = "owner"},
{table = "addon_inventory_items", column = "owner"},
{table = "datastore_data", column = "owner"},
{table = "society_moneywash", column = "identifier"},
{table = "lspd_user_judgments", column = "userId"},
{table = "lspd_mdc_user_notes", column = "userId"},
{table = "owned_vehicles", column = "owner"},
{table = "owned_properties", column = "owner"},
{table = "user_inventory", column = "identifier"},
{table = "phone_calls", column = "owner"},
--{table = "phone_messages", column = "owner"},
{table = "playersTattoos", column = "identifier"},
{table = "d_user_peds", column = "identifier"},
}
local not_found = {
["type"] = "AdaptiveCard",
["minHeight"] = "auto",
["body"] = {
{
["type"] = "ColumnSet",
["columns"] = {
{
["type"] = "Column",
["items"] = {
{
["type"] = "TextBlock",
["text"] = "Nie posiadasz konta!\nPołącz się aby stworzyć postać.",
["size"] = "small",
["horizontalAlignment"] = "left"
},
}
},
}
}
},
["actions"] = {},
["$schema"] = "http://adaptivecards.io/schemas/adaptive-card.json",
["version"] = "1.0"
}
StopResource('hardcap')
AddEventHandler('onResourceStop', function(resource)
if resource == GetCurrentResourceName() then
if GetResourceState('hardcap') == 'stopped' then
StartResource('hardcap')
end
end
end)
-- Connexion d'un client
AddEventHandler("playerConnecting", function(name, reject, def)
local source = source
local steamID = GetSteamID(source)
-- pas de steam ? ciao
if not steamID then
reject(Config.NoSteam)
CancelEvent()
return
end
-- Lancement de la rocade,
-- si cancel du client : CancelEvent() pour ne pas tenter de co.
if not Rocade(steamID, def, source) then
CancelEvent()
end
end)
-- Fonction principale, utilise l'objet "deferrals" transmis par l'evenement "playerConnecting"
function Rocade(steamID, def, source)
-- retarder la connexion
def.defer()
-- faire patienter un peu pour laisser le temps aux listes de s'actualiser
AntiSpam(def)
-- retirer notre ami d'une éventuelle liste d'attente ou connexion
Purge(steamID)
-- l'ajouter aux players
-- ou actualiser la source
AddPlayer(steamID, source)
-- le mettre en file d'attente
table.insert(waiting, steamID)
-- tant que le steamID n'est pas en connexion
local stop = false
repeat
for i,p in ipairs(connecting) do
if p == steamID then
stop = true
break
end
end
-- Hypothèse: Quand un joueur en file d'attente a un ping = 0, ça signifie que la source est perdue
-- Détecter si l'user clique sur "cancel"
-- Le retirer de la liste d'attente / connexion
-- Le message d'accident ne devrait j'amais s'afficher
for j,sid in ipairs(waiting) do
for i,p in ipairs(players) do
-- Si un joueur en file d'attente a un ping = 0
if sid == p[1] and p[1] == steamID and (GetPlayerPing(p[3]) == 0) then
-- le purger
Purge(steamID)
-- comme il a annulé, def.done ne sert qu'à identifier un cas non géré
def.done(Config.Accident)
return false
end
end
end
-- Mettre à jour le message d'attente
def.update(GetMessage(steamID))
Citizen.Wait(Config.TimerRefreshClient * 1000)
until stop
local player = source
def.update("Sprawdzanie konta...")
Citizen.Wait(600)
local LastCharId = GetLastCharacter(player)
SetIdentifierToChar(GetPlayerIdentifiers(player)[1], LastCharId)
local steamid = GetPlayerIdentifiers(player)[1]
local id = string.gsub(steamid, "steam", "")
pCards[steamid] = {}
MySQL.Async.fetchAll("SELECT * FROM `users` WHERE `identifier` LIKE '%"..id.."%'", {
}, function(result)
MySQL.Async.fetchAll("SELECT * FROM `neey_chars` WHERE `identifier` = @identifier", {
['@identifier'] = steamid
}, function(result2)
if result2[1] ~= nil then
return
else
MySQL.Async.execute(
'INSERT INTO `neey_chars`(`identifier`) VALUES (@identifier)',
{
['@identifier'] = GetPlayerIdentifiers(player)[1]
}
)
end
end)
if (result[1] ~= nil) then
if #result[1] < 2 then
MySQL.Async.execute(
'UPDATE `user_lastcharacter` SET `charid`= 1 WHERE `steamid` = @identifier',
{
['@identifier'] = GetPlayerIdentifiers(player)[1]
}
)
end
local Characters = GetPlayerCharacters(player)
pCards[steamid] = {
["type"] = "AdaptiveCard",
["minHeight"] = "auto",
--["backgroundImage"] = "https://i.imgur.com/WTun0SK.png",
["body"] = {
{
["type"] = "ColumnSet",
["columns"] = {
{
["type"] = "Column",
["items"] = {
{
["type"] = "TextBlock",
["text"] = "Imię i nazwisko postaci",
["size"] = "small",
["horizontalAlignment"] = "left"
},
{
["type"] = "Input.ChoiceSet",
["choices"] = {},
["style"] = "expanded",
["id"] = "char_id",
["value"] = "char1"
}
}
},
{
["type"] = "Column",
["items"] = {
{
["type"] = "TextBlock",
["text"] = "Pozycja",
["size"] = "small",
["horizontalAlignment"] = "left"
},
{
["type"] = "Input.ChoiceSet",
["choices"] = {
{
["title"] = "Ostatnia pozycja",
["value"] = "lastPosition"
},
},
["style"] = "expanded",
["id"] = "spawnPoint",
["value"] = "lastPosition"
}
}
}
}
}
},
["actions"] = {},
["$schema"] = "http://adaptivecards.io/schemas/adaptive-card.json",
["version"] = "1.0"
}
local limit = MySQLAsyncExecute("SELECT * FROM `neey_chars` WHERE `identifier` = '"..GetPlayerIdentifiers(player)[1].."'")
if limit[1].limit > 1 then
if #result < 2 then
buttonCreate = {
{
["type"] = "Action.Submit",
["title"] = "Połącz"
},
{
["type"] = "Action.Submit",
["title"] = "Stwórz postać",
["data"] = {
["x"] = "setupChar"
}
},
}
else
buttonCreate = {
{
["type"] = "Action.Submit",
["title"] = "Połącz"
},
}
end
else
buttonCreate = {
{
["type"] = "Action.Submit",
["title"] = "Połącz"
},
}
end
for k,v in ipairs(Characters) do
if result[k].firstname ~= '' then
local data = {
["title"] = result[k].firstname .. ' ' .. result[k].lastname,
["value"] = "char"..k,
}
pCards[steamid].body[1].columns[1].items[2].choices[k] = data
else
local data = {
["title"] = 'Dokończ rejestrację postaci!',
["value"] = "char"..k,
}
pCards[steamid].body[1].columns[1].items[2].choices[k] = data
end
end
pCards[steamid].actions = buttonCreate
def.presentCard(pCards[steamid], function(submittedData, rawData)
if submittedData.x ~= nil then
local idc = string.gsub(steamid, "steam", "Char2")
MySQL.Async.execute('INSERT INTO users (`identifier`, `money`, `bank`, `group`, `permission_level`, `license`) VALUES ("'..idc..'", 0, 100000, "user", 0, "'..GetPlayerIdentifiers(player)[2]..'")')
TriggerEvent("neey_characters:chosen", player, '2')
pCards[steamid] = 0
def.done()
else
local char_id = submittedData.char_id
local char = string.gsub(char_id, "char", "")
TriggerEvent("neey_characters:chosen", player, char)
pCards[steamid] = 0
def.done()
end
end)
else
local buttonCreate = {
{
["type"] = "Action.Submit",
["title"] = "Połącz"
},
}
not_found.actions = buttonCreate
def.presentCard(not_found, function(submittedData, rawData)
def.done()
end)
end
end)
return true
end
-- Vérifier si une place se libère pour le premier de la file
Citizen.CreateThread(function()
local maxServerSlots = GetConvarInt('sv_maxclients', 100)
while true do
Citizen.Wait(Config.TimerCheckPlaces * 1000)
CheckConnecting()
-- si une place est demandée et disponible
if #waiting > 0 and #connecting + #GetPlayers() < maxServerSlots then
ConnectFirst()
end
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(5000)
SetHttpHandler(function(req, res)
local path = req.path
if req.path == '/count' then
res.send(json.encode({
count = #waiting
}))
return
end
end)
end
end)
-- Mettre régulièrement les points à jour
Citizen.CreateThread(function()
while true do
UpdatePoints()
Citizen.Wait(Config.TimerUpdatePoints * 1000)
end
end)
-- Lorsqu'un joueur est kick
-- lui retirer le nombre de points fourni en argument
RegisterServerEvent("rocademption:playerKicked")
AddEventHandler("rocademption:playerKicked", function(src, points)
local sid = GetSteamID(src)
Purge(sid)
for i,p in ipairs(prePoints) do
if p[1] == sid then
p[2] = p[2] - points
return
end
end
local initialPoints = GetInitialPoints(sid)
table.insert(prePoints, {sid, initialPoints - points})
end)
-- Quand un joueur spawn, le purger
RegisterServerEvent("rocademption:playerConnected")
AddEventHandler("rocademption:playerConnected", function()
local sid = GetSteamID(source)
Purge(sid)
end)
-- Quand un joueur drop, le purger
AddEventHandler("playerDropped", function(reason)
local steamID = GetSteamID(source)
Purge(steamID)
end)
-- si le ping d'un joueur en connexion semble partir en couille, le retirer de la file
-- Pour éviter un fantome en connexion
function CheckConnecting()
for i,sid in ipairs(connecting) do
for j,p in ipairs(players) do
if p[1] == sid and (GetPlayerPing(p[3]) == 500) then
table.remove(connecting, i)
break
end
end
end
end
-- ... connecte le premier de la file
function ConnectFirst()
if #waiting == 0 then return end
local maxPoint = 0
local maxSid = waiting[1][1]
local maxWaitId = 1
for i,sid in ipairs(waiting) do
local points = GetPoints(sid)
if points > maxPoint then
maxPoint = points
maxSid = sid
maxWaitId = i
end
end
table.remove(waiting, maxWaitId)
table.insert(connecting, maxSid)
end
-- retourne le nombre de kilomètres parcourus par un steamID
function GetPoints(steamID)
for i,p in ipairs(players) do
if p[1] == steamID then
return p[2]
end
end
end
-- Met à jour les points de tout le monde
function UpdatePoints()
for i,p in ipairs(players) do
local found = false
for j,sid in ipairs(waiting) do
if p[1] == sid then
p[2] = p[2] + Config.AddPoints
found = true
break
end
end
if not found then
for j,sid in ipairs(connecting) do
if p[1] == sid then
found = true
break
end
end
if not found then
p[2] = p[2] - Config.RemovePoints
if p[2] < GetInitialPoints(p[1]) - Config.RemovePoints then
Purge(p[1])
table.remove(players, i)
end
end
end
end
end
function AddPlayer(steamID, source)
for i,p in ipairs(players) do
if steamID == p[1] then
players[i] = {p[1], p[2], source}
return
end
end
local initialPoints = GetInitialPoints(steamID)
table.insert(players, {steamID, initialPoints, source})
end
function GetInitialPoints(steamID)
local points = Config.RemovePoints + 1
for n,p in ipairs(prePoints) do
if p[1] == steamID then
points = p[2]
break
end
end
return points
end
function GetPlace(steamID)
local points = GetPoints(steamID)
local place = 1
for i,sid in ipairs(waiting) do
for j,p in ipairs(players) do
if p[1] == sid and p[2] > points then
place = place + 1
end
end
end
return place
end
function GetMessage(steamID)
local msg = ""
local witam = "NIE"
local rodzajbiletu = 'Standard 📜'
if GetPoints(steamID) ~= nil then
if GetPoints(steamID) > 1500 then
rodzajbiletu = 'Bronze ticket 🧹'
end
if GetPoints(steamID) > 2500 then
rodzajbiletu = 'Golden ticket 📀'
end
if GetPoints(steamID) > 4200 then
rodzajbiletu = 'Platinum ticket 💎'
end
if GetPoints(steamID) > 5000 then
rodzajbiletu = 'Kasjan bilet'
end
if GetPoints(steamID) > 5500 then
rodzajbiletu = 'Admin ticket 💣'
end
msg = '\n\n' .. Config.EnRoute .. " " .. " Rodzaj biletu: " .. rodzajbiletu ..".\n"
msg = msg .. Config.Position .. GetPlace(steamID) .. "/".. #waiting .. " " .. ".\n"
msg = msg .. "-- ( " .. Config.EmojiMsg
local e1 = RandomEmojiList()
local e2 = RandomEmojiList()
local e3 = RandomEmojiList()
local emojis = e1 .. e2 .. e3
if( e1 == e2 and e2 == e3 ) then
emojis = emojis .. Config.EmojiBoost
LoterieBoost(steamID)
end
-- avec les jolis emojis
msg = msg .. emojis .. " ) --"
else
msg = Config.Error
end
return msg
end
function LoterieBoost(steamID)
for i,p in ipairs(players) do
if p[1] == steamID then
p[2] = p[2] + Config.LoterieBonusPoints
return
end
end
end
function Purge(steamID)
for n,sid in ipairs(connecting) do
if sid == steamID then
table.remove(connecting, n)
end
end
for n,sid in ipairs(waiting) do
if sid == steamID then
table.remove(waiting, n)
end
end
end
function AntiSpam(def)
for i=Config.AntiSpamTimer,0,-1 do
def.update(Config.PleaseWait_1 .. i .. Config.PleaseWait_2)
Citizen.Wait(1000)
end
end
function RandomEmojiList()
randomEmoji = EmojiList[math.random(#EmojiList)]
return randomEmoji
end
-- Helper pour récupérer le steamID or false
function GetSteamID(src)
local sid = GetPlayerIdentifiers(src)[1] or false
if (sid == false or sid:sub(1,5) ~= "steam") then
return false
end
return sid
end
RegisterServerEvent("neey_characters:chosen")
AddEventHandler("neey_characters:chosen", function(source, charid)
local _source = source
SetLastCharacter(source, charid)
SetCharToIdentifier(GetPlayerIdentifiers(source)[1], tonumber(charid))
end)
function GetPlayerCharacters(source)
local identifier = GetIdentifierWithoutSteam(GetPlayerIdentifiers(source)[1])
local Chars = MySQLAsyncExecute("SELECT * FROM `users` WHERE identifier LIKE '%"..identifier.."%'")
for i = 1, #Chars, 1 do
charJob = MySQLAsyncExecute("SELECT * FROM `jobs` WHERE `name` = '"..Chars[i].job.."'")
charJobgrade = MySQLAsyncExecute("SELECT * FROM `job_grades` WHERE `grade` = '"..Chars[i].job_grade.."'")
Chars[i].job = charJob[1].label
Chars[i].job_grade = charJobgrade[1].label
end
return Chars
end
function GetLastCharacter(source)
local LastChar = MySQLAsyncExecute("SELECT `charid` FROM `user_lastcharacter` WHERE `steamid` = '"..GetPlayerIdentifiers(source)[1].."'")
if LastChar[1] ~= nil and LastChar[1].charid ~= nil then
return tonumber(LastChar[1].charid)
else
MySQLAsyncExecute("INSERT INTO `user_lastcharacter` (`steamid`, `charid`) VALUES('"..GetPlayerIdentifiers(source)[1].."', 1)")
return 1
end
end
function SetLastCharacter(source, charid)
MySQLAsyncExecute("UPDATE `user_lastcharacter` SET `charid` = '"..charid.."' WHERE `steamid` = '"..GetPlayerIdentifiers(source)[1].."'")
end
function SetIdentifierToChar(identifier, charid)
for _, itable in pairs(IdentifierTables) do
MySQLAsyncExecute("UPDATE `"..itable.table.."` SET `"..itable.column.."` = 'Char"..charid..GetIdentifierWithoutSteam(identifier).."' WHERE `"..itable.column.."` = '"..identifier.."'")
end
end
function SetCharToIdentifier(identifier, charid)
for _, itable in pairs(IdentifierTables) do
MySQLAsyncExecute("UPDATE `"..itable.table.."` SET `"..itable.column.."` = '"..identifier.."' WHERE `"..itable.column.."` = 'Char"..charid..GetIdentifierWithoutSteam(identifier).."'")
end
end
function DeleteCharacter(identifier, charid)
for _, itable in pairs(IdentifierTables) do
MySQLAsyncExecute("DELETE FROM `"..itable.table.."` WHERE `"..itable.column.."` = 'Char"..charid..GetIdentifierWithoutSteam(identifier).."'")
end
end
function GetSpawnPos(source)
local SpawnPos = MySQLAsyncExecute("SELECT `position` FROM `users` WHERE `identifier` = '"..GetPlayerIdentifiers(source)[1].."'")
return json.decode(SpawnPos[1].position)
end
function GetIdentifierWithoutSteam(Identifier)
return string.gsub(Identifier, "steam", "")
end
function MySQLAsyncExecute(query)
local IsBusy = true
local result = nil
MySQL.Async.fetchAll(query, {}, function(data)
result = data
IsBusy = false
end)
while IsBusy do
Citizen.Wait(0)
end
return result
end
RegisterCommand("deletechar", function(source, args, rawCommand)
if (source > 0) then
return
else
if args[1] ~= nil then
if args[2] ~= nil then
DeleteCharacter(args[1], args[2])
end
end
end
end) |
--[[
Angle gates
]]
GateActions("Angle")
-- Add
GateActions["angle_add"] = {
name = "Addition",
inputs = { "A", "B", "C", "D", "E", "F", "G", "H" },
inputtypes = { "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE" },
compact_inputs = 2,
outputtypes = { "ANGLE" },
output = function(gate, A , B , C , D , E , F , G , H)
if !A then A = Angle (0, 0, 0) end
if !B then B = Angle (0, 0, 0) end
if !C then C = Angle (0, 0, 0) end
if !D then D = Angle (0, 0, 0) end
if !E then E = Angle (0, 0, 0) end
if !F then F = Angle (0, 0, 0) end
if !G then G = Angle (0, 0, 0) end
if !H then H = Angle (0, 0, 0) end
return (A + B + C + D + E + F + G + H)
end,
label = function(Out)
return string.format ("Addition = (%d,%d,%d)",
Out.p, Out.y, Out.r)
end
}
-- Subtract
GateActions["angle_sub"] = {
name = "Subtraction",
inputs = { "A", "B" },
inputtypes = { "ANGLE", "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A, B)
if !A then A = Angle (0, 0, 0) end
if !B then B = Angle (0, 0, 0) end
return (A - B)
end,
label = function(Out, A, B)
return string.format ("%s - %s = (%d,%d,%d)", A, B, Out.p, Out.y, Out.r)
end
}
-- Negate
GateActions["angle_neg"] = {
name = "Negate",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A)
if !A then A = Angle (0, 0, 0) end
return Angle (-A.p, -A.y, -A.r)
end,
label = function(Out, A)
return string.format ("-%s = (%d,%d,%d)", A, Out.p, Out.y, Out.r)
end
}
-- Multiply/Divide by constant
GateActions["angle_mul"] = {
name = "Multiplication",
inputs = { "A", "B" },
inputtypes = { "ANGLE", "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A, B)
if !A then A = Angle (0, 0, 0) end
if !B then B = Angle (0, 0, 0) end
return Angle(A.p * B.p , A.y * B.y , A.r * B.r)
end,
label = function(Out, A, B)
return string.format ("%s * %s = (%d,%d,%d)", A, B, Out.p, Out.y, Out.r)
end
}
-- Component Derivative
GateActions["angle_derive"] = {
name = "Delta",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "ANGLE" },
timed = true,
output = function(gate, A)
local t = CurTime ()
if !A then A = Angle (0, 0, 0) end
local dT, dA = t - gate.LastT, A - gate.LastA
gate.LastT, gate.LastA = t, A
if (dT) then
return Angle (dA.p/dT, dA.y/dT, dA.r/dT)
else
return Angle (0, 0, 0)
end
end,
reset = function(gate)
gate.LastT, gate.LastA = CurTime (), Angle (0, 0, 0)
end,
label = function(Out, A)
return string.format ("diff(%s) = (%d,%d,%d)", A, Out.p, Out.y, Out.r)
end
}
GateActions["angle_divide"] = {
name = "Division",
inputs = { "A", "B" },
inputtypes = { "ANGLE", "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A, B)
if !A then A = Angle (0, 0, 0) end
if !B or B == Angle (0, 0, 0) then B = Angle (0, 0, 0) return B end
return Angle(A.p / B.p , A.y / B.y , A.r / B.r)
end,
label = function(Out, A, B)
return string.format ("%s / %s = (%d,%d,%d)", A, B, Out.p, Out.y, Out.r)
end
}
-- Conversion To/From
GateActions["angle_convto"] = {
name = "Compose",
inputs = { "Pitch", "Yaw", "Roll" },
inputtypes = { "NORMAL", "NORMAL", "NORMAL" },
outputtypes = { "ANGLE" },
output = function(gate, Pitch, Yaw, Roll)
return Angle (Pitch, Yaw, Roll)
end,
label = function(Out, Pitch, Yaw, Roll)
return string.format ("angle(%s,%s,%s) = (%d,%d,%d)", Pitch, Yaw, Roll, Out.p, Out.y, Out.r)
end
}
GateActions["angle_convfrom"] = {
name = "Decompose",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputs = { "Pitch", "Yaw", "Roll" },
output = function(gate, A)
if A then
return A.p, A.y, A.r
end
return 0, 0, 0
end,
label = function(Out, A)
return string.format ("%s -> Pitch:%d Yaw:%d Roll:%d", A, Out.Pitch, Out.Yaw, Out.Roll)
end
}
-- Identity
GateActions["angle_ident"] = {
name = "Identity",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A)
if !A then A = Angle (0, 0, 0) end
return A
end,
label = function(Out, A)
return string.format ("%s = (%d,%d,%d)", A, Out.p, Out.y, Out.r)
end
}
-- Shifts the components left.
GateActions["angle_shiftl"] = {
name = "Shift Components Left",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A)
if !A then A = Angle (0, 0, 0) end
return Angle(A.y,A.r,A.p)
end,
label = function(Out, A )
return string.format ("shiftL(%s) = (%d,%d,%d)", A , Out.p, Out.y, Out.r)
end
}
-- Shifts the components right.
GateActions["angle_shiftr"] = {
name = "Shift Components Right",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A)
if !A then A = Angle (0, 0, 0) end
return Angle(A.r,A.p,A.y)
end,
label = function(Out, A )
return string.format ("shiftR(%s) = (%d,%d,%d)", A , Out.p, Out.y, Out.r)
end
}
GateActions["angle_fruvecs"] = {
name = "Direction - (forward, up, right)",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputs = { "Forward", "Up" , "Right" },
outputtypes = { "VECTOR" , "VECTOR" , "VECTOR" },
timed = true,
output = function(gate, A )
if !A then return Vector(0,0,0) , Vector(0,0,0) , Vector(0,0,0) else return A:Forward() , A:Up() , A:Right() end
end,
label = function(Out)
return string.format ("Forward = (%f , %f , %f)\nUp = (%f , %f , %f)\nRight = (%f , %f , %f)", Out.Forward.x , Out.Forward.y , Out.Forward.z, Out.Up.x , Out.Up.y , Out.Up.z, Out.Right.x , Out.Right.y , Out.Right.z)
end
}
GateActions["angle_norm"] = {
name = "Normalize",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A)
if !A then A = Angle (0, 0, 0) end
return Angle(math.NormalizeAngle(A.p),math.NormalizeAngle(A.y),math.NormalizeAngle(A.r))
end,
label = function(Out, A )
return string.format ("normalize(%s) = (%d,%d,%d)", A , Out.p, Out.y, Out.r)
end
}
GateActions["angle_tostr"] = {
name = "To String",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "STRING" },
output = function(gate, A)
if !A then A = Angle (0, 0, 0) end
return "["..tostring(A.p)..","..tostring(A.y)..","..tostring(A.r).."]"
end,
label = function(Out, A )
return string.format ("toString(%s) = \""..Out.."\"", A)
end
}
-- Equal
GateActions["angle_compeq"] = {
name = "Equal",
inputs = { "A", "B" },
inputtypes = { "ANGLE", "ANGLE" },
outputtypes = { "NORMAL" },
output = function(gate, A, B)
if (A == B) then return 1 end
return 0
end,
label = function(Out, A, B)
return string.format ("(%s == %s) = %d", A, B, Out)
end
}
-- Not Equal
GateActions["angle_compineq"] = {
name = "Not Equal",
inputs = { "A", "B" },
inputtypes = { "ANGLE", "ANGLE" },
outputtypes = { "NORMAL" },
output = function(gate, A, B)
if (A == B) then return 0 end
return 1
end,
label = function(Out, A, B)
return string.format ("(%s != %s) = %d", A, B, Out)
end
}
-- Returns a rounded angle.
GateActions["angle_round"] = {
name = "Round",
inputs = { "A" },
inputtypes = { "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, A)
if !A then A = Angle(0, 0, 0) end
return Angle(math.Round(A.p),math.Round(A.y),math.Round(A.r))
end,
label = function(Out, A)
return string.format ("round(%s) = (%d,%d,%d)", A, Out.p, Out.y, Out.r)
end
}
GateActions["angle_select"] = {
name = "Select",
inputs = { "Choice", "A", "B", "C", "D", "E", "F", "G", "H" },
inputtypes = { "NORMAL", "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE", "ANGLE" },
outputtypes = { "ANGLE" },
output = function(gate, Choice, ...)
Choice = math.Clamp(Choice,1,8)
return ({...})[Choice]
end,
label = function(Out, Choice)
return string.format ("select(%s) = %s", Choice, Out)
end
}
GateActions["angle_mulcomp"] = {
name = "Multiplication (component)",
inputs = { "A", "B" },
inputtypes = { "ANGLE", "NORMAL" },
outputtypes = { "ANGLE" },
output = function(gate, A, B)
if !A then A = Angle(0, 0, 0) end
if !B then B = 0 end
return Angle( A.p * B, A.y * B, A.r * B )
end,
label = function(Out, A, B)
return string.format ("%s * %s = "..tostring(Out), A, B )
end
}
GateActions["angle_clampn"] = {
name = "Clamp (numbers)",
inputs = { "A", "Min", "Max" },
inputtypes = { "ANGLE", "NORMAL", "NORMAL" },
outputtypes = { "ANGLE" },
output = function( gate, A, Min, Max )
if (Min > Max) then Min, Max = Max, Min end
return Angle( math.Clamp(A.p,Min,Max), math.Clamp(A.y,Min,Max), math.Clamp(A.r,Min,Max) )
end,
label = function( Out, A, Min, Max )
return "Clamp(" .. A .. "," .. Min .. "," .. Max .. ") = " .. tostring(Out)
end
}
GateActions["angle_clampa"] = {
name = "Clamp (angles)",
inputs = { "A", "Min", "Max" },
inputtypes = { "ANGLE", "ANGLE", "ANGLE" },
outputtypes = { "ANGLE" },
output = function( gate, A, Min, Max )
if (Min.p > Max.p) then Min.p, Max.p = Max.p, Min.p end
if (Min.y > Max.y) then Min.y, Max.y = Max.y, Min.y end
if (Min.r > Max.r) then Min.r, Max.r = Max.r, Min.r end
return Angle( math.Clamp(A.p,Min.p,Max.p), math.Clamp(A.y,Min.y,Max.y), math.Clamp(A.r,Min.r,Max.r) )
end,
label = function( Out, A, Min, Max )
return "Clamp(" .. A .. "," .. Min .. "," .. Max .. ") = " .. tostring(Out)
end
}
GateActions()
|
--[[
TheNexusAvenger
Service for managing feature flags with Nexus Admin.
--]]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage"))
local ServerScriptServiceProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ServerScriptService"))
local Armor = ReplicatedStorageProject:GetResource("Data.Armor")
local GameTypes = ReplicatedStorageProject:GetResource("Data.GameTypes")
local MapTypes = ReplicatedStorageProject:GetResource("Data.MapTypes")
local RobuxItems = ReplicatedStorageProject:GetResource("Data.RobuxItems")
local NexusEventCreator = ReplicatedStorageProject:GetResource("External.NexusInstance.Event.NexusEventCreator")
local NexusAdminFeatureFlags
local FeatureFlagService = ReplicatedStorageProject:GetResource("External.NexusInstance.NexusInstance"):Extend()
FeatureFlagService:SetClassName("FeatureFlagService")
FeatureFlagService.RoundFeatureFlagChanged = NexusEventCreator:CreateEvent()
FeatureFlagService.MeshDeformationFeatureFlagChanged = NexusEventCreator:CreateEvent()
coroutine.wrap(function()
--Get Nexus Admin's Feature Flag service.
local NexusAdmin = ServerScriptServiceProject:GetResource("NexusAdmin")
while not NexusAdmin:GetAdminLoaded() do wait() end
NexusAdminFeatureFlags = NexusAdmin.FeatureFlags
--Add the feature flags for the rounds and maps.
for RoundTypeName,_ in pairs(GameTypes) do
NexusAdminFeatureFlags:AddFeatureFlag("Round"..tostring(RoundTypeName).."Enabled",true)
NexusAdminFeatureFlags:GetFeatureFlagChangedEvent("Round"..tostring(RoundTypeName).."Enabled"):Connect(function()
FeatureFlagService.RoundFeatureFlagChanged:Fire()
end)
end
for MapTypeName,_ in pairs(MapTypes) do
NexusAdminFeatureFlags:AddFeatureFlag("Map"..tostring(MapTypeName).."Enabled",true)
NexusAdminFeatureFlags:GetFeatureFlagChangedEvent("Map"..tostring(MapTypeName).."Enabled"):Connect(function()
FeatureFlagService.RoundFeatureFlagChanged:Fire()
end)
end
FeatureFlagService.RoundFeatureFlagChanged:Fire()
--Add the feature flags for the shop items.
NexusAdminFeatureFlags:AddFeatureFlag("ShopEnabled",true)
for ArmorName,_ in pairs(Armor) do
NexusAdminFeatureFlags:AddFeatureFlag("Armor"..tostring(ArmorName).."PurchaseEnabled",true)
end
--Add the feature flags for Robux items.
NexusAdminFeatureFlags:AddFeatureFlag("RobuxPurchasesEnabled",true)
for _,RobuxData in pairs(RobuxItems) do
NexusAdminFeatureFlags:AddFeatureFlag("RobuxPurchase"..tostring(RobuxData.Name).."Enabled",true)
end
--Add the feature flag for mesh deformation.
NexusAdminFeatureFlags:AddFeatureFlag("UseMeshDeformation",true)
NexusAdminFeatureFlags:GetFeatureFlagChangedEvent("UseMeshDeformation"):Connect(function()
FeatureFlagService.MeshDeformationFeatureFlagChanged:Fire()
end)
FeatureFlagService.MeshDeformationFeatureFlagChanged:Fire()
end)()
--[[
Returns the value of a feature flag.
--]]
function FeatureFlagService:GetFeatureFlag(Name)
if NexusAdminFeatureFlags then
return NexusAdminFeatureFlags:GetFeatureFlag(Name)
end
return true
end
--[[
Returns if a round type and map type are enabled.
--]]
function FeatureFlagService:RoundEnabled(RoundType,MapType)
return self:GetFeatureFlag("Round"..tostring(RoundType).."Enabled") and self:GetFeatureFlag("Map"..tostring(MapType).."Enabled")
end
--[[
Returns if an item purchase is enabled.
--]]
function FeatureFlagService:ItemPurchaseEnabled(ItemName)
return self:GetFeatureFlag("ShopEnabled") and self:GetFeatureFlag("Armor"..tostring(ItemName).."PurchaseEnabled")
end
--[[
Returns if a Robux purchase is enabled.
--]]
function FeatureFlagService:RobuxPurchaseEnabled(RobuxItemName)
return self:GetFeatureFlag("RobuxPurchasesEnabled") and self:GetFeatureFlag("RobuxPurchase"..tostring(RobuxItemName).."Enabled")
end
return FeatureFlagService |
require "class"
Vector3 = Class(function(self, x, y, z)
self.x, self.y, self.z = x or 0, y or 0, z or 0
end)
Point = Vector3
function Vector3:__add(rhs)
return Vector3(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
end
function Vector3:__sub(rhs)
return Vector3(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
end
function Vector3:__mul(rhs)
return Vector3(self.x * rhs, self.y * rhs, self.z * rhs)
end
function Vector3:__div(rhs)
return Vector3(self.x / rhs, self.y / rhs, self.z / rhs)
end
function Vector3:Dot(rhs)
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
end
function Vector3:Cross(rhs)
return Vector3(self.y * rhs.z - self.z * rhs.y,
self.z * rhs.x - self.x * rhs.z,
self.x * rhs.y - self.y * rhs.x)
end
function Vector3:__tostring()
return string.format("(%2.2f, %2.2f, %2.2f)", self.x, self.y, self.z)
end
function Vector3:__eq(rhs)
return self.x == rhs.x and self.y == rhs.y and self.z == rhs.z
end
function Vector3:DistSq(other)
return (self.x - other.x) * (self.x - other.x) + (self.y - other.y) * (self.y - other.y) + (self.z - other.z) * (self.z - other.z)
end
function Vector3:Dist(other)
return math.sqrt(self:DistSq(other))
end
function Vector3:LengthSq()
return self.x * self.x + self.y * self.y + self.z * self.z
end
function Vector3:Length()
return math.sqrt(self:LengthSq())
end
function Vector3:Normalize()
local len = self:Length()
if len > 0 then
self.x = self.x / len
self.y = self.y / len
self.z = self.z / len
end
return self
end
function Vector3:GetNormalized()
return self / self:Length()
end
function Vector3:Invert()
self.x = -self.x
self.y = -self.y
self.z = -self.z
return self
end
function Vector3:GetInverse()
return Vector3(-self.x, -self.y, -self.z)
end
function Vector3:Get()
return self.x, self.y, self.z
end
function Vector3:IsVector3()
return true
end
function ToVector3(obj, y, z)
if not obj then
return
end
if obj.IsVector3 then
-- note: specifically not a function call!
return obj
end
if type(obj) == "table" then
return Vector3(tonumber(obj[1]), tonumber(obj[2]), tonumber(obj[3]))
else
return Vector3(tonumber(obj), tonumber(y), tonumber(z))
end
end
|
-- premake5.lua
defines { "TRACE" }
workspace "Erlang.NET"
configurations { "Debug", "Release" }
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
optimize "On"
project "test"
location "test"
kind "ConsoleApp"
language "C#"
targetdir "bin/%{cfg.buildcfg}"
objdir "obj/%{prj.name}"
files { "test/**.cs", "test/**.Config" }
links { "System", "System.Configuration", "deps/log4net", "Erlang.NET" }
project "Erlang.NET"
location "Erlang.NET"
kind "SharedLib"
language "C#"
targetdir "bin/%{cfg.buildcfg}"
objdir "obj/%{prj.name}"
files { "Erlang.NET/**.cs", "Erlang.NET/**.Config" }
links { "System", "System.Configuration", "deps/log4net" }
project "echo"
location "echo"
kind "ConsoleApp"
language "C#"
targetdir "bin/%{cfg.buildcfg}"
objdir "obj/%{prj.name}"
files { "echo/**.cs", "echo/**.Config" }
links { "System", "System.Configuration", "deps/log4net", "Erlang.NET" }
project "epmd"
location "epmd"
kind "ConsoleApp"
language "C#"
targetdir "bin/%{cfg.buildcfg}"
objdir "obj/%{prj.name}"
files { "epmd/**.cs", "epmd/**.Config" }
links { "System", "System.Configuration", "System.Configuration.Install", "System.ServiceProcess", "deps/log4net", "Erlang.NET" }
project "ping"
location "ping"
kind "ConsoleApp"
language "C#"
targetdir "bin/%{cfg.buildcfg}"
objdir "obj/%{prj.name}"
files { "ping/**.cs", "ping/**.Config" }
links { "System", "System.Configuration", "deps/log4net", "Erlang.NET" }
|
require("lsp").setup "typescript"
|
HpwRewrite.Language = HpwRewrite.Language or { }
HpwRewrite.Language.Languages = HpwRewrite.Language.Languages or { }
HpwRewrite.Language.CurrentLanguage = "en"
function HpwRewrite.Language:AddLanguage(codename, name)
if self.Languages[codename] then return end
self.Languages[codename] = { }
self.Languages[codename].Name = name
self.Languages[codename].Dictonary = { }
print("[Wand] Added " .. name .. " language")
end
function HpwRewrite.Language:AddWord(lCodeName, index, word)
local lang = self.Languages[lCodeName]
if not lang then print("[Wand] Language " .. lCodeName .. " not found!") return end
lang.Dictonary[index] = word
end
function HpwRewrite.Language:GetWord(index, lCodeName)
lCodeName = lCodeName or self.CurrentLanguage
local lang = self.Languages[lCodeName]
if not lang then print("[Wand] Language " .. lCodeName .. " not found!") return end
local word = lang.Dictonary[index]
if not word then
lang = self.Languages["en"] -- Default one
if lang then
word = lang.Dictonary[index]
if not word then
print("[Wand] Word " .. index .. " not found!")
return index
end
return word
end
end
return word
end
HpwRewrite:IncludeFolder("hpwrewrite/language", true)
-- Defaulting to ENGLISH if your homelang is not found
local cvar = GetConVar("gmod_language")
if cvar then
if HpwRewrite.Language.Languages[string.lower(cvar:GetString())] then
HpwRewrite.Language.CurrentLanguage = string.lower(cvar:GetString())
end
else
print("[Wand] Can't find 'gmod_language' variable!")
end
local customlang = HpwRewrite.CVars.Language
if customlang then
local val = customlang:GetString()
if val != customlang:GetDefault() and HpwRewrite.Language.Languages[val] then
HpwRewrite.Language.CurrentLanguage = string.lower(val)
end
end
print("[Wand] Loaded " .. HpwRewrite.Language.CurrentLanguage .. " language!") |
g_DGSCanvasIndex = 0
function dgsCreateCanvas(renderSource,w,h,color)
assert(isElement(renderSource),"Bad argument @dgsCreateCanvas at argument 1, expected texture/shader/render target got "..type(renderSource))
local eleType = getElementType(renderSource)
assert(eleType=="shader" or eleType=="texture" or eleType=="render-target-texture","Bad argument @dgsCreateCanvas at argument 1, expected texture/shader/render target got "..eleType)
assert(type(w) == "number","Bad argument @dgsCreateCanvas at argument 2, expect number got "..type(w))
assert(type(h) == "number","Bad argument @dgsCreateCanvas at argument 3, expect number got "..type(h))
color = color or 0xFFFFFFFF
local canvas = dxCreateRenderTarget(w,h,true) -- Main Render Target
if not isElement(canvas) then
local videoMemory = dxGetStatus().VideoMemoryFreeForMTA
outputDebugString("Failed to create render target for dgs-dxcanvas [Expected:"..(0.0000076*w*h).."MB/Free:"..videoMemory.."MB]",2)
return false
end
dgsSetData(canvas,"asPlugin","dgs-dxcanvas")
dgsSetData(canvas,"blendMode","blend")
dgsSetData(canvas,"renderSource",renderSource)
dgsSetData(canvas,"resolution",{w,h})
triggerEvent("onDgsPluginCreate",canvas,sourceResource)
return canvas
end
function dgsCanvasRender(canvas)
local resolution = dgsElementData[canvas].resolution
local renderSource = dgsElementData[canvas].renderSource
local blendMode = dxGetBlendMode()
dxSetRenderTarget(canvas,true)
dxDrawImage(0,0,resolution[1],resolution[2],renderSource)
dxSetRenderTarget()
dxSetBlendMode(blendMode)
end |
local _hook_Add = hook.Add
if not gAC.config.ANTISCREENGRAB_CHECKS then return end
gAC.Network:AddReceiver(
"CRV",
function(data, plr)
if plr.AntiScreenGrab then return end
plr.AntiScreenGrab = true
gAC.AddDetection( plr, "Anti-Screengrab Detected [Code 130]", gAC.config.ANTISCREENGRAB_PUNSIHMENT, gAC.config.ANTISCREENGRAB_PUNSIHMENT_BANTIME )
end
)
_hook_Add("gAC.CLFilesLoaded", "g-AC_AntiScreenGrab", function(ply)
gAC.Network:Send("CRV", "", ply)
end) |
slot1 = 99
class("ChangeChatRoomCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot2 = slot1:getBody()
if not getProxy(PlayerProxy) then
return
end
if not slot3:getData() then
return
end
if not slot2 then
pg.TipsMgr.GetInstance():ShowTips(i18n("main_notificationLayer_not_roomId"))
return
end
if slot0 < slot2 or slot2 < 0 then
pg.TipsMgr.GetInstance():ShowTips(i18n("main_notificationLayer_roomId_invaild"))
return
end
pg.ConnectionMgr.GetInstance():Send(11401, {
room_id = slot2
}, 11402, function (slot0)
if slot0.result == 0 then
slot0:changeChatRoom(slot0.room_id or slot0.changeChatRoom)
slot0:updatePlayer(slot0)
getProxy(ChatProxy).clearMsg(slot0.changeChatRoom)
slot0.changeChatRoom:sendNotification(GAME.CHANGE_CHAT_ROOM_DONE, slot0)
elseif slot0.result == 6 then
slot3:sendNotification(GAME.CHAT_ROOM_MAX_NUMBER)
else
pg.TipsMgr.GetInstance():ShowTips(errorTip("player_change_chat_room_erro", slot0.result))
end
end)
end
return class("ChangeChatRoomCommand", pm.SimpleCommand)
|
--
-- Register basic_signs for Magic pen
-- https://gitlab.com/VanessaE/basic_signs
--
local nodes = {}
for nodename,_ in pairs(minetest.registered_nodes) do
if nodename:find('^basic_signs:') then
-- Match found, add to registration list
table.insert(nodes, nodename)
end
end
if minetest.registered_nodes["default:sign_wall_wood"] then
table.insert(nodes, "default:sign_wall_wood")
end
if minetest.registered_nodes["default:sign_wall_steel"] then
table.insert(nodes, "default:sign_wall_steel")
end
local truncate = metatool.ns('magic_pen').truncate
local get_content_title = metatool.ns('magic_pen').get_content_title
local paste
if signs_lib then
paste = function(self, node, pos, player, data)
if data.content then
signs_lib.update_sign(pos, { text = truncate(data.content, 512) })
end
end
else
paste = function(self, node, pos, player, data)
if data.content then
local meta = minetest.get_meta(pos)
meta:set_string("text", truncate(data.content, 512))
meta:set_string("infotext", data.content)
end
end
end
local definition = {
name = 'basic_signs',
nodes = nodes,
group = 'text',
protection_bypass_read = "interact",
paste = paste
}
function definition:before_write(pos, player)
return signs_lib.can_modify(pos, player)
end
function definition:copy(node, pos, player)
local meta = minetest.get_meta(pos)
local content = meta:get("text")
local nicename = minetest.registered_nodes[node.name].description or node.name
return {
description = ("%s at %s"):format(nicename, minetest.pos_to_string(pos)),
content = content,
title = get_content_title(content),
source = meta:get("owner"),
}
end
return definition
|
-- Copyright (c) 2016, prpl Foundation
--
-- Permission to use, copy, modify, and/or distribute this software for any purpose with or without
-- fee is hereby granted, provided that the above copyright notice and this permission notice appear
-- in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
-- INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
-- FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-- ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
-- Author: Nils Koenig <openwrt@newk.it>
local fs = require "nixio.fs"
local sys = require "luci.sys"
local uci = require("luci.model.uci").cursor()
function time_validator(self, value, desc)
if value ~= nil then
h_str, m_str = string.match(value, "^(%d%d?):(%d%d?)$")
h = tonumber(h_str)
m = tonumber(m_str)
if ( h ~= nil and
h >= 0 and
h <= 23 and
m ~= nil and
m >= 0 and
m <= 59) then
return value
end
end
return nil, translatef("The value %s is invalid", desc)
end
-- -------------------------------------------------------------------------------------------------
-- BEGIN Map
m = Map("wifi_schedule", translate("Wifi Schedule"), translate("Defines a schedule when to turn on and off wifi."))
function m.on_commit(self)
sys.exec("/usr/bin/wifi_schedule.sh cron")
end
-- END Map
-- BEGIN Global Section
global_section = m:section(TypedSection, "global", translate("Global Settings"))
global_section.optional = false
global_section.rmempty = false
global_section.anonymous = true
-- END Section
-- BEGIN Global Enable Checkbox
global_enable = global_section:option(Flag, "enabled", translate("Enable Wifi Schedule"))
global_enable.optional = false
global_enable.rmempty = false
function global_enable.validate(self, value, global_section)
if value == "1" then
if ( fs.access("/sbin/wifi") and
fs.access("/usr/bin/wifi_schedule.sh") )then
return value
else
return nil, translate("Could not find required /usr/bin/wifi_schedule.sh or /sbin/wifi")
end
else
return "0"
end
end
-- END Global Enable Checkbox
-- BEGIN Global Logging Checkbox
global_logging = global_section:option(Flag, "logging", translate("Enable logging"))
global_logging.optional = false
global_logging.rmempty = false
global_logging.default = 0
-- END Global Enable Checkbox
-- BEGIN Global Activate WiFi Button
enable_wifi = global_section:option(Button, "enable_wifi", translate("Activate wifi"))
function enable_wifi.write()
sys.exec("/usr/bin/wifi_schedule.sh start manual")
end
-- END Global Activate Wifi Button
-- BEGIN Global Disable WiFi Gracefully Button
disable_wifi_gracefully = global_section:option(Button, "disable_wifi_gracefully", translate("Disable wifi gracefully"))
function disable_wifi_gracefully.write()
sys.exec("/usr/bin/wifi_schedule.sh stop manual")
end
-- END Global Disable Wifi Gracefully Button
-- BEGIN Disable WiFi Forced Button
disable_wifi_forced = global_section:option(Button, "disable_wifi_forced", translate("Disabled wifi forced"))
function disable_wifi_forced.write()
sys.exec("/usr/bin/wifi_schedule.sh forcestop manual")
end
-- END Global Disable WiFi Forced Button
-- BEGIN Global Unload Modules Checkbox
global_unload_modules = global_section:option(Flag, "unload_modules", translate("Unload Modules (experimental; saves more power)"))
global_unload_modules.optional = false
global_unload_modules.rmempty = false
global_unload_modules.default = 0
-- END Global Unload Modules Checkbox
-- BEGIN Modules
modules = global_section:option(TextValue, "modules", "")
modules:depends("unload_modules", global_unload_modules.enabled);
modules.wrap = "off"
modules.rows = 10
function modules.cfgvalue(self, section)
mod = uci:get("wifi_schedule", section, "modules")
if mod == nil then
mod = ""
end
return mod:gsub(" ", "\r\n")
end
function modules.write(self, section, value)
if value then
value_list = value:gsub("\r\n", " ")
ListValue.write(self, section, value_list)
uci:set("wifi_schedule", section, "modules", value_list)
end
end
-- END Modules
-- BEGIN Determine Modules
determine_modules = global_section:option(Button, "determine_modules", translate("Determine Modules Automatically"))
determine_modules:depends("unload_modules", global_unload_modules.enabled);
function determine_modules.write(self, section)
output = sys.exec("/usr/bin/wifi_schedule.sh getmodules")
modules:write(section, output)
end
-- END Determine Modules
-- BEGIN Section
d = m:section(TypedSection, "entry", translate("Schedule events"))
d.addremove = true
--d.anonymous = true
-- END Section
-- BEGIN Enable Checkbox
c = d:option(Flag, "enabled", translate("Enable"))
c.optional = false
c.rmempty = false
-- END Enable Checkbox
-- BEGIN Day(s) of Week
dow = d:option(MultiValue, "daysofweek", translate("Day(s) of Week"))
dow.optional = false
dow.rmempty = false
dow:value("Monday", translate("Monday"))
dow:value("Tuesday", translate("Tuesday"))
dow:value("Wednesday", translate("Wednesday"))
dow:value("Thursday", translate("Thursday"))
dow:value("Friday", translate("Friday"))
dow:value("Saturday", translate("Saturday"))
dow:value("Sunday", translate("Sunday"))
-- END Day(s) of Weel
-- BEGIN Start Wifi Dropdown
starttime = d:option(Value, "starttime", translate("Start WiFi"))
starttime.optional = false
starttime.rmempty = false
starttime:value("00:00")
starttime:value("01:00")
starttime:value("02:00")
starttime:value("03:00")
starttime:value("04:00")
starttime:value("05:00")
starttime:value("06:00")
starttime:value("07:00")
starttime:value("08:00")
starttime:value("09:00")
starttime:value("10:00")
starttime:value("11:00")
starttime:value("12:00")
starttime:value("13:00")
starttime:value("14:00")
starttime:value("15:00")
starttime:value("16:00")
starttime:value("17:00")
starttime:value("18:00")
starttime:value("19:00")
starttime:value("20:00")
starttime:value("21:00")
starttime:value("22:00")
starttime:value("23:00")
function starttime.validate(self, value, d)
return time_validator(self, value, translate("Start Time"))
end
-- END Start Wifi Dropdown
-- BEGIN Stop Wifi Dropdown
stoptime = d:option(Value, "stoptime", translate("Stop WiFi"))
stoptime.optional = false
stoptime.rmempty = false
stoptime:value("00:00")
stoptime:value("01:00")
stoptime:value("02:00")
stoptime:value("03:00")
stoptime:value("04:00")
stoptime:value("05:00")
stoptime:value("06:00")
stoptime:value("07:00")
stoptime:value("08:00")
stoptime:value("09:00")
stoptime:value("10:00")
stoptime:value("11:00")
stoptime:value("12:00")
stoptime:value("13:00")
stoptime:value("14:00")
stoptime:value("15:00")
stoptime:value("16:00")
stoptime:value("17:00")
stoptime:value("18:00")
stoptime:value("19:00")
stoptime:value("20:00")
stoptime:value("21:00")
stoptime:value("22:00")
stoptime:value("23:00")
function stoptime.validate(self, value, d)
return time_validator(self, value, translate("Stop Time"))
end
-- END Stop Wifi Dropdown
-- BEGIN Force Wifi Stop Checkbox
force_wifi = d:option(Flag, "forcewifidown", translate("Force disabling wifi even if stations associated"))
force_wifi.default = false
force_wifi.rmempty = false
function force_wifi.validate(self, value, d)
if value == "0" then
if fs.access("/usr/bin/iwinfo") then
return value
else
return nil, translate("Could not find required programm /usr/bin/iwinfo")
end
else
return "1"
end
end
-- END Force Wifi Checkbox
return m
|
local L = LibStub("AceLocale-3.0"):GetLocale("IceHUD", false)
local validUnits = {"player", "target", "focus", "pet", "vehicle", "targettarget", "main hand weapon", "off hand weapon"}
local buffOrDebuff = {"buff", "debuff", "charges", "spell count"}
-- OVERRIDE
function IceStackCounter_GetOptions(frame, opts)
opts["customHeader"] = {
type = 'header',
name = L["Aura settings"],
order = 30.1,
}
opts["auraTarget"] = {
type = 'select',
values = validUnits,
name = L["Unit to track"],
desc = L["Select which unit that this bar should be looking for buffs/debuffs on"],
get = function(info)
return IceHUD:GetSelectValue(info, frame.moduleSettings.auraTarget)
end,
set = function(info, v)
frame.moduleSettings.auraTarget = info.option.values[v]
frame.unit = info.option.values[v]
frame:Redraw()
IceHUD:NotifyOptionsChange()
end,
disabled = function()
return not frame.moduleSettings.enabled or frame.moduleSettings.auraType == "charges" or frame.moduleSettings.auraType == "spell count"
end,
order = 30.4,
}
opts["auraType"] = {
type = 'select',
values = buffOrDebuff,
name = L["Buff or debuff?"],
desc = L["Whether we are tracking a buff or debuff"],
get = function(info)
return IceHUD:GetSelectValue(info, frame.moduleSettings.auraType)
end,
set = function(info, v)
frame.moduleSettings.auraType = info.option.values[v]
frame:Redraw()
end,
disabled = function()
return not frame.moduleSettings.enabled or frame.unit == "main hand weapon" or frame.unit == "off hand weapon"
end,
order = 30.5,
}
opts["auraName"] = {
type = 'input',
name = L["Aura to track"],
desc = L["Which buff/debuff this counter will be tracking. \n\nRemember to press ENTER after filling out this box with the name you want or it will not save."],
get = function()
return frame.moduleSettings.auraName
end,
set = function(info, v)
frame.moduleSettings.auraName = v
frame:Redraw()
end,
disabled = function()
return not frame.moduleSettings.enabled or frame.unit == "main hand weapon" or frame.unit == "off hand weapon"
end,
usage = "<which aura to track>",
order = 30.6,
}
opts["trackOnlyMine"] = {
type = 'toggle',
name = L["Only track auras by me"],
desc = L["Checking this means that only buffs or debuffs that the player applied will trigger this bar"],
get = function()
return frame.moduleSettings.onlyMine
end,
set = function(info, v)
frame.moduleSettings.onlyMine = v
frame:Redraw()
end,
disabled = function()
return not frame.moduleSettings.enabled or frame.unit == "main hand weapon" or frame.unit == "off hand weapon"
or frame.moduleSettings.auraType == "charges" or frame.moduleSettings.auraType == "spell count"
end,
order = 30.7,
}
opts["maxCount"] = {
type = 'input',
name = L["Maximum applications"],
desc = L["How many total applications of this buff/debuff can be applied. For example, only 5 sunders can ever be on a target, so this would be set to 5 for tracking Sunder.\n\nRemember to press ENTER after filling out this box with the name you want or it will not save."],
get = function()
return tostring(frame.moduleSettings.maxCount)
end,
set = function(info, v)
if not v or not tonumber(v) or tonumber(v) <= 0 then
v = 5
end
frame.moduleSettings.maxCount = tonumber(v)
frame:Redraw()
end,
disabled = function()
return not frame.moduleSettings.enabled or frame.moduleSettings.auraType == "charges"
end,
usage = "<the maximum number of valid applications>",
order = 30.9,
}
end
function IceStackCounter_GetMaxCount(frame)
if frame.moduleSettings.auraType == "charges" then
local _, max = GetSpellCharges(frame.moduleSettings.auraName)
return max or 1
else
return tonumber(frame.moduleSettings.maxCount)
end
end
function IceStackCounter_GetDefaultSettings(defaults)
defaults["maxCount"] = 5
defaults["auraTarget"] = "player"
defaults["auraName"] = ""
defaults["onlyMine"] = true
defaults["auraType"] = "buff"
end
function IceStackCounter_Enable(frame)
frame:RegisterEvent("UNIT_AURA", "UpdateCustomCount")
frame:RegisterEvent("UNIT_PET", "UpdateCustomCount")
if IceHUD.EventExistsPlayerPetChanged then
frame:RegisterEvent("PLAYER_PET_CHANGED", "UpdateCustomCount")
end
if FocusUnit then
frame:RegisterEvent("PLAYER_FOCUS_CHANGED", "UpdateCustomCount")
end
frame:RegisterEvent("PLAYER_DEAD", "UpdateCustomCount")
frame:RegisterEvent("SPELL_UPDATE_CHARGES", "UpdateCustomCount")
frame.unit = frame.moduleSettings.auraTarget or "player"
if not tonumber(frame.moduleSettings.maxCount) or tonumber(frame.moduleSettings.maxCount) <= 0 then
frame.moduleSettings.maxCount = 5
frame:Redraw()
end
end
function IceStackCounter_GetCount(frame)
if not frame.moduleSettings.auraName then
return
end
local points
if IceHUD.IceCore:IsInConfigMode() then
points = tonumber(frame.moduleSettings.maxCount)
else
if frame.moduleSettings.auraType == "charges" then
points = GetSpellCharges(frame.moduleSettings.auraName) or 0
elseif frame.moduleSettings.auraType == "spell count" then
points = GetSpellCount(frame.moduleSettings.auraName) or 0
else
points = IceHUD:GetAuraCount(frame.moduleSettings.auraType == "buff" and "HELPFUL" or "HARMFUL",
frame.unit, frame.moduleSettings.auraName, frame.moduleSettings.onlyMine, true)
end
end
frame.lastPoints = points
if (points == 0) then
points = nil
end
return points
end
function IceStackCounter_UseTargetAlpha(frame)
if frame.moduleSettings.auraType == "charges" then
return IceStackCounter_GetCount(frame) ~= IceStackCounter_GetMaxCount(frame) or frame.target or frame.combat
else
return frame.lastPoints ~= nil and frame.lastPoints > 0
end
end
|
-- fsu.lua : File System Utilities
--
-- This is a collection of file utility functions that use only standard Lua
-- API functions. Use the "lfsu" module for additional functions that
-- require LFS.
--
-- Functions
-- =========
--
-- Without LFS, FSU cannot detect the underlying OS, so it provides two
-- versions of some functions. `fsu.win` holds versions suitable for
-- Windows, `fsu.nix` holds versions suitable for UNIX systems.
--
-- cleanpath(path) --> path
--
-- Remove redundant "." and "dir/.." segments from the path. Initial
-- ".." elements will be retained. Redundant trailing "/" is trimmed.
-- In Windows, convert slashes to "/".
--
-- splitpath(path) --> dir, name
--
-- Given path, return parent directory and name within that directory.
-- If there are no directory separators, return ".". Any ".." or "."
-- elements in the input are treated as significant (cleanpath() is not
-- called). Slashes are normalized (Windows).
--
-- If `path` is relative and includes no directory separators, the `dir`
-- result is ".". If `path` identifies a root directory, `dir` is the
-- root directory and `name` is ".".
--
-- resolve(dir, path) --> path
--
-- Combine directory name with a path relative to it, returning a "clean"
-- path. Example: resove("a/b", "../c") --> "a/c".
--
-- relpathto(src, dst, [cwd]) --> path
--
-- Compute a relative path to `dst` as if `src` were the current working
-- directory. Returned path has no trailing slash unless its a root
-- directory. In Windows, returned path has forward slashes, and result
-- may be absolute when drive letters differ between `src` and `dst`. If
-- `src` or `dst` are relative and `cwd` is supplied, `cwd` indicates the
-- directory to which they are relative.
--
-- If `src` is an absolute path and `dst` relative, `cwd` is needed to
-- successfully construct a result (an error results otherwise).
--
-- If `src` is relative and `dst` absolute, `cwd` is needed to construct
-- a relative path (an absolute path is returned otherwise).
--
-- If `src` begins with more ".." elements than `dst` (after both have
-- been resolved with `cwd`, if given), then an error results.
--
-- On error, relpathto() returns nil and an error string.
--
-- read(filename) --> data, [error]
--
-- Return file contents, or nil and error string.
--
-- write(filename, data) --> success, [error]
--
-- Write contents to file.
--
-- File Name Conventions
-- =====================
--
-- Returned directory names do not have trailing slashes unless they
-- identify a root directory (e.g. "/" or "C:/"). Input strings naming
-- directories *may* include a trailing slash for non-root directories.
--
-- `win` functions accept forward- or backslashes, recognize drive letters,
-- perform case-insensitive comparisons (but preserve case), and return
-- paths with forward slashes.
--
-- `nix` functions recognize only "/" as a directory separator and perform
-- case-sensitive comparisions.
--
----------------------------------------------------------------
-- Shared functions
----------------------------------------------------------------
local function addslash(p)
if p:sub(-1) == "/" then
return p
end
return p .. "/"
end
-- Split "dir/name" into "dir" and "name". Root dir = "/"
--
local function splitpath(path)
if path:sub(-1) == "/" then
path = path:sub(1,-2)
end
local dir, name = path:match("(.*)/(.*)")
if dir then
return (dir=="" and "/" or dir), name
elseif path == "" then
return "/", "."
end
return ".", path
end
-- Eliminate "." and ".." where possible, and normalize path:
-- * Use only "/" as a separator character.
-- * No trailing "/", except in the case of the root directory
-- * No "." elements, except in the case of a solitary "."
-- * No ".." elements, except at the start of the path.
--
local function cleanpath(path)
local init, path = path:match("^(/*)(.*)")
while path:sub(1,2) == "./" do
path = path:sub(3)
end
local e,post
local n = 1
repeat
n, e, post = path:match("/()(%.%.?)(.?)", n)
if post ~= "" and post ~= "/" then
-- skip
elseif e == "." then
-- "xxx" /. "/yyy" => "xxx/yyy"
path = path:sub(1,n-2) .. path:sub(n+1)
n = n - 1
else
-- "xxx/" parent/../ "yyyy" -> "xxx/yyy"
local a = n-2
while a > 0 and path:sub(a,a) ~= "/" do
a = a - 1
end
local parent = path:sub(a+1,n-2)
if parent ~= "" and parent ~= ".." then
path = path:sub(1,a) .. path:sub(n+3)
n = a
end
end
until n == nil
-- no trailing '/'
if path:sub(-1,-1) then
path = path:match("(.-)/*$")
end
path = init .. path
return path ~= "" and path or "."
end
-- Compute relative from directory `src` to directory `dst`. `src` and
-- `dst` must be absolute, clean paths. Result is always a relative path,
-- or nil if src begins with ".." elements.
--
local function xrelpathto(src, dst, streq)
local s = addslash(src)
local d = addslash(dst)
while true do
local a, b = s:match("[^/]*/"), d:match("[^/]*/")
if not a then
break
elseif streq(a,b) then
s = s:sub(#a+1)
d = d:sub(#a+1)
elseif a == "../" then
return nil, "relpathto: destination is above root directory"
elseif a == "/" then
return nil, "relpathto: no base for destination directory"
elseif b == "/" then
break -- absolute from relative?
else
s = s:sub(#a+1)
d = "../" .. d
end
end
d = d:sub(1,-2)
return d == "" and "." or d
end
local function read(name)
local f,err = io.open(name, "r")
if not f then
return f,err
end
local data = f:read("*a")
f:close()
return data
end
local function write(name, data)
local f,err = io.open(name, "wb")
if not f then
return f,err
end
f:write(data)
f:close()
return true
end
----------------------------------------------------------------
-- UNIX functions
----------------------------------------------------------------
local nix = {
read = read,
write = write,
cleanpath = cleanpath,
splitpath = splitpath,
}
local function streq(a,b)
return a==b
end
function nix.resolve(dir, path)
if path:sub(1,1) == "/" then
--
else
path = addslash(dir) .. path
end
return cleanpath(path)
end
function nix.relpathto(src, dst, cwd)
if cwd then
src = nix.resolve(cwd, src)
dst = nix.resolve(cwd, dst)
end
return xrelpathto(src, dst, streq)
end
----------------------------------------------------------------
-- Windows functions
----------------------------------------------------------------
local function splitdev(path)
local drv, rest = path:match("^([a-zA-Z]%:)(.*)")
return drv, rest or path
end
local function joindev(drive, path)
return drive and drive..path or path
end
local function streqi(a,b)
return a==b or a and b and a:upper()==b:upper()
end
local function fixslashes(path)
return path:gsub("\\", "/")
end
local win = {
read = read,
write = write,
}
function win.cleanpath(path)
local drv, p = splitdev( fixslashes(path) )
return joindev(drv, cleanpath(p))
end
function win.splitpath(path)
local drv, x = splitdev( fixslashes(path) )
local xdir, xpath = splitpath(x)
return joindev(drv, xdir), xpath
end
function win.resolve(dir, path)
if path:match("^[a-zA-Z]:[/\\]") then
--
elseif path:match("^[/\\]") then
path = joindev(dir:match("^([a-zA-Z]:)"), path)
else
path = addslash(dir) .. path
end
return win.cleanpath(path)
end
function win.relpathto(src, dst, cwd)
if cwd then
src = win.resolve(cwd, src)
dst = win.resolve(cwd, dst)
end
local sd, sp = splitdev(src)
local dd, dp = splitdev(dst)
if streqi(sd, dd) then
return xrelpathto(sp, dp, streqi)
end
return dst
end
----------------------------------------------------------------
return {
nix = nix,
win = win,
}
|
require('src/test')
require('src/core')
require('src/builtins')
require('src/contextlib')
require('src/objects')
require('src/logic')
require('src/string')
require('src/system')
require('src/navigation')
describe('navigation',
it('tree_root_nagivation', function()
local l = list()
local function f(v) return function() l:append({'fw', v}) end end
local function b(v) return function() l:append({'bw', v}) end end
local t = TransitionTree()
t:add('left', f('left'), b('root'))
t:add('mid', f('mid'), b('root'))
t:add('right', f('right'), b('root'))
t['left']:add('a', f('a'), b('left'))
t['left']:add('b', f('b'), b('left'))
t['mid']:add('c', f('c'), b('mid'))
t['mid']:add('d', f('d'), b('mid'))
t['right']:add('e', f('e'), b('right'))
t['right']:add('f', f('f'), b('right'))
t:navigate('a', 'f')
local ea = {'bw', 'bw', 'fw', 'fw'}
local en = {'left', 'root', 'right', 'f'}
for i, v in pairs(ea) do
assertEqual(l[i][1], ea[i], 'Did not navigate in correct direction')
assertEqual(l[i][2], en[i], 'Did not navigate to correct node')
end
end),
it('tree_lca_nagivation', function()
local l = list()
local function f(v) return function() l:append({'fw', v}) end end
local function b(v) return function() l:append({'bw', v}) end end
local t = TransitionTree()
t:add('left', f('left'), b('root'))
t:add('mid', f('mid'), b('root'))
t:add('right', f('right'), b('root'))
t['left']:add('a', f('a'), b('left'))
t['left']:add('b', f('b'), b('left'))
t['mid']:add('c', f('c'), b('mid'))
t['mid']:add('d', f('d'), b('mid'))
t['right']:add('e', f('e'), b('right'))
t['right']:add('f', f('f'), b('right'))
t:navigate('a', 'b')
local ea = {'bw', 'fw'}
local en = {'left', 'b'}
for i, v in pairs(ea) do
assertEqual(l[i][1], ea[i], 'Did not navigate in correct direction')
assertEqual(l[i][2], en[i], 'Did not navigate to correct node')
end
end)
)
run_tests()
|
local Container = require('containers/abstract/Container')
local Ban, get = require('class')('Ban', Container)
function Ban:__init(data, parent)
Container.__init(self, data, parent)
self._user = self.client._users:_insert(data.user)
end
function Ban:__hash()
return self._user._id
end
function Ban:delete()
return self._parent:unbanUser(self._user)
end
function get.reason(self)
return self._reason
end
function get.guild(self)
return self._parent
end
function get.user(self)
return self._user
end
return Ban
|
slot2 = "GetRedPacketPopupView"
GetRedPacketPopupView = class(slot1)
GetRedPacketPopupView.ctor = function (slot0)
slot6 = "csb/common/PopUpRedPacketTip.csb"
ClassUtil.extends(slot2, slot0, AbstractZoomPopupView, true)
slot5 = false
slot9 = slot0.onContentTxtChanged
createSetterGetterHandler(slot2, slot0, "contentTxt", handler(slot7, slot0))
slot4 = "confirmCallback"
createSetterGetterHandler(slot2, slot0)
slot0._contentTf = slot0._rootView.view.txtContent_tf
slot4 = false
slot0._rootView.setTouchEnabled(slot2, slot0._rootView)
slot4 = TextField.H_CENTER
slot0._contentTf.setHAlign(slot2, slot0._contentTf)
end
GetRedPacketPopupView.onBtnClick = function (slot0, slot1, slot2)
if slot1 == slot0._rootView.view.btnConfirm then
if slot0._confirmCallback then
slot0._confirmCallback()
end
slot5 = slot0
slot0.hide(slot4)
elseif slot1 == slot0._rootView.view.btnClose or slot0._rootView.view.btnCancel then
slot5 = slot0
slot0.hide(slot4)
end
end
GetRedPacketPopupView.onContentTxtChanged = function (slot0)
slot4 = slot0._contentTxt
slot0._contentTf.setHtmlText(slot2, slot0._contentTf)
end
GetRedPacketPopupView.hide = function (slot0)
slot3 = slot0
AbstractZoomPopupView.hide(slot2)
end
GetRedPacketPopupView.destroy = function (slot0)
slot3 = slot0._rootView.view.btnConfirm
slot0._rootView.view.btnConfirm.destroy(slot2)
slot3 = slot0._rootView.view.btnClose
slot0._rootView.view.btnClose.destroy(slot2)
slot3 = slot0._rootView.view.btnCancel
slot0._rootView.view.btnCancel.destroy(slot2)
end
return
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( "shared.lua" )
util.AddNetworkString( "alcoholvendoropen" )
util.AddNetworkString( "AVBuyBeer" )
util.AddNetworkString( "AVBuyWine" )
util.AddNetworkString( "AVBuyGin" )
util.AddNetworkString( "AVSellAll" )
local AVBuyPriceBeer
local AVSellPriceBeer
local AVBuyPriceWine
local AVSellPriceWine
local EnableBuy
local EnableSell
function ENT:Initialize( )
self.AutomaticFrameAdvance = true
self:SetModel( "models/eli.mdl" )
self:SetHullType( HULL_HUMAN )
self:SetSolid( SOLID_BBOX )
self:SetHullSizeNormal( )
self:SetNPCState( NPC_STATE_SCRIPT )
self:CapabilitiesAdd( CAP_ANIMATEDFACE )
self:SetUseType( SIMPLE_USE )
self:DropToFloor( )
AVBuyPriceBeer = EggrollAM:GetConfig( "AVBuyPriceBeer" )
AVSellPriceBeer = EggrollAM:GetConfig( "AVSellPriceBeer" )
AVBuyPriceWine = EggrollAM:GetConfig( "AVBuyPriceWine" )
AVSellPriceWine = EggrollAM:GetConfig( "AVSellPriceWine" )
AVBuyPriceGin = EggrollAM:GetConfig( "AVBuyPriceGin" )
AVSellPriceGin = EggrollAM:GetConfig( "AVSellPriceGin" )
EnableBuy = EggrollAM:GetConfig( "EnableBuy" )
EnableSell = EggrollAM:GetConfig( "EnableSell" )
self:SetVendorName( EggrollAM:GetConfig( "VendorName" ) )
end
function ENT:AcceptInput( _, _, caller )
net.Start( "alcoholvendoropen" )
net.WriteBool( EnableBuy )
net.WriteBool( EnableSell )
net.Send( caller )
end
net.Receive( "AVBuyBeer", function( _, ply )
if ply:canAfford( AVBuyPriceBeer ) then
EggrollAMBeerEffect( ply )
else
ply:ChatPrint( "You cannot afford beer." )
end
end )
net.Receive( "AVBuyWine", function( _, ply )
if ply:canAfford( AVBuyPriceWine ) then
EggrollAMWineEffect( ply )
else
ply:ChatPrint( "You cannot afford wine." )
end
end )
net.Receive( "AVBuyGin", function( _, ply )
if ply:canAfford( AVBuyPriceGin ) then
EggrollAMGinEffect( ply )
else
ply:ChatPrint( "You cannot afford gin." )
end
end )
net.Receive( "AVSellAll", function( _, ply )
local nobeertosell
local nowinetosell
local nogintosell
if ply:GetNWInt( "EggrollBeerAmount", 0 ) > 0 then
local SellAllPrice = AVSellPriceBeer * ply:GetNWInt( "EggrollBeerAmount", 0 )
ply:addMoney( SellAllPrice )
ply:SetNWInt( "EggrollBeerAmount", 0 )
ply:ChatPrint( "You've been given $" .. SellAllPrice .. " for selling beer." )
else
nobeertosell = true
end
if ply:GetNWInt( "EggrollWineAmount", 0 ) > 0 then
local SellAllPrice = AVSellPriceWine * ply:GetNWInt( "EggrollWineAmount", 0 )
ply:addMoney( SellAllPrice )
ply:SetNWInt( "EggrollWineAmount", 0 )
ply:ChatPrint( "You've been given $" .. SellAllPrice .. " for selling wine." )
else
nowinetosell = true
end
if ply:GetNWInt( "EggrollGinAmount", 0 ) > 0 then
local SellAllPrice = AVSellPriceGin * ply:GetNWInt( "EggrollGinAmount", 0 )
ply:addMoney( SellAllPrice )
ply:SetNWInt( "EggrollGinAmount", 0 )
ply:ChatPrint( "You've been given $" .. SellAllPrice .. " for selling gin." )
else
nogintosell = true
end
if nobeertosell and nowinetosell and nogintosell then
ply:ChatPrint( "You have nothing to sell." )
end
end )
|
--------------------- DIMENSIONAL TANK MK1 ------------------------
--------- TANK 1 ----------
-- Entity --
dmE = {}
dmE.type = "storage-tank"
dmE.name = "StorageTank1MK1"
dmE.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank1.png"
dmE.icon_size = 32
dmE.flags = {"placeable-player", "player-creation"}
dmE.minable = nil
dmE.max_health = 500
dmE.corpse = "medium-remnants"
dmE.collision_box = {{-5.9, -6.6}, {6.2, 5.5}}
dmE.selection_box = {{-5.9, -6.6}, {6.2, 5.5}}
dmE.flags = {"not-rotatable"}
dmE.order = "a"
dmE.fluid_box =
{
base_area = 100,
height = 100,
base_level = -1,
pipe_covers = pipecoverspictures(),
pipe_connections = {}
}
dmE.two_direction_only = true
dmE.window_bounding_box = {{-0.125, 0.6875}, {0.1875, 1.1875}}
dmE.pictures =
{
picture =
{
sheets =
{
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DimensionalTank.png",
priority = "extra-high",
frames = 2,
width = 219,
height = 215,
shift = util.by_pixel(10, -3),
scale = 2
},
{
filename = "__base__/graphics/entity/storage-tank/hr-storage-tank-shadow.png",
priority = "extra-high",
frames = 2,
width = 291,
height = 153,
shift = util.by_pixel(29.75, 22.25),
scale = 2,
draw_as_shadow = true
}
}
},
fluid_background =
{
filename = "__base__/graphics/entity/storage-tank/fluid-background.png",
priority = "extra-high",
width = 32,
height = 15,
},
window_background =
{
filename = "__base__/graphics/entity/storage-tank/window-background.png",
priority = "extra-high",
width = 17,
height = 24,
scale = 3.5,
shift = {0.3,2.0}
},
flow_sprite =
{
filename = "__base__/graphics/entity/pipe/fluid-flow-low-temperature.png",
priority = "extra-high",
width = 160,
height = 20,
scale=3,
shift = {0.3,2.2}
},
gas_flow =
{
filename = "__base__/graphics/entity/pipe/steam.png",
priority = "extra-high",
line_length = 10,
width = 24,
height = 15,
frame_count = 60,
axially_symmetrical = false,
direction_count = 1,
animation_speed = 0.25,
hr_version =
{
filename = "__base__/graphics/entity/pipe/hr-steam.png",
priority = "extra-high",
line_length = 10,
width = 48,
height = 30,
frame_count = 60,
axially_symmetrical = false,
animation_speed = 0.25,
direction_count = 1,
scale = 0.5
}
}
}
dmE.flow_length_in_ticks = 360
dmE.vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }
dmE.working_sound =
{
sound =
{
filename = "__base__/sound/storage-tank.ogg",
volume = 0.8
},
match_volume_to_activity = true,
apparent_volume = 1.5,
max_sounds_per_type = 3
}
dmE.circuit_wire_connection_points = circuit_connector_definitions["storage-tank"].points
dmE.circuit_connector_sprites = circuit_connector_definitions["storage-tank"].sprites
dmE.circuit_wire_max_distance = default_circuit_wire_max_distance
data:extend{dmE}
-- Technology --
local dmT = {}
dmT.name = "StorageTankMK1_1"
dmT.type = "technology"
dmT.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank1.png"
dmT.icon_size = 32
dmT.unit = {
count=450,
time=2,
ingredients={
{"DimensionalSample", 1}
}
}
dmT.prerequisites = {"ControlCenter"}
dmT.effects = {{type="nothing", effect_description={"description.DimensionalTank1"}}, {type="unlock-recipe", recipe="ModuleID1"}}
data:extend{dmT}
--------- TANK 2 ----------
-- Entity --
dt2 = {}
dt2.type = "storage-tank"
dt2.name = "StorageTank2MK1"
dt2.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank2.png"
dt2.icon_size = 32
dt2.flags = {"placeable-player", "player-creation"}
dt2.minable = nil
dt2.max_health = 500
dt2.corpse = "medium-remnants"
dt2.collision_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt2.selection_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt2.flags = {"not-rotatable"}
dt2.order = "a"
dt2.fluid_box =
{
base_area = 100,
height = 100,
base_level = -1,
pipe_covers = pipecoverspictures(),
pipe_connections = {}
}
dt2.two_direction_only = true
dt2.window_bounding_box = {{-0.125, 0.6875}, {0.1875, 1.1875}}
dt2.pictures =
{
picture =
{
sheets =
{
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DimensionalTank2.png",
priority = "extra-high",
frames = 2,
width = 219,
height = 215,
shift = util.by_pixel(10, -3),
scale = 2
},
{
filename = "__base__/graphics/entity/storage-tank/hr-storage-tank-shadow.png",
priority = "extra-high",
frames = 2,
width = 291,
height = 153,
shift = util.by_pixel(29.75, 22.25),
scale = 2,
draw_as_shadow = true
}
}
},
fluid_background =
{
filename = "__base__/graphics/entity/storage-tank/fluid-background.png",
priority = "extra-high",
width = 32,
height = 15,
},
window_background =
{
filename = "__base__/graphics/entity/storage-tank/window-background.png",
priority = "extra-high",
width = 17,
height = 24,
scale = 3.5,
shift = {0.3,2.0}
},
flow_sprite =
{
filename = "__base__/graphics/entity/pipe/fluid-flow-low-temperature.png",
priority = "extra-high",
width = 160,
height = 20,
scale=3,
shift = {0.3,2.2}
},
gas_flow =
{
filename = "__base__/graphics/entity/pipe/steam.png",
priority = "extra-high",
line_length = 10,
width = 24,
height = 15,
frame_count = 60,
axially_symmetrical = false,
direction_count = 1,
animation_speed = 0.25,
hr_version =
{
filename = "__base__/graphics/entity/pipe/hr-steam.png",
priority = "extra-high",
line_length = 10,
width = 48,
height = 30,
frame_count = 60,
axially_symmetrical = false,
animation_speed = 0.25,
direction_count = 1,
scale = 0.5
}
}
}
dt2.flow_length_in_ticks = 360
dt2.vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }
dt2.working_sound =
{
sound =
{
filename = "__base__/sound/storage-tank.ogg",
volume = 0.8
},
match_volume_to_activity = true,
apparent_volume = 1.5,
max_sounds_per_type = 3
}
dt2.circuit_wire_connection_points = circuit_connector_definitions["storage-tank"].points
dt2.circuit_connector_sprites = circuit_connector_definitions["storage-tank"].sprites
dt2.circuit_wire_max_distance = default_circuit_wire_max_distance
data:extend{dt2}
-- Technology --
local dt2T = {}
dt2T.name = "StorageTankMK1_2"
dt2T.type = "technology"
dt2T.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank2.png"
dt2T.icon_size = 32
dt2T.unit = {
count=650,
time=2,
ingredients={
{"DimensionalSample", 1}
}
}
dt2T.prerequisites = {"StorageTankMK1_1"}
dt2T.effects = {{type="nothing", effect_description={"description.DimensionalTank2"}}, {type="unlock-recipe", recipe="ModuleID2"}}
data:extend{dt2T}
--------- TANK 3 ----------
-- Entity --
dt3 = {}
dt3.type = "storage-tank"
dt3.name = "StorageTank3MK1"
dt3.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank3.png"
dt3.icon_size = 32
dt3.flags = {"placeable-player", "player-creation"}
dt3.minable = nil
dt3.max_health = 500
dt3.corpse = "medium-remnants"
dt3.collision_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt3.selection_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt3.flags = {"not-rotatable"}
dt3.order = "a"
dt3.fluid_box =
{
base_area = 100,
height = 100,
base_level = -1,
pipe_covers = pipecoverspictures(),
pipe_connections = {}
}
dt3.two_direction_only = true
dt3.window_bounding_box = {{-0.125, 0.6875}, {0.1875, 1.1875}}
dt3.pictures =
{
picture =
{
sheets =
{
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DimensionalTank3.png",
priority = "extra-high",
frames = 2,
width = 219,
height = 215,
shift = util.by_pixel(10, -3),
scale = 2
},
{
filename = "__base__/graphics/entity/storage-tank/hr-storage-tank-shadow.png",
priority = "extra-high",
frames = 2,
width = 291,
height = 153,
shift = util.by_pixel(29.75, 22.25),
scale = 2,
draw_as_shadow = true
}
}
},
fluid_background =
{
filename = "__base__/graphics/entity/storage-tank/fluid-background.png",
priority = "extra-high",
width = 32,
height = 15,
},
window_background =
{
filename = "__base__/graphics/entity/storage-tank/window-background.png",
priority = "extra-high",
width = 17,
height = 24,
scale = 3.5,
shift = {0.3,2.0}
},
flow_sprite =
{
filename = "__base__/graphics/entity/pipe/fluid-flow-low-temperature.png",
priority = "extra-high",
width = 160,
height = 20,
scale=3,
shift = {0.3,2.2}
},
gas_flow =
{
filename = "__base__/graphics/entity/pipe/steam.png",
priority = "extra-high",
line_length = 10,
width = 24,
height = 15,
frame_count = 60,
axially_symmetrical = false,
direction_count = 1,
animation_speed = 0.25,
hr_version =
{
filename = "__base__/graphics/entity/pipe/hr-steam.png",
priority = "extra-high",
line_length = 10,
width = 48,
height = 30,
frame_count = 60,
axially_symmetrical = false,
animation_speed = 0.25,
direction_count = 1,
scale = 0.5
}
}
}
dt3.flow_length_in_ticks = 360
dt3.vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }
dt3.working_sound =
{
sound =
{
filename = "__base__/sound/storage-tank.ogg",
volume = 0.8
},
match_volume_to_activity = true,
apparent_volume = 1.5,
max_sounds_per_type = 3
}
dt3.circuit_wire_connection_points = circuit_connector_definitions["storage-tank"].points
dt3.circuit_connector_sprites = circuit_connector_definitions["storage-tank"].sprites
dt3.circuit_wire_max_distance = default_circuit_wire_max_distance
data:extend{dt3}
-- Technology --
local dt3T = {}
dt3T.name = "StorageTankMK1_3"
dt3T.type = "technology"
dt3T.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank3.png"
dt3T.icon_size = 32
dt3T.unit = {
count=800,
time=2,
ingredients={
{"DimensionalSample", 1}
}
}
dt3T.prerequisites = {"StorageTankMK1_2"}
dt3T.effects = {{type="nothing", effect_description={"description.DimensionalTank3"}}, {type="unlock-recipe", recipe="ModuleID3"}}
data:extend{dt3T}
--------- TANK 4 ----------
-- Entity --
dt4 = {}
dt4.type = "storage-tank"
dt4.name = "StorageTank4MK1"
dt4.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank4.png"
dt4.icon_size = 32
dt4.flags = {"placeable-player", "player-creation"}
dt4.minable = nil
dt4.max_health = 500
dt4.corpse = "medium-remnants"
dt4.collision_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt4.selection_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt4.flags = {"not-rotatable"}
dt4.order = "a"
dt4.fluid_box =
{
base_area = 100,
height = 100,
base_level = -1,
pipe_covers = pipecoverspictures(),
pipe_connections = {}
}
dt4.two_direction_only = true
dt4.window_bounding_box = {{-0.125, 0.6875}, {0.1875, 1.1875}}
dt4.pictures =
{
picture =
{
sheets =
{
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DimensionalTank4.png",
priority = "extra-high",
frames = 2,
width = 219,
height = 215,
shift = util.by_pixel(10, -3),
scale = 2
},
{
filename = "__base__/graphics/entity/storage-tank/hr-storage-tank-shadow.png",
priority = "extra-high",
frames = 2,
width = 291,
height = 153,
shift = util.by_pixel(29.75, 22.25),
scale = 2,
draw_as_shadow = true
}
}
},
fluid_background =
{
filename = "__base__/graphics/entity/storage-tank/fluid-background.png",
priority = "extra-high",
width = 32,
height = 15,
},
window_background =
{
filename = "__base__/graphics/entity/storage-tank/window-background.png",
priority = "extra-high",
width = 17,
height = 24,
scale = 3.5,
shift = {0.3,2.0}
},
flow_sprite =
{
filename = "__base__/graphics/entity/pipe/fluid-flow-low-temperature.png",
priority = "extra-high",
width = 160,
height = 20,
scale=3,
shift = {0.3,2.2}
},
gas_flow =
{
filename = "__base__/graphics/entity/pipe/steam.png",
priority = "extra-high",
line_length = 10,
width = 24,
height = 15,
frame_count = 60,
axially_symmetrical = false,
direction_count = 1,
animation_speed = 0.25,
hr_version =
{
filename = "__base__/graphics/entity/pipe/hr-steam.png",
priority = "extra-high",
line_length = 10,
width = 48,
height = 30,
frame_count = 60,
axially_symmetrical = false,
animation_speed = 0.25,
direction_count = 1,
scale = 0.5
}
}
}
dt4.flow_length_in_ticks = 360
dt4.vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }
dt4.working_sound =
{
sound =
{
filename = "__base__/sound/storage-tank.ogg",
volume = 0.8
},
match_volume_to_activity = true,
apparent_volume = 1.5,
max_sounds_per_type = 3
}
dt4.circuit_wire_connection_points = circuit_connector_definitions["storage-tank"].points
dt4.circuit_connector_sprites = circuit_connector_definitions["storage-tank"].sprites
dt4.circuit_wire_max_distance = default_circuit_wire_max_distance
data:extend{dt4}
-- Technology --
local dt4T = {}
dt4T.name = "StorageTankMK1_4"
dt4T.type = "technology"
dt4T.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank4.png"
dt4T.icon_size = 32
dt4T.unit = {
count=1100,
time=2,
ingredients={
{"DimensionalSample", 1}
}
}
dt4T.prerequisites = {"StorageTankMK1_3"}
dt4T.effects = {{type="nothing", effect_description={"description.DimensionalTank4"}}, {type="unlock-recipe", recipe="ModuleID4"}}
data:extend{dt4T}
--------- TANK 5 ----------
-- Entity --
dt5T = {}
dt5T.type = "storage-tank"
dt5T.name = "StorageTank5MK1"
dt5T.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank5.png"
dt5T.icon_size = 32
dt5T.flags = {"placeable-player", "player-creation"}
dt5T.minable = nil
dt5T.max_health = 500
dt5T.corpse = "medium-remnants"
dt5T.collision_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt5T.selection_box = {{-5.9, -6.6}, {6.2, 5.5}}
dt5T.flags = {"not-rotatable"}
dt5T.order = "a"
dt5T.fluid_box =
{
base_area = 100,
height = 100,
base_level = -1,
pipe_covers = pipecoverspictures(),
pipe_connections = {}
}
dt5T.two_direction_only = true
dt5T.window_bounding_box = {{-0.125, 0.6875}, {0.1875, 1.1875}}
dt5T.pictures =
{
picture =
{
sheets =
{
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DimensionalTank5.png",
priority = "extra-high",
frames = 2,
width = 219,
height = 215,
shift = util.by_pixel(10, -3),
scale = 2
},
{
filename = "__base__/graphics/entity/storage-tank/hr-storage-tank-shadow.png",
priority = "extra-high",
frames = 2,
width = 291,
height = 153,
shift = util.by_pixel(29.75, 22.25),
scale = 2,
draw_as_shadow = true
}
}
},
fluid_background =
{
filename = "__base__/graphics/entity/storage-tank/fluid-background.png",
priority = "extra-high",
width = 32,
height = 15,
},
window_background =
{
filename = "__base__/graphics/entity/storage-tank/window-background.png",
priority = "extra-high",
width = 17,
height = 24,
scale = 3.5,
shift = {0.3,2.0}
},
flow_sprite =
{
filename = "__base__/graphics/entity/pipe/fluid-flow-low-temperature.png",
priority = "extra-high",
width = 160,
height = 20,
scale=3,
shift = {0.3,2.2}
},
gas_flow =
{
filename = "__base__/graphics/entity/pipe/steam.png",
priority = "extra-high",
line_length = 10,
width = 24,
height = 15,
frame_count = 60,
axially_symmetrical = false,
direction_count = 1,
animation_speed = 0.25,
hr_version =
{
filename = "__base__/graphics/entity/pipe/hr-steam.png",
priority = "extra-high",
line_length = 10,
width = 48,
height = 30,
frame_count = 60,
axially_symmetrical = false,
animation_speed = 0.25,
direction_count = 1,
scale = 0.5
}
}
}
dt5T.flow_length_in_ticks = 360
dt5T.vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }
dt5T.working_sound =
{
sound =
{
filename = "__base__/sound/storage-tank.ogg",
volume = 0.8
},
match_volume_to_activity = true,
apparent_volume = 1.5,
max_sounds_per_type = 3
}
dt5T.circuit_wire_connection_points = circuit_connector_definitions["storage-tank"].points
dt5T.circuit_connector_sprites = circuit_connector_definitions["storage-tank"].sprites
dt5T.circuit_wire_max_distance = default_circuit_wire_max_distance
data:extend{dt5T}
-- Technology --
local dt5T = {}
dt5T.name = "StorageTankMK1_5"
dt5T.type = "technology"
dt5T.icon = "__Mobile_Factory_Graphics__/graphics/icones/DimensionalTank5.png"
dt5T.icon_size = 32
dt5T.unit = {
count=1350,
time=2,
ingredients={
{"DimensionalSample", 1}
}
}
dt5T.prerequisites = {"StorageTankMK1_4"}
dt5T.effects = {{type="nothing", effect_description={"description.DimensionalTank5"}}, {type="unlock-recipe", recipe="ModuleID5"}}
data:extend{dt5T} |
arrows = {
{"throwing:arrow", "throwing:arrow_entity"},
{"throwing:arrow_fire", "throwing:arrow_fire_entity"},
{"throwing:arrow_teleport", "throwing:arrow_teleport_entity"},
{"throwing:arrow_dig", "throwing:arrow_dig_entity"},
{"throwing:arrow_build", "throwing:arrow_build_entity"}
}
local throwing_shoot_arrow = function(itemstack, player)
for _,arrow in ipairs(arrows) do
if player:get_inventory():get_stack("main", player:get_wield_index()+1):get_name() == arrow[1] then
if not minetest.setting_getbool("creative_mode") then
player:get_inventory():remove_item("main", arrow[1])
end
local playerpos = player:getpos()
local obj = minetest.env:add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, arrow[2])
local dir = player:get_look_dir()
obj:setvelocity({x=dir.x*19, y=dir.y*19, z=dir.z*19})
obj:setacceleration({x=dir.x*-3, y=-10, z=dir.z*-3})
obj:setyaw(player:get_look_yaw()+math.pi)
minetest.sound_play("throwing_sound", {pos=playerpos})
if obj:get_luaentity().player == "" then
obj:get_luaentity().player = player
end
obj:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name()
return true
end
end
return false
end
minetest.register_tool("throwing:bow_wood", {
description = "Wood Bow",
inventory_image = "throwing_bow_wood.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if throwing_shoot_arrow(itemstack, user, pointed_thing) then
if not minetest.setting_getbool("creative_mode") then
itemstack:add_wear(65535/50)
end
end
return itemstack
end,
})
minetest.register_craft({
output = 'throwing:bow_wood',
recipe = {
{'farming:string', 'default:wood', ''},
{'farming:string', '', 'default:wood'},
{'farming:string', 'default:wood', ''},
}
})
minetest.register_tool("throwing:bow_stone", {
description = "Stone Bow",
inventory_image = "throwing_bow_stone.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if throwing_shoot_arrow(item, user, pointed_thing) then
if not minetest.setting_getbool("creative_mode") then
itemstack:add_wear(65535/100)
end
end
return itemstack
end,
})
minetest.register_craft({
output = 'throwing:bow_stone',
recipe = {
{'farming:string', 'default:cobble', ''},
{'farming:string', '', 'default:cobble'},
{'farming:string', 'default:cobble', ''},
}
})
minetest.register_tool("throwing:bow_steel", {
description = "Steel Bow",
inventory_image = "throwing_bow_steel.png",
stack_max = 1,
on_use = function(itemstack, user, pointed_thing)
if throwing_shoot_arrow(item, user, pointed_thing) then
if not minetest.setting_getbool("creative_mode") then
itemstack:add_wear(65535/200)
end
end
return itemstack
end,
})
minetest.register_craft({
output = 'throwing:bow_steel',
recipe = {
{'farming:string', 'default:steel_ingot', ''},
{'farming:string', '', 'default:steel_ingot'},
{'farming:string', 'default:steel_ingot', ''},
}
})
dofile(minetest.get_modpath("throwing").."/arrow.lua")
dofile(minetest.get_modpath("throwing").."/fire_arrow.lua")
dofile(minetest.get_modpath("throwing").."/teleport_arrow.lua")
dofile(minetest.get_modpath("throwing").."/dig_arrow.lua")
dofile(minetest.get_modpath("throwing").."/build_arrow.lua")
if minetest.setting_get("log_mods") then
minetest.log("action", "throwing loaded")
end
|
-----------------------------------
-- Insurgency
-- Scythe weapon skill
-- Skill level: N/A
-- Delivers a fourfold attack. Damage varies with TP. Liberator: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Dark Knight) quest.
-- Appears to be heavily modified by attack.
-- Aligned with the Flame Gorget, Light Gorget & Shadow Gorget.
-- Aligned with the Flame Belt, Light Belt & Shadow Belt.
-- Element: None
-- Modifiers: STR:20% INT:20%
-- 100%TP 200%TP 300%TP
-- 0.50 0.75 1.00
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 4
params.ftp100 = 0.5 params.ftp200 = 0.75 params.ftp300 = 1
params.str_wsc = 0.2 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.2
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.atk100 = 1; params.atk200 = 1; params.atk300 = 1
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp200 = 3.25 params.ftp300 = 6
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
-- Apply aftermath
if damage > 0 then
tpz.aftermath.addStatusEffect(player, tp, tpz.slot.MAIN, tpz.aftermath.type.MYTHIC)
end
return tpHits, extraHits, criticalHit, damage
end
|
local buf_map = require('core.utils').keymap.buf_map
buf_map('n', '<space>ts', '<cmd>0r ~/.config/nvim/after/skeleton/python<CR>')
|
local msg
context("Selectors test", function()
local rspamd_task = require "rspamd_task"
local logger = require "rspamd_logger"
local lua_selectors = require "lua_selectors"
local test_helper = require "rspamd_test_helper"
local cfg = rspamd_config
local task
test_helper.init_url_parser()
before(function()
local res
res,task = rspamd_task.load_from_string(msg, cfg)
task:set_from_ip("198.172.22.91")
task:set_user("cool user name")
task:set_helo("hello mail")
task:set_request_header("hdr1", "value1")
task:process_message()
task:get_mempool():set_variable("int_var", 1)
task:get_mempool():set_variable("str_var", "str 1")
if not res then
assert_true(false, "failed to load message")
end
end)
local function check_selector(selector_string)
local sels = lua_selectors.parse_selector(cfg, selector_string)
local elts = lua_selectors.process_selectors(task, sels)
local res = lua_selectors.combine_selectors(task, elts, ':')
return res
end
local cases = {
["rcpts + weekend"] = {
selector = "rcpts:addr.take_n(5).lower;time('message', '!%w').in(6, 7).id('weekends')",
expect = {
"nobody@example.com:weekends",
"no-one@example.com:weekends"}},
["weekend + rcpts"] = {
selector = "time('message', '!%w').in(6, 7).id('weekends');rcpts:addr.take_n(5).lower",
expect = {
"weekends:nobody@example.com",
"weekends:no-one@example.com"}},
["id(rcpt) + rcpts + weekend"] = {
selector = "id('rcpt');rcpts:addr.take_n(5).lower;time('message', '!%w').in(6, 7).id('weekends')",
expect = {
"rcpt:nobody@example.com:weekends",
"rcpt:no-one@example.com:weekends"}},
["id(rcpt) + id(2) rcpts + weekend"] = {
selector = "id('rcpt'); id(2); rcpts:addr.take_n(5).lower; time('message', '!%w').in(6, 7).id('weekends')",
expect = {
"rcpt:2:nobody@example.com:weekends",
"rcpt:2:no-one@example.com:weekends"}},
-- There are two rcpts but only one url in the message
-- resulting table size is the size of the smallest table
["id(rcpt) + id(2) + rcpts and urls + weekend"] = {
selector = "id('rcpt'); id(2); rcpts:addr.take_n(5).lower; id('urls'); urls:get_host; time('message', '!%w').in(6, 7).id('weekends')",
expect = {
"rcpt:2:nobody@example.com:urls:example.net:weekends"}},
}
for case_name, case in pairs(cases) do
test("case " .. case_name, function()
local elts = check_selector(case.selector)
assert_not_nil(elts)
assert_rspamd_table_eq({actual = elts, expect = case.expect})
end)
end
end)
--[=========[ ******************* message ******************* ]=========]
msg = [[
Received: from ca-18-193-131.service.infuturo.it ([151.18.193.131] helo=User)
by server.chat-met-vreemden.nl with esmtpa (Exim 4.76)
(envelope-from <upwest201diana@outlook.com>)
id 1ZC1sl-0006b4-TU; Mon, 06 Jul 2015 10:36:08 +0200
From: <whoknows@nowhere.com>
To: <nobody@example.com>, <no-one@example.com>
Date: Sat, 22 Sep 2018 14:36:51 +0100 (BST)
subject: Second, lower-cased header subject
Subject: Test subject
Content-Type: multipart/alternative;
boundary="_000_6be055295eab48a5af7ad4022f33e2d0_"
--_000_6be055295eab48a5af7ad4022f33e2d0_
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64
Hello world
--_000_6be055295eab48a5af7ad4022f33e2d0_
Content-Type: text/html; charset="utf-8"
<html><body>
<a href="http://example.net">http://example.net</a>
<a href="mailto:test@example.net">mail me</a>
</html>
--_000_6be055295eab48a5af7ad4022f33e2d0_
Content-Type: application/zip; name=f.zip
Content-Disposition: attachment; size=166; filename=f.zip
Content-Transfer-Encoding: base64
UEsDBAoAAAAAAINe6kgAAAAAAAAAAAAAAAAIABwAZmFrZS5leGVVVAkAA8YaglfGGoJXdXgLAAEE
6AMAAAToAwAAUEsBAh4DCgAAAAAAg17qSAAAAAAAAAAAAAAAAAgAGAAAAAAAAAAAALSBAAAAAGZh
a2UuZXhlVVQFAAPGGoJXdXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEATgAAAEIAAAAAAA==
--_000_6be055295eab48a5af7ad4022f33e2d0_
Content-Type: application/zip; name=f.zip
Content-Disposition: attachment; size=166; filename=f2.zip
Content-Transfer-Encoding: base64
UEsDBAoAAAAAAINe6kgAAAAAAAAAAAAAAAAIABwAZmFrZS5leGVVVAkAA8YaglfGGoJXdXgLAAEE
6AMAAAToAwAAUEsBAh4DCgAAAAAAg17qSAAAAAAAAAAAAAAAAAgAGAAAAAAAAAAAALSBAAAAAGZh
a2UuZXhlVVQFAAPGGoJXdXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEATgAAAEIAAAAAAA==
]]
|
--- Test motor encoders.
local ledr = require 'led_ring'
ledr.init(50)
local pos = { 1, 1, 1 }
local feedback_encoders = function (encoder, dir, counter)
print("encoder: " .. encoder,"direction: "..dir,"counter: "..counter)
ledr.set_led(pos[encoder], 0, 0, 0)
pos[encoder] = counter % ledr.n_leds + 1
local leds = {}
for i=1, 3 do
leds[pos[i]] = leds[pos[i]] or {0, 0, 0}
leds[pos[i]][i] = 255
end
for i, color in pairs(leds) do
ledr.set_led(i, color[1], color[2], color[3])
end
ledr.update()
end
local callback1 = function (dir, counter, button)
feedback_encoders(1, dir, counter)
end
local callback2 = function (dir, counter, button)
feedback_encoders(2, dir, counter)
end
local callback3 = function (dir, counter, button)
feedback_encoders(3, dir, counter)
end
enc0 = encoder.attach(pio.GPIO39, pio.GPIO37, 0, callback1)
enc1 = encoder.attach(pio.GPIO38, pio.GPIO36, 0, callback2)
enc2 = encoder.attach(pio.GPIO34, pio.GPIO35, 0, callback3)
ledr.clear()
ledr.set_led(1, 255, 255, 255)
ledr.update() |
return {
code = "EXAMPLE_DLG_OK",
desc = "例子:单按钮提示,用户自己提供回调",
style = {
_name = 'ErrorStyleDlgOk',
btn_name = "联知道了",
},
} |
return {
["a"] = 1,
["b"] = 2,
["c"] = 3,
["d"] = "",
["e"] = "something else",
["f"] = {
["g"] = {
["off"] = 0,
["on"] = 1
}
},
["h"] = {
["i"] = "dd"
}
}
|
local _2afile_2a = "fnl/conjure/linked-list.fnl"
local _2amodule_name_2a = "conjure.linked-list"
local _2amodule_2a
do
package.loaded[_2amodule_name_2a] = {}
_2amodule_2a = package.loaded[_2amodule_name_2a]
end
local _2amodule_locals_2a
do
_2amodule_2a["aniseed/locals"] = {}
_2amodule_locals_2a = (_2amodule_2a)["aniseed/locals"]
end
local autoload = (require("conjure.aniseed.autoload")).autoload
local a = autoload("conjure.aniseed.core")
do end (_2amodule_locals_2a)["a"] = a
local function create(xs, prev)
if not a["empty?"](xs) then
local rest = a.rest(xs)
local node = {}
a.assoc(node, "val", a.first(xs))
a.assoc(node, "prev", prev)
return a.assoc(node, "next", create(rest, node))
else
return nil
end
end
_2amodule_2a["create"] = create
local function val(l)
local _2_ = l
if _2_ then
return a.get(_2_, "val")
else
return _2_
end
end
_2amodule_2a["val"] = val
local function next(l)
local _4_ = l
if _4_ then
return a.get(_4_, "next")
else
return _4_
end
end
_2amodule_2a["next"] = next
local function prev(l)
local _6_ = l
if _6_ then
return a.get(_6_, "prev")
else
return _6_
end
end
_2amodule_2a["prev"] = prev
local function first(l)
local c = l
while prev(c) do
c = prev(c)
end
return c
end
_2amodule_2a["first"] = first
local function last(l)
local c = l
while next(c) do
c = next(c)
end
return c
end
_2amodule_2a["last"] = last
local function _until(f, l)
local c = l
local r = false
local function step()
r = f(c)
return r
end
while (c and not step()) do
c = next(c)
end
if r then
return c
else
return nil
end
end
_2amodule_2a["until"] = _until
local function cycle(l)
local start = first(l)
local _end = last(l)
a.assoc(start, "prev", _end)
a.assoc(_end, "next", start)
return l
end
_2amodule_2a["cycle"] = cycle |
local first_run = not _G.bfredl
if first_run then
local status, fire = pcall(require, 'vim.dumpster_fire')
if status then
fire.dumpster_test("/tmp/mycache")
end
end
package.loaded.bfredl = nil -- force reload
_G.bfredl = require'bfredl'
_G.b = _G.bfredl -- for convenience
if first_run then
vim.cmd [[autocmd VimEnter * lua _G.bfredl.vimenter(true)]]
else
-- already dunnit, so fake it on reload
_G.bfredl.vimenter(false)
end
|
-- Event management --
event = {}
event.listeners = {
["component_added"] = function(addr, ctype)
if ctype == "filesystem" then
if fs.mount then
fs.mount(addr)
end
elseif ctype == "gpu" then
term.enableGPU(addr)
end
end,
["component_removed"] = function(addr, ctype)
if ctype == "filesystem" then
if fs.unmount then
fs.unmount(addr)
end
elseif ctype == "gpu" then
term.disableGPU(addr)
end
end
}
setmetatable(event.listeners, { __index = table })
function event.addListener(event, func)
event.listeners[event] = func
end
function event.removeListener(event)
if event.listeners[event] then
event.listeners[event] = nil
end
end
local pullSignal = computer.pullSignal
function event.pull(filter, timeout)
if timeout then
local data = {pullSignal(timeout)}
if event.listeners[data[1]] then -- Support event listeners
event.listeners[data[1]](table.unpack(data, 2, data.n))
end
if data[1] == filter then
return table.unpack(data)
elseif not filter then
return table.unpack(data)
end
return
end
while true do
local data = {pullSignal()}
if event.listeners[data[1]] then -- Support event listeners
event.listeners[data[1]](table.unpack(data, 2, data.n))
end
if data[1] == filter then
return table.unpack(data)
elseif not filter then
return table.unpack(data)
end
end
end
|
return {
"_preload.lua",
"android.lua",
"vsandroid_vcxproj.lua",
"vsandroid_sln2005.lua",
"vsandroid_vstudio.lua",
"vsandroid_androidproj.lua",
}
|
local PopupDialogScreen = require "screens/popupdialog"
local assets=
{
Asset("ANIM", "anim/cave_exit_rope.zip"),
}
local function GetVerb(inst)
return STRINGS.ACTIONS.ACTIVATE.CLIMB
end
local function onnear(inst)
inst.AnimState:PlayAnimation("down")
inst.AnimState:PushAnimation("idle_loop", true)
inst.SoundEmitter:PlaySound("dontstarve/cave/rope_down")
end
local function onfar(inst)
inst.AnimState:PlayAnimation("up")
inst.SoundEmitter:PlaySound("dontstarve/cave/rope_up")
end
local function OnActivate(inst)
SetPause(true)
local level = GetWorld().topology.level_number or 1
local function head_upwards()
SaveGameIndex:GetSaveFollowers(GetPlayer())
SaveGameIndex:SetSaveSeasonData(GetPlayer())
local function onsaved()
SetPause(false)
StartNextInstance({reset_action=RESET_ACTION.LOAD_SLOT, save_slot = SaveGameIndex:GetCurrentSaveSlot()}, true)
end
local cave_num = SaveGameIndex:GetCurrentCaveNum()
if level == 1 then
SaveGameIndex:SaveCurrent(function() SaveGameIndex:LeaveCave(onsaved) end, "ascend", cave_num)
else
-- Ascend
local level = level - 1
SaveGameIndex:SaveCurrent(function() SaveGameIndex:EnterCave(onsaved,nil, cave_num, level) end, "ascend", cave_num)
end
end
GetPlayer().HUD:Hide()
TheFrontEnd:Fade(false, 2, function()
head_upwards()
end)
end
local function fn(Sim)
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
local minimap = inst.entity:AddMiniMapEntity()
minimap:SetIcon( "cave_open2.png" )
anim:SetBank("exitrope")
anim:SetBuild("cave_exit_rope")
inst:AddComponent("playerprox")
inst.components.playerprox:SetDist(5,7)
inst.components.playerprox:SetOnPlayerFar(onfar)
inst.components.playerprox:SetOnPlayerNear(onnear)
inst:AddComponent("inspectable")
inst:AddComponent("activatable")
inst.components.activatable.OnActivate = OnActivate
inst.components.activatable.inactive = true
inst.components.activatable.getverb = GetVerb
inst.components.activatable.quickaction = true
return inst
end
return Prefab( "common/cave_exit", fn, assets)
|
--- #
--- # ADDMONEY
--- #
xAdmin.Core.RegisterCommand("addmoney", "[DarkRP] Gives the target X money", 100, function(admin, args)
if not args or not args[1] then
return
end
if not DarkRP then
return
end
if not args[2] or not tonumber(args[2]) or tonumber(args[2]) <= 0 then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provid a valid amount you want to add to the target"}, admin)
return
end
args[2] = tonumber(args[2])
local target = xAdmin.Core.GetUser(args[1], admin)
if not IsValid(target) then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provide a valid target. The following was not recognised: " .. args[1]}, admin)
return
end
xAdmin.Core.Msg({admin, " has added ", Color(0, 255, 0), DarkRP.formatMoney(args[2]), color_white, " to ", target})
target:addMoney(args[2])
end)
--- #
--- # REMOVEMONEY
--- #
xAdmin.Core.RegisterCommand("removemoney", "[DarkRP] Takes X money from the target", 100, function(admin, args)
if not args or not args[1] then
return
end
if not DarkRP then
return
end
if not args[2] or not tonumber(args[2]) or tonumber(args[2]) <= 0 then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provid a valid amount you want to add to the target"}, admin)
return
end
args[2] = tonumber(args[2])
local target = xAdmin.Core.GetUser(args[1], admin)
if not IsValid(target) then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provide a valid target. The following was not recognised: " .. args[1]}, admin)
return
end
xAdmin.Core.Msg({admin, " has taken ", Color(0, 255, 0), DarkRP.formatMoney(args[2]), color_white, " from ", target})
target:addMoney(-args[2])
end)
--- #
--- # SETMONEY
--- #
xAdmin.Core.RegisterCommand("setmoney", "[DarkRP] Sets the target's money to X", 100, function(admin, args)
if not args or not args[1] then
return
end
if not DarkRP then
return
end
if not args[2] or not tonumber(args[2]) or tonumber(args[2]) <= 0 then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provid a valid amount you want to add to the target"}, admin)
return
end
args[2] = tonumber(args[2])
local target = xAdmin.Core.GetUser(args[1], admin)
if not IsValid(target) then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provide a valid target. The following was not recognised: " .. args[1]}, admin)
return
end
xAdmin.Core.Msg({admin, " has set ", target, "'s money to ", Color(0, 255, 0), DarkRP.formatMoney(args[2])})
target:addMoney(-target:getDarkRPVar("money") + args[2]) -- Seems that DarkRP doesn't have a setMonet class?
end)
--- #
--- # SETJOB
--- #
xAdmin.Core.RegisterCommand("setjob", "[DarkRP] Sets the target's job", 100, function(admin, args)
if not args or not args[1] then
return
end
if not DarkRP then
return
end
if not args[2] then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provide a valid target"}, admin)
return
end
local target = xAdmin.Core.GetUser(args[1], admin)
local job = DarkRP.getJobByCommand(args[2])
if not job then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provide a valid job "}, admin)
return
end
if not IsValid(target) then
xAdmin.Core.Msg({xAdmin.Config.ColorLog, "[xAdmin] ", color_white, "Please provide a valid target. The following was not recognised: " .. args[1]}, admin)
return
end
xAdmin.Core.Msg({admin, " has set ", target, "'s job to ", Color(0, 255, 0), job.name})
target:changeTeam(job.team, true, true)
end)
|
-- Lighting mode as f.lux
--
-- Author: Yuhuang Hu
-- Email : duguyue100@gmail.com
-- Lighting support
local color_temp = 3400
local night_start = "19:00"
local night_end = "8:00"
local transition = hs.timer.hours(3)
local invert_at_night = false
local wf_redshift=hs.window.filter.new({VLC={focused=true},Photos={focused=true},loginwindow={visible=true,allowRoles='*'}},'wf-redshift')
local day_color_temp = 6500
-- Lighting profile
hs.redshift.start(color_temp, night_start, night_end, transition, invert_at_night, wf_redshift, day_color_temp)
-- stop lighting mode
function stop_lighting()
hs.redshift.stop()
end
-- toggle_lighting
function toggle_lighting()
hs.redshift.toggle()
end
|
----------------------------------------------------------------------------------------------------
--
-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
--
-- SPDX-License-Identifier: Apache-2.0 OR MIT
--
--
--
----------------------------------------------------------------------------------------------------
Script.ReloadScript("scripts/Utils/EntityUtils.lua")
RopeEntity =
{
Properties=
{
MultiplayerOptions = {
bNetworked = 0,
},
},
}
------------------------------------------------------------------------------------------------------
function RopeEntity:OnSpawn()
if (self.Properties.MultiplayerOptions.bNetworked == 0) then
self:SetFlags(ENTITY_FLAG_CLIENT_ONLY,0);
end
end
------------------------------------------------------------------------------------------------------
function RopeEntity:OnPhysicsBreak( vPos,nPartId,nOtherPartId )
self:ActivateOutput("Break",nPartId+1 );
end
------------------------------------------------------------------------------------------------------
function RopeEntity:Event_Remove()
self:DrawSlot(0,0);
self:DestroyPhysics();
self:ActivateOutput( "Remove", true );
end
------------------------------------------------------------------------------------------------------
function RopeEntity:Event_Hide()
self:Hide(1);
self:ActivateOutput( "Hide", true );
end
------------------------------------------------------------------------------------------------------
function RopeEntity:Event_UnHide()
self:Hide(0);
self:ActivateOutput( "UnHide", true );
end
------------------------------------------------------------------------------------------------------
function RopeEntity:Event_BreakStart( vPos,nPartId,nOtherPartId )
local RopeParams = {}
RopeParams.entity_name_1 = "#unattached";
self:SetPhysicParams(PHYSICPARAM_ROPE,RopeParams);
end
function RopeEntity:Event_BreakEnd( vPos,nPartId,nOtherPartId )
local RopeParams = {}
RopeParams.entity_name_2 = "#unattached";
self:SetPhysicParams(PHYSICPARAM_ROPE,RopeParams);
end
function RopeEntity:Event_BreakDist( sender, dist )
local RopeParams = {}
RopeParams.break_point = dist;
self:SetPhysicParams(PHYSICPARAM_ROPE,RopeParams);
end
function RopeEntity:Event_Disable()
local RopeParams = {}
RopeParams.bDisabled = 1;
self:SetPhysicParams(PHYSICPARAM_ROPE,RopeParams);
end
function RopeEntity:Event_Enable()
local RopeParams = {}
RopeParams.bDisabled = 0;
self:SetPhysicParams(PHYSICPARAM_ROPE,RopeParams);
end
RopeEntity.FlowEvents =
{
Inputs =
{
Hide = { RopeEntity.Event_Hide, "bool" },
UnHide = { RopeEntity.Event_UnHide, "bool" },
Remove = { RopeEntity.Event_Remove, "bool" },
BreakStart = { RopeEntity.Event_BreakStart, "bool" },
BreakEnd = { RopeEntity.Event_BreakEnd, "bool" },
BreakDist = { RopeEntity.Event_BreakDist, "float" },
Disable = { RopeEntity.Event_Disable, "bool" },
Enable = { RopeEntity.Event_Enable, "bool" },
},
Outputs =
{
Hide = "bool",
UnHide = "bool",
Remove = "bool",
Break = "int",
},
}
|
g_atat_house_loot_deed = {
description = "ATAT House Blueprint",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "atat_house_loot_deed", weight = 10000000}
}
}
addLootGroupTemplate("g_atat_house_loot_deed", g_atat_house_loot_deed)
|
local function anim(i)
local str = [[
animations {
id: "]] .. i .. [["
start_tile: ]] .. i .. [[
end_tile: ]] .. i .. [[
playback: PLAYBACK_NONE
fps: 30
flip_horizontal: 0
flip_vertical: 0
}]]
print(str)
end
print([[
image: "/map/siberia.png"
tile_width: 32
tile_height: 32
tile_margin: 0
tile_spacing: 0
collision: ""
material_tag: "tile"
collision_groups: "default"
extrude_borders: 1
inner_padding: 0
]])
for i = 1, 176 do
anim(i)
end |
#include "datascripts/color4.lua"
function c_UiColor(color4)
UiColor(color4.r, color4.g, color4.b, color4.a)
end
function c_UiColorFilter(color4)
UiColorFilter(color4.r, color4.g, color4.b, color4.a)
end
function c_UiTextOutline(color4, thickness)
thickness = thickness or 0.1
UiTextOutline(color4.r, color4.g, color4.b, color4.a, thickness)
end
function c_UiTextShadow(color4, distance, blur)
distance = distance or 1.0
blur = blur or 0.5
UiTextShadow(color4.r, color4.g, color4.b, color4.a, distance, blur)
end
function c_UiButtonImageBox(path, borderWidth, borderHeight, color4)
color4 = color4 or Color4.White
UiButtonImageBox(path, borderWidth, borderHeight, color4.r, color4.g, color4.b, color4.a)
end
function c_UiButtonHoverColor(color4)
UiButtonHoverColor(color4.r, color4.g, color4.b, color4.a)
end
function c_UiButtonPressColor(color4)
UiButtonPressColor(color4.r, color4.g, color4.b, color4.a)
end
function drawToggle(label, value, callback)
local enabledText = "Enabled"
local disabledText = "Disabled"
UiPush()
UiButtonImageBox("ui/common/box-outline-6.png", 6, 6)
if UiTextButton(label .. (value and enabledText or disabledText), 400, 40) then
callback(not value)
end
UiPop()
end |
local authRouter = require("app.routes.auth")
local todoRouter = require("app.routes.todo")
local errorRouter = require("app.routes.error")
return function(app)
app:use("/auth", authRouter())
app:use("/todo", todoRouter())
app:use("/error", errorRouter())
app:get("/", function(req, res, next)
local data = {
name = req.query.name or "lor",
desc = req.query.desc or 'a framework of lua based on OpenResty'
}
res:render("welcome", data)
end)
end
|
----------------------------
-- SSBase --
-- Created by Skeyler.com --
----------------------------
DeriveGamemode("base")
GM.Name = "SSBase"
GM.Author = "Skeyler Servers"
GM.Email = "info@skeyler.com"
GM.Website = "skeyler.com"
GM.TeamBased = false
GM.VIPBonusHP = false
GM.HUDShowVel = false
GM.HUDShowTimer = false
SS = {}
PLAYER_META = FindMetaTable("Player")
ENTITY_META = FindMetaTable("Entity")
TEAM_SPEC = TEAM_SPECTATOR
SS.DefaultModels = {
"models/player/group01/male_01.mdl",
"models/player/group01/male_02.mdl",
"models/player/group01/male_03.mdl",
"models/player/group01/male_04.mdl",
"models/player/group01/male_05.mdl",
"models/player/group01/male_06.mdl",
"models/player/group01/male_07.mdl",
"models/player/group01/male_08.mdl",
"models/player/group01/male_09.mdl"
}
team.SetUp(TEAM_SPEC, "Spectator", Color(150, 150, 150), false)
PLAYER_META.Alive2 = PLAYER_META.Alive2 or PLAYER_META.Alive
function PLAYER_META:Alive()
if self:Team() == TEAM_SPEC then return false end
return self:Alive2()
end
-- Atlas chat shared config.
if (atlaschat) then
-- We don't want rank icons or avatars.
atlaschat.enableAvatars = atlaschat.config.New("Enable avatars?", "avatars", false, true, true, true, true)
atlaschat.enableRankIcons = atlaschat.config.New("Enable rank icons?", "rank_icons", false, true, true, true, true)
end
function GM:CalcMainActivity( ply, velocity )
ply.CalcIdeal = ACT_MP_STAND_IDLE
ply.CalcSeqOverride = -1
if ( self:HandlePlayerNoClipping( ply, velocity ) ||
self:HandlePlayerDriving( ply ) ||
self:HandlePlayerVaulting( ply, velocity ) ||
self:HandlePlayerDucking( ply, velocity ) ||
self:HandlePlayerSwimming( ply, velocity ) ) then
else
local len2d = velocity:Length2D()
if ( len2d > 150 ) then ply.CalcIdeal = ACT_MP_RUN elseif ( len2d > 0.5 ) then ply.CalcIdeal = ACT_MP_WALK end
end
ply.m_bWasOnGround = ply:IsOnGround()
ply.m_bWasNoclipping = ( ply:GetMoveType() == MOVETYPE_NOCLIP && !ply:InVehicle() )
return ply.CalcIdeal, ply.CalcSeqOverride
end
function GM:DoAnimationEvent( ply, event, data )
if event == PLAYERANIMEVENT_ATTACK_PRIMARY then
if ply:Crouching() then
ply:AnimRestartGesture( GESTURE_SLOT_ATTACK_AND_RELOAD, ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, true )
else
ply:AnimRestartGesture( GESTURE_SLOT_ATTACK_AND_RELOAD, ACT_MP_ATTACK_STAND_PRIMARYFIRE, true )
end
return ACT_VM_PRIMARYATTACK
elseif event == PLAYERANIMEVENT_ATTACK_SECONDARY then
-- there is no gesture, so just fire off the VM event
return ACT_VM_SECONDARYATTACK
elseif event == PLAYERANIMEVENT_RELOAD then
if ply:Crouching() then
ply:AnimRestartGesture( GESTURE_SLOT_ATTACK_AND_RELOAD, ACT_MP_RELOAD_CROUCH, true )
else
ply:AnimRestartGesture( GESTURE_SLOT_ATTACK_AND_RELOAD, ACT_MP_RELOAD_STAND, true )
end
return ACT_INVALID
elseif event == PLAYERANIMEVENT_CANCEL_RELOAD then
ply:AnimResetGestureSlot( GESTURE_SLOT_ATTACK_AND_RELOAD )
return ACT_INVALID
end
return nil
end |
local effect = {}
effect.name = "Color waves"
effect.wait = 1/20
effect.params = {
text="Ciao", -- text to write
fg={r=1, g=1, b=0}, -- text color color
bg={r=0, g=0, b=0}, -- background color
}
effect.update = function(gen, params)
for j = 0, ny, 1
do
t = zmatrix[0][j]
for i = 0, nx-1, 1
do
zmatrix[i][j] = zmatrix[i+1][j]
end
zmatrix[nx-1][j] = t
end
end
effect.init = function(params)
for i = 0, nx, 1 do
for j = 0, ny, 1 do
zmatrix[i][j]=params.bg
-- zmatrix[2][2]={r=1, g=1, b=1}
plotstring8x8(params.text,1,1,params.fg,params.bg)
end
end
end
table.insert(effects, effect)
|
-- @Author:pandayu
-- @Version:1.0
-- @DateTime:2018-09-09
-- @Project:pandaCardServer CardGame
-- @Contact: QQ:815099602
local accMgr = require "manager.accMgr"
local roleMgr = require "manager.roleMgr"
local global = require "game.global"
local config = require "game.config"
local geturl = require "include.geturl"
local md5 = ngx.md5
local task_config = require "game.template.task"
local cjson = require "cjson"
local _M = function(role,data)
if not data.uid or not data.verify or type(data.verify) ~= "string" then return 2 end
if data.uid == "gm" then
if data.verify ~= md5(global.gm_password) then return 201 end
return 0
end
if not accMgr:is_login(data.uid) then return 200 end
if not accMgr:check_verify(data.uid,data.verify) then return 201 end
local role,bcreate = roleMgr:load_role(data.uid)
if not role then return 202 end
if config.acc_address then
local cid = role:get_cid()
--ngx.log(ngx.ERR,"cid:",cid)
local ok,res = geturl(config.acc_address,{
type = "acc",
cid = cid,
id = config.server_id
},ngx.HTTP_GET)
--ngx.log(ngx.ERR,"res:",res)
local ok,getdata = pcall(cjson.decode,res)
if ok and type(getdata) == 'table' then
--ngx.log(ngx.ERR,"getdata.status:",getdata.status)
if getdata.status >0 then return res end
else
ngx.log(ngx.ERR,"res:",res)
return 203
end
end
local bc = 0
local rdata = nil
local name = ""
if bcreate then
bc = 1
role:update()
role.extend:calc_offline()
rdata = role:get_client_data()
else
role.soldiers:conscripts(1011,1)
role.army:go_battle(1011,1)
--name = role.random_name()
end
if role.tasklist then role.tasklist:trigger(task_config.trigger_type.login,1) end
if role.both then role.both:check_refresh_list() end
return 0,{
id = role.id,
bcreate = bc,
data = rdata,
name = name,
}
end
return _M
|
-- Copyright (c) 2019 Redfern, Trevor <trevorredfern@gmail.com>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
return function(source, dest, overwrite)
for k, v in pairs(source) do
if overwrite or not dest[k] then
dest[k] = v
end
end
end
|
--[[-------------------------------------------------------------------------
Access
The access flags work by adding or removing a char to a player's string.
When we need to check a player's access we look for that access flag (char)
in that string and if we find it, they have that access.
If we don't they don't.
What access flag covers what is essentially up to you, but I have put my
standards into the sh_config for reference.
---------------------------------------------------------------------------]]
-- Access flags as used by commands
-- Please only add values
-- Changing the current values might break the gamemode
rp.cfg["Access Flags"] = {}
rp.cfg["Access Flags"]["*"] = "owner"
rp.cfg["Access Flags"]["b"] = "everyone"
rp.cfg["Access Flags"]["z"] = "superadmin"
rp.cfg["Access Flags"]["d"] = "developer"
rp.cfg["Access Flags"]["a"] = "admin"
rp.cfg["Access Flags"]["m"] = "moderator"
rp.cfg["Access Flags"]["v"] = "Vehicles"
rp.cfg["Access Flags"]["w"] = "Weapons"
rp.cfg["Access Flags"]["y"] = "Advert"
rp.cfg["Access Flags"]["p"] = "President"
rp.cfg["Access Flags"]["x"] = "F.B.I."
rp.cfg["Access Flags"]["s"] = "S.W.A.T."
rp.cfg["Access Flags"]["o"] = "Police Officer"
rp.cfg["Access Flags"]["l"] = "Paramedic"
rp.cfg["Access Flags"]["f"] = "Fireman"
rp.cfg["Access Flags"]["k"] = "Dispatch"
rp.cfg["Access Flags"]["c"] = "Chef"
rp.cfg["Access Flags"]["h"] = "Doctor"
rp.cfg["Access Flags"]["g"] = "Gun Dealer"
rp.cfg["Access Flags"]["n"] = "Mechanic"
rp.cfg["Normal Access"] = "b"
local pMeta = FindMetaTable("Player")
-- Give a player access
function pMeta:GiveAccess(access)
self:SetAccess(self:GetAccess() .. access)
end
-- Revoke a player's access
function pMeta:RevokeAccess(access)
self:SetAccess(string.gsub(self:GetAccess(), access, ""))
end
-- Make a player go on duty
function pMeta:GoOnDuty(rank)
self:SetNotSolid(true)
self:GodEnable()
self:StripWeapons()
self:StripAmmo()
self:Give("weapon_physgun")
self:SetRenderMode(RENDERMODE_NONE)
self:SetWeaponColor(Vector(0, 1, 0))
for _, v in pairs(self:GetWeapons()) do
v:SetRenderMode(RENDERMODE_NONE)
v:SetColor(Color(0, 255, 0, 0))
end
self:SetAccess(rank.access)
self:SetOnDuty(true)
ServerLog("ADMIN", self:Nick() .. " (" .. self:SteamID() .. ") is now on duty")
end
-- Make a player go off duty
function pMeta:GoOffDuty()
self:SetNotSolid(false)
self:GodDisable()
self:StripWeapon("weapon_physgun")
self:SetRenderMode(RENDERMODE_NORMAL)
for _, v in pairs(self:GetWeapons()) do
v:SetRenderMode(RENDERMODE_NORMAL)
end
self:SetAccess(rp.cfg["Default Access"])
self:SetOnDuty(false)
self:Spawn()
ServerLog("ADMIN", self:Nick() .. " (" .. self:SteamID() .. ") is now off duty")
end
-- Make admins go off duty when they disconnect
hook.Add("PlayerDisconnected", "Go off duty when disconnecting", function(ply)
if ply:GetOnDuty() then
ply:GoOffDuty()
end
end) |
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
util.AddNetworkString("starfall_custom_prop")
function ENT:Initialize()
self.BaseClass.Initialize(self)
self:PhysicsInitMultiConvex(self.Mesh)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:EnableCustomCollisions(true)
self:DrawShadow(false)
end
|
local _={}
_[130]={}
_[129]={}
_[128]={}
_[127]={}
_[126]={}
_[125]={}
_[124]={}
_[123]={}
_[122]={}
_[121]={}
_[120]={text="c",tags=_[130]}
_[119]={text="b",tags=_[129]}
_[118]={text="a",tags=_[128]}
_[117]={}
_[116]={text="ab",tags=_[127]}
_[115]={text="aa",tags=_[117]}
_[114]={text="ab"}
_[113]={text="aa"}
_[112]={}
_[111]={text="c",tags=_[126]}
_[110]={text="b",tags=_[125]}
_[109]={text="a",tags=_[112]}
_[108]={}
_[107]={text="c",tags=_[108]}
_[106]={}
_[105]={}
_[104]={text="ab",tags=_[105]}
_[103]={text="aa",tags=_[124]}
_[102]={}
_[101]={text="c",tags=_[102]}
_[100]={}
_[99]={}
_[98]={text="b",tags=_[99]}
_[97]={text="a",tags=_[123]}
_[96]={}
_[95]={text="c",tags=_[96]}
_[94]={}
_[93]={text="ab",tags=_[94]}
_[92]={text="aa",tags=_[122]}
_[91]={}
_[90]={text="c",tags=_[91]}
_[89]={}
_[88]={text="b",tags=_[89]}
_[87]={text="a",tags=_[121]}
_[86]={_[120]}
_[85]={_[119]}
_[84]={_[118]}
_[83]={text="-> aa",tags=_[117]}
_[82]={_[116]}
_[81]={_[115]}
_[80]={text="-> aa",tags=_[112]}
_[79]={_[114]}
_[78]={_[113]}
_[77]={text="-> a",tags=_[112]}
_[76]={_[111]}
_[75]={_[110]}
_[74]={_[109]}
_[73]={text="-> c",tags=_[108]}
_[72]={_[107]}
_[71]={text="autoflush",tags=_[106]}
_[70]={text="-> ab",tags=_[105]}
_[69]={_[104]}
_[68]={_[103]}
_[67]={text="-> c",tags=_[102]}
_[66]={_[101]}
_[65]={text="autoflush",tags=_[100]}
_[64]={text="-> b",tags=_[99]}
_[63]={_[98]}
_[62]={_[97]}
_[61]={text="-> c",tags=_[96]}
_[60]={_[95]}
_[59]={text="-> ab",tags=_[94]}
_[58]={_[93]}
_[57]={_[92]}
_[56]={text="-> c",tags=_[91]}
_[55]={_[90]}
_[54]={text="-> b",tags=_[89]}
_[53]={_[88]}
_[52]={_[87]}
_[51]={_[84],_[85],_[86]}
_[50]={_[83]}
_[49]={_[81],_[82]}
_[48]={_[80]}
_[47]={_[78],_[79]}
_[46]={_[77]}
_[45]={_[74],_[75],_[76]}
_[44]={_[73]}
_[43]={_[72]}
_[42]={_[71]}
_[41]={_[70]}
_[40]={_[68],_[69]}
_[39]={_[67]}
_[38]={_[66]}
_[37]={_[65]}
_[36]={_[64]}
_[35]={_[62],_[63]}
_[34]={_[61]}
_[33]={_[60]}
_[32]={_[59]}
_[31]={_[57],_[58]}
_[30]={_[56]}
_[29]={_[55]}
_[28]={_[54]}
_[27]={_[52],_[53]}
_[26]={"error","invalid choice; in event flush at test/tests/resume from paragraph with nested choice.ans:76"}
_[25]={"choice",_[51]}
_[24]={"text",_[50]}
_[23]={"choice",_[49]}
_[22]={"text",_[48]}
_[21]={"choice",_[47]}
_[20]={"text",_[46]}
_[19]={"choice",_[45]}
_[18]={"text",_[44]}
_[17]={"choice",_[43]}
_[16]={"text",_[42]}
_[15]={"text",_[41]}
_[14]={"choice",_[40]}
_[13]={"text",_[39]}
_[12]={"choice",_[38]}
_[11]={"text",_[37]}
_[10]={"text",_[36]}
_[9]={"choice",_[35]}
_[8]={"text",_[34]}
_[7]={"choice",_[33]}
_[6]={"text",_[32]}
_[5]={"choice",_[31]}
_[4]={"text",_[30]}
_[3]={"choice",_[29]}
_[2]={"text",_[28]}
_[1]={"choice",_[27]}
_[0]={_[1],_[2],_[3],_[4],_[5],_[6],_[7],_[8],_[9],_[10],_[11],_[12],_[13],_[14],_[15],_[16],_[17],_[18],_[19],_[20],_[21],_[22],_[23],_[24],_[25],_[26]}
_[113].tags=_[112]
_[114].tags=_[112]
return _[0]
--[[
{ "choice", { { {
tags = {},
text = "a"
} }, { {
tags = {},
text = "b"
} } } }
{ "text", { {
tags = {},
text = "-> b"
} } }
{ "choice", { { {
tags = {},
text = "c"
} } } }
{ "text", { {
tags = {},
text = "-> c"
} } }
{ "choice", { { {
tags = {},
text = "aa"
} }, { {
tags = {},
text = "ab"
} } } }
{ "text", { {
tags = {},
text = "-> ab"
} } }
{ "choice", { { {
tags = {},
text = "c"
} } } }
{ "text", { {
tags = {},
text = "-> c"
} } }
{ "choice", { { {
tags = {},
text = "a"
} }, { {
tags = {},
text = "b"
} } } }
{ "text", { {
tags = {},
text = "-> b"
} } }
{ "text", { {
tags = {},
text = "autoflush"
} } }
{ "choice", { { {
tags = {},
text = "c"
} } } }
{ "text", { {
tags = {},
text = "-> c"
} } }
{ "choice", { { {
tags = {},
text = "aa"
} }, { {
tags = {},
text = "ab"
} } } }
{ "text", { {
tags = {},
text = "-> ab"
} } }
{ "text", { {
tags = {},
text = "autoflush"
} } }
{ "choice", { { {
tags = {},
text = "c"
} } } }
{ "text", { {
tags = {},
text = "-> c"
} } }
{ "choice", { { {
tags = {},
text = "a"
} }, { {
tags = {},
text = "b"
} }, { {
tags = {},
text = "c"
} } } }
{ "text", { {
tags = {},
text = "-> a"
} } }
{ "choice", { { {
tags = <1>{},
text = "aa"
} }, { {
tags = <table 1>,
text = "ab"
} } } }
{ "text", { {
tags = {},
text = "-> aa"
} } }
{ "choice", { { {
tags = {},
text = "aa"
} }, { {
tags = {},
text = "ab"
} } } }
{ "text", { {
tags = {},
text = "-> aa"
} } }
{ "choice", { { {
tags = {},
text = "a"
} }, { {
tags = {},
text = "b"
} }, { {
tags = {},
text = "c"
} } } }
{ "error", "invalid choice; in event flush at test/tests/resume from paragraph with nested choice.ans:76" }
]]-- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.