content stringlengths 5 1.05M |
|---|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You 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.
--
local tracer = require("skywalking.tracer")
local client = require("skywalking.client")
local Span = require('skywalking.span')
local subsystem = ngx.config.subsystem
local SkyWalkingHandler = {
PRIORITY = 100001,
VERSION = "0.1.1",
}
function SkyWalkingHandler:init_worker()
require("skywalking.util").set_randomseed()
end
function SkyWalkingHandler:access(config)
if subsystem == "stream" then
kong.log.warn("Not supportted to trace \"stream\" request yet.")
return
end
if config.sample_ratio == 100 or math.random() * 100 < config.sample_ratio then
kong.ctx.plugin.skywalking_sample = true
if not client:isInitialized() then
local metadata_buffer = ngx.shared.tracing_buffer
metadata_buffer:set('serviceName', config.service_name)
metadata_buffer:set('serviceInstanceName', config.service_instance_name)
metadata_buffer:set('includeHostInEntrySpan', config.include_host_in_entry_span)
client:startBackendTimer(config.backend_http_uri)
end
tracer:start(self:get_remote_peer(ngx.ctx.balancer_data))
end
end
function SkyWalkingHandler:get_remote_peer(balancer_data)
local peer = ''
if balancer_data then
if balancer_data.host then
peer = balancer_data.host
else
peer = balancer_data.ip
end
peer = peer .. ':' .. balancer_data.port
end
return peer
end
function SkyWalkingHandler:body_filter(config)
if ngx.arg[2] and kong.ctx.plugin.skywalking_sample then
local entrySpan = ngx.ctx.entrySpan
Span.tag(entrySpan, 'kong.node', kong.node.get_hostname())
Span.setComponentId(entrySpan, 6001)
local service = kong.router.get_service()
if service and service.id then
Span.tag(entrySpan, 'kong.service', service.id)
local route = kong.router.get_route()
if route and route.id then
Span.tag(entrySpan, "kong.route", route.id)
end
if type(service.name) == "string" then
Span.tag(entrySpan, "kong.service_name", service.name)
end
end
Span.setComponentId(ngx.ctx.exitSpan, 6001)
tracer:finish()
end
end
function SkyWalkingHandler:log(config)
tracer:prepareForReport()
end
return SkyWalkingHandler
|
-- Galexy
StormFox.SetNetworkData("GalaxyAngle",math.random(90))
hook.Add("StormFox - Sunset","StormFox.SetGalaxyAngle",function()
StormFox.SetNetworkData("GalaxyAngle",math.random(360))
end) |
--下面基础组件间的require有依赖顺序相关,闲着没事也别换顺序,要加新的往文件尾加就好
Util = CS.XLuaFramework.Util
AppConfig = CS.XLuaFramework.AppConfig
ResMgr = CS.XLuaFramework.ResourceManager.GetInstance()
NetMgr = CS.XLuaFramework.NetworkManager.GetInstance()
UIHelper = CS.XLuaFramework.UIHelper
cookiesManager = CS.XLuaFramework.CookiesManager.GetInstance()
GameObject = CS.UnityEngine.GameObject
GameConst = CS.UnityMMO.GameConst
GameVariable = CS.UnityMMO.GameVariable
SceneMgr = CS.UnityMMO.SceneMgr
TextAnchor = CS.UnityEngine.TextAnchor
-- SkillMgr = CS.UnityMMO.SkillManager
Mathf = require "Common.UnityEngine.Mathf"
Vector2 = require "Common.UnityEngine.Vector2"
Vector3 = require "Common.UnityEngine.Vector3"
Vector4 = require "Common.UnityEngine.Vector4"
Quaternion = require "Common.UnityEngine.Quaternion"
Color = require "Common.UnityEngine.Color"
Ray = require "Common.UnityEngine.Ray"
Bounds = require "Common.UnityEngine.Bounds"
RaycastHit = require "Common.UnityEngine.RaycastHit"
Touch = require "Common.UnityEngine.Touch"
LayerMask = require "Common.UnityEngine.LayerMask"
Plane = require "Common.UnityEngine.Plane"
Time = require "Common.UnityEngine.Time"
Object = require "Common.UnityEngine.Object"
require("Common/BaseClass")
require("Common.Util.util")
require("Common.Util.LuaUtil")
list = require("Common.Util.list")
require("Common.Util.event")
require("Common.Util.Timer")
UpdateManager = require "Common.UpdateManager"
require "Common.GlobalEventSystem"
require("Game.Common.Action.ActionNodeWrapper")
require("Game.Common.Action.ActionTweenFunction")
require("Game.Common.Action.Action")
require("Game.Common.Action.ActionInterval")
require("Game.Common.Action.ActionEase")
require("Game.Common.Action.ActionInstant")
require("Game.Common.Action.ActionManager")
require("Game.Common.Action.ActionCatmullRom")
-- require("Game.Common.Action.ActionExtend")
--顺序无关的
require("Common.Util.Functor")
require("Game.Common.UIGlobal")
require("Tools.CookieWrapper")
require("Game.Common.GameResPath")
|
local string = require "luv.string"
local io, type, require, math, tostring = io, type, require, math, tostring
local ipairs = ipairs
local tr = tr
local models, fields, references, forms, crypt, widgets = require "luv.db.models", require "luv.fields", require "luv.fields.references", require "luv.forms", require "luv.crypt", require "luv.fields.widgets"
local widgets = require "luv.fields.widgets"
local Exception = require "luv.exceptions".Exception
local capitalize = string.capitalize
module(...)
local MODULE = (...)
local property = models.Model.property
local GroupRight = models.Model:extend{
__tag = .....".GroupRight";
__tostring = function (self) return tostring(self.model)..": "..tostring(self.action) end;
Meta = {labels={"group right";"group rights"}};
model = fields.Text{true; min=1};
action = fields.Text{true; min=1};
description = fields.Text{max=false};
superuserRight = function (self) return self._superuserRight end;
}
GroupRight._superuserRight = GroupRight{model="any model";action="any action"}
local UserGroup = models.Model:extend{
__tag = .....".UserGroup";
__tostring = function (self) return tostring(self.title) end;
Meta = {labels={"user group";"user groups"}};
title = fields.Text{true; unique=true};
description = fields.Text{max=false};
rights = references.ManyToMany{GroupRight; relatedName="groups"};
hasRight = function (self, model, action)
local superuserRight = GroupRight:superuserRight()
for _, v in self.rights:all()() do
if (v.model == superuserRight.model and v.action == superuserRight.action)
or (v.model == model and v.action == action) then
return true
end
end
return false
end;
}
local User = models.Model:extend{
__tag = .....".User";
__tostring = function (self) return tostring(self.name) end;
_sessId = "LUV_AUTH";
sessId = property"string";
secretSalt = property"string";
Meta = {labels={"user";"users"}};
-- Fields
active = fields.Boolean{default=true; "active user"};
login = fields.Login();
name = fields.Text();
email = fields.Email();
passwordHash = fields.Text{true};
group = references.ManyToOne{UserGroup; relatedName="users"};
-- Methods
encodePassword = function (self, password, method, salt)
if not password then Exception"empty password is restricted" end
method = method or "sha1"
if not salt then
salt = tostring(crypt.hash(method, math.random(2000000000)))
salt = salt:slice(math.random(10), math.random(5, salt:utf8len()-10))
end
return method.."$"..salt.."$"..tostring(crypt.hash(method, password..salt..(self:secretSalt() or "")))
end;
comparePassword = function (self, password)
local method, salt, hash = self.passwordHash:split("$", "$")
return self:encodePassword(password, method, salt) == self.passwordHash
end;
authUser = function (self, session, loginForm)
if self._authUser then return self._authUser end
local sessId = self:sessId()
if not loginForm or "table" ~= type(loginForm) or not loginForm.isA
or not loginForm:isA(require(MODULE).forms.Login) or not loginForm:submitted() or not loginForm:valid() then
if not session[sessId] then
session[sessId] = nil
session:save()
self._authUser = nil
return nil
end
local user = self:find(session[sessId].user)
if not user then
session[sessId] = nil
session:save()
end
self._authUser = user
return user
end
local user = self:find{login=loginForm.login}
if not user or not user:comparePassword(loginForm.password) then
session[sessId] = nil
session:save()
loginForm:addError(("Invalid authorisation data."):tr())
return nil
end
session[sessId] = {user=user.pk}
session:save()
self._authUser = user
return user
end;
logout = function (self, session)
session[self:sessId()] = nil
session:save()
end;
-- Rights
hasRight = function (self, model, action)
return self.group and self.group:hasRight(model, right)
end;
hasSuperuserRight = function (self)
return self.group and self.group:hasRight(GroupRight.superuserRight.model, GroupRight.superuserRight.action)
end;
rightToCreate = function (self, model)
if "string" ~= type(model) then
model = model:label()
end
return GroupRight{model=model;action="create";description="Right to create "..model}
end;
rightToEdit = function (self, model)
if "string" ~= type(model) then
model = model:label()
end
return GroupRight{model=model;action="edit";description="Right to edit "..model}
end;
rightToDelete = function (self, model)
if "string" ~= type(model) then
model = model:label()
end
return GroupRight{model=model;action="delete";description="Right to delete "..model}
end;
canCreate = function (self, model)
local right = self:rightToCreate(model)
return self:hasRight(right.model, right.action)
end;
canEdit = function (self, model)
local right = self:rightToEdit(model)
return self:hasRight(right.model, right.action)
end;
canDelete = function (self, model)
local right = self:rightToDelete(model)
return self:hasRight(right.model, right.action)
end;
}
local Login = forms.Form:extend{
__tag = .....".Login",
Meta = {fields={"login";"password";"signIn"}};
login = User:field"login":clone();
password = fields.Password{required=true};
signIn = fields.Submit(("sign in"):tr():capitalize());
}
local _modelsAdmins
local modelsAdmins = function ()
if not _modelsAdmins then
local ModelAdmin = require"luv.contrib.admin".ModelAdmin
_modelsAdmins = {
ModelAdmin:extend{
__tag = MODULE..".GroupRightAdmin";
_model = GroupRight;
_category = "authorisation";
_smallIcon = {path="/images/icons/auth/user_accept16.png";width=16;height=16};
_bigIcon = {path="/images/icons/auth/user_accept48.png";width=48;height=48};
_displayList = {"model";"action"};
_fields = {"id";"model";"action";"description"};
};
ModelAdmin:extend{
__tag = MODULE..".UserGroupAdmin";
_model = UserGroup;
_category = "authorisation";
_smallIcon = {path="/images/icons/auth/users16.png";width=16;height=16};
_bigIcon = {path="/images/icons/auth/users48.png";width=48;width=48};
_displayList = {"title"};
_fields = {"id";"title";"description";"rights"};
};
ModelAdmin:extend{
__tag = MODULE..".UserAdmin";
_model = User;
_category = "authorisation";
_smallIcon = {path="/images/icons/auth/community_users16.png";width=16;height=16};
_bigIcon = {path="/images/icons/auth/community_users48.png";width=48;height=48};
_displayList = {"login";"name";"group"};
_form = forms.ModelForm:extend{
Meta = {model = User;fields={"id";"login";"password";"password2";"name";"group";"active"}};
id = User:field"id":clone();
login = User:field"login":clone();
name = User:field"name":clone();
password = fields.Text{minLength=6;maxLength=32;widget=widgets.PasswordInput};
password2 = fields.Text{minLength=6;maxLength=32;label="repeat password";widget=widgets.PasswordInput};
group = fields.ModelSelect(UserGroup:all():value());
active = User:field"active":clone();
isValid = function (self)
if not forms.Form.valid(self) then
return false
end
if self.password then
if self.password ~= self.password2 then
self:addError(("Entered passwords don't match."):tr())
return false
end
end
return true
end;
};
initModel = function (self, model, form)
model.id = form.id
model.login = form.login
model.name = form.name
model.group = form.group
model.active = form.active
if form.password then
model.passwordHash = model:encodePassword(form.password)
end
end;
};
}
end
return _modelsAdmins
end
return {
models = {
GroupRight = GroupRight;
UserGroup = UserGroup;
User = User;
};
forms = {
Login = Login;
};
modelsAdmins = modelsAdmins;
}
|
--------------------------------------------------------------------------------
-- pk-core.lua: dsl-fsm exports profile
-- This file is a part of le-dsl-fsm project
-- Copyright (c) LogicEditor <info@logiceditor.com>
-- Copyright (c) le-dsl-fsm authors
-- See file `COPYRIGHT` for the license.
--------------------------------------------------------------------------------
local tset = import 'lua-nucleo/table-utils.lua' { 'tset' }
--------------------------------------------------------------------------------
local PROFILE = { }
--------------------------------------------------------------------------------
PROFILE.skip = setmetatable(tset
{
}, {
__index = function(t, k)
-- Excluding files outside of pk-core/ and inside pk-core/code
local v = (not k:match("^dsl%-fsm/"))
or k:match("^dsl%-fsm/code/")
t[k] = v
return v
end;
})
--------------------------------------------------------------------------------
return PROFILE
|
local T, C, L, G = unpack(select(2, ...))
if not (C.plugins.enable and C.plugins.raidcd) then return end
------------------------------------------------------------
-- Raid Cooldown
-- Author: Allez
------------------------------------------------------------
local raidcd = {
["max"] = 10, -- max number of displayed bars.
-- bars
["barwidth"] = 200, -- set bar width.
["iconsize"] = 23, -- set icons height.
["statusbarheight"] = 3, -- set status bar height. (if set to 'auto', to status bar height will be equal to icon size)
}
local RAID_COOLDOWNS = {
-- Priest
-- Discipline
[33206] = 4.0, -- Pain Suppression
[62618] = 3.0, -- Power World: Barrier
-- Holy
[47788] = 4.0, -- Guardian Spirit
[64843] = 3.0, -- Divine Hymn
[64901] = 6.0, -- Symbol of Hope
-- Shadow
[15286] = 3.0, -- Vampiric Embrace
-- [47585] = 2.0, -- Dispersion
------------------------------------------------------------
-- Druid
[20484] = 10.0, -- Rebirth
-- Balance
[29166] = 3.0, -- Innervate
-- Guardian
[61336] = 2.0, -- Survival Instincts
-- Restoration
[740] = 3.0, -- Tranquility
[102342] = 1.5, -- Ironbark
------------------------------------------------------------
-- Monk
[122278] = 2.0, -- Dampen Harm
-- Brewmaster
[115176] = 5.0, -- Zen Meditation
[120954] = 7.0, -- Fortifying Brew (Brewmaster)
-- Mistweaver
[115310] = 3.0, -- Revival
[116849] = 3.0, -- Life Cocoon
[198664] = 3.0, -- Invoke Chi-Ji, the Red Crane
-- Windwalker
------------------------------------------------------------
-- Shaman
-- Elemental
-- Enhancement
-- [120668] = 300, -- Stormlash Totem
-- Restoration
[98008] = 3.0, -- Spirit Link Totem
[108280] = 3.0, -- Healing Tide Totem
[157153] = 0.5, -- Cloudburst Totem
[198838] = 1.0, -- Earthen Shield Totem
[207399] = 5.0, -- Ancestral Protection Totem
[108271] = 1.5, -- Astral Shift
[108281] = 2.0, -- Ancestral Guidance
[114050] = 3.0, -- Ascendance
------------------------------------------------------------
-- Warlock
[20707] = 10, -- Soulstone
------------------------------------------------------------
-- Paladin
-- Holy
[31821] = 3, -- Aura Mastery
-- Protection
[633] = 10, -- Lay on Hands
[642] = 5, -- Divine Shield
-- Warrior
-- Arms / Fury
[97462] = 3, -- Commanding Shout
-- Protection
[871] = 4, -- Shield Wall
------------------------------------------------------------
-- removed spells
-- [10060] = 120, -- Power Infusion
-- [115213] = 180, -- Avert Harm
-- [16190] = 180, -- Mana Tide Totem
}
local COMBAT_EVENTS = {
SPELL_RESSURECT = true,
SPELL_CAST_SUCCESS = true,
SPELL_ARUA_APPLIED = true,
}
local ZONE_TYPES = {
none = false, -- when outside an instance
pvp = false, -- when in a battleground
arena = true, -- when in an arena
party = true, -- when in a 5-man instance
raid = true, -- when in a raid instance
-- nil when in an unknown kind of instance, eg. in a scenario
}
local filter = COMBATLOG_OBJECT_AFFILIATION_RAID + COMBATLOG_OBJECT_AFFILIATION_PARTY + COMBATLOG_OBJECT_AFFILIATION_MINE
local band = bit.band
local format = string.format
local floor = math.floor
local bars = {}
local fontName, fontSize, fontStyle = C.media.pixelfont, 10, "THINOUTLINE, MONOCHROME"
local frame = CreateFrame("Frame", "RaidCD", UIParent)
frame:SetPoint("LEFT", UIParent, "LEFT", 40, 200)
frame:SetSize(raidcd.barwidth, raidcd.iconsize)
frame:SetTemplate("Transparent")
local text = frame:CreateFontString(nil, "OVERLAY")
text:SetPoint("CENTER")
text:SetJustifyH("CENTER")
text:SetFont(fontName, fontSize, fontStyle)
text:SetText("RaidCD")
frame:SetFrameLevel(10)
frame:Hide()
-- convert seconds to day/hour/minute
local function FormatTime(s)
local minute = 60
if (s >= minute) then
return format("%dm", ceil(s / minute))
elseif (s >= (minute / 12)) then
return format("%ds", s)
else
return format("%.1fs", s)
end
end
-- update bars positions.
local UpdatePositions = function()
for i = 1, #bars do
bars[i]:ClearAllPoints()
if i == 1 then
bars[i]:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 0, 0)
else
bars[i]:SetPoint("TOPLEFT", bars[i - 1], "BOTTOMLEFT", 0, -7)
end
bars[i].id = i
if (i <= raidcd.max) then
bars[i]:Show()
else
bars[i]:Hide()
end
end
end
-- stop cooldown bar.
local StopTimer = function(bar)
bar:SetScript("OnUpdate", nil)
bar:Hide()
table.remove(bars, bar.id)
UpdatePositions()
end
-- update status bar.
local OnUpdate = function(self, elapsed)
local curTime = GetTime()
if self.endTime < curTime then
StopTimer(self)
return
end
self.statusbar:SetValue(100 - (curTime - self.startTime) / (self.endTime - self.startTime) * 100)
self.right:SetText(FormatTime(self.endTime - curTime))
end
-- display tooltip.
local OnEnter = function(self)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:AddDoubleLine(self.spell, self.right:GetText())
GameTooltip:SetClampedToScreen(true)
GameTooltip:Show()
end
-- hide tooltip.
local OnLeave = function(self)
GameTooltip:Hide()
end
-- send a chat message.
local OnMouseDown = function(self, button)
if button == "LeftButton" then
if IsInRaid() then
chat = "RAID"
elseif IsInGroup() then
chat = "PARTY"
else
chat = "SAY"
end
SendChatMessage(format("Cooldown: %s - %s (%s remaining)!", self.caster, self.spell, self.right:GetText()), chat)
elseif button == "RightButton" then
StopTimer(self)
end
end
-- create cooldown bar
local function CreateBar()
local bar = CreateFrame("Frame", nil, UIParent)
bar:SetSize(frame:GetSize())
bar:SetFrameStrata("LOW")
local button = CreateFrame("Button", nil, bar)
button:SetPoint("BOTTOMRIGHT", bar, "BOTTOMLEFT", -7, 0)
button:SetSize(raidcd.iconsize, raidcd.iconsize)
button:SetBorder("Default")
local icon = button:CreateTexture(nil, "ARTWORK")
icon:SetAllPoints(button)
icon:SetTexCoord(.08,.92,.08,.92)
local statusbar = CreateFrame("StatusBar", nil, bar)
statusbar:SetPoint("BOTTOMLEFT", button, "BOTTOMRIGHT", 7, 0)
statusbar:SetStatusBarTexture(C.media.normTex)
statusbar:SetMinMaxValues(0, 100)
statusbar:SetFrameLevel(bar:GetFrameLevel() - 1)
statusbar:SetBorder("Default")
if (raidcd.statusbarheight == 'auto') then
statusbar:SetSize(bar:GetSize())
else
statusbar:SetSize(raidcd.barwidth, raidcd.statusbarheight)
end
local left = bar:CreateFontString(nil, "OVERLAY")
left:SetPoint("LEFT", statusbar, 3, 12)
left:SetJustifyH("LEFT")
left:SetFont(fontName, fontSize, fontStyle)
local right = bar:CreateFontString(nil, "OVERLAY")
right:SetPoint("RIGHT", statusbar, -2, 12)
right:SetJustifyH("RIGHT")
right:SetFont(fontName, fontSize, fontStyle)
bar.button = button
bar.icon = icon
bar.statusbar = statusbar
bar.left = left
bar.right = right
return bar
end
-- start a new cooldown bar
local function StartTimer(sourceName, spellID)
local name, rank, icon = GetSpellInfo(spellID)
for k, v in pairs(bars) do
if (v.caster == sourceName and v.spell == name) then
return
end
end
local bar = CreateBar()
local now = GetTime()
local cooldown = RAID_COOLDOWNS[spellID] * 60
bar.caster = sourceName
bar.spell = name
bar.startTime = now
bar.endTime = now + cooldown
bar.left:SetText(sourceName)
bar.right:SetText(FormatTime(cooldown))
if (icon) then
bar.icon:SetTexture(icon)
end
local color = RAID_CLASS_COLORS[select(2, UnitClass(sourceName))]
bar.statusbar:SetStatusBarColor(color.r, color.g, color.b)
bar:EnableMouse(true)
bar:SetScript("OnUpdate", OnUpdate)
bar:SetScript("OnEnter", OnEnter)
bar:SetScript("OnLeave", OnLeave)
bar:SetScript("OnMouseDown", OnMouseDown)
table.insert(bars, bar)
table.sort(bars, function(a, b)
if (a.endTime == b.endTime) then
return a.spell < b.spell
end
return a.endTime < b.endTime
end)
UpdatePositions()
end
-- function to process combat log events.
local function ProcessCombatLog(self, timestamp, combatEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...)
if COMBAT_EVENTS[combatEvent] then
local spellID, spellName, spellSchool = ...
local inInstance, instanceType = IsInInstance()
if (RAID_COOLDOWNS[spellID] and ZONE_TYPES[instanceType]) then
StartTimer(sourceName, spellID)
end
end
end
-- function to handle events.
local function OnEvent(self, event, ...)
if (event == "COMBAT_LOG_EVENT_UNFILTERED") then
ProcessCombatLog(self, ...)
elseif (event == "ZONE_CHANGED_NEW_AREA") then
local inInstance, instanceType = IsInInstance()
if (instanceType == "arena") then
for k, v in pairs(bars) do
StopTimer(v)
end
end
end
end
local f = CreateFrame("Frame")
f:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
f:RegisterEvent("ZONE_CHANGED_NEW_AREA")
f:SetScript("OnEvent", OnEvent)
-- Test Mode
SLASH_RAIDCD1 = "/raidcd"
SlashCmdList["RAIDCD"] = function(msg)
local max = math.random(5, 20)
local i = 0
for spellID, cooldown in pairs(RAID_COOLDOWNS) do
StartTimer(T.myName, spellID)
if (i > max) then
break
end
i = i + 1
end
end |
-- Autogenerated from KST: please remove this line if doing any edits by hand!
local luaunit = require("luaunit")
require("switch_integers")
TestSwitchIntegers = {}
function TestSwitchIntegers:test_switch_integers()
local r = SwitchIntegers:from_file("src/switch_integers.bin")
luaunit.assertEquals(#r.opcodes, 4)
luaunit.assertEquals(r.opcodes[1].code, 1)
luaunit.assertEquals(r.opcodes[1].body, 7)
luaunit.assertEquals(r.opcodes[2].code, 2)
luaunit.assertEquals(r.opcodes[2].body, 16448)
luaunit.assertEquals(r.opcodes[3].code, 4)
luaunit.assertEquals(r.opcodes[3].body, 4919)
luaunit.assertEquals(r.opcodes[4].code, 8)
luaunit.assertEquals(r.opcodes[4].body, 4919)
end
|
assert(GENE.ADENINE == 0)
assert(GENE.CYTOSINE == 1)
assert(GENE.GUANINE == 2)
assert(GENE.THYMINE == 3)
assert(ATOM.ELECTRON == 0)
assert(ATOM.PROTON == 1)
assert(ATOM.NEUTRON == 2)
assert(FRUIT.APPLE == 0)
assert(FRUIT.BANANA == 1)
assert(FRUIT.PEACH == 2)
assert(FRUIT.PLUM == 3)
assert(_G["`poncho`"]["`glucho`"] == 0)
assert(_G["`poncho`"]["`becho`"] == 1)
|
return function ()
local Brightness = Import("ga.corebyte.Sugar.Helpers.Brightness")
RemoteCommand:Register("brightness", function (Parameters)
Brightness.Set(Parameters.Amount)
end)
end |
local AS = unpack(AddOnSkins)
if not AS:CheckAddOn('Hekili') then return end
function AS:Hekili()
for Display, _ in ipairs( Hekili.DB.profile.displays ) do
for Buttons = 1, Hekili.DB.profile.displays[Display].numIcons do
local Button = _G['Hekili_D'..Display..'_B'..Buttons]
AS:CreateBackdrop(Button)
AS:SkinTexture(Button.Texture)
end
end
end
AS:RegisterSkin('Hekili', AS.Hekili)
|
local cjson_decode = require("cjson").decode
local cjson_encode = require("cjson").encode
local _M = {}
local function json_decode(json)
if json then
local status, res = pcall(cjson_decode, json)
if status then
return res
end
end
end
local function json_encode(table)
if table then
local status, res = pcall(cjson_encode, table)
if status then
return res
end
end
end
function _M.encode(status, content, headers)
return json_encode({
status = status,
content = content,
headers = headers
})
end
function _M.decode(str)
return json_decode(str)
end
return _M
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You 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.
--
local error = error
local ipairs = ipairs
local require = require
local etcd = require("app.core.etcd")
local log = require("app.core.log")
local tab_nkeys = require("table.nkeys")
local str = require("app.utils.str_utils")
local core_table = require("app.core.table")
local time = require("app.core.time")
local timer = require("app.core.timer")
local json = require("app.core.json")
local router
local _M = {}
local route_timer
local route_watch_timer
local etcd_prefix = "routes/"
local etcd_watch_opts = {
timeout = 60,
prev_kv = true
}
local function create_key(prefix)
return str.md5(str.trim(prefix))
end
_M.create_key = create_key
-- 构造路由前缀
local function get_etcd_key(key)
return str.join_str("", etcd_prefix, key)
end
-- 路由配置是否存在
local function is_exsit_by_key(key)
local etcd_key = get_etcd_key(key)
local res, err = etcd.get(etcd_key)
return not err and res.body.kvs and tab_nkeys(res.body.kvs) > 0
end
-- 查询所有路由配置,返回 list
local function query_list()
local resp, err = etcd.readdir(etcd_prefix)
if err ~= nil then
log.error("failed to load routes: ", err)
return nil, err
end
local routes = {}
if resp.body.kvs and tab_nkeys(resp.body.kvs) > 0 then
for _, kv in ipairs(resp.body.kvs) do
core_table.insert(routes, kv.value)
end
end
return routes, nil
end
_M.query_list = query_list
local function query_enable_routers()
local list, err = query_list()
if not list or tab_nkeys(list) < 1 then
return nil, err
end
local routes = {}
for _, route in ipairs(list) do
if route.status == 1 then
core_table.insert(routes, route)
end
end
return routes, nil
end
_M.query_enable_routers = query_enable_routers
local function watch_routes(ctx)
log.info("watch routes start_revision: ", ctx.start_revision)
local opts = {
timeout = etcd_watch_opts.timeout,
prev_kv = etcd_watch_opts.prev_kv,
start_revision = ctx.start_revision
}
local chunk_fun, err = etcd.watchdir(etcd_prefix, opts)
if not chunk_fun then
log.error("routes chunk err: ", err)
return
end
while true do
local chunk
chunk, err = chunk_fun()
if not chunk then
if err ~= "timeout" then
log.error("routes chunk err: ", err)
end
break
end
log.info("routes watch result: ", json.delay_encode(chunk.result))
ctx.start_revision = chunk.result.header.revision + 1
if chunk.result.events then
for _, event in ipairs(chunk.result.events) do
log.error("routes event: ", event.type, " - ", json.delay_encode(event))
router.refresh()
end
end
end
end
-- 删除路由
local function remove_route(key)
log.notice("remove route: ", key)
local etcd_key = get_etcd_key(key)
local _, err = etcd.delete(etcd_key)
if err then
log.error("remove route error: ", err)
return false, err
end
return true, nil
end
_M.remove_route = remove_route
-- 根据 url 前缀删除路由配置
local function remove_route_by_prefix(prefix)
log.notice("remove route by prefix: ", prefix)
local key = create_key(prefix)
return remove_route(key)
end
_M.remove_route_by_prefix = remove_route_by_prefix
-- 保存路由配置
local function save_route(route)
local key = create_key(route.prefix)
route.key = key
local etcd_key = get_etcd_key(key)
route.time = time.now() * 1000
local _, err = etcd.set(etcd_key, route)
if err then
log.error("save route error: ", err)
return false, err
end
return true, nil
end
_M.save_route = save_route
function _M.update_route(route)
local key = route.key
local newKey = create_key(route.prefix)
-- 检查路由是否已经存在
if str.is_blank(key) and is_exsit_by_key(newKey) then
return false, "路由[" .. route.prefix .. "]配置已存在"
end
log.info("save route", json.delay_encode(route))
local _, err = save_route(route)
-- 如果路由前缀修改了,需要删除之前的路由配置
if err == nil and key and key ~= newKey then
_, err = remove_route(key)
end
if err then
log.error("update route error: ", err)
return false, err
end
return true, nil
end
local function _init()
router.refresh()
route_watch_timer:recursion()
end
-- 初始化
function _M.init()
router = require("app.router")
route_timer = timer.new("route.timer", _init, {delay = 0})
route_watch_timer = timer.new("route.watch.timer", watch_routes, {delay = 0})
local ok, err = route_timer:once()
if not ok then
error("failed to load routes: " .. err)
end
end
return _M
|
--Function to get nuget
fs.makeDir("lib")
if fs.exists("lib/genlib") == false then
shell.run("wget","https://raw.githubusercontent.com/augustclear/ComputerCraft/main/Utilities/genlib.lua","lib/genlib")
end
local gl = require("lib.genlib")
--Calls to get files
gl.nuget("https://raw.githubusercontent.com/augustclear/ComputerCraft/main/Utilities/genlib.lua","lib/genlib")
gl.nuget("https://raw.githubusercontent.com/augustclear/ComputerCraft/main/Turtles/turtlelib.lua","lib/turtlelib")
gl.nuget("https://raw.githubusercontent.com/augustclear/ComputerCraft/main/Turtles/turtlebg.lua","turtlebg")
gl.nuget("https://raw.githubusercontent.com/augustclear/ComputerCraft/main/Turtles/turtlefg.lua","turtlefg")
gl.nuget("https://raw.githubusercontent.com/augustclear/ComputerCraft/main/Turtles/setconfig.lua","setconfig")
term.clear()
term.setCursorPos(1,1)
--Setup Commands
local w = require("lib.turtlelib")
w.open()
local id = shell.openTab("turtlebg")
multishell.setTitle(id,"GPS")
--Files to run
if turtle.getFuelLevel() < 1000 then
print("I need food!!!!")
turtle.refuel(1000)
else
id = shell.openTab("turtlefg")
multishell.setTitle(id,"COMMAND")
end |
local vim = vim
local common = require('galaxyline.common')
local colors = require('galaxyline.colors')
local uv = vim.loop
local M = {}
M.section = {}
M.section.left = {}
M.section.right = {}
M.section.short_line_left = {}
M.section.short_line_right = {}
M.short_line_list = {}
local provider_group = {}
local async_load
-- why async load providers? because found the diagnostic providers
-- take a lot of startup time
async_load = uv.new_async(vim.schedule_wrap(function ()
local vcs = require('galaxyline.provider_vcs')
local fileinfo = require('galaxyline.provider_fileinfo')
local buffer = require('galaxyline.provider_buffer')
local extension = require('galaxyline.provider_extensions')
local whitespace =require('galaxyline.provider_whitespace')
provider_group = {
BufferIcon = buffer.get_buffer_type_icon,
BufferNumber = buffer.get_buffer_number,
FileTypeName = buffer.get_buffer_filetype,
GitBranch = vcs.get_git_branch,
DiffAdd = vcs.diff_add,
DiffModified = vcs.diff_modified,
DiffRemove = vcs.diff_remove,
LineColumn = fileinfo.line_column,
FileFormat = fileinfo.get_file_format,
FileEncode = fileinfo.get_file_encode,
FileSize = fileinfo.get_file_size,
FileIcon = fileinfo.get_file_icon,
FileName = fileinfo.get_current_file_name,
SFileName = fileinfo.filename_in_special_buffer,
LinePercent = fileinfo.current_line_percent,
ScrollBar = extension.scrollbar_instance,
VistaPlugin = extension.vista_nearest,
WhiteSpace = whitespace.get_item,
}
local diagnostic = require('galaxyline.provider_diagnostic')
provider_group.DiagnosticError = diagnostic.get_diagnostic_error
provider_group.DiagnosticWarn = diagnostic.get_diagnostic_warn
provider_group.DiagnosticHint = diagnostic.get_diagnostic_hint
provider_group.DiagnosticInfo = diagnostic.get_diagnostic_info
async_load:close()
end))
do
if next(provider_group) == nil then
async_load:send()
end
end
local function check_component_exists(component_name)
for _,pos_value in pairs(M.section) do
for _,v in pairs(pos_value) do
if v[component_name] ~= nil then
return true,v[component_name]
end
end
end
return false,nil
end
local function exec_provider(icon,cmd)
local output = cmd()
if output == nil then return '' end
if string.len(icon) ~= 0 and string.len(output) ~= 0 and output then
return icon .. output
end
return output
end
-- component decorator
-- that will output the component result with icon
-- component provider and icon can be string or table
function M.component_decorator(component_name)
-- if section doesn't have component just return
local ok,component_info = check_component_exists(component_name)
if not ok then
print(string.format('Does not found this component: %s',component_name))
return
end
local provider = component_info.provider or ''
local icon = component_info.icon or ''
local _switch = {
['string'] = function()
if provider_group[provider] == nil then
if next(provider_group) ~= nil then
print(string.format('The provider of %s does not exist in default provider group',component_name))
return ''
end
return ''
end
return exec_provider(icon,provider_group[provider])
end,
['function'] = function()
return exec_provider(icon,provider)
end,
['table'] = function()
local output = ''
for _,v in pairs(provider) do
if type(v) ~= 'string' and type(v) ~= 'function' then
print(string.format('Wrong provider type in %s',component_name))
return ''
end
if type(v) == 'string' then
if type(provider_group[v]) ~= 'function' then
if next(provider_group) ~= nil then
print(string.format('Does not found the provider in default provider provider in %s',component_name))
return ''
end
return ''
end
output = output .. exec_provider(icon,provider_group[v])
end
if type(v) == 'function' then
output = output .. exec_provider(icon,v)
end
end
return output
end
}
local _switch_metatable = {
__index = function(_type)
return print(string.format('Type %s of provider does not support',_type))
end
}
setmetatable(_switch,_switch_metatable)
return _switch[type(provider)]()
end
local function generate_section(component_name)
local line = ''
line = line .. '%#'..'Galaxy'.. component_name..'#'
line = line .. [[%{luaeval('require("galaxyline").component_decorator')]]..'("'..component_name..'")}'
return line
end
local function generate_separator_section(component_name,separator)
local separator_name = component_name .. 'Separator'
local line = ''
line = line .. '%#'..separator_name..'#' .. separator
return line
end
local function section_complete_with_option(component,component_info,position)
local tmp_line = ''
-- get the component condition and dynamicswitch
local condition = component_info.condition or nil
local separator = component_info.separator or ''
if condition ~= nil then
if condition() then
tmp_line = tmp_line .. generate_section(component)
if string.len(separator) ~= 0 then
if position == 'left' then
tmp_line = tmp_line .. generate_separator_section(component,separator)
else
tmp_line = generate_separator_section(component,separator) .. tmp_line
end
end
end
return tmp_line
end
tmp_line = tmp_line .. generate_section(component)
if string.len(separator) ~= 0 then
if position == 'left' then
tmp_line = tmp_line .. generate_separator_section(component,separator)
else
tmp_line = generate_separator_section(component,separator) .. tmp_line
end
end
return tmp_line
end
local function load_section(section_area,pos)
local section = ''
if section_area ~= nil then
for _,component in pairs(section_area) do
for component_name,component_info in pairs(component) do
local ls = section_complete_with_option(component_name,component_info,pos)
section = section .. ls
end
end
end
return section
end
local function register_user_events()
local user_events = {}
for _,section in pairs(M.section) do
for _,component_info in pairs(section) do
local event = component_info['event'] or ''
if string.len(event) > 0 then
table.insert(user_events,event)
end
end
end
if next(user_events) == nil then return end
common.nvim_create_augroups(user_events)
end
local async_combin
local short_line = ''
async_combin = uv.new_async(vim.schedule_wrap(function()
local left_section = load_section(M.section.left,'left')
local right_section = load_section(M.section.right,'right')
local short_left_section = load_section(M.section.short_line_left,'left')
local short_right_section = load_section(M.section.short_line_right,'right')
local line = ''
if not common.has_value(M.short_line_list,vim.bo.filetype) then
line = left_section .. '%=' .. right_section
else
short_line = short_left_section .. '%=' .. short_right_section
line = short_line
end
vim.wo.statusline = line
end))
function M.load_galaxyline()
async_combin:send()
colors.init_theme(M.section)
register_user_events()
end
function M.inactive_galaxyline()
vim.wo.statusline = short_line
end
function M.init_colorscheme()
colors.init_theme(M.section)
end
function M.disable_galaxyline()
vim.wo.statusline = ''
vim.api.nvim_command('augroup galaxyline')
vim.api.nvim_command('autocmd!')
vim.api.nvim_command('augroup END!')
end
function M.galaxyline_augroup()
local events = { 'ColorScheme', 'FileType','BufWinEnter','BufReadPost','BufWritePost',
'BufEnter','WinEnter','FileChangedShellPost','VimResized','TermOpen'}
vim.api.nvim_command('augroup galaxyline')
vim.api.nvim_command('autocmd!')
for _, def in ipairs(events) do
local command = string.format('autocmd %s * lua require("galaxyline").load_galaxyline()',def)
vim.api.nvim_command(command)
end
vim.api.nvim_command('autocmd WinLeave * lua require("galaxyline").inactive_galaxyline()')
vim.api.nvim_command('augroup END')
end
return M
|
function description()
return "Find text in the current webview"
end
function run()
if #arguments > 0 then
local windex = focused_window_index()
local query = table.concat(arguments, " ")
find(windex, focused_webview_index(windex), query)
end
return false -- continue to display command
end
|
local Buffer
local function reload_buffer()
package.loaded["spec.03-plugins.09-galileo.ngx"] = nil
package.loaded["kong.plugins.galileo.buffer"] = nil
_G.ngx = require "spec.03-plugins.09-galileo.ngx"
Buffer = require "kong.plugins.galileo.buffer"
end
describe("ALF Buffer", function()
local conf, _ngx
before_each(function()
reload_buffer()
conf = {
server_addr = "10.10.10.10",
service_token = "abcd",
environment = "test",
log_bodies = false,
retry_count = 0,
connection_timeout = 30,
flush_timeout = 2,
queue_size = 1000,
host = "collector.galileo.mashape.com",
port = 443,
}
_ngx = {
status = 200,
var = {
scheme = "https",
host = "example.com",
request_uri = "/request/path",
request_length = 32,
remote_addr = "127.0.0.1",
server_addr = "10.10.10.10",
},
ctx = {
KONG_PROXY_LATENCY = 3,
KONG_WAITING_TIME = 15,
KONG_RECEIVE_TIME = 25,
},
}
end)
it("sanity", function()
local buf = assert(Buffer.new(conf))
assert.equal(0, #buf.sending_queue)
assert.equal(0, #buf.cur_alf.entries)
assert.equal(conf.flush_timeout * 1000, buf.flush_timeout)
assert.equal(conf.connection_timeout * 1000, buf.connection_timeout)
end)
it("sane defaults", function()
local buf = assert(Buffer.new {
service_token = "abcd",
server_addr = "",
host = "",
port = 80
})
assert.equal(0, buf.retry_count)
assert.equal(30000, buf.connection_timeout)
assert.equal(2000, buf.flush_timeout)
assert.equal(1000, buf.queue_size)
assert.False(buf.log_bodies)
end)
it("returns error on invalid conf", function()
local buf, err = Buffer.new()
assert.equal("arg #1 (conf) must be a table", err)
assert.is_nil(buf)
buf, err = Buffer.new {}
assert.equal("server_addr must be a string", err)
assert.is_nil(buf)
buf, err = Buffer.new {server_addr = "10.10.10.10"}
assert.equal("service_token must be a string", err)
assert.is_nil(buf)
buf, err = Buffer.new {
service_token = "abcd",
server_addr = "10.10.10.10",
environment = false
}
assert.equal("environment must be a string", err)
assert.is_nil(buf)
end)
describe("add_entry()", function()
it("adds an entry to the underlying ALF serializer", function()
local buf = assert(Buffer.new(conf))
assert.equal(0, #buf.cur_alf.entries)
for i = 1, 10 do
assert(buf:add_entry(_ngx, nil, nil))
assert.equal(i, #buf.cur_alf.entries)
end
end)
it("calls flush() if the number of entries reaches 'queue_size'", function()
local buf = assert(Buffer.new(conf))
local s_flush = spy.on(buf, "flush")
assert.equal(0, #buf.cur_alf.entries)
for i = 1, conf.queue_size - 1 do
assert(buf:add_entry(_ngx, nil, nil))
end
assert.equal(conf.queue_size - 1, #buf.cur_alf.entries)
assert(buf:add_entry(_ngx, nil, nil))
assert.spy(s_flush).was_called(1)
end)
it("refreshes last_t on each call", function()
local buf = assert(Buffer.new(conf))
local last_t = buf.last_t
assert(buf:add_entry(_ngx, nil, nil))
assert.is_number(buf.last_t)
assert.not_equal(last_t, buf.last_t)
end)
end)
describe("flush()", function()
it("JSON encode the current ALF and add it to sending_queue", function()
local buf = assert(Buffer.new(conf))
local send = stub(buf, "send")
assert.equal(0, #buf.cur_alf.entries)
for i = 1, 20 do
assert(buf:add_entry(_ngx, nil, nil))
end
assert(buf:flush())
assert.stub(send).was_called(1)
assert.equal(0, #buf.cur_alf.entries) -- flushed
assert.equal(1, #buf.sending_queue)
assert.True(buf.sending_queue_size > 0)
for i = 1, 20 do
assert(buf:add_entry(_ngx, nil, nil))
end
assert(buf:flush())
assert.stub(send).was_called(2)
assert.equal(0, #buf.cur_alf.entries) -- flushed
assert.equal(2, #buf.sending_queue)
end)
it("discards ALFs when we have too much data in 'sending_queue' already",function()
conf.log_bodies = true
local body_10mb = string.rep(".", 10 * 2^20)
local buf = assert(Buffer.new(conf))
assert.has_error(function()
for i = 1, 210 do -- exceeding our 200MB limit
assert(buf:add_entry(_ngx, body_10mb))
local ok, err = buf:flush() -- growing the sending_queue, as if it's stuck
if not ok then
error(err) -- assert() seems to not work with assert.has_error
end
end
end, "buffer full")
end)
end)
describe("send()", function()
it("returns if the 'sending_queue' is empty", function()
local buf = assert(Buffer.new(conf))
local ok, err = buf:send()
assert.equal("empty queue", err)
assert.is_nil(ok)
end)
it("pops the oldest batch in the 'sending_queue'", function()
conf.log_bodies = true
local buf = assert(Buffer.new(conf))
assert(buf:add_entry(_ngx, "body1"))
assert(buf:flush()) -- calling send()
assert.equal(0, #buf.sending_queue) -- poped
end)
end)
end)
|
return {'meranti','merbau','mercantiel','mercantilisme','mercantilistisch','mercator','mercatorprojectie','merceriseren','merchandise','merchandiser','merchandising','merci','mercurochroom','merel','meren','merendeel','merendeels','merengebied','merengue','merg','mergbeen','mergel','mergelaarde','mergelachtig','mergelen','mergelgroeve','mergelgrot','mergelkalk','mergelput','mergelsteen','mergelwinning','mergpijp','meridiaan','meridiaancirkel','meridionaal','merinos','merinosschaap','merinoswol','meristeem','merite','merites','meritocratie','meritocratisch','merk','merkafhankelijk','merkartikel','merkbaar','merkbekendheid','merkel','merkelijk','merken','merkenaanbod','merkenbeleid','merkenbureau','merkendorp','merkengemachtigde','merkenportefeuille','merkenrecht','merkentrouw','merkenvoorkeur','merkenwet','merker','merkgaren','merkgebonden','merkhouder','merkidentiteit','merkinbreuk','merkinkt','merkje','merkkledij','merkkleding','merklap','merkletter','merkloos','merknaam','merkproduct','merkrecht','merksteen','merkteken','merktrouw','merkvast','merkvervalsing','merkvoorkeur','merkwaardig','merkwaardigerwijs','merkwaardigerwijze','merkwaardigheid','merrie','merriepaard','merrieveulen','merovingisch','merseybeat','merchandiseartikel','meridiaanshoogte','meroniem','merkdealer','merkbeleving','merkimago','merkwaarde','merkbescherming','merkeigenaar','merkgebruik','merkgeneesmiddel','merkregistratie','merkstreep','merkbeleid','merkkeuze','merkbaarheid','merkmedicijn','merkstift','merkcommunicatie','merkportfolio','mergschede','merabelubaai','merchtem','mercurius','mere','merelbeeks','merelbeke','merelbekenaar','merendree','merkem','merksem','merksemmenaar','merksems','merksplas','mertens','merwijk','mercedes','mercy','meredith','merel','meriam','merian','merijn','merit','merle','merlijn','merlin','merlot','mert','mervin','mervyn','meryem','meryl','merks','merx','merkus','merkx','merkelbach','merckx','mermans','merkens','merkies','merbis','merovingers','merovingische','mercantiele','merels','mereltje','mereltjes','mergbeenderen','mergelachtige','mergelde','mergelden','mergelgroeven','mergelstenen','mergelt','mergpijpen','meridiaancirkels','meridianen','meridionale','merinosschapen','merkafhankelijke','merkartikelen','merkartikels','merkbaarder','merkbare','merkdealers','merkelijke','merkelijker','merkelijkste','merkels','merkers','merkgeneesmiddelen','merkhouders','merklappen','merkletters','merknamen','merkproducenten','merkproducten','merkrechten','merkstenen','merkt','merkte','merktekenen','merktekens','merktekentje','merktekentjes','merkten','merkwaardige','merkwaardiger','merkwaardigere','merkwaardigheden','merkwaardigs','merkwaardigst','merkwaardigste','merriepaarden','merries','merrietje','merrietjes','merrieveulens','mercantilistische','mercatores','mergbenen','mergelgrotten','meritocratische','merkbaarst','merkenbureaus','merkengemachtigden','merkloze','merkjes','merkvaste','merchandiseartikelen','merchandisers','meridiaanshoogten','meridiaanshoogtes','meroniemen','mercedessen','mercedes','mercys','meres','merediths','merels','meriams','merians','merijns','merits','merles','merlijns','merlins','merlots','merts','mervins','mervyns','meryems','meryls','merkwaarden','mergpijpje','mergpijpjes','merkmedicijnen','mergelgroeves','merkregistraties','merkstrepen','merchtemse','merksemse'} |
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
-- #######################################
-- ## Project: iLife ##
-- ## For MTA: San Andreas ##
-- ## Name: cVehicleCategoryManager.lua ##
-- ## Author: MasterM ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- ## Date: June 2015 ##
-- #######################################
cVehicleCategoryManager = inherit(cSingleton);
local lp = getLocalPlayer()
--[[
]]
-- ///////////////////////////////
-- ///// getVehicleCategory //////
-- ///// Returns: iCat //////
-- ///////////////////////////////
function cVehicleCategoryManager:getVehicleCategory(uVeh)
local iVehID = uVeh
if type(uVeh) == "userdata" and getElementType(uVeh) == "vehicle" then
iVehID = getElementModel(uVeh)
elseif type(uVeh) == "string" then
iVehID = getVehicleModelFromName(uVeh)
end
if tonumber(iVehID) then
for i,v in pairs(self.tbl_VehicleCategoryData) do
if v.veh_ids[tostring(iVehID)] then
return i
end
end
end
return false
end
-- ////////////////////////////////////
-- ///// getVehiclesFromCategory //////
-- ///// Returns: tblVehs //////
-- ////////////////////////////////////
function cVehicleCategoryManager:getVehiclesFromCategory(iID)
if self.tbl_VehicleCategoryData[iID] then
return self.tbl_VehicleCategoryData[iID].veh_ids
else
return false
end
end
-- ///////////////////////////////
-- ///// getCategoryName //////
-- ///// Returns: sName //////
-- ///////////////////////////////
function cVehicleCategoryManager:getCategoryName(iID)
if type(iID) == "userdata" then
iID = self:getVehicleCategory(iID)
end
if self.tbl_VehicleCategoryData[iID] then
return self.tbl_VehicleCategoryData[iID].name
else
return false
end
end
-- ///////////////////////////////
-- ///// getCategoryMileage //////
-- ///// Returns: iMileage //////
-- ///////////////////////////////
function cVehicleCategoryManager:getCategoryMileage(iID)
if type(iID) == "userdata" then
iID = self:getVehicleCategory(iID)
end
if self.tbl_VehicleCategoryData[iID] then
return self.tbl_VehicleCategoryData[iID].mileage
else
return false
end
end
-- ///////////////////////////////
-- ///// getCategoryTax //////
-- ///// Returns: iTax //////
-- ///////////////////////////////
function cVehicleCategoryManager:getCategoryTax(iID)
if type(iID) == "userdata" then
iID = self:getVehicleCategory(iID)
end
if self.tbl_VehicleCategoryData[iID] then
return self.tbl_VehicleCategoryData[iID].tax
else
return false
end
end
-- ///////////////////////////////
-- ///// getCategoryFuelType//////
-- ///// Returns: sFuelType //////
-- ///////////////////////////////
function cVehicleCategoryManager:getCategoryFuelType(iID)
if type(iID) == "userdata" then
iID = self:getVehicleCategory(iID)
end
if self.tbl_VehicleCategoryData[iID] then
return self.tbl_VehicleCategoryData[iID].fueltype
else
return false
end
end
-- ///////////////////////////////
-- ///// getCategoryTankSize//////
-- ///// Returns: iTankSize //////
-- ///////////////////////////////
function cVehicleCategoryManager:getCategoryTankSize(iID)
if type(iID) == "userdata" then
iID = self:getVehicleCategory(iID)
end
if self.tbl_VehicleCategoryData[iID] then
return self.tbl_VehicleCategoryData[iID].tank
else
return false
end
end
-- ///////////////////////////////
-- ///// isNoFuelVehicleCategory //////
-- ///// Returns: bool //////
-- ///////////////////////////////
function cVehicleCategoryManager:isNoFuelVehicleCategory(iID)
if type(iID) == "userdata" then
iID = self:getVehicleCategory(iID)
end
if self.tbl_VehicleCategoryData[iID] then
return self.tbl_VehicleCategoryData[iID].tank == 0 and true or false
else
return false
end
end
-- ///////////////////////////////
-- ///// onDataRecieve //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cVehicleCategoryManager:onDataRecieve(tblData)
self.tbl_VehicleCategoryData = tblData
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cVehicleCategoryManager:constructor()
-- Klassenvariablen --
self.tbl_VehicleCategoryData = {}
-- Funktionen --
self.recieveDataFunc = function(...) self:onDataRecieve(...) end
-- Events --
addEvent("cVehicleCategoryManager_OnClientRecieveData", true)
addEventHandler("cVehicleCategoryManager_OnClientRecieveData", resourceRoot, self.recieveDataFunc)
triggerServerEvent("cVehicleCategoryManager_OnClientRequestData", resourceRoot)
end
-- EVENT HANDLER --
|
local newdecoder = require 'lunajson.decoder'
local newencoder = require 'lunajson.encoder'
local sax = require 'lunajson.sax'
-- If you need multiple contexts of decoder and/or encoder,
-- you can require lunajson.decoder and/or lunajson.encoder directly.
return {
decode = newdecoder(),
encode = newencoder(),
newparser = sax.newparser,
newfileparser = sax.newfileparser,
}
|
Global( "PlayerBuffs", {} )
function PlayerBuffs:Init(anID)
self.playerID = anID
self.unitParams = {}
self.ignoreRaidBuffsID = {}
self.ignoreTargeterBuffsID = {}
self.ignorePlateBuffsID = {}
self.updateCnt = 0
self.readAllBuffPlatesEventFunc = self:GetReadAllBuffPlatesEventFunc()
self.readAllRaidEventFunc = self:GetReadAllRaidEventFunc()
self.readAllTargetEventFunc = self:GetReadAllTargetEventFunc()
self.readAllAboveHeadEventFunc = self:GetReadAllAboveHeadEventFunc()
self.delEventFunc = self:GetDelEventFunc()
self.addEventFunc = self:GetAddEventFunc()
self.changeEventFunc = self:GetChangedEventFunc()
self.base = copyTable(PlayerBase)
self.base:Init()
self:RegisterEvent(anID)
end
function PlayerBuffs:ClearLastValues()
self.updateCnt = 0
self.ignoreRaidBuffsID = {}
self.ignoreTargeterBuffsID = {}
self.ignorePlateBuffsID = {}
self.ignoreAboveHeadBuffsID = {}
end
function PlayerBuffs:SubscribeTargetGui(aLitener)
self:ClearLastValues()
self.base:SubscribeTargetGui(self.playerID, aLitener, self.readAllTargetEventFunc)
end
function PlayerBuffs:UnsubscribeTargetGui()
self.base:UnsubscribeTargetGui()
end
function PlayerBuffs:SubscribeRaidGui(aLitener)
self:ClearLastValues()
self.base:SubscribeRaidGui(self.playerID, aLitener, self.readAllRaidEventFunc)
end
function PlayerBuffs:UnsubscribeRaidGui()
self.base:UnsubscribeRaidGui()
end
function PlayerBuffs:SubscribeAboveHeadGui(aLitener)
self:ClearLastValues()
self.base:SubscribeAboveHeadGui(self.playerID, aLitener, self.readAllAboveHeadEventFunc)
end
function PlayerBuffs:UnsubscribeAboveHeadGui()
self.base:UnsubscribeAboveHeadGui()
end
function PlayerBuffs:SubscribeBuffPlateGui(aLiteners)
self:ClearLastValues()
self.base:SubscribeBuffPlateGui(self.playerID, aLiteners, self.readAllBuffPlatesEventFunc)
end
function PlayerBuffs:UnsubscribeBuffPlateGui()
self.base:UnsubscribeBuffPlateGui()
end
function PlayerBuffs:TryDestroy()
if self.base:CanDestroy() then
self:UnRegisterEvent()
return true
end
return false
end
function PlayerBuffs:UpdateValueIfNeeded()
self.updateCnt = self.updateCnt + 1
if self.updateCnt == 3000 then
self:ClearLastValues()
end
for i, buffPlate in pairs(self.base.guiBuffPlatesListeners) do
buffPlate.listenerUpdateTick(buffPlate)
end
if self.base.guiAboveHeadListener then
self.base.guiAboveHeadListener.listenerUpdateTick(self.base.guiAboveHeadListener)
end
end
function PlayerBuffs:InitIgnorePlatesBuffsList(anIndex)
if not self.ignorePlateBuffsID[anIndex] then
self.ignorePlateBuffsID[anIndex] = {}
end
end
function PlayerBuffs:CallListenerIfNeeded(aBuffID, aListener, aCondition, aRaidType, anIgnoreBuffsList)
if aListener and not anIgnoreBuffsList[aBuffID] then
local buffInfo = aBuffID and object.GetBuffInfo(aBuffID)
if buffInfo and buffInfo.name then
if aCondition:IsImportant(buffInfo) then
aListener.listenerChangeImportantBuff(buffInfo, aListener)
end
local searchResult, findedObj, cleanableBuff = aCondition:Check(buffInfo)
if searchResult then
buffInfo.cleanableBuff = cleanableBuff
if aRaidType then
if buffInfo.isPositive then
aListener.listenerChangeBuff(buffInfo, aListener, findedObj)
else
aListener.listenerChangeBuffNegative(buffInfo, aListener, findedObj)
end
else
aListener.listenerChangeBuffNegative(buffInfo, aListener, findedObj)
end
else
anIgnoreBuffsList[aBuffID] = true
end
end
end
end
function PlayerBuffs:GetReadAllEventFunc(aParams, aListener, aCondition, aRaidType, anIgnoreBuffsList)
if aListener and aCondition then
--local unitBuffs = object.GetBuffs(aParams.unitId)
local unitBuffs = object.GetBuffsWithProperties(aParams.unitId, true, true)
for i, buffID in pairs(unitBuffs) do
self:CallListenerIfNeeded(buffID, aListener, aCondition, aRaidType, anIgnoreBuffsList)
end
unitBuffs = object.GetBuffsWithProperties(aParams.unitId, false, true)
for i, buffID in pairs(unitBuffs) do
self:CallListenerIfNeeded(buffID, aListener, aCondition, aRaidType, anIgnoreBuffsList)
end
end
end
function PlayerBuffs:GetReadAllRaidEventFunc()
return function(aParams)
self:GetReadAllEventFunc(aParams, self.base.guiRaidListener, GetBuffConditionForRaid(), true, self.ignoreRaidBuffsID)
end
end
function PlayerBuffs:GetReadAllTargetEventFunc()
return function(aParams)
local profile = GetCurrentProfile()
local asRaid = profile.targeterFormSettings.separateBuffDebuff
self:GetReadAllEventFunc(aParams, self.base.guiTargetListener, GetBuffConditionForTargeter(), asRaid, self.ignoreTargeterBuffsID)
end
end
function PlayerBuffs:GetReadAllBuffPlatesEventFunc()
return function(aParams)
for i, buffPlate in pairs(self.base.guiBuffPlatesListeners) do
self:InitIgnorePlatesBuffsList(i)
self:GetReadAllEventFunc(aParams, buffPlate, GetBuffConditionForBuffPlate(i), false, self.ignorePlateBuffsID[i])
end
end
end
function PlayerBuffs:GetReadAllAboveHeadEventFunc()
return function(aParams)
--LogInfo("GetReadAllAboveHeadEventFunc ", self.playerID)
self:GetReadAllEventFunc(aParams, self.base.guiAboveHeadListener, GetBuffConditionForAboveHead(), false, self.ignoreAboveHeadBuffsID)
--LogInfo("GetReadAllAboveHeadEventFunc end")
end
end
function PlayerBuffs:GetAddEventFunc()
return function(aParams)
local profile = GetCurrentProfile()
local asRaid = profile.targeterFormSettings.separateBuffDebuff
self:CallListenerIfNeeded(aParams.buffId, self.base.guiRaidListener, GetBuffConditionForRaid(), true, self.ignoreRaidBuffsID)
self:CallListenerIfNeeded(aParams.buffId, self.base.guiTargetListener, GetBuffConditionForTargeter(), asRaid, self.ignoreTargeterBuffsID)
for i, buffPlate in pairs(self.base.guiBuffPlatesListeners) do
self:InitIgnorePlatesBuffsList(i)
self:CallListenerIfNeeded(aParams.buffId, buffPlate, GetBuffConditionForBuffPlate(i), false, self.ignorePlateBuffsID[i])
end
self:CallListenerIfNeeded(aParams.buffId, self.base.guiAboveHeadListener, GetBuffConditionForAboveHead(), false, self.ignoreAboveHeadBuffsID)
end
end
function PlayerBuffs:GetDelEventFunc()
return function(aParams)
if self.base.guiRaidListener then
self.base.guiRaidListener.listenerRemoveBuff(aParams.buffId, self.base.guiRaidListener)
self.base.guiRaidListener.listenerRemoveBuffNegative(aParams.buffId, self.base.guiRaidListener)
self.base.guiRaidListener.listenerRemoveImportantBuff(aParams.buffId, self.base.guiRaidListener)
end
local profile = GetCurrentProfile()
local asRaid = profile.targeterFormSettings.separateBuffDebuff
if self.base.guiTargetListener then
if asRaid then
self.base.guiTargetListener.listenerRemoveBuff(aParams.buffId, self.base.guiTargetListener)
end
self.base.guiTargetListener.listenerRemoveBuffNegative(aParams.buffId, self.base.guiTargetListener)
end
for i, buffPlate in pairs(self.base.guiBuffPlatesListeners) do
buffPlate.listenerRemoveBuffNegative(aParams.buffId, buffPlate)
end
if self.base.guiAboveHeadListener then
self.base.guiAboveHeadListener.listenerRemoveBuffNegative(aParams.buffId, self.base.guiAboveHeadListener)
end
end
end
function PlayerBuffs:GetChangedEventFunc()
return function(aParams)
local profile = GetCurrentProfile()
local asRaid = profile.targeterFormSettings.separateBuffDebuff
self:CallListenerIfNeeded(aParams, self.base.guiRaidListener, GetBuffConditionForRaid(), true, self.ignoreRaidBuffsID)
self:CallListenerIfNeeded(aParams, self.base.guiTargetListener, GetBuffConditionForTargeter(), asRaid, self.ignoreTargeterBuffsID)
for i, buffPlate in pairs(self.base.guiBuffPlatesListeners) do
self:InitIgnorePlatesBuffsList(i)
self:CallListenerIfNeeded(aParams, buffPlate, GetBuffConditionForBuffPlate(i), false, self.ignorePlateBuffsID[i])
end
self:CallListenerIfNeeded(aParams, self.base.guiAboveHeadListener, GetBuffConditionForAboveHead(), false, self.ignoreAboveHeadBuffsID)
end
end
function PlayerBuffs:RegisterEvent(anID)
self.unitParams.objectId = anID
common.RegisterEventHandler(self.addEventFunc, 'EVENT_OBJECT_BUFF_ADDED', self.unitParams)
common.RegisterEventHandler(self.delEventFunc, 'EVENT_OBJECT_BUFF_REMOVED', self.unitParams)
if g_debugSubsrb then
self.base:reg("buff")
self.base:reg("buff")
end
end
function PlayerBuffs:UnRegisterEvent()
common.UnRegisterEventHandler(self.addEventFunc, 'EVENT_OBJECT_BUFF_ADDED', self.unitParams)
common.UnRegisterEventHandler(self.delEventFunc, 'EVENT_OBJECT_BUFF_REMOVED', self.unitParams)
if g_debugSubsrb then
self.base:unreg("buff")
self.base:unreg("buff")
end
end |
-- Copyright 2019 Xingwang Liao <kuoruan@gmail.com>
-- Licensed to the public under the MIT License.
local dsp = require "luci.dispatcher"
local m, s, o
m = Map("frpc", "%s - %s" % { translate("Frpc"), translate("Proxy Rules") })
s = m:section(TypedSection, "rule")
s.anonymous = true
s.addremove = true
s.sortable = true
s.template = "cbi/tblsection"
s.extedit = dsp.build_url("admin/services/frpc/rules/%s")
function s.create(...)
local sid = TypedSection.create(...)
if sid then
m.uci:save("frpc")
luci.http.redirect(s.extedit % sid)
return
end
end
o = s:option(Flag, "disabled", translate("Disabled"))
o = s:option(DummyValue, "name", translate("Name"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "?"
end
o = s:option(DummyValue, "type", translate("Type"))
o.cfgvalue = function (...)
local v = Value.cfgvalue(...)
return v and v:upper() or "?"
end
o = s:option(DummyValue, "local_ip", translate("Local IP"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "?"
end
o = s:option(DummyValue, "local_port", translate("Local Port"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or "?"
end
o = s:option(DummyValue, "remote_port", translate("Remote Port"))
o.cfgvalue = function (...)
return Value.cfgvalue(...) or translate("Not set")
end
return m
|
-- Heist Carrier: 3082.3117 -4717.1191 15.2622
exports('GetHeistCarrierObject', function()
return HeistCarrier
end)
HeistCarrier = {
ipl = {
"hei_carrier",
"hei_carrier_int1",
"hei_carrier_int1_lod",
"hei_carrier_int2",
"hei_carrier_int2_lod",
"hei_carrier_int3",
"hei_carrier_int3_lod",
"hei_carrier_int4",
"hei_carrier_int4_lod",
"hei_carrier_int5",
"hei_carrier_int5_lod",
"hei_carrier_int6",
"hei_carrier_int6_lod",
"hei_carrier_lod",
"hei_carrier_slod"
},
Enable = function(state) EnableIpl(HeistCarrier.ipl, state) end
}
|
vim.cmd([[
try
"themes: catppuccin, nightfox, gruvbox, github_*, kanagawa, tokyonight, dracula, onedarkpro
colorscheme tokyonight
catch /^Vim\%((\a\+)\)\=:E185/
colorscheme default
set background=dark
endtry
]])
|
require 'nn'
require 'graph-criterion'
local GraphCriterionTest = torch.TestSuite()
local tester = torch.Tester()
local c = nn.GraphCriterion({
nn.ClassNLLCriterion(),
nn.ClassNLLCriterion(),
})
function GraphCriterionTest:with_incorrect_num_outputs()
local f = function()
local output = {torch.rand(2), torch.rand(3), torch.rand(4)}
local label = {1, 1, 1}
return c:forward(output, label)
end
tester:assertError(f)
local g = function()
local output = {torch.rand(2), torch.rand(3), torch.rand(4)}
local label = {1, 1, 1}
return c:backward(output, label)
end
tester:assertError(g)
end
function GraphCriterionTest:with_1_label()
local output = {torch.Tensor({-0.7, -0.2}), torch.Tensor({-0.6, -0.4})}
local label = 1
local loss, split_losses = c:forward(output, label)
tester:assertalmosteq(loss, 1.3, 1e-4)
tester:assertalmosteq(split_losses[1], 0.7, 1e-4)
tester:assertalmosteq(split_losses[2], 0.6, 1e-4)
local grad_output = c:backward(output, label)
tester:assertTensorEq(grad_output[1], torch.Tensor({-1, 0}), 1e-4)
tester:assertTensorEq(grad_output[2], torch.Tensor({-1, 0}), 1e-4)
end
function GraphCriterionTest:with_a_nil_criterion()
local nil_c = nn.GraphCriterion({
nn.ClassNLLCriterion(),
false
})
local output = {torch.Tensor({-0.7, -0.2}), torch.Tensor({-0.6, -0.4})}
local label = 1
local loss, split_losses = nil_c:forward(output, label)
tester:assertalmosteq(loss, 0.7, 1e-4)
tester:assertalmosteq(split_losses[1], 0.7, 1e-4)
tester:assertalmosteq(split_losses[2], 0, 1e-4)
local grad_output = nil_c:backward(output, label)
tester:assertTensorEq(grad_output[1], torch.Tensor({-1, 0}), 1e-4)
tester:assertTensorEq(grad_output[2], torch.Tensor({0, 0}), 1e-4)
end
tester:add(GraphCriterionTest)
tester:run()
|
local creator = cc.import("creator.init")
local CannonBall01AI = cc.import(".CannonBall01AI")
local ShipAI = cc.class("ShipAI", creator.ComponentBase)
function ShipAI:onLoad(target)
self._lastFire = math.random(0, 20) / 10
self._fireInterval = math.random(8, 25) / 10
self._speed = math.random(50, 300) / 10
if math.random(1, 100) % 2 == 0 then
self._speed = -self._speed
end
end
function ShipAI:update(target, dt)
local x, y = target:getPosition()
x = x + self._speed * dt
target:setPositionX(x)
if (self._speed < 0 and x < -400) or (self._speed > 0 and x > 400) then
self._speed = -self._speed
end
if self._lastFire <= 0 then
self._fireInterval = math.random(8, 25) / 10
self._lastFire = self._fireInterval
local assets = creator.getAssets()
local bullet = assets:createPrefab("resources/CannonBall01")
bullet.hittime = math.random(75, 135) / 100
bullet.hitx = x + math.random(-200, 200)
bullet.hity = y - math.random(50, 200)
bullet:addComponent(CannonBall01AI.new())
bullet:trackComponents()
bullet:setPosition(x, y)
bullet:setLocalZOrder(1000)
target:getParent():addChild(bullet)
else
self._lastFire = self._lastFire - dt
end
end
return ShipAI
|
-- This is a standalone description.
local Policy = require('apicast.policy')
local PolicyChain = require('apicast.policy_chain')
local Upstream = require('apicast.upstream')
local load_balancer = require('apicast.balancer')
local Configuration = require('apicast.policy.standalone.configuration')
local resty_env = require('resty.env')
local _M = Policy.new('standalone')
local tab_new = require('resty.core.base').new_tab
local insert = table.insert
local pairs = pairs
local assert = assert
local format = string.format
local concat = table.concat
local setmetatable = setmetatable
local function load_configuration(url)
local configuration, err = Configuration.new(url)
if configuration then
configuration, err = configuration:load()
end
return configuration, err
end
local new = _M.new
--- Initialize the Standalone APIcast policy
-- @tparam[opt] table config Policy configuration.
function _M.new(config)
local self = new(config)
self.url = (config and config.url) or resty_env.get('APICAST_CONFIGURATION')
return self
end
local empty_chain = PolicyChain.new()
-- forward all policy request methods to the policy chain
for _,phase in Policy.request_phases() do
_M[phase] = function(self, context, ...)
if context[self] then
return context[self][phase](context[self], context, ...)
end
end
end
local function build_objects(constructor, list)
if not list then return {} end
local objects = tab_new(#list, 0)
for i=1, #list do
local object = constructor(list[i])
if object.name then
objects[object.name] = object
end
objects[i] = object
end
return objects
end
local Route = { }
local function build_routes(configuration)
return build_objects(Route.new, configuration.routes)
end
local Destination = { }
do
local Destination_mt = { __index = Destination }
function Destination.new(config)
if not config then return nil end
return setmetatable({
service = config.service,
upstream = config.upstream,
http_response = config.http_response,
}, Destination_mt)
end
end
local Condition = { }
do
local Condition_mt = { __index = Condition }
local operations = {
server_port = function(self) return
ngx.var.server_name == self.value or ngx.var.server_port == self.value
end,
uri_path = function(self) return ngx.var.uri == self.value end,
http_method = function(self) return ngx.req.get_method() == self.value end,
http_host = function(self) return ngx.var.host == self.value end,
always = function(self) return self.value end,
unknown = function(self) ngx.log(ngx.ERR, 'unknown condition ', self.name); return end
}
function Condition.new(name, value)
return setmetatable({
fun = operations[name] or operations.unknown,
value = value,
name = name,
}, Condition_mt)
end
function Condition:match(context)
local res = self:fun(context)
ngx.log(ngx.DEBUG, 'condition ', self.name, ' == ', self.value, ' : ', res)
return res
end
end
local Match = { }
do
local Match_mt = { __index = Match }
function Match.new(config)
local matchers = { }
for name, value in pairs(config) do
insert(matchers, Condition.new(name, value))
end
return setmetatable(matchers, Match_mt)
end
function Match:any(context)
for i=1, #self do
if self[i]:match(context) then
return self[i]
end
end
end
function Match:all(context)
for i=1, #self do
if not self[i]:match(context) then
return false
end
end
return true
end
end
do
local Route_mt = {
__index = Route,
__tostring = function(route)
local match = tab_new(#route.conditions, 0)
for i=1, #route.conditions do
match[i] = format("%s = %s", route.conditions[i].name, route.conditions[i].value)
end
return format('%s', concat(match, ' and '))
end
}
function Route.new(config)
return setmetatable({
name = config.name,
conditions = Match.new(config.match),
destination = Destination.new(assert(config.destination, 'route is missing destination')),
routes = build_routes(config),
}, Route_mt)
end
function Route:match(context)
return self.conditions:all(context)
end
end
local Service = { }
local function build_services(configuration)
return build_objects(Service.new, configuration.internal)
end
do
local Service_mt = { __index = Service }
local null = ngx.null
local function policy_configuration(policy)
local config = policy.configuration
if config and config ~= null then
return config
end
end
local function build_policy_chain(policies)
local chain = PolicyChain.new()
for i=1, #policies do
chain:add_policy(policies[i].policy, policies[i].version, policy_configuration(policies[i]))
end
return chain
end
function Service.new(config)
return setmetatable({
name = config.name,
upstream = Upstream.new(config.upstream),
policy_chain = build_policy_chain(config.policy_chain),
}, Service_mt)
end
end
local External = { }
local function build_upstreams(configuration)
return build_objects(External.new, configuration.external)
end
do
local External_mt = { __index = External }
local UpstreamPolicy = Policy.new('Standalone Upstream Policy')
local UpstreamPolicy_new = UpstreamPolicy.new
function UpstreamPolicy.new(config)
local self = UpstreamPolicy_new(config)
self.upstream = Upstream.new(config.server)
return self
end
function UpstreamPolicy:content(context)
context[self] = self.upstream
self.upstream:call(context)
end
UpstreamPolicy.balancer = load_balancer.call
function External.new(config)
local upstream_policy = UpstreamPolicy.new(config)
local upstream = upstream_policy.upstream
local policy_chain = PolicyChain.new({ upstream_policy }):freeze()
return setmetatable({
name = config.name,
server = upstream,
load_balancer = config.load_balancer,
policy_chain = policy_chain,
retries = config.retries,
}, External_mt)
end
end
local default = {
services = build_objects(Service.new, {
{ name = 'not_found',
policy_chain = {
{ policy = 'apicast.policy.echo', configuration = { status = ngx.HTTP_NOT_FOUND } },
},
},
}),
}
function _M:load_configuration()
local url = self.url
if not url then
return nil, 'not initialized'
end
local configuration, err = load_configuration(url)
if configuration then
self.routes = build_routes(configuration)
self.services = setmetatable(build_services(configuration), { __index = default.services })
self.upstreams = build_upstreams(configuration)
ngx.log(ngx.DEBUG, 'loaded standalone configuration from: ', url, ' ', configuration)
return configuration
else
ngx.log(ngx.WARN, 'failed to load ', url, ' err: ', err)
self.routes = {}
self.services = setmetatable({}, { __index = default.services })
self.upstreams = {}
return nil, err
end
end
local function run_phase(phase, services, ...)
if not services then return end
for _, service in ipairs(services) do
ngx.log(ngx.DEBUG, 'running phase ', phase, ' on service ', service.name)
service.policy_chain[phase](service.policy_chain, ...)
end
end
function _M:init(...)
if self then -- initializing policy instance
local config, err = self:load_configuration(self)
if config then
-- TODO: we need to run this because some policies are "internal" and not being
-- found and executed by the apicast.executor :init phase.
-- However, this means some policies get .init called twice (or multiple times)
-- and need to be changed to initialize only once (like starting timers).
run_phase('init', self.services, ...)
return config
else
error(err)
return nil, err
end
end
end
function _M:init_worker(...)
run_phase('init_worker', self.services, ...)
end
local find_route, match_route
match_route = function (route, context)
ngx.log(ngx.DEBUG, 'testing route: ', route)
if route:match(context) then
ngx.log(ngx.DEBUG, 'route matched: ', route)
if route.routes then
return find_route(route.routes) or route
else
return route
end
end
end
find_route = function (routes, context)
if not routes then return end
for i=1, #routes do
local route = match_route(routes[i], context)
if route then return route end
end
end
local function find_service(self, route)
local destination = route and route.destination
if not destination then return nil, 'no destination' end
if destination.service then
return self.services[destination.service]
end
if destination.upstream then
local upstream = self.upstreams[destination.upstream]
if upstream then
return upstream
else
return nil, 'upstream not found'
end
end
return nil, 'destination not found'
end
local function not_found(self)
return assert(self.services.not_found, 'missing service: not_found')
end
function _M:dispatch(route)
if not route then
ngx.log(ngx.ERR, 'route not found')
return not_found(self)
end
local service, err = find_service(self, route)
if service then
return service
else
ngx.log(ngx.ERR, 'could not find the route destination: ', err)
return not_found(self)
end
end
local rewrite = _M.rewrite
function _M:rewrite(context)
local route = find_route(self.routes, context)
context.service = self:dispatch(route)
context[self] = assert(context.service.policy_chain or empty_chain, 'missing policy chain')
return rewrite(self, context)
end
local content = _M.content
function _M:content(context)
content(self, context)
local upstream = context.service.upstream
if upstream then
return upstream:call(context)
end
end
local balancer = _M.balancer
function _M:balancer(context)
balancer(self, context)
load_balancer:call(context)
end
return _M
|
-- vim:foldmethod=marker
local repl = require 'repl'
pcall(require, 'luarocks.loader')
require 'Test.More'
plan(8)
do -- getprompt tests {{{
is(repl:getprompt(1), '>')
is(repl:getprompt(2), '>>')
end -- }}}
do -- prompt abstract tests {{{
error_like(function()
repl:prompt(1)
end, 'You must implement the showprompt method')
error_like(function()
repl:prompt(2)
end, 'You must implement the showprompt method')
end -- }}}
do -- name tests {{{
is(repl:name(), 'REPL')
end -- }}}
do -- handleline abstract tests {{{
is(_G.testresult, nil)
error_like(function()
repl:handleline '_G.testresult = 17'
end, 'You must implement the displayresults method')
is(_G.testresult, 17)
end -- }}}
|
Railbeam = {
MULTIHIT_SCORE = 200,
beamTrail = nil,
impactSparks = nil,
health = 1,
maxHealth = 1
}
function Railbeam:new(X, Y)
s = Projectile:new(X,Y)
setmetatable(s, self)
setmetatable(self, Projectile)
self.__index = self
s.health = 2
s.maxHealth = 2
return s
end
function Railbeam:setAnimations()
--No animations to set
return
end
function Railbeam:doConfig()
self:setPersistance(true)
self.killOffScreen = false
self:loadSpriteSheet(LevelManager:getParticle("bullet-orange"), 20, 20)
self:setCollisionBox(-5,-5,32,32)
self:addAnimation("default", {1}, 0, false)
self:addAnimation("kill", {2,3,4,5}, .02, false)
self:playAnimation("default")
self.attackPower = 1.7
self.visible = false
self.massless = true
--GameState.playerBullets:add(self)
GameState.worldParticles:add(self)
self.beamTrail = Emitter:new()
for i=1, 30 do
--Create the trail sprites
local curBeam = Sprite:new(0,0)
curBeam:loadSpriteSheet(LevelManager:getParticle("railLaser"), 48, 16)
curBeam:addAnimation("default", {1,2,3,4,5,6}, .1+math.random()*.1, false)
curBeam:playAnimation("default")
curBeam.originX = curBeam.width/2
curBeam.originY = curBeam.height/2
self.beamTrail:addParticle(curBeam)
curBeam.killOffScreen = false
end
--Set fire trail parameters
self.beamTrail:setSpeed(15,20)
self.beamTrail:setGravity(10)
self.beamTrail:setRadial(true)
self.beamTrail:lockParent(self, true)
self.beamTrail:start(false, 1, .01, -1)
--self.beamTrail:stop()
GameState.emitters:add(self.beamTrail)
self.impactSparks = Emitter:new()
for i=1, 10 do
local curParticle = Sprite:new(0,0)
curParticle:loadSpriteSheet(LevelManager:getParticle("thruster"), 16, 8)
curParticle:addAnimation("default", {1,2,3,4}, .1, true)
curParticle:playAnimation("default")
curParticle.originX = curParticle.width/2
curParticle.originY = curParticle.height/2
curParticle.color = {0,184,255}
self.impactSparks:addParticle(curParticle)
end
self.impactSparks:setSpeed(100, 350)
self.impactSparks:setOffset(10)
self.impactSparks:setSize(32,32)
self.impactSparks:setGravity(400)
self.impactSparks:setRadial(true)
self.impactSparks:start(true, .5, .02, -1)
self.impactSparks:stop()
self.impactSparks:lockParent(self, false)
GameState.emitters:add(self.impactSparks)
end
function Railbeam:update()
self.beamTrail:setAngle(-self.angle * 180/math.pi, 2)
Projectile.update(self)
end
function Railbeam:collide()
self.impactSparks:setAngle(-self.angle * 180/math.pi, 30)
self.impactSparks:restart()
if self.health <= 0 then
GameState.shieldBreak:play(self.x, self.y)
GameState.score = GameState.score + self.MULTIHIT_SCORE
Projectile.kill(self)
end
--Projectile.collide(self)
end
function Railbeam:getType()
return "Railbeam"
end |
OCRP_CRAFTINGMENU = nil
function OpenCraftingMenu()
local frame = vgui.Create("OCRP_BaseMenu")
frame:SetSize(585, 400)
frame:Center()
frame:SetOCRPTitle("Crafting")
frame:MakePopup()
OCRP_CRAFTINGMENU = frame
local itemList = vgui.Create("DPanelList", frame)
itemList:EnableVerticalScrollbar(true)
itemList:SetSpacing(10)
itemList:SetNoSizing(true)
itemList:EnableHorizontal(true)
itemList:SetPadding(10)
itemList.VBar:SetEnabled(true)
frame.itemList = itemList
-- Draw outline outside actual itemList so items don't cover it
local op = frame.Paint
function frame:Paint(w,h)
op(self, w, h)
draw.RoundedBox(8, itemList:GetPos()-1, select(2, itemList:GetPos())-1, itemList:GetWide()+2, itemList:GetTall()+2, Color(39,168,216,255))
end
local opl = itemList.PerformLayout
function itemList:PerformLayout(w, h)
opl(self, w, h)
self.VBar:SetTall(self:GetTall()-10)
self.VBar:SetPos(self:GetWide()-17, 5)
end
function itemList:Paint(w,h)
draw.RoundedBox(8, 0, 0, w, h, Color(25,25,25,255))
--draw.RoundedBox(8, 1, 1, w-2, h-2, Color(25,25,25,255))
end
local title = vgui.Create("DPanel", frame)
frame.categoryName = categoryName or "Weapons and Ammo"
frame.category = category or "Wep"
function title:Paint(w,h)
draw.RoundedBox(8, 0, 0, w, h, Color(25,25,25,255))
draw.DrawText("These are the craftable items in the " .. frame.categoryName .. " category.", "Trebuchet19", 5, 5, Color(255,255,255,255))
end
function frame:LayoutInfo(item)
if frame.info and frame.info:IsValid() then frame.info:Remove() end
local info = vgui.Create("OCRP_BaseMenu")
info:SetSize(200, 400)
info:SetPos(frame:GetPos()+frame:GetWide()+20, select(2, frame:GetPos()))
info:AllowCloseButton(false)
info:MakePopup()
self.info = info
local itemNameText = GAMEMODE.OCRP_Items[item.Item].Name
if item.Amount then
itemNameText = itemNameText .. " x" .. item.Amount
end
surface.SetFont("Trebuchet19")
local namew,nameh = surface.GetTextSize(itemNameText)
local itemName = vgui.Create("DPanel", info)
itemName:SetSize(namew, nameh+5)
itemName:SetPos(info:GetWide()/2-itemName:GetWide()/2, 10)
function itemName:Paint(w,h)
draw.DrawText(itemNameText, "Trebuchet19", 0, 0, Color(39,168,216,255))
draw.RoundedBox(0, 0, nameh+2, w, 1, Color(39,168,216,255))
end
surface.SetFont("UiBold")
local skillsw,skillsh = surface.GetTextSize("Skills Required")
local skillsTotalHeight = skillsh+15
local widestSkill = skillsw
local skillsInfo = {}
for k,v in pairs(item.Skills) do
if v <= 0 then continue end
skillsTotalHeight = skillsTotalHeight + draw.GetFontHeight("UiBold") + 10
local text = "- " .. GAMEMODE.OCRP_Skills[k].Name .. " " .. tostring(v)
local newwide = surface.GetTextSize(text)
if newwide > widestSkill then
widestSkill = newwide
end
skillsInfo[text] = {}
skillsInfo[text]["color"] = CL_HasSkill(k,v) and Color(255,255,255,255) or Color(255,0,0,255)
skillsInfo[text]["wide"] = newwide
end
local skills = vgui.Create("DPanel", info)
skills:SetSize(widestSkill+10,skillsTotalHeight)
skills:SetPos(info:GetWide()/2-skills:GetWide()/2, 50)
function skills:Paint(w,h)
draw.RoundedBox(8, 0, 0, w, h, Color(35,35,35,255))
draw.DrawText("Skills Required", "UiBold", w/2-skillsw/2, 5, Color(255,255,255,255))
draw.RoundedBox(0, w/2-skillsw/2, skillsh+7, skillsw, 1, Color(255,255,255,255))
local y = skillsh+17
for k1,v1 in pairs(skillsInfo) do
draw.DrawText(k1, "UiBold", w/2-v1["wide"]/2, y, v1["color"])
y = y + draw.GetFontHeight("UiBold") + 10
end
end
surface.SetFont("UiBold")
local itemsw,itemsh = surface.GetTextSize("Items Required")
local itemsTotalHeight = itemsh+15
local widestItem = itemsw
local itemsInfo = {}
for k,v in pairs(item.Requirements) do
if v.Amount <= 0 then continue end
itemsTotalHeight = itemsTotalHeight + draw.GetFontHeight("UiBold") + 10
local text = "- " .. GAMEMODE.OCRP_Items[v.Item].Name .. " x" .. v.Amount
local newwide = surface.GetTextSize(text)
if newwide > widestItem then
widestItem = newwide
end
itemsInfo[text] = {}
itemsInfo[text]["color"] = CL_HasItem(v.Item, v.Amount) and Color(255,255,255,255) or Color(255,0,0,255)
itemsInfo[text]["wide"] = newwide
end
local items = vgui.Create("DPanel", info)
items:SetSize(widestItem+10,itemsTotalHeight)
items:SetPos(info:GetWide()/2-items:GetWide()/2, select(2, skills:GetPos())+skillsTotalHeight+20)
function items:Paint(w,h)
draw.RoundedBox(8, 0, 0, w, h, Color(35,35,35,255))
draw.DrawText("Items Required", "UiBold", w/2-itemsw/2, 5, Color(255,255,255,255))
draw.RoundedBox(0, w/2-itemsw/2, itemsh+7, itemsw, 1, Color(255,255,255,255))
local y = itemsh+17
for k,v in pairs(itemsInfo) do
draw.DrawText(k, "UiBold", w/2-v["wide"]/2, y, v["color"])
y = y + draw.GetFontHeight("UiBold") + 10
end
end
local endY = select(2, items:GetPos()) + items:GetTall() + 10
if item.HeatSource then
local needFurnace = vgui.Create("DLabel", info)
needFurnace:SetText("Furnace Required")
needFurnace:SetTextColor(Color(255,0,0,255))
needFurnace:SetFont("UiBold")
local tr = LocalPlayer():GetEyeTrace()
if tr.Entity and tr.Entity:GetClass() == "item_base" and tr.Entity:GetNWString("Class") == "item_furnace" then
if tr.Entity:GetPos():Distance(LocalPlayer():GetPos()) < 100 then
needFurnace:SetTextColor(Color(255,255,255,255))
end
end
needFurnace:SizeToContents()
needFurnace:SetPos(info:GetWide()/2-needFurnace:GetWide()/2, endY)
endY = endY + needFurnace:GetTall() + 10
end
local oldP = info.Paint
function info:Paint(w,h)
oldP(self, w, h)
local x,y = skills:GetPos()
draw.RoundedBox(8, x-1, y-1, skills:GetWide()+2, skills:GetTall()+2, Color(39,168,216,255))
local x,y = items:GetPos()
draw.RoundedBox(8, x-1, y-1, items:GetWide()+2, items:GetTall()+2, Color(39,168,216,255))
end
info:SetSize(200, endY)
end
local side = vgui.Create("DPanel")
function frame:Layout(scroll)
surface.SetFont("Trebuchet19")
local textw,texth = surface.GetTextSize("These are the craftable items in the " .. frame.categoryName .. " category.")
title:SetSize(textw+10,texth+10)
title:SetPos(frame:GetWide()/2-title:GetWide()/2, 10)
itemList:SetSize(575, self:GetTall()-10-texth-20)
itemList:SetPos(5, 5+texth+10+10)
itemList:Clear()
for _,craftTable in pairs(GAMEMODE.OCRP_Recipies) do -- Really.. The shitty english makes fixing this gamemode hard
if craftTable.Cata == frame.category then
local item = vgui.Create("DPanel")
item:SetSize(100, 140)
local name = GAMEMODE.OCRP_Items[craftTable.Item].Name
local amount = craftTable.Amount
function item:Paint(w,h)
draw.RoundedBox(8, 0, 0, w, h, Color(0,0,0,255))
draw.DrawText(name, "UiBold", w/2, 5, Color(255,255,255,255), TEXT_ALIGN_CENTER)
if amount then
draw.DrawText("x" .. amount, "UiBold", w/2, 15, Color(255,255,255,255), TEXT_ALIGN_CENTER)
end
end
function item:OnCursorEntered()
frame:LayoutInfo(craftTable)
end
function item:OnCursorExited()
if frame.info and frame.info:IsValid() then frame.info:Remove() end
end
local itemMdlPanel = vgui.Create("DModelPanel", item)
itemMdlPanel:SetSize(80, 80)
itemMdlPanel:SetPos(5, 30)
itemMdlPanel:SetModel(GAMEMODE.OCRP_Items[craftTable.Item].Model)
itemMdlPanel:SetCursor("arrow")
local itemTable = GAMEMODE.OCRP_Items[craftTable.Item]
if itemTable.Angle then
itemMdlPanel:GetEntity():SetAngles(itemTable.Angle)
end
if itemTable.Material then
itemMdlPanel:GetEntity():SetMaterial(itemTable.Material)
end
if itemTable.MdlColor then
itemMdlPanel:SetColor(itemTable.MdlColor)
end
FocusModelPanel(itemMdlPanel)
itemMdlPanel.OnCursorEntered = item.OnCursorEntered
itemMdlPanel.OnCursorExited = item.OnCursorExited
-- Can craft?
local hasSkills = true
for skill,level in pairs(craftTable.Skills) do
if level > 0 then
if not CL_HasSkill(skill, level) then
hasSkills = false
end
end
end
local hasItems = true
for _,req in pairs(craftTable.Requirements) do
if req.Amount > 0 then
if not CL_HasItem(req.Item, req.Amount) then
hasItems = false
end
end
end
local lookingAtFurnace = false
local tr = LocalPlayer():GetEyeTrace()
if tr.Entity and tr.Entity:GetClass() == "item_base" and tr.Entity:GetNWString("Class") == "item_furnace" then
if tr.Entity:GetPos():Distance(LocalPlayer():GetPos()) < 100 then
lookingAtFurnace = true
end
end
if not craftTable.HeatSource then lookingAtFurnace = true end
if hasSkills and hasItems and lookingAtFurnace then
local craft = vgui.Create("OCRP_BaseButton", item)
craft:SetSize(90, 15)
craft:SetPos(5, 115)
craft:SetText("Craft")
function craft:DoClick()
if not CL_HasRoom(craftTable.Item, craftTable.Amount or 1) then
OCRP_AddHint("Cannot craft because it would exceed your max weight or max amount for this item.")
return
end
frame:SetMouseInputEnabled(false)
side:SetMouseInputEnabled(false)
StartCrafting(_, craftTable.Time or 2)
timer.Simple(craftTable.Time or 2, function()
frame:SetMouseInputEnabled(true)
side:SetMouseInputEnabled(true)
end)
end
else
local cantCraft = vgui.Create("DLabel", item)
cantCraft:SetFont("UiBold")
cantCraft:SetTextColor(Color(255,0,0,255))
cantCraft:SetText("Can't Craft")
cantCraft:SizeToContents()
cantCraft:SetPos(item:GetWide()/2-cantCraft:GetWide()/2, 115)
end
itemList:AddItem(item)
end
end
-- Fill it with blanks to ensure everything fits and there's a visible scrollbar
-- This just makes it look better
while #itemList:GetItems() < 11 do
local filler = vgui.Create("DPanel")
filler:SetSize(100, 140)
filler.Paint = function() end
itemList:AddItem(filler)
end
itemList.VBar:SetScroll(scroll or 0)
end
frame:Layout()
side:SetSize(130, 230)
side:SetPos(frame:GetPos()-side:GetWide(), select(2, frame:GetPos())+20)
function side:Paint(w,h)
draw.RoundedBoxEx(8, 0, 0, w, h, Color(0,0,0,255), true, false, true, false)
-- Around weps btn
draw.RoundedBoxEx(8, 5, 5, w-5, 40, Color(20,20,20,255), true, false, true, false)
-- Around tables btn
draw.RoundedBoxEx(8, 5, 5+40+5, w-5, 40, Color(20,20,20,255), true, false, true, false)
-- Around barriers
draw.RoundedBoxEx(8, 5, 5+40+5+40+5, w-5, 40, Color(20,20,20,255), true, false, true, false)
-- Around misc
draw.RoundedBoxEx(8, 5, 5+40+5+40+5+40+5, w-5, 40, Color(20,20,20,255), true, false, true, false)
-- Around utils
draw.RoundedBoxEx(8, 5, 5+40+5+40+5+40+5+40+5, w-5, 40, Color(20,20,20,255), true, false, true, false)
end
local weps = vgui.Create("OCRP_BaseButton", side)
weps:SetSize(115, 30)
weps:SetPos(10, 10)
weps:SetText("Weapons and Ammo")
function weps:DoClick()
frame.categoryName = "Weapons and Ammo"
frame.category = "Wep"
frame:Layout()
end
local tables = vgui.Create("OCRP_BaseButton", side)
tables:SetSize(115, 30)
tables:SetPos(10, 10+40+5)
tables:SetText("Tables")
function tables:DoClick()
frame.categoryName = "Tables"
frame.category = "Tables"
frame:Layout()
end
local barriers = vgui.Create("OCRP_BaseButton", side)
barriers:SetSize(115, 30)
barriers:SetPos(10, 10+40+5+40+5)
barriers:SetText("Barriers")
function barriers:DoClick()
frame.categoryName = "Barriers"
frame.category = "Barriers"
frame:Layout()
end
local misc = vgui.Create("OCRP_BaseButton", side)
misc:SetSize(115, 30)
misc:SetPos(10, 10+40+5+40+5+40+5)
misc:SetText("Misc. Props")
function misc:DoClick()
frame.categoryName = "Miscellaneous Props"
frame.category = "Misc"
frame:Layout()
end
local utils = vgui.Create("OCRP_BaseButton", side)
utils:SetSize(115, 30)
utils:SetPos(10, 10+40+5+40+5+40+5+40+5)
utils:SetText("Utilities")
function utils:DoClick()
frame.categoryName = "Utilities"
frame.category = "Utilities"
frame:Layout()
end
local oldOR = frame.OnRemove
function frame:OnRemove()
oldOR(self)
if side and side:IsValid() then side:Remove() end
if self.info and self.info:IsValid() then self.info:Remove() end
end
end
net.Receive("OCRP_CraftingMenu", function(len)
OpenCraftingMenu()
--GUI_Crafting_Menu()
end)
function StartCrafting(recipe, time)
local endtime = CurTime() + time
local progress = vgui.Create("DProgress")
progress:SetSize(200, 40)
progress:Center()
progress:MakePopup()
function progress:Think()
local val = math.Clamp(1-(endtime-CurTime())/time, 0, 1)
self:SetFraction(val)
if val == 1 then
net.Start("CraftItem")
net.WriteInt(recipe, 32)
net.SendToServer()
self:Remove()
end
end
end |
local function setup ()
local annotation = require('neogen')
vim.keymap.set('n', '<leader>cn', annotation.generate, {desc = 'Generate annotation for current node'})
vim.keymap.set('n', '<leader>cnf', function () annotation.generate({type = 'func'}) end, {desc = 'Generate annotation for current function'})
vim.keymap.set('n', '<leader>cnc', function () annotation.generate({type = 'class'}) end, {desc = 'Generate annotation for current class'})
vim.keymap.set('n', '<leader>cnt', function () annotation.generate({type = 'type'}) end, {desc = 'Generate annotation for current type'})
end
return {
setup = setup
}
|
-- example HTTP POST script which demonstrates setting the
-- HTTP method, body, and adding a header
wrk.method = "POST"
wrk.body = "grant_type=&username=one&password=two&scope=&client_id=&client_secret="
wrk.headers["accept"] = "application/json"
wrk.headers["Content-Type"] = "application/x-www-form-urlencoded"
|
obstacle = {}
local angle
angleSpeed = 1.0
local canGetPoint
function obstacle:getAngle()
return angle
end
function obstacle:getCanGetPoint()
return canGetPoint
end
function obstacle:setCanGetPoint(val)
canGetPoint = val
end
function obstacle:resetAngle()
angle = 0
end
function obstacle:load()
obstacle:setCanGetPoint(true)
obstacle:resetAngle()
end
function obstacle:update(dt)
angle = angle + dt * angleSpeed * math.pi/2
angle = angle % (2*math.pi)
if (angle >= 0 and angle <= 1) then
obstacle:setCanGetPoint(true)
angleSpeed = love.math.random(850, 1520) / 1000
end
end
function obstacle:draw()
love.graphics.push()
love.graphics.translate(gw * 0.5, gh * 0.9)
love.graphics.rotate(-angle)
love.graphics.rectangle("fill", -30,0, 60, gh * 0.38)
love.graphics.pop()
end
return obstacle
|
return function()
local PureCollection = require(script.Parent.PureCollection)
local SinglePureCollection = require(script.Parent.SinglePureCollection)
local Registry = require(script.Parent.Registry)
local t = require(script.Parent.Parent.t)
local function makeEntities(registry)
for i = 1, 100 do
local entity = registry:create()
if i % 2 == 0 then
registry:add(entity, "Test1", {})
end
if i % 3 == 0 then
registry:add(entity, "Test2", {})
end
if i % 4 == 0 then
registry:add(entity, "Test3", {})
end
if i % 5 == 0 then
registry:add(entity, "Test4", {})
end
end
end
beforeEach(function(context)
local registry = Registry.new()
registry:define("Test1", t.table)
registry:define("Test2", t.table)
registry:define("Test3", t.table)
registry:define("Test4", t.table)
context.registry = registry
end)
describe("new", function()
it("should create a new PureCollection when there are multiple components", function(context)
local collection = PureCollection.new(context.registry, {
required = { "Test1" },
forbidden = { "Test2" },
})
expect(getmetatable(collection)).to.equal(PureCollection)
end)
it("should create a new SinglePureCollection when there is only one required component ", function(context)
local collection = PureCollection.new(context.registry, {
required = { "Test1" },
})
expect(getmetatable(collection)).to.equal(SinglePureCollection)
end)
end)
describe("each", function()
describe("required", function()
it("should iterate all and only the entities with at least the required components and pass their data", function(context)
local registry = context.registry
local collection = PureCollection.new(registry, {
required = { "Test1", "Test2", "Test3" }
})
local toIterate = {}
makeEntities(registry)
for _, entity in ipairs(registry._pools.Test1.dense) do
if registry:has(entity, "Test2") and registry:has(entity, "Test3") then
toIterate[entity] = true
end
end
collection:each(function(entity, test1, test2, test3)
expect(toIterate[entity]).to.equal(true)
expect(test1).to.equal(registry:get(entity, "Test1"))
expect(test2).to.equal(registry:get(entity, "Test2"))
expect(test3).to.equal(registry:get(entity, "Test3"))
toIterate[entity] = nil
return test1, test2, test3
end)
expect(next(toIterate)).to.equal(nil)
end)
it("should replace required components with ones returned by the callback", function(context)
local registry = context.registry
local collection = PureCollection.new(registry, {
required = { "Test1", "Test2" }
})
local toIterate = {}
makeEntities(registry)
collection:each(function(entity)
local newTest1 = {}
local newTest2 = {}
toIterate[entity] = { newTest1, newTest2 }
return newTest1, newTest2
end)
collection:each(function(entity, test1, test2)
expect(test1).to.equal(toIterate[entity][1])
expect(test2).to.equal(toIterate[entity][2])
end)
end)
end)
end)
end
|
--[[
Copyright 2015 Rackspace
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.
--]]
local FEATURE_UPGRADES = { name = 'upgrades', version = '1.0.0' }
local FEATURE_CONFD = { name = 'confd', version = '1.0.0' }
local FEATURE_HEALTH = { name = 'health', version = '1.0.0' }
local FEATURES = {
FEATURE_UPGRADES,
FEATURE_CONFD,
FEATURE_HEALTH
}
local function disable(name, remove)
for i, v in pairs(FEATURES) do
if v.name == name then
if remove then
table.remove(FEATURES, i)
else
v.disabled = true
end
break
end
end
end
local function get(name)
if not name then return FEATURES end
for _, v in pairs(FEATURES) do
if v.name == name then return v end
end
return
end
local function disableWithOption(option, name, remove)
if not option then return end
option = option:lower()
if option == 'disabled' or option == 'false' then
disable(name, remove)
end
end
exports.get = get
exports.disable = disable
exports.disableWithOption = disableWithOption
|
-----------------------------------------
-- ID: 5610
-- Item: hellsteak_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Health 22
-- Strength 7
-- Intelligence -3
-- Health Regen While Healing 2
-- hMP +1
-- Attack % 20 (cap 150)
-- Ranged ATT % 20 (cap 150)
-- Dragon Killer 5
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then
result = tpz.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(tpz.effect.FOOD, 0, 0, 14400, 5610)
end
function onEffectGain(target, effect)
target:addMod(tpz.mod.HP, 22)
target:addMod(tpz.mod.STR, 7)
target:addMod(tpz.mod.INT, -3)
target:addMod(tpz.mod.HPHEAL, 2)
target:addMod(tpz.mod.MPHEAL, 1)
target:addMod(tpz.mod.FOOD_ATTP, 20)
target:addMod(tpz.mod.FOOD_ATT_CAP, 150)
target:addMod(tpz.mod.FOOD_RATTP, 20)
target:addMod(tpz.mod.FOOD_RATT_CAP, 150)
target:addMod(tpz.mod.DRAGON_KILLER, 5)
end
function onEffectLose(target, effect)
target:delMod(tpz.mod.HP, 22)
target:delMod(tpz.mod.STR, 7)
target:delMod(tpz.mod.INT, -3)
target:delMod(tpz.mod.HPHEAL, 2)
target:delMod(tpz.mod.MPHEAL, 1)
target:delMod(tpz.mod.FOOD_ATTP, 20)
target:delMod(tpz.mod.FOOD_ATT_CAP, 150)
target:delMod(tpz.mod.FOOD_RATTP, 20)
target:delMod(tpz.mod.FOOD_RATT_CAP, 150)
target:delMod(tpz.mod.DRAGON_KILLER, 5)
end
|
local class = require 'pl.class'
local krpc = require 'krpc.init'
local platform = require 'krpc.platform'
ServerTest = class()
function ServerTest:setUp()
self.conn = self.connect()
end
function ServerTest:tearDown()
self.conn:close()
end
function ServerTest:get_rpc_port()
local port = os.getenv('RPC_PORT')
if port == nil then
port = 50000
end
return port
end
function ServerTest:get_stream_port()
local port = os.getenv('STREAM_PORT')
if port == nil then
port = 50001
end
return port
end
function ServerTest:connect()
return krpc.connect('LuaClientTest', 'localhost',
ServerTest.get_rpc_port(), ServerTest.get_stream_port())
end
return ServerTest
|
require 'Items/ProceduralDistributions'
-- DoomsdayPreppers1
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, 2);
table.insert(ProceduralDistributions.list["LibraryBooks"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["LibraryBooks"].items, 2);
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, 1);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 2);
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["CrateBooks"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["CrateBooks"].items, 2);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 4);
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, 0.5);
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 0.2);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.DoomsdayPreppers1");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 0.2);
-- DoomsdayPreppers2
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, 2);
table.insert(ProceduralDistributions.list["LibraryBooks"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["LibraryBooks"].items, 2);
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, 1);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 2);
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["CrateBooks"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["CrateBooks"].items, 2);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 4);
table.insert(ProceduralDistributions.list["GarageCarpentry"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["GarageCarpentry"].items, 0.5);
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 0.2);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.DoomsdayPreppers2");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 0.2);
-- WeaponHandlersReloaded
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, 0.5);
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, 0.5);
table.insert(ProceduralDistributions.list["LibraryBooks"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["LibraryBooks"].items, 0.5);
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, 0.2);
table.insert(ProceduralDistributions.list["CrateBooks"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["CrateBooks"].items, 0.2);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 0.5);
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.WeaponHandlersReloaded");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 0.5);
-- TheUltimateHuntingGuide1
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, 2);
table.insert(ProceduralDistributions.list["LibraryBooks"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["LibraryBooks"].items, 2);
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, 1);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 2);
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["CrateBooks"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["CrateBooks"].items, 1);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 4);
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 2);
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.TheUltimateHuntingGuide1");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 1);
-- TheUltimateHuntingGuide2
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, 2);
table.insert(ProceduralDistributions.list["LibraryBooks"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["LibraryBooks"].items, 2);
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["LivingRoomShelf"].items, 1);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 2);
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, 2);
table.insert(ProceduralDistributions.list["CrateBooks"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["CrateBooks"].items, 1);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 4);
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 2);
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.TheUltimateHuntingGuide2");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 1);
-- TheSniperGuide
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["BookstoreBooks"].items, 0.5);
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["BookstoreMisc"].items, 0.5);
table.insert(ProceduralDistributions.list["LibraryBooks"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["LibraryBooks"].items, 0.5);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 0.5);
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["CampingStoreBooks"].items, 0.5);
table.insert(ProceduralDistributions.list["CrateBooks"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["CrateBooks"].items, 0.2);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 2);
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 2);
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["PostOfficeBooks"].items, 0.2);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.TheSniperGuide");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 0.2);
-- KCM_Compound
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 0.5);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 2);
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, 2);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 4);
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, 4);
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, 0.25);
table.insert(ProceduralDistributions.list["Locker"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["Locker"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, "KCMweapons.KCM_Compound");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, 0.5);
-- KCM_Compound02
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 0.5);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 1);
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, 1);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 4);
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, 4);
table.insert(ProceduralDistributions.list["Locker"].items, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["Locker"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, "KCMweapons.KCM_Compound02");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, 1);
-- HandCrossbow
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 2);
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, 2);
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, 2);
table.insert(ProceduralDistributions.list["Locker"].items, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["Locker"].items, 0.25);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, "KCMweapons.HandCrossbow");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, 1);
-- CrossbowBoltLargeBox
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 0.25);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 0.25);
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, 0.25);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 0.25);
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, 0.25);
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, 0.25);
table.insert(ProceduralDistributions.list["Locker"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["Locker"].items, 0.25);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, "KCMweapons.CrossbowBoltLargeBox");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, 0.5);
-- CrossbowBoltLarge
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["LockerArmyBedroom"].items, 0.5);
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 0.5);
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, 0.5);
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["FirearmWeapons"].items, 0.5);
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["FirearmWeapons"].junk, 0.5);
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, 0.5);
table.insert(ProceduralDistributions.list["Locker"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["Locker"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, "KCMweapons.CrossbowBoltLarge");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, 0.5);
-- CrossbowBoltBox
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 0.25);
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, 0.25);
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, 0.25);
table.insert(ProceduralDistributions.list["Locker"].items, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["Locker"].items, 0.25);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 1);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, "KCMweapons.CrossbowBoltBox");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, 0.5);
-- CrossbowBolt
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["CampingStoreBackpacks"].items, 0.5);
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["CampingStoreGear"].items, 0.5);
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["GarageMetalwork"].items, 0.5);
table.insert(ProceduralDistributions.list["Locker"].items, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["Locker"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].items, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["WardrobeMan"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["WardrobeMan"].junk, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].items, 0.5);
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, "KCMweapons.CrossbowBolt");
table.insert(ProceduralDistributions.list["WardrobeRedneck"].junk, 0.5); |
local m = {}
screalms = m
local storage = minetest.get_mod_storage()
local realm_store = storage:get("realms") and minetest.deserialize(storage:get("realms")) or {}
local areastore = AreaStore()
-- Save modified realm_store back to storage.
local function save()
storage:set_string("realms", minetest.serialize(realm_store))
end
local realms = {}
m.realms = realms
-- Realm sizes must be aligned
m.ALIGN = 16
local function coord_ok(value)
return (value % m.ALIGN) == 0
end
-- There must be sizable "buffer" space between realms.
m.SPACING = 400
local function global_box(corner, size)
return b.box.new_add(corner, size)
end
local function allocate_position(realm)
minetest.log("action", "Allocating position for new realm: " .. realm.id)
-- Loop through all possible positions until a space is found that does not collide.
for x=b.WORLDA.min.x, b.WORLDA.max.x, realm.size.x + m.SPACING do
for z=b.WORLDA.min.z, b.WORLDA.max.z, realm.size.z + m.SPACING do
local corner = vector.new(x, realm.y - realm.size.y / 2, z)
local box = global_box(corner, realm.size)
-- Ensure within world and not collides with another realm.
if b.box.inside_box(box, b.WORLDA.box) and #b.t.keys(areastore:get_areas_in_area(box.a, box.b, true)) == 0 then
-- Use this position.
return corner
end
end
end
-- No position found.
return nil
end
-- Get the corner and size of an allocated or previous realm region.
local function get_position(realm)
-- Table describing the stored realm.
local store = realm_store[realm.id] or {
corner = allocate_position(realm),
size = realm.size,
}
-- No corner means not allocated.
if not store.corner then
return nil
end
-- Changing realm sizes could lead to spatial collisions.
-- Warn if we're using a different stored size.
if not vector.equals(store.size, realm.size) then
minetest.log("warning", ("Realm %s stored size %s differs from registered size %s; will continue using stored size"):format(realm.id, minetest.pos_to_string(store.size), minetest.pos_to_string(realm.size)))
end
-- Save the realm data.
realm_store[realm.id] = store
save()
-- Return the (possibly previously) allocated position and the realm size (stored size if already generated, otherwise registered size)
return store.corner, store.size
end
-- Register a new realm.
function m.register(id, def)
assert(not realms[id], "realm already exists")
-- Create realm from defaults and supplied values.
local r = b.t.combine({
-- Human-readable identifier of the realm.
description = "?",
-- Realm size.
size = vector.new(480, 480, 480),
-- Realm Y location.
y = 0,
-- Realm limits nodes.
limit_top = "aurum_base:limit",
limit_bottom = "aurum_base:foundation",
-- Apply client-side appearances.
apply_player = function(player) m.apply_underground(player) end,
}, def, {
id = id,
-- Default biome setup.
biome_default = b.t.combine({
node_stone = "aurum_base:stone",
node_water = "aurum_base:water_source",
node_river_water = "aurum_base:river_water_source",
depth_filler = 0,
node_riverbed = "aurum_base:sand",
depth_riverbed = 2,
node_cave_liquid = {"aurum_base:water_source", "aurum_base:lava_source"},
node_dungeon = "aurum_base:stone_brick",
node_dungeon_stair = "aurum_base:stone_brick_sh_stairs",
}, def.biome_default or {}),
})
-- Ensure valid positioning.
assert(coord_ok(r.size.x))
assert(coord_ok(r.size.y))
assert(coord_ok(r.size.z))
-- Find a global position and get the actual size of the realm
r.global_corner, r.size = get_position(r)
assert(r.global_corner, "out of room registering " .. r.id .. ", cannot add a realm of this size")
-- Relative 0,0,0 point.
r.center = vector.divide(r.size, 2)
-- Global center.
r.global_center = vector.add(r.global_corner, r.center)
-- Local bounding box.
r.local_box = b.box.new(vector.multiply(r.center, -1), r.center)
-- Global bounding box.
r.global_box = global_box(r.global_corner, r.size)
-- Add realm global box to areastore.
areastore:insert_area(r.global_box.a, r.global_box.b, id)
minetest.log("action", ("Registered realm (%s) centered at %s, size %s"):format(id, minetest.pos_to_string(r.global_center), minetest.pos_to_string(r.size)))
realms[id] = r
return r
end
-- Remove a realm by ID, freeing the id and stored position.
-- Note that if any of this realm has already been generated, *weird things* can happen.
function m.unregister(id)
realms[id] = nil
realm_store[id] = nil
end
-- Get a realm definition.
function m.get(id)
return realms[id]
end
-- Get position within realm.
function m.rpos(realm_id, global_pos)
return vector.subtract(global_pos, realms[realm_id].global_center)
end
-- Get global position from realm.
function m.gpos(realm_id, realm_pos)
return vector.add(realms[realm_id].global_center, realm_pos)
end
-- Checks which realm a point is in.
-- Returns realm id or nil
function m.pos_to_realm(global_pos)
local a = areastore:get_areas_for_pos(global_pos, false, true)
for k,v in pairs(a) do
return v.data
end
end
-- Checks which realm a box is colliding with. Does not support multiple collisions.
-- Returns realm id or nil.
function m.box_to_realm(global_box)
local a = areastore:get_areas_in_area(global_box.a, global_box.b, true, false, true)
for k,v in pairs(a) do
return v.data
end
end
-- Generate the realm border.
minetest.register_on_generated(function(minp, maxp, seed)
-- Check if any part of the block is in a realm.
local realm = m.box_to_realm(b.box.new(minp, maxp))
-- If not within a realm, then we don't need to generate the border.
if not realm then
return
end
realm = m.get(realm)
-- Read all data.
local vm, emin, emax = minetest.get_mapgen_object("voxelmanip")
local area = VoxelArea:new{MinEdge = emin, MaxEdge = emax}
local data = vm:get_data()
local center = vector.divide(vector.add(emin, emax), 2)
local c_border = minetest.get_content_id((maxp.y > 0) and realm.limit_top or realm.limit_bottom)
for _,axis in ipairs{"x", "y", "z"} do
local sign = math.sign(center[axis] - realm.global_center[axis])
local corner = (sign < 0) and "a" or "b"
local border = realm.global_box[corner][axis]
if emin[axis] <= border and emax[axis] >= border then
local emin = table.copy(emin)
local emax = table.copy(emax)
emin[axis] = border
emax[axis] = border
for i in area:iterp(emin, emax) do
data[i] = c_border
end
end
end
-- And write back.
vm:set_data(data)
vm:write_to_map()
end)
b.dofile("check_underground.lua")
|
-- -*- coding: utf-8 -*-
-- Documentation
--- \fn table.toLuaCode(inTable, indent, resultHandler)
--- \brief Преобразует объект типа таблица в строку лунового кода, создающего такую таблицу
--- \param[in] inTable таблица для обработки
--- \param[in] indent отступ от начала строки для элементов таблицы
--- \param[in] resultHandler указатель на функцию-обработчик результата, если nil, то функция просто вернет результирующую строку
--- \fn findKey(inTable, inKey)
--- \brief Определяет наличие в таблице ключа с заданным значением (без рекурсивного обхода всей таблицы)
--- \param[in] inTable таблица для поиска
--- \param[in] inKey значение ключа, который надо разыскать
--- \return true если искомый ключ был найден, иначе false
--- \fn findValue(inTable, inValue)
--- \brief Аналогична findKey, только ищется значение в таблице, а не ключ
--- \see findKey
--- \fn table.keys(inTable)
--- \brief Return list of keys in 'inTable'
--- \param[in] inTable table for processing
--- \fn table.isEmpty(tableValue)
--- \return true if table does not contain any elements
--- \fn convertTextToRePattern(text)
--- \brief Replace magic chars ( ) . % + - [ ] ^ $ ? * at 'text' with used at re patterns
--- \param[in] text Source text for pattern creation
--- \return Regula expression patterns
--- \fn string.split(str, delimiter)
--- \brief Splitting string into parts using 'delimited' as a bound beatween them
--- \param[in] str String for cutting
--- \param[in] delimiter It is pattern for delimiter substring. I.e. string.len(delimiter) maybe > 1. Attention with special simbols, whith need % before them.
--- \return Array (i.e. {'a', 'b',}) of string parts
local luaExt = require "yunit.lua_ext"
function testFindInTable()
isTrue(luaExt.findKey({[1] = "1"}, 1))
isFalse(luaExt.findKey({[2] = "1"}, 1))
isTrue(luaExt.findValue({[1] = "1"}, "1"))
isFalse(luaExt.findValue({[1] = "2"}, "1"))
end
function toLuaCode()
local t =
{
[1] = 1,
['a'] = [[a]],
[{}] = {},
}
local spaceAsTab = string.rep(' ', 4);
local str = table.toLuaCode(t, spaceAsTab);
isNotNil(string.find(str, "['a'] = [=[a]=],", 1, true))
isNotNil(string.find(str, "[1] = 1,", 1, true))
isNotNil(string.find(str, "[{}] = {},", 1, true), str)
end
function testStringSplit()
local parts = {};
parts = string.split('', ';');
areEq('', parts[1]);
parts = string.split(';', ';');
areEq('', parts[1]);
areEq('', parts[2]);
parts = string.split(';/bin;', ';');
areEq('', parts[1]);
areEq('/bin', parts[2]);
areEq('', parts[3]);
parts = string.split('/bin;/local/bin;c:', ';');
areEq('/bin', parts[1]);
areEq('/local/bin', parts[2]);
areEq('c:', parts[3]);
parts = string.split('aa bb cc\tdd\t\tee\t gg', '%s+');
areEq('aa', parts[1]);
areEq('bb', parts[2]);
areEq('cc', parts[3]);
areEq(6, #parts);
end
function tableKeysTest()
local keyList = table.keys({[10] = 1, [11] = 1, [12] = 1, [13] = 1});
table.sort(keyList);
areEq(10, keyList[1]);
areEq(11, keyList[2]);
areEq(12, keyList[3]);
areEq(13, keyList[4]);
end
function tableEmptyTest()
isTrue(table.isEmpty{});
isFalse(table.isEmpty{''});
end
function convertTextToRePattern()
areEq('exportDg %.cpp', luaExt.convertTextToRePattern('exportDg .cpp'));
end
function tableCompareTest()
isTrue(table.isEqual({}, {}));
isTrue(table.isEqual({1}, {1}));
isTrue(table.isEqual({1.1}, {1.1}));
isTrue(table.isEqual({'a'}, {'a'}));
isTrue(table.isEqual({{}}, {{}}));
isTrue(table.isEqual({1, 1.1, 'a', {}}, {1, 1.1, 'a', {}}));
isTrue(table.isEqual({{1}}, {{1}}));
isTrue(table.isEqual({['a'] = 'a', ['1.1'] = 1.1, ['1'] = 1, {}}, {['1.1'] = 1.1, ['1'] = 1, ['a'] = 'a', {}}));
local a = function () end
isTrue(table.isEqual({['a'] = a, ['1.1'] = 1.1, ['1'] = 1, {}}, {['1.1'] = 1.1, ['1'] = 1, ['a'] = a, {}}));
isFalse(table.isEqual({['a'] = true}, {['a'] = false}));
isTrue(table.isEqual({['a'] = false}, {['a'] = false}));
isFalse(table.isEqual({}, {1}));
isFalse(table.isEqual({}, {1.1}));
isFalse(table.isEqual({}, {'a'}));
isFalse(table.isEqual({}, {{}}));
isFalse(table.isEqual({1}, {}));
isFalse(table.isEqual({1.1}, {}));
isFalse(table.isEqual({'a'}, {}));
isFalse(table.isEqual({{}}, {}));
isTrue(table.isEqual( { [{1}] = 1}, { [{1}] = 1} ));
end
|
browserList = {}
browserList_mt = { __index = browserList }
local activatedBrowsers = {}
local ROW_HEIGHT = 14
local keyUp,keyDown,ignore
--NOTE: All functions lack necessary checks to verify valid args, its intended for internal use only
-------
local function browserListGridlistClick( button,state,x,y )
if state == "up" then return end
ignore = false
if getElementType(source) ~= "gui-gridlist" then return end
for self,oldScrollPosition in pairs(activatedBrowsers) do
if source == self.gridlist then
-- local startKey = math.ceil(guiScrollBarGetScrollPosition(self.scrollbar) * self.rowMultiplier)
local startKey = self.startKey
local row = guiGridListGetSelectedItem ( self.gridlist )
if row == -1 then
row = 0
--Possibly add a check if row ~= self.selected.
else
row = row + startKey
end
self:setSelected(row)
end
end
end
local function browserListDoubleClick(button,state,x,y)
for self,oldScrollPosition in pairs(activatedBrowsers) do
if source == self.gridlist then
if self.doubleClickCallback then
self.doubleClickCallback()
end
end
end
end
local function checkPosition(self)
local newPosition = guiScrollBarGetScrollPosition ( self.scrollbar )
if not ignore then
if newPosition ~= math.floor(self.position) then
self.position = newPosition
end
end
end
local function updateActivatedBrowsers()
for self,oldScrollPosition in pairs(activatedBrowsers) do
checkPosition(self)
local position = self.position
if position < 0 then position = 0 end
if position ~= oldScrollPosition then
guiGridListClear ( self.gridlist )
local centre = math.ceil(position * self.rowMultiplier)
local startKey = centre + 1
local targetKey = startKey + self.gridlistRowCount - 1
--set the text
local i = startKey
while i ~= targetKey do
rowColumns = self.rowList[i]
if type(rowColumns) == "table" then
local pos = guiGridListAddRow ( self.gridlist )
for columnID, text in ipairs(rowColumns) do
guiGridListSetItemText(self.gridlist,pos,columnID,text,false,false)
end
else --if its a linear table then there's only 1 column to set
local pos = guiGridListAddRow ( self.gridlist )
guiGridListSetItemText(self.gridlist,pos,1,rowColumns,false,false)
end
i = i + 1
end
if self.selected >= startKey and self.selected <= targetKey then
local row = self.selected - startKey
guiGridListSetSelectedItem ( self.gridlist,row,1)
end
self.startKey = startKey
activatedBrowsers[self] = position
end
end
end
--Scroll stuff
local scrollTimer
local isScrolling = false
local initialDelay = 600
local acceleration = 100
local maximum = 50 --lower the faster
local function browserListScrollList ( key, newRepeatDelay )
if not isScrolling then return end
for self,oldScrollPosition in pairs(activatedBrowsers) do --this is lazy, it means all browserLists scroll simultaneously
local cellrow = self:getSelected()
-- local rowCount = 5
local rowCount = self.rowCount
if key == keyUp then
cellrow = cellrow - 1
if cellrow <= 0 then
cellrow = rowCount
end
elseif key == keyDown then
cellrow = cellrow + 1
if cellrow > rowCount then
cellrow = 1
end
end
self:setSelected(cellrow)
self:centre(cellrow)
newRepeatDelay = newRepeatDelay - acceleration
if newRepeatDelay < maximum then newRepeatDelay = maximum end
if isScrolling then
scrollTimer = setTimer ( browserListScrollList, newRepeatDelay, 1, key, newRepeatDelay )
end
end
end
local function browserListScroll ( key, keyState )
if keyState == "down" then
isScrolling = true
browserListScrollList ( key, initialDelay )
elseif keyState == "up" then
isScrolling = false
for k,timer in pairs(getTimers()) do
if timer == scrollTimer then
killTimer ( scrollTimer )
break
end
end
end
end
local function gridlistScroll(key,keyState)
for self,oldScrollPosition in pairs(activatedBrowsers) do
if guiGetMouseOverElement() == self.gridlist then
--get the current position
local row = (self.position*self.rowMultiplier) + (self.gridlistRowCount/2)
--local row = math.floor(row)
if key == "mouse_wheel_up" then
row = row - 3
else
row = row + 3
end
self:centre(row)
end
end
end
function round(number,idp)
local mult = 10^(idp or 0)
return math.floor(number * mult + 0.5) / mult
end
function browserList:create(x,y,width,height,columnTable,relative,parent)
local new = {}
setmetatable( new, browserList_mt )
new.gridlist = guiCreateGridList (x,y,width,height,relative,parent)
guiGridListSetSortingEnabled ( new.gridlist,false )
local x,y = guiGetSize ( new.gridlist, false )
new.scrollbar = guiCreateScrollBar(x - 20,0,20,y,false,false,new.gridlist)
new.gridlistSizeY = y - 23
new.gridlistRowCount = math.ceil((y-25)/ROW_HEIGHT) --The number of rows you can fit into it
for key,columnSubTable in pairs(columnTable) do
for columnName,width in pairs(columnSubTable) do
guiGridListAddColumn ( new.gridlist,tostring(columnName),width )
end
end
return new
end
function browserList:setSize(x,y)--only supports absolute positioning for now
self.gridlistSizeY = y - 23
self.gridlistRowCount = math.ceil((y-25)/ROW_HEIGHT)
self.scrollDistance = self.rowCount - self.gridlistRowCount
self.rowMultiplier = self.scrollDistance/100
guiSetSize ( self.gridlist,x,y,false)
local scrollbarX = guiGetSize ( self.gridlist, false )
guiSetPosition ( self.scrollbar,scrollbarX - 20,0,false)
guiSetSize ( self.scrollbar,20,y,false)
end
function browserList:setRows(rowTable)
--store the data
self.currentStartKey = 1
self.rowCount = #rowTable --total number of rows
self.rowList = rowTable
self.scrollDistance = self.rowCount - self.gridlistRowCount
self.rowMultiplier = self.scrollDistance/100 --how much 1% of a scrollbar would represent
-- self.stepSize = 1/((self.gridlistRowCount/9.34) * self.rowMultiplier )
--guiSetProperty(self.scrollbar,"StepSize",tostring(self.stepSize) )
guiSetProperty(self.scrollbar,"StepSize","0" )
self.startKey = 1
self.selected = 0
self.position = 0
guiScrollBarSetScrollPosition ( self.scrollbar, 0 )
if self.rowCount < self.gridlistRowCount then
guiSetVisible ( self.scrollbar, false )
else
guiSetVisible ( self.scrollbar, true )
end
self:setSelected(0)
guiGridListGetSelectedItem ( self.gridlist,-1,-1 )
--
guiGridListClear ( self.gridlist )
if #rowTable == 0 then
guiGridListAddRow ( self.gridlist )
guiGridListSetItemText ( self.gridlist, 0, 1,"No results found", true, false )
return true
end
local i = 1
local target = self.gridlistRowCount + 2
while i ~= target do
local rowColumns = rowTable[i]
if type(rowColumns) == "table" then
local pos = guiGridListAddRow ( self.gridlist )
for columnID, text in ipairs(rowColumns) do
guiGridListSetItemText(self.gridlist,pos,columnID,text,false,false)
end
else --if its a linear table then there's only 1 column to set
local pos = guiGridListAddRow ( self.gridlist )
guiGridListSetItemText(self.gridlist,pos,1,rowColumns,false,false)
end
i = i + 1
end
return true
end
function browserList:clear()
guiGridListClear ( self.gridlist )
return true
end
local enabledBrowsers = {}
function browserList:enable(up,down)
activatedBrowsers[self] = guiScrollBarGetScrollPosition ( self.scrollbar )
local count = 0
for k,v in pairs(activatedBrowsers) do
count = count + 1
end
--
if count == 1 then
addEventHandler ( "onClientRender",getRootElement(),updateActivatedBrowsers )
addEventHandler("onClientGUIMouseDown",getRootElement(),browserListGridlistClick )
addEventHandler("onClientGUIDoubleClick",getRootElement(),browserListDoubleClick )
if not up then up = "arrow_u" end
if not down then down = "arrow_d" end
keyUp,keyDown = up,down
bindKey ( keyUp, "both", browserListScroll )
bindKey ( keyDown, "both", browserListScroll )
bindKey ( "mouse_wheel_up", "both", gridlistScroll )
bindKey ( "mouse_wheel_down", "both", gridlistScroll )
end
return true
end
function browserList:disable()
activatedBrowsers[self] = nil
local count = 0
for k,v in pairs(activatedBrowsers) do
count = count + 1
end
--
if count == 0 then
removeEventHandler ( "onClientRender",getRootElement(),updateActivatedBrowsers )
removeEventHandler("onClientGUIMouseDown",getRootElement(),browserListGridlistClick )
removeEventHandler("onClientGUIDoubleClick",getRootElement(),browserListDoubleClick )
unbindKey ( keyUp, "both", browserListScroll )
unbindKey ( keyDown, "both", browserListScroll )
unbindKey ( "mouse_wheel_up", "both", gridlistScroll )
unbindKey ( "mouse_wheel_down", "both", gridlistScroll )
end
return true
end
function browserList:setSelected(value)
self.selected = value
local startKey = self.startKey
local targetKey = startKey + self.gridlistRowCount + 1
if self.selected >= startKey and self.selected <= targetKey then
local row = self.selected - startKey
guiGridListSetSelectedItem ( self.gridlist,row,1)
end
if self.callback then
self.callback(value)
end
return true
end
function browserList:getSelected()
return self.selected
end
function browserList:getSelectedText()
return self.rowList[self.selected]
end
function browserList:centre(row)
local position = (row - (self.gridlistRowCount/2))/self.rowMultiplier
if position < 0 then position = 0 end
if position > 100 then position = 100 end
ignore = true
guiScrollBarSetScrollPosition ( self.scrollbar, (position) )
self.position = position
end
browserList.center = browserList.centre
function browserList:addCallback(theFunction)
self.callback = theFunction
end
function browserList:addDoubleClickCallback(theFunction)
self.doubleClickCallback = theFunction
end
|
--[[
Whiteout
by alfunx (Alphonse Mariya)
based on Blackout
--]]
local gears = require("gears")
local t_util = require("config.util_theme")
local os, math, string = os, math, string
local colors = { }
colors.black_1 = "#fbf1c7"
colors.black_2 = "#928374"
colors.red_1 = "#cc241d"
colors.red_2 = "#9d0006"
colors.green_1 = "#98971a"
colors.green_2 = "#79740e"
colors.yellow_1 = "#d79921"
colors.yellow_2 = "#b57614"
colors.blue_1 = "#458588"
colors.blue_2 = "#076678"
colors.purple_1 = "#b16286"
colors.purple_2 = "#8f3f71"
colors.aqua_1 = "#689d6a"
colors.aqua_2 = "#427b58"
colors.white_1 = "#7c6f64"
colors.white_2 = "#3c3836"
colors.orange_1 = "#d65d0e"
colors.orange_2 = "#af3a03"
colors.bw_0_h = "#f9f5d7"
colors.bw_0 = "#fbf1c7"
colors.bw_0_s = "#f2e5bc"
colors.bw_1 = "#ebdbb2"
colors.bw_2 = "#d5c4a1"
colors.bw_3 = "#bdae93"
colors.bw_4 = "#a89984"
colors.bw_5 = "#928374"
colors.bw_6 = "#7c6f64"
colors.bw_7 = "#665c54"
colors.bw_8 = "#504945"
colors.bw_9 = "#3c3836"
colors.bw_10 = "#282828"
colors = t_util.set_colors(colors)
-- Use _dir to preserve parent theme.dir
local theme = require("themes.blackout.theme")
theme.name = "whiteout"
theme.alternative = "blackout"
theme._dir = string.format("%s/.config/awesome/themes/%s", os.getenv("HOME"), theme.name)
-- theme.wallpaper = theme.dir .. "/wallpapers/wall.png"
theme.wallpaper = theme.dir .. "/wallpapers/escheresque.png"
theme.wallpaper_fn = gears.wallpaper.tiled
theme.titlebar_close_button_focus = theme._dir .. "/icons/titlebar/close_focus.png"
theme.titlebar_close_button_normal = theme._dir .. "/icons/titlebar/close_normal.png"
theme.titlebar_ontop_button_focus_active = theme._dir .. "/icons/titlebar/ontop_focus_active.png"
theme.titlebar_ontop_button_normal_active = theme._dir .. "/icons/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_inactive = theme._dir .. "/icons/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_inactive = theme._dir .. "/icons/titlebar/ontop_normal_inactive.png"
theme.titlebar_sticky_button_focus_active = theme._dir .. "/icons/titlebar/sticky_focus_active.png"
theme.titlebar_sticky_button_normal_active = theme._dir .. "/icons/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_inactive = theme._dir .. "/icons/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_inactive = theme._dir .. "/icons/titlebar/sticky_normal_inactive.png"
theme.titlebar_floating_button_focus_active = theme._dir .. "/icons/titlebar/floating_focus_active.png"
theme.titlebar_floating_button_normal_active = theme._dir .. "/icons/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_inactive = theme._dir .. "/icons/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_inactive = theme._dir .. "/icons/titlebar/floating_normal_inactive.png"
theme.titlebar_minimize_button_focus = theme._dir .. "/icons/titlebar/minimized_focus.png"
theme.titlebar_minimize_button_normal = theme._dir .. "/icons/titlebar/minimized_normal.png"
theme.titlebar_maximized_button_focus_active = theme._dir .. "/icons/titlebar/maximized_focus_active.png"
theme.titlebar_maximized_button_normal_active = theme._dir .. "/icons/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_inactive = theme._dir .. "/icons/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_inactive = theme._dir .. "/icons/titlebar/maximized_normal_inactive.png"
return theme
|
local invoke = require('invoke')
local tool = {}
function tool.getExternalStorageDirectory()
return invoke('com.shininggames.tool.Tool', 'getExternalStorageDirectory','not')
end
return tool
|
help([[
For detailed instructions, go to:
https://...
]])
whatis("Version: 3.18.2")
whatis("Keywords: System, Utility")
whatis("URL: https://cmake.org/download/")
whatis("Description: Compilation tool")
setenv("DDTPATH", "/opt/sw/cmake-3.18.2/bin")
prepend_path("PATH", "/opt/sw/cmake-3.18.2/bin")
prepend_path("LD_LIBRARY_PATH","/opt/cmake-3.18.2/lib")
setenv("CMAKE_ROOT", "/opt/sw/cmake-3.18.2/share")
|
return {
tllirritator = {
acceleration = 0.12,
activatewhenbuilt = true,
brakerate = 2.97,
buildcostenergy = 395433,
buildcostmetal = 24947,
builder = false,
buildpic = "tllirritator.dds",
buildtime = 330000,
canattack = true,
canguard = true,
canmove = true,
canpatrol = true,
canstop = 1,
category = "ALL HUGE MOBILE SURFACE UNDERWATER",
collisionvolumeoffsets = "0 -6 4",
collisionvolumescales = "115 142 115",
collisionvolumetype = "CylY",
corpse = "tllirritator_dead",
defaultmissiontype = "Standby",
description = "Experimental Shield Unit",
energystorage = 1000,
explodeas = "BANTHA_BLAST",
firestandorders = 1,
footprintx = 7,
footprintz = 7,
idleautoheal = 10,
idletime = 30,
immunetoparalyzer = 1,
losemitheight = 130,
maneuverleashlength = 1250,
mass = 24947,
maxdamage = 80950,
maxslope = 36,
maxvelocity = 1.55,
maxwaterdepth = 12,
mobilestandorders = 1,
movementclass = "HKBOT7",
name = "Irritator",
noautofire = false,
objectname = "tllirritator",
radardistance = 0,
radaremitheight = 130,
script = "tllirritator.cob",
seismicsignature = 0,
selfdestructas = "KROG_BLAST",
selfdestructcountdown = 10,
sightdistance = 650,
sonardistance = 0,
standingfireorder = 2,
standingmoveorder = 1,
steeringmode = 2,
threed = 1,
turninplaceanglelimit = 140,
turninplacespeedlimit = 0.858,
turnrate = 225,
unitname = "tllirritator",
upright = true,
version = 1,
zbuffer = 1,
customparams = {
buildpic = "tllirritator.dds",
faction = "TLL",
shield_emit_height = 30,
shield_power = 2000,
shield_radius = 150,
},
featuredefs = {
tllirritator_dead = {
blocking = false,
damage = 33783,
description = "tllirritator Shielded Mech Wreckage",
energy = 0,
featuredead = "tllirritator_heap",
footprintx = 6,
footprintz = 6,
metal = 17625,
object = "tllirritator_dead",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
tllirritator_heap = {
blocking = false,
damage = 42229,
description = "tllirritator Shielded Mech Debris",
energy = 0,
footprintx = 6,
footprintz = 6,
metal = 9400,
object = "6X6A",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
},
sfxtypes = {
explosiongenerators = {
[1] = "custom:tllroaster_muzzle",
[2] = "custom:lightning_muzzle_spark",
[3] = "custom:heli_muzzle",
},
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "kbcormov",
},
select = {
[1] = "kbcorsel",
},
},
weapondefs = {
rave_missile = {
acceleration = 0.3,
areaofeffect = 96,
avoidfeature = false,
cegtag = "Tll_titan_trail",
craterareaofeffect = 0,
craterboost = 0,
cratermult = 0,
explosiongenerator = "custom:Explosion_Medium_VLight",
firestarter = 70,
impulseboost = 0.123,
impulsefactor = 0.123,
model = "titan_missile",
name = "Mini-Rocket",
noselfdamage = true,
proximitypriority = -1,
range = 900,
reloadtime = 0.25,
smoketrail = true,
soundhitdry = "xplosml2",
soundhitwet = "splshbig",
soundhitwetvolume = 0.6,
soundstart = "rocklit1",
startvelocity = 220,
targetable = 16,
texture1 = "null",
texture2 = "null",
texture3 = "null",
texture4 = "null",
tolerance = 9000,
tracks = true,
turnrate = 35000,
weaponacceleration = 150,
weapontimer = 0.60,
weapontype = "StarburstLauncher",
weaponvelocity = 2100,
damage = {
default = 150,
subs = 5,
},
},
tllirritator_shield = {
name = "PersonalShield",
shieldbadcolor = "1 0.2 0.2 0.35",
shieldenergyuse = 300,
shieldforce = 8,
shieldgoodcolor = "0.2 1 0.2 0.35",
shieldintercepttype = 1,
shieldmaxspeed = 3500,
shieldpower = 2000,
shieldpowerregen = 30,
shieldpowerregenenergy = 300,
shieldradius = 150,
shieldrepulser = true,
smartshield = true,
soundhitwet = "sizzle",
soundhitwetvolume = 0.5,
visibleshieldrepulse = true,
weapontype = "Shield",
damage = {
default = 100,
},
},
mini_barret = {
areaofeffect = 200,
beamttl = 10,
craterareaofeffect = 200,
craterboost = 0,
cratermult = 0,
duration = 0.6,
energypershot = 3000,
explosiongenerator = "custom:Explosion_Barret_Tesla",
firestarter = 90,
impulseboost = 0,
impulsefactor = 0,
intensity = 25,
name = "Ultra lightning Weapon2",
noselfdamage = true,
range = 900,
reloadtime = 4,
rgbcolor = "0.6 0.6 0.9",
soundhitdry = "maghit",
soundhitwet = "sizzle",
soundhitwetvolume = 0.3,
soundstart = "tll_lightning",
texture1 = "strike",
thickness = 16,
turret = true,
weapontype = "LightningCannon",
weaponvelocity = 560,
customparams = {
light_mult = 1.4,
light_radius_mult = 0.9,
},
damage = {
commanders = 2500,
default = 5000,
subs = 5,
},
},
},
weapons = {
[1] = {
badtargetcategory = "MEDIUM SMALL TINY",
def = "MINI_BARRET",
onlytargetcategory = "SURFACE",
},
[3] = {
def = "RAVE_MISSILE",
onlytargetcategory = "SURFACE VTOL",
},
[4] = {
def = "tllirritator_Shield",
},
},
},
}
|
--- This callback is required for the movelistener to know who
-- detected the adventurer when it arrived.
-- @classmod MoveListenerPostAbilityCallbackEvent
-- region imports
local class = require('classes/class')
local prototype = require('prototypes/prototype')
require('prototypes/event')
require('prototypes/serializable')
local simple_serializer = require('utils/simple_serializer')
local adventurers = require('functional/game_context/adventurers')
local detection = require('functional/detection')
local system_messages = require('functional/system_messages')
local AdventurerEvent = require('classes/events/adventurer')
local SendToDetectedByCallbackEvent = require('classes/events/callbacks/send_to_detected_by')
-- endregion
local MoveListenerPostAbilityCallbackEvent = {}
simple_serializer.inject(MoveListenerPostAbilityCallbackEvent)
function MoveListenerPostAbilityCallbackEvent:init()
if type(self.adventurer_name) ~= 'string' then
error(string.format('expected adventurer name is string, got %s (type=%s)',
tostring(self.adventurer_name), type(self.adventurer_name)), 3)
end
if type(self.from) ~= 'table' then
error(string.format('expected from is table, but type=%s', type(self.from)))
end
end
function MoveListenerPostAbilityCallbackEvent:process(game_ctx, local_ctx, networking)
if local_ctx.id ~= 0 then return end
local moved_advn_name = self.adventurer_name
local moved_advn, moved_advn_ind = adventurers.get_by_name(game_ctx, moved_advn_name)
local events = {}
local completed_nms = {}
for _, loc in ipairs(self.from) do
local advns = adventurers.get_by_location(game_ctx, loc)
for _, advn in ipairs(advns) do
if not completed_nms[advn.name] then
completed_nms[advn.name] = true
if advn:is_detected(moved_advn_name) then
table.insert(events, AdventurerEvent:new{
type = 'remove_detect',
adventurer_name = advn.name,
detected_name = moved_advn_name
})
end
end
end
end
table.insert(events, AdventurerEvent:new{
type = 'clear_detect',
adventurer_name = moved_advn_name
})
table.insert(events, SendToDetectedByCallbackEvent:new{
adventurer_name = self.adventurer_name,
message = string.format('%s has arrived at your location.', self.adventurer_name)
})
networking:broadcast_events(game_ctx, local_ctx, events)
system_messages:send(game_ctx, local_ctx, networking, moved_advn_ind,
string.format('Movement to %s finished', moved_advn.locations[1]), 0)
end
prototype.support(MoveListenerPostAbilityCallbackEvent, 'event')
prototype.support(MoveListenerPostAbilityCallbackEvent, 'serializable')
return class.create('MoveListenerPostAbilityCallbackEvent', MoveListenerPostAbilityCallbackEvent)
|
-- ----------------------------------------------------
-- kvalue_manipulate.lua
--
-- Sep/16/2010
-- ----------------------------------------------------
require('Memcached')
-- ----------------------------------------------------
function disp_proc (redis,key)
result = redis:get (key)
if (result ~= null) then
json = require("json")
obj = json.decode(result)
out_str = key .. "\t" .. obj.name .. "\t"
out_str = out_str .. obj.population .. "\t" .. obj.date_mod
print (out_str)
end
end
-- ----------------------------------------------------
function update_proc (mem,key)
result = mem:get (key)
if (result ~= null) then
today = (os.date ("*t").year) .. "-" ..
(os.date ("*t").month) .. "-" ..
(os.date ("*t").day)
json = require("json")
obj = json.decode(result)
obj.population=population_in
obj.date_mod=today
str_json = json.encode (obj)
print (str_json)
mem:set (key,str_json)
end
end
-- ----------------------------------------------------
function record_out_proc (redis,id_in,name_in,population_in,date_mod_in)
json = require("json")
obj = {name=name_in,
population=population_in, date_mod=date_mod_in}
str_json = json.encode (obj)
print (id_in .. "\t" .. str_json)
redis:set (id_in,str_json)
end
-- ----------------------------------------------------
|
-- Small set of functions that provide random jittering
-- of different kinds (rotation, shift, brightness) that
-- can be applied to input images used the 'jitter' function
tnt = require 'torchnet'
function rotate(img)
mask = torch.DoubleTensor(img:size()):fill(1.0)
theta = torch.uniform(-0.2, 0.2)
img_rot = image.rotate(img, theta, bilinear)
mask = (image.rotate(mask, theta) - 1) * (-1)
return torch.cmul(mask,img) + img_rot
end
function shift(img)
mask = torch.DoubleTensor(img:size()):fill(1.0)
x_shift = torch.round(torch.uniform(-2.5, 2.5))
y_shift = torch.round(torch.uniform(-2.5, 2.5))
img_shift = image.translate(img, x_shift, y_shift)
mask = (image.translate(mask, x_shift, y_shift) - 1) * (-1)
return torch.cmul(mask, img) + img_shift
end
function bright(img)
val = torch.uniform(0, 1.0)
if val > 0.5 then
return img
end
hsv = image.rgb2hsv(img)
hsv[3] = hsv[3] + torch.uniform(-0.1,1.5)
return image.hsv2rgb(hsv)
end
function jitter(img)
return tnt.transform.compose{
[1] = bright,
[2] = shift,
[3] = rotate
}(img)
end
|
--[[
$Id$
Copyright © 2012, 2017, 2021 VideoLAN and AUTHORS
Authors: Ludovic Fauvet <etix@videolan.org>
Pierre Ynard
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return ( vlc.access == "http" or vlc.access == "https" ) and (
string.match( vlc.path, "^www%.liveleak%.com/v%?" )
or string.match( vlc.path, "^www%.liveleak%.com/view%?" )
)
end
-- Parse function.
function parse()
local p = {}
local title
local art
local video
while true do
line = vlc.readline()
if not line then break end
-- Try to find the title
if not title then
title = string.match( line, "shareTitle: *'(.-[^\\])'" )
if title then
if string.match( title, "^'" ) then
title = nil
else
-- FIXME: do this properly (see #24958)
title = string.gsub( title, "\\'", "'" )
end
end
end
-- Try to find the art
if not art then
art = string.match( line, '<meta property="og:image" content="([^"]+)"' )
end
-- Try to find the video
if not video and string.match( line, '<video ' ) then
while not string.match( line, '</video>') do
local more = vlc.readline()
if not more then break end
line = line..more
end
-- Apparently the two formats are listed HD first, SD second
local prefres = vlc.var.inherit( nil, 'preferred-resolution' )
for source in string.gmatch( line, '<source( .-)>' ) do
local src = string.match( source, ' src="([^"]+)"' )
if src then
video = vlc.strings.resolve_xml_special_chars( src )
if prefres < 0 then
break
end
local height = tonumber( string.match( source, ' label="(%d+).-"' ) )
if ( not height ) or height <= prefres then
break
end
end
end
end
end
if video then
table.insert( p, { path = video; name = title; arturl = art; } )
end
return p
end
|
RegisterNetEvent("npc-jobmanager:playerBecameJob")
AddEventHandler("npc-jobmanager:playerBecameJob", function(job, name, notify)
if isMedic and job ~= "ems" then isMedic = false isInService = false end
if isCop and job ~= "police" then isCop = false isInService = false end
if job == "police" then isCop = true isInService = true end
if job == "ems" then isMedic = true isInService = true end
end)
local attempted = 0
local pickup = false
local additionalWait = 0
RegisterNetEvent('sec:PickupCash')
AddEventHandler('sec:PickupCash', function()
pickup = true
TriggerEvent("sec:PickupCashLoop")
Wait(180000)
Wait(additionalWait)
pickup = false
end)
RegisterNetEvent('sec:PickupCashLoop')
AddEventHandler('sec:PickupCashLoop', function()
local markerlocation = GetOffsetFromEntityInWorldCoords(attempted, 0.0, -3.7, 0.1)
SetVehicleHandbrake(attempted,true)
while pickup do
Citizen.Wait(0)
local coords = GetEntityCoords(GetPlayerPed(-1))
local aDist = GetDistanceBetweenCoords(coords["x"], coords["y"],coords["z"], markerlocation["x"],markerlocation["y"],markerlocation["z"])
if aDist < 10.0 then
DrawMarker(27,markerlocation["x"],markerlocation["y"],markerlocation["z"], 0, 0, 0, 0, 0, 0, 1.51, 1.51, 0.3, 212, 189, 0, 30, 0, 0, 2, 0, 0, 0, 0)
if aDist < 2.0 then
if IsDisabledControlJustReleased(0, 38) then
pickUpCash()
end
DrawText3Ds(markerlocation["x"],markerlocation["y"],markerlocation["z"], "Press [E] to pick up cash.")
else
DrawText3Ds(markerlocation["x"],markerlocation["y"],markerlocation["z"], "Get Closer to pick up the cash.")
end
end
end
end)
-- function DropItemPedBankCard()
-- local pos = GetEntityCoords(PlayerPedId())
-- local myluck = math.random(5)
-- if myluck == 1 then
-- TriggerEvent("player:receiveItem","securityblue",1)
-- elseif myluck == 2 then
-- TriggerEvent("player:receiveItem","securityblack",1)
-- elseif myluck == 3 then
-- TriggerEvent("player:receiveItem","securitygreen",1)
-- elseif myluck == 4 then
-- TriggerEvent("player:receiveItem","securitygold",1)
-- else
-- TriggerEvent("player:receiveItem","securityred",1)
-- end
-- end
RegisterNetEvent('sec:AddPeds')
AddEventHandler('sec:AddPeds', function(veh)
local cType = 's_m_m_highsec_01'
local pedmodel = GetHashKey(cType)
RequestModel(pedmodel)
while not HasModelLoaded(pedmodel) do
RequestModel(pedmodel)
Citizen.Wait(100)
end
ped2 = CreatePedInsideVehicle(veh, 4, pedmodel, 0, 1, 0.0)
DecorSetBool(ped2, 'ScriptedPed', true)
ped3 = CreatePedInsideVehicle(veh, 4, pedmodel, 1, 1, 0.0)
DecorSetBool(ped3, 'ScriptedPed', true)
ped4 = CreatePedInsideVehicle(veh, 4, pedmodel, 2, 1, 0.0)
DecorSetBool(ped4, 'ScriptedPed', true)
GiveWeaponToPed(ped2, GetHashKey('WEAPON_SpecialCarbine'), 420, 0, 1)
GiveWeaponToPed(ped3, GetHashKey('WEAPON_SpecialCarbine'), 420, 0, 1)
GiveWeaponToPed(ped4, GetHashKey('WEAPON_SpecialCarbine'), 420, 0, 1)
SetPedDropsWeaponsWhenDead(ped2,false)
SetPedRelationshipGroupDefaultHash(ped2,GetHashKey('COP'))
SetPedRelationshipGroupHash(ped2,GetHashKey('COP'))
SetPedAsCop(ped2,true)
SetCanAttackFriendly(ped2,false,true)
SetPedDropsWeaponsWhenDead(ped3,false)
SetPedRelationshipGroupDefaultHash(ped3,GetHashKey('COP'))
SetPedRelationshipGroupHash(ped3,GetHashKey('COP'))
SetPedAsCop(ped3,true)
SetCanAttackFriendly(ped3,false,true)
SetPedDropsWeaponsWhenDead(ped4,false)
SetPedRelationshipGroupDefaultHash(ped4,GetHashKey('COP'))
SetPedRelationshipGroupHash(ped4,GetHashKey('COP'))
SetPedAsCop(ped4,true)
SetCanAttackFriendly(ped4,false,true)
TaskCombatPed(ped2, GetPlayerPed(-1), 0, 16)
TaskCombatPed(ped3, GetPlayerPed(-1), 0, 16)
TaskCombatPed(ped4, GetPlayerPed(-1), 0, 16)
end)
local pickingup = false
function pickUpCash()
local gotcard = false
local alerted = false
local addedAdditionalTime = false
if not pickingup then
TriggerEvent("alert:noPedCheck", "banktruck")
local coords = GetEntityCoords(GetPlayerPed(-1))
-- Citizen.Trace("Doing Animation")
local length = 2
pickingup = true
RequestAnimDict("anim@mp_snowball")
while not HasAnimDictLoaded("anim@mp_snowball") do
Citizen.Wait(0)
end
while pickingup do
local coords2 = GetEntityCoords(GetPlayerPed(-1))
local aDist = GetDistanceBetweenCoords(coords["x"], coords["y"],coords["z"], coords2["x"],coords2["y"],coords2["z"])
if aDist > 1.0 or not pickup then
pickingup = false
end
if IsEntityPlayingAnim(GetPlayerPed(-1), "anim@mp_snowball", "pickup_snowball", 3) then
--ClearPedSecondaryTask(player)
else
TaskPlayAnim(GetPlayerPed(-1), "anim@mp_snowball", "pickup_snowball", 8.0, -8, -1, 49, 0, 0, 0, 0)
end
local chance = math.random(1,60)
if not alerted then
TriggerEvent("alert:noPedCheck", "banktruck")
alerted = true
end
if chance > 35 and not gotcard then
gotcard = true
DropItemPedBankCard()
end
if chance < 30 then
TriggerEvent("player:receiveItem","band",math.random(length))
end
TriggerEvent("player:receiveItem","rollcash",math.random(length))
local waitMin = 4000
local waitMax = 6000
Wait(waitMin, waitMax)
length = length + 1
if length > 15 then
length = 15
end
end
additionalWait = 0
ClearPedTasks(GetPlayerPed(-1))
end
end
RegisterNetEvent('sec:AttemptHeist')
AddEventHandler('sec:AttemptHeist', function(veh)
attempted = veh
SetEntityAsMissionEntity(attempted,true,true)
local plate = GetVehicleNumberPlateText(veh)
TriggerServerEvent("sec:checkRobbed",plate)
end)
RegisterNetEvent('sec:AllowHeist')
AddEventHandler('sec:AllowHeist', function()
TriggerServerEvent('banktruckrobbery:log')
TriggerEvent("sec:AddPeds",attempted)
SetVehicleDoorOpen(attempted, 2, 0, 0)
SetVehicleDoorOpen(attempted, 3, 0, 0)
TriggerEvent("sec:PickupCash")
end)
function DrawText3Ds(x,y,z, text)
local onScreen,_x,_y=World3dToScreen2d(x,y,z)
local px,py,pz=table.unpack(GetGameplayCamCoords())
SetTextScale(0.35, 0.35)
SetTextFont(4)
SetTextProportional(1)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(1)
AddTextComponentString(text)
DrawText(_x,_y)
local factor = (string.len(text)) / 370
DrawRect(_x,_y+0.0125, 0.015+ factor, 0.03, 41, 11, 41, 68)
end
--TaskCombatPed(ped, GetPlayerPed(-1), 0, 16)
function FindEndPointCar(x,y)
local randomPool = 50.0
while true do
if (randomPool > 2900) then
return
end
local vehSpawnResult = {}
vehSpawnResult["x"] = 0.0
vehSpawnResult["y"] = 0.0
vehSpawnResult["z"] = 30.0
vehSpawnResult["x"] = x + math.random(randomPool - (randomPool * 2),randomPool) + 1.0
vehSpawnResult["y"] = y + math.random(randomPool - (randomPool * 2),randomPool) + 1.0
roadtest, vehSpawnResult, outHeading = GetClosestVehicleNode(vehSpawnResult["x"], vehSpawnResult["y"], vehSpawnResult["z"], 0, 55.0, 55.0)
Citizen.Wait(1000)
if vehSpawnResult["z"] ~= 0.0 then
local caisseo = GetClosestVehicle(vehSpawnResult["x"], vehSpawnResult["y"], vehSpawnResult["z"], 20.000, 0, 70)
if not DoesEntityExist(caisseo) then
return vehSpawnResult["x"], vehSpawnResult["y"], vehSpawnResult["z"], outHeading
end
end
randomPool = randomPool + 50.0
end
--endResult["x"], endResult["y"], endResult["z"]
end |
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
test_vector_target = class({})
LinkLuaModifier( "modifier_test_vector_target", "lua_abilities/test_vector_target/modifier_test_vector_target", LUA_MODIFIER_MOTION_NONE )
function test_vector_target:GetBehavior()
return DOTA_ABILITY_BEHAVIOR_POINT + DOTA_ABILITY_BEHAVIOR_VECTOR_TARGETING
end
--------------------------------------------------------------------------------
-- Make Vector Targeting work
test_vector_target.position_init = nil
test_vector_target.position_end = nil
test_vector_target.first_cast = true
test_vector_target.prev_time = 0
function test_vector_target:CastFilterResultLocation( loc )
if IsServer() then
-- if reached this part, it must be first cast
self.first_cast = true
-- check time elapsed. If it is bigger than last frame time, assumed that it is a new cast
local a = GameRules:GetGameTime()-self.prev_time
local b = GameRules:GetGameFrameTime()
if a>b then
-- reset start and end position
self.position_init = nil
end
self.prev_time = GameRules:GetGameTime()
-- check if init is nil
if not self.position_init then
self.position_init = loc
else
self.position_end = loc
end
end
return UF_SUCCESS
end
function test_vector_target:OnAbilityPhaseStart()
if self.first_cast then
-- cast second time
self:GetCaster():CastAbilityOnPosition( self.position_init, self, self:GetCaster():GetPlayerOwnerID() )
self:PlayEffects2( self.position_init )
-- not first cast anymore
self.first_cast = false
return false
else
-- second cast
return true
end
end
function test_vector_target:GetCastRange( loc, target )
if self.first_cast then
return 0
end
return self.BaseClass.GetCastRange( self, loc, target )
end
function test_vector_target:GetCastPoint()
return 0
end
--------------------------------------------------------------------------------
-- Ability Start
function test_vector_target:OnSpellStart()
-- unit identifier
local caster = self:GetCaster()
self:PlayEffects( self.position_init, 100 )
self:PlayEffects( self.position_end, 100 )
self.position_init = nil
self.position_end = nil
end
function test_vector_target:PlayEffects( position, radius )
-- get resources
local particle_cast = "particles/units/heroes/hero_nevermore/nevermore_shadowraze.vpcf"
-- local radius = 100
-- create particle
local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_WORLDORIGIN, nil )
ParticleManager:SetParticleControl( effect_cast, 0, position )
ParticleManager:SetParticleControl( effect_cast, 1, Vector( radius, 1, 1 ) )
ParticleManager:ReleaseParticleIndex( effect_cast )
end
function test_vector_target:PlayEffects2( position )
-- Get Resources
local particle_cast = "particles/units/heroes/hero_tinker/tinker_motm.vpcf"
-- Create Particle
local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_WORLDORIGIN, nil )
ParticleManager:SetParticleControl( effect_cast, 0, position )
ParticleManager:ReleaseParticleIndex( effect_cast )
end |
-- VARIABLES ===================================================================
local owner_transform = nil
local owner_CircleParticle = nil
local timer = 0
RunTime = 0.1
--emitRate = 150
-- FUNCTIONS ===================================================================
function Constructor()
owner_CircleParticle = owner:GetComponent("ParticleEmitter_Circle")
owner_transform = owner:GetComponent("Transform")
end
function OnUpdate(dt)
if (timer < RunTime) then
timer = timer + dt
else
owner_CircleParticle:SetEmitRate(0)
owner:Destroy()
end
--Debug purposes
--if (IsKeyPressed(KEY_1)) then
-- timer = 0
-- owner_CircleParticle:SetEmitRate(emitRate)
--end
end |
-- Copyright (C) Dejiang Zhu(doujiang24)
local response = require "resty.kafka.response"
local auth_utils = require "resty.kafka.auth.init"
local to_int32 = response.to_int32
local setmetatable = setmetatable
local tcp = ngx.socket.tcp
local ngx_log = ngx.log
local _M = {}
local mt = { __index = _M }
local function _sock_send_receive(sock, request)
local bytes, err = sock:send(request:package())
if not bytes then
return nil, err, true
end
-- Reading a 4 byte `message_size`
local len, err = sock:receive(4)
if not len then
if err == "timeout" then
sock:close()
return nil, err
end
return nil, err, true
end
local data, err = sock:receive(to_int32(len))
if not data then
if err == "timeout" then
sock:close()
return nil, err, true
end
end
return response:new(data, request.api_version), nil, true
end
function _M.new(self, host, port, socket_config, auth_config)
return setmetatable({
host = host,
port = port,
config = socket_config,
auth = auth_config or nil,
}, mt)
end
function _M.send_receive(self, request)
local sock, err = tcp()
if not sock then
return nil, err, true
end
local keepalive = self.config.keepalive or false
sock:settimeout(self.config.socket_timeout)
local ok, err = sock:connect(self.host, self.port)
if not ok then
return nil, err, true
end
if self.config.ssl then
-- TODO: add reused_session for better performance of short-lived connections
local opts = {
ssl_verify = self.config.ssl_verify,
client_cert = self.config.client_cert,
client_priv_key = self.config.client_priv_key,
}
-- TODO END
local _, err = sock:tlshandshake(opts)
if err then
return nil, "failed to do SSL handshake with " ..
self.host .. ":" .. tostring(self.port) .. ": " .. err, true
end
end
-- authenticate if auth config is passed and socked connection is new
if self.auth and sock:getreusedtimes() == 0 then -- SASL AUTH
local ok, auth, err
auth, err = auth_utils.new(self.auth)
if not auth then
return nil, err
end
ok, err = auth:authenticate(sock)
if not ok then
local msg = "failed to do " .. self.auth.mechanism .." auth with " ..
self.host .. ":" .. tostring(self.port) .. ": " .. err, true
return nil, msg
end
end
local data, err, f = _sock_send_receive(sock, request)
if keepalive then
ngx_log(ngx.DEBUG, "storing sock in pool to keep-alive")
sock:setkeepalive(self.config.keepalive_timeout, self.config.keepalive_size)
end
return data, err, f
end
return _M
|
package.cpath = "../?.so"
package.path = "../?.lua";
function valid()
local encodings = require "util.encodings";
local utf8 = assert(encodings.utf8, "no encodings.utf8 module");
for line in io.lines("utf8_sequences.txt") do
local data = line:match(":%s*([^#]+)"):gsub("%s+", ""):gsub("..", function (c) return string.char(tonumber(c, 16)); end)
local expect = line:match("(%S+):");
if expect ~= "pass" and expect ~= "fail" then
error("unknown expectation: "..line:match("^[^:]+"));
end
local valid = utf8.valid(data);
assert_equal(valid, utf8.valid(data.." "));
assert_equal(valid, expect == "pass", line);
end
end
|
object_tangible_wearables_jacket_jacket_ace_imperial_craft = object_tangible_wearables_jacket_shared_jacket_ace_imperial_craft:new {
}
ObjectTemplates:addTemplate(object_tangible_wearables_jacket_jacket_ace_imperial_craft, "object/tangible/wearables/jacket/jacket_ace_imperial_craft.iff") |
local config = require 'goldsmith.config'
local log = require 'goldsmith.log'
local M = {}
-- 'current' is simply the most recent 'go' buffer to have been used
local current
local all = {}
local default_action_map = {
godef = { act = "<cmd>lua require'goldsmith.cmds.lsp'.goto_definition()<cr>", ft = { 'go' } },
hover = { act = "<cmd>lua require'goldsmith.cmds.lsp'.hover()<cr>", ft = { 'go' } },
goimplementation = { act = "<cmd>lua require'goldsmith.cmds.lsp'.goto_implementation()<cr>", ft = { 'go' } },
sighelp = { act = "<cmd>lua require'goldsmith.cmds.lsp'.signature_help()<cr>", ft = { 'go' } },
['add-ws-folder'] = { act = "<cmd>lua require'goldsmith.cmds.lsp'.add_workspace_folder()<cr>", ft = '*' },
['rm-ws-folder'] = { act = "<cmd>lua require'goldsmith.cmds.lsp'.remove_workspace_folder()<cr>", ft = '*' },
['list-ws-folders'] = { act = "<cmd>lua require'goldsmith.cmds.lsp'.list_workspace_folders()<cr>", ft = '*' },
typedef = { act = "<cmd>lua require'goldsmith.cmds.lsp'.type_definition()<cr>", ft = { 'go' } },
rename = { act = "<cmd>lua require'goldsmith.cmds.lsp'.rename()<cr>", ft = { 'go' } },
goref = { act = "<cmd>lua require'goldsmith.cmds.lsp'.references()<cr>", ft = { 'go' } },
codeaction = { act = "<cmd>lua require'goldsmith.cmds.lsp'.code_action()<cr>", ft = '*' },
showdiag = { act = "<cmd>lua require'goldsmith.cmds.lsp'.show_diagnostics()<cr>", ft = '*' },
prevdiag = { act = "<cmd>lua require'goldsmith.cmds.lsp'.goto_previous_diagnostic()<cr>", ft = '*' },
nextdiag = { act = "<cmd>lua require'goldsmith.cmds.lsp'.goto_next_diagnostic()<cr>", ft = '*' },
setloclist = { act = "<cmd>lua require'goldsmith.cmds.lsp'.diag_set_loclist()<cr>", ft = '*' },
format = { act = "<cmd>lua require'goldsmith.cmds.format'.run(1)<cr>", ft = '*' },
['toggle-debug-console'] = { act = "<cmd>lua require'goldsmith.log'.toggle_debug_console()<cr>", ft = '*' },
['test-close-window'] = { act = "<cmd>lua require'goldsmith.winbuf'.close_window('test')<cr>", ft = { 'go' } },
['test-last'] = { act = "<cmd>lua require'goldsmith.testing'.last()<cr>", ft = { 'go' } },
['test-visit'] = { act = "<cmd>lua require'goldsmith.testing'.visit()<cr>", ft = { 'go' } },
['test-nearest'] = { act = "<cmd>lua require'goldsmith.testing'.nearest()<cr>", ft = { 'go' } },
['test-suite'] = { act = "<cmd>lua require'goldsmith.testing'.suite()<cr>", ft = { 'go' } },
['test-pkg'] = { act = "<cmd>lua require'goldsmith.testing'.pkg()<cr>", ft = { 'go' } },
['test-b-nearest'] = { act = "<cmd>lua require'goldsmith.testing'.nearest({type='bench'})<cr>", ft = { 'go' } },
['test-b-suite'] = { act = "<cmd>lua require'goldsmith.testing'.suite({type='bench'})<cr>", ft = { 'go' } },
['test-b-pkg'] = { act = "<cmd>lua require'goldsmith.testing'.pkg({type='bench'})<cr>", ft = { 'go' } },
['test-a-nearest'] = { act = "<cmd>lua require'goldsmith.testing'.nearest({type='any'})<cr>", ft = { 'go' } },
['test-a-suite'] = { act = "<cmd>lua require'goldsmith.testing'.suite({type='any'})<cr>", ft = { 'go' } },
['test-a-pkg'] = { act = "<cmd>lua require'goldsmith.testing'.pkg({type='any'})<cr>", ft = { 'go' } },
['alt-file'] = { act = "<cmd>lua require'goldsmith.cmds.alt'.run()<cr>", ft = { 'go' } },
['alt-file-force'] = { act = "<cmd>lua require'goldsmith.cmds.alt'.run('!')<cr>", ft = { 'go' } },
['fillstruct'] = { act = "<cmd>lua require'goldsmith.cmds.fillstruct'.run(1000)<cr>", ft = { 'go' } },
['codelens-on'] = { act = "<cmd>lua require'goldsmith.cmds.lsp'.turn_on_codelens()<cr>", ft = '*' },
['codelens-off'] = { act = "<cmd>lua require'goldsmith.cmds.lsp'.turn_off_codelens()<cr>", ft = '*' },
['codelens-run'] = { act = "<cmd>lua require'goldsmith.cmds.lsp'.run_codelens()<cr>", ft = '*' },
['sym-highlight-on'] = {
act = "<cmd>lua require'goldsmith.cmds.lsp'.turn_on_symbol_highlighting()<cr>",
ft = { 'go' },
},
['sym-highlight-off'] = {
act = "<cmd>lua require'goldsmith.cmds.lsp'.turn_off_symbol_highlighting()<cr>",
ft = { 'go' },
},
['sym-highlight'] = { act = "<cmd>lua require'goldsmith.cmds.lsp'.highlight_current_symbol()<cr>", ft = { 'go' } },
['start-follow'] = { act = "<cmd>lua require'goldsmith.winbuf'.start_follow_buffer()<cr>" },
['stop-follow'] = { act = "<cmd>lua require'goldsmith.winbuf'.stop_follow_buffer()<cr>" },
['close-terminal'] = { act = "<cmd>lua require'goldsmith.winbuf'.close_window('job_terminal')<cr>", ft = '*' },
['build'] = { act = "<cmd>lua require'goldsmith.cmds.build'.run()<cr>", ft = '*' },
['run'] = { act = "<cmd>lua require'goldsmith.cmds.run'.run()<cr>", ft = '*' },
['build-last'] = { act = "<cmd>lua require'goldsmith.cmds.build'.last()<cr>", ft = '*' },
['run-last'] = { act = "<cmd>lua require'goldsmith.cmds.run'.last()<cr>", ft = '*' },
['close-any'] = { act = "<cmd>lua require'goldsmith.winbuf'.close_any_window(false)<cr>", ft = '*' },
['super-close-any'] = { act = "<cmd>lua require'goldsmith.winbuf'.close_any_window(true)<cr>", ft = '*' },
['coverage'] = {
act = "<cmd>lua require'goldsmith.cmds.coverage'.run({bang='<bang>',type='job'})<cr>",
ft = { 'go' },
},
['coverage-browser'] = {
act = "<cmd>lua require'goldsmith.cmds.coverage'.run({bang='<bang>',type='web'})<cr>",
ft = { 'go' },
},
['coverage-on'] = { act = "<cmd>lua require'goldsmith.cmds.coverage'.on()<cr>", ft = { 'go' } },
['coverage-off'] = { act = "<cmd>lua require'goldsmith.cmds.coverage'.off()<cr>", ft = { 'go' } },
['coverage-files'] = { act = "<cmd>lua require'goldsmith.cmds.coverage'.show_files()<cr>", ft = { 'go' } },
['telescope-go-files'] = { act = "<cmd>lua require'goldsmith.telescope'.go_files()<cr>", ft = '*' },
['telescope-go-test-files'] = { act = "<cmd>lua require'goldsmith.telescope'.go_test_files()<cr>", ft = '*' },
['telescope-go-code-files'] = { act = "<cmd>lua require'goldsmith.telescope'.go_code_files()<cr>", ft = '*' },
['telescope-go-covered-files'] = { act = "<cmd>lua require'goldsmith.telescope'.go_covered_files()<cr>", ft = '*' },
['contextual-help'] = { act = "<cmd>lua require'goldsmith.cmds.contextualhelp'.run()<cr>", ft = { 'go' } },
}
function M.checkin(b)
current = b
all[current] = current
end
-- return the most recent buffer if it is valid, otherwise just return any of the registered buffers
-- assuming it is valid
function M.get_valid_buffer()
if current ~= nil and vim.api.nvim_buf_is_valid(M.current) then
return current
end
for _, buf in pairs(all) do
-- maybe nvim_buf_is_loaded would be sufficient?
if vim.api.nvim_buf_is_valid(buf) then
return buf
else
all[buf] = nil
end
end
end
function M.set_project_root()
local rootdir = require('lspconfig.util').root_pattern(unpack(config.get('system', 'root_dir')))(vim.fn.expand '%:p')
or vim.fn.expand '%:p:h'
vim.cmd(string.format('lcd %s', rootdir))
log.debug('Autoconfig', string.format('root dir: %s', rootdir))
return rootdir
end
function M.set_omnifunc(b)
vim.api.nvim_buf_set_option(b, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
end
-- for use in non-go related buffers
function M.set_buffer_map(buf, mode, name, user_act, opts)
local act = user_act or default_action_map[name].act
local maps = config.get_mapping(name)
for _, km in ipairs(maps) do
vim.api.nvim_buf_set_keymap(buf, mode, km, act, opts or {})
end
end
function M.set_buffer_keymaps(buf)
local function set_map(name, modes, maps, action, opts)
local plug = string.format('<Plug>(goldsmith-%s)', name)
for _, mode in ipairs(modes) do
vim.api.nvim_buf_set_keymap(buf, mode, plug, action, opts)
end
for _, km in ipairs(maps) do
for _, mode in ipairs(modes) do
vim.api.nvim_buf_set_keymap(buf, mode, km, plug, {})
end
end
end
local ft = vim.opt.filetype:get()
local opts = { noremap = true, silent = true }
for name, d in pairs(default_action_map) do
local maps = config.get_mapping(name)
if d.ft and (d.ft == '*' or vim.tbl_contains(d.ft, ft)) then
set_map(name, d.m or { 'n' }, maps, d.act, opts)
end
end
return true
end
function M.is_managed_buffer()
local b = vim.api.nvim_get_current_buf()
if all[b] ~= nil then
return true
end
return false
end
function M.setup()
local b = vim.api.nvim_get_current_buf()
M.checkin(b)
if not pcall(M.set_project_root) then
log.error('Autoconfig', 'Failed to set project root. Is lspconfig installed?')
end
local omni = config.get('completion', 'omni')
if omni then
M.set_omnifunc(b)
end
M.set_buffer_keymaps(b)
end
return M
|
require('heine').load()
|
data:extend({
{
type = "mining-drill",
name = "hydraulic-mining-drill",
icon = "__Hydraulic_Mining_Drill__/graphics/icons/mining-drill/hydraulic-mining-drill.png",
flags = {"placeable-neutral", "player-creation"},
resource_categories = {"basic-solid"},
minable = {mining_time = 1, result = "hydraulic-mining-drill"},
max_health = 100,
corpse = "medium-remnants",
collision_box = {{ -0.9, -0.9}, {0.9, 0.9}},
selection_box = {{ -1, -1}, {1, 1}},
mining_speed = 0.25,
module_specification =
{
module_slots = 6,
module_info_icon_shift = {0, 0.5},
module_info_multi_row_initial_height_modifier = -0.3
},
working_sound =
{
sound =
{
filename = "__base__/sound/burner-mining-drill.ogg",
volume = 0.8
},
},
energy_source =
{
type = "electric",
-- will produce this much * energy pollution units per tick
emissions = 1000 / 2.5,
usage_priority = "primary-input"
},
energy_usage = "0.01kW",
mining_power = 3,
animations =
{
north =
{
filename = "__Hydraulic_Mining_Drill__/graphics/entity/mining_drill/north.png",
priority = "high",
width = 110,
height = 76,
frame_count = 32,
line_length = 4,
shift = {0.6875, -0.09375},
animation_speed = 0.5
},
east =
{
priority = "extra-high",
width = 94,
height = 74,
line_length = 4,
shift = {0.4375, -0.09375},
filename = "__Hydraulic_Mining_Drill__/graphics/entity/mining_drill/east.png",
frame_count = 32,
animation_speed = 0.5
},
south =
{
priority = "extra-high",
width = 89,
height = 88,
line_length = 4,
shift = {0.40625, 0},
filename = "__Hydraulic_Mining_Drill__/graphics/entity/mining_drill/south.png",
frame_count = 32,
animation_speed = 0.5
},
west =
{
priority = "extra-high",
width = 91,
height = 78,
line_length = 4,
shift = {0.09375, -0.0625},
filename = "__Hydraulic_Mining_Drill__/graphics/entity/mining_drill/west.png",
frame_count = 32,
animation_speed = 0.5
}
},
resource_searching_radius = 0.99,
vector_to_place_result = {-0.5, -1.3},
fast_replaceable_group = "mining-drill"
},
{
type = "assembling-machine",
name = "helper-tank",
icon = "__Hydraulic_Mining_Drill__/graphics/nil.png",
flags = {"placeable-neutral", "placeable-player", "player-creation"},
minable = {mining_time = 1, result = "iron-plate"},
max_health = 500,
order = "a",
selectable_in_game = false,
corpse = "medium-remnants",
collision_box = {{-0.9, -0.9}, {0.9, 0.9}},
selection_box = {{ -1, -1}, {1, 1}},
crafting_categories = {"hydraulic-mining"},
--crafting_categories = {"crafting", "advanced-crafting", "crafting-with-fluid"},
crafting_speed = 1,
ingredient_count = 2,
module_specification =
{
--module_slots = 6,
--module_info_icon_shift = {0, 0.5},
--module_info_multi_row_initial_height_modifier = -0.3
},
allowed_effects = {"consumption", "speed", "pollution"},
corpse = "small-remnants",
fluid_boxes =
{
{
production_type = "input",
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = -1,
pipe_connections = {{ type="input", position = {-0.5, 1.5} }}
},
--{
--[[production_type = "output",
--pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = 1,
pipe_connections = {{ type="output", position = {-0.5, -1.5} }}]]--
--},
off_when_no_fluid_recipe = false
},
--[[working_sound =
{
sound =
{
filename = "__base__/sound/burner-mining-drill.ogg",
volume = 0
},
},--]]
energy_source =
{
type = "electric",
usage_priority = "secondary-input",
emissions = 0
},
energy_usage = "0.01kW",
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
animation =
{
north =
{
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
priority = "high",
width = 1000,
height = 1000,
frame_count = 1,
--line_length = 4,
--shift = {0.6875, -0.09375},
},
east =
{
priority = "extra-high",
width = 1000,
height = 1000,
-- line_length = 4,
-- shift = {0.4375, -0.09375},
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
frame_count = 1,
},
south =
{
priority = "extra-high",
width = 1000,
height = 1000,
--line_length = 4,
--shift = {0.40625, 0},
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
frame_count = 1,
},
west =
{
priority = "extra-high",
width = 1000,
height = 1000,
-- line_length = 4,
--shift = {0.09375, -0.0625},
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
frame_count = 1,
}
}
},
{
type = "electric-pole",
name = "helper-pole",
icon = "__Hydraulic_Mining_Drill__/graphics/nil.png",
flags = {"placeable-neutral", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "small-electric-pole"},
max_health = 35,
order = "a",
selectable_in_game = false,
corpse = "small-remnants",
collision_box = {{-0.1, -0.1}, {0.1, 0.1}},
selection_box = {{-0.1, -0.1}, {0.1, 0.1}},
drawing_box = {{-0.1, -0.1}, {0.1, 0.1}},
maximum_wire_distance = 0,
supply_area_distance = 0.5,
vehicle_impact_sound = { filename = "__base__/sound/car-wood-impact.ogg", volume = 1.0 },
pictures =
{
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
priority = "extra-high",
width = 32,
height = 32,
direction_count = 1,
},
connection_points =
{
{
shadow =
{
copper = {2.7, 0},
red = {2.3, 0},
green = {3.1, 0}
},
wire =
{
copper = {0, -2.7},
red = {-0.4,-2.7},
green = {0.4,-2.7}
}
},
},
radius_visualisation_picture =
{
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
width = 32,
height = 32,
priority = "extra-high-no-scale"
}
},
{
type = "generator",
name = "helper-panel",
icon = "__Hydraulic_Mining_Drill__/graphics/nil.png",
flags = {"placeable-neutral","player-creation"},
minable = {mining_time = 1, result = "steam-engine"},
max_health = 300,
selectable_in_game = false,
order = "a",
corpse = "big-remnants",
dying_explosion = "medium-explosion",
effectivity = 1,
fluid_usage_per_tick = 0.00001,
resistances =
{
{
type = "fire",
percent = 70
}
},
fluid_box = {
base_area = 100,
pipe_connections =
{
{ position = {0, -0.1} },
},
},
collision_box = {{-0.1, -0.1}, {0.1, 0.1}},
selection_box = {{-0.1, -0.1}, {0.1, 0.1}},
energy_source =
{
type = "electric",
usage_priority = "secondary-output"
},
horizontal_animation =
{
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
width = 246,
height = 137,
frame_count = 1,
line_length = 1,
},
vertical_animation =
{
filename = "__Hydraulic_Mining_Drill__/graphics/nil.png",
width = 155,
height = 186,
frame_count = 1,
line_length = 1,
},
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
min_perceived_performance = 0.25,
}
}) |
-- global stuff
require('console').init()
require('overrides').init()
-- ensure IPC is there
hs.ipc.cliInstall()
-- lower logging level for hotkeys
require('hs.hotkey').setLogLevel("warning")
-- global config
config = {
apps = {
terms = { 'kitty' },
browsers = { 'Google Chrome', 'Safari' }
},
wm = {
defaultDisplayLayouts = {
['Color LCD'] = 'monocle',
['DELL U3818DW'] = 'main-center'
},
displayLayouts = {
['Color LCD'] = { 'monocle', 'main-right', 'side-by-side' },
['DELL U3818DW'] = { 'main-center', 'main-right', 'side-by-side' }
}
},
window = {
highlightBorder = false,
highlightMouse = true,
historyLimit = 0
},
network = {
home = 'Skynet 5G'
},
homebridge = {
studioSpeakers = { aid = 10, iid = 11, name = "Studio Speakers" },
studioLights = { aid = 9, iid = 11, name = "Studio Lights" },
tvLights = { aid = 6, iid = 11, name = "TV Lights" }
}
}
-- requires
bindings = require('bindings')
controlplane = require('utils.controlplane')
watchables = require('utils.watchables')
watchers = require('utils.watchers')
wm = require('utils.wm')
-- no animations
hs.window.animationDuration = 0.0
-- hints
hs.hints.fontName = 'Helvetica-Bold'
hs.hints.fontSize = 22
hs.hints.hintChars = { 'A', 'S', 'D', 'F', 'J', 'K', 'L', 'Q', 'W', 'E', 'R', 'Z', 'X', 'C' }
hs.hints.iconAlpha = 1.0
hs.hints.showTitleThresh = 0
-- controlplane
controlplane.enabled = { 'autohome', 'automount' }
-- watchers
watchers.enabled = { 'urlevent' }
watchers.urlPreference = config.apps.browsers
-- bindings
bindings.enabled = { 'ask-before-quit', 'block-hide', 'ctrl-esc', 'f-keys', 'focus', 'global', 'tiling', 'term-ctrl-i', 'viscosity' }
bindings.askBeforeQuitApps = config.apps.browsers
-- start/stop modules
local modules = { bindings, controlplane, watchables, watchers, wm }
hs.fnutils.each(modules, function(module)
if module then module.start() end
end)
-- stop modules on shutdown
hs.shutdownCallback = function()
hs.fnutils.each(modules, function(module)
if module then module.stop() end
end)
end
|
local installer = require "nvim-lsp-installer.core.installer"
local std = require "nvim-lsp-installer.core.managers.std"
local client = require "nvim-lsp-installer.core.managers.github.client"
local platform = require "nvim-lsp-installer.platform"
local M = {}
---@param repo string
---@param asset_file string
---@param release string
local function with_release_file_receipt(repo, asset_file, release)
return function()
local ctx = installer.context()
ctx.receipt:with_primary_source {
type = "github_release_file",
repo = repo,
file = asset_file,
release = release,
}
end
end
---@async
---@param opts {repo: string, version: Optional|nil, asset_file: string|fun(release: string):string}
function M.release_file(opts)
local ctx = installer.context()
local release = (opts.version or ctx.requested_version):or_else_get(function()
return client.fetch_latest_release(opts.repo)
:map(function(release)
return release.tag_name
end)
:get_or_throw "Failed to fetch latest release from GitHub API."
end)
---@type string
local asset_file = type(opts.asset_file) == "function" and opts.asset_file(release) or opts.asset_file
if not asset_file then
error(
(
"Could not find which release file to download. Most likely the current operating system, architecture (%s), or libc (%s) is not supported."
):format(platform.arch, platform.get_libc())
)
end
local download_url = ("https://github.com/%s/releases/download/%s/%s"):format(opts.repo, release, asset_file)
return {
release = release,
download_url = download_url,
asset_file = asset_file,
with_receipt = with_release_file_receipt(opts.repo, download_url, release),
}
end
---@param filename string
---@param processor async fun()
local function release_file_processor(filename, processor)
---@async
---@param opts {repo: string, asset_file: string|fun(release: string):string}
return function(opts)
local release_file_source = M.release_file(opts)
std.download_file(release_file_source.download_url, filename)
processor(release_file_source)
return release_file_source
end
end
M.unzip_release_file = release_file_processor("archive.zip", function()
std.unzip("archive.zip", ".")
end)
M.untarxz_release_file = release_file_processor("archive.tar.xz", function()
std.untarxz "archive.tar.xz"
end)
M.untargz_release_file = release_file_processor("archive.tar.gz", function()
std.untar "archive.tar.gz"
end)
---@async
---@param opts {repo: string, out_file:string, asset_file: string|fun(release: string):string}
function M.gunzip_release_file(opts)
local release_file_source = M.release_file(opts)
std.download_file(
release_file_source.download_url,
("%s.gz"):format(assert(opts.out_file, "out_file must be specified"))
)
std.gunzip(opts.out_file)
return release_file_source
end
return M
|
local ELEVATOR_SYSTEM = script:GetCustomProperty("ElevatorSystem"):WaitForObject()
local ELEVATOR = script:GetCustomProperty("Elevator"):WaitForObject()
local AUTOACTIVE_TRIGGER = script:GetCustomProperty("AutoActiveTrigger"):WaitForObject() -- Keppu (Antti) Apr. 5 2021 New addition to make the elevator usage more streamlined
local BOTTOM_TRIGGER = script:GetCustomProperty("BottomTrigger"):WaitForObject()
local TOP_TRIGGER = script:GetCustomProperty("TopTrigger"):WaitForObject()
local ELEVATOR_TRIGGER = script:GetCustomProperty("ElevatorTrigger"):WaitForObject()
local BOTTOM_LANDING = script:GetCustomProperty("BottomLanding"):WaitForObject()
local TOP_LANDING = script:GetCustomProperty("TopLanding"):WaitForObject()
local SPEED = ELEVATOR_SYSTEM:GetCustomProperty("Speed")
local ACTIVATION_DELAY = ELEVATOR_SYSTEM:GetCustomProperty("ActivationDelay")
local BOTTOM_POSITION = BOTTOM_LANDING:GetWorldPosition()
local TOP_POSITION = TOP_LANDING:GetWorldPosition()
local MOVE_DURATION = (TOP_POSITION.z - BOTTOM_POSITION.z) / SPEED
local WAIT_DURATION = script:GetCustomProperty("WaitDuration")-- Keppu (Antti) Apr. 6 2021
local UPELEVATOR = script:GetCustomProperty("UpElevator")-- Keppu (Antti) Apr. 6 2021
local isMoving = false
local isAtBottom = true -- Or moving towards the bottom
function SendElevator(toBottom)
isMoving = true
isAtBottom = toBottom
BOTTOM_TRIGGER.collision = Collision.FORCE_OFF
TOP_TRIGGER.collision = Collision.FORCE_OFF
ELEVATOR_TRIGGER.collision = Collision.FORCE_OFF
Task.Wait(ACTIVATION_DELAY)
if toBottom then
ELEVATOR:MoveTo(BOTTOM_POSITION, MOVE_DURATION)
else
ELEVATOR:MoveTo(TOP_POSITION, MOVE_DURATION)
end
Task.Wait(MOVE_DURATION)
if isAtBottom then
TOP_TRIGGER.collision = Collision.INHERIT
else
BOTTOM_TRIGGER.collision = Collision.INHERIT
end
ELEVATOR_TRIGGER.collision = Collision.INHERIT
isMoving = false
Task.Wait(WAIT_DURATION) -- Keppu (Antti) Apr. 6 2021
if UPELEVATOR then SendElevator(true) else SendElevator(false) end -- Keppu (Antti) Apr. 6 2021
end
function OnInteracted_Bottom(trigger, player)
if not isMoving and not isAtBottom then
SendElevator(true)
end
end
function OnInteracted_Top(trigger, player)
if not isMoving and isAtBottom then
SendElevator(false)
end
end
function OnInteracted_Elevator(trigger, player)
if not isMoving then
SendElevator(not isAtBottom)
end
end
BOTTOM_TRIGGER.interactedEvent:Connect(OnInteracted_Bottom)
TOP_TRIGGER.interactedEvent:Connect(OnInteracted_Top)
ELEVATOR_TRIGGER.interactedEvent:Connect(OnInteracted_Elevator)
-- Keppu (Antti) Apr. 5 2021 New addition to make the elevator usage more streamlined
function OnEndOverlap(theTrigger, player)
end
function OnBeginOverlap(theTrigger, player)
if (not player or not player:IsA("Player")) then return
else
SendElevator(not isAtBottom)
end
end
AUTOACTIVE_TRIGGER.beginOverlapEvent:Connect(OnBeginOverlap)
Task.Wait(1)
if not UPELEVATOR then SendElevator(false) end
|
local WIRE_SCROLL_SPEED = 0.5
local WIRE_BLINKS_PER_SECOND = 2
local CurPathEnt = {}
local Wire_DisableWireRender = 0
WireLib.Wire_GrayOutWires = false
WIRE_CLIENT_INSTALLED = 1
--Msg("loading materials\n")
list.Add("WireMaterials", "cable/rope_icon")
list.Add("WireMaterials", "cable/cable2")
list.Add("WireMaterials", "cable/xbeam")
list.Add("WireMaterials", "cable/redlaser")
list.Add("WireMaterials", "cable/blue_elec")
list.Add("WireMaterials", "cable/physbeam")
list.Add("WireMaterials", "cable/hydra")
--new wire materials by Acegikmo
list.Add("WireMaterials", "arrowire/arrowire")
list.Add("WireMaterials", "arrowire/arrowire2")
local mats = {
["tripmine_laser"] = Material("tripmine_laser"),
["Models/effects/comball_tape"] = Material("Models/effects/comball_tape")
}
for _, mat in pairs(list.Get("WireMaterials")) do
--Msg("loading material: ",mat,"\n")
mats[mat] = Material(mat)
end
local function getmat(mat)
if mats[mat] == nil then
mats[mat] = Material(mat)
end
return mats[mat]
end
local beam_mat = mats["tripmine_laser"]
local beamhi_mat = mats["Models/effects/comball_tape"]
local lastrender, scroll, shouldblink = 0, 0, false
function Wire_Render(ent)
if (Wire_DisableWireRender == 0) then
local wires = ent.WirePaths
if wires then
if next(wires) then
local t = CurTime()
if lastrender ~= t then
local w, f = math.modf(t * WIRE_BLINKS_PER_SECOND)
shouldblink = f < 0.5
scroll = t * WIRE_SCROLL_SPEED
lastrender = t
end
local blink = shouldblink and ent:GetNW2String("BlinkWire")
for net_name, wiretbl in pairs(wires) do
local width = wiretbl.Width
if width > 0 and blink ~= net_name then
local start = wiretbl.StartPos
if IsValid(ent) then
start = ent:LocalToWorld(start)
end
local color = wiretbl.Color
if WireLib.Wire_GrayOutWires then
local h, s, v = ColorToHSV(color)
v = 0.175
local tmpColor = HSVToColor(h, s, v)
color = Color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a) -- HSVToColor does not return a proper Color structure.
end
local nodes = wiretbl.Path
local len = #nodes
if len > 0 then
render.SetMaterial(getmat(wiretbl.Material))
render.StartBeam(len * 2 + 1)
render.AddBeam(start, width, scroll, color)
for j = 1, len do
local node = nodes[j]
local node_ent = node.Entity
if IsValid(node_ent) then
local endpos = node_ent:LocalToWorld(node.Pos)
scroll = scroll + (endpos - start):Length() / 10
render.AddBeam(endpos, width, scroll, color)
render.AddBeam(endpos, width, scroll, color) -- A second beam in the same position ensures the line stays consistent and doesn't change width/become distorted.
start = endpos
end
end
render.EndBeam()
end
end
end
end
else
ent.WirePaths = {}
net.Start("WireLib.Paths.RequestPaths")
net.WriteEntity(ent)
net.SendToServer()
end
end
end
local function Wire_GetWireRenderBounds(ent)
if not IsValid(ent) then return end
local bbmin = ent:OBBMins()
local bbmax = ent:OBBMaxs()
if ent.WirePaths then
for net_name, wiretbl in pairs(ent.WirePaths) do
local nodes = wiretbl.Path
local len = #nodes
for j = 1, len do
local node_ent = nodes[j].Entity
local nodepos = nodes[j].Pos
if (node_ent:IsValid()) then
nodepos = ent:WorldToLocal(node_ent:LocalToWorld(nodepos))
if (nodepos.x < bbmin.x) then
bbmin.x = nodepos.x
end
if (nodepos.y < bbmin.y) then
bbmin.y = nodepos.y
end
if (nodepos.z < bbmin.z) then
bbmin.z = nodepos.z
end
if (nodepos.x > bbmax.x) then
bbmax.x = nodepos.x
end
if (nodepos.y > bbmax.y) then
bbmax.y = nodepos.y
end
if (nodepos.z > bbmax.z) then
bbmax.z = nodepos.z
end
end
end
end
end
if (ent.ExtraRBoxPoints) then
for _, point_l in pairs(ent.ExtraRBoxPoints) do
local point = point_l
if (point.x < bbmin.x) then
bbmin.x = point.x
end
if (point.y < bbmin.y) then
bbmin.y = point.y
end
if (point.z < bbmin.z) then
bbmin.z = point.z
end
if (point.x > bbmax.x) then
bbmax.x = point.x
end
if (point.y > bbmax.y) then
bbmax.y = point.y
end
if (point.z > bbmax.z) then
bbmax.z = point.z
end
end
end
return bbmin, bbmax
end
function Wire_UpdateRenderBounds(ent)
local bbmin, bbmax = Wire_GetWireRenderBounds(ent)
ent:SetRenderBounds(bbmin, bbmax)
end
local function WireDisableRender(pl, cmd, args)
if args[1] then
Wire_DisableWireRender = tonumber(args[1])
end
Msg("\nWire DisableWireRender/WireRenderMode = " .. tostring(Wire_DisableWireRender) .. "\n")
end
concommand.Add("cl_Wire_DisableWireRender", WireDisableRender)
concommand.Add("cl_Wire_SetWireRenderMode", WireDisableRender)
function Wire_DrawTracerBeam(ent, beam_num, hilight, beam_length)
local beam_length = beam_length or ent:GetBeamLength(beam_num)
if (beam_length > 0) then
local x, y = 0, 0
if (ent.GetSkewX and ent.GetSkewY) then
x, y = ent:GetSkewX(beam_num), ent:GetSkewY(beam_num)
end
local start, ang = ent:GetPos(), ent:GetAngles()
if (ent.ls ~= start or ent.la ~= ang or ent.ll ~= beam_length or ent.lx ~= x or ent.ly ~= y) then
ent.ls, ent.la = start, ang
if (ent.ll ~= beam_length or ent.lx ~= x or ent.ly ~= y) then
ent.ll, ent.lx, ent.ly = beam_length, x, y
if (x == 0 and y == 0) then
ent.endpos = start + (ent:GetUp() * beam_length)
else
local skew = Vector(x, y, 1)
skew = skew * (beam_length / skew:Length())
local beam_x = ent:GetRight() * skew.x
local beam_y = ent:GetForward() * skew.y
local beam_z = ent:GetUp() * skew.z
ent.endpos = start + beam_x + beam_y + beam_z
end
ent.ExtraRBoxPoints = ent.ExtraRBoxPoints or {}
ent.ExtraRBoxPoints[beam_num] = ent:WorldToLocal(ent.endpos)
else
ent.endpos = ent:LocalToWorld(ent.ExtraRBoxPoints[beam_num])
end
end
local trace = {}
trace.start = start
trace.endpos = ent.endpos
trace.filter = {ent}
if ent:GetNW2Bool("TraceWater") then
trace.mask = MASK_ALL
end
trace = util.TraceLine(trace)
render.SetMaterial(beam_mat)
render.DrawBeam(start, trace.HitPos, 6, 0, 10, ent:GetColor())
if (hilight) then
render.SetMaterial(beamhi_mat)
render.DrawBeam(start, trace.HitPos, 6, 0, 10, Color(255, 255, 255, 255))
end
end
end
hook.Add("InitPostEntity", "language_strings", function()
for class, tbl in pairs(scripted_ents.GetList()) do
if tbl.t.PrintName and tbl.t.PrintName ~= "" then
language.Add(class, tbl.t.PrintName)
end
end
end)
if not CanRunConsoleCommand then
function CanRunConsoleCommand()
return false
end
hook.Add("Initialize", "CanRunConsoleCommand", function()
function CanRunConsoleCommand()
return true
end
end)
end
function Derma_StringRequestNoBlur(...)
local f = math.max
function math.max(...)
local ret = f(...)
for i = 1, 20 do
local name, value = debug.getlocal(2, i)
if name == "Window" then
value:SetBackgroundBlur(false)
break
end
end
return ret
end
local ok, ret = xpcall(Derma_StringRequest, debug.traceback, ...)
math.max = f
if not ok then
error(ret, 0)
end
return ret
end
function WireLib.hud_debug(text, oneframe)
hook.Add("HUDPaint", "wire_hud_debug", function()
if oneframe then
hook.Remove("HUDPaint", "wire_hud_debug")
end
draw.DrawText(text, "Trebuchet24", 10, 200, Color(255, 255, 255, 255), 0)
end)
end |
local Window = require "Window"
local GameLib = require "GameLib"
local AccountItemLib = require "AccountItemLib"
local MatchMakingLib = require "MatchMakingLib"
local Apollo = require "Apollo"
local XmlDoc = require "XmlDoc"
local ApolloTimer = require "ApolloTimer"
local GroupLib = require "GroupLib"
local PublicEvent = require "PublicEvent"
local EssenceEventTracker = {}
local kstrAddon = "EssenceTracker"
local lstrAddon = "Essence Tracker"
local ktShortContentTypes = {
[GameLib.CodeEnumRewardRotationContentType.Dungeon] = "Dng",
[GameLib.CodeEnumRewardRotationContentType.PeriodicQuest] = "Day",
[GameLib.CodeEnumRewardRotationContentType.Expedition] = "Exp",
[GameLib.CodeEnumRewardRotationContentType.WorldBoss] = "WB",
[GameLib.CodeEnumRewardRotationContentType.PvP] = "PvP",
[GameLib.CodeEnumRewardRotationContentType.DungeonNormal] = "Que",
[GameLib.CodeEnumRewardRotationContentType.None] = "None",
}
local knExtraSortBaseValue = 100
local keFeaturedSort = {
ContentType = 1,
TimeRemaining = 2,
Multiplier = knExtraSortBaseValue + 0,
Color = knExtraSortBaseValue + 1,
}
local keRewardTypes = {
Multiplier = 2,
Addition = 1,
}
local keAttendedEvents = {
Instance = 1,
WorldBoss = 2,
Daily = 3,
}
local ktEssenceRewardTypes = {
[AccountItemLib.CodeEnumAccountCurrency.PurpleEssence] = keRewardTypes.Addition,
[AccountItemLib.CodeEnumAccountCurrency.BlueEssence] = keRewardTypes.Multiplier,
[AccountItemLib.CodeEnumAccountCurrency.RedEssence] = keRewardTypes.Multiplier,
[AccountItemLib.CodeEnumAccountCurrency.GreenEssence] = keRewardTypes.Multiplier,
}
local ktContentTypeToAttendedEvent = {
[GameLib.CodeEnumRewardRotationContentType.Dungeon] = keAttendedEvents.Instance,
[GameLib.CodeEnumRewardRotationContentType.DungeonNormal] = keAttendedEvents.Instance,
[GameLib.CodeEnumRewardRotationContentType.Expedition] = keAttendedEvents.Instance,
[GameLib.CodeEnumRewardRotationContentType.PvP] = keAttendedEvents.Instance,
[GameLib.CodeEnumRewardRotationContentType.WorldBoss] = keAttendedEvents.WorldBoss,
[GameLib.CodeEnumRewardRotationContentType.PeriodicQuest] = keAttendedEvents.Daily,
[GameLib.CodeEnumRewardRotationContentType.None] = nil, --just to be complete.
}
local ktContentTypeTimes = {
[GameLib.CodeEnumRewardRotationContentType.Dungeon] = {
[keRewardTypes.Multiplier] = 2 * 3600, --2 hrs
[keRewardTypes.Addition] = 4 * 86400, --4 days
},
[GameLib.CodeEnumRewardRotationContentType.DungeonNormal] = {
[keRewardTypes.Multiplier] = 0,
[keRewardTypes.Addition] = 1 * 86400, --1 day
},
[GameLib.CodeEnumRewardRotationContentType.Expedition] = {
[keRewardTypes.Multiplier] = 1 * 3600, --1 h
[keRewardTypes.Addition] = 4 * 86400, --4 days
},
[GameLib.CodeEnumRewardRotationContentType.PvP] = {
[keRewardTypes.Multiplier] = 2 * 3600, --2 hrs
[keRewardTypes.Addition] = 4 * 86400, --4 days
},
[GameLib.CodeEnumRewardRotationContentType.WorldBoss] = {
[keRewardTypes.Multiplier] = 1 * 86400, --1 day
[keRewardTypes.Addition] = 4 * 86400, --4 days
},
[GameLib.CodeEnumRewardRotationContentType.PeriodicQuest] = {
[keRewardTypes.Multiplier] = 1 * 86400, --1 day
[keRewardTypes.Addition] = 0,
},
[GameLib.CodeEnumRewardRotationContentType.None] = {
[keRewardTypes.Multiplier] = 0,
[keRewardTypes.Addition] = 0,
},
}
local ktMatchTypeNames = {
[MatchMakingLib.MatchType.Shiphand] = Apollo.GetString("MatchMaker_Shiphands"),
[MatchMakingLib.MatchType.Adventure] = Apollo.GetString("MatchMaker_Adventures"),
[MatchMakingLib.MatchType.Dungeon] = Apollo.GetString("CRB_Dungeons"), -- <- ACTUALLY USED!
[MatchMakingLib.MatchType.Battleground] = Apollo.GetString("MatchMaker_Battlegrounds"),
[MatchMakingLib.MatchType.RatedBattleground]= Apollo.GetString("MatchMaker_Battlegrounds"),
[MatchMakingLib.MatchType.Warplot] = Apollo.GetString("MatchMaker_Warplots"),
[MatchMakingLib.MatchType.OpenArena] = Apollo.GetString("MatchMaker_Arenas"),
[MatchMakingLib.MatchType.Arena] = Apollo.GetString("MatchMaker_Arenas"),
[MatchMakingLib.MatchType.WorldStory] = Apollo.GetString("QuestLog_WorldStory"),
[MatchMakingLib.MatchType.PrimeLevelDungeon] = Apollo.GetString("MatchMaker_PrimeLevelDungeon"),
[MatchMakingLib.MatchType.PrimeLevelExpedition] = Apollo.GetString("MatchMaker_PrimeLevelExpedition"),
[MatchMakingLib.MatchType.PrimeLevelAdventure] = Apollo.GetString("MatchMaker_PrimeLevelAdventure"),
[MatchMakingLib.MatchType.ScaledPrimeLevelDungeon] = Apollo.GetString("MatchMaker_PrimeLevelDungeon"),
[MatchMakingLib.MatchType.ScaledPrimeLevelExpedition] = Apollo.GetString("MatchMaker_PrimeLevelExpedition"),
[MatchMakingLib.MatchType.ScaledPrimeLevelAdventure] = Apollo.GetString("MatchMaker_PrimeLevelAdventure"),
}
local kstrColors = {
kstrRed = "ffff4c4c",
kstrGreen = "ff2fdc02",
kstrYellow = "fffffc00",
kstrLightGrey = "ffb4b4b4",
kstrHighlight = "ffffe153",
}
function EssenceEventTracker:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
-- Data
o.nTrackerCounting = -1 -- Start at -1 so that loading up with 0 quests will still trigger a resize
o.bIsLoaded = false
o.bSetup = false
o.bObjectiveTrackerLoaded = false
o.tRotations = {}
o.tContentIds = {}
-- Saved data
o.bShow = true
o.tMinimized =
{
bRoot = false,
bDoneRoot = false,
tQuests = {},
}
o.tEventsDone = {}
o.tInstancesAttending = {}
o.tWorldBossesAttending = {}
o.tCustomSortFunctions = {
[keFeaturedSort.ContentType] = self.SortByContentType,
[keFeaturedSort.TimeRemaining] = self.SortByTimeRemaining,
[keFeaturedSort.Multiplier] = self.SortByMultiplier,
[keFeaturedSort.Color] = self.SortByColor
}
o.eSort = keFeaturedSort.ContentType
return o
end
function EssenceEventTracker:Init()
Apollo.GetPackage("Gemini:Hook-1.0").tPackage:Embed(self)
Apollo.RegisterAddon(self)
end
function EssenceEventTracker:OnLoad()
self.xmlDoc = XmlDoc.CreateFromFile("EssenceEventTracker.xml")
self.xmlDoc:RegisterCallback("OnDocumentReady", self)
Apollo.LoadSprites("EssenceTrackerSprites.xml")
self.timerUpdateDelay = ApolloTimer.Create(0.1, false, "UpdateAll", self)
self.timerUpdateDelay:Stop()
self.timerRealTimeUpdate = ApolloTimer.Create(1.0, true, "RedrawTimers", self)
self.timerRealTimeUpdate:Stop()
self:HookMatchMaker()
end
function EssenceEventTracker:OnSave(eType)
if eType == GameLib.CodeEnumAddonSaveLevel.Character then
return {
tMinimized = self.tMinimized,
bShow = self.bShow,
eSort = self.eSort,
}
elseif eType == GameLib.CodeEnumAddonSaveLevel.Realm then
return {
_version = 2,
tEventsDone = self.tEventsDone,
tInstancesAttending = self.tInstancesAttending,
tWorldBossesAttending = self.tWorldBossesAttending,
}
end
end
function EssenceEventTracker:OnRestore(eType, tSavedData)
if eType == GameLib.CodeEnumAddonSaveLevel.Character then
if tSavedData.tMinimized ~= nil then
self.tMinimized = tSavedData.tMinimized
end
if tSavedData.bShow ~= nil then
self.bShow = tSavedData.bShow
end
if tSavedData.eSort ~= nil then
self.eSort = tSavedData.eSort
end
elseif eType == GameLib.CodeEnumAddonSaveLevel.Realm then
if not tSavedData._version then --_version=1
local fNow = GameLib.GetGameTime()
local tNow = GameLib.GetServerTime()
local offset = self:CompareDateTables(tSavedData.tDate, tNow)
self.tEventsDone = {}
for i, tRewardEnds in pairs(tSavedData.tEventsDone or {}) do
self.tEventsDone[i] = {}
for j, v in pairs(tRewardEnds) do
self.tEventsDone[i][j] = self:BuildDateTable(v-offset, fNow, tNow)
self.tEventsDone[i][j].bDone = true
end
end
elseif tSavedData._version == 2 then
local a,b --passthrough for :AdjustDateTable
self.tEventsDone = {}
for i, tRewardEnds in pairs(tSavedData.tEventsDone or {}) do
self.tEventsDone[i] = {}
for j, v in pairs(tRewardEnds) do
local bDone = v.bDone
self.tEventsDone[i][j],a,b = self:AdjustDateTable(v, a, b)
self.tEventsDone[i][j].bDone = (bDone == nil) and true or bDone
end
end
self.tInstancesAttending = tSavedData.tInstancesAttending or tSavedData.tEventsAttending or {}
self.tWorldBossesAttending = tSavedData.tWorldBossesAttending or {}
end
end
end
function EssenceEventTracker:OnDocumentReady()
if self.xmlDoc == nil or not self.xmlDoc:IsLoaded() then
Apollo.AddAddonErrorText(self, "Could not load the main window document for some reason.")
return
end
--instance tracking
Apollo.RegisterEventHandler("MatchEntered", "OnMatchEntered", self)
Apollo.RegisterEventHandler("MatchLeft", "OnMatchLeft", self)
Apollo.RegisterEventHandler("PlayerChanged", "OnPlayerChanged", self)
--worldboss tracking
Apollo.RegisterEventHandler("PublicEventStart", "OnPublicEventStart", self)
Apollo.RegisterEventHandler("PublicEventLeave", "OnPublicEventLeave", self)
Apollo.RegisterEventHandler("PublicEventEnd", "OnPublicEventEnd", self)
--general stuff
Apollo.RegisterEventHandler("ChannelUpdate_Loot", "OnItemGained", self)
Apollo.RegisterEventHandler("PlayerLevelChange", "OnPlayerLevelChange", self)
Apollo.RegisterEventHandler("CharacterCreated", "OnCharacterCreated", self)
Apollo.RegisterEventHandler("ObjectiveTrackerLoaded", "OnObjectiveTrackerLoaded", self)
Event_FireGenericEvent("ObjectiveTracker_RequestParent")
Apollo.RegisterEventHandler("NextFrame", "OnNextFrame_DelayedLoad", self)
end
do --this is/was required, because of game crashes. It just delays the whole Setup-Process by two Frames.
local bOnce = false
function EssenceEventTracker:OnNextFrame_DelayedLoad()
if bOnce then
Apollo.RemoveEventHandler("NextFrame", self)
self.bIsLoaded = true
self:Setup()
self:OnPlayerChanged()
self:CheckRestoredAttendingInstances()
self:CheckRestoredAttendingWorldBosses()
else
bOnce = true
end
end
end
function EssenceEventTracker:OnObjectiveTrackerLoaded(wndForm)
if not wndForm or not wndForm:IsValid() then
return
end
self.bObjectiveTrackerLoaded = true
Apollo.RemoveEventHandler("ObjectiveTrackerLoaded", self)
Apollo.RegisterEventHandler("QuestInit", "OnQuestInit", self)
Apollo.RegisterEventHandler("PlayerLevelChange", "OnPlayerLevelChange", self)
Apollo.RegisterEventHandler("CharacterCreated", "OnCharacterCreated", self)
self.wndMain = Apollo.LoadForm(self.xmlDoc, "ContentGroupItem", wndForm, self)
self.wndContainerAvailable = self.wndMain:FindChild("EventContainerAvailable")
self.wndContainerDone = self.wndMain:FindChild("EventContainerDone")
self:Setup()
end
function EssenceEventTracker:Setup()
if not self.bIsLoaded then return end
if GameLib.GetPlayerUnit() == nil or GameLib.GetPlayerLevel(true) < 50 then
self.wndMain:Show(false)
return
end
if self.bSetup or not self.bObjectiveTrackerLoaded then
return
end
Apollo.RegisterEventHandler("ToggleShowEssenceTracker", "ToggleShowEssenceTracker", self)
local tContractData =
{
["strAddon"] = lstrAddon,
["strEventMouseLeft"] = "ToggleShowEssenceTracker",
["strEventMouseRight"] = "",
["strIcon"] = "EssenceTracker_Icon",
["strDefaultSort"] = kstrAddon,
}
Event_FireGenericEvent("ObjectiveTracker_NewAddOn", tContractData)
self.bSetup = true
self:UpdateAll()
end
function EssenceEventTracker:ToggleShowEssenceTracker()
self.bShow = not self.bShow
self:UpdateAll()
end
function EssenceEventTracker:OnPlayerLevelChange()
self:Setup()
end
function EssenceEventTracker:OnCharacterCreated()
self:Setup()
end
---------------------------------------------------------------------------------------------------
-- MatchMaker
---------------------------------------------------------------------------------------------------
function EssenceEventTracker:HookMatchMaker()
local matchmaker = Apollo.GetAddon("MatchMaker")
if not matchmaker then return end --if MatchMaker does not exist, we will never get a valid LoadForm.
--GeminiHook
self:Hook(Apollo, "RegisterEventHandler", "OnRegisterEvent")
end
function EssenceEventTracker:OnRegisterEvent(strEvent, strHandler, tHandler)
if strEvent == "ToggleGroupFinder" and strHandler == "OnToggleMatchMaker" then
self.addonMatchMaker = tHandler
self:Hook(self.addonMatchMaker, "BuildFeaturedControl", "BuildFeaturedControlHook")
self:SilentPostHook(self.addonMatchMaker, "BuildRewardsList", "BuildRewardsListHook")
self:SilentPostHook(self.addonMatchMaker, "HelperCreateFeaturedSort", "HelperCreateFeaturedSortHook")
self:RawHook(self.addonMatchMaker, "GetSortedRewardList", "GetSortedRewardListHook")
self:Unhook(Apollo, "RegisterEventHandler")
end
end
function EssenceEventTracker:BuildFeaturedControlHook(addonMatchMaker, wndParent, tRewardListEntry)
local rTbl = self:GetRotationForFeaturedReward(tRewardListEntry)
if not rTbl then return end
local bDone = self:IsDone(rTbl)
tRewardListEntry.tRewardInfo.bGranted = bDone
end
function EssenceEventTracker:BuildRewardsListHook(tRet, ref, tRewardRotation)
local arRewardList = tRet[1]
for i=1, #arRewardList do
arRewardList[i].nContentId = tRewardRotation.nContentId
end
end
function EssenceEventTracker:HelperCreateFeaturedSortHook()
self:AddAdditionalSortOptions()
end
function EssenceEventTracker:GetSortedRewardListHook(ref, arRewardList, ...)
self:UpdateSortType(self.addonMatchMaker.tWndRefs.wndFeaturedSort:GetData())
if self.tCustomSortFunctions[self.eSort] then
table.sort(arRewardList,
function (tData1, tData2)
local rTbl1 = self:GetRotationForFeaturedReward(tData1)
local rTbl2 = self:GetRotationForFeaturedReward(tData2)
if not rTbl1 or not rTbl2 then
return self:CompareNil(rTbl1, rTbl2) > 0
end
return self.tCustomSortFunctions[self.eSort](self, rTbl1, rTbl2)
end
)
return arRewardList
else
--original function
return self.hooks[self.addonMatchMaker]["GetSortedRewardList"](ref, arRewardList, ...)
end
end
function EssenceEventTracker:AddAdditionalSortOptions()
local wndSort = self:GetSortWindow()
if not wndSort then return end
local wndSortDropdown = wndSort:FindChild("FeaturedFilterDropdown")
if not wndSortDropdown then return end
local wndSortContainer = wndSortDropdown:FindChild("Container")
local refXmlDoc = self.addonMatchMaker.xmlDoc
local strSortOptionForm = "FeaturedContentFilterBtn"
local wndSortMultiplier = Apollo.LoadForm(refXmlDoc, strSortOptionForm, wndSortContainer, self.addonMatchMaker)
wndSortMultiplier:SetData(keFeaturedSort.Multiplier)
wndSortMultiplier:SetText(Apollo.GetString("Protogames_Bonus")) --"Multiplier"
if wndSort:GetData() == keFeaturedSort.Multiplier then
wndSortMultiplier:SetCheck(true)
end
local wndSortColor = Apollo.LoadForm(refXmlDoc, strSortOptionForm, wndSortContainer, self.addonMatchMaker)
wndSortColor:SetData(keFeaturedSort.Color)
wndSortColor:SetText(Apollo.GetString("AccountInventory_Essence").." "..Apollo.GetString("CRB_Color"))--"Essence Color"
local sortContainerChildren = wndSortContainer:GetChildren()
local nLeft, nTop, nRight = wndSortDropdown:GetOriginalLocation():GetOffsets()
local nBottom = nTop + (#sortContainerChildren * wndSortMultiplier:GetHeight()) + 11
wndSortDropdown:SetAnchorOffsets(nLeft, nTop, nRight, nBottom)
wndSortContainer:ArrangeChildrenVert(Window.CodeEnumArrangeOrigin.LeftOrTop)
for i = 1, #sortContainerChildren do
local sortButton = sortContainerChildren[i]
if self.eSort == sortButton:GetData() then
wndSort:SetData(sortButton:GetData())
wndSort:SetText(sortButton:GetText())
sortButton:SetCheck(true)
else
sortButton:SetCheck(false)
end
end
end
function EssenceEventTracker:GetSortWindow()
--self.addonMatchMaker.tWndRefs.wndFeaturedSort
local wndSort = self.addonMatchMaker
wndSort = wndSort and wndSort.tWndRefs
wndSort = wndSort and wndSort.wndFeaturedSort
return wndSort
end
function EssenceEventTracker:UpdateSortType(eSort)
local old_eSort = self.eSort
self.eSort = eSort
if eSort ~= old_eSort then
self:UpdateAll()
end
end
function EssenceEventTracker:CompareNil(rTbl1, rTbl2)
if not rTbl1 and not rTbl2 then
return 0
elseif not rTbl1 then
return 1
elseif not rTbl2 then
return -1
end
return 0
end
function EssenceEventTracker:CompareCompletedStatus(rTbl1, rTbl2)
local bIsDone1 = self:IsDone(rTbl1)
local bIsDone2 = self:IsDone(rTbl2)
if bIsDone1 and not bIsDone2 then return 1 end
if not bIsDone1 and bIsDone2 then return -1 end
return 0
end
function EssenceEventTracker:SortByContentType(rTbl1, rTbl2)
local nCompare = self:CompareCompletedStatus(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByContentType(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByMultiplier(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
return self:CompareByContentId(rTbl1, rTbl2) < 0
end
function EssenceEventTracker:SortByTimeRemaining(rTbl1, rTbl2)
local nCompare = self:CompareCompletedStatus(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByTimeRemaining(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByMultiplier(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByContentType(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
return self:CompareByContentId(rTbl1, rTbl2) < 0
end
function EssenceEventTracker:SortByMultiplier(rTbl1, rTbl2)
local nCompare = self:CompareCompletedStatus(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByMultiplier(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByTimeRemaining(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByContentType(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
return self:CompareByContentId(rTbl1, rTbl2) < 0
end
function EssenceEventTracker:SortByColor(rTbl1, rTbl2)
local nCompare = self:CompareCompletedStatus(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByColor(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByMultiplier(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
nCompare = self:CompareByContentType(rTbl1, rTbl2)
if nCompare ~= 0 then return nCompare < 0 end
return self:CompareByContentId(rTbl1, rTbl2) < 0
end
function EssenceEventTracker:CompareByContentType(rTbl1, rTbl2)
local nA = rTbl1.src.nContentType or 0
local nB = rTbl2.src.nContentType or 0
return nA - nB
end
function EssenceEventTracker:CompareByTimeRemaining(rTbl1, rTbl2)
local nA = rTbl1.fEndTime or 0
local nB = rTbl2.fEndTime or 0
local nAB = nA - nB
return math.abs(nAB)<5 and 0 or nAB
end
function EssenceEventTracker:CompareByMultiplier(rTbl1, rTbl2)
local nA = rTbl1.tReward and rTbl1.tReward.nMultiplier or 0
local nB = rTbl2.tReward and rTbl2.tReward.nMultiplier or 0
return nB - nA
end
function EssenceEventTracker:CompareByColor(rTbl1, rTbl2)
local nA = rTbl1.tReward and rTbl1.tReward.monReward and rTbl1.tReward.monReward:GetAccountCurrencyType() or 0
local nB = rTbl2.tReward and rTbl2.tReward.monReward and rTbl2.tReward.monReward:GetAccountCurrencyType() or 0
return nB - nA
end
function EssenceEventTracker:CompareByContentId(rTbl1, rTbl2)
local nA = rTbl1.src.nContentId or 0
local nB = rTbl2.src.nContentId or 0
return nB - nA
end
function EssenceEventTracker:GetFeaturedEntries()
--self.addonMatchMaker.tWndRefs.wndMain:FindChild("TabContent:RewardContent"):GetChildren()
local wndFeaturedEntries = self.addonMatchMaker
wndFeaturedEntries = wndFeaturedEntries and wndFeaturedEntries.tWndRefs
wndFeaturedEntries = wndFeaturedEntries and wndFeaturedEntries.wndMain
wndFeaturedEntries = wndFeaturedEntries and wndFeaturedEntries:FindChild("TabContent:RewardContent")
wndFeaturedEntries = wndFeaturedEntries and wndFeaturedEntries:GetChildren() or {}
return wndFeaturedEntries
end
function EssenceEventTracker:GetRotationForFeaturedReward(tData)
local rTbl = tData and self.tContentIds
rTbl = rTbl and rTbl[tData.nContentId]
rTbl = rTbl and rTbl[tData.tRewardInfo.nRewardType] or nil
return rTbl
end
---------------------------------------------------------------------------------------------------
-- Drawing
---------------------------------------------------------------------------------------------------
function EssenceEventTracker:IsInterestingRotation(rot)
return not(#rot.arRewards < 1 or #rot.arRewards <= 1 and rot.arRewards[1].nRewardType == keRewardTypes.Multiplier
and rot.arRewards[1].nMultiplier <= 1)
end
function EssenceEventTracker:rTblFromRotation(src, reward)
return { --usually called 'rTbl'
strText = "["..ktShortContentTypes[src.nContentType].."] "..self:GetTitle(src),
fEndTime = (reward and reward.nSecondsRemaining or 0) + GameLib.GetGameTime(),
src = src,
strIcon = reward and reward.strIcon or "",
strMult = tostring(reward and reward.nMultiplier and reward.nMultiplier>1 and reward.nMultiplier or ""),
tReward = reward,
}
end
function EssenceEventTracker:BuildRotationTable( rot )
local redo = false
for _, reward in ipairs(rot.arRewards) do
if reward.nRewardType == keRewardTypes.Addition or reward.nRewardType == keRewardTypes.Multiplier
and reward.nMultiplier > 1 then
local rTbl = self:rTblFromRotation(rot, reward)
table.insert(self.tRotations, rTbl)
self.tContentIds[rot.nContentId] = self.tContentIds[rot.nContentId] or {}
self.tContentIds[rot.nContentId][reward.nRewardType] = rTbl
if reward.nSecondsRemaining <= 0 then
redo = true
end
end
end
return redo
end
function EssenceEventTracker:GetTitle(rot)--[[
nContentType: (1-6)
1,3,5 - strWorld
2 - strZoneName
4 - peWorldBoss:GetName()
6 - ktMatchTypeNames[eMatchType] ]]
if rot.nContentType%2 == 1 then
return rot.strWorld
elseif rot.nContentType == 2 then
return rot.strZoneName
elseif rot.nContentType == 4 then
return rot.peWorldBoss:GetName()
elseif rot.nContentType == 6 then
return ktMatchTypeNames[rot.eMatchType]
end
end
function EssenceEventTracker:UpdateAll()
if not self.bSetup then return end
self.timerUpdateDelay:Stop()
self.tRotations = {}
self.tContentIds = {}
for idx, nContentType in pairs(GameLib.CodeEnumRewardRotationContentType) do
GameLib.RequestRewardUpdate(nContentType)
end
local redo = false --do we need to :UpdateAll() again, because nSecondsLeft <= 0
local arRewardRotations = GameLib.GetRewardRotations()
for _, rotation in ipairs(arRewardRotations or {}) do
if self:IsInterestingRotation(rotation) then --filter all (only) 1x Multiplicators, aka. all thats 'default'
if self:BuildRotationTable(rotation) then
redo = true
end
end
end
local player = GameLib.GetPlayerUnit()
if not player or GameLib.GetPlayerLevel(true)~=50 then
self.bAllowShow = false
else
self.bAllowShow = true
end
if redo or not player or self.bAllowShow and #self.tRotations == 0 then
self.updateTimer = self.updateTimer or ApolloTimer.Create(0, false, "UpdateAll", self)
self.updateTimer:Start()
else
self.updateTimer = nil
end
self:RedrawAll()
end
function EssenceEventTracker:UpdateFeaturedList()
if next(self:GetFeaturedEntries{}) ~= nil then
self.addonMatchMaker:BuildFeaturedList()
end
end
function EssenceEventTracker:RedrawAll()
if not self.wndMain then return end
local nStartingHeight = self.wndMain:GetHeight()
local bStartingShown = self.wndMain:IsShown()
local nAvailable, nDone = 0,0
for i, rTbl in ipairs(self.tRotations) do
nAvailable, nDone = self:DrawRotation(rTbl, nAvailable, nDone)
end
local tAvailableChildren = self.wndContainerAvailable:GetChildren()
for i = nAvailable+1, #tAvailableChildren, 1 do
tAvailableChildren[i]:Destroy()
end
local tDoneChildren = self.wndContainerDone:GetChildren()
for i = nDone+1, #tDoneChildren, 1 do
tDoneChildren[i]:Destroy()
end
local bShow = self.bAllowShow and self.bShow or false
if bShow then
if self.tMinimized.bRoot then
self.wndContainerAvailable:Show(false)
self.wndContainerDone:Show(false)
local nLeft, nOffset, nRight = self.wndMain:GetAnchorOffsets() --current location
local _, nTop, _, nBottom = self.wndMain:GetOriginalLocation():GetOffsets()
self.wndMain:SetAnchorOffsets(nLeft, nOffset, nRight, nOffset + nBottom - nTop)
else
-- Resize quests
local nAvailableHeight = self.wndContainerAvailable:ArrangeChildrenVert(Window.CodeEnumArrangeOrigin.LeftOrTop,
function(wndA, wndB)
return self.tCustomSortFunctions[self.eSort](self, wndA:GetData(), wndB:GetData())
end)
self.wndContainerAvailable:SetAnchorOffsets(0,0,0,nAvailableHeight)
if self.tMinimized.bDoneRoot then
self.wndContainerDone:SetAnchorOffsets(0,0,0,0)
else
local nDoneHeight = self.wndContainerDone:ArrangeChildrenVert(Window.CodeEnumArrangeOrigin.LeftOrTop,
function(wndA, wndB)
return self.tCustomSortFunctions[self.eSort](self, wndA:GetData(), wndB:GetData())
end)
self.wndContainerDone:SetAnchorOffsets(0,0,0,nDoneHeight)
end
self.wndContainerAvailable:Show(true)
self.wndContainerDone:Show(true)
local nHeight = self.wndMain:ArrangeChildrenVert()
local nLeft, nTop, nRight, _ = self.wndMain:GetAnchorOffsets()
self.wndMain:SetAnchorOffsets(nLeft, nTop, nRight, nTop+nHeight)
end
end
self.wndMain:Show(bShow)
self.wndMain:FindChild("HeadlineBtn:MinimizeBtn"):SetCheck(self.tMinimized.bRoot)
self.wndMain:FindChild("DoneHeadline:DoneHeadlineBtn:MinimizeBtn"):SetCheck(self.tMinimized.bDoneRoot)
if nStartingHeight ~= self.wndMain:GetHeight() or self.nAvailableCounting ~= nAvailable
or self.nDoneCounting ~= nDone or bShow ~= bStartingShown then
local tData =
{
["strAddon"] = lstrAddon,
["strText"] = nAvailable,
["bChecked"] = bShow,
}
Event_FireGenericEvent("ObjectiveTracker_UpdateAddOn", tData)
end
if bShow and not self.tMinimized.bRoot then
self.timerRealTimeUpdate:Start()
end
self.nAvailableCounting = nAvailable
self.nDoneCounting = nDone
end
function EssenceEventTracker:DrawRotation(rTbl, nAvailable, nDone)
local bDone = self:IsDone(rTbl)
local wndContainer = bDone and self.wndContainerDone or self.wndContainerAvailable
local idx = bDone and nDone+1 or nAvailable+1
while not wndContainer:GetChildren()[idx] do
Apollo.LoadForm(self.xmlDoc, "EssenceItem", wndContainer, self)
end
local wndForm = wndContainer:GetChildren()[idx]
wndForm:FindChild("EssenceIcon"):SetSprite(rTbl.strIcon)
wndForm:FindChild("EssenceIcon"):SetText(rTbl.strMult)
if rTbl.tReward.nRewardType == keRewardTypes.Addition then -- example: 400 Purple Essence
wndForm:FindChild("EssenceIcon"):SetTooltip(rTbl.tReward.monReward:GetMoneyString())
elseif rTbl.tReward.nRewardType == keRewardTypes.Multiplier then --example: 4x Green Essence
wndForm:FindChild("EssenceIcon"):SetTooltip(rTbl.tReward.nMultiplier.."x "..rTbl.tReward.monReward:GetTypeString())
else --remove
wndForm:FindChild("EssenceIcon"):SetTooltip("")
end
wndForm:FindChild("ControlBackerBtn:TimeText"):SetText(self:HelperTimeString(rTbl.fEndTime-GameLib.GetGameTime()))
if bDone then
wndForm:FindChild("ControlBackerBtn:TitleText"):SetText(self:HelperColorize(rTbl.strText, kstrColors.kstrRed))
else
wndForm:FindChild("ControlBackerBtn:TitleText"):SetText(
self:HelperColorizeIf(rTbl.strText, kstrColors.kstrYellow, self:IsAttended(rTbl)))
end
wndForm:SetData(rTbl)
--returns nAvailable, nDone (incremented accordingly)
return (bDone and nAvailable or idx), (bDone and idx or nDone)
end
function EssenceEventTracker:RedrawTimers()
local update = false
for _, wndForm in ipairs(self.wndContainerAvailable:GetChildren()) do
local rTbl = wndForm:GetData()
local fTimeLeft = rTbl.fEndTime-GameLib.GetGameTime()
wndForm:FindChild("ControlBackerBtn:TimeText"):SetText(self:HelperTimeString(fTimeLeft))
if fTimeLeft < 0 then update = true end
end
for _, wndForm in ipairs(self.wndContainerDone:GetChildren()) do
local rTbl = wndForm:GetData()
local fTimeLeft = rTbl.fEndTime-GameLib.GetGameTime()
wndForm:FindChild("ControlBackerBtn:TimeText"):SetText(self:HelperTimeString(fTimeLeft))
if fTimeLeft < 0 then update = true end
end
if update then
self:UpdateAll()
end
end
---------------------------------------------------------------------------------------------------
-- Game Events
---------------------------------------------------------------------------------------------------
function EssenceEventTracker:OnQuestInit()
self:Setup()
if self.bSetup then
self.timerUpdateDelay:Start()
end
end
function EssenceEventTracker:OnPlayerLevelChange()
self:Setup()
end
function EssenceEventTracker:OnCharacterCreated()
self:Setup()
end
function EssenceEventTracker:OnItemGained(type, args)
if type == GameLib.ChannelUpdateLootType.Currency and args.monNew then
if ktEssenceRewardTypes[args.monNew:GetAccountCurrencyType()] then
self:UpdateAll()
self:UpdateFeaturedList()
end
end
end
do
local instances = {
[13] = {--"Stormtalon's Lair",
parentZoneId = nil, id = 19, nContentId = 12, nContentType = 1, nBase = 65,
},
[14] = {--"Skullcano",
{parentZoneId = 0, id = 20, nContentId = 13, nContentType = 1, nBase = 65},
{parentZoneId = 20, id = 73, nContentId = 13, nContentType = 1, nBase = 65},
},
[48] = {--"Sanctuary of the Swordmaiden",
parentZoneId = nil, id = 85, nContentId = 14, nContentType = 1, nBase = 70,
},
[15] = { --"Ruins of Kel Voreth"
parentZoneId = nil, id = 21, nContentId = 15, nContentType = 1, nBase = 65,
},
[69] = {--"Ultimate Protogames",
parentZoneId = 154, id = nil, nContentId = 16, nContentType = 1, nBase = 70, --?
},
[90] = { --"Academy",
parentZoneId = 469, id = nil, nContentId = 17, nContentType = 1, nBase = 70,
},
[105] = { --"Citadel",
parentZoneId = nil, id = 560, nContentId = 45, nContentType = 1, nBase = 70,
},
[18] = {--"Infestation",
parentZoneId = nil, id = 25, nContentId = 18, nContentType = 3, nBase = 45,
},
[38] = {--"Outpost M-13",
parentZoneId = 63, id = nil, nContentId = 19, nContentType = 3, nBase = 50,
},
[51] = {--"Rage Logic",
parentZoneId = 93, id = nil, nContentId = 20, nContentType = 3, nBase = 45,
},
[58] = {--"Space Madness",
parentZoneId = nil, id = 121, nContentId = 21, nContentType = 3, nBase = 45,
},
[62] = {--"Gauntlet",
parentZoneId = 132, id = nil, nContentId = 22, nContentType = 3, nBase = 45,
},
[60] = {--"Deepd Space Exploration",
parentZoneId = 140, id = nil, nContentId = 23, nContentType = 3, nBase = 50,
},
[83] = {--"Fragment Zero",
{parentZoneId = nil,id = 277, nContentId = 24, nContentType = 3, nBase = 50,},
{parentZoneId = 277,id = nil, nContentId = 24, nContentType = 3, nBase = 50,},
},
[107] = { --"Ether",
parentZoneId = 562, id = nil, nContentId = 25, nContentType = 3, nBase = 50,
},
[40] = { --"Walatiki Temple"
parentZoneId = nil, id = 69, nContentId = 38, nContentType = 5, nBase = 150, --?
},
[53] = { --"Halls of the Bloodsworn"
parentZoneId = nil, id = 99, nContentId = 39, nContentType = 5, nBase = 80,
},
[57] = { --"Daggerstone Pass"
parentZoneId = nil, id = 103, nContentId = 40, nContentType = 5, nBase = 300,
},
}
function EssenceEventTracker:GetCurrentInstance()
local zone = GameLib.GetCurrentZoneMap()
if not zone then return nil, true end --return nil, bNoZone
if not instances[zone.continentId] then return nil end
if #instances[zone.continentId] > 0 then
for _, instance in ipairs(instances[zone.continentId]) do
if (not instance.parentZoneId or instance.parentZoneId==zone.parentZoneId)
and (not instance.id or instance.id==zone.id) then
return instance
end
end
else
local instance = instances[zone.continentId]
if (not instance.parentZoneId or instance.parentZoneId==zone.parentZoneId)
and (not instance.id or instance.id==zone.id) then
return instance
end
end
return nil
end
function EssenceEventTracker:OnMatchEntered() --no args
Apollo.RegisterEventHandler("SubZoneChanged", "OnEnteredMatchZone", self)
end
function EssenceEventTracker:OnEnteredMatchZone() --OnSubZoneChanged
Apollo.RemoveEventHandler("SubZoneChanged", self)
local inst = self:GetCurrentInstance()
if not inst then
return self:ClearAttendings(keAttendedEvents.Instance)
end
local tmp = self.tInstancesAttending
self.tInstancesAttending = {}
if tmp and next(tmp) then
for cId, tEnd in pairs(tmp) do
for rId, tDate in pairs(tEnd) do
if tDate.nInstanceContentId == inst.nContentId then
self.tInstancesAttending[cId] = self.tInstancesAttending[cId] or {}
self.tInstancesAttending[cId][rId] = tDate
end
end
end
end
--check normal instances
for nRewardType, rTbl in pairs(self.tContentIds[inst.nContentId] or {}) do
if self:CheckVeteran(rTbl.src.bIsVeteran) then
self:MarkAsAttended(rTbl, inst.nContentId)
end
end
--check queues
for nRewardType, rTbl in pairs(self.tContentIds[46] or {}) do --46 = Random Normal Queue
if self:CheckVeteran(rTbl.src.bIsVeteran) and rTbl.src.eMatchType == inst.nContentType then
self:MarkAsAttended(rTbl, inst.nContentId)
end
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:OnMatchLeft()
self:ClearAttendings(keAttendedEvents.Instance)
-- self:UpdateAll() --included in above
-- self:UpdateFeaturedList()
end
function EssenceEventTracker:GainedEssence(tMoney)
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:CheckVeteran(bVet)
local tInstanceSettingsInfo = GameLib.GetInstanceSettings()
if bVet then
return tInstanceSettingsInfo.eWorldDifficulty == GroupLib.Difficulty.Veteran
else
return tInstanceSettingsInfo.eWorldDifficulty == GroupLib.Difficulty.Normal
end
end
function EssenceEventTracker:CheckForInstanceAttendance(rTbl)
local inst = self:GetCurrentInstance()
if not inst then return end
if rTbl.src.nContentId == 46 then
if self:CheckVeteran(rTbl.src.bIsVeteran) and rTbl.src.eMatchType == inst.nContentType then
self:MarkAsAttended(rTbl, inst.nContentId)
end
elseif inst.nContentId == rTbl.src.nContentId then
if self:CheckVeteran(rTbl.src.bIsVeteran) then
self:MarkAsAttended(rTbl, inst.nContentId)
end
end
end
function EssenceEventTracker:OnPlayerChanged()
if not self.bSetup then return end --prevent calling GameLib.GetRewardRotations() previous to being allowed.
--i know all of this is REALLY weird, but I'm really fed up with these problems..
for idx, nContentType in pairs(GameLib.CodeEnumRewardRotationContentType) do
GameLib.RequestRewardUpdate(nContentType)
end
GameLib.GetRewardRotations()
self.timerAfterPlayerChanged = ApolloTimer.Create(2, false, "AfterPlayerChanged", self)
end
function EssenceEventTracker:AfterPlayerChanged()
local arRewardRotations = GameLib.GetRewardRotations()
for _, tContent in ipairs(arRewardRotations or {}) do
if ktContentTypeToAttendedEvent[tContent.nContentType] == keAttendedEvents.Instance then
for i, tReward in pairs(tContent.arRewards) do
local rTbl = self:rTblFromRotation(tContent, tReward)
local nMaxTime = ktContentTypeTimes[rTbl.src.nContentType][rTbl.tReward.nRewardType] or 0
if tReward.bGranted and self:IsDone_Saves(rTbl) == nil and nMaxTime - rTbl.tReward.nSecondsRemaining > 30 then
self:MarkAsDone(rTbl)
end
end
end
end
self:UpdateAll()
end
end
do --worldbosses
local eventIdToContentId = {
[150] = 26, --MetalMaw
[372] = 27, --King Plush
[590] = 28, --Dreamspore
[491] = 29, --Zoetic
[593] = 30, --Grendelus
[169] = 31, --Kraggar
[177] = 32, --MetalMawPrime
[847] = 33, --KHG
[586] = 34, --Mecha
[852] = 35, --Gargantua
[855] = 36, --Scorchwing
[870] = 37, --Renhakul
}
function EssenceEventTracker:OnPublicEventStart(tEvent)
if not tEvent:IsActive() then return end
local eId = tEvent:GetId()
local cId = eventIdToContentId[eId]
if not cId then return end
for nRewardType, rTbl in pairs(self.tContentIds[cId] or {}) do
self:MarkAsAttended(rTbl, eId)
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:OnPublicEventLeave(tEvent)
local eId = tEvent:GetId()
local cId = eventIdToContentId[eId]
if not cId then return end
for nRewardType, rTbl in pairs(self.tContentIds[cId] or {}) do
self:ClearAttendings(nil, rTbl)
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:OnPublicEventEnd(tEvent, arg2, arg3)
local eId = tEvent:GetId()
local cId = eventIdToContentId[eId]
if not cId then return end
for nRewardType, rTbl in pairs(self.tContentIds[cId] or {}) do
self:ClearAttendings(nil, rTbl)
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:CheckForWorldBossAttendance(rTbl)
local events = PublicEvent and PublicEvent.GetActiveEvents()
if rTbl then
for i, tEvent in ipairs(events) do
local eId = tEvent:GetId()
local cId = eventIdToContentId[eId]
if rTbl.src.nContentId == cId then
self:MarkAsAttended(rTbl, eId)
break;
end
end
else
for i, tEvent in ipairs(events) do
local eId = tEvent:GetId()
local cId = eventIdToContentId[eId]
for _, rTbl2 in pairs(cId and self.tContentIds[cId] or {}) do
self:MarkAsAttended(rTbl2, eId)
end
end
end
end
end
function EssenceEventTracker:IsRewardEqual(tRewardA, tRewardB)
-- .bGranted dont compare
-- .monReward compare color & amount
-- .nMultiplier
-- .nRewardType
-- .nSecondsRemaining ~60s difference
-- .strIcon uninteresting
if math.abs(tRewardB.nSecondsRemaining-tRewardA.nSecondsRemaining) > 60 then return false end
if tRewardA.monReward:GetAccountCurrencyType() ~= tRewardB.monReward:GetAccountCurrencyType() then return false end
if tRewardA.monReward:GetAmount() ~= tRewardB.monReward:GetAmount() then return false end
if tRewardA.nMultiplier ~= tRewardB.nMultiplier then return false end
if tRewardA.nRewardType ~= tRewardB.nRewardType then return false end --is this nesseccary?
return true
end
function EssenceEventTracker:IsDone_Rotation(rTbl)
local tRewards = GameLib.GetRewardRotation(rTbl.src.nContentId, rTbl.src.bIsVeteran or false)
if not tRewards then return false end
for i, tReward in ipairs(tRewards) do
if self:IsRewardEqual(tReward, rTbl.tReward) then
return tReward.bGranted
end
end
return nil
end
function EssenceEventTracker:IsDone_Saves(rTbl)
local tRewardEnds = self.tEventsDone[rTbl.src.nContentId]
if not tRewardEnds then return nil end
local tEnd = tRewardEnds[rTbl.tReward.nRewardType]
if not tEnd then return nil end
local fEnd = tEnd.nGameTime
if not fEnd then return nil end
if math.abs(fEnd - rTbl.fEndTime) < 60 then
return tEnd.bDone
else
return nil
end
end
function EssenceEventTracker:IsDone(rTbl)
local bDone = self:IsDone_Saves(rTbl)
if bDone then
return true
elseif bDone == false then
if not self:IsDone_Rotation(rTbl) then
self:RemoveDoneMark(rTbl) -- the game agrees in the Event not being done -> remove the mark.
end
return false
end
bDone = self:IsDone_Rotation(rTbl)
if bDone ~= true then return false end
local nMaxTime = ktContentTypeTimes[rTbl.src.nContentType][rTbl.tReward.nRewardType] or 0
if ktContentTypeToAttendedEvent[rTbl.src.nContentType] == keAttendedEvents.Instance then
return false
elseif nMaxTime - rTbl.tReward.nSecondsRemaining < 30 then --do not believe this.
self:MarkAsDone(rTbl, nil, true)
end
self:MarkAsDone(rTbl)
return bDone
end
function EssenceEventTracker:MarkAsDone(rTbl, bToggle, bInverse) --bInverse = Mark as 'Not Done', bToggle is priorized
local cId, rId = rTbl.src.nContentId, rTbl.tReward.nRewardType
if bToggle and self:IsDone(rTbl) then
-- if :IsDone returns true, its guaranteed for a table in tEventsDone to exist.
self.tEventsDone[cId][rId].bDone = false
else
self.tEventsDone[cId] = self.tEventsDone[cId] or {}
self.tEventsDone[cId][rId] = self:BuildDateTable(rTbl.fEndTime)
self.tEventsDone[cId][rId].bDone = bInverse and false or true
end
end
function EssenceEventTracker:RemoveDoneMark(rTbl)
local cId, rId = rTbl.src.nContentId, rTbl.tReward.nRewardType
if not self.tEventsDone[cId] then return end
self.tEventsDone[cId][rId] = nil
if not next(self.tEventsDone[cId]) then
self.tEventsDone[cId] = nil
end
end
--rTbl only to clear a specific attending. (can leave eType out then)
function EssenceEventTracker:ClearAttendings(eType, rTbl) --eType from keAttendedEvents
if rTbl then
eType = ktContentTypeToAttendedEvent[rTbl.src.nContentType]
local tAttendingEvents = (eType == keAttendedEvents.Instance and self.tInstancesAttending
or eType == keAttendedEvents.WorldBoss and self.tWorldBossesAttending
or nil)
if not tAttendingEvents or not tAttendingEvents[rTbl.src.nContentId] then return end
tAttendingEvents[rTbl.src.nContentId][rTbl.tReward.nRewardType] = nil
if not next(tAttendingEvents[rTbl.src.nContentId]) then
tAttendingEvents[rTbl.src.nContentId] = nil
end
elseif eType == keAttendedEvents.Instance then
self.tInstancesAttending = {}
elseif eType == keAttendedEvents.WorldBoss then
self.tWorldBossesAttending = {}
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:MarkAsAttended(rTbl, ...)
local eType = ktContentTypeToAttendedEvent[rTbl.src.nContentType]
local cId, rId = rTbl.src.nContentId, rTbl.tReward.nRewardType
if eType == keAttendedEvents.Instance then
self.tInstancesAttending[cId] = self.tInstancesAttending[cId] or {}
self.tInstancesAttending[cId][rId] = self:BuildDateTable(rTbl.fEndTime)
self.tInstancesAttending[cId][rId].nInstanceContentId = ...
elseif eType == keAttendedEvents.WorldBoss then
self.tWorldBossesAttending[cId] = self.tWorldBossesAttending[cId] or {}
self.tWorldBossesAttending[cId][rId] = self:BuildDateTable(rTbl.fEndTime)
self.tWorldBossesAttending[cId][rId].nEventId = ...
else --keAttendedEvents.Daily
return
end
end
function EssenceEventTracker:IsAttended(rTbl)
local eType = ktContentTypeToAttendedEvent[rTbl.src.nContentType]
local tAttendingEvents = (eType == keAttendedEvents.Instance and self.tInstancesAttending
or eType == keAttendedEvents.WorldBoss and self.tWorldBossesAttending
or nil)
if not tAttendingEvents then return false end
local tAttendEndings = tAttendingEvents[rTbl.src.nContentId]
if not tAttendEndings then return false end
local tEnd = tAttendEndings[rTbl.tReward.nRewardType]
if not tEnd then return false end
local fEnd = tEnd.nGameTime
if not fEnd then return false end
return math.abs(fEnd - rTbl.fEndTime) < 60
end
function EssenceEventTracker:CheckForAttendance(rTbl)
local eType = ktContentTypeToAttendedEvent[rTbl.src.nContentType]
if eType == keAttendedEvents.Instance then
self:CheckForInstanceAttendance(rTbl)
elseif eType == keAttendedEvents.WorldBoss then
self:CheckForWorldBossAttendance(rTbl)
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:CheckRestoredAttendingInstances()
local inst, bFailed = self:GetCurrentInstance()
if bFailed then
self.CheckRestoredAttendingInstancesTimer = (self.CheckRestoredAttendingInstancesTimer
or ApolloTimer.Create(0.1, true, "CheckRestoredAttendingInstances", self))
return
else
self.CheckRestoredAttendingInstancesTimer = (self.CheckRestoredAttendingInstancesTimer
and self.CheckRestoredAttendingInstancesTimer:Stop() or nil)
if not inst then
return self:ClearAttendings(keAttendedEvents.Instance)
end
end
if not self.tInstancesAttending or not next(self.tInstancesAttending) then return end
local temp,a,b = self.tInstancesAttending,nil,nil --a,b just passthrough for AdjustDateTable
self.tInstancesAttending = {}
for cId, tEnd in pairs(temp) do
for rId, tDate in pairs(tEnd) do
if tDate.nInstanceContentId == inst.nContentId then
self.tInstancesAttending[cId] = self.tInstancesAttending[cId] or {}
self.tInstancesAttending[cId][rId],a,b = self:AdjustDateTable(tDate,a,b)
self.tInstancesAttending[cId][rId].nInstanceContentId = inst.nContentId
end
end
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:CheckRestoredAttendingWorldBosses()
local events = PublicEvent and PublicEvent.GetActiveEvents()
if not events then
self.CheckRestoredAttendingWorldBossesTimer = (self.CheckRestoredAttendingWorldBossesTimer
or ApolloTimer.Create(0.1, true, "CheckRestoredAttendingWorldBosses", self))
return
else
self.CheckRestoredAttendingWorldBossesTimer = (self.CheckRestoredAttendingWorldBossesTimer
and self.CheckRestoredAttendingInstancesTimer:Stop() or nil)
end
--basically we just want to wait till 'events' is available, to then trigger this updating process:
self.tWorldBossesAttending = {}
self:CheckForWorldBossAttendance(nil)
self:UpdateAll()
self:UpdateFeaturedList()
end
---------------------------------------------------------------------------------------------------
-- Controls Events
---------------------------------------------------------------------------------------------------
function EssenceEventTracker:OnHeadlineBtnMouseEnter(wndHandler, wndControl)
if wndHandler == wndControl then
wndHandler:FindChild("MinimizeBtn"):Show(true)
end
end
function EssenceEventTracker:OnHeadlineBtnMouseExit(wndHandler, wndControl)
if wndHandler == wndControl then
local wndBtn = wndHandler:FindChild("MinimizeBtn")
wndBtn:Show(wndBtn:IsChecked())
end
end
function EssenceEventTracker:OnHeadlineMinimizeBtnChecked(wndHandler, wndControl, eMouseButton)
self.tMinimized.bRoot = true
self:UpdateAll()
end
function EssenceEventTracker:OnHeadlineMinimizeBtnUnChecked(wndHandler, wndControl, eMouseButton)
self.tMinimized.bRoot = false
self:UpdateAll()
end
function EssenceEventTracker:OnDoneHeadlineBtnMouseEnter(wndHandler, wndControl)
if wndHandler == wndControl then
wndHandler:FindChild("MinimizeBtn"):Show(true)
end
end
function EssenceEventTracker:OnDoneHeadlineBtnMouseExit(wndHandler, wndControl)
if wndHandler == wndControl then
wndHandler:FindChild("MinimizeBtn"):Show(false)
end
end
function EssenceEventTracker:OnDoneHeadlineMinimizeBtnChecked(wndHandler, wndControl, eMouseButton)
self.tMinimized.bDoneRoot = true
self:UpdateAll()
end
function EssenceEventTracker:OnDoneHeadlineMinimizeBtnUnChecked(wndHandler, wndControl, eMouseButton)
self.tMinimized.bDoneRoot = false
self:UpdateAll()
end
function EssenceEventTracker:OnGenerateTooltip(wndControl, wndHandler, eType, arg1, arg2)
end
function EssenceEventTracker:OnEssenceItemClick(wndHandler, wndControl, eMouseButton, bDoubleClick)
if not bDoubleClick or wndHandler~=wndControl then return end
local rTbl = wndHandler:GetParent():GetData() --Button -> EssenceItem
if self:IsAttended(rTbl) then --Mark as Done + Remove Attendance
self:MarkAsDone(rTbl)
self:ClearAttendings(nil, rTbl)
else
self:MarkAsDone(rTbl, true)
self:CheckForAttendance(rTbl)
end
self:UpdateAll()
self:UpdateFeaturedList()
end
function EssenceEventTracker:EssenceItemMouseExit(wndHandler, wndControl)
if wndHandler == wndControl then
wndHandler:FindChild("QueueButton"):Show(false)
end
end
function EssenceEventTracker:EssenceItemMouseEnter(wndHandler, wndControl)
local rTbl = wndHandler:GetParent():GetData()
if wndHandler == wndControl and ktContentTypeToAttendedEvent[rTbl.src.nContentType] == keAttendedEvents.Instance then
wndHandler:FindChild("QueueButton"):Show(true)
end
end
function EssenceEventTracker:OnQueueButtonClick(wndHandler, wndControl, eMouseButton, bDoubleClick)
local rTbl = wndHandler:GetParent():GetParent():GetData()
Event_FireGenericEvent("ContentQueueStart", rTbl.src.nContentId, self:GetTitle(rTbl.src))
end
---------------------------------------------------------------------------------------------------
-- Helpers
---------------------------------------------------------------------------------------------------
do
local function buildRet(...)
return {...}, select("#", ...)
end
local function returnRet(tbl, max, idx)
idx = idx or 1
if idx > max then return end
return tbl[idx], returnRet(tbl, max, idx+1)
end
function EssenceEventTracker:SilentPostHook(object, method, handler)
if type(handler) ~= "function" and type(handler) ~= "string" then
error(("Usage: SilentPostHook(object, method, handler): 'handler' - expected function or string got %s"):format(
type(handler)), 2)
end
local f = (type(handler) == "function" and handler or
function(...) self[handler](self,...) end)
self:RawHook(object, method, function(...)
local a,b = buildRet(self.hooks[object][method](...))
f(a,...)
return returnRet(a,b)
end)
end
end
function EssenceEventTracker:HelperTimeString(fTime, strColorOverride)
local fSeconds = fTime % 60
local fMinutes = (fTime / 60)%60
local fHours = (fTime / 3600)%24
local fDays = (fTime / 86400)
local strColor = kstrColors.kstrYellow
if strColorOverride then
strColor = strColorOverride
end
local strTime;
if fDays >= 1 then
strTime = ("%dd"):format(fDays)
elseif fHours >= 1 then
strTime = ("%dh"):format(fHours)
else
strTime = ("%d:%.02d"):format(fMinutes, fSeconds)
end
return string.format("<T Font=\"CRB_InterfaceMedium_B\" TextColor=\"%s\">(%s)</T>", strColor, strTime)
end
function EssenceEventTracker:HelperColorize(str, strColor)
return string.format("<T TextColor=\"%s\">%s</T>", strColor, str)
end
function EssenceEventTracker:HelperColorizeIf(str, strColor, bIf)
if bIf then
return self:HelperColorize(str, strColor)
else
return str
end
end
do
local constants = {
[1] = 31 * 86400,
[2] = 28 * 86400,
[3] = 31 * 86400,
[4] = 30 * 86400,
[5] = 31 * 86400,
[6] = 30 * 86400,
[7] = 31 * 86400,
[8] = 31 * 86400,
[9] = 30 * 86400,
[10]= 31 * 86400,
[11]= 30 * 86400,
[12]= 31 * 86400,
}
--this is no readable date-table. But its fine to compare with others.
function EssenceEventTracker:BuildDateTable(fTime, fNow, tNow)
fNow = fNow or GameLib.GetGameTime()
tNow = tNow or GameLib.GetServerTime()
local dT = fTime-fNow
return {
nYear = tNow.nYear,
nMonth = tNow.nMonth,
nDay = tNow.nDay,
nHour = tNow.nHour,
nMinute = tNow.nMinute,
nSecond = tNow.nSecond + dT,
nGameTime = fTime,
}
end
function EssenceEventTracker:AdjustDateTable(tTime, fNow, tNow)
fNow = fNow or GameLib.GetGameTime()
tNow = tNow or GameLib.GetServerTime()
tTime.nGameTime = fNow+self:CompareDateTables(tNow, tTime)
return tTime, fNow, tNow
end
function EssenceEventTracker:CompareDateTables(date1, date2) --returns seconds between date1 and date2
local nTotal = 0
local nYear = 0
if date1.nYear < date2.nYear then
local diff = date2.nYear-date1.nYear
nTotal = nTotal + diff * 31536000
nTotal = nTotal + math.floor(((date1.nYear-1)%4+diff)/4) * 86400
nYear = date1.nYear
elseif date1.nYear > date2.nYear then
local diff = date1.nYear-date2.nYear
nTotal = nTotal - diff * 31536000
nTotal = nTotal - math.floor(((date2.nYear-1)%4+diff)/4) * 86400
nYear = date2.nYear
end
if date1.nMonth < date2.nMonth then
for i = date1.nMonth, date2.nMonth-1, 1 do
nTotal = nTotal + constants[i]
end
if nYear%4 == 0 and date1.nMonth <= 2 and date2.nMonth > 2 then
nTotal = nTotal + 86400 --+1 day
end
elseif date1.nMonth > date2.nMonth then
for i = date2.nMonth, date1.nMonth-1, 1 do
nTotal = nTotal - constants[i]
end
if nYear%4 == 0 and date2.nMonth <= 2 and date1.nMonth > 2 then
nTotal = nTotal - 86400
end
end
if date1.nDay ~= date2.nDay then
nTotal = nTotal + (date2.nDay-date1.nDay)*86400
end
if date1.nHour ~= date2.nHour then
nTotal = nTotal + (date2.nHour-date1.nHour)*3600
end
if date1.nMinute ~= date2.nMinute then
nTotal = nTotal + (date2.nMinute-date1.nMinute)*60
end
nTotal = nTotal + date2.nSecond - date1.nSecond
return nTotal
end
end
local EssenceEventTrackerInst = EssenceEventTracker:new()
EssenceEventTrackerInst:Init()
|
local SHADER_NAME = "WithoutShadow";
_G["Create"..SHADER_NAME.."Shader"] = function()
local vertexShader = [[
uniform mat4 cl_ModelViewProjectionMatrix;
attribute vec4 Position;
attribute vec2 TexCoord;
varying vec2 vTexCoords;
void main()
{
vTexCoords = TexCoord;
gl_Position = cl_ModelViewProjectionMatrix * Position;
};
]];
local fragShader = [[
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 vTexCoords;
uniform sampler2D TexSample;
void main()
{
gl_FragColor = texture2D(TexSample, vTexCoords);
};
]];
files.Write("shaders/Lighting/Vert"..SHADER_NAME..".fx", vertexShader);
files.Write("shaders/Lighting/Frag"..SHADER_NAME..".fx", fragShader);
return Shader("shaders/Lighting/Vert"..SHADER_NAME..".fx", "shaders/Lighting/Frag"..SHADER_NAME..".fx");
end; |
-- Zytharian (roblox: Legend26)
-- Initialize all the classes
local projectRoot = game.ServerScriptService
-- Includes
local Util = require(projectRoot.Modules.Utilities)
-- Initialize StandardClasses and ClassSystem
require(projectRoot.Modules.ClassSystem)
require(projectRoot.Modules.StandardClasses)
-- Initialize server classes
local numClasses = 0
local dPrint = Util.Debug.print
local DEBUG = true
initClasses = (function (obj)
for _,v in next, obj:GetChildren() do
dPrint("-> Init class " .. v.Name, DEBUG)
numClasses = numClasses + 1
require(v)
initClasses(v)
end
end)
dPrint("Initializing classes", DEBUG)
initClasses(script)
dPrint("Classes initialized: #" .. numClasses, DEBUG)
return false |
local awful = require('awful')
local beautiful = require('beautiful')
local gears = require('gears')
local wibox = require('wibox')
local display = require('sanity/util/display')
local FontIcon = require('sanity/util/fonticon')
local client_geos = {}
function client_or_tag_floating(c)
if c.maximized then
return false
end
if c.floating then
return true
end
local tag_floating = false
if c.first_tag then
local tag_layout_name = awful.layout.getname(c.first_tag.layout)
tag_floating = tag_layout_name == 'floating'
end
return tag_floating
end
function should_show_titlebars(c)
return not c.requests_no_titlebar and client_or_tag_floating(c)
end
function apply_geometry(c)
if client_or_tag_floating(c) and client_geos[c.window] ~= nil then
c:geometry(client_geos[c.window])
end
end
function save_geometry(c)
if client_or_tag_floating(c) then
client_geos[c.window] = c:geometry()
end
end
tag.connect_signal('property::layout', function(t)
for _, c in ipairs(t:clients()) do
if client_or_tag_floating(c) then
apply_geometry(c)
end
c:emit_signal('request::titlebars')
end
end)
tag.connect_signal('request::screen', function(t)
for s in screen do
if s ~= t.screen then
local t2 = awful.tag.find_by_name(s, t.name)
if t2 then
t:swap(t2)
else
t.screen = s
end
return
end
end
end)
client.connect_signal('manage', function(c)
if awesome.startup and
not c.size_hints.user_position
and not c.size_hints.program_position then
-- Prevent clients from being unreachable after screen count changes.
awful.placement.no_offscreen(c)
end
c.shape = beautiful.border_shape
save_geometry(c)
c.launch_time = os.time(os.date("!*t"))
end)
client.connect_signal('property::tags', function(c)
-- fixes new clients and moving clients between
-- tags not updating the titlebars
c:emit_signal('request::titlebars')
end)
-- Add a titlebar if titlebars_enabled is set to true in the rules.
client.connect_signal('request::titlebars', function(c)
-- buttons for the titlebar
local buttons = gears.table.join(
awful.button({ }, 1, function()
client.focus = c
c:raise()
awful.mouse.client.move(c)
end),
awful.button({ }, 3, function()
client.focus = c
c:raise()
awful.mouse.client.resize(c)
end)
)
local icon_widget
local font_icon
local font_icon_override = display.get_icon_for_client(c)
if font_icon_override then
font_icon = FontIcon {
icon = font_icon_override,
size = 20,
margin_l = 4,
margin_t = 0,
margin_b = 0,
color = colors.gray
}
icon_widget = wibox.container.margin(
font_icon,
2, 2, 2, 2
)
else
icon_widget = wibox.container.margin(
awful.titlebar.widget.iconwidget(c),
4, 4, 4, 4
)
end
c.update_titlebar = function(focused)
if font_icon_override and font_icon then
if focused then
font_icon:update(font_icon_override, beautiful.border_focus)
elseif c.ontop then
font_icon:update(font_icon_override, beautiful.border_ontop)
else
font_icon:update(font_icon_override, beautiful.fg_normal)
end
end
end
awful.titlebar(c) : setup {
{ -- Left
icon_widget,
buttons = buttons,
layout = wibox.layout.fixed.horizontal
},
{ -- Middle
{ -- Title
align = 'center',
widget = awful.titlebar.widget.titlewidget(c)
},
buttons = buttons,
layout = wibox.layout.flex.horizontal
},
{ -- Right
awful.titlebar.widget.minimizebutton(c),
awful.titlebar.widget.maximizedbutton(c),
awful.titlebar.widget.closebutton(c),
layout = wibox.layout.fixed.horizontal()
},
layout = wibox.layout.align.horizontal
}
if not should_show_titlebars(c) then
awful.titlebar.hide(c)
end
c.maximized_vertical = false
c.maximized_horizontal = false
end)
client.connect_signal('property::floating', function(c)
if should_show_titlebars(c) then
awful.titlebar.show(c)
else
awful.titlebar.hide(c)
end
apply_geometry(c)
end)
client.connect_signal('property::maximized', function(client)
if client.maximized then
client.border_width = 0
client.shape = nil
else
client.border_width = beautiful.border_width
client.shape = beautiful.border_shape
end
end)
client.connect_signal('property::fullscreen', function(client)
awful.screen.focused().mywibar.visible = not awful.screen.focused().mywibar.visible
-- no idea why this only works with `client.maximized` but not `client.fullscreen`
if client.maximized then
client.border_width = 0
client.shape = nil
else
client.border_width = beautiful.border_width
client.shape = beautiful.border_shape
end
end)
function apply_border_color(c, focused)
if focused then
c.border_color = beautiful.border_focus
elseif c.ontop then
c.border_color = beautiful.border_ontop
else
c.border_color = beautiful.border_normal
end
if c.update_titlebar then
c.update_titlebar(focused)
end
end
client.connect_signal('focus', function(c)
apply_border_color(c, true)
end)
client.connect_signal('unfocus', function(c)
apply_border_color(c, false)
end)
client.connect_signal('property::ontop', function(c)
apply_border_color(c, true)
end)
client.connect_signal('request::activate', function(c, context, hints)
c.minimized = false
awful.ewmh.activate(c, context, hints)
end)
client.connect_signal('property::urgent', function()
awful.client.urgent.jumpto(false)
end)
client.connect_signal('untagged', function()
-- HACK: fix exiting from a fullscreen application
awful.screen.focused().mywibar.visible = true
end)
-- https://bbs.archlinux.org/viewtopic.php?pid=1106376#p1106376
client.connect_signal('property::geometry', save_geometry)
client.connect_signal('unmanage', function(c) client_geos[c.window] = nil end)
screen.connect_signal('primary_changed', function(s)
-- to avoid all tags being active on the new screen after the tag screen
-- handler swaps all the tags to the new screen
awful.tag.viewidx(0, s)
end)
|
#!/usr/bin/env tarantool
------------
-- File Watcher.
-- Watcher for files, directories, objects and services.
-- ...
-- @module watcher
-- @author hernandez, raciel
-- @license MIT
-- @copyright Raciel Hernández 2019
------------
local strict = require('strict')
local fiber = require('fiber')
local fio = require('fio')
local dig = require('digest')
local errno = require('errno')
local log = require('log')
local pairs = pairs
local ipairs = ipairs
local type = type
local os_time = os.time
local string_find = string.find
local fib_sleep = fiber.sleep
local fio_glob = fio.glob
local fio_is_dir = fio.path.is_dir
local fio_listdir = fio.listdir
local table_sort = table.sort
local db = require('db.engine')
local ut = require('util')
local FILE = require('types.file').FILE
local WATCHER = require('types.file').WATCHER
local SORT = require('types.file').SORT
local db_awatcher = db.awatcher
strict.on()
--[[
local FW_DEFAULT = {
PREFIX = 'FW',
ACTION = 'CREATION',
MAXWAIT = 60,
INTERVAL = 0.5,
CHECK_INTERVAL = 0.5,
ITERATIONS = 10
}
]]
local BULK_CAPACITY = 1000000
-- Add the last date of file modification
local function add_lst_modif( tbl )
local t = {}
local fio_lstat = fio.lstat
for _, v in pairs( tbl ) do
local lst_mod = fio_lstat(v)
if lst_mod then
t[#t+1] = {v, lst_mod.mtime}
else
t[#t+1] = {v, 0} --Artitrary zero for mtime when file not exist
end
end
return t
end
-- Take n items from a table
local function take_n_items(
--[[required]] tbl,
--[[required]] nitems )
if nitems == 0 then
return tbl --Take all items
elseif nitems == 1 then
if type(tbl[1])=='table' then
return { tbl[1][1] }
else
return { tbl[1] }
end
else
--Take the n first items
local t = {}
local item
for i = 1, nitems, 1 do
if type(tbl[i])=='table' then
item = tbl[i][1]
else
item = tbl[i]
end
t[#t+1] = item
end
return t
end
end
--- Sort Files by name or date of modification
-- Sort a list of files by name or change date
-- @param flst table : File list
-- @param sort_by string : Sorting criterion
-- @param take_n int : Return the first N elements for monitoring
-- @return sorted_list table: Sorted list
-- @fixme: Sort for date modification don't work
local function sort_files_by(
--[[required]] flst,
--[[required]] sort_by,
--[[required]] take_n)
local size = #flst
if take_n == 0 then return {} end
if size == 0 then return flst end
if take_n > size or not take_n then take_n = size end
if sort_by == SORT.NO_SORT then
return take_n_items(flst, take_n)
elseif sort_by == SORT.ALPHA_ASC then
table_sort(
flst,
function(a, b)
return a < b
end
)
return take_n_items(flst, take_n)
elseif sort_by == SORT.ALPHA_DSC then
table_sort(
flst,
function(a, b)
return a > b
end
)
return take_n_items(flst, take_n)
elseif sort_by == SORT.MTIME_ASC then
local flst_ex = add_lst_modif(flst)
table_sort(
flst_ex,
function(a, b)
return a[2] < b[2]
end
)
return take_n_items(flst_ex, take_n)
elseif sort_by == SORT.MTIME_DSC then
local flst_ex = add_lst_modif(flst)
table_sort(
flst_ex,
function(a, b)
return a[2] > b[2]
end
)
return take_n_items(flst_ex, take_n)
end
end
local bfd_end = fiber.cond() --Bulk file deletion end
--- Watcher for Bulk File Deletion
local function bulk_file_deletion(
wid,
bulk,
maxwait,
interval,
nmatch
)
fib_sleep(0.1)
local fio_exists = fio.path.lexists
local ini = os_time()
local notdelyet = bulk
while (os_time() - ini) < maxwait do
for i=1,#notdelyet do
local file = notdelyet[i]
if not file then break end
if not fio_exists(file) then
db_awatcher.upd(
wid, file, true, FILE.DELETED
)
notdelyet[i] = nil
end
end
if db_awatcher.match(wid, WATCHER.FILE_DELETION)>=nmatch then
break
end
fib_sleep(interval)
end
bfd_end:signal()
end
local bfa_end = fiber.cond() --Bulk file alteration end
--- Watcher for Bulk File Alteration
local function bulk_file_alteration(
wid,
bulk,
awhat,
maxwait,
interval,
nmatch
)
fib_sleep(0.1)
local fio_exists = fio.path.lexists
local fio_lstat = fio.lstat
local dig_sha256 = dig.sha256
local io_open = io.open
local ini = os_time()
local not_alter_yet = bulk
local is_over = false
while (os_time() - ini) < maxwait do
for i=1,#not_alter_yet do
if not_alter_yet[i] then
local file = not_alter_yet[i][1]
local attr = not_alter_yet[i][2]
if not file then break end
if not fio_exists(file) then
db_awatcher.upd(
wid, file, true, FILE.DISAPPEARED_UNEXPECTEDLY
)
not_alter_yet[i] = nil
else
local alter_lst = ''
local flf = fio_lstat(file)
local sha256
if not fio_is_dir(file) then
if flf.size ~= 0 then
local fh = io_open(file, 'r')
local cn = fh:read()
sha256 = dig_sha256(cn)
fh:close()
else
sha256 = ''
end
else
local lstdir = fio_listdir(file)
if not lstdir then
sha256 = ''
else
sha256 = dig_sha256(ut.tostring(lstdir))
end
end
if sha256 ~= attr.sha256 then
alter_lst = string.format(
'%s%s', alter_lst, FILE.CONTENT_ALTERATION
)
end
if flf.size ~= attr.size then
alter_lst = string.format(
'%s%s', alter_lst, FILE.SIZE_ALTERATION
)
end
if flf.ctime ~= attr.ctime then
alter_lst = string.format(
'%s%s', alter_lst, FILE.CHANGE_TIME_ALTERATION
)
end
if flf.mtime ~= attr.mtime then
alter_lst = string.format(
'%s%s', alter_lst, FILE.MODIFICATION_TIME_ALTERATION
)
end
if flf.uid ~= attr.uid then
alter_lst = string.format(
'%s%s', alter_lst, FILE.OWNER_ALTERATION
)
end
if flf.gid ~= attr.gid then
alter_lst = string.format(
'%s%s', alter_lst, FILE.GROUP_ALTERATION
)
end
if flf.inode ~= attr.inode then
alter_lst = string.format(
'%s%s', alter_lst, FILE.INODE_ALTERATION
)
end
if awhat == '1' and alter_lst ~= '' then
db_awatcher.upd(
wid, file, true, FILE.ANY_ALTERATION
)
not_alter_yet[i] = nil --Exclude item
else
if string_find(alter_lst, awhat) then
db_awatcher.upd(
wid, file, true, awhat
)
not_alter_yet[i] = nil --Exclude item
end
end
end
if db_awatcher.match(wid, awhat)>=nmatch then
is_over = true
break
end
fib_sleep(interval)
end
end
if is_over then
break
end
end
bfa_end:signal()
end
--deep: {0, 1,2,3,4,5..}
local function recursive_tree(
--[[required]] root,
--[[optional]] deep,
--[[optional]] shidden
)
local _deep = deep or {0} --zero for all directory deep
local _shidden = shidden or false --false for ignore the hidden files and folders
table.sort(_deep) --Sort _deep
local function get_level (path)
local folders={}
for str in string.gmatch(path, "([^/]+)") do
table.insert(folders, str)
end
return #folders
end
local level_root = get_level(root) --root level ref
local t = {} --table resultant
local function explore_dir(dir)
local level = get_level(dir) - level_root
if (level > _deep[#_deep]) then
return t
end
if fio_is_dir(dir) then
local flst = fio_listdir(dir)
if flst then
for k=1,#flst do
local file = flst[k]
local ofile
if (string.byte(file, 1) ~= 46) or (_shidden == true) then
ofile = string.format('%s/%s', dir, file)
if (_deep[1]==0) or (ut.is_valof(_deep, level)) then
t[#t+1] = ofile
end
if fio_is_dir(ofile) then
explore_dir(ofile)
end
end
end
end
collectgarbage()
end
end
explore_dir(root)
return t
end
--- Consolidate the watch list items
-- Expand patterns types if exists and Remove duplicates for FW Deletion
local function consolidate(
wlist,
recur,
deep,
hidden
)
local _recur = recur or false
local _deep = deep or {0}
local _hidden = hidden or false
local _wlist = ut.deduplicate(wlist)
local t = {}
for _,v in pairs(_wlist) do
if v ~= '' then
if string_find(v, '*') then
local pattern_result = fio_glob(v)
--Merge pattern items result with t
for _,nv in ipairs(pattern_result) do
t[#t+1] = nv
end
else
if (_recur==true) and fio_is_dir(v) then
local tr = recursive_tree(v, _deep, _hidden)
for rv = 1, #tr do
t[#t+1] = tr[rv]
end
else
t[#t+1] = v
end
end
end
end
if #t~=0 then
return ut.deduplicate(t)
else
return {}
end
end
-- Determines if a file is stable in relation to its size and layout
-- If the size does not vary in the given conditions, then return true
local function is_stable_size(
--[[require]] path,
--[[optional]] interval,
--[[optional]] iterations)
local p_interval = interval or 1
local p_iterations = iterations or 15
local is_stable
local fio_lstat = fio.lstat
local r_size = fio_lstat(path).size --reference size
local mssg
local stable_iter = 0 --Stable iteration couter
while true do
local o_lstat = fio_lstat(path)
local f_size
if o_lstat then
f_size = o_lstat.size
if f_size == r_size then
stable_iter = stable_iter +1
if stable_iter > p_iterations then
is_stable = true
break
else
fib_sleep(p_interval)
end
else
stable_iter = 0
end
else
--File dissapear
mssg = FILE.DISAPPEARED_UNEXPECTEDLY
is_stable = false
break
end
r_size = f_size --Update the reference size
end
if not is_stable then is_stable = false end
return is_stable, mssg
end
local bfc_end = fiber.cond() --Bulk file creacion end
local function bulk_file_creation(
wid,
bulk,
maxwait,
interval,
minsize,
stability,
novelty,
nmatch)
fib_sleep(0.1)
local fio_lexists = fio.path.lexists
local fio_lstat = fio.lstat
local ini = os_time()
local nfy = bulk --not_found_yet
local fnd = {} --founded
local nff = 0
local nfp = 0
local ch_cff = fiber.channel(BULK_CAPACITY)
local function check_files_found(
ch,
_minsize,
_stability,
_novelty
)
while true do
local data = ch:get()
if data == nil then
break
end
fiber.create(
function()
if _novelty then
local lmod = fio_lstat(data).mtime
if not (lmod >= _novelty[1] and lmod <= _novelty[2]) then
db_awatcher.upd(
wid, data, false, FILE.IS_NOT_NOVELTY
)
return
end
end
if _stability then
local stble, merr = is_stable_size(
data,
_stability[1],
_stability[2]
)
if not stble then
db_awatcher.upd(
wid, data, false, FILE.UNSTABLE_SIZE
)
if merr then
db_awatcher.upd(wid, data, false, merr)
end
return
end
end
if _minsize then
if not (fio_lstat(data).size >= minsize) then
db_awatcher.upd(wid, data, false, FILE.UNEXPECTED_SIZE)
return
end
end
db_awatcher.upd(wid, data, true, FILE.HAS_BEEN_CREATED)
end
)
end
end
fiber.create(
check_files_found,
ch_cff,
minsize,
stability,
novelty
)
while ((os_time() - ini) < maxwait) do
for k,v in pairs(nfy) do
if not string_find(v, '*') then
if fio_lexists(v) then
fnd[#fnd+1]=v
nfy[k] = nil
nff = nff + 1
if stability or minsize or novelty then
ch_cff:put(v, 0)
else
db_awatcher.upd(
wid, v, true, FILE.HAS_BEEN_CREATED
)
end
end
else
local pit = fio_glob(v) --pattern_items
if #pit~=0 then
for _,u in pairs(pit) do
if not ut.is_valof(fnd, u) then
fnd[#fnd+1]=u
nfp = nfp + 1
if stability or minsize or novelty then
db_awatcher.add(wid, u)
ch_cff:put(u, 0)
else
db_awatcher.put(wid, u, true, FILE.HAS_BEEN_CREATED)
end
end
end
end
end
end
--Exit as soon as posible
if db_awatcher.match(wid)>=nmatch then
break
end
fib_sleep(interval)
end
--'MAXWAIT_TIMEOUT'
bfc_end:signal()
end
--File watcher deletion
local function file_deletion(
wid,
cwlist,
maxwait,
interval,
sort,
cases,
match)
local cwlist_o = sort_files_by(cwlist, sort, cases)
local nbulks = math.floor(1 + (#cwlist)/BULK_CAPACITY)
local bulk_fibs = {} --Fiber list
local pos = 0
for i = 1, nbulks do
local bulk = {}
local val
for j = 1, BULK_CAPACITY do
pos = pos + 1
val = cwlist_o[pos]
if val then
bulk[j] = val
db_awatcher.add(wid, val, false, FILE.NOT_YET_DELETED)
else
break
end
end
local bfid = fiber.create(
bulk_file_deletion,
wid,
bulk,
maxwait,
interval,
match
)
bfid:name('fwd-bulk-d')
bulk_fibs[i] = bfid
end
bfd_end:wait()
--Cancel fibers
for _, fib in pairs(bulk_fibs) do
local fid = fiber.id(fib)
pcall(fiber.cancel, fid)
end
return {
wid = wid,
ans = db_awatcher.close(wid, match, WATCHER.FILE_DELETION)
}
end
--- File Watch for File Creations
--
local function file_creation(
--[[required]] wid,
--[[required]] wlist,
--[[optional]] maxwait,
--[[optional]] interval,
--[[optional]] minsize,
--[[optional]] stability,
--[[optional]] novelty,
--[[optional]] match
)
local nbulks = math.floor(1 + (#wlist)/BULK_CAPACITY)
local bulk_fibs = {} --Fiber list
local pos = 0
for i = 1, nbulks do
local bulk = {}
local val
for j = 1, BULK_CAPACITY do
pos = pos + 1
val = wlist[pos]
if val then
bulk[j] = val
if not string_find(val, '*') then
db_awatcher.add(wid, val)
--[[else
--TODO: Review this, it is necessary?
db_awatcher.add(
wid,
val,
false,
FILE.IS_PATTERN
)
]]
end
else
break
end
end
local bfid = fiber.create(
bulk_file_creation,
wid,
bulk,
maxwait,
interval,
minsize,
stability,
novelty,
match
)
bfid:name('fwc-bulk-c')
bulk_fibs[i] = bfid
end
bfc_end:wait()
--Cancel fibers
for _, fib in pairs(bulk_fibs) do
local fid = fiber.id(fib)
pcall(fiber.cancel, fid)
end
return {
wid = wid,
ans = db_awatcher.close(
wid,
match,
WATCHER.FILE_CREATION
)
}
end
local function file_alteration(
wid,
wlist,
maxwait,
interval,
awhat,
match
)
local fio_lstat = fio.lstat
local dig_sha256 = dig.sha256
local io_open = io.open
local fio_exists = fio.path.lexists
local nbulks = math.floor(1 + (#wlist)/BULK_CAPACITY)
local bulk_fibs = {} --Fiber list
local pos = 0
for i = 1, nbulks do
local bulk = {}
local val
local k = 0
for _ = 1, BULK_CAPACITY do
pos = pos + 1
val = wlist[pos]
local _sha256
if val then
if fio_exists(val) then
local flf = fio_lstat(val)
--FIX: When file dissapear this fail with error
-- attempt to index local 'flf' (a nil value)
-- This occur when the file is erased or change extension
if not fio_is_dir(val) then
if flf.size ~= 0 then
local fh = io_open(val, 'r')
local cn = fh:read()
_sha256 = dig_sha256(cn)
fh:close()
else
_sha256 = ''
end
else
local lstdir = fio_listdir(val)
if not lstdir then
local message = {'Ignoring sha256 for', val, '-', errno.strerror()}
log.warn(table.concat(message, ' '))
_sha256 = ''
else
_sha256 = dig_sha256(ut.tostring(lstdir))
end
end
local as = {
sha256 = _sha256,
size = flf.size,
ctime = flf.ctime,
mtime = flf.mtime,
uid = flf.uid,
gid = flf.gid,
inode = flf.inode
}
k = k + 1
bulk[k] = {val, as}
db_awatcher.add(wid, val, false, FILE.NO_ALTERATION)
else
db_awatcher.put(wid, val, false, FILE.NOT_EXISTS) --0r dissapear?
end
else
break
end
end
if bulk[1] then
local bfid = fiber.create(
bulk_file_alteration,
wid,
bulk,
awhat,
maxwait,
interval,
match
)
bfid:name('fwa-bulk-a')
bulk_fibs[i] = bfid
end
end
if bulk_fibs[1] then
bfa_end:wait() --Waiting for ended
--Cancel fibers
for _, fib in pairs(bulk_fibs) do
local fid = fiber.id(fib)
pcall(fiber.cancel, fid)
end
end
return {
wid = wid,
ans = db_awatcher.close(wid, match, awhat)
}
end
-- Export API functions
return {
deletion = file_deletion,
creation = file_creation,
alteration = file_alteration,
consolidate = consolidate,
recursive = recursive_tree
} |
#!/bin/env lua
--------------------------------------------------------------------------------
-- Main Unit Test Script
--------------------------------------------------------------------------------
package.path = "navbar/?.lua;" .. package.path
local lu = require('luaunit')
local gen = require('generic')
local tree = require('tree')
-------------------------------------------------------------------------------
TestNodeSimple = {} -- class
function TestNodeSimple:setUp()
-- Set up our tests
local no_children = tree.NodeSimple("No Children")
local with_children = tree.NodeSimple("With Children")
local child1 = tree.NodeSimple("Children 1 with Children")
local child2 = tree.NodeSimple("Children 2")
local child3 = tree.NodeSimple("Children 3")
local childA = tree.NodeSimple("Children A")
local childB = tree.NodeSimple("Children B")
local linear0 = tree.NodeSimple(tree.SEP)
local linear1 = tree.NodeSimple('Path1')
local linear2 = tree.NodeSimple('Path2')
linear0:append(linear1)
linear1:append(linear2)
local simple = tree.NodeSimple("Simple", true)
with_children:append(child1)
with_children:append(child2)
with_children:append(child3)
child1:append(childA)
child1:append(childB)
self.nList = {
empty = tree.NodeSimple(),
simple = simple,
no_children = no_children,
with_children = with_children,
linear0 = linear0,
linear2 = linear2,
child1 = child1,
child2 = child2,
child3 = child3,
childA = childA,
childB = childB,
}
end
function TestNodeSimple:test_default()
local node = self.nList['empty']
assert(node.name == '', 'name not empty')
assert(gen.is_empty(node:get_children()), 'children not empty')
assert(node:get_parent() == nil, 'parent not nil')
end
function TestNodeSimple:test_simple()
local node = self.nList['simple']
assert(node.name == 'Simple', 'wrong name')
assert(gen.is_empty(node:get_children()), 'wrong children')
assert(node:get_parent() == nil, 'wrong parent')
end
function TestNodeSimple:test_append_child()
local parent = tree.NodeSimple("Parent")
local children = parent:get_children()
lu.assertEquals(children, {})
for i=1,5 do
local node = tree.NodeSimple("Node"..i)
parent:append(node)
lu.assertEquals(#children, i)
lu.assertEquals(parent, node:get_parent())
lu.assertEquals(children[#children], node)
end
end
function TestNodeSimple:test_count_children()
local no_children = self.nList['no_children']:get_children()
lu.assertEquals(#no_children, 0)
local with_children = self.nList['with_children']:get_children()
lu.assertEquals(#with_children, 3)
local child1 = self.nList['child1']:get_children()
lu.assertEquals(#child1, 2)
end
function TestNodeSimple:test_display_tree()
local node
local root
local treestr
-- An empty node returns ' ' = lead .. repeat*spacing .. space .. name
-- with lead = ' ', repeat='', name=''
node = self.nList['empty']
lu.assertEquals(node:tree('bare', 0), '. ')
-- If hide_me is set to true, returns ''
lu.assertEquals(node:tree('bare', 0, true), '')
-- A single node without children return the name of the node with some
-- indent.
node = self.nList['simple']
lu.assertEquals(node:tree('bare', 0), '. Simple')
-- If hide_me is set to true, returns ''
lu.assertEquals(node:tree('bare', 0, true), '')
-- A node with children returns the tree properly indented, the lead
-- character is 'v' for open node and '>' for closed nodes.
node = self.nList['child1']
lu.assertEquals(node:tree('bare', 0), 'v Children 1 with Children\n . Children A\n . Children B')
-- If hide_me is set to true, returns only the chidren.
lu.assertEquals(node:tree('bare', 0, true), '. Children A\n. Children B')
-- A node with a single child, which has a single child
node = self.nList['linear0']
treestr = 'v '..tree.SEP..'\n v Path1\n . Path2'
lu.assertEquals(node:tree('bare', 0), treestr)
-- A node with children and some children have children too.
node = self.nList['with_children']
treestr = 'v With Children\n v Children 1 with Children\n . Children A\n . Children B\n . Children 2\n . Children 3'
lu.assertEquals(node:tree('bare', 0), treestr)
-- If hide_me is set to true, returns only the chidren.
treestr = 'v Children 1 with Children\n . Children A\n . Children B\n. Children 2\n. Children 3'
lu.assertEquals(node:tree('bare', 0, true), treestr)
-- A node with children and some children have children too.
treestr = '- With Children\n - Children 1 with Children\n | . Children A\n | L Children B\n . Children 2\n L Children 3'
lu.assertEquals(node:tree('ascii'), treestr)
treestr = '▾ With Children\n ├ Children 1 with Children\n │ ├ Children A\n │ └ Children B\n ├ Children 2\n └ Children 3'
lu.assertEquals(node:tree('box'), treestr)
-- print('\n' .. self.nList['with_children']:tree('box', 0))
end
function TestNodeSimple:test_display_tree_with_closed_items()
local node
local root
local treestr
node = self.nList['empty']
lu.assertEquals(node:tree('bare', 0, false), '. ')
lu.assertEquals(node:tree('bare', 0, false, gen.set({''})), '. ') -- no children
node = self.nList['simple']
lu.assertEquals(node:tree('bare', 0, false), '. Simple')
lu.assertEquals(node:tree('bare', 0, false, gen.set({'Simple'})), '. Simple') -- no children
node = self.nList['linear0']
treestr = 'v '..tree.SEP..'\n v Path1\n . Path2'
lu.assertEquals(node:tree('bare', 0, false), treestr)
treestr = 'v '..tree.SEP..'\n > Path1'
closed = gen.set({tree.SEP..'/Path1'})
lu.assertEquals(node:tree('bare', 0, false, closed), treestr)
node = self.nList['with_children']
treestr = 'v With Children\n v Children 1 with Children\n . Children A\n . Children B\n . Children 2\n . Children 3'
lu.assertEquals(node:tree('bare', 0, false), treestr)
treestr = 'v With Children\n v Children 1 with Children\n . Children A\n . Children B\n . Children 2\n . Children 3'
closed = gen.set({'Children 1 with Children'})
lu.assertEquals(node:tree('bare', 0, false, closed), treestr)
closed = gen.set({'With ChildrenChildren 1 with Children'})
lu.assertEquals(node:tree('bare', 0, false, closed), treestr)
closed = gen.set({'/With Children/Children 1 with Children'})
lu.assertEquals(node:tree('bare', 0, false, closed), treestr)
closed = gen.set({'With Children/Children 1 with Children'})
treestr = 'v With Children\n > Children 1 with Children\n . Children 2\n . Children 3'
lu.assertEquals(node:tree('bare', 0, false, closed), treestr)
closed = gen.set({'With Children/Children 1 with Children', 'With Children/Children 2'})
treestr = 'v With Children\n > Children 1 with Children\n . Children 2\n . Children 3'
lu.assertEquals(node:tree('bare', 0, false, closed), treestr)
closed = gen.set({'With Children', 'With Children/Children 1 with Children', 'With Children/Children 2'})
treestr = '> With Children'
lu.assertEquals(node:tree('bare', 0, false, closed), treestr)
end
function TestNodeSimple:test_get_abs_label()
local node
local expected = {
empty = '',
simple = 'Simple',
no_children = 'No Children',
with_children = 'With Children',
linear0 = tree.SEP,
linear2 = tree.SEP..'/Path1/Path2',
child1 = 'With Children/Children 1 with Children',
child2 = 'With Children/Children 2',
child3 = 'With Children/Children 3',
childA = 'With Children/Children 1 with Children/Children A',
childB = 'With Children/Children 1 with Children/Children B',
}
for k, v in pairs(expected) do
node = self.nList[k]
lu.assertEquals(node:get_abs_label(), v)
end
end
-- class TestNode
--------------------------------------------------------------------------------
-- Running the test
--------------------------------------------------------------------------------
local runner = lu.LuaUnit.new()
-- runner:setOutputType("junit", "junit_xml_file")
os.exit(runner:runSuite())
|
function f(x, y)
return x*x + y*y*y;
end
|
local cVector = require 'libvctr'
local plpath = require 'pl.path'
local cVector = require 'libvctr'
local chunk_size = cVector.chunk_size()
local lVector = require 'Q/RUNTIME/VCTR/lua/lVector'
local Scalar = require 'libsclr'
local srcdir = "../gen_src/"
local incdir = "../gen_inc/"
if ( not plpath.isdir(srcdir) ) then plpath.mkdir(srcdir) end
if ( not plpath.isdir(incdir) ) then plpath.mkdir(incdir) end
local gen_code = require("Q/UTILS/lua/gen_code")
local q_qtypes = nil; local bqtypes = nil
if ( arg[1] ) then
qtypes = { arg[1] }
else
qtypes = { 'I1', 'I2', 'I4', 'I8','F4', 'F8' }
end
local num_produced = 0
local x = lVector({qtype = "B1"})
variations = { "vv", "vs", "sv", "ss" }
for _, variation in ipairs(variations) do
for _, qtype in ipairs(qtypes) do
local y, z
if ( variation == "vv" ) then
y = assert(lVector({qtype = qtype}))
z = assert(lVector({qtype = qtype}))
elseif ( variation == "vs" ) then
y = assert(lVector({qtype = qtype}))
z = assert(Scalar.new(0, qtype))
elseif ( variation == "sv" ) then
y = assert(Scalar.new(0, qtype))
z = assert(lVector({qtype = qtype}))
elseif ( variation == "ss" ) then
y = assert(Scalar.new(0, qtype))
z = assert(Scalar.new(0, qtype))
else
error("variaton = " .. vv)
end
local sp_fn_name = 'ifxthenyelsez_specialize'
local sp_fn = require(sp_fn_name)
local status, subs = pcall(sp_fn, variation, x, y, z)
if ( status ) then
gen_code.doth(subs, incdir)
gen_code.dotc(subs, srcdir)
print("Generated ", subs.fn)
num_produced = num_produced + 1
else
print(subs)
end
end
end
assert(num_produced > 0)
|
GeneralToolEditor = GeneralToolEditor or class(ToolEditor)
local difficulty_ids = {"normal", "hard", "overkill", "overkill_145", "easy_wish", "overkill_290", "sm_wish"}
local difficulty_loc = {
"menu_difficulty_normal",
"menu_difficulty_hard",
"menu_difficulty_very_hard",
"menu_difficulty_overkill",
"menu_difficulty_easy_wish",
"menu_difficulty_apocalypse",
"menu_difficulty_sm_wish"
}
local GenTool = GeneralToolEditor
function GenTool:init(parent)
GenTool.super.init(self, parent, "GeneralToolEditor")
end
function GenTool:build_menu()
self._holder:ClearItems()
local groups_opt = {align_method = "grid", control_slice = 0.5}
local opt = self:GetPart("opt")
local editors = self._holder:divgroup("Editors")
editors:button("EffectEditor", ClassClbk(self, "open_effect_editor"))
local game = self._holder:group("Game", groups_opt)
game:slider("GameSpeed", ClassClbk(self, "set_game_speed"), 1, {max = 10, min = 0.1, step = 0.3, wheel_control = true, help = "High settings can have a negative effect on game logic, use with caution"})
game:combobox("Difficulty", ClassClbk(self, "set_difficulty"), difficulty_loc, table.get_key(difficulty_ids, Global.game_settings.difficulty), {items_localized = true, items_pretty = true})
game:numberbox("MissionFilter", ClassClbk(self, "set_mission_filter"), Global.current_mission_filter or 0, {floats = 0, min = 0, max = 5, help = "Set a mission filter to be forced on the level, 0 uses the default filter."})
game:tickbox("PauseGame", ClassClbk(self, "pause_game"), false, {size_by_text = true})
game:tickbox("MuteMusic", ClassClbk(self, "mute_music"), false, {size_by_text = true})
game:button("FlushMemory", ClassClbk(Application, "apply_render_settings"), {size_by_text = true, help = "Clears unused textures from memory (has a small chance to break things)"})
local other = self._holder:group("Other", groups_opt)
other:s_btn("LogPosition", ClassClbk(self, "position_debug"))
if BeardLib.current_level then
other:s_btn("OpenMapInExplorer", ClassClbk(self, "open_in_explorer"))
end
other:s_btn("OpenLevelInExplorer", ClassClbk(self, "open_in_explorer", true))
other:tickbox("UseLight", ClassClbk(opt, "toggle_light"), false, {text = "Head Light", help = "Turn head light on / off"})
self._breakdown = self._holder:group("LevelBreakdown", groups_opt)
self:build_level_breakdown()
self._built = true
end
function GenTool:set_visible(visible)
GenTool.super.set_visible(self, visible)
if visible then
self:build_level_breakdown()
end
end
function GenTool:open_effect_editor()
managers.editor._particle_editor_active = true
managers.editor:set_enabled()
end
function GenTool:pause_game(item)
local paused = item:Value()
Application:set_pause(paused)
SoundDevice:set_rtpc("ingame_sound", paused and 0 or 1)
end
function GenTool:set_mission_filter(item)
local filter = item:Value()
Global.current_mission_filter = filter > 0 and filter or nil
managers.mission:set_mission_filter({Global.current_mission_filter})
end
function GenTool:mute_music(item)
local mute = item:Value()
if mute then
SoundDevice:set_rtpc("option_music_volume", 0)
else
SoundDevice:set_rtpc("option_music_volume", Global.music_manager.volume * 100)
end
end
function GenTool:set_game_speed(item)
local value = item:Value()
TimerManager:pausable():set_multiplier(value)
TimerManager:game_animation():set_multiplier(value)
end
function GenTool:set_difficulty(item)
local difficulty = item:Value()
Global.game_settings.difficulty = difficulty_ids[difficulty] or "normal"
tweak_data.character:init(tweak_data)
tweak_data:set_difficulty()
end
function GenTool:position_debug()
BLE:log("Camera Position: %s", tostring(managers.editor._camera_pos))
BLE:log("Camera Rotation: %s", tostring(managers.editor._camera_rot))
end
function GenTool:open_in_explorer(world_path)
local opt = self:GetPart("opt")
Application:shell_explore_to_folder(string.gsub(world_path == true and opt:map_world_path() or opt:map_path(), "/", "\\"))
end
function GenTool:build_level_breakdown()
local icons = BLE.Utils.EditorIcons
local opt = {size = self._holder.size * 0.9, inherit_values = {size = self._holder.size * 0.9, border_color = Color.green}, private = {full_bg_color = false, background_color = false}}
self._breakdown:ClearItems()
local tb = self._breakdown:GetToolbar()
tb:tb_imgbtn("Refresh", ClassClbk(self, "build_level_breakdown"), nil, icons.reset_settings, {help = "Recalculate List"})
local units_group = self._breakdown:divgroup("TotalUnits", opt)
tb = units_group:GetToolbar()
tb:tb_imgbtn("UnitSummary", ClassClbk(self, "create_level_summary"), nil, icons.list, {help = "Create Unit Summary"})
local elements_group = self._breakdown:divgroup("TotalElements", opt)
tb = elements_group:GetToolbar()
tb:tb_imgbtn("ElementSummary", ClassClbk(self, "create_level_summary"), nil, icons.list, {help = "Create Element Summary"})
local instances_group = self._breakdown:divgroup("TotalInstances", opt)
tb = instances_group:GetToolbar()
tb:tb_imgbtn("InstanceSummary", ClassClbk(self, "create_level_summary"), nil, icons.list, {help = "Create Instance Summary"})
local total_units = 0
local total_elements = 0
local total_instances = 0
local cont_id = managers.worlddefinition._start_id
local continents = managers.worlddefinition._continent_definitions
for _, continent in ipairs(managers.editor._continents) do
if continents[continent] then
local statics = continents[continent].statics and #continents[continent].statics or 0
units_group:divider(continent, {text = continent..": "..statics.." / "..cont_id})
total_units = total_units + statics
for name, data in pairs(managers.mission._missions[continent]) do
local elements = data.elements and #data.elements or 0
local instances = data.instances and #data.instances or 0
elements_group:divider(name, {text = name..": "..elements})
total_elements = total_elements + elements
total_instances = total_instances + instances
end
end
end
units_group:SetText("Total Units: "..total_units)
elements_group:SetText("Total Elements: "..total_elements)
instances_group:SetText("Total Instances: "..total_instances)
end
function GenTool:create_level_summary(item)
local entries = {}
local function add_entry(name, group)
group = group or ""
if entries[group] and entries[group][name] then
entries[group][name] = entries[group][name] + 1
else
entries[group] = entries[group] or {}
entries[group][name] = 1
end
end
local type = item:Name()
if type == "UnitSummary" then
for _, unit in pairs(World:find_units_quick("disabled", "all")) do
local ud = unit:unit_data()
if ud and ud.name then
add_entry(ud.name, ud.continent)
end
end
elseif type == "ElementSummary" then
for _, element in ipairs(self:GetPart("mission"):units()) do
local mission = element:mission_element()
if mission then
add_entry(mission.element.class, mission.element.script)
end
end
elseif type == "InstanceSummary" then
for _, name in pairs(managers.world_instance:instance_names()) do
local data = managers.world_instance:get_instance_data_by_name(name)
add_entry(data.folder, data.continent.." - "..data.script)
end
end
local list = {}
for group_name, group in pairs(entries) do
for name, times in pairs(group) do
if type == "ElementSummary" then name = string.pretty2(name:gsub("Element", ""):gsub("Editor", "")) end
table.insert(list, {name = string.format("%s (%d)", name, times), create_group = group_name, times = times})
end
end
table.sort(list, function(a, b)
return a.times > b.times
end)
BLE.ListDialog:Show({
list = list,
sort = false
})
end |
local o = {
-- Automatically save to log, otherwise only saves when requested
-- you need to bind a save key if you disable it
auto_save = true,
save_bind = "",
-- Runs automatically when --idle
auto_run_idle = true,
-- Write watch later for current file when switching
write_watch_later = true,
-- Display menu bind
display_bind = "`",
-- Middle click: Select; Right click: Exit;
-- Scroll wheel: Up/Down
mouse_controls = true,
-- Reads from config directory or an absolute path
log_path = "history.log",
-- Date format in the log (see lua date formatting)
date_format = "%d/%m/%y %X",
-- Show file paths instead of media-title
show_paths = false,
-- Split paths to only show the file or show the full path
split_paths = true,
-- Font settings
font_scale = 50,
border_size = 0.7,
-- Highlight color in BGR hexadecimal
hi_color = "H46CFFF",
-- Draw ellipsis at start/end denoting ommited entries
ellipsis = false
}
(require "mp.options").read_options(o)
local utils = require("mp.utils")
o.log_path = utils.join_path(mp.find_config_file("."), o.log_path)
local cur_title, cur_path
local list_drawn = false
function esc_string(str)
return str:gsub("([%p])", "%%%1")
end
function get_path()
local path = mp.get_property("path")
local title = mp.get_property("media-title"):gsub("\"", "")
if not path then return end
if path:find("http.?://") or path:find("magnet:%?") then
return title, path
else
return title, utils.join_path(mp.get_property("working-directory"), path)
end
end
function unbind()
if o.mouse_controls then
mp.remove_key_binding("recent-WUP")
mp.remove_key_binding("recent-WDOWN")
mp.remove_key_binding("recent-MMID")
mp.remove_key_binding("recent-MRIGHT")
end
mp.remove_key_binding("recent-UP")
mp.remove_key_binding("recent-DOWN")
mp.remove_key_binding("recent-ENTER")
mp.remove_key_binding("recent-1")
mp.remove_key_binding("recent-2")
mp.remove_key_binding("recent-3")
mp.remove_key_binding("recent-4")
mp.remove_key_binding("recent-5")
mp.remove_key_binding("recent-6")
mp.remove_key_binding("recent-7")
mp.remove_key_binding("recent-8")
mp.remove_key_binding("recent-9")
mp.remove_key_binding("recent-0")
mp.remove_key_binding("recent-ESC")
mp.remove_key_binding("recent-DEL")
mp.set_osd_ass(0, 0, "")
list_drawn = false
end
function read_log(func)
local f = io.open(o.log_path, "r")
if not f then return end
local list = {}
for line in f:lines() do
table.insert(list, (func(line)))
end
f:close()
return list
end
function read_log_table()
return read_log(function(line)
local t, p
t, p = line:match("^.-\"(.-)\" | (.*)$")
return {title = t, path = p}
end)
end
-- Write path to log on file end
-- removing duplicates along the way
function write_log(delete)
if not cur_path then return end
local content = read_log(function(line)
if line:find(esc_string(cur_path)) then
return nil
else
return line
end
end)
f = io.open(o.log_path, "w+")
if content then
for i=1, #content do
f:write(("%s\n"):format(content[i]))
end
end
if not delete then
f:write(("[%s] \"%s\" | %s\n"):format(os.date(o.date_format), cur_title, cur_path))
end
f:close()
end
-- Display list on OSD and terminal
function draw_list(list, start, choice)
local msg = string.format("{\\fscx%f}{\\fscy%f}{\\bord%f}",
o.font_scale, o.font_scale, o.border_size)
local hi_start = string.format("{\\1c&H%s}", o.hi_color)
local hi_end = "{\\1c&HFFFFFF}"
if o.ellipsis then
if start ~= 0 then
msg = msg.."..."
end
msg = msg.."\\h\\N\\N"
end
local size = #list
for i=1, math.min(10, size-start), 1 do
local key = i % 10
local p
if o.show_paths then
if o.split_paths and not list[size-start-i+1].path:find("^http.?://") then
_, p = utils.split_path(list[size-start-i+1].path)
else
p = list[size-start-i+1].path or ""
end
else
p = list[size-start-i+1].title or list[size-start-i+1].path or ""
end
if i == choice+1 then
msg = msg..hi_start.."("..key..") "..p.."\\N\\N"..hi_end
else
msg = msg.."("..key..") "..p.."\\N\\N"
end
if not list_drawn then
print("("..key..") "..p)
end
end
if o.ellipsis and start+10 < size then
msg = msg .."..."
end
mp.set_osd_ass(0, 0, msg)
end
-- Handle up/down keys
function select(list, start, choice, inc)
choice = choice + inc
if choice < 0 then
choice = choice + 1
start = start + inc
elseif choice >= math.min(#list, 10) then
choice = choice - 1
start = start + inc
end
if start > math.max(#list-10, 0) then
start = start - 1
elseif start < 0 then
start = start + 1
end
draw_list(list, start, choice)
return start, choice
end
-- Delete selected entry from the log
function delete(list, start, choice)
local playing_path = cur_path
cur_path = list[#list-start-choice].path
if not cur_path then
print("Failed to delete")
return
end
write_log(true)
print("Deleted \""..cur_path.."\"")
cur_path = playing_path
end
-- Load file and remove binds
function load(list, start, choice)
unbind()
if start+choice >= #list then return end
if o.write_watch_later then
mp.command("write-watch-later-config")
end
mp.commandv("loadfile", list[#list-start-choice].path, "replace")
end
-- Display list and add keybinds
function display_list()
if list_drawn then
unbind()
return
end
local list = read_log_table()
if not list or not list[1] then
mp.osd_message("Log empty")
return
end
local choice = 0
local start = 0
draw_list(list, start, choice)
list_drawn = true
mp.add_forced_key_binding("UP", "recent-UP", function()
start, choice = select(list, start, choice, -1)
end, {repeatable=true})
mp.add_forced_key_binding("DOWN", "recent-DOWN", function()
start, choice = select(list, start, choice, 1)
end, {repeatable=true})
mp.add_forced_key_binding("ENTER", "recent-ENTER", function()
load(list, start, choice)
end)
mp.add_forced_key_binding("DEL", "recent-DEL", function()
delete(list, start, choice)
list = read_log_table()
if not list or not list[1] then
unbind()
return
end
start, choice = select(list, start, choice, 0)
end)
if o.mouse_controls then
mp.add_forced_key_binding("WHEEL_UP", "recent-WUP", function()
start, choice = select(list, start, choice, -1)
end)
mp.add_forced_key_binding("WHEEL_DOWN", "recent-WDOWN", function()
start, choice = select(list, start, choice, 1)
end)
mp.add_forced_key_binding("MBTN_MID", "recent-MMID", function()
load(list, start, choice)
end)
mp.add_forced_key_binding("MBTN_RIGHT", "recent-MRIGHT", function()
unbind()
end)
end
mp.add_forced_key_binding("1", "recent-1", function() load(list, start, 0) end)
mp.add_forced_key_binding("2", "recent-2", function() load(list, start, 1) end)
mp.add_forced_key_binding("3", "recent-3", function() load(list, start, 2) end)
mp.add_forced_key_binding("4", "recent-4", function() load(list, start, 3) end)
mp.add_forced_key_binding("5", "recent-5", function() load(list, start, 4) end)
mp.add_forced_key_binding("6", "recent-6", function() load(list, start, 5) end)
mp.add_forced_key_binding("7", "recent-7", function() load(list, start, 6) end)
mp.add_forced_key_binding("8", "recent-8", function() load(list, start, 7) end)
mp.add_forced_key_binding("9", "recent-9", function() load(list, start, 8) end)
mp.add_forced_key_binding("0", "recent-0", function() load(list, start, 9) end)
mp.add_forced_key_binding("ESC", "recent-ESC", function() unbind() end)
end
if o.auto_save then
mp.register_event("end-file", function() write_log(false) end)
else
mp.add_key_binding(o.save_bind, "recent-save", function()
write_log(false)
mp.osd_message("Saved entry to log")
end)
end
if o.auto_run_idle then
mp.register_event("idle", display_list)
end
mp.register_event("file-loaded", function()
unbind()
cur_title, cur_path = get_path()
end)
mp.add_key_binding(o.display_bind, "display-recent", display_list)
|
package("libyaml")
set_homepage("http://pyyaml.org/wiki/LibYAML")
set_description("Canonical source repository for LibYAML.")
set_urls("https://github.com/yaml/libyaml/archive/$(version).tar.gz",
"https://github.com/yaml/libyaml.git")
add_versions("0.2.2", "46bca77dc8be954686cff21888d6ce10ca4016b360ae1f56962e6882a17aa1fe")
on_install("macosx", "linux", function (package)
if not os.isfile("configure") then
os.vrun("./bootstrap")
end
import("package.tools.autoconf").install(package)
end)
on_test(function (package)
assert(package:has_cfuncs("yaml_document_initialize", {includes = "yaml.h"}))
end)
|
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
function onThink() npcHandler:onThink() end
keywordHandler:addKeyword({'furniture'}, StdModule.say, {npcHandler = npcHandler, text = "Well, as you can see, I sell furniture. Ask me for a {trade} if you're interested to see my wares."})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = "My name is Nydala. I run this store."})
keywordHandler:addKeyword({'time'}, StdModule.say, {npcHandler = npcHandler, text = "It is |TIME|. Do you need a clock for your house?"})
npcHandler:setMessage(MESSAGE_GREET, "Welcome to Carlin Furniture Store, |PLAYERNAME|.")
npcHandler:setMessage(MESSAGE_SENDTRADE, "Have a look. Most furniture comes in handy kits. Just use them in your house to assemble the furniture. Do you want to see only a certain {type} of furniture?")
npcHandler:addModule(FocusModule:new())
|
local solarized_low = require('solarized.solarized-low.highlights')
local lightColors = {
none = {'none', 'none'},
base2 = {'#073642',23},
red = {'#dc322f',203},
green = {'#859900',142},
yellow = {'#b58900',178},
blue = {'#268bd2',38},
magenta = {'#d33682',169},
cyan = {'#2aa198',37},
base02 = {'#eee8d5',230},
back = {'#eee8d5',230},
base3 = {'#002b36',23},
orange = {'#cb4b16',166},
base1 = {'#586e75',102},
base0 = {'#657b83',103},
base00 = {'#839496',145},
violet = {'#6c71c4',104},
base01 = {'#93a1a1',145},
base03 = {'#fdf6e3',231},
err_bg = {'#fdf6e3',231}
}
local darkColors = {
none = {'none', 'none'},
base02 = {'#073642',23},
back = {'#073642',23},
red = {'#dc322f',203},
green = {'#859900',142},
yellow = {'#b58900',178},
blue = {'#268bd2',38},
magenta = {'#d33682',169},
cyan = {'#2aa198',37},
base2 = {'#eee8d5',230},
base03 = {'#002b36',23},
orange = {'#cb4b16',166},
base01 = {'#586e75',102},
base00 = {'#657b83',103},
base0 = {'#839496',145},
violet = {'#6c71c4',104},
base1 = {'#93a1a1',145},
base3 = {'#fdf6e3',231},
err_bg = {'#fdf6e3',231}
}
if vim.o.bg == 'light' then
solarized_low.load_syntax(lightColors)
solarized_low.terminal_colors(lightColors)
end
if vim.o.bg == 'dark' then
solarized_low.load_syntax(darkColors)
solarized_low.terminal_colors(darkColors)
end
|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local str_decode = require("string_decode")
--
-- A bootloader for Android used on various devices powered by Qualcomm
-- Snapdragon chips:
--
-- <https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors>
--
-- Although not all of the Snapdragon based Android devices use this particular
-- bootloader format, it is known that devices with the following chips have used
-- it (example devices are given for each chip):
--
-- * APQ8064 ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_S4_Pro))
-- - Nexus 4 "mako": [sample][sample-mako] ([other samples][others-mako]),
-- [releasetools.py](https://android.googlesource.com/device/lge/mako/+/33f0114/releasetools.py#98)
--
-- * MSM8974AA ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_800,_801_and_805_(2013/14)))
-- - Nexus 5 "hammerhead": [sample][sample-hammerhead] ([other samples][others-hammerhead]),
-- [releasetools.py](https://android.googlesource.com/device/lge/hammerhead/+/7618a7d/releasetools.py#116)
--
-- * MSM8992 ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_808_and_810_(2015)))
-- - Nexus 5X "bullhead": [sample][sample-bullhead] ([other samples][others-bullhead]),
-- [releasetools.py](https://android.googlesource.com/device/lge/bullhead/+/2994b6b/releasetools.py#126)
--
-- * APQ8064-1AA ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_600_(2013)))
-- - Nexus 7 \[2013] (Mobile) "deb" <a href="#doc-note-data-after-img-bodies">(\**)</a>: [sample][sample-deb] ([other samples][others-deb]),
-- [releasetools.py](https://android.googlesource.com/device/asus/deb/+/14c1638/releasetools.py#105)
-- - Nexus 7 \[2013] (Wi-Fi) "flo" <a href="#doc-note-data-after-img-bodies">(\**)</a>: [sample][sample-flo] ([other samples][others-flo]),
-- [releasetools.py](https://android.googlesource.com/device/asus/flo/+/9d9fee9/releasetools.py#130)
--
-- * MSM8996 Pro-AB ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_820_and_821_(2016)))
-- - Pixel "sailfish" <a href="#doc-note-bootloader-size">(\*)</a>:
-- [sample][sample-sailfish] ([other samples][others-sailfish])
-- - Pixel XL "marlin" <a href="#doc-note-bootloader-size">(\*)</a>:
-- [sample][sample-marlin] ([other samples][others-marlin])
--
-- * MSM8998 ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_835_(2017)))
-- - Pixel 2 "walleye" <a href="#doc-note-bootloader-size">(\*)</a>: [sample][sample-walleye] ([other samples][others-walleye])
-- - Pixel 2 XL "taimen": [sample][sample-taimen] ([other samples][others-taimen])
--
-- <small id="doc-note-bootloader-size">(\*)
-- `bootloader_size` is equal to the size of the whole file (not just `img_bodies` as usual).
-- </small>
--
-- <small id="doc-note-data-after-img-bodies">(\**)
-- There are some data after the end of `img_bodies`.
-- </small>
--
-- ---
--
-- On the other hand, devices with these chips **do not** use this format:
--
-- * <del>APQ8084</del> ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_800,_801_and_805_(2013/14)))
-- - Nexus 6 "shamu": [sample][foreign-sample-shamu] ([other samples][foreign-others-shamu]),
-- [releasetools.py](https://android.googlesource.com/device/moto/shamu/+/df9354d/releasetools.py#12) -
-- uses "Motoboot packed image format" instead
--
-- * <del>MSM8994</del> ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_808_and_810_(2015)))
-- - Nexus 6P "angler": [sample][foreign-sample-angler] ([other samples][foreign-others-angler]),
-- [releasetools.py](https://android.googlesource.com/device/huawei/angler/+/cf92cd8/releasetools.py#29) -
-- uses "Huawei Bootloader packed image format" instead
--
-- [sample-mako]: https://androidfilehost.com/?fid=96039337900113996 "bootloader-mako-makoz30f.img"
-- [others-mako]: https://androidfilehost.com/?w=search&s=bootloader-mako&type=files
--
-- [sample-hammerhead]: https://androidfilehost.com/?fid=385035244224410247 "bootloader-hammerhead-hhz20h.img"
-- [others-hammerhead]: https://androidfilehost.com/?w=search&s=bootloader-hammerhead&type=files
--
-- [sample-bullhead]: https://androidfilehost.com/?fid=11410963190603870177 "bootloader-bullhead-bhz32c.img"
-- [others-bullhead]: https://androidfilehost.com/?w=search&s=bootloader-bullhead&type=files
--
-- [sample-deb]: https://androidfilehost.com/?fid=23501681358552487 "bootloader-deb-flo-04.02.img"
-- [others-deb]: https://androidfilehost.com/?w=search&s=bootloader-deb-flo&type=files
--
-- [sample-flo]: https://androidfilehost.com/?fid=23991606952593542 "bootloader-flo-flo-04.05.img"
-- [others-flo]: https://androidfilehost.com/?w=search&s=bootloader-flo-flo&type=files
--
-- [sample-sailfish]: https://androidfilehost.com/?fid=6006931924117907154 "bootloader-sailfish-8996-012001-1904111134.img"
-- [others-sailfish]: https://androidfilehost.com/?w=search&s=bootloader-sailfish&type=files
--
-- [sample-marlin]: https://androidfilehost.com/?fid=6006931924117907131 "bootloader-marlin-8996-012001-1904111134.img"
-- [others-marlin]: https://androidfilehost.com/?w=search&s=bootloader-marlin&type=files
--
-- [sample-walleye]: https://androidfilehost.com/?fid=14943124697586348540 "bootloader-walleye-mw8998-003.0085.00.img"
-- [others-walleye]: https://androidfilehost.com/?w=search&s=bootloader-walleye&type=files
--
-- [sample-taimen]: https://androidfilehost.com/?fid=14943124697586348536 "bootloader-taimen-tmz30m.img"
-- [others-taimen]: https://androidfilehost.com/?w=search&s=bootloader-taimen&type=files
--
-- [foreign-sample-shamu]: https://androidfilehost.com/?fid=745849072291678307 "bootloader-shamu-moto-apq8084-72.04.img"
-- [foreign-others-shamu]: https://androidfilehost.com/?w=search&s=bootloader-shamu&type=files
--
-- [foreign-sample-angler]: https://androidfilehost.com/?fid=11410963190603870158 "bootloader-angler-angler-03.84.img"
-- [foreign-others-angler]: https://androidfilehost.com/?w=search&s=bootloader-angler&type=files
--
-- ---
--
-- The `bootloader-*.img` samples referenced above originally come from factory
-- images packed in ZIP archives that can be found on the page [Factory Images
-- for Nexus and Pixel Devices](https://developers.google.com/android/images) on
-- the Google Developers site. Note that the codenames on that page may be
-- different than the ones that are written in the list above. That's because the
-- Google page indicates **ROM codenames** in headings (e.g. "occam" for Nexus 4)
-- but the above list uses **model codenames** (e.g. "mako" for Nexus 4) because
-- that is how the original `bootloader-*.img` files are identified. For most
-- devices, however, these code names are the same.
-- See also: Source (https://android.googlesource.com/device/lge/hammerhead/+/7618a7d/releasetools.py)
AndroidBootldrQcom = class.class(KaitaiStruct)
function AndroidBootldrQcom:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function AndroidBootldrQcom:_read()
self.magic = self._io:read_bytes(8)
if not(self.magic == "\066\079\079\084\076\068\082\033") then
error("not equal, expected " .. "\066\079\079\084\076\068\082\033" .. ", but got " .. self.magic)
end
self.num_images = self._io:read_u4le()
self.ofs_img_bodies = self._io:read_u4le()
self.bootloader_size = self._io:read_u4le()
self.img_headers = {}
for i = 0, self.num_images - 1 do
self.img_headers[i + 1] = AndroidBootldrQcom.ImgHeader(self._io, self, self._root)
end
end
AndroidBootldrQcom.property.img_bodies = {}
function AndroidBootldrQcom.property.img_bodies:get()
if self._m_img_bodies ~= nil then
return self._m_img_bodies
end
local _pos = self._io:pos()
self._io:seek(self.ofs_img_bodies)
self._m_img_bodies = {}
for i = 0, self.num_images - 1 do
self._m_img_bodies[i + 1] = AndroidBootldrQcom.ImgBody(i, self._io, self, self._root)
end
self._io:seek(_pos)
return self._m_img_bodies
end
--
-- According to all available `releasetools.py` versions from AOSP (links are
-- in the top-level `/doc`), this should determine only the size of
-- `img_bodies` - there is [an assertion](
-- https://android.googlesource.com/device/lge/hammerhead/+/7618a7d/releasetools.py#167)
-- for it.
--
-- However, files for certain Pixel devices (see `/doc`) apparently declare
-- the entire file size here (i.e. including also fields from `magic` to
-- `img_headers`). So if you interpreted `bootloader_size` as the size of
-- `img_bodies` substream in these files, you would exceed the end of file.
-- Although you could check that it fits in the file before attempting to
-- create a substream of that size, you wouldn't know if it's meant to
-- specify the size of just `img_bodies` or the size of the entire bootloader
-- payload (whereas there may be additional data after the end of payload)
-- until parsing `img_bodies` (or at least summing sizes from `img_headers`,
-- but that's stupid).
--
-- So this field isn't reliable enough to be used as the size of any
-- substream. If you want to check if it has a reasonable value, do so in
-- your application code.
AndroidBootldrQcom.ImgHeader = class.class(KaitaiStruct)
function AndroidBootldrQcom.ImgHeader:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function AndroidBootldrQcom.ImgHeader:_read()
self.name = str_decode.decode(KaitaiStream.bytes_terminate(self._io:read_bytes(64), 0, false), "ASCII")
self.len_body = self._io:read_u4le()
end
AndroidBootldrQcom.ImgBody = class.class(KaitaiStruct)
function AndroidBootldrQcom.ImgBody:_init(idx, io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self.idx = idx
self:_read()
end
function AndroidBootldrQcom.ImgBody:_read()
self.body = self._io:read_bytes(self.img_header.len_body)
end
AndroidBootldrQcom.ImgBody.property.img_header = {}
function AndroidBootldrQcom.ImgBody.property.img_header:get()
if self._m_img_header ~= nil then
return self._m_img_header
end
self._m_img_header = self._root.img_headers[self.idx + 1]
return self._m_img_header
end
|
local Linq;
if (LibStub) then
Linq = LibStub("Linq");
else
Linq = require "linq";
end
--- @type Set|Enumerable
local Set = Linq.Set;
local assert, type, pairs, setmetatable = assert, type, pairs, setmetatable;
local tinsert = table.insert;
-- *********************************************************************************************************************
-- ** HashSet
-- *********************************************************************************************************************
--- @class HashSet : Set
local HashSet = {};
local HashSetMT = {__index = function(t, key, ...) return HashSet[key] or Linq.Enumerable[key]; end};
Mixin(HashSet, Set);
--- Initializes a new instance of the {@see HashSet} class.
--- @param source table|nil @The collection whose elements are copied to the new set, or `nil` to start with an empty set.
--- @param comparer function|nil @The function to use when comparing values in the set, or `nil` to use the default equality comparer.
--- @return HashSet @The new instance of {@see HashSet}.
function HashSet.New(source, comparer)
assert(source == nil or type(source) == "table");
local set = setmetatable({}, HashSetMT);
set.source = {};
set.Comparer = comparer;
set.Length = 0;
if (Linq.Enumerable.IsEnumerable(source)) then
for _, v in source:GetEnumerator() do set:Add(v); end
else
for _, v in pairs(source or {}) do set:Add(v); end
end
set:_SetIterator();
return set;
end
--- Removes all elements in the specified collection from the current {@see HashSet} object.
--- @param other table @The collection of items to remove from the {@see HashSet} object.
function HashSet:ExceptWith(other)
if (self.Length == 0) then
-- The set is already empty
return;
elseif (other == self) then
-- A set minus itself is empty
self:Clear();
else
for _, value in pairs(other) do
-- Remove every element in other from self
self:Remove(value);
end
end
end
--- Modifies the current {@see HashSet} object to contain only elements that are present in that object and in the specified collection.
--- @param other table @The collection to compare to the current {@see HashSet} object.
function HashSet:IntersectWith(other)
if (self.Length == 0 or other == self) then
-- Intersection with empty set is empty
-- Intersection with self is the same set
return;
else
-- Mark items taht are contained in both sets
local itemsToKeep = {};
for _, value in pairs(other) do
local key = self:_FindItemKey(value);
if (key ~= nil) then itemsToKeep[key] = true; end
end
-- Remove items that have not been marked
for key, _ in pairs(self.source) do
if (not itemsToKeep[key]) then
self.source[key] = nil;
self.Length = self.Length - 1;
end
end
end
end
-- --- TODO: Code+Test+Doc
-- function HashSet:RemoveWhere(predicate) end
--- Modifies the current {@see HashSet} object to contain only elements that are present either in that object or in the specified collection, but not both.
--- @param other table @The collection to compare to the current {@see HashSet} object.
function HashSet:SymmetricExceptWith(other)
if (self.Length == 0) then
-- If set is empty, then symmetric difference is other.
self:UnionWith(other);
elseif (other == self) then
-- The symmetric difference of a set with itself is the empty set.
self:Clear();
else
-- Mark items that could not be added and those that were added from the other set
local addedFromOther = {};
local itemsToRemove = {};
for _, value in pairs(other) do
if (self:Add(value)) then
tinsert(addedFromOther, value);
else
tinsert(itemsToRemove, value);
end
end
for _, value in pairs(Linq.Enumerable.From(itemsToRemove):Except(addedFromOther):ToArray()) do
-- Removes only items taht are marked as itemsToRemove but not addedFromOther
self:Remove(value);
end
end
end
--- Searches the set for a given value and returns the equal value it finds, if any.
--- @param equalValue any @The value to search for.
--- @return boolean @A value indicating whether the search was successful.
--- @return any @The value from the set that the search found, or `nil` when the search yielded no match.
function HashSet:TryGetValue(equalValue)
if (self.Comparer) then
for _, value in pairs(self.source) do
if (self.Comparer(value, equalValue)) then
-- The item exists in the set
return true, value;
end
end
-- This item does not exist in the set
return false, nil;
else
if (self.source[equalValue]) then
-- The item exists in the set
return true, equalValue;
else
-- This item does not exist in the set
return false, nil;
end
end
end
--- Modifies the current {@see HashSet} object to contain all elements that are present in itself, the specified collection, or both.
--- @param other table @The collection to compare to the current {@see HashSet} object.
function HashSet:UnionWith(other) for _, value in pairs(other) do self:Add(value); end end
-- *********************************************************************************************************************
-- ** Export
-- *********************************************************************************************************************
Linq.HashSet = HashSet;
|
local Native = require('lib.stdlib.native')
local converter = require('lib.stdlib.enum.converter')
---@class DialogEvent
local DialogEvent = {
ButtonClick = 90, --EVENT_DIALOG_BUTTON_CLICK
Click = 91, --EVENT_DIALOG_CLICK
}
DialogEvent = converter(Native.ConvertDialogEvent, DialogEvent)
return DialogEvent
|
function onStartCountdown()
-- Block the first countdown and start a timer of 0.8 seconds to play the dialogue
if not allowCountdown and isStoryMode and not seenCutscene then
setProperty('inCutscene', true);
runTimer('startDialogue', 0.8);
allowCountdown = true;
return Function_Stop;
end
return Function_Continue;
end
function onTimerCompleted(tag, loops, loopsLeft)
if tag == 'startDialogue' then -- Timer completed, play dialogue
startDialogue('dialogue', 'breakfast');
end
end
function onBeatHit()
if (getProperty(curBeat) == 48) then
--setProperty('defaultCamZoom', 1.2);
doTweenZoom('preDropZoom', 'camGame', 1.2, 4.8, 'quadInOut');
else
if (getProperty(curBeat) == 64) then
setProperty('defaultCamZoom', 0.8);
else
if (getProperty(curBeat) == 128) then
setProperty('defaultCamZoom', 1.0);
else
if (getProperty(curBeat) == 192) then
setProperty('defaultCamZoom', 1.2);
else
if (getProperty(curBeat) == 228) then
setProperty('defaultCamZoom', 0.8);
end
end
end
end
end
end |
---@class PetInfo
C_PetInfo = {}
---@param uiMapID number
---@return PetTamerMapInfo petTamers
function C_PetInfo.GetPetTamersForMap(uiMapID) end
---@class PetTamerMapInfo
---@field areaPoiID number
---@field position table
---@field name string
---@field atlasName string|nil
---@field textureIndex number|nil
local PetTamerMapInfo = {}
|
return {
summary = 'A box Shape.',
description = 'A type of `Shape` that can be used for cubes or boxes.',
extends = 'Shape',
constructors = {
'lovr.physics.newBoxShape',
'World:newBoxCollider'
}
}
|
--[[
Handler for the big red X that shows up when you
hit the wrong sort of object with the wrong sort of tool.
Stop trying to pickaxe trees!
]]
local propUIContainer = script:GetCustomProperty("UIContainer"):WaitForObject()
local propGraphicPanel = script:GetCustomProperty("GraphicPanel"):WaitForObject()
propUIContainer.isEnabled = false
local updateTask = nil
local baseColors = {}
for k,v in pairs (propGraphicPanel:FindDescendantsByType("UIImage")) do
baseColors[v] = v:GetColor()
end
local TIME_ON_SCREEN = 2
function OnWrongTool(worldPos)
if updateTask ~= nil then updateTask:Cancel() end
updateTask = Task.Spawn(function()
local startTime = time()
SetAlpha(1.0)
while time() < startTime + TIME_ON_SCREEN do
local screenPos = UI.GetScreenPosition(worldPos)
if screenPos ~= nil then
propUIContainer.isEnabled = true
propGraphicPanel.x = screenPos.x
propGraphicPanel.y = screenPos.y
else
propUIContainer.isEnabled = false
end
SetAlpha(1 - (time() - startTime) / TIME_ON_SCREEN)
Task.Wait()
end
propUIContainer.isEnabled = false
updateTask = nil
end)
end
function SetAlpha(alpha)
for k,v in pairs(baseColors) do
v.a = alpha
k:SetColor(v)
end
end
Events.Connect("WrongTool", OnWrongTool)
|
--[[
© 2020 TERRANOVA do not share, re-distribute or modify
without permission of its author (zacharyenriquee@gmail.com).
--]]
local PLUGIN = PLUGIN;
-- Called when a player's uniform status has been changed
function PLUGIN:AdjustPlayer(event, client)
local character = client:GetCharacter();
local cpData = character:GetCPInfo()
if(character:IsMetropolice()) then
if(event == "Unequipped") then
character:SetDescription(cpData.cpCitizenDesc);
character:SetClass(CLASS_MPUH);
character:SetCustomClass("Citizen" );
elseif(event == "Equipped") then
character:SetDescription(cpData.cpDesc);
character:SetClass(CLASS_MPU);
character:SetCustomClass("Civil Protection");
netstream.Start(client, "RecalculateHUDObjectives", PLUGIN.socioStatus)
end;
client:ResetBodygroups()
character:UpdateCPStatus();
end;
end;
-- Returns if a tagline exists from the tagline config table.
function PLUGIN:TaglineExists(tagline)
for i = 1, #cpSystem.config.taglines do
if(tagline == cpSystem.config.taglines[i]) then
return true;
end;
end;
return false;
end; |
--[[ Abstract Node class. ]]
local Node = torch.class('fg.Node')
--[[ Automatic identifier. ]]
function Node:register()
local tab = torch.getmetatable(torch.type(self))
tab.num_exist = (tab.num_exist or 0) + 1
end
function Node:get_global_count()
local tab = torch.getmetatable(torch.type(self))
return tab.num_exist or 0
end
--[[ Constructor. ]]
function Node:__init(name, convergence)
self:register()
self.name = name or torch.type(self)..self:get_global_count()
self.incoming = {}
self.outgoing = {}
self.prev_outgoing = {}
self.convergence = convergence or 1e-5
self.enabled = true
end
--[[ Resets and empties the incoming and outgoing buffers. ]]
function Node:reset()
self.enabled = true
end
--[[ Receives a message from a node. ]]
function Node:receive(node, message)
if self.enabled then
self.incoming[node] = message
end
end
--[[ Sends a message to all listeners. ]]
function Node:send()
for node, message in pairs(self.outgoing) do
node:receive(self, message)
end
end
--[[ Prepare for new iteration by caching outgoing messages. ]]
function Node:next()
for node, message in pairs(self.outgoing) do
self.prev_outgoing[node] = message:clone()
end
end
--[[ Normalizes the messages in the outgoing buffer to sum to 1. ]]
function Node:normalize()
for node, message in pairs(self.outgoing) do
message:normalize()
end
end
--[[ Returns if outgoing message did not change. ]]
function Node:converged()
if not self.enabled then return true end
for node, message in pairs(self.outgoing) do
local prev_message = self.prev_outgoing[node]
if prev_message == nil or (torch.csub(message.P, prev_message.P):abs():max() > self.convergence) then
return false
end
end
return true
end
return Node
|
-- license:BSD-3-Clause
-- copyright-holders:Miodrag Milanovic
local exports = {
name = "dummy",
version = "0.0.1",
description = "A dummy example",
license = "BSD-3-Clause",
author = { name = "Miodrag Milanovic" }}
local dummy = exports
function dummy.startplugin()
emu.register_start(function()
emu.print_verbose("Starting " .. emu.gamename())
end)
emu.register_stop(function()
emu.print_verbose("Exiting " .. emu.gamename())
end)
local function menu_populate()
return {{ "This is a", "test", "off" }, { "Also a", "test", "" }}
end
local function menu_callback(index, event)
emu.print_verbose("index: " .. index .. " event: " .. event)
return false
end
emu.register_menu(menu_callback, menu_populate, "Dummy")
end
return exports
|
local PADDING = 10 -- tooltip border width
local MAX_WIDTH = 250
local MAX_HEIGHT = 500
local MOUSE_X_OFFSET = 15
local MOUSE_Y_OFFSET = 20
-- Helper Functions
local function ResizeToFit(self)
self.text:ClearAll()
local w = math.min(MAX_WIDTH, self.text:GetWidth())
self.text:SetWidth(w)
local h = math.min(MAX_HEIGHT, self.text:GetHeight())
self.text:ClearWidth()
self.text:SetPoint("TOPLEFT", self, "TOPLEFT", PADDING, PADDING)
self.text:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", -PADDING, -PADDING)
self:SetWidth(w + PADDING * 2)
self:SetHeight(h + PADDING * 2)
end
-- Public Functions
local function GetFontSize(self)
return self.text:GetFontSize()
end
local function SetFontSize(self, size)
assert(type(size) == "number", "param 1 must be a number!")
self.text:SetFontSize(size)
ResizeToFit(self)
end
local function GetFontColor(self)
return self.text:GetFontColor()
end
local function SetFontColor(self, r, g, b, a)
self.text:SetFontColor(r, g, b, a)
end
local INVERSE_ANCHORS = {
TOPLEFT = "BOTTOMRIGHT",
TOPRIGHT = "BOTTOMLEFT",
BOTTOMLEFT = "TOPRIGHT",
BOTTOMRIGHT = "TOPLEFT",
TOPCENTER = "BOTTOMCENTER",
BOTTOMCENTER = "TOPCENTER",
CENTERLEFT = "CENTERRIGHT",
CENTERRIGHT = "CENTERLEFT",
}
local function Show(self, owner, text, anchor, xoffset, yoffset)
assert(type(owner) == "table", "param 1 must be a frame!")
assert(type(text) == "string", "param 2 must be a string!")
assert(anchor == nil or type(anchor) == "string", "param 3 must be a string!")
assert(xoffset == nil or type(xoffset) == "number", "param 4 must be a number!")
assert(yoffset == nil or type(yoffset) == "number", "param 5 must be a number!")
anchor = anchor or "MOUSE"
xoffset = 0
yoffset = 0
self.owner = owner
self.text:SetText(text)
self:ClearAll()
ResizeToFit(self)
if anchor == "MOUSE" then
local m = Inspect.Mouse()
-- bottom right location by default
local selfAnchor = "TOPLEFT"
local targetAnchor = "TOPLEFT"
local x = m.x + MOUSE_X_OFFSET
local y = m.y + MOUSE_Y_OFFSET
local _, _, screenWidth, screenHeight = UIParent:GetBounds()
-- flip to the left if it goes past the right edge of the screen
if x + self:GetWidth() > screenWidth then
x = m.x
selfAnchor = string.gsub(selfAnchor, "LEFT", "RIGHT")
end
-- flip upwards if it goes past the bottom edge of the screen
if y + self:GetHeight() > screenHeight then
y = m.y
selfAnchor = string.gsub(selfAnchor, "TOP", "BOTTOM")
end
self:SetPoint(selfAnchor, UIParent, targetAnchor, x, y)
else
local ttAnchor = INVERSE_ANCHORS[anchor]
if not ttAnchor then
print("LSW: Unsupported anchor point for tooltip: " .. anchor)
ttAnchor = "TOPLEFT"
anchor = "BOTTOMRIGHT"
end
self:SetPoint(ttAnchor, owner, anchor, xoffset, yoffset)
end
self:SetVisible(true)
end
local function Hide(self, owner)
if self.owner ~= owner then return end
self:SetVisible(false)
self.owner = nil
end
local function InjectEvents(self, frame, tooltipTextFunc, anchor, xoffset, yoffset)
assert(type(frame) == "table", "param 1 must be a frame!")
assert(type(tooltipTextFunc) == "function", "param 2 must be a function!")
assert(anchor == nil or type(anchor) == "string", "param 3 must be a string!")
assert(xoffset == nil or type(xoffset) == "number", "param 4 must be a number!")
assert(yoffset == nil or type(yoffset) == "number", "param 5 must be a number!")
-- Can't use self inside the event functions since it will then refer to the frame, not our tooltip.
local tooltip = self
local oldMouseIn = frame.Event.MouseIn
local oldMouseMove = frame.Event.MouseMove
local oldMouseOut = frame.Event.MouseOut
frame.Event.MouseIn = function(self)
tooltip:Show(self, tooltipTextFunc(tooltip), anchor, xoffset, yoffset)
if oldMouseIn then oldMouseIn(self) end
end
frame.Event.MouseMove = function(self, x, y)
tooltip:Show(self, tooltipTextFunc(tooltip), anchor, xoffset, yoffset)
if oldMouseMove then oldMouseMove(self, x, y) end
end
frame.Event.MouseOut = function(self)
tooltip:Hide(self)
if oldMouseOut then oldMouseOut(self) end
end
frame.LSW_Tooltip_OldMouseIn = oldMouseIn
frame.LSW_Tooltip_OldMouseMove = oldMouseMove
frame.LSW_Tooltip_OldMouseOut = oldMouseOut
end
local function RemoveEvents(self, frame)
assert(type(frame) == "table", "param 1 must be a frame!")
frame.Event.MouseIn = frame.LSW_Tooltip_OldMouseIn
frame.Event.MouseMove = frame.LSW_Tooltip_OldMouseMove
frame.Event.MouseOut = frame.LSW_Tooltip_OldMouseOut
frame.LSW_Tooltip_OldMouseIn = nil
frame.LSW_Tooltip_OldMouseMove = nil
frame.LSW_Tooltip_OldMouseOut = nil
end
-- Constructor Function
function Library.LibSimpleWidgets.Tooltip(name, parent)
local widget = UI.CreateFrame("Frame", name, parent)
widget.text = UI.CreateFrame("Text", name .. "Text", widget)
widget.text:SetBackgroundColor(0, 0, 0, 1)
widget:SetLayer(999)
Library.LibSimpleWidgets.SetBorder("tooltip", widget)
widget.__lsw_border:SetPosition("inside")
widget:SetVisible(false)
widget.text:SetWordwrap(true)
ResizeToFit(widget)
widget.GetFontSize = GetFontSize
widget.SetFontSize = SetFontSize
widget.GetFontColor = GetFontColor
widget.SetFontColor = SetFontColor
widget.Show = Show
widget.Hide = Hide
widget.InjectEvents = InjectEvents
widget.RemoveEvents = RemoveEvents
return widget
end
|
object_tangible_food_generic_dish_havla = object_tangible_food_generic_shared_dish_havla:new {
}
ObjectTemplates:addTemplate(object_tangible_food_generic_dish_havla, "object/tangible/food/generic/dish_havla.iff")
|
IN_FILE_PATH = "../../SavedVariables/ArkadiusTradeToolsExports.lua"
dofile(IN_FILE_PATH)
local args = {
['--latest'] = 'useLatest',
['--members'] = 'useOnlyMembers'
}
-- Defining these as globals so setting them by name is easier
useLatest = false
useOnlyMembers = false
for idx, _arg in pairs(arg) do
if args[_arg] then
_G[args[_arg]] = true
end
end
local useLatest = arg[1] and arg[1] == '--latest'
local function escapeQuotes(s)
local value = s:gsub("\"", "\"\"")
return value
end
local function WriteLine(args)
OUT_FILE:write(
args.guildName
.. ',' .. args.startTimeStamp
.. ',' .. args.endTimeStamp
.. ',' .. escapeQuotes(args.displayName)
.. ',' .. tostring(args.member)
.. ',' .. args.salesVolume
.. ',' .. args.purchaseVolume
.. ',' .. (args.rankIndex or "")
.. ',' .. (args.rankName or "")
.. ',' .. args.taxes
.. ',' .. args.purchaseTaxes
.. ',' .. args.salesCount
.. ',' .. args.purchaseCount
.. ',' .. args.internalSalesVolume
.. ',' .. args.itemCount
.. '\n'
)
end
local servers = {}
for k in pairs(ArkadiusTradeToolsExportsData.exports) do
servers[#servers + 1] = k
end
local function isValidServer(input)
return servers[input] ~= nil
end
local input
if #servers == 1 then input = 1 end
while not isValidServer(input) do
io.write('Available Servers:\n')
for key, value in pairs(servers) do
io.write(key .. ". " .. value .. "\n")
end
io.write("Which server would you like to use? ")
io.flush()
input = tonumber(io.read())
end
-- local guilds = {}
-- for k, v in pairs(ArkadiusTradeToolsExportsData.exports[servers[input]]) do
-- guilds[v.guildName] = true
-- end
-- local guildName
-- repeat
-- io.write('Available Servers:\n')
-- for key, value in pairs(servers) do
-- io.write(key .. ". " .. value .. "\n")
-- end
-- io.write("Which server would you like to use? ")
-- io.flush()
-- guildName = tonumber(io.read())
-- until isValidServer(guildName)
local exports = ArkadiusTradeToolsExportsData.exports[servers[input]]
table.sort(exports, function(a, b)
if (a.createdTimeStamp == b.createdTimeStamp) then
if (a.startTimeStamp == b.startTimeStamp) then
if a.endTimeStamp == b.endTimeStamp then
return a.guildName < b.guildName
end
return a.endTimeStamp > b.endTimeStamp
end
return a.startTimeStamp > b.startTimeStamp
end
return a.createdTimeStamp > b.createdTimeStamp
end)
local selectedExport
if not useLatest then
io.write('Available Exports:\n')
for idx, value in ipairs(exports) do
io.write(idx .. ". " .. value.guildName .. "\n")
io.write(" End Date: ".. os.date('%Y-%m-%dT%H:%M:%S', value.endTimeStamp) .. '\n')
io.write(" Start Date: ".. os.date('%Y-%m-%dT%H:%M:%S', value.startTimeStamp) .. '\n\n')
end
io.write("Which export would you like to use? ")
io.flush()
selectedExport = tonumber(io.read())
else
selectedExport = 1
end
local sortedExportsData = exports[selectedExport]
table.sort(
sortedExportsData.data,
function(a, b)
if (a.stats.salesVolume == b.stats.salesVolume) then
if a.isMember == b.isMember then
if a.stats.purchaseVolume == b.stats.purchaseVolume then
return a.displayName < b.displayName
end
return a.stats.purchaseVolume > b.stats.purchaseVolume
end
return a.isMember
end
return a.stats.salesVolume > b.stats.salesVolume
end
)
local headersMap = {
"Guild",
"Start Timestamp",
"End Timestamp",
"Display Name",
"Member",
"Sales",
"Purchases",
"Rank Index",
"Rank Name",
"Taxes (Sales)",
"Taxes (Purchases)",
"Sales Count",
"Purchase Count",
"Internal Sales Volume",
"Sold Items",
}
local headers = table.concat(headersMap, ',') .. '\n'
local startTimeStamp = os.date('%Y-%m-%dT%H.%M.%S', sortedExportsData.startTimeStamp)
local endTimeStamp = os.date('%Y-%m-%dT%H.%M.%S', sortedExportsData.endTimeStamp)
local isMembers = useOnlyMembers and "Members" or "All"
local newPath = string.format("../../SavedVariables/ArkadiusTradeToolsExports-%s %s %s-%s.csv", sortedExportsData.guildName, isMembers, startTimeStamp, endTimeStamp)
OUT_FILE_PATH = "../../SavedVariables/ArkadiusTradeToolsExports.csv"
OUT_FILE = assert(io.open(newPath, "w"))
OUT_FILE:write(headers)
startTimeStamp = os.date('%Y-%m-%dT%H:%M:%S', sortedExportsData.startTimeStamp)
endTimeStamp = os.date('%Y-%m-%dT%H:%M:%S', sortedExportsData.endTimeStamp)
for key, data in ipairs(sortedExportsData.data) do
local displayName = data.displayName
local member = data.isMember
local stats = data.stats
local purchaseTaxes = stats["purchaseTaxes"]
local purchaseVolume = stats["purchaseVolume"]
local purchasedItemCount = stats["purchasedItemCount"]
local purchaseCount = stats["purchaseCount"]
local itemCount = stats["itemCount"]
local taxes = stats["taxes"]
local salesCount = stats["salesCount"]
local internalSalesVolume = stats["internalSalesVolume"]
local salesVolume = stats["salesVolume"]
if data.isMember or not useOnlyMembers then
WriteLine({
guildName = sortedExportsData.guildName
, startTimeStamp = startTimeStamp
, endTimeStamp = endTimeStamp
, displayName = displayName
, member = member
, stats = stats
, rankIndex = data.rankIndex
, rankName = data.rankName
, purchaseTaxes = purchaseTaxes
, purchaseVolume = purchaseVolume
, purchasedItemCount = purchasedItemCount
, purchaseCount = purchaseCount
, itemCount = itemCount
, taxes = taxes
, salesCount = salesCount
, internalSalesVolume = internalSalesVolume
, salesVolume = salesVolume
})
end
end
OUT_FILE:close()
os.rename(OUT_FILE_PATH, newPath)
print(string.format("Saved to %s", newPath)) |
PIOVER180 = 0.0174532925199
FUN_EPSILON = 0.0005
--Vector2D Class (table)
Vector2D = {X = 0,Y = 0,className = "Vector2D"}
--Vector2D Class Metatable
Vector2D.mt = {}
--Creation by Constructor simulation
Vector2D.mt.__call = function(caller,x,y)
x = x or 0 --set x to 0 if it is nil
y = y or 0 --set y to 0 if it is nil
p = {}
setmetatable(p,Vector2D)
Vector2D.__index = Vector2D
p.X = x
p.Y = y
p.className = "Vector2D"
return p
end
setmetatable(Vector2D,Vector2D.mt)
--Creation with new
function Vector2D:new(x,y)
x = x or 0 --set x to 0 if it is nil
y = y or 0 --set y to 0 if it is nil
p = {}
setmetatable(p,self)
self.__index = self
p.X = x
p.Y = y
p.className = "Vector2D"
return p
end
--Addition overload (adding two Vector2Ds)
Vector2D.__add = function(a,b)
local pr = Vector2D()
pr.X = a.X + b.X
pr.Y = a.Y + b.Y
return pr
end
--Substraction overload
Vector2D.__sub = function(a,b)
local pr = Vector2D()
pr.X = a.X - b.X
pr.Y = a.Y - b.Y
return pr
end
--Vector2D * number overload
Vector2D.__mul = function(a,b)
local pr = Vector2D()
pr.X = a.X * b
pr.Y = a.Y * b
return pr
end
--Vector2D / number number overload
Vector2D.__div = function(a,b)
local pr = Vector2D()
pr.X = a.X / b
pr.Y = a.Y / b
return pr
end
--comparing 2 Vector2Ds
Vector2D.__eq = function(a,b)
if(a.X == b.X and a.Y == b.Y) then return true end
return false
end
function Vector2D:Translate(x,y)
self.X = self.X + x
self.Y = self.Y + y
end
function Vector2D:Scale(x,y)
self.X = self.X * x
self.Y = self.Y * y
end
function Vector2D:Rotate(angle)
COS = math.cos(angle * PIOVER180);
SIN = math.sin(angle * PIOVER180);
X1 = (self.X*COS - self.Y*SIN);
Y1 = (self.Y*COS + self.X*SIN);
self.X = X1;
self.Y = Y1;
end
function Vector2D:GetNormal()
local pr = Vector2D()
pr.X = -self.Y
pr.Y = self.X
return pr
end
function Vector2D:GetReflectedVector(vn)
local rv = Vector2D();
d = math.sqrt(self.X * self.X + self.Y * self.Y);
if((d<= -FUN_EPSILON) or (d >=FUN_EPSILON)) then
rv.X = self.X/d;
rv.Y = self.Y/d;
end
dot = (rv.X*vn.X + rv.Y*vn.Y);
rv.X = rv.X - 2*dot*vn.X;
rv.Y = rv.Y - 2*dot*vn.Y;
return rv
end
function Vector2D:SetNormalize()
d = math.sqrt(self.X*self.X + self.Y*self.Y);
if((d<= -FUN_EPSILON) or (d >=FUN_EPSILON))
then
self.X = self.X/d;
self.Y = self.Y/d;
end
end
function Vector2D:GetDotProduct(v)
return (self.X*v.X + self.Y*v.Y)
end
function Vector2D:GetLength()
return math.sqrt(self.X*self.X + self.Y*self.Y)
end
function Vector2D:Clear()
self.X = 0
self.Y = 0
end
-- this is used by C++ to create a lua Vector2D
function CreateVector()
local pt = Vector2D()
return pt
end |
function lambda_prompt_filter()
clink.prompt.value = string.gsub(clink.prompt.value, "{lamb}", "λ")
end
clink.prompt.register_filter(lambda_prompt_filter, 40) |
-----------------------------------------------------------------------------------------------------------------------
-- RedFlat top widget --
-----------------------------------------------------------------------------------------------------------------------
-- Widget with list of top processes
-----------------------------------------------------------------------------------------------------------------------
-- Grab environment
-----------------------------------------------------------------------------------------------------------------------
local unpack = unpack or table.unpack
local awful = require("awful")
local beautiful = require("beautiful")
local wibox = require("wibox")
local timer = require("gears.timer")
local redutil = require("redflat.util")
local system = require("redflat.system")
local decoration = require("redflat.float.decoration")
local redtip = require("redflat.float.hotkeys")
-- Initialize tables for module
-----------------------------------------------------------------------------------------------------------------------
local top = { keys = {} }
-- key bindings
top.keys.management = {
{
{}, "c", function() top:set_sort("cpu") end,
{ description = "Sort by CPU usage", group = "Management" }
},
{
{}, "m", function() top:set_sort("mem") end,
{ description = "Sort by RAM usage", group = "Management" }
},
}
top.keys.action = {
{
{}, "k", function() top.kill_selected() end,
{ description = "Kill process", group = "Action" }
},
{
{}, "Escape", function() top:hide() end,
{ description = "Close top list widget", group = "Action" }
},
{
{ "Mod4" }, "F1", function() redtip:show() end,
{ description = "Show hotkeys helper", group = "Action" }
},
}
top.keys.all = awful.util.table.join(top.keys.management, top.keys.action)
top._fake_keys = {
{
{}, "N", nil,
{ description = "Select process by key", group = "Management",
keyset = { "1", "2", "3", "4", "5", "6", "7", "8", "9" } }
},
}
-- Generate default theme vars
-----------------------------------------------------------------------------------------------------------------------
local function default_style()
local style = {
timeout = 2,
screen_gap = 0,
set_position = nil,
geometry = { width = 460, height = 380 },
border_margin = { 10, 10, 10, 10 },
labels_width = { num = 30, cpu = 70, mem = 120 },
title_height = 48,
list_side_gap = 8,
border_width = 2,
bottom_height = 80,
button_margin = { 140, 140, 22, 22 },
keytip = { geometry = { width = 400 } },
title_font = "Sans 14 bold",
unit = { { "KB", -1 }, { "MB", 1024 }, { "GB", 1024^2 } },
color = { border = "#575757", text = "#aaaaaa", highlight = "#eeeeee", main = "#b1222b",
bg = "#161616", bg_second = "#181818", wibox = "#202020" },
shape = nil
}
return redutil.table.merge(style, redutil.table.check(beautiful, "float.top") or {})
end
-- Support functions
-----------------------------------------------------------------------------------------------------------------------
-- Sort functions
--------------------------------------------------------------------------------
local function sort_by_cpu(a, b)
return a.pcpu > b.pcpu
end
local function sort_by_mem(a, b)
return a.mem > b.mem
end
-- Fuction to build list item
--------------------------------------------------------------------------------
local function construct_item(style)
local item = {}
item.label = {
number = wibox.widget.textbox(),
name = wibox.widget.textbox(),
cpu = wibox.widget.textbox(),
mem = wibox.widget.textbox()
}
item.label.cpu:set_align("right")
item.label.mem:set_align("right")
local bg = style.color.bg
-- Construct item layouts
------------------------------------------------------------
local mem_label_with_gap = wibox.container.margin(item.label.mem, 0, style.list_side_gap)
local num_label_with_gap = wibox.container.margin(item.label.number, style.list_side_gap)
local right = wibox.layout.fixed.horizontal()
right:add(wibox.container.constraint(item.label.cpu, "exact", style.labels_width.cpu, nil))
right:add(wibox.container.constraint(mem_label_with_gap, "exact", style.labels_width.mem, nil))
local middle = wibox.layout.align.horizontal()
middle:set_left(item.label.name)
local left = wibox.container.constraint(num_label_with_gap, "exact", style.labels_width.num, nil)
local item_horizontal = wibox.layout.align.horizontal()
item_horizontal:set_left(left)
item_horizontal:set_middle(middle)
item_horizontal:set_right(right)
item.layout = wibox.container.background(item_horizontal, bg)
-- item functions
------------------------------------------------------------
function item:set_bg(color)
bg = color
item.layout:set_bg(color)
end
function item:set_select()
item.layout:set_bg(style.color.main)
item.layout:set_fg(style.color.highlight)
end
function item:set_unselect()
item.layout:set_bg(bg)
item.layout:set_fg(style.color.text)
end
function item:set(args)
if args.number then item.label.number:set_text(args.number) end
if args.name then item.label.name:set_text(args.name) end
if args.cpu then item.label.cpu:set_text(args.cpu) end
if args.mem then item.label.mem:set_text(args.mem) end
if args.pid then item.pid = args.pid end
end
------------------------------------------------------------
return item
end
-- Fuction to build top list
--------------------------------------------------------------------------------
local function list_construct(n, style, select_function)
local list = {}
local list_layout = wibox.layout.flex.vertical()
list.layout = wibox.container.background(list_layout, style.color.bg)
list.items = {}
for i = 1, n do
list.items[i] = construct_item(style)
list.items[i]:set({ number = i})
list.items[i]:set_bg((i % 2) == 1 and style.color.bg or style.color.bg_second)
list_layout:add(list.items[i].layout)
list.items[i].layout:buttons(awful.util.table.join(
awful.button({ }, 1, function() select_function(i) end)
))
end
return list
end
-- Initialize top widget
-----------------------------------------------------------------------------------------------------------------------
function top:init()
-- Initialize vars
--------------------------------------------------------------------------------
local number_of_lines = 9 -- number of lines in process list
local selected = {}
local cpu_storage = { cpu_total = {}, cpu_active = {} }
local style = default_style()
local sort_function, title, toplist
self.style = style
-- Select process function
--------------------------------------------------------------------------------
local function select_item(i)
if selected.number and selected.number ~= i then toplist.items[selected.number]:set_unselect() end
toplist.items[i]:set_select()
selected.pid = toplist.items[i].pid
selected.number = i
end
-- Set sorting rule
--------------------------------------------------------------------------------
function self:set_sort(args)
if args == "cpu" then
sort_function = sort_by_cpu
title:set({ cpu = "▾ CPU", mem = "Memory"})
elseif args == "mem" then
sort_function = sort_by_mem
title:set({ cpu = "CPU", mem = "▾ Memory"})
end
end
-- Kill selected process
--------------------------------------------------------------------------------
function self.kill_selected()
if selected.number then awful.spawn.with_shell("kill " .. selected.pid) end
self:update_list()
end
-- Widget keygrabber
--------------------------------------------------------------------------------
self.keygrabber = function(mod, key, event)
if event ~= "press" then return end
for _, k in ipairs(self.keys.all) do
if redutil.key.match_grabber(k, mod, key) then k[3](); return end
end
if string.match("123456789", key) then select_item(tonumber(key)) end
end
-- Build title
--------------------------------------------------------------------------------
title = construct_item(style)
title:set_bg(style.color.wibox)
title:set({ number = "#", name = "Process Name", cpu = "▾ CPU", mem = "Memory"})
for _, txtbox in pairs(title.label) do
txtbox:set_font(style.title_font)
end
title.label.cpu:buttons(awful.util.table.join(
awful.button({ }, 1, function() self:set_sort("cpu") end)
))
title.label.mem:buttons(awful.util.table.join(
awful.button({ }, 1, function() self:set_sort("mem") end)
))
-- Build top list
--------------------------------------------------------------------------------
toplist = list_construct(number_of_lines, style, select_item)
-- Update function
--------------------------------------------------------------------------------
function self:update_list()
local proc = system.proc_info(cpu_storage)
table.sort(proc, sort_function)
if selected.number then
toplist.items[selected.number]:set_unselect()
selected.number = nil
end
for i = 1, number_of_lines do
toplist.items[i]:set({
name = proc[i].name,
cpu = string.format("%.1f", proc[i].pcpu * 100),
--mem = string.format("%.0f", proc[i].mem) .. " MB",
mem = redutil.text.dformat(proc[i].mem, style.unit, 2, " "),
pid = proc[i].pid
})
if selected.pid and selected.pid == proc[i].pid then
toplist.items[i]:set_select()
selected.number = i
end
end
end
-- Construct widget layouts
--------------------------------------------------------------------------------
local buttonbox = wibox.widget.textbox("Kill")
local button_widget = decoration.button(buttonbox, self.kill_selected)
local button_layout = wibox.container.margin(button_widget, unpack(style.button_margin))
local bottom_area = wibox.container.constraint(button_layout, "exact", nil, style.bottom_height)
local area = wibox.layout.align.vertical()
area:set_top(wibox.container.constraint(title.layout, "exact", nil, style.title_height))
area:set_middle(toplist.layout)
area:set_bottom(bottom_area)
local list_layout = wibox.container.margin(area, unpack(style.border_margin))
-- Create floating wibox for top widget
--------------------------------------------------------------------------------
self.wibox = wibox({
ontop = true,
bg = style.color.wibox,
border_width = style.border_width,
border_color = style.color.border,
shape = style.shape
})
self.wibox:set_widget(list_layout)
self.wibox:geometry(style.geometry)
-- Update timer
--------------------------------------------------------------------------------
self.update_timer = timer({timeout = style.timeout})
self.update_timer:connect_signal("timeout", function() self:update_list() end)
-- First run actions
--------------------------------------------------------------------------------
self:set_keys()
self:set_sort("cpu")
self:update_list()
end
-- Hide top widget
-----------------------------------------------------------------------------------------------------------------------
function top:hide()
self.wibox.visible = false
self.update_timer:stop()
awful.keygrabber.stop(self.keygrabber)
redtip:remove_pack()
end
-- Show top widget
-----------------------------------------------------------------------------------------------------------------------
function top:show(srt)
if not self.wibox then self:init() end
if self.wibox.visible then
top:hide()
else
if srt then self:set_sort(srt) end
self:update_list()
if self.style.set_position then
self.style.set_position(self.wibox)
else
awful.placement.under_mouse(self.wibox)
end
redutil.placement.no_offscreen(self.wibox, self.style.screen_gap, screen[mouse.screen].workarea)
self.wibox.visible = true
self.update_timer:start()
awful.keygrabber.run(self.keygrabber)
redtip:set_pack("Top process", self.tip, self.style.keytip.column, self.style.keytip.geometry)
end
end
-- Set user hotkeys
-----------------------------------------------------------------------------------------------------------------------
function top:set_keys(keys, layout)
layout = layout or "all"
if keys then
self.keys[layout] = keys
if layout ~= "all" then self.keys.all = awful.util.table.join(self.keys.management, self.keys.action) end
end
self.tip = awful.util.table.join(self.keys.all, self._fake_keys)
end
-- End
-----------------------------------------------------------------------------------------------------------------------
return top
|
object_tangible_component_armor_shield_generator_personal_borvo = object_tangible_component_armor_shared_shield_generator_personal_borvo:new {
}
ObjectTemplates:addTemplate(object_tangible_component_armor_shield_generator_personal_borvo, "object/tangible/component/armor/shield_generator_personal_borvo.iff")
|
local TOCNAME,GBB=...
local function DetermineGameVersion()
local version, _, _, _ = GetBuildInfo()
if version:sub(1, 1) == "2" then
GBB.GameType = "TBC"
GBB.PANELOFFSET = 1
else
GBB.GameType = "VANILLA"
GBB.PANELOFFSET = 0
end
end
DetermineGameVersion()
function GBB.GetDungeonNames()
local DefaultEnGB={
["RFC"] = "Ragefire Chasm",
["DM"] = "The Deadmines",
["WC"] = "Wailing Caverns",
["SFK"] = "Shadowfang Keep",
["STK"] = "The Stockade",
["BFD"] = "Blackfathom Deeps",
["GNO"] = "Gnomeregan",
["RFK"] = "Razorfen Kraul",
["SM2"] = "Scarlet Monastery",
["SMG"] = "Scarlet Monastery: Graveyard",
["SML"] = "Scarlet Monastery: Library",
["SMA"] = "Scarlet Monastery: Armory",
["SMC"] = "Scarlet Monastery: Cathedral",
["RFD"] = "Razorfen Downs",
["ULD"] = "Uldaman",
["ZF"] = "Zul'Farrak",
["MAR"] = "Maraudon",
["ST"] = "The Sunken Temple",
["BRD"] = "Blackrock Depths",
["DM2"] = "Dire Maul",
["DME"] = "Dire Maul: East",
["DMN"] = "Dire Maul: North",
["DMW"] = "Dire Maul: West",
["STR"] = "Stratholme",
["SCH"] = "Scholomance",
["LBRS"] = "Lower Blackrock Spire",
["UBRS"] = "Upper Blackrock Spire (10)",
["RAMPS"] = "Hellfire Citadel: Ramparts",
["BF"] = "Hellfire Citadel: Blood Furnace",
["SP"] = "Coilfang Reservoir: Slave Pens",
["UB"] = "Coilfang Reservoir: Underbog",
["MT"] = "Auchindoun: Mana Tombs",
["CRYPTS"] = "Auchindoun: Auchenai Crypts",
["SETH"] = "Auchindoun: Sethekk Halls",
["OHB"] = "Caverns of Time: Old Hillsbrad",
["MECH"] = "Tempest Keep: The Mechanar",
["BM"] = "Caverns of Time: Black Morass",
["MGT"] = "Magisters' Terrace",
["SH"] = "Hellfire Citadel: Shattered Halls",
["BOT"] = "Tempest Keep: Botanica",
["SL"] = "Auchindoun: Shadow Labyrinth",
["SV"] = "Coilfang Reservoir: Steamvault",
["ARC"] = "Tempest Keep: The Arcatraz",
["KARA"] = "Karazhan",
["GL"] = "Gruul's Lair",
["MAG"] = "Hellfire Citadel: Magtheridon's Lair",
["SSC"] = "Coilfang Reservoir: Serpentshrine Cavern",
["EYE"] = "The Eye",
["ZA"] = "Zul-Aman",
["HYJAL"] = "The Battle For Mount Hyjal",
["BT"] = "Black Temple",
["SWP"] = "Sunwell Plateau",
["ONY"] = "Onyxia's Lair (40)",
["MC"] = "Molten Core (40)",
["ZG"] = "Zul'Gurub (20)",
["AQ20"] = "Ruins of Ahn'Qiraj (20)",
["BWL"] = "Blackwing Lair (40)",
["AQ40"] = "Temple of Ahn'Qiraj (40)",
["NAX"] = "Naxxramas (40)",
["WSG"] = "Warsong Gulch (PvP)",
["AB"] = "Arathi Basin (PvP)",
["AV"] = "Alterac Valley (PvP)",
["EOTS"] = "Eye of the Storm (PvP)",
["MISC"] = "Miscellaneous",
["TRADE"] = "Trade",
["DEBUG"] = "DEBUG INFO",
["BAD"] = "DEBUG BAD WORDS - REJECTED",
}
local dungeonNamesLocales={
deDE ={
["RFC"] = "Flammenschlund",
["DM"] = "Die Todesminen",
["WC"] = "Die Höhlen des Wehklagens",
["SFK"] = "Burg Schattenfang",
["STK"] = "Das Verlies",
["BFD"] = "Die Tiefschwarze Grotte",
["GNO"] = "Gnomeregan",
["RFK"] = "Kral der Klingenhauer",
["SM2"] = "Scharlachrotes Kloster",
["SMG"] = "Scharlachrotes Kloster: Friedhof",
["SML"] = "Scharlachrotes Kloster: Bibliothek",
["SMA"] = "Scharlachrotes Kloster: Waffenkammer",
["SMC"] = "Scharlachrotes Kloster: Kathedrale",
["RFD"] = "Hügel der Klingenhauer",
["ULD"] = "Uldaman",
["ZF"] = "Zul'Farrak",
["MAR"] = "Maraudon",
["ST"] = "Der Tempel von Atal'Hakkar",
["BRD"] = "Die Schwarzfels-Tiefen",
["DM2"] = "Düsterbruch",
["DME"] = "Düsterbruch: Ost",
["DMN"] = "Düsterbruch: Nord",
["DMW"] = "Düsterbruch: West",
["STR"] = "Stratholme",
["SCH"] = "Scholomance",
["LBRS"] = "Die Untere Schwarzfelsspitze",
["UBRS"] = "Obere Schwarzfelsspitze (10)",
["RAMPS"] = "Höllenfeuerzitadelle: Höllenfeuerbollwerk",
["BF"] = "Höllenfeuerzitadelle: Der Blutkessel",
["SP"] = "Echsenkessel: Die Sklavenunterkünfte",
["UB"] = "Echsenkessel: Der Tiefensumpf",
["MT"] = "Auchindoun: Die Managruft",
["CRYPTS"] = "Auchindoun: Die Auchenaikrypta",
["SETH"] = "Auchindoun: Sethekkhallen",
["OHB"] = "Höhlen der Zeit: Flucht von Durnholde",
["MECH"] = "Festung der Stürme: Die Mechanar",
["BM"] = "Höhlen der Zeit: Der Schwarze Morast",
["MGT"] = "Die Terrasse der Magister",
["SH"] = "Höllenfeuerzitadelle: Die Zerschmetterten Hallen",
["BOT"] = "Festung der Stürme: Botanica",
["SL"] = "Auchindoun: Schattenlabyrinth",
["SV"] = "Echsenkessel: Die Dampfkammer",
["ARC"] = "Festung der Stürme: Die Arcatraz",
["KARA"] = "Karazhan",
["GL"] = "Gruuls Unterschlupf",
["MAG"] = "Höllenfeuerzitadelle: Magtheridons Kammer",
["SSC"] = "Echsenkessel: Höhle des Schlangenschreins",
["EYE"] = "Das Auge des Sturms",
["ZA"] = "Zul-Aman",
["HYJAL"] = "Schlacht um den Berg Hyjal",
["BT"] = "Der Schwarze Tempel",
["SWP"] = "Sonnenbrunnenplateau",
["ONY"] = "Onyxias Hort (40)",
["MC"] = "Geschmolzener Kern (40)",
["ZG"] = "Zul'Gurub (20)",
["AQ20"] = "Ruinen von Ahn'Qiraj (20)",
["BWL"] = "Pechschwingenhort (40)",
["AQ40"] = "Tempel von Ahn'Qiraj (40)",
["NAX"] = "Naxxramas (40)",
["WSG"] = "Warsongschlucht (PVP)",
["AV"] = "Alteractal (PVP)",
["AB"] = "Arathibecken (PVP)",
["EOTS"] = "Auge des Sturms (PvP)",
["MISC"] = "Verschiedenes",
["TRADE"] = "Handel",
},
frFR ={
["RFC"] = "Gouffre de Ragefeu",
["DM"] = "Les Mortemines",
["WC"] = "Cavernes des lamentations",
["SFK"] = "Donjon d'Ombrecroc",
["STK"] = "La Prison",
["BFD"] = "Profondeurs de Brassenoire",
["GNO"] = "Gnomeregan",
["RFK"] = "Kraal de Tranchebauge",
["SM2"] = "Monastère écarlate",
["SMG"] = "Monastère écarlate: Cimetière",
["SML"] = "Monastère écarlate: Bibliothèque",
["SMA"] = "Monastère écarlate: Armurerie",
["SMC"] = "Monastère écarlate: Cathédrale",
["RFD"] = "Souilles de Tranchebauge",
["ULD"] = "Uldaman",
["ZF"] = "Zul'Farrak",
["MAR"] = "Maraudon",
["ST"] = "Le temple d'Atal'Hakkar",
["BRD"] = "Profondeurs de Blackrock",
["DM2"] = "Hache-tripes",
["DME"] = "Hache-tripes: Est",
["DMN"] = "Hache-tripes: Nord",
["DMW"] = "Hache-tripes: Ouest",
["STR"] = "Stratholme",
["SCH"] = "Scholomance",
["LBRS"] = "Pic Blackrock",
["UBRS"] = "Pic Blackrock (10)",
["RAMPS"] = "Citadelle des Flammes Infernales: Remparts des Flammes infernales",
["BF"] = "Citadelle des Flammes Infernales: La Fournaise du sang",
["SP"] = "Réservoir de Glissecroc : Les enclos aux esclaves",
["UB"] = "Réservoir de Glissecroc : La Basse-tourbière",
["MT"] = "Auchindoun: Tombes-mana",
["CRYPTS"] = "Auchindoun: Cryptes Auchenaï",
["SETH"] = "Auchindoun: Les salles des Sethekk",
["OHB"] = "Grottes du Temps: Contreforts de Hautebrande d'antan",
["MECH"] = "Donjon de la Tempête: Le Méchanar",
["BM"] = "Grottes du Temps: Le Noir Marécage",
["MGT"] = "Terrasse des Magistères",
["SH"] = "Citadelle des Flammes Infernales: Les Salles brisées",
["BOT"] = "Donjon de la Tempête: Botanica",
["SL"] = "Auchindoun: Labyrinthe des ombres",
["SV"] = "Réservoir de Glissecroc : Le Caveau de la vapeur",
["ARC"] = "Donjon de la Tempête: L'Arcatraz",
["KARA"] = "Karazhan",
["GL"] = "Repaire de Gruul",
["MAG"] = "Citadelle des Flammes Infernales: Le repaire de Magtheridon",
["SSC"] = "Réservoir de Glissecroc : Caverne du sanctuaire du Serpent",
["EYE"] = "L'Œil du cyclone",
["ZA"] = "Zul-Aman",
["HYJAL"] = "Sommet d'Hyjal",
["BT"] = "Temple noir",
["SWP"] = "Plateau du Puits de soleil",
["ONY"] = "Repaire d'Onyxia (40)",
["MC"] = "Cœur du Magma (40)",
["ZG"] = "Zul'Gurub (20)",
["AQ20"] = "Ruines d'Ahn'Qiraj (20)",
["BWL"] = "Repaire de l'Aile noire (40)",
["AQ40"] = "Ahn'Qiraj (40)",
["NAX"] = "Naxxramas (40)",
},
esMX ={
["RFC"] = "Sima Ígnea",
["DM"] = "Las Minas de la Muerte",
["WC"] = "Cuevas de los Lamentos",
["SFK"] = "Castillo de Colmillo Oscuro",
["STK"] = "Las Mazmorras",
["BFD"] = "Cavernas de Brazanegra",
["GNO"] = "Gnomeregan",
["RFK"] = "Horado Rajacieno",
["SM2"] = "Monasterio Escarlata",
["SMG"] = "Monasterio Escarlata: Friedhof",
["SML"] = "Monasterio Escarlata: Bibliothek",
["SMA"] = "Monasterio Escarlata: Waffenkammer",
["SMC"] = "Monasterio Escarlata: Kathedrale",
["RFD"] = "Zahúrda Rojocieno",
["ULD"] = "Uldaman",
["ZF"] = "Zul'Farrak",
["MAR"] = "Maraudon",
["ST"] = "El Templo de Atal'Hakkar",
["BRD"] = "Profundidades de Roca Negra ",
["DM2"] = "La Masacre",
["DME"] = "La Masacre: Ost",
["DMN"] = "La Masacre: Nord",
["DMW"] = "La Masacre: West",
["STR"] = "Stratholme",
["SCH"] = "Scholomance",
["LBRS"] = "Cumbre de Roca Negra",
["UBRS"] = "Cumbre de Roca Negra (10)",
["RAMPS"] = "Hellfire Citadel: Ramparts",
["BF"] = "Hellfire Citadel: Blood Furnace",
["SP"] = "Coilfang Reservoir: Slave Pens",
["UB"] = "Coilfang Reservoir: Underbog",
["MT"] = "Auchindoun: Mana Tombs",
["CRYPTS"] = "Auchindoun: Auchenai Crypts",
["SETH"] = "Auchindoun: Sethekk Halls",
["OHB"] = "Caverns of Time: Old Hillsbrad",
["MECH"] = "Tempest Keep: The Mechanar",
["BM"] = "Caverns of Time: Black Morass",
["MGT"] = "Magisters' Terrace",
["SH"] = "Hellfire Citadel: Shattered Halls",
["BOT"] = "Tempest Keep: Botanica",
["SL"] = "Auchindoun: Shadow Labyrinth",
["SV"] = "Coilfang Reservoir: Steamvault",
["ARC"] = "Tempest Keep: The Arcatraz",
["KARA"] = "Karazhan",
["GL"] = "Gruul's Lair",
["MAG"] = "Hellfire Citadel: Magtheridon's Lair",
["SSC"] = "Coilfang Reservoir: Serpentshrine Cavern",
["EYE"] = "The Eye",
["ZA"] = "Zul-Aman",
["HYJAL"] = "The Battle For Mount Hyjal",
["BT"] = "Black Temple",
["SWP"] = "Sunwell Plateau",
["ONY"] = "Guarida de Onyxia (40)",
["MC"] = "Núcleo de Magma (40)",
["ZG"] = "Zul'Gurub (20)",
["AQ20"] = "Ruinas de Ahn'Qiraj (20)",
["BWL"] = "Guarida Alanegra (40)",
["AQ40"] = "Ahn'Qiraj (40)",
["NAX"] = "Naxxramas (40)",
},
ruRU = {
["AB"] = "Низина Арати (PvP)",
["AQ20"] = "Руины Ан'Киража (20)",
["AQ40"] = "Ан'Кираж (40)",
["AV"] = "Альтеракская Долина (PvP)",
["BAD"] = "ОТЛАДКА ПЛОХИЕ СЛОВА - ОТКЛОНЕН",
["BFD"] = "Непроглядная Пучина",
["BRD"] = "Глубины Черной горы",
["BWL"] = "Логово Крыла Тьмы (40)",
["DEBUG"] = "ИНФОРМАЦИЯ О ОТЛАДКАХ",
["DM"] = "Мертвые копи",
["DM2"] = "Забытый Город",
["DME"] = "Забытый Город: Восток",
["DMN"] = "Забытый Город: Север",
["DMW"] = "Забытый Город: Запад",
["GNO"] = "Гномреган",
["LBRS"] = "Низ Вершины Черной горы",
["MAR"] = "Мародон",
["MC"] = "Огненные Недра (40)",
["MISC"] = "Прочее",
["NAX"] = "Наксрамас (40)",
["RAMPS"] = "Цитадель Адского Пламени: Бастионы",
["BF"] = "Цитадель Адского Пламени: Кузня Крови",
["SP"] = "Резервуар Кривого Клыка: Узилище",
["UB"] = "Резервуар Кривого Клыка: Нижетопь",
["MT"] = "Аукиндон: Гробницы Маны",
["CRYPTS"] = "Аукиндон: Аукенайские гробницы",
["SETH"] = "Аукиндон: Сетеккские залы",
["OHB"] = "Пещеры Времени: Старые предгорья Хилсбрада",
["MECH"] = "Крепость Бурь: Механар",
["BM"] = "Пещеры Времени: Черные топи",
["MGT"] = "Терраса магистров",
["SH"] = "Цитадель Адского Пламени: Разрушенные залы",
["BOT"] = "Крепость Бурь: Ботаника",
["SL"] = "Аукиндон: Темный лабиринт",
["SV"] = "Резервуар Кривого Клыка: Паровое подземелье",
["ARC"] = "Крепость Бурь: Аркатрац",
["KARA"] = "Каражан",
["GL"] = "Логово Груула",
["MAG"] = "Цитадель Адского Пламени: Логово Магтеридона",
["SSC"] = "Резервуар Кривого Клыка: Змеиное святилище",
["EYE"] = "Крепость Бурь: Око",
["ZA"] = "Зул'Аман",
["HYJAL"] = "Пещеры Времени: Вершина Хиджала",
["BT"] = "Черный Храм",
["SWP"] = "Плато Солнечного Колодца",
["ONY"] = "Логово Ониксии (40)",
["RFC"] = "Огненная пропасть",
["RFD"] = "Курганы Иглошкурых",
["RFK"] = "Лабиринты Иглошкурых",
["SCH"] = "Некроситет",
["SFK"] = "Крепость Темного Клыка",
["SM2"] = "Монастырь Алого ордена",
["SMA"] = "Монастырь Алого ордена: Оружейная",
["SMC"] = "Монастырь Алого ордена: Собор",
["SMG"] = "Монастырь Алого ордена: Кладбище",
["SML"] = "Монастырь Алого ордена: Библиотека",
["ST"] = "Затонувший Храм",
["STK"] = "Тюрьма",
["STR"] = "Стратхольм",
["TRADE"] = "Торговля",
["UBRS"] = "Верх Вершины Черной горы (10)",
["ULD"] = "Ульдаман",
["WC"] = "Пещеры Стенаний",
["WSG"] = "Ущелье Песни Войны (PvP)",
["EOTS"] = "Eye of the Storm (PvP)",
["ZF"] = "Зул'Фаррак",
["ZG"] = "Зул'Гуруб (20)",
},
}
local dungeonNames = dungeonNamesLocales[GetLocale()] or {}
if GroupBulletinBoardDB and GroupBulletinBoardDB.CustomLocalesDungeon and type(GroupBulletinBoardDB.CustomLocalesDungeon) == "table" then
for key,value in pairs(GroupBulletinBoardDB.CustomLocalesDungeon) do
if value~=nil and value ~="" then
dungeonNames[key.."_org"]=dungeonNames[key] or DefaultEnGB[key]
dungeonNames[key]=value
end
end
end
setmetatable(dungeonNames, {__index = DefaultEnGB})
dungeonNames["DEADMINES"]=dungeonNames["DM"]
return dungeonNames
end
local function Union ( a, b )
local result = {}
for k,v in pairs ( a ) do
result[k] = v
end
for k,v in pairs ( b ) do
result[k] = v
end
return result
end
GBB.VanillaDungeonLevels ={
["RFC"] = {13,18}, ["DM"] = {18,23}, ["WC"] = {15,25}, ["SFK"] = {22,30}, ["STK"] = {22,30}, ["BFD"] = {24,32},
["GNO"] = {29,38}, ["RFK"] = {30,40}, ["SMG"] = {28,38}, ["SML"] = {29,39}, ["SMA"] = {32,42}, ["SMC"] = {35,45},
["RFD"] = {40,50}, ["ULD"] = {42,52}, ["ZF"] = {44,54}, ["MAR"] = {46,55}, ["ST"] = {50,60}, ["BRD"] = {52,60},
["LBRS"] = {55,60}, ["DME"] = {58,60}, ["DMN"] = {58,60}, ["DMW"] = {58,60}, ["STR"] = {58,60}, ["SCH"] = {58,60},
["UBRS"] = {58,60}, ["ONY"] = {60,60}, ["MC"] = {60,60}, ["ZG"] = {60,60}, ["AQ20"]= {60,60}, ["BWL"] = {60,60},
["AQ40"] = {60,60}, ["NAX"] = {60,60}, ["WSG"] = {10,70}, ["AB"] = {20,70}, ["AV"] = {51,70}, ["MISC"]= {0,100},
["DEBUG"] = {0,100}, ["BAD"] = {0,100}, ["TRADE"]= {0,100}, ["SM2"] = {28,42}, ["DM2"] = {58,60}, ["DEADMINES"]={18,23},
}
GBB.PostTbcDungeonLevels = {
["RFC"] = {13,20}, ["DM"] = {16,24}, ["WC"] = {16,24}, ["SFK"] = {17,25}, ["STK"] = {21,29}, ["BFD"] = {20,28},
["GNO"] = {24,40}, ["RFK"] = {23,31}, ["SMG"] = {28,34}, ["SML"] = {30,38}, ["SMA"] = {32,42}, ["SMC"] = {35,44},
["RFD"] = {33,41}, ["ULD"] = {36,44}, ["ZF"] = {42,50}, ["MAR"] = {40,52}, ["ST"] = {45,54}, ["BRD"] = {48,60},
["LBRS"] = {54,60}, ["DME"] = {54,61}, ["DMN"] = {54,61}, ["DMW"] = {54,61}, ["STR"] = {56,61}, ["SCH"] = {56,61},
["UBRS"] = {53,61}, ["ONY"] = {60,60}, ["MC"] = {60,60}, ["ZG"] = {60,60}, ["AQ20"]= {60,60}, ["BWL"] = {60,60},
["AQ40"] = {60,60}, ["NAX"] = {60,60}, ["WSG"] = {10,70}, ["AB"] = {20,70}, ["AV"] = {51,70}, ["MISC"]= {0,100},
["DEBUG"] = {0,100}, ["BAD"] = {0,100}, ["TRADE"]= {0,100}, ["SM2"] = {28,42}, ["DM2"] = {58,60}, ["DEADMINES"]={16,24},
}
GBB.TbcDungeonLevels = {
["RAMPS"] = {60,62}, ["BF"] = {61,63}, ["SP"] = {62,64}, ["UB"] = {63,65}, ["MT"] = {64,66}, ["CRYPTS"] = {65,67},
["SETH"] = {67,69}, ["OHB"] = {66,68}, ["MECH"] = {69,70}, ["BM"] = {69,70}, ["MGT"] = {70,70}, ["SH"] = {70,70},
["BOT"] = {70,70}, ["SL"] = {70,70}, ["SV"] = {70,70}, ["ARC"] = {70,70}, ["KARA"] = {70,70}, ["GL"] = {70,70},
["MAG"] = {70,70}, ["SSC"] = {70,70}, ["EYE"] = {70,70}, ["ZA"] = {70,70}, ["HYJAL"] = {70,70}, ["BT"] = {70,70},
["SWP"] = {70,70}, ["EOTS"] = {15,70},
}
GBB.TbcDungeonNames = {
"RAMPS", "BF", "SP", "UB", "MT", "CRYPTS",
"SETH", "OHB", "MECH", "BM", "MGT", "SH",
"BOT", "SL", "SV", "ARC", "KARA", "GL",
"MAG", "SSC", "EYE", "ZA", "HYJAL", "BT",
"SWP",
}
GBB.VanillDungeonNames = {
"RFC", "WC" , "DM" , "SFK", "STK", "BFD", "GNO",
"RFK", "SMG", "SML", "SMA", "SMC", "RFD", "ULD",
"ZF", "MAR", "ST" , "BRD", "LBRS", "DME", "DMN",
"DMW", "STR", "SCH", "UBRS", "ONY", "MC", "ZG",
"AQ20", "BWL", "AQ40", "NAX",
}
GBB.PvpNames = {
"WSG", "AB", "AV", "EOTS"
}
GBB.Misc = {"MISC", "TRADE",}
GBB.DebugNames = {
"DEBUG", "BAD", "NIL",
}
-- Needed because Lua sucks, Blizzard switch to Python please
-- Takes in a list of dungeon lists, it will then concatenate the lists into a single list
-- it will put the dungeons in an order and give them a value incremental value that can be used for sorting later
-- ie one list "Foo" which contains "Bar" and "FooBar" and a second list "BarFoo" which contains "BarBar"
-- the output would be single list with "Bar" = 1, "FooBar" = 2, "BarFoo" = 3, "BarBar" = 4
local function ConcatenateLists(Names)
local result = {}
local index = 1
for k, nameLists in pairs (Names) do
for _, v in pairs(nameLists) do
result[v] = index
index = index + 1
end
end
return result, index
end
function GBB.GetDungeonSort()
local dungeonOrder = {GBB.VanillDungeonNames, GBB.TbcDungeonNames, GBB.PvpNames, GBB.Misc, GBB.DebugNames}
local vanillaDungeonSize = 0
-- Why does Lua not having a fucking size function
for _, _ in pairs(GBB.VanillDungeonNames) do
vanillaDungeonSize = vanillaDungeonSize + 1
end
local debugSize = 0
for _, _ in pairs(GBB.DebugNames) do
debugSize = debugSize+1
end
GBB.TBCDUNGEONSTART = vanillaDungeonSize + 1
GBB.MAXDUNGEON = vanillaDungeonSize
local tmp_dsort, concatenatedSize = ConcatenateLists(dungeonOrder)
local dungeonSort = {}
GBB.TBCMAXDUNGEON = concatenatedSize - debugSize - 1
for dungeon,nb in pairs(tmp_dsort) do
dungeonSort[nb]=dungeon
dungeonSort[dungeon]=nb
end
-- Need to do this because I don't know I am too lazy to debug the use of SM2, DM2, and DEADMINES
dungeonSort["SM2"] = 10.5
dungeonSort["DM2"] = 19.5
dungeonSort["DEADMINES"] = 99
return dungeonSort
end
local function DetermineVanillDungeonRange()
if GBB.GameType == "TBC" then
return GBB.PostTbcDungeonLevels
end
return GBB.VanillaDungeonLevels
end
GBB.dungeonLevel = Union(DetermineVanillDungeonRange(), GBB.TbcDungeonLevels)
|
object_tangible_loot_creature_loot_collections_meatlump_code_word_07 = object_tangible_loot_creature_loot_collections_shared_meatlump_code_word_07:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_meatlump_code_word_07, "object/tangible/loot/creature/loot/collections/meatlump_code_word_07.iff")
|
local typedefs = require "kong.db.schema.typedefs"
local split = require("kong.tools.utils").split
local RateLimitModel = require "kong.plugins.header-based-rate-limiting.rate_limit_model"
local get_null_uuid = require "kong.plugins.header-based-rate-limiting.get_null_uuid"
local function is_null_or_exists(entity_db, entity_id)
if not entity_id or entity_id == get_null_uuid(kong.db.strategy) then
return true
end
local res, err = entity_db:select({ id = entity_id })
if not err and res then
return true
end
return false
end
local function check_whether_service_exists(service_id)
if is_null_or_exists(kong.db.services, service_id) then
return true
end
return false, ("The referenced service '%s' does not exist."):format(service_id)
end
local function check_whether_route_exists(route_id)
if is_null_or_exists(kong.db.routes, route_id) then
return true
end
return false, ("The referenced route '%s' does not exist."):format(route_id)
end
local function check_infix(encoded_header_composition)
local individual_headers = split(encoded_header_composition, ",")
local prev_header
for _, header in ipairs(individual_headers) do
if header == "*" and prev_header ~= nil and prev_header ~= "*" then
return false, "Infix wildcards are not allowed in a header composition."
end
prev_header = header
end
return true
end
local function check_unique(encoded_header_composition, header_based_rate_limit)
local model = RateLimitModel(kong.db)
local custom_rate_limits = model:get(
header_based_rate_limit.service_id,
header_based_rate_limit.route_id,
{
encoded_header_composition
}
)
if #custom_rate_limits == 0 then
return true
end
return false, "A header based rate limit is already configured for this combination of service, route and header composition."
end
local function validate_header_composition(encoded_header_composition, header_based_rate_limit)
local valid, error_message = check_infix(encoded_header_composition)
if not valid then
return false, error_message
end
return check_unique(encoded_header_composition, header_based_rate_limit)
end
local db_type = kong and kong.configuration.database or "postgres"
local primary_key = { "id" }
if db_type == "cassandra" then
primary_key = { "service_id", "route_id", "header_composition" }
end
local SCHEMA = {
name = "header_based_rate_limits",
primary_key = primary_key,
cache_key = { "service_id", "route_id", "header_composition" },
generate_admin_api = false,
fields = {
{ id = typedefs.uuid },
{ service_id = { type = "string", default = get_null_uuid(db_type)} },
{ route_id = { type = "string", default = get_null_uuid(db_type)} },
{ header_composition = { type = "string", required = true } },
{ rate_limit = { type = "number", required = true } }
},
entity_checks = {
{ custom_entity_check = {
field_sources = { "service_id", "route_id", "header_composition" },
fn = function(entity)
if entity.service_id ~= ngx.null then
local valid, error_message = check_whether_service_exists(entity.service_id)
if not valid then
return false, error_message
end
end
if entity.route_id ~= ngx.null then
local valid, error_message = check_whether_route_exists(entity.route_id)
if not valid then
return false, error_message
end
end
if entity.header_composition ~= ngx.null then
local valid, error_message = validate_header_composition(entity.header_composition, entity)
if not valid then
return false, error_message
end
end
return true
end
} }
}
}
return { header_based_rate_limits = SCHEMA }
|
gPlugin = nil;
gConfig = nil;
gCollectionClass = nil;
function Initialize(aPlugin)
aPlugin:SetName("TinyWoodCutter")
aPlugin:SetVersion(1)
gPlugin = aPlugin
LoadSettings()
math.randomseed(os.time())
cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_BREAKING_BLOCK, OnPlayerBreakingBlock)
LOG("Initialised " .. aPlugin:GetName() .. " v." .. aPlugin:GetVersion())
return true
end
function OnDisable()
LOG(gPlugin:GetName() .. " v" .. gPlugin:GetVersion() .. " was disabled")
end |
----------------------------------------------------------------------------------------------------
-- Issue: https://github.com/smartdevicelink/sdl_core/issues/3668
----------------------------------------------------------------------------------------------------
-- Description: Check SDL transfer erroneous response to the App in case HMI responds
-- with unsuccessful result code to at least one 'SetGlobalProperties' request
--
-- Steps:
-- 1. App is registered
-- 2. App sends 'SetGlobalProperties' for multiple properties
-- 3. App sends 'ResetGlobalProperties' for multiple properties
-- SDL does:
-- - Send a few SetGlobalProperties requests to HMI
-- 4. HMI responds with unsuccessful result code to at least one request
-- SDL does:
-- - Transfer erroneous response to the App
----------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require("user_modules/sequences/actions")
local utils = require("user_modules/utils")
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local grids = {
DRIVER = { col = 0, colspan = 1, row = 0, rowspan = 1, level = 0, levelspan = 1 },
FRONT_PASSENGER = { col = 2, colspan = 1, row = 0, rowspan = 1, level = 0, levelspan = 1 }
}
--[[ Local Functions ]]
local function sendSetGlobalProperties()
local mobileSession = common.mobile.getSession()
local hmi = common.hmi.getConnection()
local params = {
userLocation = { grid = grids.FRONT_PASSENGER },
menuTitle = "Menu Title",
helpPrompt = { { text = "Help Prompt", type = "TEXT" } }
}
local cid = mobileSession:SendRPC("SetGlobalProperties", params)
hmi:ExpectRequest("RC.SetGlobalProperties", {
userLocation = params.userLocation,
appID = common.app.getHMIId()
})
:Do(function(_, data)
hmi:SendResponse(data.id, data.method, "SUCCESS", {})
end)
hmi:ExpectRequest("UI.SetGlobalProperties", {
menuTitle = params.menuTitle,
appID = common.app.getHMIId()
})
:Do(function(_, data)
hmi:SendResponse(data.id, data.method, "SUCCESS", {})
end)
hmi:ExpectRequest("TTS.SetGlobalProperties", {
helpPrompt = params.helpPrompt,
appID = common.app.getHMIId()
})
:Do(function(_, data)
hmi:SendResponse(data.id, data.method, "SUCCESS", {})
end)
mobileSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end
local function sendResetGlobalProperties(pIfaceError)
local mobileSession = common.mobile.getSession()
local hmi = common.hmi.getConnection()
local params = { properties = { "USER_LOCATION", "HELPPROMPT", "MENUNAME" } }
local cid = mobileSession:SendRPC("ResetGlobalProperties", params)
local function sendResponse(data)
local iface = utils.splitString(data.method, '.')[1]
if iface == pIfaceError then
hmi:SendError(data.id, data.method, "REJECTED", "Error message")
else
hmi:SendResponse(data.id, data.method, "SUCCESS", {})
end
end
hmi:ExpectRequest("RC.SetGlobalProperties")
:Do(function(_, data)
sendResponse(data)
end)
hmi:ExpectRequest("UI.SetGlobalProperties")
:Do(function(_, data)
sendResponse(data)
end)
hmi:ExpectRequest("TTS.SetGlobalProperties")
:Do(function(_, data)
sendResponse(data)
end)
mobileSession:ExpectResponse(cid, { success = false, resultCode = "REJECTED" })
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Title("Test")
for _, iface in pairs({"UI", "TTS", "RC"}) do
runner.Title("Erroneous response from HMI for interface " .. iface)
runner.Step("Send SetGlobalProperties with multiple properties", sendSetGlobalProperties)
runner.Step("Send ResetGlobalProperties with erroneous response from HMI", sendResetGlobalProperties, { iface })
end
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
local box = require 'box'
local fiber = require 'fiber'
local assert = assert
local say_error = say_error
local pairs, type = pairs, type
local ev_now = os.ev_now
local tostring = tostring
local loops_stat = stat.new_with_graphite('loops')
-- exmaple
--
-- local box = require 'box'
-- local loop = require 'box.loop'
-- local function action(ushard, state, conf)
-- if state == nil then
-- state = initial_state_for_ushard() -- we just entered into ushard
-- end
-- local space = ushard:object_space(conf.space)
-- if we_do_some_useful_things_and_succeed(state, space, conf) then
-- modify(state, conf)
-- if done_with_this_ushard(state, conf) then
-- return nil, sleep
-- else
-- return state, sleep
-- end
-- else -- go to next ushard
-- return nil, sleep
-- end
-- end
--
-- loop.start{name="some_loop", exec=action, space=1, other_op=2}}
module(...)
local function loop(state, conf)
local end_sleep = _M.testing and 0.03 or 1
local first = box.next_primary_ushard_n(-1)
if first == -1 then
return nil, end_sleep
end
if state == nil then
state = {states={}, sleeps={}}
end
local ushardn = first
local now = ev_now()
local min_sleep_till = now + end_sleep
local states, sleeps = {}, {}
local txn_name = "loop:"..conf.name
local stat_name = conf.name .. "_box_cnt"
repeat
local sleep_till = state.sleeps[ushardn] or 0
local ustate = state.states[ushardn]
if sleep_till <= now then
loops_stat:add1(stat_name)
local ok, state_or_err, sleep = box.with_named_txn(ushardn, txn_name, conf.exec, ustate, conf.user)
fiber.gc()
if not ok then
say_error('box.loop "%s"@%d: %s', conf.name, ushardn, state_or_err)
loops_stat:add1(conf.name .. "_box_error")
state_or_err = nil
sleep = end_sleep
elseif state_or_err == nil and (sleep or 0) < end_sleep then
sleep = end_sleep
end
now = ev_now()
sleep_till = now + (sleep or end_sleep)
ustate = state_or_err
end
states[ushardn] = ustate
sleeps[ushardn] = sleep_till
if sleep_till < min_sleep_till then
min_sleep_till = sleep_till
end
ushardn = box.next_primary_ushard_n(ushardn)
until ushardn == -1 or sleeps[ushardn]
if ushardn == -1 then
return nil, end_sleep
end
state.states = states
state.sleeps = sleeps
return state, (min_sleep_till <= now and 0.001 or (min_sleep_till - now))
end
function start(conf)
local newconf = {exec = conf.exec, name = conf.name, user={}}
local name = conf.name
assert(type(name) == "string")
for k,v in pairs(conf) do
newconf.user[k] = v
end
newconf.user.exec = nil
fiber.loop(name, loop, newconf)
end
|
local sprites = {}
for i, mod in ipairs(script:GetChildren()) do
for k, v in pairs(require(mod)) do
sprites[k] = v
end
end
return sprites |
--[[
Singular BillboardGui that displays a user's ChatBubbles.
We also have BubbleChatBillboards (notice the plural), which handles
rendering each BubbleChatBillboard.
]]
local CorePackages = game:GetService("CorePackages")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Roact = require(CorePackages.Packages.Roact)
local RoactRodux = require(CorePackages.Packages.RoactRodux)
local t = require(CorePackages.Packages.t)
local Otter = require(CorePackages.Packages.Otter)
local BubbleChatList = require(script.Parent.BubbleChatList)
local ChatBubbleDistant = require(script.Parent.ChatBubbleDistant)
local Types = require(script.Parent.Parent.Types)
local Constants = require(script.Parent.Parent.Constants)
local BubbleChatBillboard = Roact.PureComponent:extend("BubbleChatBillboard")
local SPRING_CONFIG = {
dampingRatio = 1,
frequency = 4,
}
BubbleChatBillboard.validateProps = t.strictInterface({
userId = t.string,
onFadeOut = t.optional(t.callback),
-- RoactRodux
chatSettings = Types.IChatSettings,
messageIds = t.optional(t.array(t.string)), -- messageIds == nil during the last bubble's fade out animation
lastMessage = t.optional(Types.IMessage),
})
function BubbleChatBillboard:init()
self:setState({
adornee = nil,
isInsideRenderDistance = false,
isInsideMaximizeDistance = false,
})
self.isMounted = false
self.offset, self.updateOffset = Roact.createBinding(Vector3.new())
self.offsetMotor = Otter.createSingleMotor(0)
self.offsetMotor:onStep(function(offset)
self.updateOffset(Vector3.new(0, offset, 0))
end)
self.offsetGoal = 0
self.onLastBubbleFadeOut = function()
if self.props.onFadeOut then
self.props.onFadeOut(self.props.userId)
end
end
end
function BubbleChatBillboard:didMount()
self.isMounted = true
local adornee = self.props.lastMessage and self.props.lastMessage.adornee
self:setState({
adornee = adornee
})
local initialOffset = self:getVerticalOffset(adornee)
self.offsetGoal = initialOffset
self.offsetMotor:setGoal(Otter.instant(initialOffset))
-- When the character respawns, we need to update the adornee
local player = Players:GetPlayerFromCharacter(adornee)
if player then
if player.Character then
coroutine.wrap(function()
self:onCharacterAdded(player, player.Character)
end)()
end
self.characterConn = player.CharacterAdded:Connect(function(character)
self:onCharacterAdded(player, character)
end)
end
-- Need to use a loop because property changed signals don't work on Position
self.heartbeatConn = RunService.Heartbeat:Connect(function()
local adorneePart = self:getAdorneePart()
if workspace.CurrentCamera and adorneePart then
local distance = (workspace.CurrentCamera.CFrame.Position - adorneePart.Position).Magnitude
local isInsideRenderDistance = distance < self.props.chatSettings.MaxDistance
local isInsideMaximizeDistance = distance < self.props.chatSettings.MinimizeDistance
if isInsideMaximizeDistance ~= self.state.isInsideMaximizeDistance or isInsideRenderDistance ~= self.state.isInsideRenderDistance then
self:setState({
isInsideRenderDistance = isInsideRenderDistance,
isInsideMaximizeDistance = isInsideMaximizeDistance
})
end
end
local offset = self:getVerticalOffset(self.state.adornee)
if math.abs(offset - self.offsetGoal) > Constants.BILLBOARD_OFFSET_EPSILON then
self.offsetGoal = offset
self.offsetMotor:setGoal(Otter.spring(offset, SPRING_CONFIG))
end
end)
end
function BubbleChatBillboard:willUnmount()
self.isMounted = false
if self.characterConn then
self.characterConn:Disconnect()
self.characterConn = nil
end
if self.heartbeatConn then
self.heartbeatConn:Disconnect()
self.heartbeatConn = nil
end
if self.humanoidDiedConn then
self.humanoidDiedConn:Disconnect()
self.humanoidDiedConn = nil
end
self.offsetMotor:destroy()
end
-- Wait for the first of the passed signals to fire
local function waitForFirst(...)
local shunt = Instance.new("BindableEvent")
local slots = {...}
local function fire(...)
for i = 1, #slots do
slots[i]:Disconnect()
end
return shunt:Fire(...)
end
for i = 1, #slots do
slots[i] = slots[i]:Connect(fire)
end
return shunt.Event:Wait()
end
-- Fires when the adornee character respawns. Updates the state adornee to the new character once it has respawned.
function BubbleChatBillboard:onCharacterAdded(player, character)
-- This part is inspired from HumanoidReadyUtil.lua
-- Make sure that character is parented, stop execution if the character has respawned again in the meantime
if not character.Parent then
waitForFirst(character.AncestryChanged, player.CharacterAdded)
end
if player.Character ~= character or not character.Parent then
return
end
-- Make sure that the humanoid is parented, stop execution if the character has respawned again in the meantime
local humanoid = character:FindFirstChildOfClass("Humanoid")
while character:IsDescendantOf(game) and not humanoid do
waitForFirst(character.ChildAdded, character.AncestryChanged, player.CharacterAdded)
humanoid = character:FindFirstChildOfClass("Humanoid")
end
if player.Character ~= character or not character:IsDescendantOf(game) then
return
end
-- Make sure that the root part is parented, stop execution if the character has respawned again in the meantime
local rootPart = character:FindFirstChild("HumanoidRootPart")
while character:IsDescendantOf(game) and not rootPart do
waitForFirst(character.ChildAdded, character.AncestryChanged, player.CharacterAdded)
rootPart = character:FindFirstChild("HumanoidRootPart")
end
if rootPart and character:IsDescendantOf(game) and player.Character == character and self.isMounted then
self:setState({
adornee = humanoid.Health == 0 and character:FindFirstChild("Head") or character
})
if self.humanoidDiedConn then
self.humanoidDiedConn:Disconnect()
self.humanoidDiedConn = nil
end
self.humanoidDiedConn = humanoid.Died:Connect(function()
self:setState({
adornee = character:FindFirstChild("Head") or character
})
end)
end
end
-- Offsets the billboard so it will align properly with the top of the
-- character, regardless of what assets they're wearing.
function BubbleChatBillboard:getVerticalOffset(adornee)
if not adornee then
return 0
elseif adornee:IsA("Model") then
-- Billboard is adornee'd to the PrimaryPart -> need to calculate the distance between it and the top of the
-- bounding box
local orientation, size = adornee:GetBoundingBox()
if adornee.PrimaryPart then
local relative = orientation:PointToObjectSpace(adornee.PrimaryPart.Position)
return size.Y / 2 - relative.Y
end
return size.Y / 2
elseif adornee:IsA("BasePart") then
return adornee.Size.Y / 2
end
end
function BubbleChatBillboard:getAdorneePart()
local adornee = self.state.adornee
if adornee and adornee:IsA("Model") then
return adornee.PrimaryPart
else
return adornee
end
end
function BubbleChatBillboard:render()
local adorneePart = self:getAdorneePart()
local isLocalPlayer = self.props.userId == tostring(Players.LocalPlayer.UserId)
local settings = self.props.chatSettings
if not adorneePart then
return
end
-- Don't render the billboard at all if out of range. We could use
-- the MaxDistance property on the billboard, but that keeps
-- instances around. This approach means nothing exists in the DM
-- when there are no messages.
if not self.state.isInsideRenderDistance then
return
end
return Roact.createElement("BillboardGui", {
Adornee = adorneePart,
Size = UDim2.fromOffset(500, 200),
SizeOffset = Vector2.new(0, 0.5),
-- For other players, increase vertical offset by 1 to prevent overlaps with the name display
-- For the local player, increase Z offset to prevent the character from overlapping his bubbles when jumping/emoting
-- This behavior is the same as the old bubble chat
StudsOffset = Vector3.new(0, (isLocalPlayer and 0 or 1) + settings.VerticalStudsOffset, isLocalPlayer and 2 or 0.1),
StudsOffsetWorldSpace = self.offset,
ResetOnSpawn = false,
}, {
DistantBubble = not self.state.isInsideMaximizeDistance and Roact.createElement(ChatBubbleDistant, {
fadingOut = not self.props.messageIds or #self.props.messageIds == 0,
onFadeOut = self.onLastBubbleFadeOut,
}),
BubbleChatList = self.state.isInsideMaximizeDistance and Roact.createElement(BubbleChatList, {
userId = self.props.userId,
isVisible = self.state.isInsideMaximizeDistance,
onLastBubbleFadeOut = self.onLastBubbleFadeOut,
})
})
end
function BubbleChatBillboard:didUpdate()
-- If self.state.isInsideRenderDistance, the responsibility to call self.onLastBubbleFadeOut will be on either
-- DistantBubble or BubbleChatList (after their fade out animation)
if (not self.props.messageIds or #self.props.messageIds == 0) and not self.state.isInsideRenderDistance then
self.onLastBubbleFadeOut()
end
end
local function mapStateToProps(state, props)
local messageIds = state.userMessages[props.userId]
local lastMessageId = messageIds and #messageIds >= 1 and messageIds[#messageIds]
return {
chatSettings = state.chatSettings,
messageIds = messageIds,
lastMessage = lastMessageId and state.messages[lastMessageId]
}
end
return RoactRodux.connect(mapStateToProps)(BubbleChatBillboard)
|
function 手势滑动(dialog,id,yy)
velocityTracker = VelocityTracker.obtain();
id.onTouch=function(v,e)
a=e.getAction()&255
switch a
case MotionEvent.ACTION_DOWN
velocityTracker.addMovement(e)
downY=e.getY()
case MotionEvent.ACTION_MOVE
velocityTracker.addMovement(e)
velocityTracker.computeCurrentVelocity(1000);
moveY=e.getY()
Y=moveY - downY
if Y>0 then
v.setTranslationY(Y/2)
end
vsd = velocityTracker.getYVelocity()
case MotionEvent.ACTION_UP
upY=e.getY()
upY=upY-downY
if upY>0 then
if upY>yy || vsd>5000 then
ObjectAnimator.ofFloat(icon_down_box,"translationY",{upY/2,activity.getWidth()}).setDuration(300).start()
--ObjectAnimator().ofFloat(v,"Y",{upY/2,activity.getHeight()}).setDuration(500).start()
task(300,function()
dialog.dismiss()
velocityTracker.recycle()
end)
else
ObjectAnimator.ofFloat(icon_down_box,"translationY",{upY/2,0}).setDuration(300).start()
--ObjectAnimator().ofFloat(v,"Y",{upY/2,0}).setDuration(500).start()
end
end
end
return true
end
end
function 显示()
import "android.graphics.drawable.ColorDrawable"
local DownLayout={
LinearLayout;
id="dc";
layout_height="fill";
layout_width="fill";
{
LinearLayout;
layout_height="fill";--导航栏高度()+activity.getHeight();
layout_width="fill";
orientation="vertical";
background="#00000000";
onClick=function()
ObjectAnimator.ofFloat(icon_down_box,"translationY",{0,activity.getWidth()}).setDuration(300).start()
task(300,function()dialog1.dismiss()end)
end,
{
LinearLayout;
layout_height=activity.getHeight();
layout_width="fill";
layout_weight="1";
},
{
LinearLayout;
id="icon_down_box";
layout_height="wrap_content";
layout_width="fill";
layout_gravity="bottom";
background="#FFffffff";
orientation="vertical";
{
FrameLayout;
layout_height="66dp";
layout_width="fill";
{
ColorCardView{radius=88,ElevationColor="6D44FE"};
layout_height="fill";
layout_width="fill";
},
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="8dp";
radius="25dp";
elevation="0";
background="#FF6D44FE";
{
LinearLayout;
layout_height="fill";
layout_width="fill";
orientation="horizontal";
{
FrameLayout;
layout_height="fill";
layout_width="50dp";
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="7.5dp";
radius="17.5dp";
elevation="0";
background="#33ffffff";
{
FrameLayout;
layout_height="fill";
layout_width="fill";
{
ImageView;
layout_height="22dp";
layout_width="22dp";
layout_gravity="center";
colorFilter="#ffffffff";
src="Image/icon/paint.png";
}
}
}
},
{
FrameLayout;
layout_height="fill";
layout_width="fill";
layout_weight="1";
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="7.5dp";
radius="17.5dp";
elevation="0";
background="#33ffffff";
{
TextView;
text="#ffffffff";
textColor="#88ffffff";
textSize="13dp";
layout_height="fill";
layout_width="fill";
gravity="center";
}
}
},
{
FrameLayout;
layout_height="fill";
layout_width="fill";
layout_weight="1";
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="7.5dp";
radius="17.5dp";
elevation="0";
background="#33ffffff";
{
TextView;
text="#FF565A5F";
textColor="#88ffffff";
textSize="13dp";
layout_height="fill";
layout_width="fill";
gravity="center";
}
}
},
{
FrameLayout;
layout_height="fill";
layout_width="50dp";
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="7.5dp";
radius="17.5dp";
elevation="0";
background="#33ffffff";
{
FrameLayout;
layout_height="fill";
layout_width="fill";
{
ImageView;
layout_height="22dp";
layout_width="22dp";
layout_gravity="center";
colorFilter="#ffffffff";
src="Image/icon/paint.png";
}
}
}
},
}
},
},
{
LinearLayout;
layout_height="50%w";
layout_width="fill";
orientation="horizontal";
{
FrameLayout;
layout_height="fill";
layout_width="fill";
{
ColorCardView{radius=33,ElevationColor="565A5F"};
layout_height="fill";
layout_width="fill";
},
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="10dp";
radius="10dp";
elevation="3dp";
background="#FF565A5F";
}
}
},
{
LinearLayout;
layout_height="66dp";
layout_width="fill";
orientation="horizontal";
{
FrameLayout;
layout_height="fill";
layout_width="fill";
layout_weight="1";
{
ColorCardView{radius=88,ElevationColor="565A5F"};
layout_height="fill";
layout_width="fill";
},
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="8dp";
radius="25dp";
elevation="0";
background="#FF565A5F";
{
LinearLayout;
layout_height="fill";
layout_width="fill";
orientation="horizontal";
{
FrameLayout;
layout_height="fill";
layout_width="50dp";
{
ImageView;
layout_height="25dp";
layout_width="25dp";
layout_gravity="center";
colorFilter="#ffffffff";
src="Image/icon/size.png";
}
},
{
TextView;
text="200*200";
textColor="#88ffffff";
textSize="13dp";
layout_height="fill";
layout_width="fill";
gravity="center";
}
}
}
},
{
FrameLayout;
layout_height="fill";
layout_width="66dp";
{
ColorCardView{radius=88,ElevationColor="565A5F"};
layout_height="fill";
layout_width="fill";
},
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="8dp";
radius="25dp";
elevation="0";
background="#FF565A5F";
{
FrameLayout;
layout_height="fill";
layout_width="fill";
{
ImageView;
layout_height="22dp";
layout_width="22dp";
layout_gravity="center";
colorFilter="#ffffffff";
src="Image/icon/svg_down.png";
}
}
}
},
{
FrameLayout;
layout_height="fill";
layout_width="66dp";
{
ColorCardView{radius=88,ElevationColor="565A5F"};
layout_height="fill";
layout_width="fill";
},
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="8dp";
radius="25dp";
elevation="0";
background="#FF565A5F";
{
FrameLayout;
layout_height="fill";
layout_width="fill";
{
ImageView;
layout_height="22dp";
layout_width="22dp";
layout_gravity="center";
colorFilter="#ffffffff";
src="Image/icon/al_down.png";
}
}
}
},
{
FrameLayout;
layout_height="fill";
layout_width="66dp";
{
ColorCardView{radius=88,ElevationColor="565A5F"};
layout_height="fill";
layout_width="fill";
},
{
CardView;
layout_height="fill";
layout_width="fill";
layout_margin="8dp";
radius="25dp";
elevation="0";
background="#FF565A5F";
{
FrameLayout;
layout_height="fill";
layout_width="fill";
{
ImageView;
layout_height="22dp";
layout_width="22dp";
layout_gravity="center";
colorFilter="#ffffffff";
src="Image/icon/png_down.png";
}
}
}
}
}
}
}
}
dialog= AlertDialog.Builder(this)
dialog1=dialog.show()
dialog1.getWindow().setContentView(loadlayout(DownLayout));
dialog1.getWindow().setBackgroundDrawable(ColorDrawable(0x00000000));
dialogWindow = dialog1.getWindow();
dialogWindow.setGravity(Gravity.BOTTOM);
dialog1.setCanceledOnTouchOutside(true)
dialog1.getWindow().getAttributes().width=(activity.Width);
dialog1.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
--dialog1.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
--]]
手势滑动(dialog1,icon_down_box,240)
控件圆角(icon_down_box,88,88,0,0,0xFFffffff)
import "android.animation.ObjectAnimator"
ObjectAnimator.ofFloat(icon_down_box,"translationY",{activity.getWidth(),0}).setDuration(380).start()
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.