content stringlengths 5 1.05M |
|---|
-- any change requiers :PackerCompile
-- https://github.com/wbthomason/packer.nvim
return require('packer').startup(function()
use {
'Pocco81/AutoSave.nvim',
branch = 'main',
config = function()
require('autosave').setup { enabled = true, events = { 'InsertLeave' } }
end,
}
use 'justincampbell/vim-eighties' -- Automatically resizes your windows
use { 'mg979/vim-visual-multi', branch = 'master' }
use 'tpope/vim-repeat'
use 'MattesGroeger/vim-bookmarks'
use 'majutsushi/tagbar'
use 'mhinz/vim-startify' -- start screen
-- use { 'goolord/alpha-nvim', config = function () require'alpha'.setup(require'alpha.themes.startify'.opts) end } -- dont know how to opening multiple files
use { 'mbbill/undotree', cmd = { 'UndotreeToggle' } }
-- use 'vim-scripts/YankRing.vim' -- fix keybinding
use 'bfredl/nvim-miniyank'
-- CODE
use 'tpope/vim-surround'
use { 'sbdchd/neoformat', cmd = { 'Neoformat' } }
-- NOTE
use { 'itchyny/calendar.vim', cmd = { 'Calendar' } } -- problem with api
use { 'aserebryakov/vim-todo-lists', tag = '0.7.1' }
use { 'kabbamine/lazyList.vim', cmd = { 'LazyList' } }
-- asciidoctor
-- use {'habamax/vim-asciidoctor', ft = {'asciidoctor', 'asciidoc', 'adoc'}}
use { 'habamax/vim-asciidoctor', ft = { 'asciidoctor' } }
-- markdown
use { 'plasticboy/vim-markdown', ft = { 'markdown' } }
use { 'previm/previm', ft = { 'markdown' } }
use { 'godlygeek/tabular', ft = { 'markdown' } } -- do wyrównywania np w tabelach http://vimcasts.org/episodes/aligning-text-with-tabular-vim/ :Tab /|
--Syntax
use 'baskerville/vim-sxhkdrc'
use 'kyazdani42/nvim-web-devicons'
-- for neovim and lua
use { 'gennaro-tedesco/nvim-jqx', ft = { 'json' } }
use {
'kyazdani42/nvim-tree.lua',
cmd = { 'NvimTreeToggle' },
config = function()
require('nvim-tree').setup {}
end,
}
use { 'b3nj5m1n/kommentary', branch = 'main' }
use {
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
}
use { 'NTBBloodbath/rest.nvim', branch = 'main', ft = { 'http' }, requires = { 'nvim-lua/plenary.nvim' } }
use { 'jose-elias-alvarez/null-ls.nvim', branch = 'main', requires = { 'nvim-lua/plenary.nvim' } }
use {
'nvim-treesitter/nvim-treesitter',
run = ':TSUpdate',
config = function()
require('nvim-treesitter.configs').setup {
ensure_installed = 'maintained',
highlight = {
enable = true,
additional_vim_regex_highlighting = false,
},
}
end,
-- {"java", "javascript", "typescript", "lua", "asciidoc", "markdown", "http", "json" }TSInstall css html
}
use {
'phaazon/hop.nvim',
branch = 'v1', -- optional but strongly recommended
config = function()
require('hop').setup { keys = 'etovxqpdygfblzhckisuran' }
end,
}
use { 'abecodes/tabout.nvim', after = { 'nvim-cmp' } } -- doesn't support asciidoc
use {
'hrsh7th/nvim-cmp',
requires = { -- https://github.com/topics/nvim-cmp list of the sources
{ 'hrsh7th/nvim-cmp' },
{ 'hrsh7th/cmp-buffer' },
{ 'hrsh7th/cmp-path' },
{ 'hrsh7th/cmp-calc' },
{ 'hrsh7th/cmp-cmdline' },
{ 'dmitmel/cmp-cmdline-history' },
{ 'quangnguyen30192/cmp-nvim-ultisnips' },
{ 'hrsh7th/cmp-nvim-lua' }, -- vim.api
{ 'hrsh7th/cmp-nvim-lsp' },
{ 'uga-rosa/cmp-dictionary' },
config = function()
require('cmp-nvim-ultisnips').setup {}
end,
},
}
use 'SirVer/ultisnips'
use { 'folke/zen-mode.nvim', branch = 'main', cmd = { 'ZenMode' } }
use {
'nvim-telescope/telescope.nvim',
requires = {
{ 'nvim-lua/popup.nvim', opt = true },
{ 'tom-anders/telescope-vim-bookmarks.nvim' },
{ 'fhill2/telescope-ultisnips.nvim' },
{ 'crispgm/telescope-heading.nvim', lock = true }, -- I added asciidoc support
{ 'nvim-lua/plenary.nvim', opt = true },
},
}
use 'nvim-lualine/lualine.nvim'
use 'akinsho/bufferline.nvim'
-- use { 'romgrk/barbar.nvim', requires = {'kyazdani42/nvim-web-devicons', opt = true} }
-- use { 'kdheepak/tabline.nvim', requires = { 'hoob3rt/lualine.nvim', 'kyazdani42/nvim-web-devicons' } }
use {
'glacambre/firenvim',
run = function()
vim.fn['firenvim#install'](0)
end,
}
-- use { "folke/which-key.nvim", config = function() require("which-key").setup { } end }
use { 'kdheepak/lazygit.nvim', cmd = { 'LazyGit' } }
-- COLORSCHEMES
-- https://www.dunebook.com/best-vim-themes/
-- https://vimcolorschemes.com/top
-- ayu, vim-one, one-half, drakula NeoSolarized, pepertheme
-- use {'rakr/vim-one', as = 'one'}
-- use 'iCyMind/NeoSolarized'
-- use 'patstockwell/vim-monokai-tasty'
use { 'dracula/vim', as = 'dracula' }
use 'bluz71/vim-moonfly-colors'
end)
|
--[[
item.lua
An item slot button
--]]
local ADDON, Addon = ...
local Item = Addon.Tipped:NewClass('Item', Addon.IsRetail and 'ItemButton' or 'Button', 'ContainerFrameItemButtonTemplate', true)
local Search = LibStub('LibItemSearch-1.2')
local Unfit = LibStub('Unfit-1.0')
Item.SlotTypes = {
[-3] = 'reagent',
[0x00001] = 'quiver',
[0x00002] = 'quiver',
[0x00003] = 'soul',
[0x00004] = 'soul',
[0x00006] = 'herb',
[0x00007] = 'enchant',
[0x00008] = 'leather',
[0x00009] = 'key',
[0x00010] = 'inscribe',
[0x00020] = 'herb',
[0x00040] = 'enchant',
[0x00080] = 'engineer',
[0x00200] = 'gem',
[0x00400] = 'mine',
[0x08000] = 'tackle',
[0x10000] = 'fridge'
}
--[[ Construct ]]--
function Item:New(parent, bag, slot)
local b = self:Super(Item):New(parent)
b:SetID(slot)
b.bag = bag
if b:IsVisible() then
b:Update()
else
b:Show()
end
return b
end
function Item:Construct()
local b = self:GetBlizzard() or self:Super(Item):Construct()
local name = b:GetName()
b.Flash = b:CreateAnimationGroup()
b.IconGlow = b:CreateTexture(nil, 'OVERLAY', nil, -1)
b.Cooldown, b.QuestBorder = _G[name .. 'Cooldown'], _G[name .. 'IconQuestTexture']
b.UpdateTooltip = self.UpdateTooltip
b.newitemglowAnim:SetLooping('NONE')
b.IconOverlay:SetAtlas('AzeriteIconFrame')
b.QuestBorder:SetTexture(TEXTURE_ITEM_QUEST_BANG)
b.IconGlow:SetTexture('Interface/Buttons/UI-ActionButton-Border')
b.IconGlow:SetBlendMode('ADD')
b.IconGlow:SetPoint('CENTER')
b.IconGlow:SetSize(67, 67)
for i = 1, 3 do
local fade = b.Flash:CreateAnimation('Alpha')
fade:SetOrder(i * 2)
fade:SetDuration(.2)
fade:SetFromAlpha(.8)
fade:SetToAlpha(0)
local fade = b.Flash:CreateAnimation('Alpha')
fade:SetOrder(i * 2 + 1)
fade:SetDuration(.3)
fade:SetFromAlpha(0)
fade:SetToAlpha(.8)
end
b:SetScript('OnEvent', nil)
b:SetScript('OnShow', b.OnShow)
b:SetScript('OnHide', b.OnHide)
b:SetScript('OnEnter', b.OnEnter)
b:SetScript('OnLeave', b.OnLeave)
b:SetScript('PreClick', b.OnPreClick)
b:HookScript('OnClick', b.OnPostClick)
return b
end
function Item:GetBlizzard(id)
if not Addon.sets.displayBlizzard and Addon.Frames:AreBasicsEnabled() then
local id = self:NumFrames() + 1
local bag = ceil(id / 36)
local slot = (id-1) % 36 + 1
local b = _G[format('ContainerFrame%dItem%d', bag, slot)]
if b then
b:ClearAllPoints()
return self:Bind(b)
end
end
end
function Item:Bind(frame)
local class = self
while class do
for k,v in pairs(class) do
frame[k] = frame[k] or v
end
class = class:GetSuper()
end
return frame
end
--[[ Interaction ]]--
function Item:OnShow()
self:RegisterFrameSignal('FOCUS_BAG', 'UpdateFocus')
self:RegisterSignal('SEARCH_CHANGED', 'UpdateSearch')
self:RegisterSignal('SEARCH_TOGGLED', 'UpdateSearch')
self:RegisterSignal('FLASH_ITEM', 'OnItemFlashed')
self:Update()
end
function Item:OnHide()
if self.hasStackSplit == 1 then
StackSplitFrame:Hide()
end
if self:IsNew() then
C_NewItems.RemoveNewItem(self:GetBag(), self:GetID())
end
self:UnregisterAll()
end
function Item:OnPreClick(button)
if not IsModifiedClick() and button == 'RightButton' then
if REAGENTBANK_CONTAINER and Addon:InBank() and IsReagentBankUnlocked() and GetContainerNumFreeSlots(REAGENTBANK_CONTAINER) > 0 then
if not Addon:IsReagents(self:GetBag()) and Search:IsReagent(self.info.link) then
for _, bag in ipairs {BANK_CONTAINER, 5, 6, 7, 8, 9, 10, 11} do
for slot = 1, GetContainerNumSlots(bag) do
if GetContainerItemID(bag, slot) == self.info.id then
local free = self.info.stack - select(2, GetContainerItemInfo(bag, slot))
if free > 0 then
SplitContainerItem(self:GetBag(), self:GetID(), min(self.info.count, free))
PickupContainerItem(bag, slot)
end
end
end
end
UseContainerItem(self:GetBag(), self:GetID(), nil, true)
end
end
end
self.locked = self.info.locked
end
function Item:OnPostClick(button)
if self:FlashFind(button) or IsModifiedClick() then
return
elseif button == 'RightButton' and Addon:InVault() and self.locked then
for i = 10, 1, -1 do
if GetVoidTransferDepositInfo(i) == self.info.id then
ClickVoidTransferDepositSlot(i, true)
end
end
end
end
function Item:OnEnter()
self:UpdateTooltip()
end
function Item:OnLeave()
self:Super(Item):OnLeave()
ResetCursor()
end
--[[ Update ]]--
function Item:Update()
self.info = self:GetInfo()
self.hasItem = self.info.id and true -- for blizzard template
self.readable = self.info.readable -- for blizzard template
self:Delay(0.05, 'UpdateSecondary')
self:UpdateSlotColor()
self:UpdateBorder()
SetItemButtonTexture(self, self.info.icon or self:GetEmptyItemIcon())
SetItemButtonCount(self, self.info.count)
end
function Item:UpdateLocked()
self.info = self:GetInfo()
self:SetLocked(self.info.locked)
end
function Item:UpdateSecondary()
if self:GetFrame() then
self:UpdateFocus()
self:UpdateSearch()
self:UpdateCooldown()
self:UpdateUpgradeIcon()
if GameTooltip:IsOwned(self) then
self:UpdateTooltip()
end
end
end
--[[ Appearance ]]--
function Item:UpdateBorder()
local id, quality, link = self.info.id, self.info.quality, self.info.link
local overlay = (link and IsCorruptedItem and IsCorruptedItem(link) and 'Nzoth-inventory-icon') or (id and C_AzeriteEmpoweredItem and C_AzeriteEmpoweredItem.IsAzeriteEmpoweredItemByID(id) and 'AzeriteIconFrame')
local new = Addon.sets.glowNew and self:IsNew()
local quest, questID = self:IsQuestItem()
local paid = self:IsPaid()
local r,g,b
if new and not self.flashAnim:IsPlaying() then
self.flashAnim:Play()
self.newitemglowAnim:Play()
end
if overlay then
self.IconOverlay:SetAtlas(overlay)
end
if id then
if Addon.sets.glowQuest and quest then
r,g,b = 1, .82, .2
elseif Addon.sets.glowUnusable and Unfit:IsItemUnusable(id) then
r,g,b = RED_FONT_COLOR.r, RED_FONT_COLOR.g, RED_FONT_COLOR.b
elseif Addon.sets.glowSets and Search:InSet(link) then
r,g,b = .1, 1, 1
elseif Addon.sets.glowQuality and quality and quality > 1 then
r,g,b = GetItemQualityColor(quality)
end
end
self.IconBorder:SetTexture(id and C_ArtifactUI and C_ArtifactUI.GetRelicInfoByItemID(id) and 'Interface/Artifacts/RelicIconFrame' or 'Interface/Common/WhiteIconFrame')
self.IconBorder:SetVertexColor(r,g,b)
self.IconBorder:SetShown(r)
self.IconGlow:SetVertexColor(r,g,b, Addon.sets.glowAlpha)
self.IconGlow:SetShown(r)
self.NewItemTexture:SetAtlas(quality and NEW_ITEM_ATLAS_BY_QUALITY[quality] or 'bags-glow-white')
self.NewItemTexture:SetShown(new and not paid)
self.JunkIcon:SetShown(Addon.sets.glowPoor and quality == LE_ITEM_QUALITY_POOR and not self.info.worthless)
self.BattlepayItemTexture:SetShown(new and paid)
self.QuestBorder:SetShown(questID)
self.IconOverlay:SetShown(overlay)
end
function Item:UpdateSlotColor()
local color = not self.info.id and Addon.sets.colorSlots and Addon.sets[self:GetSlotType() .. 'Color'] or {}
local r,g,b = color[1] or 1, color[2] or 1, color[3] or 1
SetItemButtonTextureVertexColor(self, r,g,b)
self:GetNormalTexture():SetVertexColor(r,g,b)
end
function Item:UpdateUpgradeIcon()
local isUpgrade = self:IsUpgrade()
if isUpgrade == nil then
self:Delay(0.5, 'UpdateUpgradeIcon')
else
self.UpgradeIcon:SetShown(isUpgrade)
end
end
function Item:SetLocked(locked)
SetItemButtonDesaturated(self, locked)
end
function Item:UpdateCooldown()
if self.info.id and (not self.info.cached) then
ContainerFrame_UpdateCooldown(self:GetBag(), self)
else
self.Cooldown:Hide()
CooldownFrame_Set(self.Cooldown, 0, 0, 0)
end
end
--[[ Searches ]]--
function Item:UpdateSearch()
local search = Addon.canSearch and Addon.search or ''
local matches = search == '' or Search:Matches(self.info.link, search)
self:SetAlpha(matches and 1 or 0.3)
self:SetLocked(not matches or self.info.locked)
end
function Item:UpdateFocus()
if self:GetBag() == self:GetFrame().focusedBag then
self:LockHighlight()
else
self:UnlockHighlight()
end
end
function Item:FlashFind(button)
if IsAltKeyDown() and button == 'LeftButton' and Addon.sets.flashFind and self.info.id then
self:SendSignal('FLASH_ITEM', self.info.id)
return true
end
end
function Item:OnItemFlashed(_, itemID)
self.Flash:Stop()
if self.info.id == itemID then
self.Flash:Play()
end
end
--[[ Tooltip ]]--
function Item:UpdateTooltip()
if self.info.link then
if self.info.cached then
self:ShowCachedTooltip()
else
self:ShowTooltip()
self:UpdateBorder()
end
else
self:OnLeave()
end
end
function Item:ShowTooltip()
local bag = self:GetBag()
local getSlot = Addon:IsBank(bag) and BankButtonIDToInvSlotID or
Addon:IsKeyring(bag) and KeyRingButtonIDToInvSlotID or
Addon:IsReagents(bag) and ReagentBankButtonIDToInvSlotID
if getSlot then
GameTooltip:SetOwner(self:GetTipAnchor())
local _, _, _, speciesID, level, breedQuality, maxHealth, power, speed, name = GameTooltip:SetInventoryItem('player', getSlot(self:GetID()))
if speciesID and speciesID > 0 then
BattlePetToolTip_Show(speciesID, level, breedQuality, maxHealth, power, speed, name)
else
if BattlePetTooltip then
BattlePetTooltip:Hide()
end
GameTooltip:Show()
end
CursorUpdate(self)
else
ContainerFrameItemButton_OnEnter(self)
end
end
function Item:ShowCachedTooltip()
Item.dummy = Item.dummy or Item:CreateDummy()
Item.dummy:SetParent(self)
Item.dummy:SetAllPoints()
Item.dummy:Show()
end
function Item:CreateDummy()
local function showTooltip(slot)
local parent = slot:GetParent()
local link = parent.info.link
if link then
GameTooltip:SetOwner(parent:GetTipAnchor())
parent:LockHighlight()
CursorUpdate(parent)
if link:find('battlepet:') then
local _, specie, level, quality, health, power, speed = strsplit(':', link)
local name = link:match('%[(.-)%]')
BattlePetToolTip_Show(tonumber(specie), level, tonumber(quality), health, power, speed, name)
else
GameTooltip:SetHyperlink(link)
GameTooltip:Show()
end
end
end
local slot = CreateFrame('Button')
slot.UpdateTooltip = showTooltip
slot:SetScript('OnEnter', showTooltip)
slot:SetScript('OnShow', showTooltip)
slot:RegisterForClicks('anyUp')
slot:SetToplevel(true)
slot:SetScript('OnClick', function(slot, button)
local parent = slot:GetParent()
if not HandleModifiedItemClick(parent.info.link) then
parent:FlashFind(button)
end
end)
slot:SetScript('OnLeave', function(slot)
slot:GetParent():UnlockHighlight()
slot:GetParent():OnLeave()
slot:Hide()
end)
return slot
end
--[[ Data ]]--
function Item:IsQuestItem()
if self.info.id then
if not self.info.cached and GetContainerItemQuestInfo then
local isQuest, questID, isActive = GetContainerItemQuestInfo(self:GetBag(), self:GetID())
return isQuest, (questID and not isActive)
else
return self.info.class == LE_ITEM_CLASS_QUESTITEM or Search:ForQuest(self.info.link)
end
end
end
function Item:IsUpgrade()
if IsContainerItemAnUpgrade then -- difference bettween nil and false
return IsContainerItemAnUpgrade(self:GetBag(), self:GetID())
end
end
function Item:IsNew()
return self:GetBag() and C_NewItems.IsNewItem(self:GetBag(), self:GetID())
end
function Item:IsPaid()
return IsBattlePayItem(self:GetBag(), self:GetID())
end
function Item:IsSlot(bag, slot)
return self:GetBag() == bag and self:GetID() == slot
end
function Item:GetInfo()
return self:GetFrame():GetItemInfo(self:GetBag(), self:GetID())
end
function Item:GetItem() -- for legacy purposes
return self.info.link
end
function Item:GetBag()
return self.bag
end
function Item:GetSlotType()
local bag = self:GetFrame():GetBagInfo(self:GetBag())
return self.SlotTypes[bag.family] or 'normal'
end
function Item:GetEmptyItemIcon()
return Addon.sets.emptySlots and 'Interface/PaperDoll/UI-Backpack-EmptySlot'
end
|
student_proto = {
[1] = { name = 70028, exp = 7129, atr1 = { {1, 100}, {2, 100}, {3, 100}, }, },
[2] = { name = 70029, exp = 14257, atr1 = { {1, 100}, {2, 100}, {3, 201}, }, },
[3] = { name = 70030, exp = 21386, atr1 = { {1, 100}, {2, 100}, {3, 302}, }, },
[4] = { name = 70031, exp = 28515, atr1 = { {1, 100}, {2, 100}, {3, 403}, }, },
[5] = { name = 70032, exp = 35644, challengeID = 1, atr1 = { {1, 100}, {2, 100}, {3, 504}, }, },
[6] = { name = 70033, exp = 42772, atr1 = { {1, 100}, {2, 100}, {3, 605}, }, },
[7] = { name = 70034, exp = 49901, atr1 = { {1, 100}, {2, 100}, {3, 706}, }, },
[8] = { name = 70035, exp = 57030, atr1 = { {1, 100}, {2, 100}, {3, 807}, }, },
[9] = { name = 70036, exp = 64158, atr1 = { {1, 100}, {2, 100}, {3, 908}, }, },
[10] = { name = 70037, exp = 71287, challengeID = 2, atr1 = { {1, 100}, {2, 100}, {3, 1009}, }, },
[11] = { name = 70038, exp = 78416, atr1 = { {1, 100}, {2, 100}, {3, 1110}, }, },
[12] = { name = 70039, exp = 85545, atr1 = { {1, 100}, {2, 100}, {3, 1211}, }, },
[13] = { name = 70040, exp = 92673, atr1 = { {1, 100}, {2, 100}, {3, 1312}, }, },
[14] = { name = 70041, exp = 99802, atr1 = { {1, 100}, {2, 100}, {3, 1413}, }, },
[15] = { name = 70042, exp = 106931, challengeID = 3, atr1 = { {1, 100}, {2, 100}, {3, 1514}, }, },
[16] = { name = 70043, exp = 114059, atr1 = { {1, 100}, {2, 100}, {3, 1615}, }, },
[17] = { name = 70044, exp = 121188, atr1 = { {1, 100}, {2, 100}, {3, 1716}, }, },
[18] = { name = 70045, exp = 128317, atr1 = { {1, 100}, {2, 100}, {3, 1817}, }, },
[19] = { name = 70046, exp = 135446, atr1 = { {1, 100}, {2, 100}, {3, 1918}, }, },
[20] = { name = 70047, exp = 142574, challengeID = 4, atr1 = { {1, 100}, {2, 100}, {3, 2019}, }, },
[21] = { name = 70048, exp = 149703, atr1 = { {1, 100}, {2, 100}, {3, 2120}, }, },
[22] = { name = 70049, exp = 156832, atr1 = { {1, 100}, {2, 100}, {3, 2221}, }, },
[23] = { name = 70050, exp = 163960, atr1 = { {1, 100}, {2, 100}, {3, 2322}, }, },
[24] = { name = 70051, exp = 171089, atr1 = { {1, 100}, {2, 100}, {3, 2423}, }, },
[25] = { name = 70052, exp = 178218, challengeID = 5, atr1 = { {1, 100}, {2, 100}, {3, 2524}, }, },
[26] = { name = 70053, exp = 185347, atr1 = { {1, 100}, {2, 100}, {3, 2625}, }, },
[27] = { name = 70054, exp = 192475, atr1 = { {1, 100}, {2, 100}, {3, 2726}, }, },
[28] = { name = 70055, exp = 199604, atr1 = { {1, 100}, {2, 100}, {3, 2827}, }, },
[29] = { name = 70056, exp = 206733, atr1 = { {1, 100}, {2, 100}, {3, 2928}, }, },
[30] = { name = 70057, exp = 213861, challengeID = 6, atr1 = { {1, 100}, {2, 100}, {3, 3029}, }, },
[31] = { name = 70058, exp = 220990, atr1 = { {1, 100}, {2, 100}, {3, 3130}, }, },
[32] = { name = 70059, exp = 228119, atr1 = { {1, 100}, {2, 100}, {3, 3231}, }, },
[33] = { name = 70060, exp = 235248, atr1 = { {1, 100}, {2, 100}, {3, 3332}, }, },
[34] = { name = 70061, exp = 242376, atr1 = { {1, 100}, {2, 100}, {3, 3433}, }, },
[35] = { name = 70062, exp = 249505, challengeID = 7, atr1 = { {1, 100}, {2, 100}, {3, 3534}, }, },
[36] = { name = 70063, exp = 256634, atr1 = { {1, 100}, {2, 100}, {3, 3635}, }, },
[37] = { name = 70064, exp = 263762, atr1 = { {1, 100}, {2, 100}, {3, 3736}, }, },
[38] = { name = 70065, exp = 270891, atr1 = { {1, 100}, {2, 100}, {3, 3837}, }, },
[39] = { name = 70066, exp = 278020, atr1 = { {1, 100}, {2, 100}, {3, 3938}, }, },
[40] = { name = 70067, exp = 285149, challengeID = 8, atr1 = { {1, 100}, {2, 100}, {3, 4039}, }, },
[41] = { name = 70068, exp = 292277, atr1 = { {1, 100}, {2, 100}, {3, 4140}, }, },
[42] = { name = 70069, exp = 299406, atr1 = { {1, 100}, {2, 100}, {3, 4241}, }, },
[43] = { name = 70070, exp = 306535, atr1 = { {1, 100}, {2, 100}, {3, 4342}, }, },
[44] = { name = 70071, exp = 313663, atr1 = { {1, 100}, {2, 100}, {3, 4443}, }, },
[45] = { name = 70072, exp = 320792, challengeID = 9, atr1 = { {1, 100}, {2, 100}, {3, 4544}, }, },
[46] = { name = 70073, exp = 327921, atr1 = { {1, 100}, {2, 100}, {3, 4645}, }, },
[47] = { name = 70074, exp = 335050, atr1 = { {1, 100}, {2, 100}, {3, 4746}, }, },
[48] = { name = 70075, exp = 342178, atr1 = { {1, 100}, {2, 100}, {3, 4847}, }, },
[49] = { name = 70076, exp = 349307, atr1 = { {1, 100}, {2, 100}, {3, 4948}, }, },
[50] = { name = 70077, exp = 356436, challengeID = 10, atr1 = { {1, 100}, {2, 100}, {3, 5049}, }, },
[51] = { name = 70078, exp = 363564, atr1 = { {1, 100}, {2, 100}, {3, 5150}, }, },
[52] = { name = 70079, exp = 370693, atr1 = { {1, 100}, {2, 100}, {3, 5251}, }, },
[53] = { name = 70080, exp = 377822, atr1 = { {1, 100}, {2, 100}, {3, 5352}, }, },
[54] = { name = 70081, exp = 384950, atr1 = { {1, 100}, {2, 100}, {3, 5453}, }, },
[55] = { name = 70082, exp = 392079, challengeID = 11, atr1 = { {1, 100}, {2, 100}, {3, 5554}, }, },
[56] = { name = 70083, exp = 399208, atr1 = { {1, 100}, {2, 100}, {3, 5655}, }, },
[57] = { name = 70084, exp = 406337, atr1 = { {1, 100}, {2, 100}, {3, 5756}, }, },
[58] = { name = 70085, exp = 413465, atr1 = { {1, 100}, {2, 100}, {3, 5857}, }, },
[59] = { name = 70086, exp = 420594, atr1 = { {1, 100}, {2, 100}, {3, 5958}, }, },
[60] = { name = 70087, exp = 427723, challengeID = 12, atr1 = { {1, 100}, {2, 100}, {3, 6059}, }, },
[61] = { name = 70088, exp = 434851, atr1 = { {1, 100}, {2, 100}, {3, 6160}, }, },
[62] = { name = 70089, exp = 441980, atr1 = { {1, 100}, {2, 100}, {3, 6261}, }, },
[63] = { name = 70090, exp = 449109, atr1 = { {1, 100}, {2, 100}, {3, 6362}, }, },
[64] = { name = 70091, exp = 456238, atr1 = { {1, 100}, {2, 100}, {3, 6463}, }, },
[65] = { name = 70092, exp = 463366, challengeID = 13, atr1 = { {1, 100}, {2, 100}, {3, 6564}, }, },
[66] = { name = 70093, exp = 470495, atr1 = { {1, 100}, {2, 100}, {3, 6665}, }, },
[67] = { name = 70094, exp = 477624, atr1 = { {1, 100}, {2, 100}, {3, 6766}, }, },
[68] = { name = 70095, exp = 484752, atr1 = { {1, 100}, {2, 100}, {3, 6867}, }, },
[69] = { name = 70096, exp = 491881, atr1 = { {1, 100}, {2, 100}, {3, 6968}, }, },
[70] = { name = 70097, exp = 499010, challengeID = 14, atr1 = { {1, 100}, {2, 100}, {3, 7069}, }, },
[71] = { name = 0, exp = 506139, },
[72] = { name = 0, exp = 513267, },
[73] = { name = 0, exp = 520396, },
[74] = { name = 0, exp = 527525, },
[75] = { name = 0, exp = 534653, },
[76] = { name = 0, exp = 541782, },
[77] = { name = 0, exp = 548911, },
[78] = { name = 0, exp = 556040, },
[79] = { name = 0, exp = 563168, },
[80] = { name = 0, exp = 570297, },
[81] = { name = 0, exp = 577426, },
[82] = { name = 0, exp = 584554, },
[83] = { name = 0, exp = 591683, },
[84] = { name = 0, exp = 598812, },
[85] = { name = 0, exp = 605941, },
[86] = { name = 0, exp = 613069, },
[87] = { name = 0, exp = 620198, },
[88] = { name = 0, exp = 627327, },
[89] = { name = 0, exp = 634455, },
[90] = { name = 0, exp = 641584, },
[91] = { name = 0, exp = 648713, },
[92] = { name = 0, exp = 655842, },
[93] = { name = 0, exp = 662970, },
[94] = { name = 0, exp = 670099, },
[95] = { name = 0, exp = 677228, },
[96] = { name = 0, exp = 684356, },
[97] = { name = 0, exp = 691485, },
[98] = { name = 0, exp = 698614, },
[99] = { name = 0, exp = 705743, },
[100] = { name = 0, exp = 712871, },
}
return student_proto
|
do
redslider = Slider.new(vec3d(0,0,0), 0, 255)
greenslider = Slider.new(vec3d(0,0,0), 0, 255)
blueslider = Slider.new(vec3d(0,0,0), 0, 255)
end
do
redslider.depth = 100
redslider.width = 10
greenslider.depth = 100
greenslider.width = 10
blueslider.depth = 100
blueslider.width = 10
redslider.lspace = transform.new()
transform.rotate(redslider.lspace, deg2rad(-90), 1,0,0)
transform.translate(redslider.lspace, 30,-50,0)
greenslider.lspace = transform.new()
transform.rotate(greenslider.lspace, deg2rad(-90), 1,0,0)
transform.translate(greenslider.lspace, 42,-50,0)
blueslider.lspace = transform.new()
transform.rotate(blueslider.lspace, deg2rad(-90), 1,0,0)
transform.translate(blueslider.lspace, 54,-50,0)
end
function showCWWithSliders()
colorwheelgrp.Widgets = {}
colorwheelgrp.Widgets[1] = colorwheelwidget
colorwheelgrp.Widgets[2] = redslider
colorwheelgrp.Widgets[3] = greenslider
colorwheelgrp.Widgets[4] = blueslider
end
function showCW()
colorwheelgrp.Widgets = {}
colorwheelgrp.Widgets[1] = colorwheelwidget
end
|
object_mobile_sher_kar = object_mobile_shared_sher_kar:new {
}
ObjectTemplates:addTemplate(object_mobile_sher_kar, "object/mobile/sher_kar.iff")
|
return function(ASS, ASSFInst, yutilsMissingMsg, createASSClass, re, util, unicode, Common, LineCollection, Line, Log, SubInspector, Yutils)
local DrawLine = createASSClass("Draw.Line", ASS.Draw.CommandBase, {"x", "y"}, {ASS.Number, ASS.Number},
{name="l", ords=2}, {ASS.Point, ASS.Draw.Move, ASS.Draw.MoveNc})
function DrawLine:ScaleToLength(len,noUpdate)
assert(Yutils, yutilsMissingMsg)
if not (self.length and self.cursor and noUpdate) then self.parent:getLength() end
self:sub(self.cursor)
self:set(self.cursor:copy():add(Yutils.math.stretch(self.x.value, self.y.value, 0, len)))
return self
end
function DrawLine:getAngle(ref, vectAngle, noUpdate)
if not ref then
if not (self.cursor and noUpdate) then self.parent:getLength() end
ref = self.cursor
end
return ASS.Point.getAngle(self, ref, vectAngle)
end
return DrawLine
end |
require("programs.none")
require("programs.enemy-detector")
require("programs.fluid-controller")
require("programs.ghost-alert-sensor")
require("programs.lua-executor")
require("programs.max-item-controller")
require("programs.storage-controller")
-- http://stackoverflow.com/questions/14942472/create-suite-of-interdependent-lua-files-without-affecting-the-global-namespace
local root = require "root"
local index = {}
local n = 0
for k, v in pairs(root) do
n = n + 1
index[n] = k
end
-- return the common table
return function() return root, index end -- return require "root" |
object_mobile_selonian_female_28 = object_mobile_shared_selonian_female_28:new {
}
ObjectTemplates:addTemplate(object_mobile_selonian_female_28, "object/mobile/selonian_female_28.iff")
|
local KUI, E, L, V, P, G = unpack(select(2, ...))
local KTT = KUI:GetModule("KuiTooltip")
local PI = KUI:GetModule("ProgressInfo")
local RI = KUI:GetModule("RealmInfo")
--Cache global variables
local format = string.format
local tinsert, twipe = table.insert, table.wipe
--WoW API / Variables
local function Tooltip()
E.Options.args.KlixUI.args.modules.args.tooltip = {
order = 29,
type = "group",
name = L["Tooltip"],
childGroups = "tab",
disabled = function() return not E.private.tooltip.enable end,
get = function(info) return E.db.KlixUI.tooltip[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip[ info[#info] ] = value; end,
args = {
header = {
order = 1,
type = "header",
name = KUI:cOption(L["Tooltip"]),
},
credits = {
order = 2,
type = "group",
name = L["Credits"],
guiInline = true,
args = {
tukui = {
order = 1,
type = "description",
fontSize = "medium",
name = format("|cffff8000ElvUI_Enhanced|r & |cff9482c9Shadow&Light - Darth Predator|r & TooltipRealmInfo (by Hizuro)"),
},
},
},
general = {
type = "group",
name = L["General"],
order = 3,
guiInline = true,
get = function(info) return E.db.KlixUI.tooltip[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip[ info[#info] ] = value; E:StaticPopup_Show("PRIVATE_RL"); end,
args = {
tooltip = {
order = 1,
type = "toggle",
name = L["Tooltip"],
desc = L["Change the visual appearance of the Tooltip.\nCredit: |cffff7d0aMerathilisUI|r"],
},
achievement = {
order = 2,
type = "toggle",
name = ACHIEVEMENT_BUTTON,
desc = L["Adds information to the tooltip, on which character you earned an achievement.\nCredit: |cffff7d0aMerathilisUI|r"],
},
keystone = {
order = 3,
type = "toggle",
name = L["Keystone"],
desc = L["Adds descriptions for mythic keystone properties to their tooltips."],
},
},
},
azerite = {
type = "group",
name = L["Azerite"],
order = 4,
disabled = function() return not E.private.tooltip.enable or IsAddOnLoaded("AzeriteTooltip") end,
hidden = function() return IsAddOnLoaded("AzeriteTooltip") end,
get = function(info) return E.db.KlixUI.tooltip.azerite[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip.azerite[ info[#info] ] = value end,
args = {
enable = {
order = 1,
type = "toggle",
name = L["Enable"],
desc = L["Enable/disable the azerite tooltip."],
set = function(info, value) E.db.KlixUI.tooltip.azerite[ info[#info] ] = value; E:StaticPopup_Show("PRIVATE_RL"); end,
},
space1 = {
order = 2,
type = "description",
name = "",
},
space2 = {
order = 3,
type = "description",
name = "",
},
RemoveBlizzard = {
order = 4,
type = "toggle",
name = L["Remove Blizzard"],
desc = L["Replaces the blizzard azerite tooltip text."],
disabled = function() return not E.db.KlixUI.tooltip.azerite.enable end,
},
OnlySpec = {
order = 5,
type = "toggle",
name = L["Specialization"],
desc = L["Only show the traits for your current specialization."],
disabled = function() return not E.db.KlixUI.tooltip.azerite.enable end,
},
Compact = {
order = 6,
type = "toggle",
name = L["Compact"],
desc = L["Only show icons in the azerite tooltip."],
disabled = function() return not E.db.KlixUI.tooltip.azerite.enable end,
},
},
},
progressInfo = {
type = "group",
name = L["Raid Progression"],
order = 5,
get = function(info) return E.db.KlixUI.tooltip.progressInfo[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip.progressInfo[ info[#info] ] = value end,
disabled = function() return not E.private.tooltip.enable end,
args = {
enable = {
order = 1,
type = 'toggle',
name = L["Enable"],
desc = L["Shows raid progress of a character in the tooltip.\n|cffff8000Note: Requires holding down the shift key.|r"],
},
NameStyle = {
order = 2,
name = L["Name Style"],
type = "select",
set = function(info, value) E.db.KlixUI.tooltip.progressInfo[ info[#info] ] = value; twipe(PI.Cache) end,
disabled = function() return not E.db.KlixUI.tooltip.progressInfo.enable end,
values = {
["LONG"] = L["Full"],
["SHORT"] = L["Short"],
},
},
DifStyle = {
order = 3,
name = L["Difficulty Style"],
type = "select",
set = function(info, value) E.db.KlixUI.tooltip.progressInfo[ info[#info] ] = value; twipe(PI.Cache) end,
disabled = function() return not E.db.KlixUI.tooltip.progressInfo.enable end,
values = {
["LONG"] = L["Full"],
["SHORT"] = L["Short"],
},
},
Raids = {
order = 4,
type = "group",
name = RAIDS,
guiInline = true,
get = function(info) return E.db.KlixUI.tooltip.progressInfo.raids[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip.progressInfo.raids[ info[#info] ] = value end,
disabled = function() return not E.db.KlixUI.tooltip.progressInfo.enable end,
args = {
uldir = { order = 1, type = "toggle", name = KUI:GetMapInfo(1148 , "name") },
},
},
},
},
realmInfo = {
type = "group",
name = L["Realm Info"]..E.NewSign,
order = 6,
get = function(info) return E.db.KlixUI.tooltip.realmInfo[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip.realmInfo[ info[#info] ] = value end,
disabled = function() return not E.private.tooltip.enable end,
args = {
enable = {
order = 1,
type = 'toggle',
name = L["Enable"],
desc = L["Shows realm info in various tooltips."],
},
tooltips = {
order = 2,
type = "group",
name = L["Tooltips"],
disabled = function() return not E.db.KlixUI.tooltip.realmInfo.enable end,
get = function(info) return E.db.KlixUI.tooltip.realmInfo[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip.realmInfo[ info[#info] ] = value end,
guiInline = true,
args = {
ttGrpFinder = {
order = 1,
type = "toggle",
name = LFGLIST_NAME,
desc = L["Show the realm info in the group finder tooltip."],
},
ttPlayer = {
order = 2,
type = "toggle",
name = L["Player Tooltips"],
desc = L["Show the realm info in the player tooltip."],
},
ttFriends = {
order = 3,
type = "toggle",
name = L["Friend List"],
desc = L["Show the realm info in the friend list tooltip."],
},
},
},
tooltipLines = {
order = 3,
type = "group",
name = L["Tooltip Lines"],
disabled = function() return not E.db.KlixUI.tooltip.realmInfo.enable end,
get = function(info) return E.db.KlixUI.tooltip.realmInfo[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip.realmInfo[ info[#info] ] = value end,
guiInline = true,
args = {
timezone = {
order = 2,
type = "toggle",
name = L["Realm Timezone"],
desc = L["Add realm timezone to the tooltip."],
},
type = {
order = 3,
type = "toggle",
name = L["Realm Type"],
desc = L["Add realm type to the tooltip."],
},
language = {
order = 4,
type = "toggle",
name = L["Realm Language"],
desc = L["Add realm language to the tooltip."],
},
connectedrealms = {
order = 5,
type = "toggle",
name = L["Connected Realms"],
desc = L["Add the connected realms to the tooltip."],
},
countryflag = {
order = 6,
type = "select",
width = "full",
name = L["Country Flag"],
desc = L["Display the country flag without text on the left side in tooltip."],
values = {
languageline = L["Behind language in 'Realm language' line"],
charactername = L["Behind the character name"],
ownline = L["In own tooltip line on the left site"],
none = ADDON_DISABLED
},
},
},
},
country_flags = {
order = 4,
type = "group",
name = L["Country Flag"],
guiInline = true,
disabled = function() return not E.db.KlixUI.tooltip.realmInfo.enable end,
get = function(info) return E.db.KlixUI.tooltip.realmInfo[ info[#info] ] end,
set = function(info, value) E.db.KlixUI.tooltip.realmInfo[ info[#info] ] = value end,
args = {
finder_counryflag = {
order = 1,
type = "toggle",
name = LFGLIST_NAME,
desc = L["Prepend country flag on character name in group finder."],
},
communities_countryflag = {
order = 2,
type = "toggle",
name = COMMUNITIES,
desc = L["Prepend country flag on character name in community member lists."],
},
},
},
},
},
},
}
end
tinsert(KUI.Config, Tooltip) |
--------------------------------------------------------------------------------
-- sohm(https://github.com/soveran/ohm)
--------------------------------------------------------------------------------
local _PACKAGE = string.gsub(...,"%.","/") or ""
local ohm = require(_PACKAGE.."/model")
local models = {}
local function model(name, scheme)
if not models[name] then
local _model = ohm.model(name, scheme)
models[name] = _model
end
return models[name]
end
return {
model = model
}
|
ITEM.name = "Consumables Permit"
ITEM.description = "A permit allowing you to sell consumable goods."
ITEM.permit = "consumables" |
require 'torch'
require 'nn'
require 'nnx'
require 'string'
_ = require 'moses'
require 'xlua'
require 'fs'
require 'os'
require 'sys'
require 'image'
require 'lfs'
ffi = require 'ffi'
------------------------------------------------------------------------
--[[ dp ]]--
-- deep learning library for torch7.
------------------------------------------------------------------------
dp = {}
dp.TORCH_DIR = os.getenv('TORCH_DATA_PATH') or os.getenv('HOME')
--[[ utils ]]--
torch.include('dp', 'utils/utils.lua')
torch.include('dp', 'utils/underscore.lua')
torch.include('dp', 'utils/os.lua')
torch.include('dp', 'utils/table.lua')
torch.include('dp', 'utils/torch.lua')
torch.include('dp', 'utils/threads.lua')
--[[ directory structure ]]--
dp.DATA_DIR = os.getenv('DEEP_DATA_PATH')
or paths.concat(dp.TORCH_DIR, 'data')
dp.check_and_mkdir(dp.DATA_DIR)
dp.SAVE_DIR = os.getenv('DEEP_SAVE_PATH')
or paths.concat(dp.TORCH_DIR, 'save')
dp.check_and_mkdir(dp.SAVE_DIR)
dp.LOG_DIR = os.getenv('DEEP_LOG_PATH')
or paths.concat(dp.TORCH_DIR, 'log')
dp.check_and_mkdir(dp.LOG_DIR)
dp.UNIT_DIR = os.getenv('DEEP_UNIT_PATH')
or paths.concat(dp.TORCH_DIR, 'unit')
dp.check_and_mkdir(dp.UNIT_DIR)
--[[ misc ]]--
torch.include('dp', 'choose.lua')
torch.include('dp', 'xplog.lua')
torch.include('dp', 'mediator.lua')
torch.include('dp', 'objectid.lua')
torch.include('dp', 'node.lua')
--[[ view ]]--
torch.include('dp', 'view/view.lua')
torch.include('dp', 'view/dataview.lua')
torch.include('dp', 'view/imageview.lua')
torch.include('dp', 'view/classview.lua')
torch.include('dp', 'view/sequenceview.lua')
torch.include('dp', 'view/listview.lua')
--[[ data ]]--
torch.include('dp', 'data/baseset.lua')
torch.include('dp', 'data/dataset.lua')
torch.include('dp', 'data/sentenceset.lua')
torch.include('dp', 'data/imageclassset.lua')
torch.include('dp', 'data/batch.lua')
torch.include('dp', 'data/carry.lua')
torch.include('dp', 'data/datasource.lua')
torch.include('dp', 'data/mnist.lua')
torch.include('dp', 'data/cifar10.lua')
torch.include('dp', 'data/cifar100.lua')
torch.include('dp', 'data/notmnist.lua')
torch.include('dp', 'data/facialkeypoints.lua')
torch.include('dp', 'data/billionwords.lua')
torch.include('dp', 'data/svhn.lua')
torch.include('dp', 'data/imagenet.lua')
torch.include('dp', 'data/imagesource.lua')
--[[ sampler ]]--
torch.include('dp', 'sampler/sampler.lua')
torch.include('dp', 'sampler/shufflesampler.lua')
torch.include('dp', 'sampler/sentencesampler.lua')
torch.include('dp', 'sampler/randomsampler.lua')
--[[ preprocess ]]--
torch.include('dp', 'preprocess/preprocess.lua')
torch.include('dp', 'preprocess/pipeline.lua')
torch.include('dp', 'preprocess/parallelpreprocess.lua')
torch.include('dp', 'preprocess/binarize.lua')
torch.include('dp', 'preprocess/standardize.lua')
torch.include('dp', 'preprocess/gcn.lua')
torch.include('dp', 'preprocess/zca.lua')
torch.include('dp', 'preprocess/lecunlcn.lua')
--[[ propagator ]]--
torch.include('dp', 'propagator/propagator.lua')
torch.include('dp', 'propagator/optimizer.lua')
torch.include('dp', 'propagator/evaluator.lua')
torch.include('dp', 'propagator/experiment.lua')
--[[ feedback ]]--
torch.include('dp', 'feedback/feedback.lua')
torch.include('dp', 'feedback/compositefeedback.lua')
torch.include('dp', 'feedback/confusion.lua')
torch.include('dp', 'feedback/perplexity.lua')
torch.include('dp', 'feedback/topcrop.lua')
torch.include('dp', 'feedback/fkdkaggle.lua')
torch.include('dp', 'feedback/facialkeypointfeedback.lua')
--torch.include('dp', 'feedback/criteria.lua')
--[[ visitor ]]--
torch.include('dp', 'visitor/visitor.lua')
torch.include('dp', 'visitor/visitorchain.lua')
torch.include('dp', 'visitor/recurrentvisitorchain.lua')
torch.include('dp', 'visitor/maxnorm.lua')
torch.include('dp', 'visitor/weightdecay.lua')
torch.include('dp', 'visitor/learn.lua')
torch.include('dp', 'visitor/momentum.lua')
torch.include('dp', 'visitor/gradclip.lua')
--[[ observer ]]--
torch.include('dp', 'observer/observer.lua')
torch.include('dp', 'observer/compositeobserver.lua')
torch.include('dp', 'observer/logger.lua')
torch.include('dp', 'observer/errorminima.lua')
torch.include('dp', 'observer/earlystopper.lua')
torch.include('dp', 'observer/savetofile.lua') --not an observer
torch.include('dp', 'observer/learningrateschedule.lua')
torch.include('dp', 'observer/adaptivelearningrate.lua')
torch.include('dp', 'observer/filelogger.lua')
--[[ nn ]]--
torch.include('dp', 'nn/Print.lua')
torch.include('dp', 'nn/PrintSize.lua')
torch.include('dp', 'nn/FairLookupTable.lua')
--[[ model ]]--
torch.include('dp', 'model/model.lua')
torch.include('dp', 'model/container.lua')
torch.include('dp', 'model/sequential.lua')
torch.include('dp', 'model/layer.lua')
torch.include('dp', 'model/neural.lua')
torch.include('dp', 'model/module.lua')
torch.include('dp', 'model/dictionary.lua')
torch.include('dp', 'model/narrowdictionary.lua')
torch.include('dp', 'model/recurrentdictionary.lua')
torch.include('dp', 'model/softmaxtree.lua')
torch.include('dp', 'model/softmaxforest.lua')
torch.include('dp', 'model/mixtureofexperts.lua')
torch.include('dp', 'model/blocksparse.lua')
torch.include('dp', 'model/convolution1D.lua')
torch.include('dp', 'model/convolution2D.lua')
torch.include('dp', 'model/inception.lua')
--[[ loss ]]--
torch.include('dp', 'loss/loss.lua')
torch.include('dp', 'loss/nll.lua')
torch.include('dp', 'loss/kldivergence.lua')
torch.include('dp', 'loss/treenll.lua')
torch.include('dp', 'loss/null.lua')
torch.include('dp', 'loss/criterion.lua')
--[[ hyper ]]--
torch.include('dp', 'hyper/hyperoptimizer.lua')
torch.include('dp', 'hyper/hyperparamsampler.lua')
torch.include('dp', 'hyper/datasourcefactory.lua')
torch.include('dp', 'hyper/experimentfactory.lua')
torch.include('dp', 'hyper/priorsampler.lua')
torch.include('dp', 'hyper/imageclassfactory.lua')
torch.include('dp', 'hyper/mlpfactory.lua')
torch.include('dp', 'hyper/contextwordfactory.lua')
torch.include('dp', 'hyper/lmfactory.lua')
--[[ postgres ]]--
torch.include('dp', 'postgres/postgres.lua')
torch.include('dp', 'postgres/logger.lua')
torch.include('dp', 'postgres/xplog.lua')
torch.include('dp', 'postgres/savetofile.lua')
torch.include('dp', 'postgres/earlystopper.lua')
torch.include('dp', 'postgres/done.lua')
torch.include('dp', 'postgres/mlpfactory.lua')
torch.include('dp', 'postgres/lmfactory.lua')
torch.include('dp', 'postgres/hyperoptimizer.lua')
--[[ test ]]--
torch.include('dp', 'test/test.lua')
torch.include('dp', 'test/test-cuda.lua')
torch.include('dp', 'test/test-datasets.lua')
return dp
|
print ("Results of read_xml_test:")
require "com.untgames.runtime"
local function CreateClassA ()
local function Foo ()
print ("ClassA.Foo")
end
local function SetProperty (name, value)
print (string.format ("SetProperty('%s', '%s')", name, value))
end
local function GetProperty (name)
print (string.format ("GetProperty('%s')", name))
end
local function Create ()
local function Baz ()
print ("ClassA.Baz")
end
return class { Baz = Baz }
end
return class "ClassA"
{
Foo = Foo,
set_A = Runtime.Attribute.String (SetProperty),
get_A = Runtime.Attribute.String (GetProperty),
Create = constructor (Create)
}
end
ClassA = CreateClassA ()
local instance = Runtime.Serialize.FromXml ("data/test.xml")
|
local included = pcall(debug.getlocal, 4, 1)
local T = require("test")
--# = os
--# :toc:
--# :toc-placement!:
--#
--# Extensions to the `os` namespace.
--#
--# toc::[]
--#
--# == *os.hostname*() -> _String_
--# Get current hostname.
--#
--# === Returns
--# [width="72%"]
--# |===
--# |string |Hostname
--# |===
local os_hostname = function()
T.is_function(os.hostname)
T.is_string(os.hostname())
end
--#
--# == *os.outbound_ip*() -> _String_
--# Get IP used for outbound connections.
--#
--# === Returns
--# [width="72%"]
--# |===
--# |string |IP
--# |===
local os_outbound_ip = function()
T.is_function(os.outbound_ip)
T.is_string(os.outbound_ip())
end
--#
--# == *os.sleep(_Number_) -> _Boolean_
--# Sleep for a number of milliseconds.
--#
--# === Arguments
--# [width="72%"]
--# |===
--# |number |Milliseconds
--# |===
--#
--# === Returns
--# [width="72%"]
--# |===
--# |boolean |`true`
--# |===
local os_sleep = function()
T.is_function(os.sleep)
T.is_true(os.sleep(500))
end
--#
--# == *os.setenv*(_String_, _String_) -> _Boolean_
--# Set environment variable.
--#
--# === Arguments
--# [width="72%"]
--# |===
--# |string |Variable
--# |string |Value
--# |===
--#
--# === Returns
--# [width="72%"]
--# |===
--# |boolean |`true` if successful
--# |===
local os_setenv = function()
T.is_function(os.setenv)
T.is_true(os.setenv("TESTLADYLUAOSSETENV", "1"))
local e = os.getenv("TESTLADYLUAOSSETENV")
T.equal(e, "1")
end
if included then
return function()
T["os.hostname"] = os_hostname
T["os.outbound_ip"] = os_outbound_ip
T["os.sleep"] = os_sleep
T["os.setenv"] = os_setenv
end
else
T["os.hostname"] = os_hostname
T["os.outbound_ip"] = os_outbound_ip
T["os.sleep"] = os_sleep
T["os.setenv"] = os_setenv
end
|
local client = require 'shared.client'
local describe, it, assert = describe, it, assert
describe('membership.views', function()
local go, path_for = client.new()
local signin = function(credentials)
if not credentials then
credentials = {username = 'demo', password = 'password'}
end
local w = go {
method = 'POST',
path = path_for('signin'),
body = credentials
}
local c = w.headers['Set-Cookie']
if not c then
return nil, w
end
return c:match('^(_a=.-);'), w
end
describe('signin', function()
local path = path_for('signin')
it('validates user credentials', function()
local w = go {method = 'POST', path = path}
assert.equals(400, w.status_code)
local errors = w.data
assert(errors.username)
assert(errors.password)
end)
it('responds with error if user is not found', function()
local auth_cookie, w = signin {
username = 'unknown', password = 'password'
}
assert.is_nil(auth_cookie)
assert.equals(400, w.status_code)
local errors = w.data
assert(errors.__ERROR__)
end)
it('issues auth cookie', function()
local auth_cookie, w = signin()
assert(auth_cookie)
local u = w.data
assert.equals('demo', u.username)
end)
end)
describe('signup', function()
local path = path_for('signup')
it('validates registration information', function()
local w = go {method = 'POST', path = path}
assert.equals(400, w.status_code)
local errors = w.data
assert(errors.email)
end)
it('checks if username is taken already', function()
local w = go {
method = 'POST',
path = path,
body = {username = 'demo', email = 'demo@somewhere.com'}
}
assert.equals(400, w.status_code)
local errors = w.data
assert(errors.username)
end)
end)
describe('signout', function()
local path = path_for('signout')
it('removes auth cookie', function()
local auth_cookie = signin()
local w = go {path = path, headers = {cookie = auth_cookie}}
assert.equals(
'_a=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/',
w.headers['Set-Cookie'])
end)
end)
describe('user', function()
local path = path_for('user')
it('responds with unauthorized status code', function()
local w = go {path = path}
assert.equals(401, w.status_code)
end)
it('confirms user is authenticated', function()
local auth_cookie = signin()
local w = go {path = path, headers = {cookie = auth_cookie}}
local u = w.data
assert.equals('demo', u.username)
end)
end)
end)
|
--***********************************************************
--** THE INDIE STONE **
--***********************************************************
require "TimedActions/ISBaseTimedAction"
---@class ISFireplaceAddFuel : ISBaseTimedAction
ISFireplaceAddFuel = ISBaseTimedAction:derive("ISFireplaceAddFuel");
function ISFireplaceAddFuel:isValid()
return self.fireplace:getObjectIndex() ~= -1 and
self.character:getInventory():contains(self.item)
end
function ISFireplaceAddFuel:waitToStart()
self.character:faceThisObject(self.fireplace)
return self.character:shouldBeTurning()
end
function ISFireplaceAddFuel:update()
self.character:faceThisObject(self.fireplace)
self.item:setJobDelta(self:getJobDelta());
self.character:setMetabolicTarget(Metabolics.HeavyDomestic);
end
function ISFireplaceAddFuel:start()
self.item:setJobType(campingText.addFuel);
self.item:setJobDelta(0.0);
self:setActionAnim("Loot")
self.character:SetVariable("LootPosition", "Low")
end
function ISFireplaceAddFuel:stop()
ISBaseTimedAction.stop(self);
self.item:setJobDelta(0.0);
end
function ISFireplaceAddFuel:perform()
self.item:setJobDelta(0.0);
if self.item:IsDrainable() then
self.item:Use()
else
self.character:removeFromHands(self.item)
self.character:getInventory():Remove(self.item)
end
local fp = self.fireplace
local args = { x = fp:getX(), y = fp:getY(), z = fp:getZ(), fuelAmt = self.fuelAmt }
sendClientCommand(self.character, 'fireplace', 'addFuel', args)
-- needed to remove from queue / start next.
ISBaseTimedAction.perform(self);
end
function ISFireplaceAddFuel:new(character, fireplace, item, fuelAmt, time)
local o = {}
setmetatable(o, self)
self.__index = self
o.character = character;
o.stopOnWalk = true;
o.stopOnRun = true;
o.maxTime = time;
if o.character:isTimedActionInstant() then o.maxTime = 1; end
-- custom fields
o.fireplace = fireplace
o.fuelAmt = fuelAmt
o.item = item;
return o;
end
|
-- luci/openwrt multi user implementation V1 --
-- users.lua by Hostle 12/12/2014 --
module("luci.users", package.seeall)
--## General dependents ##--
require "luci.sys"
--## Add/Remove User files and dependants ##--
local fs = require "nixio.fs"
local passwd = "/etc/passwd"
local passwd2 = "/etc/passwd-"
local shadow = "/etc/shadow"
local shadow2 = "/etc/shadow-"
local groupy = "/etc/group"
local users_file = "/etc/config/users"
local homedir
--## global User buffers ##--
local ui_users = {}
local ui_usernames = {}
local sys_usernames = {}
local valid_users = {}
--## debugging ##--
local debug = 0
local logfile = "/tmp/users.log"
--## users model boiler plate ##--
users = {}
users.prototype = { name = "new user", user_group = "default", shell = "none", menu_items = "none" }
users.metatable = { __index = users.prototype }
function users:new(user)
setmetatable(users, users.metatable)
return user
end
--## login function to provide valid usernames, used by dispatcher,index and serviceclt ##--
function login()
local users = assert(io.open("/etc/passwd", "r"))
local i = 1
for line in users:lines() do
if line and line ~= "" then
line = line:sub(1, line:find(":")-1)
if line ~= "daemon" and line ~= "network" and line ~= "nobody" then
valid_users[i] = line
i = i + 1
end
end
end
users:close()
return valid_users
end
--########################################### File parsing fuctions ########################################--
--## load user tmp buffer (tbuf) into ui_usernames buffer ##--
function process_ui_user(tbuf)
local nbuf = {}
local user = users:new()
local line = ""
local menu_items = ""
for k,v in pairs(tbuf) do
if v:find("option name") then
name = v:sub(v:find("option")+13, -2)
nbuf["name"]= name
end
if v:find("user_group") then
user_group = v:sub(v:find("option")+19,-2)
nbuf["user_group"]=user_group
end
if v:find("shell") then
shell = v:sub(v:find("option")+14,-2)
nbuf["shell"]=shell
end
if v:find("status_menu") then
status_menu = v:sub(v:find("option")+20,-2)
nbuf["status_menu"]=status_menu
end
if v:find("system_menu") then
system_menu = v:sub(v:find("option")+20,-2)
nbuf["system_menu"]=system_menu
end
if v:find("network_menu") then
network_menu = v:sub(v:find("option")+21,-2)
nbuf["network_menu"]=network_menu
end
if v:find("status_subs") then
status_subs = v:sub(v:find("option")+20,-2)
nbuf["status_subs"]=status_subs
end
if v:find("system_subs") then
system_subs = v:sub(v:find("option")+20,-2)
nbuf["system_subs"]=system_subs
end
if v:find("network_subs") then
network_subs = v:sub(v:find("option")+21,-2)
nbuf["network_subs"]=network_subs
end
end
if nbuf.status_menu and nbuf.status_menu ~= "nil" then
menu_items = menu_items .. " " .. nbuf.status_menu
end
if nbuf.system_menu and nbuf.system_menu ~= "nil" then
menu_items = menu_items .. " " .. nbuf.system_menu
end
if nbuf.network_menu and nbuf.network_menu ~= "nil" then
menu_items = menu_items .. " " .. nbuf.network_menu
end
if nbuf.network_subs then
menu_items = menu_items .. " " .. nbuf.network_subs
end
if nbuf.system_subs then
menu_items = menu_items .. " " .. nbuf.system_subs
end
if nbuf.status_subs then
menu_items = menu_items .. " " .. nbuf.status_subs
end
nbuf.menu_items = menu_items:sub(2,-1)
user = users:new({ name = nbuf.name, user_group = nbuf.user_group, shell = nbuf.shell,
menu_items = nbuf.menu_items })
ui_users[user.name] = { user_group = nbuf.user_group, shell = nbuf.shell,
menu_items = nbuf.menu_items } --## add user and info to ui_users buffer
ui_usernames[#ui_usernames+1]=user.name --## keep track of ui_usernames
end
--## seperate users from "/etc/config/users" file and add to temp buffer (tbuf) ##--
function load_ui_user_file()
local file = io.open(users_file, "r")
local buf = {}
local buft = {}
local i = 1
for line in file:lines() do
if line ~= nil then
buf[i]=line
i = i + 1
end
end
file:close()
for i=1, #buf do
if buf[i]:find("config user") then
j = 1
repeat
buft[j]= buf[i+j]
j = j + 1
until buf[j] == ""
process_ui_user(buft) --## send user to be added to ui_users
end
end
end
--## function to load users from "/etc/passwd" file into sys_usernames buffer ##--
function load_sys_user_file()
local file = assert(io.open(passwd, "r"))
local line = ""
local i = 1
for line in file:lines() do
if line and line ~= "" then
line = line:sub(1, line:find(":")-1)
if line ~= "root" and line ~= "daemon" and line ~= "network" and line ~= "nobody" and line ~= "ftp" then
sys_usernames[i] = line
i = i + 1
end
end
end
file:close()
end
--## function to find new users and add them to the system (checks if shell has changed too) ##--
function add_users()
local x = 1
repeat
for i,v in pairs(ui_usernames) do
tmp_name = v
for j,k in pairs(sys_usernames) do
if tmp_name == k then is_user = true end
end
if is_user then
if ui_users[tmp_name].shell == "1" then
check_shell(tmp_name,true)
else
check_shell(tmp_name,false)
end
end
if not is_user then
create_user(tmp_name,ui_users[tmp_name].shell,ui_users[tmp_name].user_group)
end
is_user = false
x = x + 1
end
until x > #ui_usernames
end
--## function to find deleted users and remove them from the system ##--
function del_users()
local tmp_name
local x = 1
repeat
for i,v in pairs(sys_usernames) do
tmp_name = v
for j,k in pairs(ui_usernames) do
if tmp_name == k then
is_user = true
end
end
if not is_user then
remove_user(tmp_name)
end
is_user = false
x = x + 1
end
until x > #sys_usernames
end
--## function to add user to system ##--
function create_user(user,shell,group)
if shell == '1' then
shell = "/bin/ash"
else
shell = "/bin/false"
end
check_user(user, group, shell)
setpasswd(user)
end
--## function to remove user from system ##--
function remove_user(user)
delete_user(user)
end
--## function to check if user gets ssh access (shell or not) ##--
function check_shell(user,has_shell)
local file = assert(io.open(passwd, "r"))
local line = ""
local shell
local i = 1
local buf = {}
for line in file:lines() do
if line and line ~= "" then
buf[i]=line
if line:find(user) then
shell = line:sub(line:find(":/bin/")+1,-1)
end
i = i + 1
end
end
file:close()
if has_shell and shell ~= "/bin/ash" then
for i = 1, #buf do
if buf[i]:find(user) then
buf[i]=buf[i]:gsub("/bin/false", "/bin/ash")
end
end
elseif not has_shell and shell ~= "/bin/false" then
for i = 1, #buf do
if buf[i]:find(user) then
buf[i]=buf[i]:gsub("/bin/ash", "/bin/false")
end
end
end
file = assert(io.open(passwd, "w+"))
for k,v in pairs(buf) do
file:write(v.."\n")
end
file:close()
end
--## function used by dispatcher to remove specified menus from index tree ##--
--## Called by disatcher to determine what menus should be visible ##--
function hide_menus(user,menus)
if user == nil then return end
local x = 1
load_ui_user_file()
local h_menus = ui_users[user].menu_items
for token in string.gmatch(h_menus, "[^%s]+") do
menus[x]=token
x = x + 1
end
return(menus)
end
--## function to set default password for new users ##--
--## duplicate of luci set password only a default password is set(openwrt)
function setpasswd(username,password)
if not password then password = "openwrt" end
password = password:gsub("'", [['"'"']])
if username then
username = username:gsub("'", [['"'"']])
end
return os.execute(
"(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " ..
"passwd '" .. username .. "' >/dev/null 2>&1"
)
end
--####################################### Ulitlity functions ###############################################--
--## function to check if user exists ##--
function checkit(val, file)
if not file then file = io.open(passwd, "r")
for line in file:lines() do
if line:find(val) then file:close() return false end
end
end
return true
end
--## function to check if file exists ##--
--## can be replaced with nixio file access ##--
local function exists(name)
if type(name)~="string" then return false end
return os.rename(name,name) and true or false
end
--## function to check if path is a file ##--
local function isFile(name)
if type(name)~="string" then return false end
if not exists(name) then return false end
local f = io.open(name)
if f then
f:close()
return true
end
return false
end
--## function to check if path is a directory ##--
local function isDir(name)
return (exists(name) and not isFile(name))
end
--## function to get next available uid ##--
function get_uid(group)
local file = assert(io.open(passwd, "r"))
local t = {}
local i = 1
local pat_uid
if group == "admin" then
pat_uid = ":1%d%d%d:1%d%d%d:"
elseif group == "user" then
pat_uid = ":2%d%d%d:2%d%d%d:"
else
if(debug > 0) then print("Error { User Group Doesn't Exists !! }") end
fs.writefile("/tmp/multi.stderr", "Error { User Group Doesn't Exists !! }")
end
for line in file:lines() do
if line:match(pat_uid) then
line = line:match(pat_uid)
uid = line:sub(2,5)
t[i] = uid
i = i + 1
end
end
file:close()
if #t < 1 then
if group == "admin" then t[1]=1000 else t[1]=2000 end
end
table.sort(t)
uid = t[#t] + 1 or 0
return uid
end
--############################################### Add User Functions ######################################--
--## functio to prepare users home dir ##--
function create_homedir(name)
local home = "/home/"
local homedir = home .. name
return homedir
end
--## function add user to passwds ##--
function add_passwd(name,uid,shell,homdir)
local file = assert(io.open(passwd, "a"))
local nuser = "\n"..name..":x:"..uid..":"..uid..":"..name..":"..homedir..":"..shell
local nuser2 = "\n"..name..":*:"..uid..":"..uid..":"..name..":"..homedir..":"..shell
if checkit(name, file) then
file:write(nuser)
file:close()
file = assert(io.open(passwd2, "a"))
file:write(nuser2)
file:close()
else
if(debug > 0) then print("Error { User Already Exists !! }") end
fs.writefile("/tmp/multi.stderr", "Error { User Already Exist !! }")
return 1
end
end
--## function add user to shadows ##--
function add_shadow(name)
local file = assert(io.open(shadow, "a"))
local shad = "\n"..name..":*:11647:0:99999:7:::"
if checkit(name, file) then
file:write(shad)
file:close()
file = assert(io.open(shadow2, "a"))
file:write(shad)
file:close()
else
if(debug > 0) then print("Error { User Already Exists !! }") end
fs.writefile("/tmp/multi.stderr", "Error { User Already Exists !! }")
return 1
end
end
--## function to add user to group ##--
function add_group(name,uid)
local grp = "\n"..name..":x:"..uid..":"..name
local file = assert(io.open(groupy, "a"))
if checkit(name, file) then
file:write(grp)
file:close()
else
if(debug > 0) then print("Error { User Already Exists !! }") end
fs.writefile("/tmp/multi.stderr", "Error { User Already Exists !! }")
return 1
end
end
--## make the users home directory and set permissions to (755) ##--
function make_home_dirs(homedir)
local home = "/home"
if not isDir(home) then
fs.mkdir(home, 755)
end
if not isDir(homedir) then
fs.mkdir(homedir, 755)
end
local cmd = "find "..homedir.." -print | xargs chown "..name..":"..name
os.execute(cmd)
end
--## function to check if user is valid ##--
function check_user(name, group, shell)
if not checkit(name) then
if(debug > 0) then print("Error { User Already Exists !! }") end
fs.writefile("/tmp/multi.stderr", "Error { User Already Exists !! }")
return 1
elseif not name and pass and uid and shell then
if(debug > 0) then print("Error { Not Enough Parameters !! }") end
fs.writefile("/tmp/multi.stderr", "Error { Not Enough Parameters !! }")
return 1
else
add_user(name, group, shell)
end
end
--## function to add user to the system ##--
function add_user(name, group, shell)
local uid = get_uid(group)
homedir = create_homedir(name)
add_passwd(name,uid,shell,homedir)
add_shadow(name)
add_group(name,uid)
make_home_dirs(homedir)
end
--################################### Remove User functions ###########################################--
--## function load file into buffer ##--
function load_file(name, buf)
local i = 1
local file = io.open(name, "r")
for line in file:lines() do
buf[i] = line
if debug > 0 then print(buf[i]) end
i = i + 1
end
file:close()
return(buf)
end
--## function to remove user from buffer ##--
function rem_user(user, buf)
for i,v in pairs(buf) do
if v:find(user) then
table.remove(buf,i)
end
end
return(buf)
end
--## function to write buffer back to file ##--
function write_file(name, buf)
local file = io.open(name, "w")
for i,v in pairs(buf) do
if debug > 0 then print(v) end
if(i < #buf) then
file:write(v.."\n")
else
file:write(v)
end
end
file:close()
end
--## function remove user from the system ##--
function delete_user(user)
local buf = { ["passwd"] = {}, ["shadow"] = {}, ["group"] = {} }
--## load files into indexed buffers ##--
load_file(passwd, buf.passwd)
load_file(shadow, buf.shadow)
load_file(groupy, buf.group)
--## remove user from buffers ##--
rem_user(user, buf.passwd)
rem_user(user, buf.shadow)
rem_user(user, buf.group)
--## write edited buffers back to the files ##--
write_file(passwd, buf.passwd)
write_file(passwd2, buf.passwd)
write_file(shadow, buf.shadow)
write_file(shadow2, buf.shadow)
write_file(groupy, buf.group)
luci.sys.call("rm /home/"..user.."/*")
fs.rmdir("/home/"..user)
end
|
module("luci.controller.pppoe-relay", package.seeall)
function index()
if not nixio.fs.access("/etc/config/pppoe-relay") then
return
end
entry({"admin", "services", "pppoe-relay"}, cbi("pppoe-relay"), _("PPPoE Relay"), 90).dependent = true
end
|
--- An input stream that reads from a file.
--
-- @module FileInputStream
-- @author sci4me
-- @license MIT
-- @copyright Scitoshi Nakayobro 2021
local class = require "middleclass"
local InputStream = require "iostream.InputStream"
local byte = string.byte
local FileInputStream = class("FileInputStream", InputStream)
function FileInputStream:initialize(path)
self.fh = io.open(path, "rb")
if not self.fh then error("file not found: " .. tostring(path)) end
end
function FileInputStream:readU8()
local x = self.fh:read(1)
if x == nil then return x end
return byte(x)
end
function FileInputStream:close()
self.fh:close()
end
return FileInputStream |
--This file adds crafting recipes depending on which dependencies are installed
if minetest.get_modpath("default") and
minetest.get_modpath("bucket")
then
minetest.register_craft(
{
output = "hot_air_balloons:item",
recipe =
{
{"default:paper", "default:paper", "default:paper"},
{"default:paper", "bucket:bucket_lava", "default:paper"},
{"", "group:wood", "" },
},
})
return
end
if minetest.get_modpath("mcl_buckets") and
minetest.get_modpath("mcl_mobitems") and
minetest.get_modpath("mcl_core")
then
minetest.register_craft(
{
output = "hot_air_balloons:item",
recipe =
{
{"mcl_mobitems:leather", "mcl_mobitems:leather", "mcl_mobitems:leather"},
{"mcl_mobitems:leather", "bucket:bucket_lava", "mcl_mobitems:leather"},
{"mcl_mobitems:string", "group:wood", "mcl_mobitems:string" },
},
})
return
end
--[[
minetest.register_craft(
{
type = "aircraft"
}
]]
--make balloon work with mcl2 creative mode
--announce in chat if no crafting recipe was added.
minetest.after(2,
function()
minetest.chat_send_all("Optional dependencies for hot_air_balloons are missing so no crafting recipe was added.\n"..
"Install either 'default' and 'bucket' or 'mcl_core', 'mcl_mobitems' 'and mcl_buckets' if this bothers you.\n"..
"All other functions of the mod should be unaffected by this.")
end)
|
Common_UnitConsumeActPoint(attacker, 1);
if Common_Break_Skill(attacker, _Skill) then return end
Common_ChangeEp(attacker, -_Skill.skill_consume_ep)
local target, all_targets = Common_GetTargets(...)
Common_ShowCfgFlagEffect(_Skill)
Common_UnitPlayAttack(attacker, _Skill.id);
Common_ShowCfgStageEffect(_Skill)
-----------------------星级对应属性
local value = 4400
local star_list = {
[1] = 0.15,
[2] = 0.21,
[3] = 0.28,
[4] = 0.36,
}
local star_promote = 0
for i = 1, attacker[40001],1 do
star_promote = star_promote + star_list[i]
end
value = value * (1 + star_promote)
--------------------------
local round = 3
local hp_per = 0.22
local pro_per = value/10000
local pet = Common_SummonPet(attacker, 1100040, 1, round, pro_per, hp_per)
local cfg = GetSkillEffectCfg(_Skill.id)
if cfg.stage_effect_1 == "0" or cfg.stage_effect_1 == 0 or cfg.stage_effect_2 == "0" or cfg.stage_effect_2 == 0 then
Common_AddStageEffect(30041, 1, 2, attacker, pet.mode)
Common_Sleep(nil, 1.2)
end
Common_Sleep(attacker, 0.3)
|
--[[
cel is licensed under the terms of the MIT license
Copyright (C) 2011 by Matthew W. Burk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--]]
local cel = require 'cel'
local metacel, metatable = cel.slot.newmetacel('document')
metacel['.text'] = cel.text.newmetacel('document.text')
metacel['.divider'] = cel.newmetacel('document.divider')
metacel['.section'] = cel.slot.newmetacel('document.section')
metacel['.hyperlink'] = cel.textbutton.newmetacel('document.hyperlink')
local _font = {}
local _host = {}
local _facestack = {}
local _hoststack = {}
local _stack = {}
local _col = {}
local _facename = {} --TODO lame hack to use this, do another way
local _filename = {} --the name of the document
local function parseunit(s)
if not s then
return 0, 'px'
end
if type(s) == 'number' then
return s, 'px'
end
local n, unit = s:match('(.+)(..)$')
if 'px' == unit then
return tonumber(n), unit
elseif 'pt' == unit then
return tonumber(n), unit
elseif 'em' == unit then
return tonumber(n), unit
else
return tonumber(s), 'px'
end
end
local function newtext(text, wrapmode, face)
return metacel['.text']:new(text, wrapmode, face)
--return cel.label.new(text)
end
local function getcurrentface(document)
local facestack = document[_facestack]
return facestack[#facestack]
end
local function getface(document)
return getcurrentface(document)
end
local function getfont(document)
return cel.getface('document.text', face).font
end
local function getpxvalue(document, value, unit)
if unit == 'px' then
return value
elseif unit == 'em' then
assert(getface(document))
return value * getface(document).font:measure('m')
elseif unit == 'pt' then
return value --TODO do conversion
end
end
function metatable.pushface(document, face)
face = cel.getface('document.text', face)
assert(face)
local facestack = document[_facestack]
facestack[#facestack + 1] = face
return document
end
function metatable.popface(document)
local facestack = document[_facestack]
facestack[#facestack] = nil
return document
end
--TODO this must go into the document.text cel
function metatable.append(document, acel)
end
--TODO this must go into the document.text cel
function metatable.appendtext(document, s)
end
local function pushhost(document, host)
if not document[_hoststack] then
document[_hoststack] = {document[_host]}
else
local stack = document[_hoststack]
stack[#stack + 1] = document[_host]
end
document[_host] = host
end
local function pophost(document)
local old = document[_host]
local stack = document[_hoststack]
document[_host] = stack[#stack]
stack[#stack] = nil
return old
end
local function push(document, acel, linker, xval, yval)
print('option', document[_host].option and document[_host].option.flex)
if not acel then
acel = cel.col.new()
acel:link(document[_host], linker, xval, yval, document[_host].option)
--acel:beginflux()
else
acel:link(document[_host], linker, xval, yval, document[_host].option)
end
pushhost(document, acel)
return document
end
local function pop(document, n)
n = n or 1
for i = 1, n do
local old = pophost(document)
--if old.endflux then old:endflux() end
end
return document
end
do --metatable.pushsection
local metacel = metacel['.section']
function metatable.pushsection(document, t)
local m = getpxvalue(document, parseunit(t.margin))
local left = getpxvalue(document, parseunit(t.leftmargin or m))
local right = getpxvalue(document, parseunit(t.rightmargin or left))
local top = getpxvalue(document, parseunit(t.topmargin or m))
local bottom = getpxvalue(document, parseunit(t.bottommargin or top))
local face = t.face
local link = t.link
local w = parseunit(t.w)
local h = parseunit(t.h)
local section = metacel:new(left, top, right, bottom, nil, nil, face)
print('pushing section')
push(document, section, link or 'fill')
print('pushed section')
push(document, nil, 'fill')
section:resize(w, h)
return document
end
function metatable.popsection(document)
return pop(document, 2)
end
end
do
local metacel = metacel['.divider']
function metatable.putdivider(document, face)
return document:put(metacel:new(1, 1, face), 'width')
end
end
do
local option = {flex=1, minw=0}
local newrow = cel.row.new
function metatable.pushrow(document, face, linker, xval, yval)
local row = newrow(nil, face)
--row:beginflux()
row.option = option
linker = linker or 'fill'
return push(document, row, 'fill.margin', xval, yval)
end
function metatable.poprow(document)
return pop(document)
end
end
function metatable.newline(document)
local font = getfont(document)
return document:put(cel.new(font:height(), font:height()))
end
--format 'nowrap'
function metatable.write(document, s, mode)
if 'nowrap' == mode then
local text = newtext(s, mode, getface(document))
text:link(document[_host], nil, nil, nil, document[_host].option)
else
local text = newtext(s, mode, getface(document))
text:link(document[_host], 'width', nil, nil, document[_host].option)
end
return document
end
function metatable.put(document, acel, linker, xval, yval)
---[[
if acel.getfontorigin then
local penx, peny = acel:getfontorigin()
end
--]]
acel:link(document[_host], linker or 'fill', xval, yval, document[_host].option)
return document
end
do
local function onclick(hyperlink)
local document = hyperlink.document
if document.onhyperlinkevent then
document:onhyperlinkevent(hyperlink.target, 'click')
end
end
function metatable.puthyperlink(document, text, target)
if target:sub(1, 1) == '.' then
target = document[_filename] .. target
end
local acel = cel.document.hyperlink.new(text, target)
acel.document = document
--TODO make these listeners
acel.onclick = onclick
document:put(acel)
end
end
metatable.get = nil
function metacel:__link(document, link, ...)
local col = document[_col]
if col then
return col, ...
else
return document, ...
end
end
function metatable.open(doc)
--doc[_col]:beginflux()
return doc
end
function metatable.close(doc)
--doc[_col]:endflux()
return doc
end
do
local _new = metacel.new
function metacel:new(face)
face = self:getface(face)
local col = cel.col.new()
local document = _new(self, 0, 0, 0, 0, nil, nil, face)
col:link(document, 'fill')
document[_col] = col
document[_host] = col
document[_facestack] = {cel.getface('document.text')}
return document
end
local _assemble = metacel.assemble
function metacel:assemble(t, doc)
doc = doc or t.self or metacel:new(t.face)
return _assemble(self, t, doc)
end
end
local document = metacel:newfactory()
--[[
document.face = setmetatable({}, {__index = function(face, k)
return function(t)
t.metacels = nil
t.names = nil
t.metacel = 'document.text'
t.name = k
face[k] = cel.face(t)
face[k][_facename] = k
return face[k]
end
end;
})
--]]
function document.newtag(f)
return setmetatable({},
{
__index = function(param, name)
param[name] = function(...)
return f(name, ...)
end
return param[name]
end;
__call = function(param, ...)
return f(nil, ...)
end;
})
end
do --hyperlink
local metacel = metacel['.hyperlink']
local _new = metacel.new
function metacel:new(text, target, face)
face = self:getface(face)
local hyperlink = _new(self, text, face)
hyperlink.target = target
return hyperlink
end
local _assemble = metacel.assemble
function metacel:assemble(t, hyperlink)
return _assemble(self, t, hyperlink or metacel:new(t.text, t.target, t.face))
end
document.hyperlink = metacel:newfactory()
--[[
hyperlink.face = cel.face {
metacel = 'textbutton',
name = '@hyperlink',
font = cel.loadfont('Arial', 12),
hovercolor = cel.color.rgb(0, 65, 255),
textcolor = cel.color.rgb(0, 0, .3 * 255),
layout = {
padding = {
l = 2,
t = 1,
},
},
}
function hyperlink.face:draw(t)
reactor.graphics.clipltrb(t.clip.l, t.clip.t, t.clip.r, t.clip.b)
if t.mousefocus then
reactor.graphics.setcolor4b(self.hovercolor)
t.font:print(t.x + t.penx, t.y + t.peny, t.text)
reactor.graphics.fillrect(t.x + t.penx, t.y + t.peny + 2, t.textw, 1)
else
reactor.graphics.setcolor4b(self.textcolor)
t.font:print(t.x + t.penx, t.y + t.peny, t.text)
end
end
--]]
end
do --document.usenamesapce
local _linebreak = {}
local _hline = {}
local function newelementfactory(call)
local function __newindex(t, key, template)
local mt = {__index = template, __call = call, __element = true}
rawset(t, key, function(t)
if type(t) == 'table' then
return setmetatable(t, mt)
else
return setmetatable({t}, mt)
end
end)
end
local mt = {__call = call, __element = true}
local function __call(self, t)
if type(t) == 'table' then
return setmetatable(t, mt)
else
return setmetatable({t}, mt)
end
end
return setmetatable({}, {__newindex = __newindex; __call = __call})
end
local function iselement(t)
local typeis = type(t)
if typeis == 'string' then
return 'string'
elseif typeis == 'function' then
return 'function'
elseif typeis == 'table' then
if cel.iscel(t) then
return 'cel'
end
local mt = getmetatable(t)
if mt and mt.__element then
return 'element'
end
return 'table'
end
end
local function callelement(element, D, elemtype)
if not element then return end
assert(D)
elemtype = elemtype or iselement(element)
if elemtype == 'string' then
D:write(element:gsub('%s+', ' '):gsub('^%s*(.-)%s*$', '%1'))
elseif elemtype == 'table' then
if element == _linebreak then
D:newline()
elseif element == _hline then
D:putdivider()
else
for index, element in ipairs(element) do
if element then
callelement(element, D)
end
end
end
elseif elemtype == 'function' then
callelement(element(), D) --TODO probably have to setfenv of elemtype before its called
elseif elemtype == 'element' then
element(D)
elseif elemtype == 'cel' then
D:put(element, element.linker, element.xval, element.yval)
end
end
local function mapelementsof(t, D, map)
assert(D)
for index, element in ipairs(t) do
if element then
local elemtype = iselement(element)
map(t, element, index, elemtype, D)
end
end
end
local function callelementsof(t, D)
assert(D)
for index, element in ipairs(t) do
if element then
callelement(element, D)
end
end
end
local factory = {}
do --factory.hyperlink
local function call(hyperlink, D)
D:puthyperlink(hyperlink.text, hyperlink.target)
end
factory.hyperlink = call
end
do --factory.list
local function map(list, element, index, elemtype, D)
if list.template then
callelement(list.template(list, element, index), D)
else
callelement(element, D, elemtype)
end
end
local function call(list, D)
mapelementsof(list, D, map)
D:newline()
end
factory.list = call
end
do --factory.code
local function map(code, element, index, elemtype, D)
if elemtype == 'string' then
local line = element:match('(.-)\r?\n')
local spaces = #(line:match('^(%s+)') or '')
local pattern = '\r?\n' .. string.rep(' ', spaces)
element = element:gsub(pattern, '\n'):sub(1 + spaces)
for line in element:gmatch('(.-)\n') do
D:write(line, 'nowrap') --TODO need richtext option to break only on \n to make this way more effecient
end
else
callelement(element, D, elemtype)
end
end
local function call(code, D)
D:pushface('@code')
mapelementsof(code, D, map)
D:popface(element)
end
factory.code = call
end
do --factory.paragraph
local mws = function(s)
return s:gsub('%s+', ' '):gsub('^%s*(.-)%s*$', '%1')
end
local function map(paragraph, element, index, elemtype, D)
if elemtype == 'string' then
D:write(mws(element))--D:newline()
else
callelement(element, D, elemtype)
end
end
local function call(paragraph, D)
mapelementsof(paragraph, D, map)
end
factory.paragraph = call
end
do --factory.text
local function map(text, element, index, elemtype, D)
if elemtype == 'string' then
D:write(element, 'nowrap')
else
callelement(element, D, elemtype)
end
end
local function call(text, D)
if text.face then
D:pushface(text.face)
mapelementsof(text, D, map)
D:popface()
else
mapelementsof(text, D, map)
end
end
factory.text = call
end
do--factory.section
local function call(section, D)
D:pushsection(section)
callelementsof(section, D)
D:popsection(section)
end
factory.section = call
end
do--factory.row
local function call(row, D)
D:pushrow()
callelementsof(row, D)
D:poprow()
end
factory.row = call
end
function document.newnamespace()
local namespace = {
linebreak = _linebreak,
hline = _hline,
}
for k, v in pairs(factory) do
namespace[k] = newelementfactory(v)
end
return namespace
end
do --document.loadfile
local _exports = {}
local export
do
local mt = {}
function mt.__index(t, key)
local env = getfenv(2)
env[_exports] = env[_exports] or {}
return function(element)
env[_exports][key] = element
end
end
export = setmetatable({}, mt)
end
local function loadfilein(_ENV, name)
local f, err = _G._G.loadfile(name)
if not f then
error (string.format("error loading file `%s' (%s)", name, err))
end
return setfenv(f, _ENV)
end
local function importnamespace(namespace)
local ns = cel.document.newnamespace()
ns[namespace] = ns
ns.documentname = documentname
setmetatable(ns, {__index = _G})
local chunk
--pcall( function()
local t = loadfilein(ns, namespace)
if t then
t()
else
error('file not found ['..namespace..']')
end
--end)
local env = getfenv(2)
for k, v in pairs(ns) do
env[k] = v;
end
end
function document.loadfile(filename)
local env = setmetatable({
export = export,
namespace = importnamespace,
}, {__index = _G})
local chunk
--pcall( function()
local t = loadfilein(env, filename)
if t then
print('calling', filename)
t(filename)
else
error('file not found ['..filename..']')
end
--end)
local name, element = next(env[_exports])
print('FOUND export', name, element)
print('FILENAME', filename)
local doc = cel.document.new()
doc[_filename] = filename
doc:open()
callelement(element, doc)
doc:close()
return doc
end
function document.loadelement(anelement)
local doc = cel.document.new()
doc[_filename] = [[~!@#$FROM ELEMENT///\\\//]]
doc:open()
callelement(anelement, doc)
doc:close()
return doc
end
end
end
return document
|
local custom = require("misc.libs.stdlib")
clientkeys = gears.table.join(
-- Fullscreen Window
awful.key({ modkey }, "f", function(c)
awful.screen.focused().mywibar.ontop = c.fullscreen
c.fullscreen = not c.fullscreen
c:raise()
end, {
description = "toggle fullscreen",
group = "client",
}),
awful.key({ modkey, "Shift" }, "Up", function(c)
awful.client.swap.bydirection("up", c)
end, {
description = "Move client up",
group = "client",
}),
awful.key({ modkey, "Shift" }, "Left", function(c)
awful.client.swap.bydirection("left", c)
end, {
description = "Move client left",
group = "client",
}),
awful.key({ modkey, "Shift" }, "Right", function(c)
awful.client.swap.bydirection("right", c)
end, {
description = "Move client right",
group = "client",
}),
awful.key({ modkey, "Shift" }, "Down", function(c)
awful.client.swap.bydirection("down", c)
end, {
description = "Move client in down",
group = "client",
}),
-- }}}
-- Close Window
awful.key({ modkey, "Shift" }, "c", function(c)
c:kill()
end, { description = "close", group = "client" }),
awful.key({ modkey }, "n", function(c)
-- The client currently has the input focus, so it cannot be
-- minimized, since minimized clients can't have the focus.
c.minimized = true
end, {
description = "minimize",
group = "client",
}),
awful.key({ modkey }, "m", function(c)
awful.titlebar.toggle(c)
c.maximized = true
c:raise()
end, {
description = "(un)maximize",
group = "client",
}),
-- Toggle titlebar
awful.key({ modkey }, "k", function(c)
awful.titlebar.toggle(c)
end, {
description = "Toggle titlebar",
group = "client",
})
)
return clientkeys
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by apple.
--- DateTime: 2018/9/11 上午12:31
---
require("objects.NewGameObject")
--- @class Ammo : NewGameObject
--- 弹药类
--- @param area Area
--- @param x number
--- @param y number
--- @param opts table
--- @field collider Collider
--- @field w number
--- @field h number
--- @field r number
--- @field v number
Ammo = NewGameObject:extend()
function Ammo:new(area,x,y,opts)
Ammo.super.new(self,area,x,y,opts)
local direction = table.random({-1,1})
self.x = gw/2 + direction * (gw/2 + 48)
self.y = random(16,gh - 16)
self.w = 8
self.h = 8
self.collider = self.area.world:newRectangleCollider(self.x,self.y,self.w,self.h)
self.collider:setCollisionClass("Collectable")
self.collider:setObject(self)
--TODO setCollisionClass learn setFixedRotation
self.collider:setFixedRotation(false)
self.r = random(0,2 * math.pi)
self.v = random(10,20)
self.collider:setLinearVelocity(self.v * math.cos(self.r),self.v * math.sin(self.r))
self.collider:applyAngularImpulse(random(-24,24))
--- 一定时间后消失
--self.time = opts.time or 0.1
--timer:after(self.time,function () self:die() end)
end
function Ammo:draw()
love.graphics.setColor(Color.ammo)
pushRote(self.x,self.y,self.collider:getAngle())
love.graphics.rectangle('line',self.x-self.w/2,self.y-self.h/2,self.w,self.h)
love.graphics.pop()
love.graphics.setColor(Color.default)
end
function Ammo:die()
self.dead = true
for _=1,math.random(4,8) do
self.area:addObject("AmmoEffect",self.x,self.y,{s=3,color = Color.ammo})
end
end
function Ammo:destroy()
--self.collider:destroy()
end |
local function setup()
vim.g.dashboard_default_executive = 'fzf'
vim.g.dashboard_session_directory = vim.g.session_dir
vim.api.nvim_exec(
'autocmd FileType dashboard set showtabline=0 | autocmd WinLeave <buffer> set showtabline=2',
false
)
end
return {
setup = setup
}
|
-- define the joystick offsets (for button assignments)
local Thrustmaster = 0
local Quadrant = 160
local XBox = 320
local last_view_type = 0
-- define the DataRef we want to use
DataRef( "view_type", "sim/graphics/view/view_type" )
-- init the view
if get("sim/cockpit/electrical/battery_on") == 1 then
command_once( "sim/view/3d_cockpit_cmnd_look" )
else
command_once( "sim/view/chase" )
end
-- do the initial things
clear_all_axis_assignments()
set_axis_assignment( 0, "roll", "normal" )
set_axis_assignment( 1, "pitch", "normal" )
set_axis_assignment( 3, "yaw", "normal" )
set_axis_assignment( 25, "mixture", "reverse" )
set_axis_assignment( 26, "prop", "reverse" )
set_axis_assignment( 27, "throttle", "normal" )
clear_all_button_assignments()
set_button_assignment( Thrustmaster + 0, "FlyWithLua/autopilot/set_autopilot_off" )
set_button_assignment( Thrustmaster + 2, "sim/view/chase" )
set_button_assignment( Thrustmaster + 3, "sim/view/chase" )
set_button_assignment( Thrustmaster + 4, "sim/general/zoom_in_fast" )
set_button_assignment( Thrustmaster + 5, "sim/general/zoom_out_fast" )
set_button_assignment( Thrustmaster + 6, "FlyWithLua/autopilot/activate_autopilot" )
set_button_assignment( Thrustmaster + 7, "FlyWithLua/autopilot/set_autopilot_off" )
set_button_assignment( Thrustmaster + 8, "sim/view/flashlight_red" )
set_button_assignment( Thrustmaster + 9, "sim/view/flashlight_wht" )
set_button_assignment( Thrustmaster + 10, "FlyWithLua/debugging/enter_code" )
set_button_assignment( Thrustmaster + 11, "FlyWithLua/debugging/reload_scripts" )
set_button_assignment( Thrustmaster + 16, "sim/general/up" )
set_button_assignment( Thrustmaster + 18, "sim/general/right_fast" )
set_button_assignment( Thrustmaster + 20, "sim/general/down" )
set_button_assignment( Thrustmaster + 22, "sim/general/left_fast" )
set_button_assignment( Quadrant + 0, "sim/flight_controls/flaps_up" )
set_button_assignment( Quadrant + 1, "sim/flight_controls/flaps_down" )
set_button_assignment( Quadrant + 2, "sim/flight_controls/speed_brakes_up_all" )
set_button_assignment( Quadrant + 3, "sim/flight_controls/speed_brakes_down_all" )
set_button_assignment( Quadrant + 4, "sim/starters/engage_starter_1" )
set_button_assignment( Quadrant + 5, "sim/starters/engage_starter_2" )
set_button_assignment( Quadrant + 6, "FlyWithLua/flight_controls/ARB" )
set( "sim/joystick/joystick_pitch_nullzone", 0.0 )
set( "sim/joystick/joystick_roll_nullzone", 0.0 )
set( "sim/joystick/joystick_heading_nullzone", 0.0 )
set( "sim/joystick/joystick_pitch_augment", 0.2 )
set( "sim/joystick/joystick_roll_augment", 0.2 )
set( "sim/joystick/joystick_heading_augment", 0.2 )
set( "sim/joystick/joystick_pitch_sensitivity", 0.2 )
set( "sim/joystick/joystick_roll_sensitivity", 0.2 )
set( "sim/joystick/joystick_heading_sensitivity", 0.2 )
set( "sim/graphics/view/field_of_view_deg", 92.5 )
local use_2D_view = false
-- and do all the every frame stuff
function B2D_update()
local Thrustmaster = 0
local Quadrant = 160
local XBox = 320
-- let button change the view between 3d inside and chase outside
-- type 1026 is the inside 3d view, type 1023 the HUD
if (( view_type == 1026 ) and ( last_view_type ~= 1026 ))
or (( view_type == 1023 ) and ( last_view_type ~= 1023 )) then
set_button_assignment( Thrustmaster + 22, "FlyWithLua/pilots_head/look_left" )
set_button_assignment( Thrustmaster + 18, "FlyWithLua/pilots_head/look_right" )
set_button_assignment( Thrustmaster + 16, "FlyWithLua/pilots_head/look_on_instruments" )
set_button_assignment( Thrustmaster + 20, "sim/view/night_vision" )
set_button_assignment( Thrustmaster + 2, "sim/view/chase" )
set_button_assignment( Thrustmaster + 3, "sim/view/chase" )
end
-- type 1017 is the chase view mode
if ( view_type == 1017 ) and ( last_view_type ~= 1017 ) then
set_button_assignment( Thrustmaster + 22, "sim/general/left_fast" )
set_button_assignment( Thrustmaster + 18, "sim/general/right_fast" )
set_button_assignment( Thrustmaster + 16, "sim/general/up" )
set_button_assignment( Thrustmaster + 20, "sim/general/down" )
set_button_assignment( Thrustmaster + 2, "sim/view/forward_with_hud" )
set_button_assignment( Thrustmaster + 3, "sim/view/3d_cockpit_cmnd_look" )
set_button_assignment( Thrustmaster + 4, "sim/general/backward" )
set_button_assignment( Thrustmaster + 5, "sim/general/forward" )
end
-- remember some last values for next frame
last_view_type = view_type
end
-- register the function to be run every frame
do_every_frame( "B2D_update()" )
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- All code above represents the dafault setting of the simulator. -- --
-- -- The following settings are mede for plane (or helicopter) types, who share a -- --
-- -- unique setting with all members of this type. -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- all helicopter will get a unique setting as default
function set_helicopter_assignments()
set_axis_assignment(12, "collective", "normal")
set( "sim/joystick/joystick_pitch_nullzone", 0.0 )
set( "sim/joystick/joystick_roll_nullzone", 0.0 )
set( "sim/joystick/joystick_heading_nullzone", 0.0 )
set( "sim/joystick/joystick_pitch_augment", 0.0 )
set( "sim/joystick/joystick_roll_augment", 0.0 )
set( "sim/joystick/joystick_heading_augment", 0.0 )
set( "sim/joystick/joystick_pitch_sensitivity", 0.0 )
set( "sim/joystick/joystick_roll_sensitivity", 0.0 )
set( "sim/joystick/joystick_heading_sensitivity", 0.0 )
set( "sim/flightmodel/controls/parkbrake", 0.0 )
set_button_assignment( Thrustmaster + 0, "FlyWithLua/HeliTrim/turn_on_tweak" )
HeliTrim_sensitivity = 0.65
end
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- After the default is set and type defaults are set as functions, we will -- --
-- -- define the settings for each of our individual plane or helicopter. -- --
-- -- To be plane spezific, we use "if PLANE_ICAO == "xyz" then ... end". -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- AW139 X-Rotors (A139)
if PLANE_ICAO == "A139" then
set_helicopter_assignments()
set( "sim/graphics/view/field_of_view_deg", 100 )
set( "sim/flightmodel/controls/parkbrake", 1.0 )
end
-- MD902 Explorer (EXPL)
if PLANE_ICAO == "EXPL" then
set_helicopter_assignments()
end
-- Hudges 300 (Hu30)
if PLANE_ICAO == "Hu30" then
set_helicopter_assignments()
set( "sim/graphics/view/field_of_view_deg", 85 )
end
-- Default Robinson R22 (r22)
if PLANE_ICAO == "r22" then
set_helicopter_assignments()
set( "sim/graphics/view/field_of_view_deg", 85 )
end
-- Robinson R44 (RH44)
if PLANE_ICAO == "RH44" then
set_helicopter_assignments()
set( "sim/graphics/view/field_of_view_deg", 85 )
end
-- Bell 206 Dreamfoil
if PLANE_ICAO == "B06" then
set_helicopter_assignments()
set( "sim/graphics/view/field_of_view_deg", 80 )
end
-- EC135 Rotorsim or Jason Chandler
if PLANE_ICAO == "EC35" then
set_helicopter_assignments()
end
-- EC145 Jason Chandler
if PLANE_ICAO == "EC45" then
set_helicopter_assignments()
end
-- Hudges 500D
if PLANE_ICAO == "h500" then
set_helicopter_assignments()
set_heli_tweak_on(-0.16, -0.08, -0.07)
set( "sim/graphics/view/field_of_view_deg", 80 )
end
-- Dreamfoil AS350
if PLANE_ICAO == "PT-DHH" then
set_helicopter_assignments()
set_heli_tweak_on(-0.16, -0.08, -0.07)
set( "sim/graphics/view/field_of_view_deg", 80 )
end
-- BO 105
if PLANE_ICAO == "B105" then
set_helicopter_assignments()
end
-- Carenado C208B
if PLANE_TAILNUMBER == "N2476D" then
autopilot_helper_vvi = 800
plane_has_reverser = true
set( "sim/graphics/view/field_of_view_deg", 105.0 )
set_default_looking_head(-0.2, 0.734, -1.18, 0, -19)
set_left_looking_head(-0.18, 0.61, -0.09, 277, -10.63)
set_right_looking_head(0, 0.6, -0.09, 85.5, -9)
set_instrument_looking_head(-0.05, 0.37, -0.26, 0, 0)
end
-- S-BACH 300
if PLANE_ICAO == "SBACH" then
plane_has_flaps = false
end
-- Jason Chandler C510
if PLANE_ICAO == "C510" then
plane_has_speedbrakes = true
end
-- Carenado Bonanza
if PLANE_ICAO == "BE33" then
set( "sim/graphics/view/field_of_view_deg", 65.0 )
end
-- Harrenssor PIPISTREL Panthera
if PLANE_ICAO == "PIPA" then
set( "sim/graphics/view/field_of_view_deg", 95.0 )
end
-- Harrenssor Diamond Aircraft TwinStar DA42
if PLANE_ICAO == "DA42" then
set( "sim/graphics/view/field_of_view_deg", 90.0 )
end
-- Cessna C172
if PLANE_ICAO == "C172" then
set( "sim/graphics/view/field_of_view_deg", 100.0 )
show_MPPS_instrument = true
end
-- Carenado C172SP
if PLANE_TAILNUMBER == "N399CK" then
set( "sim/graphics/view/field_of_view_deg", 100.0 )
show_MPPS_instrument = true
set_default_looking_head(-0.07, 0.68, 0, 0.56, -6.85)
set_left_looking_head(-0.18, 0.61, -0.09, 277, -10.63)
set_right_looking_head(0, 0.6, -0.09, 85.5, -9)
set_instrument_looking_head(-0.05, 0.37, -0.26, 0, 0)
end
-- Blackshape Prime
if PLANE_TAILNUMBER == "T7-BLK" then
set( "sim/flightmodel/weight/m_fixed", 125.0 )
set( "sim/flightmodel/weight/m_fuel1", 25,0 )
set( "sim/flightmodel/weight/m_fuel2", 25,0 )
set( "sim/graphics/view/field_of_view_deg", 100.0 )
set_default_looking_head(0, 0.68, 0, 0.56, -6.85)
set_left_looking_head(0, 0.68, 0, 270, 0)
set_right_looking_head(0, 0.68, 0, 90, 0)
set_instrument_looking_head(0, 0.45, -0.2, 0, -15)
end
-- STMA Sherpa
if PLANE_ICAO == "SHRP" then
set( "sim/graphics/view/field_of_view_deg", 105.0 )
plane_has_reverser = true
set_button_assignment(Quadrant + 6, "sim/engines/thrust_reverse_hold")
end
-- Carenado CT210M Centurion
if PLANE_TAILNUMBER == "N3888Y" then
set( "sim/graphics/view/field_of_view_deg", 105.0 )
set_default_looking_head(-0.05, 0.48, -0.2, 0, 4.8)
set_left_looking_head(-0.25, 0.42, -0.26, 272, -5)
set_right_looking_head(0, 0.4, -0.26, 100, -5)
set_instrument_looking_head(-0.16, 0.11, -0.23, 0, -5)
set_button_assignment( Quadrant + 6, "sim/flight_controls/brakes_regular" )
end
|
local io = require 'io'
local load_data = {}
function load_data.read_txt_table(fname)
local tab = {}
local file = io.open(fname)
for line in file:lines() do
local k,v = unpack(line:split(" "))
tab[tonumber(k)+1] = v
end
return tab
end
return load_data
|
require "resty.nettle.types.curve25519"
local types = require "resty.nettle.types.common"
local lib = require "resty.nettle.hogweed"
local ffi = require "ffi"
local ffi_str = ffi.string
local curve = {}
function curve.mul(n, p)
if p then
lib.nettle_curve25519_mul(types.uint8_t_32, n, p)
else
lib.nettle_curve25519_mul_g(types.uint8_t_32, n)
end
return ffi_str(types.uint8_t_32, 32);
end
return curve
|
-- Removed, basically, because it's fucked.
FlinchMixin = CreateMixin(FlinchMixin)
FlinchMixin.type = "Flinch"
FlinchMixin.networkVars =
{
}
function FlinchMixin:GetFlinchIntensity()
return 0
end |
require 'love.image'
require 'love.thread'
require 'love.math'
require 'love.filesystem'
require 'love.image'
require 'trace'
require 'chunk'
require 'properties'
local thisChannel = love.thread.getChannel("physics")
local mainChannel = love.thread.getChannel("main")
print(' physics ready')
while true do
local payload = thisChannel:demand()
Physics:update(payload.x, payload.y, payload.dt)
end |
-- Copyright 2006-2021 gwash. See LICENSE.
-- Archlinux PKGBUILD LPeg lexer.
local lexer = require('lexer')
local token, word_match = lexer.token, lexer.word_match
local P, S = lpeg.P, lpeg.S
local lex = lexer.new('pkgbuild')
-- Whitespace.
lex:add_rule('whitespace', token(lexer.WHITESPACE, lexer.space^1))
-- Comments.
lex:add_rule('comment', token(lexer.COMMENT, lexer.to_eol('#')))
-- Strings.
local sq_str = lexer.range("'", false, false)
local dq_str = lexer.range('"')
local ex_str = lexer.range('`')
local heredoc = '<<' * P(function(input, index)
local s, e, _, delimiter = input:find('(["\']?)([%a_][%w_]*)%1[\n\r\f;]+', index)
if s == index and delimiter then
e = select(2, input:find('[\n\r\f]+' .. delimiter, e))
return e and e + 1 or #input + 1
end
end)
lex:add_rule('string', token(lexer.STRING, sq_str + dq_str + ex_str + heredoc))
-- Numbers.
lex:add_rule('number', token(lexer.NUMBER, lexer.number))
-- Keywords.
lex:add_rule('keyword', token(lexer.KEYWORD, word_match{
'patch', 'cd', 'make', 'patch', 'mkdir', 'cp', 'sed', 'install', 'rm', 'if', 'then', 'elif',
'else', 'fi', 'case', 'in', 'esac', 'while', 'for', 'do', 'done', 'continue', 'local', 'return',
'git', 'svn', 'co', 'clone', 'gconf-merge-schema', 'msg', 'echo', 'ln',
-- Operators.
'-a', '-b', '-c', '-d', '-e', '-f', '-g', '-h', '-k', '-p', '-r', '-s', '-t', '-u', '-w', '-x',
'-O', '-G', '-L', '-S', '-N', '-nt', '-ot', '-ef', '-o', '-z', '-n', '-eq', '-ne', '-lt', '-le',
'-gt', '-ge', '-Np', '-i'
}))
-- Functions.
lex:add_rule('function',
token(lexer.FUNCTION, word_match('build check package pkgver prepare') * '()'))
-- Constants.
lex:add_rule('constant', token(lexer.CONSTANT, word_match{
-- We do *not* list pkgver srcdir and startdir here.
-- These are defined by makepkg but user should not alter them.
'arch', 'backup', 'changelog', 'checkdepends', 'conflicts', 'depends', 'epoch', 'groups',
'install', 'license', 'makedepends', 'md5sums', 'noextract', 'optdepends', 'options', 'pkgbase',
'pkgdesc', 'pkgname', 'pkgrel', 'pkgver', 'provides', 'replaces', 'sha1sums', 'sha256sums',
'sha384sums', 'sha512sums', 'source', 'url', 'validpgpkeys'
}))
-- Identifiers.
lex:add_rule('identifier', token(lexer.IDENTIFIER, lexer.word))
-- Variables.
local symbol = S('!#?*@$')
local parens = lexer.range('(', ')', true)
local brackets = lexer.range('[', ']', true)
local braces = lexer.range('{', '}', true)
local backticks = lexer.range('`', true, false)
local number = lexer.dec_num
lex:add_rule('variable', token(lexer.VARIABLE, '$' *
(symbol + parens + brackets + braces + backticks + number + lexer.word)))
-- Operators.
lex:add_rule('operator', token(lexer.OPERATOR, S('=!<>+-/*^~.,:;?()[]{}')))
-- Fold points.
lex:add_fold_point(lexer.OPERATOR, '(', ')')
lex:add_fold_point(lexer.OPERATOR, '{', '}')
lex:add_fold_point(lexer.COMMENT, lexer.fold_consecutive_lines('#'))
return lex
|
-----------------------------------
-- Area: The Eldieme Necropolis
-- Mob: Sturm
-- Involved in Quest: A New Dawn (BST AF3)
-----------------------------------
local ID = require("scripts/zones/The_Eldieme_Necropolis/IDs")
require("scripts/globals/quests")
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(tpz.mobMod.IDLE_DESPAWN, 300)
end
function onMobDeath(mob, player, isKiller)
if player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.A_NEW_DAWN) == QUEST_ACCEPTED and player:getCharVar("ANewDawn_Event") == 4 then
player:setCharVar("ANewDawn_Event", 5)
end
if isKiller then
for i = ID.mob.TAIFUN, ID.mob.TROMBE do
if GetMobByID(i):isSpawned() then
DespawnMob(i)
end
end
end
end
|
local path = "conf/skins.xml"
local skinsData = {}
local function loadData()
local fileNode = xmlLoadFile(path, true)
if not fileNode then return warn("skins conf file not found", 2) and false end
local fileData = xmlNodeGetData(fileNode)
xmlUnloadFile(fileNode)
for i, skinData in ipairs(fileData.children) do
local model = tonumber(skinData.attributes.model)
skinsData[model] = {
name = skinData.attributes.name,
groups = split(skinData.attributes.groups, ","),
walking = tonumber(skinData.attributes.walking)
}
end
return true
end
loadData()
function isValidPedModel(model)
if not scheck("n") then return false end
return skinsData[model] and true or false
end
function getPedModelName(model)
if not scheck("n") then return false end
if not skinsData[model] then return warn("invalid ped model", 2) and false end
return skinsData[model].name
end
function getPedModelFromPartialName(partialName)
if not scheck("s") then return false end
partialName = utf8.lower(partialName)
for model, data in pairs(skinsData) do
if utf8.find(utf8.lower(data.name), partialName, 1, true) then return model end
end
return nil
end
function getPedModelGroups(model)
if not scheck("n") then return false end
if not skinsData[model] then return warn("invalid ped model", 2) and false end
return skinsData[model].groups
end
function getPedModelWalkingStyle(model)
if not scheck("n") then return false end
if not skinsData[model] then return warn("invalid ped model", 2) and false end
return skinsData[model].walking
end |
function onCreate()
makeLuaSprite('whitebg','',-1000,200)
makeGraphic('whitebg',400,100,'FFFFFF')
setObjectCamera('whitebg','other')
setProperty('whitebg.alpha',0.7)
addLuaSprite('whitebg')
makeLuaText('songtext',songName,400,0,200)
setTextSize('songtext',30)
setObjectCamera('songtext','other')
setTextAlignment('songtext','center')
addLuaText('songtext')
makeLuaText('authortext',difficultyName,400,0,260)
setTextSize('authortext',30)
setObjectCamera('authortext','other')
setTextAlignment('authortext','center')
addLuaText('authortext')
end
function onCreatePost()
doTweenX('songtweenin','whitebg',0,1,'cubeOut')
end
function onUpdate()
setProperty('songtext.x',getProperty('whitebg.x'))
setProperty('authortext.x',getProperty('whitebg.x'))
end
function onTweenCompleted(tag)
if tag == 'songtweenin' then
runTimer('tweentimer',3)
end
if tag == 'songtweenout' then
removeLuaText('authortext')
removeLuaText('songtext')
removeLuaSprite('whitebg')
end
end
function onTimerCompleted(tag)
if tag == 'tweentimer' then
doTweenX('songtweenout','whitebg',-1000,1,'cubeIn')
end
end
|
local function Reply(msg)
local text = msg.content_.text_
if ChatType == 'sp' or ChatType == 'gp' then
if not DevAli:get(ReLaX..'Ali:Lock:Reply'..msg.chat_id_) then
if text == "انجب" or text == "نجب" or text == "انجبي" or text == "نجبي" or text == "انجبو" or text == "نجبو" then
if SudoId(msg) then
rd = 'مطوريي اغلط شكد متريد نورتنه ، ♥️💪🏿'
elseif SudoBot(msg) then
rd = 'احترم نفسكك لا عبالكك رافعيك مطور ، 🖕🏿♥️'
elseif ManagerAll(msg) then
rd = 'حبيبي راح اسامحكك لان مدير وع راسي ، 🖐🏿♥️'
elseif AdminAll(msg) then
rd = 'راح اسامحكك هلمره لانك ادمن ، ☝🏿♥️'
elseif VipAll(msg) then
rd = 'راح احترمكك تره بس هلمره لانك مميز عندي ، ☝🏿♥️'
elseif AliConstructor(msg) then
rd = 'تاج راسيي غير انت منشئ المجموعه ،🖐🏿♥️'
elseif Constructor(msg) then
rd = 'تاج راسيي انت المنشئ الاساسي ،🖐🏿♥️'
elseif BasicConstructor(msg) then
rd = 'حبيبي المنشئ استقبلها منكك ،👍🏿♥️'
elseif Manager(msg) then
rd = 'حبيبي راح اسامحكك لان مدير وع راسي ، 🖐🏿♥️'
elseif Admin(msg) then
rd = 'راح اسامحكك هلمره لانك ادمن ، ☝🏿♥️'
elseif VipMem(msg) then
rd = 'راح احترمكك تره بس هلمره لانك مميز عندي ، ☝🏿♥️'
else
rd = 'لكك هوه انت عضو وجاي تغلط ؟، 🖕🏿♥️'
end
Dev_Ali(msg.chat_id_, msg.id_, 1,rd, 1, 'html')
end
if text == 'دي' or text == 'ديي' or text == 'دي بابه' then
ReLaXTEAM = "آخلُِآقٌڪڪ لُِڪڪ 𖠙 😒🔪"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'السلام عليكم' or text == 'سلام عليكم' then
ReLaXTEAM = "ياھَہّلْاا ۅﻋ̝̚لْيڪْم الْﺳ̭͠ لْام 𖠙 🤤♥️"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == '😭💔' or text == '😭😭' or text == '😭😭😭' or text == '😿💔' or text == '😭😭😭' or text == '😭😭😭😭' then
ReLaXTEAM = "مآآعٍآشُ آلُِي يزعٍلُِڪڪ 𖠙 😏♥️"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == '🌚💔' or text == '💔🌚' or text == '🚶♂💔' or text == '💔' or text == '😔💔' or text == '🚶♀💔' or text == '😭' then
ReLaXTEAM = "شبّيي اﻟ̣̣פﻟ̣̣و 𖠙 😿💔"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'باي' or text == 'بااي' or text == 'اروح' or text == 'اروح احسن' or text == 'اولي احسن' or text == 'راح اروح' or text == 'باي انام' then
ReLaXTEAM = "أُرٌجُعُ عٍيدِهآآ مٍوو تنِْسةه 𖠙 🤤♥️"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'هلو' or text == 'هلاو' or text == 'هلا' or text == 'هلاوو' or text == 'هيلاو' or text == 'هيلاوو' or text == 'هلاا' then
local ReLaXTEAM = {"اࠗط็لق֯ق֯ هٞللاࠗ୨و 𖠙 🤤♥️" ,"هۂَلاا نۨہٰورتت يعمۘري 𖠙 🤤♥️" }
DevAli2 = math.random(#ReLaXTEAM)
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM[DevAli2] , 1, 'md')
return false
end
if text == 'شونك' or text == 'شونج' or text == 'شلونك' or text == 'شلونج' or text == 'شونكم' or text == 'شلونكم' or text == 'شلخبار' or text == 'شلون الاخبار' or text == 'شخبارك' then
local ReLaXTEAM = {"ماﺷ͠ يةھَہّ يﻋ̝̚مريي ۅاﻧﺗ̲ت 𖠙 🤤♥️" ,"الحۡمۘدللهۂَ ٰوانۨہتت 𖠙 🤤♥️","تمۘامۘ عمۘري ٰوانۨہتت 𖠙 🤤♥️"}
DevAli2 = math.random(#ReLaXTEAM)
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM[DevAli2] , 1, 'md')
return false
end
if text == 'وينك' or text == 'وينج' then
ReLaXTEAM = "مْوٌجہوٌدِ يہمْگُ يحلوُ 𖠙 😉♥️"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'بوت عواي' or text == 'بوت زربه' or text == 'البوت عاوي' or text == 'البوت زربه' then
ReLaXTEAM = "اطردكك تجرب ؟ ، 😕🔪"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'نايمين' or text == 'ميتين' then
ReLaXTEAM = "طُآمسين ووعٍيوونڪ 𖠙 😪🖤ۦ"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'هلوباي' or text == 'هلو باي' then
ReLaXTEAM = "شحۡسۜيت مۘنۨہ هيجۚ ּكتبت ؟ 🌝♥️"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'اكلك' or text == 'اكلج' or text == 'اكلكم' then
ReLaXTEAM = "ڪوولُِ مآڪوولُِ لُِآحٍدِ 𖠙 😉♥️"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'فرخ' or text == 'فرخه' then
ReLaXTEAM = "ٰوينۨہهۂَ خۡل احۡصرهۂَ 𖠙 😹♥️"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
if text == 'سورس عبس' or text == 'سورس بروكس' or text == 'سورس ديف بروكس' or text == 'سورس زربه' or text == 'السورس زربه' or text == 'سورس عاوي' or text == 'السورس عاوي' then
ReLaXTEAM = "لُِآ سوورس خآلُِتڪ دِي لُِڪ 𖠙 😒🔪"
Dev_Ali(msg.chat_id_, msg.id_, 1, ReLaXTEAM, 1, 'md')
return false
end
end
if Manager(msg) then
if text == 'تفعيل ردود البوت' or text == 'تفعيل الردود' then
if not DevAli:get(ReLaX..'Ali:Lock:Reply'..msg.chat_id_) then
Dev_Ali(msg.chat_id_, msg.id_, 1, '⌁︙ردود البوت بالتاكيد مفعله ', 1, 'md')
else
Dev_Ali(msg.chat_id_, msg.id_, 1, '⌁︙تم تفعيل ردود البوت', 1, 'md')
DevAli:del(ReLaX..'Ali:Lock:Reply'..msg.chat_id_)
end end
if text == 'تعطيل ردود البوت' or text == 'تعطيل الردود' then
if DevAli:get(ReLaX..'Ali:Lock:Reply'..msg.chat_id_) then
Dev_Ali(msg.chat_id_, msg.id_, 1, '⌁︙ردود البوت بالتاكيد معطله ', 1, 'md')
else
DevAli:set(ReLaX..'Ali:Lock:Reply'..msg.chat_id_,true)
Dev_Ali(msg.chat_id_, msg.id_, 1, '⌁︙تم تعطيل ردود البوت', 1, 'md')
end end
end
end
end
return {
ReLaX = Reply
}
|
local _0_0 = nil
do
local name_23_0_ = "conjure.client.clojure.nrepl.ui"
local loaded_23_0_ = package.loaded[name_23_0_]
local module_23_0_ = nil
if ("table" == type(loaded_23_0_)) then
module_23_0_ = loaded_23_0_
else
module_23_0_ = {}
end
module_23_0_["aniseed/module"] = name_23_0_
module_23_0_["aniseed/locals"] = (module_23_0_["aniseed/locals"] or {})
module_23_0_["aniseed/local-fns"] = (module_23_0_["aniseed/local-fns"] or {})
package.loaded[name_23_0_] = module_23_0_
_0_0 = module_23_0_
end
local function _1_(...)
_0_0["aniseed/local-fns"] = {require = {["nrepl-state"] = "conjure.client.clojure.nrepl.state", a = "conjure.aniseed.core", client = "conjure.client", log = "conjure.log", str = "conjure.aniseed.string", text = "conjure.text"}}
return {require("conjure.aniseed.core"), require("conjure.client"), require("conjure.log"), require("conjure.client.clojure.nrepl.state"), require("conjure.aniseed.string"), require("conjure.text")}
end
local _2_ = _1_(...)
local a = _2_[1]
local client = _2_[2]
local log = _2_[3]
local nrepl_state = _2_[4]
local str = _2_[5]
local text = _2_[6]
do local _ = ({nil, _0_0, {{}, nil}})[2] end
local display = nil
do
local v_23_0_ = nil
do
local v_23_0_0 = nil
local function display0(lines, opts)
return client["with-filetype"]("clojure", log.append, lines, opts)
end
v_23_0_0 = display0
_0_0["display"] = v_23_0_0
v_23_0_ = v_23_0_0
end
_0_0["aniseed/locals"]["display"] = v_23_0_
display = v_23_0_
end
local state = nil
do
local v_23_0_ = (_0_0["aniseed/locals"].state or {["join-next"] = {key = nil}})
_0_0["aniseed/locals"]["state"] = v_23_0_
state = v_23_0_
end
local handle_join_line = nil
do
local v_23_0_ = nil
local function handle_join_line0(resp)
local next_key = nil
if resp.out then
next_key = "out"
elseif resp.err then
next_key = "err"
else
next_key = nil
end
local _4_ = a.get(state, "join-next", {})
local key = _4_["key"]
if (next_key or resp.value) then
local function _5_()
if (next_key and not text["trailing-newline?"](a.get(resp, next_key))) then
return {key = next_key}
end
end
a.assoc(state, "join-next", _5_())
end
return (next_key and (key == next_key))
end
v_23_0_ = handle_join_line0
_0_0["aniseed/locals"]["handle-join-line"] = v_23_0_
handle_join_line = v_23_0_
end
local display_result = nil
do
local v_23_0_ = nil
do
local v_23_0_0 = nil
local function display_result0(resp, opts)
local opts0 = (opts or {})
local joined_3f = handle_join_line(resp)
local _3_
if resp.out then
local _4_
if opts0["simple-out?"] then
_4_ = "; "
elseif opts0["raw-out?"] then
_4_ = ""
else
_4_ = "; (out) "
end
_3_ = text["prefixed-lines"](text["trim-last-newline"](resp.out), _4_, {["skip-first?"] = joined_3f})
elseif resp.err then
_3_ = text["prefixed-lines"](text["trim-last-newline"](resp.err), "; (err) ", {["skip-first?"] = joined_3f})
elseif resp.value then
if not (opts0["ignore-nil?"] and ("nil" == resp.value)) then
_3_ = text["split-lines"](resp.value)
else
_3_ = nil
end
else
_3_ = nil
end
return display(_3_, {["join-first?"] = joined_3f})
end
v_23_0_0 = display_result0
_0_0["display-result"] = v_23_0_0
v_23_0_ = v_23_0_0
end
_0_0["aniseed/locals"]["display-result"] = v_23_0_
display_result = v_23_0_
end
local display_sessions = nil
do
local v_23_0_ = nil
do
local v_23_0_0 = nil
local function display_sessions0(sessions, cb)
local current = a["get-in"](nrepl_state, {"conn", "session"})
local function _3_(_4_0)
local _5_ = _4_0
local idx = _5_[1]
local session = _5_[2]
local _6_
if (current == session.id) then
_6_ = ">"
else
_6_ = " "
end
return str.join({"; ", _6_, idx, " - ", session.str()})
end
display(a.concat({("; Sessions (" .. a.count(sessions) .. "):")}, a["map-indexed"](_3_, sessions)), {["break?"] = true})
if cb then
return cb()
end
end
v_23_0_0 = display_sessions0
_0_0["display-sessions"] = v_23_0_0
v_23_0_ = v_23_0_0
end
_0_0["aniseed/locals"]["display-sessions"] = v_23_0_
display_sessions = v_23_0_
end
return nil |
-- Copyright (C) Yichun Zhang (agentzh)
local base = require "resty.core.base"
base.allows_subsystem('http')
local ffi = require "ffi"
local C = ffi.C
local ffi_str = ffi.string
local getfenv = getfenv
local error = error
local tonumber = tonumber
local errmsg = base.get_errmsg_ptr()
local get_string_buf = base.get_string_buf
local get_string_buf_size = base.get_string_buf_size
local get_size_ptr = base.get_size_ptr
local FFI_DECLINED = base.FFI_DECLINED
local FFI_OK = base.FFI_OK
local FFI_BUSY = base.FFI_BUSY
ffi.cdef[[
int ngx_http_lua_ffi_ssl_get_ocsp_responder_from_der_chain(
const char *chain_data, size_t chain_len, char *out, size_t *out_size,
char **err);
int ngx_http_lua_ffi_ssl_create_ocsp_request(const char *chain_data,
size_t chain_len, unsigned char *out, size_t *out_size, char **err);
int ngx_http_lua_ffi_ssl_validate_ocsp_response(const unsigned char *resp,
size_t resp_len, const char *chain_data, size_t chain_len,
unsigned char *errbuf, size_t *errbuf_size);
int ngx_http_lua_ffi_ssl_set_ocsp_status_resp(ngx_http_request_t *r,
const unsigned char *resp, size_t resp_len, char **err);
]]
local _M = { version = base.version }
function _M.get_ocsp_responder_from_der_chain(certs, maxlen)
local buf_size = maxlen
if not buf_size then
buf_size = get_string_buf_size()
end
local buf = get_string_buf(buf_size)
local sizep = get_size_ptr()
sizep[0] = buf_size
local rc = C.ngx_http_lua_ffi_ssl_get_ocsp_responder_from_der_chain(certs,
#certs, buf, sizep, errmsg)
if rc == FFI_DECLINED then
return nil
end
if rc == FFI_OK then
return ffi_str(buf, sizep[0])
end
if rc == FFI_BUSY then
return ffi_str(buf, sizep[0]), "truncated"
end
return nil, ffi_str(errmsg[0])
end
function _M.create_ocsp_request(certs, maxlen)
local buf_size = maxlen
if not buf_size then
buf_size = get_string_buf_size()
end
local buf = get_string_buf(buf_size)
local sizep = get_size_ptr()
sizep[0] = buf_size
local rc = C.ngx_http_lua_ffi_ssl_create_ocsp_request(certs,
#certs, buf, sizep,
errmsg)
if rc == FFI_OK then
return ffi_str(buf, sizep[0])
end
if rc == FFI_BUSY then
return nil, ffi_str(errmsg[0]) .. ": " .. tonumber(sizep[0])
.. " > " .. buf_size
end
return nil, ffi_str(errmsg[0])
end
function _M.validate_ocsp_response(resp, chain, max_errmsg_len)
local errbuf_size = max_errmsg_len
if not errbuf_size then
errbuf_size = get_string_buf_size()
end
local errbuf = get_string_buf(errbuf_size)
local sizep = get_size_ptr()
sizep[0] = errbuf_size
local rc = C.ngx_http_lua_ffi_ssl_validate_ocsp_response(
resp, #resp, chain, #chain, errbuf, sizep)
if rc == FFI_OK then
return true
end
-- rc == FFI_ERROR
return nil, ffi_str(errbuf, sizep[0])
end
function _M.set_ocsp_status_resp(ocsp_resp)
local r = getfenv(0).__ngx_req
if not r then
return error("no request found")
end
local rc = C.ngx_http_lua_ffi_ssl_set_ocsp_status_resp(r, ocsp_resp,
#ocsp_resp,
errmsg)
if rc == FFI_DECLINED then
-- no client status req
return true, "no status req"
end
if rc == FFI_OK then
return true
end
-- rc == FFI_ERROR
return nil, ffi_str(errmsg[0])
end
return _M
|
return {
timer_messages_fn = {},
timer_messages_flag_active = false,
start_timer_messages = function(self)
if self.cnf.timer_messages ~= nil and #self.cnf.timer_messages > 0 then
for i = TMR_SERVER_MESSAGES, ( TMR_SERVER_MESSAGES + (#self.cnf.timer_messages-1) ) do
if self.cnf.timer_messages[i-TMR_SERVER_MESSAGES+1].active['disable'] == false and self.cnf.timer_messages[i-TMR_SERVER_MESSAGES+1].active[self.parent.flag.SERVER] ~= nil and self.cnf.timer_messages[i-TMR_SERVER_MESSAGES+1].active[self.parent.flag.SERVER] == true then
if self.timer_messages_fn[i] == nil then
self.timer_messages_fn[i] = function()
local num_func = i
if type(sdbs.cnf.server.timer_messages[num_func-TMR_SERVER_MESSAGES+1].text) == 'string' then
sdbs.say:smg(sdbs.cnf.server.timer_messages[num_func-TMR_SERVER_MESSAGES+1].text)
elseif type(sdbs.cnf.server.timer_messages[num_func-TMR_SERVER_MESSAGES+1].text) == 'function' then
local smg = sdbs.cnf.server.timer_messages[num_func-TMR_SERVER_MESSAGES+1].text()
if smg~= nil then sdbs.say:smg(smg) end
end
end
tmr.create(i,self.cnf.timer_messages[i-TMR_SERVER_MESSAGES+1].period,self.timer_messages_fn[i])
self.parent.log:w('Activate server timer messages TMR: '..tostring(i))
end
end
end
self.timer_messages_flag_active = true
end
end,
stop_timer_messages = function(self)
if self.cnf.timer_messages ~= nil and #self.cnf.timer_messages > 0 then
for i = TMR_SERVER_MESSAGES, ( TMR_SERVER_MESSAGES + (#self.cnf.timer_messages-1) ) do
if self.cnf.timer_messages[i-TMR_SERVER_MESSAGES+1].active['disable'] == false and self.cnf.timer_messages[i-TMR_SERVER_MESSAGES+1].active[self.parent.flag.SERVER] ~= nil and self.cnf.timer_messages[i-TMR_SERVER_MESSAGES+1].active[self.parent.flag.SERVER] == true and self.timer_messages_fn[i] ~= nil then
tmr.remove(i)
self.timer_messages_fn[i] = nil
self.parent.log:w('Deactivate server timer messages TMR: '..tostring(i))
end
end
self.timer_messages_flag_active = false
end
end,
on_player_connect = function(self)
if #self.parent.cn.data > 0 and self.timer_messages_flag_active == false then
self:start_timer_messages()
end
end,
on_player_disconnect = function(self,cn)
if #self.parent.cn.data == 0 and self.timer_messages_flag_active == true then
self:stop_timer_messages()
end
end,
is_linux = function(self)
end,
is_gema = function(self)
for _,v in ipairs(self.parent.cnf.server.list_name_server_gema) do
if self.parent.flag.SERVER:find(v) then
return true
end
end
return false
end,
sendmail = function(self,email,text,cn)
if self.cnf.msmtp.active then
local PLAYER, SUBJECT, MESSAGE, BODY, COMMAND, dcn ,email,text= {}, {}, '', '', '',nil,email,text
if type(email) == 'string' then
email = self.parent.fn:split(email,',')
for k,v in ipairs(email) do
email[k] = self.parent.fn:trim(v)
end
end
local temail = {}
for k,v in ipairs(email) do
if v ~= NOT_EMAIL or v ~= '' then
table.insert(temail,v)
end
end
email = nil
if #temail == 0 then
self.parent.log:w(self.cnf.msmtp.text['send_email_no_to'])
if cn ~= nil then self.parent.say:me(cn,self.cnf.msmtp.text['send_email_no']) end
return
end
if type(text) ~= 'string' and type(text) == 'table' then
text = table.concat(text,'')
end
--text = string.gsub(text,'|','\\|')
--text = self.parent.fn:escape_SPECL(text)
if type(text) ~= 'string' then
self.parent.log:w(self.cnf.msmtp.text['send_email_no_text'])
if cn ~= nil then self.parent.say:me(cn,self.cnf.msmtp.text['send_email_no']) end
return
end
if type(self.cnf.msmtp.subject) == 'string' then
table.insert(SUBJECT,self.cnf.msmtp.subject)
else
for _,v in ipairs(self.cnf.msmtp.subject) do
table.insert(SUBJECT,v)
end
end
for k,v in ipairs(SUBJECT) do
SUBJECT[k] = string.format(v,string.upper(self.parent.flag.SERVER))
end
SUBJECT = table.concat(SUBJECT, ', ')
if cn ~=nil then
dcn = self.parent.cn:get_dcn(cn)
if self.parent.cn.data[dcn].account.email == '' then self.parent.cn.data[dcn].account.email = NOT_EMAIL end
if type(self.cnf.msmtp.sent_by_the_player) == 'string' then
table.insert(PLAYER,self.cnf.msmtp.sent_by_the_player)
else
for _,v in ipairs(self.cnf.msmtp.sent_by_the_player) do
table.insert(PLAYER,v)
end
end
for k,v in ipairs(PLAYER) do
PLAYER[k] = string.format(v,self.parent.cn.data[dcn].name,self.parent.cn.data[dcn].account.email,self.parent.cn.data[dcn].ip)
end
else
if type(self.cnf.msmtp.sent_by_the_server) == 'string' then
table.insert(PLAYER,self.cnf.msmtp.sent_by_the_server)
else
for _,v in ipairs(self.cnf.msmtp.sent_by_the_server) do
table.insert(PLAYER,v)
end
end
for k,v in ipairs(PLAYER) do
PLAYER[k] = string.format(v,string.upper(self.parent.flag.SERVER))
end
end
PLAYER = table.concat(PLAYER, '\n')
BODY = string.format('%s\n%s\n\n\n%s\nauthor: %s\n%s\n%s',PLAYER,text,PLUGIN_NAME..' '..PLUGIN_VERSION,PLUGIN_AUTHOR,PLUGIN_SITE,PLUGIN_EMAIL)
for _,vemail in ipairs(temail) do
MESSAGE = string.format('"Date: %s\nFrom: %s\nTo: %s\nSubject: %s\nContent-Type: text/plain; charset=UTF-8\n\n%s"',os.date(),self.cnf.msmtp.from,vemail,SUBJECT,BODY)
COMMAND = string.format("echo '%s' | /usr/bin/msmtp --host=%s --port=%s --tls=%s --tls-certcheck=off --tls-starttls=%s --auth=login --user=%s --passwordeval=\"echo %s\" -f %s %s > /dev/null &",MESSAGE,self.cnf.msmtp.server,self.cnf.msmtp.port,self.cnf.msmtp.tls,self.cnf.msmtp.tls_starttls,self.cnf.msmtp.from,self.cnf.msmtp.password,self.cnf.msmtp.from,vemail)
if os.execute(COMMAND) then
self.parent.log:w(self.cnf.msmtp.text['send_email_ok'])
if cn ~= nil then self.parent.say:me(cn,self.cnf.msmtp.text['send_email_ok']) end
else
self.parent.log:w(self.cnf.msmtp.text['send_email_no'])
if cn ~= nil then self.parent.say:me(cn,self.cnf.msmtp.text['send_email_no']) end
end
end
else
if cn ~= nil then self.parent.say.me(cn,self.cnf.msmtp.text['disable_activate']) end
end
end,
timer_service_fn = {},
start_timer_service = function(self)
if self.cnf.timer_service ~= nil and #self.cnf.timer_service > 0 then
for i = TMR_SERVER_SERVICE, ( TMR_SERVER_SERVICE + (#self.cnf.timer_service-1) ) do
if self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].active['disable'] == false and self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].active[self.parent.flag.SERVER] ~= nil and self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].active[self.parent.flag.SERVER] == true then
if self.timer_service_fn[i] == nil and type(self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].fn) == 'function' then
self.timer_service_fn[i] = function()
local num_func = i
if type(sdbs.cnf.server.timer_service[num_func-TMR_SERVER_SERVICE+1].fn) == 'function' then
sdbs.cnf.server.timer_service[num_func-TMR_SERVER_SERVICE+1].fn()
end
end
tmr.create(i,self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].period,self.timer_service_fn[i])
self.parent.log:w('Activate server timer service TMR: '..tostring(i))
end
end
end
end
end,
stop_timer_service = function(self)
if self.cnf.timer_service ~= nil and #self.cnf.timer_service > 0 then
for i = TMR_SERVER_SERVICE, ( TMR_SERVER_SERVICE + (#self.cnf.timer_service-1) ) do
if self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].active['disable'] == false and self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].active[self.parent.flag.SERVER] ~= nil and self.cnf.timer_service[i-TMR_SERVER_SERVICE+1].active[self.parent.flag.SERVER] == true and self.timer_service_fn[i]~=nil then
tmr.remove(i)
self.timer_service_fn[i] = nil
self.parent.log:w('Deactivate server timer service TMR: '..tostring(i))
end
end
end
end,
start_server = function(self)
if self.cnf.log.active and self.cnf.log.start.active then
self.parent.sql:server_log_start_update(self.parent.flag.SERVER)
end
if self.cnf.msmtp.active and self.cnf.msmtp.allert_and_send_to.start_server.active then
local text = {}
for _,v in ipairs(self.cnf.msmtp.allert_and_send_to.start_server.text) do
table.insert(text,string.format(v,os.date('%d-%m-%Y %X')))
end
self:sendmail(self.cnf.msmtp.allert_and_send_to.start_server.to,text)
end
end,
stop_server = function(self)
if self.cnf.log.active and self.cnf.log.stop.active then
self.parent.sql:server_log_stop_update(self.parent.flag.SERVER)
end
if self.cnf.msmtp.active and self.cnf.msmtp.allert_and_send_to.stop_server.active then
local text = {}
for _,v in ipairs(self.cnf.msmtp.allert_and_send_to.stop_server.text) do
table.insert(text,string.format(v,os.date('%d-%m-%Y %X')))
end
self:sendmail(self.cnf.msmtp.allert_and_send_to.stop_server.to,text)
end
end,
server_log_visit_to_msmtp = function(self,aemail,atext,timestamp_start,timestamp_end)
if self.cnf.msmtp.active then
local text = {}
table.insert(text,string.format('\nStarting date for statistics: %s',os.date('%d-%m-%Y %X',self.cnf.log.starting_date_of_creation_of_statistics)))
local f,r = self.parent.sql:server_log_get(self.parent.flag.SERVER)
if f then
table.insert(text,string.format('\n\nThe server started: %s',os.date('%d-%m-%Y %X',r.timestamp_start)))
table.insert(text,string.format('\nThe number of calls to the server: %s',tostring(r.count_connect_player)))
table.insert(text,string.format('\nThe number of played maps: %s',tostring(r.count_change_map)))
end
f,r = nil,nil
table.insert(text,string.format('\nThe number of maps on the server:\n\tJust: %s. Gema: %s. In the rotator: %s. Gema in the rotator: %s.',self.parent.gm.map:get_cmaps(),self.parent.gm.map:get_cgmaps(),self.parent.gm.map:get_crmaps(),self.parent.gm.map:get_crgmaps()))
local f,r = self.parent.sql:server_log_change_map_get_list(self.parent.flag.SERVER,self.cnf.msmtp.allert_and_send_to.log_visit.top_map)
if f then
table.insert(text,string.format('\nTop %s popular maps ( Name / Played ) :',#r))
for _,v in ipairs(r) do
table.insert(text,string.format('\n\t%s / %s',v.map,v.count_change))
end
end
f,r = nil,nil
local ts,te = 0,0
if timestamp_start ~= nil and tonumber(timestamp_start) ~= nil then
ts = os.time() - ( tonumber(timestamp_start)*60*60 )
else
ts = os.time()
end
if timestamp_end ~= nil and tonumber(timestamp_end) ~= nil then
te = ts - ( tonumber(timestamp_end) * 60 * 60 )
else
te = ts - ( self.cnf.msmtp.allert_and_send_to.log_visit.time_period * 60 * 60 )
end
f,r = self.parent.sql:server_log_visit_player_get_list(self.parent.flag.SERVER,ts,te)
ts,te = nil,nil
if f then
local tracking_implicit,tracking_player, tracking_clan, players_called,key = {},{},{},{},#r
while #r > 0 do
for _,v in ipairs(self.cnf.msmtp.allert_and_send_to.log_visit.tracking_implicit) do
if #r >= 1 and string.find(string.lower(r[key].player),v) then
table.insert(tracking_implicit,table.remove(r,key))
key = key - 1
end
end
for _,v in ipairs(self.cnf.msmtp.allert_and_send_to.log_visit.tracking_player) do
if #r >= 1 and v == r[key].player then
table.insert(tracking_player,table.remove(r,key))
key = key - 1
end
end
for _,v in ipairs(self.cnf.msmtp.allert_and_send_to.log_visit.tracking_clan) do
if #r >= 1 and string.find(r[key].player,v) then
table.insert(tracking_clan,table.remove(r,key))
key = key - 1
end
end
if #r >= 1 then table.insert(players_called,table.remove(r,key)) end
key = key - 1
end
if #tracking_implicit > 0 then
table.insert(text,string.format('\n\nTracked implicit players visited: %s',tostring(#tracking_implicit)))
table.insert(text,'\n\t( Player / Hits / IP / OLD IP / date )')
for _,v in ipairs(tracking_implicit) do
if v.old_ip_1 == '' then v.old_ip_1 =v.ip end
table.insert(text,string.format('\n\t%s / %s / %s / %s / %s',v.player,v.count_visit,v.ip,v.old_ip_1,os.date('%d-%m-%Y %X',v.timestamp_connect)))
end
end
if #tracking_player > 0 then
table.insert(text,string.format('\n\nTracked players visited: %s',tostring(#tracking_player)))
table.insert(text,'\n\t( Player / Hits / IP / OLD IP / date )')
for _,v in ipairs(tracking_player) do
if v.old_ip_1 == '' then v.old_ip_1 =v.ip end
table.insert(text,string.format('\n\t%s / %s / %s / %s / %s',v.player,v.count_visit,v.ip,v.old_ip_1,os.date('%d-%m-%Y %X',v.timestamp_connect)))
end
end
if #tracking_clan > 0 then
table.insert(text,string.format('\n\nTracked a clan of players visited: %s',tostring(#tracking_clan)))
table.insert(text,'\n\t( Player / Hits / IP / OLD IP / date )')
for _,v in ipairs(tracking_clan) do
if v.old_ip_1 == '' then v.old_ip_1 =v.ip end
table.insert(text,string.format('\n\t%s / %s / %s / %s / %s',v.player,v.count_visit,v.ip,v.old_ip_1,os.date('%d-%m-%Y %X',v.timestamp_connect)))
end
end
if #players_called > 0 then
table.insert(text,string.format('\n\nPlayers called for: %s',tostring(#players_called)))
table.insert(text,'\n\t( Player / Hits / IP / OLD IP / date )')
for _,v in ipairs(players_called) do
if v.old_ip_1 == '' then v.old_ip_1 =v.ip end
table.insert(text,string.format('\n\t%s / %s / %s / %s / %s',v.player,v.count_visit,v.ip,v.old_ip_1,os.date('%d-%m-%Y %X',v.timestamp_connect)))
end
end
end
f,r,tracking_player, tracking_clan,tracking_implicit, players_called, key = nil,nil,nil,nil,nil,nil,nil
local email = aemail or self.cnf.msmtp.allert_and_send_to.log_visit.to
if type(email) == 'string' then
local e = {}
table.insert(e,email)
email = e
end
if atext ~=nil then
if type(atext) == 'string' then table.insert(text,atext) else
for _,v in ipairs(atext) do
table.insert(text,v)
end
end
end
self.parent.log:w(string.format('%s%s','send email: ', table.concat(email,',')))
self:sendmail(email,text)
email,text,e = nil,nil,nil
end
end,
init = function(self,obj)
self.parent = obj
self.cnf = self.parent.cnf.server
self.parent.log:w('Module SERVER init OK')
end
}
|
--单点登录并使用redis作为用户token存储时,采用的数据类型为hash
--KEYS[1]每个用户独特唯一的token的key
--KEYS[2]每个用户每次登录时随机生成的token的key
--ARGS[1]为用户请求时携带的token的value
--ARGS[2]为验证token成功时重新设置失效时间的值
if redis.call('hget', KEYS[1], KEYS[2]) == ARGS[1] then
if redis.call('expire', KEYS[1], ARGS[2]) == 1 then
return true
end
end
return false |
DefineClass.Unit =
{
__parents = { "Movable", "CommandObject", "UngridedObstacle", "DoesNotObstructConstruction", "SyncObject","Renamable" },
encyclopedia_id = false,
enum_flags = { efUnit = true, efWalkable = false, efCollision = false, efApplyToGrids = false, efSelectable = true, },
class_flags = { cfComponentSound = true },
ShadowBias = "Units",
fx = false,
fx_actor = false,
fx_target = false,
pfclass = 0,
goto_target = false,
holder = false,
always_renderable = false,
current_dome = false, -- the dome the unit is physically inside, not "home dome"
dome_version = 0,
entrance_type = false, -- means any
lead_in_out = false, -- current lead in/out object
visit_door_opened = false,
visit_end_time = false,
visit_spot_end_time = false,
visit_restart = false,
visit_thread = false,
direction_arrow_scale = 100,
init_with_command = "Start",
use_passages = false,
}
function Unit:GameInit()
if self.init_with_command then
if type(self.init_with_command) == "table" then
self:SetCommand(table.unpack(self.init_with_command))
else
self:SetCommand(self.init_with_command)
end
end
self:SetHeat(255)
PlayFX("Spawn", "start", self)
end
function Unit:Done()
self:StopFX()
PlayFX("Spawn", "end", self)
self:SetHolder(false)
end
function Unit:CanBeControlled()
return false
end
local invalid_obj_pos = point(-1, -1)
function Unit:Gossip(gossip, ...)
if not netAllowGossip then return end
NetGossip(self.class, self.handle, IsValid(self) and self:GetPos() or invalid_obj_pos, gossip, GameTime(), ...)
end
function Unit:GossipName()
return self.class
end
function Unit:Start()
Sleep(AsyncRand(1000))
end
local Sleep = Sleep
function Unit:MoveSleep(time)
Sleep(time)
end
function Unit:StartFX(fx, target, actor)
actor = actor or self
PlayFX(fx, "start", actor, target)
self.fx = fx
self.fx_actor = actor
self.fx_target = target
end
function Unit:PlayFXMoment(moment)
if self.fx then
PlayFX(self.fx, moment, self.fx_actor, self.fx_target)
end
end
function Unit:StopFX()
if self.fx then
PlayFX(self.fx, "end", self.fx_actor, self.fx_target)
self.fx = false
self.fx_actor = false
self.fx_target = false
end
end
function Unit:OnCommandStart()
self:StopFX()
self.goto_target = false
end
function Unit:StartMoving()
end
function Unit:StopMoving()
end
Unit.Step = pf.Step
local pfFinished = const.pfFinished
local pfFailed = const.pfFailed
local pfDestLocked = const.pfDestLocked
local pfTunnel = const.pfTunnel
local pfTeleportDist = 50*guim
function Unit:Goto(...)
local pfStep = self.Step
local status = pfStep(self, ...)
if status < 0 and status ~= pfTunnel then
return status == pfFinished
end
self.goto_target = ...
self:StartMoving()
self:PushDestructor(function(self)
if IsValid(self) then
self:StopMoving()
self.goto_target = false
self:ClearPath()
end
end)
local pfSleep = self.MoveSleep
while true do
if status > 0 then
pfSleep(self, status)
elseif status == pfTunnel then
local end_point = pf.GetPathPoint(self, pf.GetPathPointCount(self))
local tunnel, param = pf.GetTunnel(self:GetPos(), end_point)
if not tunnel or not tunnel:TraverseTunnel(self, self:GetPos(), end_point, param) then
self:ClearPath()
status = pfFailed
break
end
else
break
end
status = pfStep(self, ...)
end
self:PopDestructor()
self:StopMoving()
self.goto_target = false
return status == pfFinished
end
function Unit:SetOutside(outside)
end
function Unit:OnEnterDome(dome)
assert(not self.current_dome or self.current_dome == dome)
self.current_dome = dome
self:SetOutside(false)
end
function Unit:OnExitDome(dome)
assert(not self.current_dome or self.current_dome == dome)
self.current_dome = false
self:SetOutside(true)
end
function Unit:WaitDoorOpening(door)
local time_to_open = door:TimeToOpen()
if time_to_open > 0 then
local wait_anim = self:GetWaitAnim()
self:SetState(wait_anim >= 0 and wait_anim or "idle")
Sleep(time_to_open)
end
end
function Unit:KickFromBuilding(building, entrance_type)
local entrance, pos, spot_type = building:GetEntrance(nil, entrance_type)
pos = spot_type and building:GetSpotPos(building:GetRandomSpot(spot_type)) or pos or building:GetPos()
self:SetHolder(false)
self:Detach()
self:SetPos(pos)
building:OnExitUnit(self)
self:SetCommand("Idle")
end
function Unit:ShowAttachedSigns(shown)
end
function Unit:EnterBuilding(building, entrance_type, spot_name) -- works only if unit/building are both outside or inside the same dome
if not IsValid(building) or not building:IsValidPos() then
return false
elseif self.holder == building then
return true
elseif not self:GotoSameDomeAsObj(building) then
return false
elseif not IsValid(building) or not building:IsValidPos() then
--retest after goto.
return false
elseif IsKindOf(building, "Dome") then
return true
elseif not IsKindOf(building, "WaypointsObj") then
return false
end
local entrance, pos, entrance_spot = building:GetEntrance(self, entrance_type or self.entrance_type, spot_name)
if entrance_spot then
local force_place = not self:IsValidPos() or not self:Goto(building, entrance_spot)
if not IsValid(building) then return false end
if force_place then
if self:IsValidPos() then
self:SetPos(building:GetSpotPos(building:GetNearestSpot(entrance_spot, self)))
else
self:SetPos(building:GetSpotPos(building:GetRandomSpot(entrance_spot)))
end
end
building:OnEnterUnit(self)
return true
end
if pos then
if not self:IsValidPos() or not IsCloser2D(self, pos, guim/2) and not self:Goto_NoDestlock(pos) then
self:SetPos(pos)
end
end
assert(entrance, "Building without entrance: " .. tostring(ObjectClass(building)))
if entrance and IsValid(building) then
building:LeadIn(self, entrance)
return true
end
end
function Unit:ExitBuilding(building, target, entrance_type, spot_name)
building = building or self.holder
if not IsValid(building) or not IsKindOf(building, "WaypointsObj") then return end
assert(building:IsValidPos())
if not building:IsValidPos() then
return
end
local entrance, pos, entrance_spot = building:GetEntrance(target or self, entrance_type or self.entrance_type, spot_name)
if entrance_spot then
if not self:IsValidPos() then
if IsValid(target) then
self:SetPos(building:GetSpotPos(building:GetNearestSpot(entrance_spot, target)))
else
self:SetPos(building:GetSpotPos(building:GetRandomSpot(entrance_spot)))
end
end
building:OnExitUnit(self)
return true
end
assert(entrance, "Building without entrance: " .. tostring(ObjectClass(building)))
if not entrance then
return
end
building:LeadOut(self, entrance)
return true
end
local StockpileEnterExitDomeOffset = point(0, 0, -80)
local function EnterExitDome(self, dome, target, enter)
if not IsValid(dome) or not dome:IsValidPos() then
return false
end
local dome_entrance = FindNearestObject(dome.dome_entrances, enter and (self:IsValidPos() and self or self.holder) or target)
assert(dome_entrance, "Dome has no entrance")
local entrance, pos = dome_entrance:GetEntrance(self, nil, enter and "Doorentrance1" or "Doorentrance2")
assert(entrance, "Dome without entrance chains")
if self.holder then
self:ExitBuilding(self.holder, pos)
if not IsValid(dome) then
return false
end
end
if not self:IsValidPos() or not self:Goto_NoDestlock(pos) then
if not IsValid(dome) or enter then
-- fail if can't enter the dome
self:OnEnterDomeFail(dome)
return false
end
self:SetPos(pos) -- teleport if can't exit the dome
if entrance and #entrance > 1 then
self:Face(entrance[#entrance-1], 0)
end
end
if not IsValid(dome) then
return false
end
--move carried box so it doesnt collide with dome entrance
local box = self:GetAttach("ResourceStockpileBox")
if box then
box:SetAttachOffset(StockpileEnterExitDomeOffset)
end
self:PushDestructor(function(self)
local box = self:GetAttach("ResourceStockpileBox")
if box then
box:SetAttachOffset(point30)
end
if self:IsValidPos() and self.safe_pos_on_failure then
self:SetPos(self.safe_pos_on_failure)
self.safe_pos_on_failure = false
end
end)
if not IsValid(dome_entrance) then
-- dome skin changed (entrance autoattach is replaced)
dome_entrance = FindNearestObject(dome.dome_entrances, pos)
entrance, pos = dome_entrance:GetEntrance(self, nil, enter and "Doorentrance1" or "Doorentrance2")
end
self.safe_pos_on_failure = entrance[#entrance]
dome:LeadIn(self, entrance)
if not IsValid(dome) then
self.safe_pos_on_failure = false
self:PopAndCallDestructor()
if self:IsValidPos() then
self:SetPos(self:GetVisualPos2D())
end
return false
end
if enter then
self:OnEnterDome(dome)
else
self:OnExitDome(dome)
end
if not IsValid(dome_entrance) then
-- dome skin changed (entrance autoattach is replaced)
dome_entrance = FindNearestObject(dome.dome_entrances, pos)
end
entrance, pos = dome_entrance:GetEntrance(self, nil, enter and "Doorexit1" or "Doorexit2")
self.safe_pos_on_failure = entrance[#entrance]
dome:LeadOut(self, entrance)
self.safe_pos_on_failure = false
self:PopDestructor()
local box = self:GetAttach("ResourceStockpileBox")
if box then
box:SetAttachOffset(point30)
end
assert(enter and self.current_dome == dome or not enter and not self.current_dome)
return true
end
-- recalc current dome when exit from outside buildings. We need to recalc current dome when the building's exit is too close to any dome.
function Unit:ValidateCurrentDomeOnExit(building)
if not IsObjInDome(building) then
self.dome_version = 0
end
end
function Unit:CalcCurrentDome()
if self.dome_version == g_DomeVersion then
return self.current_dome
end
self.dome_version = g_DomeVersion
local dome, pos
if self.holder then
dome = IsObjInDome(self.holder)
elseif self:IsValidPos() then
pos = GetPassablePointNearby(GetTopmostParent(self):GetPos(), self.pfclass)
end
dome = dome or pos and GetDomeAtPoint(pos) or false
if self:TimeToPosInterpolationEnd() > 0 and pos and GetDomeAtPoint(self:GetVisualPos2D()) ~= dome then
self:SetPos(pos)
end
if self.current_dome ~= dome then
if self.current_dome then
self:OnExitDome(self.current_dome)
end
if dome then
self:OnEnterDome(dome)
end
end
return dome
end
function AreDomesConnectedWithPassageDeep() end
-- goes inside the same dome as obj, or outside domes if obj is not in a dome
function Unit:GotoSameDomeAsObj(obj)
local obj_dome = IsPoint(obj) and GetDomeAtPoint(obj) or IsObjInDome(obj) or IsKindOf(obj, "Dome") and obj or false
local unit_dome = self:CalcCurrentDome()
if unit_dome == obj_dome then
self:ExitBuilding(self.holder, obj)
return true
end
if self.use_passages then
local conn, through_dome = AreDomesConnectedWithPassageDeep(unit_dome, obj_dome)
--we need a pnt to go to, go to the passage exit in dest dome closest to us
if conn then
local my_pos = self:GetPos()
local exits = obj_dome.passage_exits[through_dome]
local best_pos
for i = 1, #exits do
if not best_pos or IsCloser2D(my_pos, exits[i], best_pos) then
best_pos = exits[i]
end
end
return self:Goto(best_pos)
end
end
if unit_dome and obj_dome then
-- !!! long range transportation of units between domes
end
local success = true
if unit_dome and (IsPoint(obj) or IsValid(obj)) then
success = EnterExitDome(self, unit_dome, obj, false) -- exit
end
if obj_dome and (IsPoint(obj) or IsValid(obj)) then
success = EnterExitDome(self, obj_dome, obj, "enter") -- enter
end
return success
end
function Unit:OnEnterDomeFail(dome)
end
function Unit:GotoUnitSpot(unit, spot)
-- pathfinding failure shields
if IsValid(unit) and self:GotoSameDomeAsObj(unit) and IsValid(unit) and self:Goto(unit, spot) then
return true
end
if not IsValid(unit) then
return false
end
if unit:GetDist2D(self) - unit:GetRadius() - self:GetRadius() < 5*guim then return true end
local pt = GetPassablePointNearby(unit:GetPos(), self.pfclass)
if self:Goto(pt) and IsValid(unit) then return true end
Sleep(1000)
end
function Unit:GotoBuildingSpot(building, spot, force_teleport)
if not IsValid(building) then
return false
end
local goto_args = building:HasMember("destroyed") and building.destroyed and building.orig_state and spot and building.orig_state[spot] and {building.orig_state[spot]} or {building, spot}
local begin_idx = spot and building:GetSpotBeginIndex("idle", spot) or -1
local success
if IsKindOf(building, "Dome") then
local idx = spot and building:GetNearestSpot("idle", spot, self)
local dome_at_pos = false
if idx then
local spot_pos = GetPassablePointNearby(#goto_args == 2 and building:GetSpotLoc(idx) or goto_args[1][idx - begin_idx + 1], self.pfclass)
dome_at_pos = GetDomeAtPoint(spot_pos)
else
dome_at_pos = building --first passable around origin will be inside
end
success = self:GotoSameDomeAsObj(dome_at_pos)
else
success = self:GotoSameDomeAsObj(building)
end
if not success or not IsValid(building) then
return false
end
local result = self:Goto(table.unpack(goto_args))
if not result then
-- if can't reach a free spot then allow colliding with other units
result = IsValid(building) and self:Goto_NoDestlock(table.unpack(goto_args))
end
if not IsValid(building) then
return false
end
local idx = spot and building:GetNearestSpot("idle", spot, self)
if not result then
local spot_pos = (#goto_args == 2 or not idx) and building:GetSpotPos(idx or -1) or goto_args[1][idx - begin_idx + 1]
if self:GetDist(spot_pos) > 2*guim then
return false
end
end
if idx then
local angle = building:GetSpotRotation(idx)
self:SetAngle(angle, 100)
else
self:Face(building, 100)
end
return true
end
function Unit:GoToRandomPosInDome(dome)
assert(dome)
if not dome then
return
end
local pts = dome.walkable_points
local idx = self:Random(1, #pts)
if not self:IsValidPos() then
self:SetPos(pts[idx])
return
end
self:Goto(pts[idx])
end
function Unit:GetRandomPos(max_radius, min_radius, center, retries, filter)
retries = retries or 25
center = center or self:GetVisualPos()
min_radius = min_radius or 0
local mw, mh = terrain.GetMapSize()
if center == InvalidPos() then
center = point(mw / 2, mh / 2)
end
for j = 1, retries do
local x, y = RotateRadius(min_radius + self:Random(max_radius - min_radius), self:Random(360 * 60), center, true)
x = Clamp(x, guim, mw - guim)
y = Clamp(y, guim, mh - guim)
if terrain.IsPassable(x, y) and (not filter or filter(x, y)) then
return point(x, y)
end
end
end
function Unit:GoToRandomPos(max_radius, min_radius, center, retries, filter)
local pt = self:GetRandomPos(max_radius, min_radius, center, retries, filter)
if pt then
return self:Goto(pt)
end
end
function Unit:ExitImpassable()
local pt = GetPassablePointNearby(self:GetVisualPos(), self.pfclass)
self:Goto(pt)
end
function Unit:Trace(...)
if config.TraceEnabled then
print(...)
end
end
function Unit:UpdateUI()
if self == SelectedObj then
Msg("UIPropertyChanged", self)
end
end
function Unit:IsInDome()
return IsObjInDome(self)
end
function Unit:SetHolder(building)
local holder = self.holder
building = building or false
if holder == building or building and not building:IsKindOf("Holder") then
return
end
if holder then
holder:OnExitHolder(self)
end
self.holder = building
if building then
building:OnEnterHolder(self)
end
assert(self.holder or self:IsValidPos())
end
function Unit:UpdateEntity()
end
--represents the shape a unit is currently obstucting, for large units.
function Unit:GetRotatedShapePoints()
if pathfind[self.pfclass + 1].large then
return UngridedObstacle.GetRotatedShapePoints(self)
end
return FallbackOutline
end
function Unit:StartAlwaysRender(reason)
if not self.always_renderable then
if self:GetGameFlags(const.gofAlwaysRenderable) ~= 0 then
return
end
self.always_renderable = {}
end
if next(self.always_renderable) == nil then
self:SetGameFlags(const.gofAlwaysRenderable)
end
self.always_renderable[reason] = true
end
function Unit:StopAlwaysRender(reason)
if not self.always_renderable then
return
end
self.always_renderable[reason] = nil
if next(self.always_renderable) == nil then
self:ClearGameFlags(const.gofAlwaysRenderable)
self.always_renderable = nil
end
end
function Unit:InterruptCommand()
if self:InterruptVisit() then
return
end
self:SetCommand("Idle")
end
function Unit:IsVisitingBuilding()
if self.lead_in_out or self.visit_end_time then
return true
end
return false
end
function Unit:InterruptVisit()
if not self.visit_end_time then
return
end
self.visit_end_time = GameTime() -- mark the visit as finished
Wakeup(self.visit_thread)
return true
end
function Unit:VisitTimeLeft()
local time = 0
if self.visit_end_time then
time = self.visit_end_time - GameTime()
end
if time > 0 and self.visit_spot_end_time then
time = Clamp(GameTime() - self.visit_spot_end_time, 0, time)
end
return time > 0 and time or 0
end
function Unit:WaitVisitEnd()
repeat
local wait = self:VisitTimeLeft()
until self.visit_restart or wait <= 0 or not WaitWakeup(wait)
end
function Unit:PlayPrg(prg, duration, ...)
self.visit_end_time = GameTime() + duration
self.visit_spot_end_time = false
self.visit_thread = CurrentThread()
-- execute prg in the destructor to make it uninterruptible
self:PushDestructor(function(self)
self.visit_end_time = false
self.visit_spot_end_time = false
self.visit_restart = false
self.visit_thread = false
end)
if not prg then
self:DetachFromMap()
self:SetOutside(false)
end
while self:VisitTimeLeft() > 0 do
self.visit_restart = false
if prg then
local prg_start_time = GameTime()
prg(self, ...)
if GameTime() - prg_start_time == 0 then
WaitWakeup(Min(5000, self:VisitTimeLeft()))
end
else
self:WaitVisitEnd() -- interrupted from visit_restart
end
end
self:PopAndCallDestructor()
end
function Unit:GotoFromUser(...) --goto and dome handling in one
self:GotoSameDomeAsObj(...)
self:Goto(...)
end
function Unit:IsDead()
return IsValid(self)
end
----- Vehicle
DefineClass.Vehicle = {
__parents = { "Unit" },
game_flags = { gofSpecialOrientMode = true },
orient_mode = "terrain",
}
function dbg_ShowMeAllSpots(obj, ss)
local s_idx = obj:GetSpotBeginIndex(ss)
local e_idx = obj:GetSpotEndIndex(ss)
for i = s_idx, e_idx do
ShowMe(obj:GetSpotPos(i))
end
end
|
--
-- Project: wiola
-- User: Konstantin Burkalev
-- Date: 02.11.17
--
local _M = {}
local json = require('wiola.serializers.json_serializer')
local redis
local config
--- Format NUMBER for using in strings
local formatNumber = function(n)
return string.format("%.0f", n)
end
---
--- Return index of obj in array t
---
--- @param t table array table
--- @param obj any object to search
--- @return index of obj or -1 if not found
---------------------------------------------------
local arrayIndexOf = function(t, obj)
if type(t) == 'table' then
for i = 1, #t do
if t[i] == obj then
return i
end
end
return -1
else
error("table.indexOf expects table for first argument, " .. type(t) .. " given")
end
end
---
--- Find URI in pattern based (prefix and wildcard) uri list
---
---
--- @param uriList table URI list (RPCs or Topics)
--- @param uri string Uri to find
--- @param all boolean Return all matches or just first
--- @return table array of matched URIs
---
local findPatternedUri = function(uriList, uri, all)
local matchedUris = {}
local comp = function(p1,p2)
local _, p1c, p2c
_, p1c = string.gsub(p1, "%.", "")
_, p2c = string.gsub(p2, "%.", "")
if p1c > p2c then -- reverse sort
return true
else
return false
end
end
table.sort(uriList, comp)
-- trying to find prefix matched uri
for _, value in ipairs(uriList) do
if string.match(uri, "^" .. string.gsub(value, "%.", "%%.") .. "%.") then
if all then
table.insert(matchedUris, value)
else
return { value }
end
end
end
local compWldCrd
compWldCrd = function(p1,p2)
local _, p1c, p2c, p1v, p2v, p1dots, p2dots, p1l, p2l
p1l = string.len(p1)
p2l = string.len(p2)
if p1l == 0 and p2l > 0 then
return false
elseif p2l == 0 and p1l > 0 then
return true
elseif p1l == 0 and p2l == 0 then
return true
end
p1dots = string.find(p1, "..", 1, true) or p1l
p2dots = string.find(p2, "..", 1, true) or p2l
p1v = string.sub(p1, 1, p1dots)
p2v = string.sub(p2, 1, p2dots)
_, p1c = string.gsub(p1v, "%.", "")
_, p2c = string.gsub(p2v, "%.", "")
if p1c > p2c then -- reverse sort
return true
elseif p1c < p2c then
return false
else
return compWldCrd(string.sub(p1, p1dots+2), string.sub(p2, p2dots+2))
end
end
table.sort(uriList, compWldCrd)
-- trying to find wildcard matched uri
for _, value in ipairs(uriList) do
local replUri, c = string.gsub(value, "%.%.", ".[0-9a-zA-Z_]+.")
if c ~= nil then -- it's wildcard uri
local re = "^" .. string.gsub(replUri, "%.", "%%.") .. "$"
if string.match(uri, re) then
if all then
table.insert(matchedUris, value)
else
return { value }
end
end
end
end
return matchedUris
end
---
--- Initialize store connection
---
--- @param cfg table store configuration
--- @return boolean, string is Ok flag, error description
---
function _M:init(cfg)
local redisOk, redisErr
local redisLib = require "resty.redis"
redis = redisLib:new()
config = cfg
if config.storeConfig.port == nil then
redisOk, redisErr = redis:connect(config.storeConfig.host)
else
redisOk, redisErr = redis:connect(config.storeConfig.host, config.storeConfig.port)
end
if redisOk and config.storeConfig.db ~= nil then
redis:select(config.storeConfig.db)
end
return redisOk, redisErr
end
---
--- Generate unique Id
---
--- @return number unique Id
---
function _M:getRegId()
local regId
local max = 2 ^ 53
local time = redis:time()
-- math.randomseed( os.time() ) -- Precision - only seconds, which is not acceptable
math.randomseed(time[1] * 1000000 + time[2])
repeat
regId = math.random(max)
-- regId = math.random(100000000000000)
until redis:sismember("wiolaIds", formatNumber(regId))
return regId
end
---
--- Add new session Id to active list
---
--- @param regId number session registration Id
--- @param session table Session information
---
function _M:addSession(regId, session)
session.sessId = formatNumber(session.sessId)
redis:sadd("wiolaIds", formatNumber(regId))
redis:hmset("wiSes" .. formatNumber(regId), session)
end
---
--- Get session info
---
--- @param regId number session registration Id
--- @return table session object or nil
---
function _M:getSession(regId)
local sessArr = redis:hgetall("wiSes" .. formatNumber(regId))
if #sessArr > 0 then
local session = redis:array_to_hash(sessArr)
session.isWampEstablished = tonumber(session.isWampEstablished)
session.sessId = tonumber(session.sessId)
if session.wampFeatures then
session.wampFeatures = json.decode(session.wampFeatures)
end
if session.authInfo then
session.authInfo = json.decode(session.authInfo)
end
return session
else
return nil
end
end
---
--- Change session info
---
--- @param regId number session registration Id
--- @param session table Session information
---
function _M:changeSession(regId, session)
session.isWampEstablished = formatNumber(session.isWampEstablished)
session.sessId = formatNumber(session.sessId)
session.wampFeatures = json.encode(session.wampFeatures)
if session.authInfo then
session.authInfo = json.encode(session.authInfo)
end
redis:hmset("wiSes" .. formatNumber(regId), session)
end
---
--- Remove session data from runtime store
---
--- @param regId number session registration Id
---
function _M:removeSession(regId)
local regIdStr = formatNumber(regId)
local session = redis:array_to_hash(redis:hgetall("wiSes" .. regIdStr))
session.realm = session.realm or ""
local subscriptions = redis:array_to_hash(redis:hgetall("wiRealm" .. session.realm .. "Subs"))
for k, v in pairs(subscriptions) do
redis:srem("wiRealm" .. session.realm .. "Sub" .. k .. "Sessions", regIdStr)
redis:del("wiRealm" .. session.realm .. "Sub" .. k .. "Session" .. regIdStr)
if redis:scard("wiRealm" .. session.realm .. "Sub" .. k .. "Sessions") == 0 then
redis:del("wiRealm" .. session.realm .. "Sub" .. k .. "Sessions")
redis:hdel("wiRealm" .. session.realm .. "Subs",k)
redis:hdel("wiRealm" .. session.realm .. "RevSubs",v)
end
end
local rpcs = redis:array_to_hash(redis:hgetall("wiSes" .. regIdStr .. "RPCs"))
for k, _ in pairs(rpcs) do
redis:srem("wiRealm" .. session.realm .. "RPCs",k)
redis:del("wiRealm" .. session.realm .. "RPC" .. k)
end
redis:del("wiSes" .. regIdStr .. "RPCs")
redis:del("wiSes" .. regIdStr .. "RevRPCs")
redis:del("wiSes" .. regIdStr .. "Challenge")
redis:srem("wiRealm" .. session.realm .. "Sessions", regIdStr)
if redis:scard("wiRealm" .. session.realm .. "Sessions") == 0 then
redis:srem("wiolaRealms",session.realm)
end
redis:del("wiSes" .. regIdStr .. "Data")
redis:del("wiSes" .. regIdStr)
redis:srem("wiolaIds",regIdStr)
end
---
--- Get session count in realm
---
--- @param realm string realm to count sessions
--- @param authroles table optional authroles list
--- @return number, table session count, session Ids array
---
function _M:getSessionCount(realm, authroles)
local count = 0
local sessionsIdList = {}
local allSessions = redis:smembers("wiRealm" .. realm .. "Sessions")
if type(authroles) == 'table' and #authroles > 0 then
for _, sessId in ipairs(allSessions) do
local sessionInfo = self:getSession(sessId)
if sessionInfo.authInfo and arrayIndexOf(authroles, sessionInfo.authInfo.authrole) > 0 then
count = count + 1
table.insert(sessionsIdList, sessId)
end
end
else
count = redis:scard("wiRealm" .. realm .. "Sessions")
sessionsIdList = allSessions
end
return count, sessionsIdList
end
---
--- Prepare data for sending to client
---
--- @param session table Session information
--- @param data table data for client
---
function _M:putData(session, data)
redis:rpush("wiSes" .. formatNumber(session.sessId) .. "Data", data)
end
---
--- Retrieve data, available for session
---
--- @param regId number session registration Id
--- @param last boolean return from the end of a queue
--- @return any client data
---
function _M:getPendingData(regId, last)
if last == true then
return redis:rpop("wiSes" .. formatNumber(regId) .. "Data")
else
return redis:lpop("wiSes" .. formatNumber(regId) .. "Data")
end
end
---
--- Set connection handler flags for session
---
--- @param regId number session registration Id
--- @param flags table flags data
---
function _M:setHandlerFlags(regId, flags)
return redis:hmset("wiSes" .. formatNumber(regId) .. "HandlerFlags", flags)
end
---
--- Retrieve connection handler flags, set up for session
---
--- @param regId number session registration Id
--- @return table flags data
---
function _M:getHandlerFlags(regId)
local flarr = redis:hgetall("wiSes" .. formatNumber(regId) .. "HandlerFlags")
if #flarr > 0 then
local fl = redis:array_to_hash(flarr)
return fl
else
return nil
end
end
---
--- Get Challenge info
---
--- @param regId number session registration Id
--- @return table challenge info object
---
function _M:getChallenge(regId)
local challenge = redis:array_to_hash(redis:hgetall("wiSes" .. formatNumber(regId) .. "Challenge"))
challenge.session = tonumber(challenge.session)
return challenge
end
---
--- Change Challenge info
---
--- @param regId number session registration Id
--- @param challenge table Challenge information
---
function _M:changeChallenge(regId, challenge)
if challenge.session then
challenge.session = formatNumber(challenge.session)
end
redis:hmset("wiSes" .. formatNumber(regId) .. "Challenge", challenge)
end
---
--- Remove Challenge data from runtime store
---
--- @param regId number session registration Id
---
function _M:removeChallenge(regId)
redis:del("wiSes" .. formatNumber(regId) .. "Challenge")
end
---
--- Add session to realm (creating one if needed)
---
--- @param regId number session registration Id
--- @param realm string session realm
---
function _M:addSessionToRealm(regId, realm)
if redis:sismember("wiolaRealms", realm) == 0 then
redis:sadd("wiolaRealms", realm)
self:registerMetaRpc(realm)
end
redis:sadd("wiRealm" .. realm .. "Sessions", formatNumber(regId))
end
---
--- Get subscription id
---
--- @param realm string session realm
--- @param uri string subscription uri
--- @return number subscription Id
---
function _M:getSubscriptionId(realm, uri)
return tonumber(redis:hget("wiRealm" .. realm .. "Subs", uri))
end
---
--- Subscribe session to topic (also create topic if it doesn't exist)
---
--- @param realm string session realm
--- @param uri string subscription uri
--- @param options table subscription options
--- @param regId number session registration Id
---
function _M:subscribeSession(realm, uri, options, regId)
local subscriptionIdStr = redis:hget("wiRealm" .. realm .. "Subs", uri)
local subscriptionId = tonumber(subscriptionIdStr)
local isNewSubscription = false
local regIdStr = formatNumber(regId)
if not subscriptionId then
subscriptionId = self:getRegId()
isNewSubscription = true
subscriptionIdStr = formatNumber(subscriptionId)
redis:hset("wiRealm" .. realm .. "Subs", uri, subscriptionIdStr)
redis:hset("wiRealm" .. realm .. "RevSubs", subscriptionIdStr, uri)
redis:hset("wiRealm" .. realm .. "Sub" .. uri, "exact", 0, "prefix", 0, "wildcard", 0)
end
redis:hmset("wiRealm" .. realm .. "Sub" .. uri .. "Session" .. regIdStr,
"subscriptionId", subscriptionIdStr,
"matchPolicy", options.match or "exact")
redis:sadd("wiRealm" .. realm .. "Sub" .. uri .. "Sessions", regIdStr)
return subscriptionId, isNewSubscription
end
---
--- Unsubscribe session from topic (also remove topic if there is no more subscribers)
---
--- @param realm string session realm
--- @param subscId number subscription Id
--- @param regId number session registration Id
---
--- @return boolean, boolean was session unsubscribed from topic, was topic removed
---
function _M:unsubscribeSession(realm, subscId, regId)
local subscIdStr = formatNumber(subscId)
local regIdStr = formatNumber(regId)
local subscr = redis:hget("wiRealm" .. realm .. "RevSubs", subscIdStr)
local isSesSubscrbd = redis:sismember("wiRealm" .. realm .. "Sub" .. subscr .. "Sessions", regIdStr)
local wasTopicRemoved = false
redis:srem("wiRealm" .. realm .. "Sub" .. subscr .. "Sessions", regIdStr)
redis:del("wiRealm" .. realm .. "Sub" .. subscr .. "Session" .. regIdStr)
if redis:scard("wiRealm" .. realm .. "Sub" .. subscr .. "Sessions") == 0 then
redis:del("wiRealm" .. realm .. "Sub" .. subscr .. "Sessions")
redis:hdel("wiRealm" .. realm .. "Subs", subscr)
redis:hdel("wiRealm" .. realm .. "RevSubs", subscIdStr)
redis:del("wiRealm" .. realm .. "Sub" .. subscr)
wasTopicRemoved = true
end
return isSesSubscrbd, wasTopicRemoved
end
---
--- Get sessions subscribed to topic
---
--- @param realm string realm
--- @param subscId number subscription Id
--- @return table array of session Ids subscribed to subscription
---
function _M:getTopicSessionsBySubId(realm, subscId)
local uri = redis:hget("wiRealm" .. realm .. "RevSubs", formatNumber(subscId))
if uri ~= ngx.null then
return redis:smembers("wiRealm" .. realm .. "Sub" .. uri .. "Sessions")
else
return nil
end
end
---
--- Get count of sessions subscribed to topic
---
--- @param realm string realm
--- @param subscId number subscription Id
--- @return table array of session Ids subscribed to subscription
---
function _M:getTopicSessionsCountBySubId(realm, subscId)
local uri = redis:hget("wiRealm" .. realm .. "RevSubs", formatNumber(subscId))
if uri ~= ngx.null then
return redis:scard("wiRealm" .. realm .. "Sub" .. uri .. "Sessions")
else
return nil
end
end
---
--- Get sessions subscribed to topic
---
--- @param realm string realm
--- @param uri string subscription uri
--- @return table array of session Ids subscribed to topic
---
function _M:getTopicSessions(realm, uri)
return redis:smembers("wiRealm" .. realm .. "Sub" .. uri .. "Sessions")
end
---
--- Get sessions to deliver event
---
--- @param realm string realm
--- @param uri string subscription uri
--- @param regId number session registration Id
--- @param options table advanced profile options
--- @return table array of session Ids to deliver event
---
function _M:getEventRecipients(realm, uri, regId, options)
local regIdStr = formatNumber(regId)
local recipients = {}
local details = {}
local exactSubsIdStr = redis:hget("wiRealm" .. realm .. "Subs", uri)
local exactSubsId = tonumber(exactSubsIdStr)
if options.disclose_me ~= nil and options.disclose_me == true then
details.publisher = regId
end
if options.trustlevel ~= nil then
details.trustlevel = options.trustlevel
end
if type(exactSubsId) == "number" and exactSubsId > 0 then
-- we need to find sessions with exact subscription
local ss = redis:smembers("wiRealm" .. realm .. "Sub" .. uri .. "Sessions")
local exactSessions = {}
for _, sesValue in ipairs(ss) do
local matchPolicy = redis:hget("wiRealm" .. realm .. "Sub" .. uri .. "Session" .. sesValue,
"matchPolicy")
if matchPolicy == "exact" then
table.insert(exactSessions, sesValue)
end
end
if #exactSessions > 0 then
table.insert(recipients, {
subId = exactSubsId,
sessions = self:filterEventRecipients(regIdStr, options, exactSessions),
details = details
})
end
end
-- Now lets find all patternBased subscriptions and their sessions
local allSubs = redis:hkeys("wiRealm" .. realm .. "Subs")
local matchedUris = findPatternedUri(allSubs, uri)
details.topic = uri
-- now we need to find sessions within matched Subs with pattern based subscription
for _, uriValue in ipairs(matchedUris) do
local ss = redis:smembers("wiRealm" .. realm .. "Sub" .. uriValue .. "Sessions")
local patternSessions = {}
for _, sesValue in ipairs(ss) do
local matchPolicy = redis:hget("wiRealm" .. realm .. "Sub" .. uriValue .. "Session" .. sesValue,
"matchPolicy")
if matchPolicy ~= "exact" then
table.insert(patternSessions, sesValue)
end
end
if #patternSessions > 0 then
table.insert(recipients, {
subId = tonumber(redis:hget("wiRealm" .. realm .. "Subs", uriValue)),
sessions = self:filterEventRecipients(regIdStr, options, patternSessions),
details = details
})
end
end
return recipients
end
---
--- Filter subscribers in subscription for event
---
--- @param regIdStr string session registration Id (as string)
--- @param options table advanced profile options
--- @param sessionsIdList table subscribers sessions Id list
--- @return table array of session Ids to deliver event
---
function _M:filterEventRecipients(regIdStr, options, sessionsIdList)
local recipients
local tmpK = "wiSes" .. regIdStr .. "TmpSetK"
local tmpL = "wiSes" .. regIdStr .. "TmpSetL"
for _, v in ipairs(sessionsIdList) do
redis:sadd(tmpK, formatNumber(v))
end
if options.eligible then -- There is eligible list
for _, v in ipairs(options.eligible) do
redis:sadd(tmpL, formatNumber(v))
end
redis:sinterstore(tmpK, tmpK, tmpL)
redis:del(tmpL)
end
if options.eligible_authid then -- There is eligible authid list
for _, v in ipairs(redis:smembers(tmpK)) do
local s = redis:array_to_hash(redis:hgetall("wiSes" .. formatNumber(v)))
for i = 1, #options.eligible_authid do
if s.wampFeatures.authid == options.eligible_authid[i] then
redis:sadd(tmpL, formatNumber(s.sessId))
end
end
end
redis:sinterstore(tmpK, tmpK, tmpL)
redis:del(tmpL)
end
if options.eligible_authrole then -- There is eligible authrole list
for _, v in ipairs(redis:smembers(tmpK)) do
local s = redis:array_to_hash(redis:hgetall("wiSes" .. formatNumber(v)))
for i = 1, #options.eligible_authrole do
if s.wampFeatures.authrole == options.eligible_authrole[i] then
redis:sadd(tmpL, formatNumber(s.sessId))
end
end
end
redis:sinterstore(tmpK, tmpK, tmpL)
redis:del(tmpL)
end
if options.exclude then -- There is exclude list
for _, v in ipairs(options.exclude) do
redis:sadd(tmpL, formatNumber(v))
end
redis:sdiffstore(tmpK, tmpK, tmpL)
redis:del(tmpL)
end
if options.exclude_authid then -- There is exclude authid list
for _, v in ipairs(redis:smembers(tmpK)) do
local s = redis:array_to_hash(redis:hgetall("wiSes" .. formatNumber(v)))
for i = 1, #options.exclude_authid do
if s.wampFeatures.authid == options.exclude_authid[i] then
redis:sadd(tmpL, formatNumber(s.sessId))
end
end
end
redis:sdiffstore(tmpK, tmpK, tmpL)
redis:del(tmpL)
end
if options.exclude_authrole then -- There is exclude authrole list
for _, v in ipairs(redis:smembers(tmpK)) do
local s = redis:array_to_hash(redis:hgetall("wiSes" .. formatNumber(v)))
for i = 1, #options.exclude_authrole do
if s.wampFeatures.authrole == options.exclude_authrole[i] then
redis:sadd(tmpL, formatNumber(s.sessId))
end
end
end
redis:sdiffstore(tmpK, tmpK, tmpL)
redis:del(tmpL)
end
if options.exclude_me == nil or options.exclude_me == true then
redis:sadd(tmpL, regIdStr)
redis:sdiffstore(tmpK, tmpK, tmpL)
redis:del(tmpL)
end
recipients = redis:smembers(tmpK)
redis:del(tmpK)
return recipients
end
---
--- Get subscriptions ids list
---
--- @param realm string realm
--- @return table array of subscriptions Ids
---
function _M:getSubscriptions(realm)
local subsIds = { exact = {}, prefix = {}, wildcard = {} }
-- TODO Make count of prefix/wildcard subscriptions
local allSubs = redis:array_to_hash(redis:hgetall("wiRealm" .. realm .. "Subs"))
--for k, v in pairs(allSubs) do
--
--end
return subsIds
end
---
--- Get registered RPC info (if exists)
---
--- @param realm string realm
--- @param uri string RPC registration uri
--- @return table RPC object
---
function _M:getRPC(realm, uri)
local rpc = redis:hgetall("wiRealm" .. realm .. "RPC" .. uri)
if #rpc < 2 then -- no exactly matched rpc uri found
local allRPCs = redis:smembers("wiRealm" .. realm .. "RPCs")
local patternRPCs = {}
for _, value in ipairs(allRPCs) do
local rp = redis:hget("wiRealm" .. realm .. "RPC" .. value, "matchPolicy")
if rp ~= ngx.null and rp ~= "exact" then
table.insert(patternRPCs, value)
end
end
local matchedUri = findPatternedUri(patternRPCs, uri, false)[1]
if matchedUri then
rpc = redis:array_to_hash(redis:hgetall("wiRealm" .. realm .. "RPC" .. matchedUri))
rpc.options = { procedure = uri }
else
return nil
end
else
rpc = redis:array_to_hash(rpc)
end
rpc.calleeSesId = tonumber(rpc.calleeSesId)
rpc.registrationId = tonumber(rpc.registrationId)
return rpc
end
---
--- Register session RPC
---
--- @param realm string realm
--- @param uri string RPC registration uri
--- @param options table registration options
--- @param regId number session registration Id
--- @return number RPC registration Id
---
function _M:registerSessionRPC(realm, uri, options, regId)
local registrationId, registrationIdStr
local regIdStr = formatNumber(regId)
if redis:sismember("wiRealm" .. realm .. "RPCs", uri) ~= 1 then
registrationId = self:getRegId()
registrationIdStr = formatNumber(registrationId)
redis:sadd("wiRealm" .. realm .. "RPCs", uri)
redis:hmset("wiRealm" .. realm .. "RPC" .. uri,
"calleeSesId", regIdStr,
"registrationId", registrationIdStr,
"matchPolicy", options.match or "exact")
if options.disclose_caller ~= nil and options.disclose_caller == true then
redis:hmset("wiRPC" .. uri, "disclose_caller", true)
end
redis:hset("wiSes" .. regIdStr .. "RPCs", uri, registrationIdStr)
redis:hset("wiSes" .. regIdStr .. "RevRPCs", registrationIdStr, uri)
end
return registrationId
end
---
--- Register Meta API RPCs, which are defined in config
---
--- @param realm string realm
---
function _M:registerMetaRpc(realm)
local uris = {}
if config.metaAPI.session == true then
table.insert(uris, 'wamp.session.count')
table.insert(uris, 'wamp.session.list')
table.insert(uris, 'wamp.session.get')
end
if config.metaAPI.subscription == true then
table.insert(uris, 'wamp.subscription.list')
table.insert(uris, 'wamp.subscription.lookup')
table.insert(uris, 'wamp.subscription.match')
table.insert(uris, 'wamp.subscription.get')
table.insert(uris, 'wamp.subscription.list_subscribers')
table.insert(uris, 'wamp.subscription.count_subscribers')
end
if config.metaAPI.registration == true then
table.insert(uris, 'wamp.registration.list')
table.insert(uris, 'wamp.registration.lookup')
table.insert(uris, 'wamp.registration.match')
table.insert(uris, 'wamp.registration.get')
table.insert(uris, 'wamp.registration.list_callees')
table.insert(uris, 'wamp.registration.count_callees')
end
local registrationId, registrationIdStr
for _, uri in ipairs(uris) do
if redis:sismember("wiRealm" .. realm .. "RPCs", uri) ~= 1 then
registrationId = self:getRegId()
registrationIdStr = formatNumber(registrationId)
redis:sadd("wiRealm" .. realm .. "RPCs", uri)
redis:hmset("wiRealm" .. realm .. "RPC" .. uri,
"calleeSesId", "0",
"registrationId", registrationIdStr)
end
end
end
---
--- Unregister session RPC
---
--- @param realm string realm
--- @param registrationId number RPC registration Id
--- @param regId number session registration Id
--- @return table RPC object
---
function _M:unregisterSessionRPC(realm, registrationId, regId)
local regIdStr = formatNumber(regId)
local registrationIdStr = formatNumber(registrationId)
local rpc = redis:hget("wiSes" .. regIdStr .. "RevRPCs", registrationIdStr)
if rpc ~= ngx.null then
redis:hdel("wiSes" .. regIdStr .. "RPCs", rpc)
redis:hdel("wiSes" .. regIdStr .. "RevRPCs", registrationIdStr)
redis:del("wiRealm" .. realm .. "RPC" .. rpc)
redis:srem("wiRealm" .. realm .. "RPCs", rpc)
end
return rpc
end
---
--- Get invocation info
---
--- @param invocReqId number invocation request Id
--- @return table Invocation object
---
function _M:getInvocation(invocReqId)
local invoc = redis:array_to_hash(redis:hgetall("wiInvoc" .. formatNumber(invocReqId)))
invoc.CallReqId = tonumber(invoc.CallReqId)
invoc.CallReqId = tonumber(invoc.CallReqId)
return invoc
end
---
--- Remove invocation
---
--- @param invocReqId number invocation request Id
---
function _M:removeInvocation(invocReqId)
redis:del("wiInvoc" .. formatNumber(invocReqId))
end
---
--- Get call info
---
--- @param callReqId number call request Id
--- @return table Call object
---
function _M:getCall(callReqId)
local call = redis:array_to_hash(redis:hgetall("wiCall" .. formatNumber(callReqId)))
call.calleeSesId = tonumber(call.calleeSesId)
call.wiInvocId = tonumber(call.wiInvocId)
return call
end
---
--- Remove call
---
--- @param callReqId number call request Id
---
function _M:removeCall(callReqId)
redis:del("wiCall" .. formatNumber(callReqId))
end
---
--- Add RPC Call & invocation
---
--- @param callReqId number call request Id
--- @param callerSessId number caller session registration Id
--- @param invocReqId number invocation request Id
--- @param calleeSessId number callee session registration Id
---
function _M:addCallInvocation(callReqId, callerSessId, invocReqId, calleeSessId)
local callReqIdStr = formatNumber(callReqId)
local callerSessIdStr = formatNumber(callerSessId)
local invocReqIdStr = formatNumber(invocReqId)
local calleeSessIdStr = formatNumber(calleeSessId)
redis:hmset("wiCall" .. callReqIdStr,
"callerSesId", callerSessIdStr,
"calleeSesId", calleeSessIdStr,
"wiInvocId", invocReqIdStr)
redis:hmset("wiInvoc" .. invocReqIdStr,
"CallReqId", callReqIdStr,
"callerSesId", callerSessIdStr)
end
return _M
|
Chest = {}
Chest.__index = Chest
function Chest.create()
local chst = GameObject.create()
setmetatable(chst,Chest)
chst.name = "Chest"
chst.physics.enabled = true
chst.physics.mass = 10
chst.physics.drag = 0.01
chst.physics.type = "dynamic"
chst.physics.trigger = "learnspell"
chst.opened = false
chst.sprite = {}
chst.sprite.open = love.graphics.newImage("sprites/chest_open.png")
chst.sprite.open:setFilter( "nearest", "nearest")
chst.sprite.closed = love.graphics.newImage("sprites/chest_closed.png")
chst.sprite.closed:setFilter( "nearest", "nearest")
chst.physics.collisionFilter = function(item, other)
return 'cross'
end
return chst
end
function Chest:load()
if self.physics.enabled == true then
world:add(self, self.position.x-(self.width/2), self.position.y-(self.height/2), self.width, self.height)
end
end
function Chest:update()
if self.physics.enabled == true then
physics(self, self.physics.collisionFilter)
end
end
function Chest:draw()
if self.sprite then
if self.opened then
love.graphics.draw(self.sprite.open, self.position.x, self.position.y, self.rotation, self.scale.x, self.scale.y, self.offset.x, self.offset.y)
else
love.graphics.draw(self.sprite.closed, self.position.x, self.position.y, self.rotation, self.scale.x, self.scale.y, self.offset.x, self.offset.y)
end
end
end
function Chest:onCollide(col)
end
function Chest:giveSpell(spell)
table.insert(gs.player.spells, spell)
-- for i=1,table.getn(spellbook) do
-- local hasSpell = false
-- for j=1,table.getn(gs.player.spells) do
-- if spellbook[i].name == gs.player.spells[j] then
-- hasSpell = true
-- end
-- end
-- if hasSpell == false then
-- table.insert(gs.player.spells, spell)
-- break
-- end
-- end
end |
workspace "DRMS"
architecture "x64"
configurations {
"Debug",
"Release",
"Distribution"
}
outputDir = "$(Configuration)-$(Platform)"
solutionDir = "$(SolutionDir)"
configurationMacro = "$(Configuration)"
platformMacro = "$(Platform)"
projectNameMacro = "$(ProjectName)"
---------- DRMS project description ----------
project "DRMS"
location "DRMS"
kind "ConsoleApp"
language "C++"
targetdir ("$(SolutionDir)bin/" .. outputDir .. "/DRMS")
objdir ("$(SolutionDir)intDir/" .. outputDir .. "/$(ProjectName)")
pchheader "drmsafx.h"
pchsource "DRMS/src/drmsafx.cpp"
files {
"DRMS/**.txt",
"DRMS/**.h",
"DRMS/**.cpp",
"DRMS/src/**.h",
"DRMS/src/**.cpp",
"DRMS/src/**.txt",
}
includedirs {
"$(SolutionDir)DRMS/src",
}
libdirs {
}
links {
}
filter "system:windows"
cppdialect "C++17"
staticruntime "On"
systemversion "latest"
defines {
"DRMS_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "DRMS_DEBUG"
symbols "On"
filter "configurations:Release"
defines "DRMS_RELEASE"
optimize "On"
filter "configurations:Distribution"
defines "DRMS_DISTRIBUTION"
optimize "On" |
--[[ Backwards compat for Lua 5.3; only loaded in 5.3 because package.loaded is
prepopulated with the existing global bit32 in 5.2. ]]
local bit32 = {}
-------------------------------------------------------------------------------
local function fold(init, op, ...)
local result = init
local args = table.pack(...)
for i = 1, args.n do
result = op(result, args[i])
end
return result
end
local function trim(n)
return n & 0xFFFFFFFF
end
local function mask(w)
return ~(0xFFFFFFFF << w)
end
function bit32.arshift(x, disp)
return x // (2 ^ disp)
end
function bit32.band(...)
return fold(0xFFFFFFFF, function(a, b) return a & b end, ...)
end
function bit32.bnot(x)
return ~x
end
function bit32.bor(...)
return fold(0, function(a, b) return a | b end, ...)
end
function bit32.btest(...)
return bit32.band(...) ~= 0
end
function bit32.bxor(...)
return fold(0, function(a, b) return a ~ b end, ...)
end
local function fieldargs(f, w)
w = w or 1
assert(f >= 0, "field cannot be negative")
assert(w > 0, "width must be positive")
assert(f + w <= 32, "trying to access non-existent bits")
return f, w
end
function bit32.extract(n, field, width)
local f, w = fieldargs(field, width)
return (n >> f) & mask(w)
end
function bit32.replace(n, v, field, width)
local f, w = fieldargs(field, width)
local m = mask(w)
return (n & ~(m << f)) | ((v & m) << f)
end
function bit32.lrotate(x, disp)
if disp == 0 then return x
elseif disp < 0 then return bit32.rrotate(x, -disp)
else return trim((x << disp) | (x >> (32 - disp))) end
end
function bit32.lshift(x, disp)
return trim(x << disp)
end
function bit32.rrotate(x, disp)
if disp == 0 then return x
elseif disp < 0 then return bit32.lrotate(x, -disp)
else return trim((x >> disp) | (x << (32 - disp))) end
end
function bit32.rshift(x, disp)
return trim(x >> disp)
end
-------------------------------------------------------------------------------
return bit32
|
local platform = { }
for k,v in next, {'windows', 'linux', 'osx'} do
platform[v] = require('Platforms.'..v)
platform[v].name = v
end
local valid = { }
for k,v in next, platform do
if v:is() then table.insert(valid, k) end
end
if #valid == 0 then
error('Unable to determine host platform')
elseif #valid > 1 then
error('Ambiguous platform: ' .. table.concat(valid, ', '))
end
platform.host = platform[valid[1]]
print('platform: ', platform.host.name)
print('architecture: ', platform.host:arch())
return platform
|
local clang = require 'clang'
local index = clang.Index()
local unsaved = {['x.c']='int fun;\nint main() {int v;return f;}'}
local unit = index:parse('x.c', {'-Wall'}, unsaved, {clang.TranslationUnit.PrecompiledPreamble})
unit:reparse(unsaved)
local cursor = unit.cursor
print('Root cursor:', cursor.kind.string, cursor.spelling)
cursor:visit(function(cursor)
print('Visiting:', cursor.kind.string, cursor.spelling)
local compl = cursor:get_completion_string()
print('Priority:', compl.priority)
print('Chunks:')
for _, c in ipairs(compl.chunks) do
print('Text:', c.text)
end
return cursor.visit_recurse -- or clang.Cursor.visit_recurse
end)
for i, v in ipairs(cursor:get_children()) do
print('Child:', v.kind.string, v.spelling)
end
print()
local completion_results = unit:complete_at('x.c', 2, 26, unsaved)
for _, result in pairs(completion_results.results) do
print('Completion result:', result.kind.string)
print('Chunks:')
for _, c in ipairs(result.string.chunks) do
print('Text:', c.text)
print('Kind:', c.kind.string)
end
end
|
local compute = require('hamming').compute
describe('hamming', function ()
it('no difference between identical strands', function ()
assert.are.equal(0, compute('A', 'A'))
end)
it('long identical strands', function ()
assert.are.equal(0, compute('GGACTGA', 'GGACTGA'))
end)
it('complete hamming distance of for single nucleotide strand', function ()
assert.are.equal(1, compute('A', 'G'))
end)
it('complete hamming distance of for small strand', function ()
assert.are.equal(2, compute('AG', 'CT'))
end)
it('small hamming distance', function ()
assert.are.equal(1, compute('AT', 'CT'))
end)
it('small hamming distance in longer strand', function ()
assert.are.equal(1, compute('GGACG', 'GGTCG'))
end)
it('non unique character in first strand', function ()
assert.are.equal(1, compute('AGA', 'AGG'))
end)
it('non unique character in second strand', function ()
assert.are.equal(1, compute('AGG', 'AGA'))
end)
it('large hamming distance', function ()
assert.are.equal(4, compute('GATACA', 'GCATAA'))
end)
it('hamming distance in very long strand', function ()
assert.are.equal(9, compute('GGACGGATTCTG', 'AGGACGGATTCT'))
end)
it('empty strands', function ()
assert.are.equal(0, compute('', ''))
end)
it('disallow first strand longer', function ()
assert.are.equal(-1, compute('AATG', 'AAA'))
end)
it('disallow second strand longer', function ()
assert.are.equal(-1, compute('ATA', 'AGTG'))
end)
end)
|
#!/usr/local/openresty/bin/resty
-- Copyright (C) 2020 by chrono
-- resty redis.lua
local cjson = require "cjson.safe"
local redis = require "resty.redis"
local rds = redis:new()
rds:set_timeout(1000) -- 1 sec
local ok,err
local res
ok, err = rds:connect("127.0.0.1",6379)
if not ok then
ngx.say("failed to connect : ", err)
rds:close()
return
end
--assert(ok)
-- test auth
--ok, err = rds:auth('12345')
--ngx.say('auth = ', ok, ' err = ', err)
local topic = 'mq'
local group = 'test_group'
local consumer = 'test_consumer'
res, err = rds:xlen(topic)
local mq_len = tonumber(res)
print(mq_len)
if mq_len == 0 then
for i=1,3 do
ok, err = rds:xadd(topic, '*', "name", i * 100)
assert(ok)
end
end
-- read all
res, err = rds:xread('count', mq_len, 'streams', topic, 0)
if err then
print('xread err: ', err)
end
-- [["mq",[["1608704712917-0",["name","100"]],["1608704712919-0",["name","200"]],["1608704712919-1",["name","300"]]]]]
print(cjson.encode(res))
assert(res[1][1] == topic)
local values = res[1][2]
for i,v in ipairs(values) do
print('#', i)
print('msg id = ', v[1])
print('msg key = ', v[2][1])
print('msg value = ', v[2][2])
end
-- xgroup
ok, err = rds:xgroup('create', topic, group, 0)
if err then
if string.find(err, 'BUSYGROUP', 1, true) then
print('group already exists')
else
print('xgroup err: ', err)
end
end
-- read a msg
res, err = rds:xreadgroup('group', group, consumer,
'count', 1, 'streams', topic, '>')
if err then
print('xread err: ', err)
end
-- [["mq",[["1608704712917-0",["name","100"]]]]]
print(cjson.encode(res))
if res == ngx.null or #res[1][2] == 0 then
print('mq is all consumed')
else
local msg_id = res[1][2][1][1]
--ok, err = rds:xack(topic, group, msg_id)
print('xack msg = ', msg_id)
end
-- check not acked
res, err = rds:xpending(topic, group)
-- [1,"1608704712917-0","1608704712917-0",[["test_consumer","1"]]]
print(cjson.encode(res))
-- get all pending msg
res, err = rds:xpending(topic, group, '-', '+', 10)
-- [["1608704712917-0","test_consumer",0,1]]
print(cjson.encode(res))
-- clear redis
--rds:del(topic)
ngx.say('redis ok')
|
RegisterCommand('laptop', function(source, args, rawCommand)
local src = source
TriggerClientEvent('laptop:client/openUI', src)
end, false) |
-- ---------------------------------------------------------------
-- Example Trigger filters (paste into "filter by" script box
-- in the trigger list).
-- ---------------------------------------------------------------
function send_to_script (name, trigger)
return trigger.send_to == sendto.script and
trigger.enabled
end -- send_to_script
function enabled (name, trigger)
return trigger.enabled
end -- enabled
function disabled (name, trigger)
return not trigger.enabled
end -- disabled
function keep_evaluating (name, trigger)
return trigger.keep_evaluating
end -- keep_evaluating
function badscript (name, trigger)
return not trigger.script_valid and
trigger.script ~= ""
end -- badscript
function temporary (name, trigger)
return trigger.temporary
end -- temporary
function matched (name, trigger)
return trigger.times_matched > 0
end -- matched
function unmatched (name, trigger)
return trigger.times_matched == 0
end -- unmatched
-- if they cancel, show everything
function everything (name, trigger)
return true
end -- everything
-- choose which function to use
result = utils.listbox ("Choose type of filtering", "Triggers",
{
send_to_script = "Send to script and enabled",
enabled = "Enabled items",
disabled = "Disabled items",
badscript = "Script name not found",
keep_evaluating = "Keep evaluating",
temporary = "Temporary triggers",
matched = "Ones that matched something",
unmatched = "Ones that never matched",
},
"badscript") -- default
-- use that function
filter = _G [result] or everything
-- ---------------------------------------------------------------
-- Example Alias filters (paste into "filter by" script box
-- in the alias list).
-- ---------------------------------------------------------------
function send_to_script (name, alias)
return alias.send_to == sendto.script and
alias.enabled
end -- send_to_script
function enabled (name, alias)
return alias.enabled
end -- enabled
function disabled (name, alias)
return not alias.enabled
end -- disabled
function keep_evaluating (name, alias)
return alias.keep_evaluating
end -- keep_evaluating
function badscript (name, alias)
return not alias.script_valid and
alias.script ~= ""
end -- badscript
function temporary (name, alias)
return alias.temporary
end -- temporary
function matched (name, alias)
return alias.times_matched > 0
end -- matched
function unmatched (name, alias)
return alias.times_matched == 0
end -- unmatched
-- if they cancel, show everything
function everything (name, alias)
return true
end -- everything
-- choose which function to use
result = utils.listbox ("Choose type of filtering", "Aliases",
{
send_to_script = "Send to script and enabled",
enabled = "Enabled items",
disabled = "Disabled items",
badscript = "Script name not found",
keep_evaluating = "Keep evaluating",
temporary = "Temporary aliases",
matched = "Ones that matched something",
unmatched = "Ones that never matched",
},
"badscript") -- default
-- use that function
filter = _G [result] or everything
-- ---------------------------------------------------------------
-- Example Timer filters (paste into "filter by" script box
-- in the timer list).
-- ---------------------------------------------------------------
function send_to_script (name, timer)
return timer.send_to == sendto.script and
timer.enabled
end -- send_to_script
function enabled (name, timer)
return timer.enabled
end -- enabled
function disabled (name, timer)
return not timer.enabled
end -- disabled
function one_shot (name, timer)
return timer.one_shot
end -- one_shot
function badscript (name, timer)
return not timer.script_valid and
timer.script ~= ""
end -- badscript
function temporary (name, timer)
return timer.temporary
end -- temporary
function fired (name, timer)
return timer.times_fired > 0
end -- fired
function not_fired (name, timer)
return timer.times_fired == 0
end -- not_fired
-- if they cancel, show everything
function everything (name, timer)
return true
end -- everything
-- choose which function to use
result = utils.listbox ("Choose type of filtering", "Timers",
{
send_to_script = "Send to script and enabled",
enabled = "Enabled items",
disabled = "Disabled items",
badscript = "Script name not found",
one_shot = "One-shot timers",
temporary = "Temporary timers",
fired = "Ones that fired",
not_fired = "Ones that never fired",
},
"badscript") -- default
-- use that function
filter = _G [result] or everything
|
vim.g.mapleader = ','
vim.o.termguicolors=true
vim.o.number=true
vim.o.tabstop=2
vim.o.shiftwidth=2
vim.o.softtabstop=2
-- replace tabs to spaces
vim.o.expandtab = true
-- only even number of spaces (3 spaces + tab = 4 spaces, 2 spaces + tab = 4 spaces)
vim.o.smarttab = true
-- reduce redraw
vim.o.lazyredraw=true
-- disable ring
vim.o.errorbells=false
vim.o.visualbell=false
-- divider
vim.o.fillchars='vert:ǀ'
-- vim.o.fillchars=vert:│,stl:\ ,stlnc:\
-- vim.o.list lcs=tab:\ \ ,conceal:\|
-- deafult split location
vim.o.splitbelow=true
vim.o.splitright=true
-- disable line wrap
vim.o.wrap = false
-- minimum reserve line when scrolling
vim.o.scrolloff=5
vim.o.backspace='2'
vim.o.encoding='UTF-8'
-- vim.o.filetype='on'
-- filetype plugin on
-- copy vim -> os clipboard
vim.o.clipboard='unnamed'
vim.o.langmenu='zh_CN.UTF-8'
-- show match space
vim.o.showmatch=true
-- search stuff
vim.o.hlsearch=true
vim.o.ignorecase=true
vim.o.smartcase=true
-- disable backup even gen a swap file
vim.o.backup=false
vim.o.swapfile=false
vim.o.writebackup=false
vim.o.autoread=true
-- avoid change buffer before you save current file.
vim.o.hidden=true
vim.o.laststatus = 2
-- size of the saved command-lines in a history table
vim.o.history = 1000
|
levels[21]={timeBetweenParticleCreation=150,weightBreakForTwoStars=500,weightBreakForThreeStars=700,numPortExplosionsWeight=125,numDiverterExplosionsWeight=25,numAntimatterExplosionsWeight=150,numParticlesInSinkWeight=50,numParticlesInPrisonWeight=50,background="5",particleSpeed=2,maxParticles=3,particlesToComplete=6,powerupFrequency=360,powerupProbability=80,antimatterProbability=70,data={{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","E","*","*","*","*","*","*","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","*","*","*","*","*","*","*","_","_","_","_","_","_","_","_","_","_","_","_","_","_","Q","H","H","H","H","H","H","H","H","W","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","*","*","*","*","*","*","*","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","Q","H","H","H","H","H","*","*","*","*","*","*","*","H","H","H","H","W","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","*","*","*","*","*","*","*","_","_","_","_","V","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","*","*","*","*","*","*","*","_","_","_","D","*","*","_","_","_","_","_","_","_","D","*","*","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","*","*","*","*","*","*","*","_","Q","H","*","*","*","H","H","H","H","H","H","H","*","*","*","H","H","H","H","H","H","H","K","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","*","*","*","_","_","_","_","_","_","_","*","*","*","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","V","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","R","*","*","*","*","_","_","_","V","_","_","V","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","*","*","*","*","*","_","_","Q","S","_","_","V","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","D","*","*","_","Q","H","H","*","*","*","*","*","H","H","S","Q","H","H","S","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","Q","H","*","*","*","H","S","_","_","*","*","*","*","*","_","_","_","V","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","*","*","*","_","_","_","_","*","*","*","*","*","_","_","D","*","*","_","_","_","_","_","N","*","*","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","V","_","_","_","_","_","_","_","V","_","_","_","Q","*","*","*","H","H","H","H","H","*","*","*","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","V","_","_","_","_","Q","H","H","S","_","_","_","V","*","*","*","_","_","_","_","_","*","*","*","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","V","_","_","_","D","*","*","_","_","_","_","_","V","_","V","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","E","*","*","*","*","*","*","_","_","_","_","_","V","_","_","A","H","H","H","*","*","*","H","H","H","H","H","C","W","A","H","H","H","H","H","H","H","W","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","*","*","*","*","*","*","*","_","_","_","_","_","V","_","_","_","_","_","_","*","*","*","_","_","_","_","_","V","A","H","H","H","H","W","_","_","_","V","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","*","*","*","*","*","*","*","_","_","_","_","_","V","_","_","I","*","*","_","_","V","_","_","_","_","_","_","V","_","_","_","B","*","*","*","*","_","V","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","*","*","*","*","*","*","*","H","H","H","H","H","K","_","_","*","*","*","_","_","V","_","_","_","_","Y","*","*","*","*","_","*","*","*","*","*","_","V","_","_","_","_","V","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","*","*","*","*","*","*","*","_","_","_","_","_","V","_","_","*","*","*","_","_","A","W","_","_","_","*","*","*","*","*","_","*","*","*","*","*","H","S","_","_","Q","H","S","_","_","_","_","_","_","_","_","V","_","_","_","_"},{"_","*","*","*","*","*","*","*","_","_","_","_","_","V","_","_","_","V","_","_","_","D","*","*","_","_","*","*","*","*","*","_","*","*","*","*","*","_","_","_","_","V","_","_","_","_","_","_","_","E","*","*","*","*","*","*","_"},{"_","*","*","*","*","*","*","*","_","_","_","_","_","A","H","H","W","A","H","H","H","*","*","*","W","_","*","*","*","*","*","_","*","*","*","*","*","_","_","_","_","V","_","_","_","_","_","_","_","*","*","*","*","*","*","*","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","V","_","_","_","_","*","*","*","V","_","*","*","*","*","*","_","_","_","_","_","_","_","_","G","*","*","*","*","_","_","_","_","_","*","*","*","*","*","*","*","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","D","*","*","_","_","_","_","V","_","V","_","_","_","V","_","_","_","_","_","_","_","_","_","_","*","*","*","*","*","_","_","_","_","_","*","*","*","*","*","*","*","_"},{"_","_","_","_","I","*","*","_","_","_","_","_","_","Q","H","*","*","*","H","H","H","H","K","_","A","H","H","H","S","_","_","_","_","_","_","_","_","_","_","*","*","*","*","*","_","_","_","_","_","*","*","*","*","*","*","*","_"},{"_","_","_","_","*","*","*","H","H","H","H","H","H","S","_","*","*","*","_","_","_","_","V","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","*","*","*","*","*","_","_","_","_","_","*","*","*","*","*","*","*","_"},{"_","_","_","_","*","*","*","_","_","_","_","_","_","_","_","_","A","H","H","H","H","H","S","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","*","*","*","*","*","_","_","_","_","_","*","*","*","*","*","*","*","_"},{"_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"}}}; |
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod = BigWigs:NewPlugin("Flash")
if not mod then return end
--------------------------------------------------------------------------------
-- Locals
--
local flashFrame, pulseFrame = nil, nil
local flasher, pulser = nil, nil
local colors = nil
-------------------------------------------------------------------------------
-- Initialization
--
do
flashFrame = UIParent:CreateTexture()
flashFrame:SetAllPoints(UIParent)
flashFrame:SetAlpha(0)
flashFrame:SetColorTexture(0, 0, 1, 0.6)
flashFrame:Hide()
flasher = flashFrame:CreateAnimationGroup()
flasher:SetScript("OnFinished", function() flashFrame:Hide() end)
local fade1 = flasher:CreateAnimation("Alpha")
fade1:SetDuration(0.2)
fade1:SetFromAlpha(0)
fade1:SetToAlpha(1)
fade1:SetOrder(1)
local fade2 = flasher:CreateAnimation("Alpha")
fade2:SetDuration(0.2)
fade2:SetFromAlpha(1)
fade2:SetToAlpha(0)
fade2:SetOrder(2)
local fade3 = flasher:CreateAnimation("Alpha")
fade3:SetDuration(0.2)
fade3:SetFromAlpha(0)
fade3:SetToAlpha(1)
fade3:SetOrder(3)
local fade4 = flasher:CreateAnimation("Alpha")
fade4:SetDuration(0.2)
fade4:SetFromAlpha(1)
fade4:SetToAlpha(0)
fade4:SetOrder(4)
pulseFrame = UIParent:CreateTexture()
pulseFrame:SetPoint("CENTER", UIParent, "CENTER")
pulseFrame:SetSize(100,100)
pulseFrame:SetAlpha(0.5)
pulseFrame:SetTexture(132337) -- Interface\\Icons\\ability_warrior_charge
pulseFrame:SetTexCoord(0.07, 0.93, 0.07, 0.93)
pulseFrame:Hide()
pulser = pulseFrame:CreateAnimationGroup()
pulser:SetScript("OnFinished", function() pulseFrame:Hide() end)
local pulse1 = pulser:CreateAnimation("Scale")
pulse1:SetDuration(0.25)
pulse1:SetScale(2.5,2.5)
pulse1:SetOrder(1)
pulse1:SetEndDelay(0.4)
local pulse2 = pulser:CreateAnimation("Scale")
pulse2:SetDuration(0.25)
pulse2:SetScale(0.2,0.2)
pulse2:SetOrder(2)
end
function mod:OnPluginEnable()
colors = BigWigs:GetPlugin("Colors")
self:RegisterMessage("BigWigs_Flash")
self:RegisterMessage("BigWigs_Pulse")
end
-------------------------------------------------------------------------------
-- Event Handlers
--
function mod:BigWigs_Flash(event, module, key)
if BigWigs.db.profile.flash then
flasher:Stop()
if colors then
local r, g, b = colors:GetColor("flash", module, key)
flashFrame:SetColorTexture(r, g, b, 0.6)
end
flashFrame:SetAlpha(0)
flashFrame:Show()
flasher:Play()
end
end
function mod:BigWigs_Pulse(event, _, _, icon)
pulser:Stop()
pulseFrame:SetTexture(icon or 134400) -- Interface\\Icons\\INV_Misc_QuestionMark
pulseFrame:Show()
pulser:Play()
end
|
data:extend(
{
{
type = "technology",
name = "coal-processing",
icon = "__Treefarm-Mod__/graphics/icons/charcoal.png",
effects = {
{
type = "unlock-recipe",
recipe = "charcoal"
},
{
type = "unlock-recipe",
recipe = "coal"
},
{
type = "unlock-recipe",
recipe = "coke-coal"
},
{
type = "unlock-recipe",
recipe = "ash"
},
{
type = "unlock-recipe",
recipe = "cokery"
}
},
prerequisites = {
"advanced-material-processing"
},
unit = {
count = 75,
ingredients = {
{"science-pack-1", 1},
{"science-pack-2", 1}
},
time = 30
}
},
{
type = "technology",
name = "fertilizer",
icon = "__Treefarm-Mod__/graphics/icons/fertilizer.png",
effects = {
{
type = "unlock-recipe",
recipe = "stone-crusher"
},
{
type = "unlock-recipe",
recipe = "crushed-stone"
},
{
type = "unlock-recipe",
recipe = "liquid-air"
},
{
type = "unlock-recipe",
recipe = "liquid-nitrogen"
},
{
type = "unlock-recipe",
recipe = "fill-liquid-nitrogen-barrel"
},
{
type = "unlock-recipe",
recipe = "empty-liquid-nitrogen-barrel"
},
{
type = "unlock-recipe",
recipe = "phosphate"
},
{
type = "unlock-recipe",
recipe = "potassium"
},
{
type = "unlock-recipe",
recipe = "fertilizer1"
},
{
type = "unlock-recipe",
recipe = "fertilizer2"
},
{
type = "unlock-recipe",
recipe = "hydroculture"
},
{
type = "unlock-recipe",
recipe = "biomass"
}
},
prerequisites = {
"fluid-handling"
},
unit = {
count = 100,
ingredients = {
{"science-pack-1", 1},
{"science-pack-2", 1}
},
time = 30
}
},
{
type = "technology",
name = "organic-plastic",
icon = "__Treefarm-Mod__/graphics/icons/cellulose.png",
effects = {
{
type = "unlock-recipe",
recipe = "cellulose"
},
{
type = "unlock-recipe",
recipe = "treefarm-mod-platic"
}
},
prerequisites = {
"fertilizer"
},
unit = {
count = 50,
ingredients = {
{"science-pack-1", 2},
{"science-pack-2", 2},
{"science-pack-3", 1}
},
time = 30
}
},
{
type = "technology",
name = "medicine",
icon = "__Treefarm-Mod__/graphics/icons/medicine.png",
effects = {
{
type = "unlock-recipe",
recipe = "nutrients"
},
{
type = "unlock-recipe",
recipe = "medicine"
}
},
prerequisites = {
"fertilizer"
},
unit = {
count = 75,
ingredients = {
{"science-pack-1", 2},
{"science-pack-2", 2},
{"science-pack-3", 1}
},
time = 45
}
},
}
) |
local Sprite = augment{}
--# Requires
local Predicates = require'Predicates'
--# Constants
Sprite.WIDTH, Sprite.HEIGHT = 16, 16
--# Helpers
local function palette_index_to_rgba(palette_index)
assert(Predicates.is_integer_in_range(0, 3)(palette_index), 'palette index must be 0, 1, 2, or 3')
if palette_index == 0 then
return 0 , 0 , 0 , 0
elseif palette_index == 1 then
return 0 , 0 , 0 , 1
elseif palette_index == 2 then
return 0.5, 0.5, 0.5, 1
else
return 1 , 1 , 1 , 1
end
end
local function rgba_to_palette_index(red, green, blue, alpha)
if alpha == 0 then
return 0
elseif red == 0 and green == 0 and blue == 0 and alpha == 1 then
return 1
elseif not (red == 1 and green == 1 and blue == 1 and alpha == 1) then
return 2
else
return 3
end
end
--# Interface
function Sprite.from_byte_string(byte_string)
assert(type(byte_string) == 'string', 'not a string')
local result = Sprite:new()
local byte_index = 1
for x = 0, Sprite.WIDTH - 1 do
for y = 0, Sprite.HEIGHT - 1 do
result:set_pixel(x, y,
tonumber(byte_string:sub(byte_index, byte_index)))
byte_index = byte_index + 1
end
end
return result
end
function Sprite.from_file(file_name)
return Sprite.from_image_data(love.image.newImageData(file_name))
end
function Sprite.from_image_data(image_data)
return Sprite:new(image_data)
end
function Sprite:initialize(source_image_data)
self.modified = false
self.image_data = love.image.newImageData(Sprite.WIDTH, Sprite.HEIGHT)
if source_image_data ~= nil then
self.image_data:paste(source_image_data, 0, 0)
end
self.image = love.graphics.newImage(self.image_data)
end
function Sprite:is_modified()
return self.modified
end
function Sprite:clear_modified()
self.modified = false
end
function Sprite:get_image()
return self.image
end
function Sprite:get_image_data()
return self.image_data
end
function Sprite:get_pixel(x, y)
return rgba_to_palette_index(self.image_data:getPixel(x, y))
end
function Sprite:set_pixel(x, y, palette_index)
self.image_data:setPixel(x, y, palette_index_to_rgba(palette_index))
self.image:replacePixels(self.image_data)
self.modified = true
end
function Sprite:to_byte_string()
local result = ''
for x = 0, Sprite.WIDTH - 1 do
for y = 0, Sprite.HEIGHT - 1 do
result = result .. tostring(self:get_pixel(x, y))
end
end
return result
end
function Sprite:to_image_data()
return self.image_data:clone()
end
--#
return Sprite
|
-- Autogenerated with DRAKON Editor 1.32
local table = table
local string = string
local pairs = pairs
local ipairs = ipairs
local type = type
local box = box
local tostring = tostring
local global_cfg = global_cfg
local clock = require("clock")
local log = require("log")
local digest = require("digest")
local fiber = require("fiber")
local fio = require("fio")
local json = require("json")
local utils = require("utils")
local users = box.space.users
local spaces = box.space.spaces
local folders = box.space.folders
local items = box.space.items
local usettings = box.space.usettings
local recent = box.space.recent
local creds = box.space.creds
local db = require(global_cfg.db)
local skip = {
id = true,
group = true
}
setfenv(1, {})
function fix_zombies()
-- item 242
local trash = db.trash_get_all()
for _, row in ipairs(trash) do
-- item 245
local space_id = row[1]
local folder_id = row[2]
-- item 246
db.folder_tree_delete(
space_id,
folder_id
)
end
end
function get_fdata(space_id, folder_id)
-- item 134
local tuple = folders:get{space_id, folder_id}
-- item 135
return tuple[3]
end
function grant(space_id, users, access)
-- item 202
if users then
for _, user_id in ipairs(users) do
-- item 207
db.rights_insert(
space_id,
user_id,
access,
{}
)
end
end
end
function import_folder_data(folder_id, content)
-- item 116
local parent = content.parent
-- item 112
if type(parent) == "table" then
-- item 118
if folder_id == "1" then
-- item 121
parent = nil
else
-- item 115
parent = "1"
end
end
-- item 72
local type = content.type
-- item 73
if type == "diagram" then
-- item 76
type = "drakon"
end
-- item 71
local data = {
name = content.name,
type = type,
parent = parent,
children = {},
tag = content.tag,
deleted = content.is_deleted
}
-- item 77
return data
end
function import_item_data(content)
-- item 98
local data = {}
for key, value in pairs(content) do
-- item 101
if skip[key] then
else
-- item 104
if key == "text" then
-- item 107
if content.content then
else
-- item 111
data.content = { txt = value }
end
else
-- item 110
data[key] = value
end
end
end
-- item 89
return data
end
function import_user_data(content, user_id)
-- item 154
local email = content.email
-- item 155
if ((email) and (type(email) == "string")) and (not (email == "")) then
else
-- item 159
email = "no_email-" .. user_id
end
-- item 153
local data = {
name = content.name,
enabled = content.is_active,
admin = content.is_admin,
spaces = {}
}
-- item 162
data.spaces[user_id] = true
-- item 163
return data, email
end
function move_rights()
-- item 222
local skip = true
-- item 177
local users = db.user_get_all()
local spaces = db.space_get_all()
for _, space in ipairs(spaces) do
-- item 178
local space_id = space[1]
local sdata = space[2]
-- item 183
grant(space_id, sdata.admins, "admin")
-- item 184
grant(space_id, sdata.readers, "read")
-- item 185
grant(space_id, sdata.writers, "write")
end
for _, user in ipairs(users) do
-- item 193
local user_id = user[1]
local email = user[2]
local data = user[3]
data.spaces = nil
-- item 194
db.user_update(
user_id,
email,
data
)
end
for _, space in ipairs(spaces) do
-- item 192
local space_id = space[1]
local sdata = space[2]
-- item 196
sdata.readers = nil
sdata.writers = nil
sdata.admins = nil
-- item 195
db.space_update(
space_id,
sdata
)
end
for _, space in ipairs(spaces) do
-- item 211
local space_id = space[1]
local sdata = db.space_get(space_id)
-- item 214
if sdata.trash then
for folder_id, dummy in pairs(sdata.trash) do
-- item 217
db.trash_insert(
space_id,
folder_id
)
end
-- item 220
sdata.trash = nil
-- item 221
db.space_update(
space_id,
sdata
)
end
end
-- item 226
local folders = db.folder_get_all()
for _, row in ipairs(folders) do
-- item 229
local space_id = row[1]
local folder_id = row[2]
local fdata = row[3]
-- item 231
if fdata.parent then
-- item 230
db.folder_tree_upsert(
space_id,
folder_id,
fdata.parent
)
end
end
for _, row in ipairs(folders) do
-- item 236
local space_id = row[1]
local folder_id = row[2]
local fdata = row[3]
-- item 237
fdata.parent = nil
fdata.children = nil
-- item 238
db.folder_update(
space_id,
folder_id,
fdata
)
end
end
function read_json_file(path)
-- item 23
local content = utils.read_all_bytes(path)
-- item 24
return json.decode(content)
end
function run_import()
-- item 13
local root = global_cfg.import
-- item 16
local user_files = fio.glob(root .. "/users/*")
-- item 27
log.info("%d users", #user_files)
for _, user_file in ipairs(user_files) do
-- item 30
local user_id = fio.basename(user_file)
-- item 142
log.info("user %s", user_id)
-- item 17
local content = read_json_file(user_file)
-- item 28
local data, email = import_user_data(content, user_id)
-- item 26
users:insert{user_id, email, data}
end
-- item 34
local cred_files = fio.glob(root .. "/creds/*")
-- item 35
log.info("%d creds", #cred_files)
for _, cred_file in ipairs(cred_files) do
-- item 38
local user_id = fio.basename(cred_file)
-- item 143
log.info("cred %s", user_id)
-- item 40
local content = read_json_file(cred_file)
-- item 41
local data = {
hash = digest.base64_decode(content.hash),
salt = digest.base64_decode(content.salt)
}
-- item 42
creds:insert{user_id, data}
end
-- item 49
local space_files = fio.glob(root .. "/spaces/*")
-- item 50
log.info("%d spaces", #space_files)
for _, space_file in ipairs(space_files) do
-- item 53
local space_id = fio.basename(space_file)
-- item 144
log.info("space %s", space_id)
-- item 55
local content = read_json_file(space_file)
-- item 56
local data = {
readers = content.readers,
writers = content.writers,
admins = content.admins,
next_id = content.next_id,
trash = utils.list_to_set(content.trash)
}
-- item 57
spaces:insert{space_id, data}
end
-- item 58
local folder_files = fio.glob(root .. "/folders/*")
-- item 59
log.info("%d folders", #folder_files)
for _, folder_file in ipairs(folder_files) do
-- item 62
local basename = fio.basename(folder_file)
local parts = utils.split(basename, "@")
local space_id = parts[1]
local folder_id = parts[2]
-- item 145
log.info("folder %s", basename)
-- item 63
local content = read_json_file(folder_file)
-- item 65
local data = import_folder_data(folder_id, content)
-- item 64
folders:insert{space_id, folder_id, data}
end
for _, folder_file in ipairs(folder_files) do
-- item 127
local basename = fio.basename(folder_file)
local parts = utils.split(basename, "@")
local space_id = parts[1]
local folder_id = parts[2]
-- item 146
log.info("folder parents %s", basename)
-- item 128
local fdata = get_fdata(space_id, folder_id)
-- item 136
if (fdata.deleted) or (not (fdata.parent)) then
else
-- item 140
local pdata = get_fdata(space_id, fdata.parent)
pdata.children[folder_id] = true
-- item 141
utils.update3(
folders,
space_id,
fdata.parent,
pdata
)
end
end
-- item 90
local item_files = fio.glob(root .. "/items/*")
-- item 91
log.info("%d items", #item_files)
for _, item_file in ipairs(item_files) do
-- item 94
local basename = fio.basename(item_file)
local parts = utils.split(basename, "@")
local space_id = parts[1]
local folder_id = parts[2]
local item_id = parts[3]
-- item 147
log.info("item %s", basename)
-- item 95
local content = read_json_file(item_file)
-- item 97
local data = import_item_data(content)
-- item 96
items:insert{space_id, folder_id, item_id, data}
end
-- item 117
log.info("import completed")
end
return {
run_import = run_import,
move_rights = move_rights,
fix_zombies = fix_zombies
}
|
norulac_raider_captain = Creature:new {
objectName = "@mob/creature_names:norulac_raider_captain",
randomNameType = NAME_GENERIC,
randomNameTag = true,
socialGroup = "norulac",
faction = "norulac_raiders",
level = 107,
chanceHit = 1.75,
damageMin = 670,
damageMax = 1050,
baseXp = 10081,
baseHAM = 29000,
baseHAMmax = 36000,
armor = 2,
resists = {55,55,70,45,75,80,55,45,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = KILLER + PACK,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/dressed_squad_leader_trainer_01.iff",
"object/mobile/dressed_squad_leader_trainer_02.iff",
"object/mobile/dressed_squad_leader_trainer_03.iff"
},
lootGroups = {},
weapons = {"dark_trooper_weapons"},
conversationTemplate = "",
attacks = merge(bountyhuntermaster,marksmanmaster,brawlermaster,swordsmanmaster,pistoleermaster)
}
CreatureTemplates:addCreatureTemplate(norulac_raider_captain, "norulac_raider_captain")
|
--[[
**
** production-information.lua -- OBS Studio Lua Script for Production Information
** Copyright (c) 2021 Dr. Ralf S. Engelschall <rse@engelschall.com>
** Distributed under MIT license <https://spdx.org/licenses/MIT.html>
**
--]]
-- global OBS API
local obs = obslua
-- global context information
local ctx = {
-- properties
propsDef = nil, -- property definition
propsDefSrcPreview = nil, -- property definition (source scene of preview)
propsDefSrcProgram = nil, -- property definition (source scene of program)
propsDefSrcTime = nil, -- property definition (source scene of time)
propsDefSrcDuration = nil, -- property definition (source scene of duration)
propsSet = nil, -- property settings (model)
propsVal = {}, -- property values
propsValSrcPreview = nil, -- property values (source scene of preview)
propsValSrcProgram = nil, -- property values (source scene of program)
propsValSrcTime = nil, -- property values (source scene of time)
propsValSrcDuration = nil, -- property values (source scene of duration)
-- duration timer
timerStart = 0, -- timer start (in nannoseconds)
timerPaused = false, -- timer paused flag
timerPausedSecs = 0, -- timer paused time (in seconds)
-- hotkey registration
hotkeyIdPause = obs.OBS_INVALID_HOTKEY_ID,
hotkeyIdReset = obs.OBS_INVALID_HOTKEY_ID
}
-- helper function: update text source properties
local function updateTextSources ()
-- clear already initialized property lists
if ctx.propsDefSrcPreview ~= nil then
obs.obs_property_list_clear(ctx.propsDefSrcPreview)
end
if ctx.propsDefSrcProgram ~= nil then
obs.obs_property_list_clear(ctx.propsDefSrcProgram)
end
if ctx.propsDefSrcTime ~= nil then
obs.obs_property_list_clear(ctx.propsDefSrcTime)
end
if ctx.propsDefSrcDuration ~= nil then
obs.obs_property_list_clear(ctx.propsDefSrcDuration)
end
-- clear all selected propety values
ctx.propsValSrcPreview = nil
ctx.propsValSrcProgram = nil
ctx.propsValSrcTime = nil
ctx.propsValSrcDuration = nil
-- iterate over all text sources...
local sources = obs.obs_enum_sources()
if sources ~= nil then
for _, source in ipairs(sources) do
local source_id = obs.obs_source_get_unversioned_id(source)
if source_id == "text_gdiplus" or source_id == "text_ft2_source" then
-- ...and fetch their source names
local name = obs.obs_source_get_name(source)
-- add source to preview text source selection list
-- and initialize selected value
if ctx.propsDefSrcPreview ~= nil then
obs.obs_property_list_add_string(ctx.propsDefSrcPreview, name, name)
end
if ctx.propsValSrcPreview == nil then
ctx.propsValSrcPreview = name
end
-- add source to program text source selection list
-- and initialize selected value
if ctx.propsDefSrcProgram ~= nil then
obs.obs_property_list_add_string(ctx.propsDefSrcProgram, name, name)
end
if ctx.propsValSrcProgram == nil then
ctx.propsValSrcProgram = name
end
-- add source to time text source selection list
-- and initialize selected value
if ctx.propsDefSrcTime ~= nil then
obs.obs_property_list_add_string(ctx.propsDefSrcTime, name, name)
end
if ctx.propsValSrcTime == nil then
ctx.propsValSrcTime = name
end
-- add source to duration text source selection list
-- and initialize selected value
if ctx.propsDefSrcDuration ~= nil then
obs.obs_property_list_add_string(ctx.propsDefSrcDuration, name, name)
end
if ctx.propsValSrcDuration == nil then
ctx.propsValSrcDuration = name
end
end
end
end
obs.source_list_release(sources)
end
-- helper function for duration pause
local function durationPause ()
ctx.timerPaused = not ctx.timerPaused
end
-- helper function for duration reset
local function durationReset ()
ctx.timerStart = obs.os_gettime_ns()
ctx.timerPausedSecs = 0
end
-- update a single target text source
local function updateTextSource (name, text)
local source = obs.obs_get_source_by_name(name)
if source ~= nil then
local settings = obs.obs_source_get_settings(source)
obs.obs_data_set_string(settings, "text", text)
obs.obs_source_update(source, settings)
obs.obs_data_release(settings)
obs.obs_source_release(source)
end
end
-- update targets for scenes
local function updateTextSourcesScene ()
-- determine current scene in preview and update text source
local previewSceneSource = obs.obs_frontend_get_current_preview_scene()
local previewSceneName = obs.obs_source_get_name(previewSceneSource)
updateTextSource(ctx.propsVal.textSourceNamePreview, previewSceneName)
obs.obs_source_release(previewSceneSource)
-- determine current scene in program and update text source
local programSceneSource = obs.obs_frontend_get_current_scene()
local programSceneName = obs.obs_source_get_name(programSceneSource)
updateTextSource(ctx.propsVal.textSourceNameProgram, programSceneName)
obs.obs_source_release(programSceneSource)
end
-- update targets for time
local function updateTextSourcesTime ()
-- determine current wallclock-time and update text source
local time = os.date("%H:%M:%S")
updateTextSource(ctx.propsVal.textSourceNameTime, time)
-- determine current duration-time and update text source
if ctx.timerPaused then
ctx.timerPausedSecs = ctx.timerPausedSecs + 1
end
local timerEnd = obs.os_gettime_ns()
local duration = math.floor((timerEnd - ctx.timerStart) / (1000 * 1000 * 1000)) - ctx.timerPausedSecs
local hour = math.floor(duration / (60 * 60))
duration = math.fmod(duration, 60 * 60)
local min = math.floor(duration / 60)
duration = math.fmod(duration, 60)
local sec = duration
local text = string.format("%02d:%02d:%02d", hour, min, sec)
if ctx.timerPaused then
text = text .. " *"
end
updateTextSource(ctx.propsVal.textSourceNameDuration, text)
end
-- script hook: description displayed on script window
function script_description ()
return [[
<h2>Production Information</h2>
Copyright © 2021 <a style="color: #ffffff; text-decoration: none;"
href="http://engelschall.com">Dr. Ralf S. Engelschall</a><br/>
Distributed under <a style="color: #ffffff; text-decoration: none;"
href="https://spdx.org/licenses/MIT.html">MIT license</a>
<p>
<b>Render production information into corresponding text sources.</b>
<p>
This is a small OBS Studio script for rendering the current
scene name visible in the Preview and Program channels, the
current wallclock time and the current on-air duration time into
pre-defined corresponding Text/GDI+ text sources. These text
sources are usually part of a (hidden) scene which is either
just part of a locally shown OBS Studio Multiview or Projector
or is broadcasted via an attached "Dedicated NDI Output" filter
to foreign monitors. In all cases, the intention is to globally
show current production information to the involved people
during a production session.
]]
end
-- script hook: define UI properties
function script_properties ()
-- create new properties
local props = obs.obs_properties_create()
-- create selection fields
ctx.propsDefSrcPreview = obs.obs_properties_add_list(props,
"textSourceNamePreview", "Preview-Name Text-Source",
obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING)
ctx.propsDefSrcProgram = obs.obs_properties_add_list(props,
"textSourceNameProgram", "Program-Name Text-Source",
obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING)
ctx.propsDefSrcTime = obs.obs_properties_add_list(props,
"textSourceNameTime", "Wallclock-Time Text-Source",
obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING)
ctx.propsDefSrcDuration = obs.obs_properties_add_list(props,
"textSourceNameDuration", "Duration-Time Text-Source",
obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING)
updateTextSources()
-- create buttons
obs.obs_properties_add_button(props, "buttonStartStop", "Duration: Start/Stop", function ()
durationPause()
return true
end)
obs.obs_properties_add_button(props, "buttonReset", "Duration: Reset", function ()
durationReset()
return true
end)
return props
end
-- script hook: define property defaults
function script_defaults (settings)
-- update our text source list (for propsValSrcXXX below)
updateTextSources()
-- provide default values
obs.obs_data_set_default_string(settings, "textSourceNamePreview", ctx.propsValSrcPreview)
obs.obs_data_set_default_string(settings, "textSourceNameProgram", ctx.propsValSrcProgram)
obs.obs_data_set_default_string(settings, "textSourceNameTime", ctx.propsValSrcTime)
obs.obs_data_set_default_string(settings, "textSourceNameDuration", ctx.propsValSrcDuration)
end
-- script hook: update state from UI properties
function script_update (settings)
-- remember settings
ctx.propsSet = settings
-- fetch property values
ctx.propsVal.textSourceNamePreview = obs.obs_data_get_string(settings, "textSourceNamePreview")
ctx.propsVal.textSourceNameProgram = obs.obs_data_get_string(settings, "textSourceNameProgram")
ctx.propsVal.textSourceNameTime = obs.obs_data_get_string(settings, "textSourceNameTime")
ctx.propsVal.textSourceNameDuration = obs.obs_data_get_string(settings, "textSourceNameDuration")
end
-- script hook: on script load
function script_load (settings)
-- define hotkeys
ctx.hotkeyIdPause = obs.obs_hotkey_register_frontend("duration_pause",
"Duration: Start/Stop", function (pressed)
if pressed then
durationPause()
end
end)
ctx.hotkeyIdReset = obs.obs_hotkey_register_frontend("duration_reset",
"Duration: Reset", function (pressed)
if pressed then
durationReset()
end
end)
local hotkeyArrayPause = obs.obs_data_get_array(settings, "hotkey_pause")
local hotkeyArrayReset = obs.obs_data_get_array(settings, "hotkey_reset")
obs.obs_hotkey_load(ctx.hotkeyIdPause, hotkeyArrayPause)
obs.obs_hotkey_load(ctx.hotkeyIdReset, hotkeyArrayReset)
obs.obs_data_array_release(hotkeyArrayPause)
obs.obs_data_array_release(hotkeyArrayReset)
-- hook into the UI events
obs.obs_frontend_add_event_callback(function (event)
if event == obs.OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED then
updateTextSources()
elseif event == obs.OBS_FRONTEND_EVENT_SCENE_CHANGED then
updateTextSourcesScene()
elseif event == obs.OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED then
updateTextSourcesScene()
end
return true
end)
-- start timer
durationReset()
obs.timer_add(updateTextSourcesTime, 1000)
end
-- script hook: on script save state
function script_save(settings)
-- save hotkeys
local hotkeyArrayPause = obs.obs_hotkey_save(ctx.hotkeyIdPause)
local hotkeyArrayReset = obs.obs_hotkey_save(ctx.hotkeyIdReset)
obs.obs_data_set_array(settings, "hotkey_pause", hotkeyArrayPause)
obs.obs_data_set_array(settings, "hotkey_reset", hotkeyArrayReset)
obs.obs_data_array_release(hotkeyArrayPause)
obs.obs_data_array_release(hotkeyArrayReset)
end
|
local convertors = require(script.Parent.Parent.Convertors)
return function(API,Parsed)
local ValueType = Parsed.ClassName
local ValueUnParsed = Parsed[ValueType]
if ValueUnParsed then
local convertor = convertors[ ValueType ]
if convertor then
return convertor(false,ValueUnParsed)
else
return nil
end
else
return nil
end
end |
loadstring(game:HttpGet('https://pastebin.com/raw/MLPypHYv', true))() |
AddCSLuaFile()
local A = "AMBER"
local R = "RED"
local DR = "D_RED"
local B = "BLUE"
local W = "WHITE"
local CW = "C_WHITE"
local SW = "S_WHITE"
local G = "GREEN"
local RB = "BLUE/RED"
local name = "NYSP Mirror Light"
local COMPONENT = {}
COMPONENT.Model = "models/supermighty/photon/whelen_linz6.mdl"
COMPONENT.Skin = 0
COMPONENT.Bodygroups = {}
COMPONENT.NotLegacy = true
COMPONENT.ColorInput = 1
COMPONENT.UsePhases = true
COMPONENT.Category = "Exterior"
COMPONENT.DefaultColors = {
[1] = "WHITE"
}
COMPONENT.Meta = {
auto_ion_left = {
AngleOffset = 0,
W = 5.1,
H = 5.5,
WMult = 1.5,
Sprite = "sprites/emv/emv_whelen_src",
Scale = 1.2,
NoLegacy = true,
DirAxis = "Up",
DirOffset = 90
},
}
COMPONENT.Positions = {
[1] = { Vector( -.9, 0, 0 ), Angle( 0, 90, 0 ), "auto_ion_left", 0, 5 },
}
COMPONENT.Sections = {
["auto_ion"] = {
[1] = { { 1, "_1" }, }
},
}
COMPONENT.Patterns = {
["auto_ion"] = {
["code1A"] = {1,1,1,1,0,0,0,0},
["code1B"] = {0,0,0,0,1,1,1,1,},
["code2A"] = { 1, 0, 1, 1, 1, 0, 0, 0, 0, 0 },
["code2B"] = { 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, },
["code3A"] = { 1, 0, 1, 0, 0, 0 },
["code3B"] = { 0, 0, 0, 1, 0, 1 },
}
}
COMPONENT.Modes = {
Primary = {
M1 = { ["auto_ion"] = "code1", },
M2 = { ["auto_ion"] = "code2", },
M3 = { ["auto_ion"] = "code3", },
},
Auxiliary = {},
Illumination = {}
}
EMVU:AddAutoComponent( COMPONENT, name ) |
Talk(5, "小兄弟想要与老朽切磋武学的奥妙吗?", "talkname5", 0);
if AskBattle() == true then goto label0 end;
do return end;
::label0::
Talk(0, "还望前辈指导.", "talkname0", 1);
if TryBattle(22) == false then goto label1 end;
LightScence();
Talk(5, "少侠武功已到如此境界,老朽也没什么好教你的了.", "talkname5", 0);
ModifyEvent(-2, -2, -2, -2, 158, -1, -1, -2, -2, -2, -2, -2, -2);
AddRepute(20);
do return end;
::label1::
LightScence();
if JudgeEthics(0, 80, 100) == true then goto label2 end;
Talk(5, "小兄弟,看来你还需再下一番努力才是.", "talkname5", 0);
do return end;
::label2::
if JudgeAttack(0, 80, 100) == true then goto label3 end;
Talk(5, "小兄弟,看来你还需再下一番努力才是.", "talkname5", 0);
do return end;
::label3::
Talk(5, "小兄弟资质不错,功力又增进不少,不错,不错.这是我最近研究出的一套剑法,你拿去好好参详吧.记住,要领悟剑的”剑意”而非”剑招”.", "talkname5", 0);
Talk(0, "谢谢前辈,晚辈谨记在心.", "talkname0", 1);
AddItem(75, 1);
ModifyEvent(-2, -2, -2, -2, 158, -1, -1, -2, -2, -2, -2, -2, -2);
do return end;
|
function empty(s)
return s == nil or s == ''
end
--
-- Checks if specified volume intersects a protected volume
--
function game.intersects_protection(minp, maxp, player_name, interval)
-- 'interval' is the largest allowed interval for the 3D lattice of checks
-- Compute the optimal float step 'd' for each axis so that all corners and
-- borders are checked. 'd' will be smaller or equal to 'interval'.
-- Subtracting 1e-4 ensures that the max co-ordinate will be reached by the
-- for loop (which might otherwise not be the case due to rounding errors).
local d = {}
for _, c in pairs({"x", "y", "z"}) do
if maxp[c] > minp[c] then
d[c] = (maxp[c] - minp[c]) / math.ceil((maxp[c] - minp[c]) / interval) - 1e-4
elseif maxp[c] == minp[c] then
d[c] = 1 -- Any value larger than 0 to avoid division by zero
else -- maxp[c] < minp[c], print error and treat as protection intersected
minetest.log("error", "maxp < minp in 'default.intersects_protection()'")
return true
end
end
for zf = minp.z, maxp.z, d.z do
local z = math.floor(zf + 0.5)
for yf = minp.y, maxp.y, d.y do
local y = math.floor(yf + 0.5)
for xf = minp.x, maxp.x, d.x do
local x = math.floor(xf + 0.5)
if minetest.is_protected({x = x, y = y, z = z}, player_name) then
return true
end
end
end
end
return false
end
function game.can_interact_with_node(player, pos)
if player then
if minetest.check_player_privs(player, "protection_bypass") then
return true
end
else
return false
end
local meta = minetest.get_meta(pos)
local owner = meta:get_string("owner")
if not owner or owner == "" or owner == player:get_player_name() then
return true
end
-- is player wielding the right key?
local item = player:get_wielded_item()
if item:get_name() == "default:key" then
local key_meta = item:get_meta()
if key_meta:get_string("secret") == "" then
local key_oldmeta = item:get_metadata()
if key_oldmeta == "" or not minetest.parse_json(key_oldmeta) then
return false
end
key_meta:set_string("secret", minetest.parse_json(key_oldmeta).secret)
item:set_metadata("")
end
return meta:get_string("key_lock_secret") == key_meta:get_string("secret")
end
return false
end
function game.set_player_priv(playername, privelege, value)
local privs = minetest.get_player_privs(playername)
if value == false then value=nil end
privs[privelege] = value
minetest.set_player_privs(playername, privs)
end
function game.get_hotbar_bg(x,y)
local out = ""
for i=0,7,1 do
out = out .."image["..x+i..","..y..";1,1;gui_hotbar_bg_"..i..".png]"
end
return out
end
|
object_tangible_quest_avatar_medical_records = object_tangible_quest_shared_avatar_medical_records:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_avatar_medical_records, "object/tangible/quest/avatar_medical_records.iff")
|
local util = {};
local ser = require("serialization").serialize
local tutil = require("payo-lib/tableutil");
local shell = require("shell")
local fs = require("filesystem")
local process = require("process")
local unicode = require("unicode")
local sh = require("sh")
local mktmp = loadfile(shell.resolve('mktmp','lua'))
if (not mktmp) then
io.stderr:write("testutils requires mktmp which could not be found\n")
return false
end
util.asserts = 0
util.assert_max = 10
util.total_tests_run = 0
util.last_time = 0
util.timeout = 1
function util.bump(ok)
local next_time = os.time()
if next_time - util.last_time > util.timeout then
util.last_time = next_time
if not util.no_sleep then
os.sleep(0)
end
io.write('.')
end
util.total_tests_run = util.total_tests_run + 1
if ok == true then return true end
util.asserts = util.asserts + 1
if util.asserts >= util.assert_max then
io.stderr:write("Too many asserts\n",debug.traceback())
os.exit(1)
end
return false
end
function util.load(lib)
package.loaded[lib] = nil;
local result = require(lib);
if (not result) then
error("failed to load library: " .. result);
return nil; -- shouldn't happen after an error
end
return result;
end
util.broken_handler = {}
util.broken_handler.__index = function()
return function() end
end
util.broken = {}
setmetatable(util.broken, util.broken_handler)
function util.assert(msg, expected, actual, detail)
local etype = type(expected);
local atype = type(actual);
local detail_msg = detail and string.format("detail: %s", ser(detail)) or ""
if (etype ~= atype) then
io.stderr:write(string.format("%s: mismatch type, %s vs %s. expected value: |%s|. %s\n", msg, etype, atype, ser(expected), detail_msg));
return util.bump()
end
-- both same type
if (etype == nil) then -- both nil
return true;
end
local matching = true;
if (etype == type({})) then
if (not tutil.equal(expected, actual)) then
matching = false;
end
elseif (expected ~= actual) then
matching = false;
end
if (not matching) then
io.stderr:write(string.format("%s\nExpected: %s\n Actual: %s\n%s\n", msg, ser(expected), ser(actual), detail_msg));
end
return util.bump(matching)
end
function util.assert_files(file_a, file_b)
util.bump(true)
local path_a = shell.resolve(file_a)
local path_b = shell.resolve(file_b)
local a_data = io.lines(path_a, "*a")()
local b_data = io.lines(path_b, "*a")()
util.assert("path a missing", fs.exists(path_a), true)
util.assert("path b missing", fs.exists(path_b), true)
util.assert("path a is dir", fs.isDirectory(path_a), false, path_a)
util.assert("path b is dir", fs.isDirectory(path_b), false, path_b)
util.assert("content mismatch", a_data, b_data)
end
function util.run_cmd(cmds, files, meta)
local chdir = shell.setWorkingDirectory
local function execute(...)
return require("sh").execute(nil, ...)
end
meta = meta or {}
local exit_code = meta.exit_code
local tmp_dir_path = mktmp('-d','-q')
local home = shell.getWorkingDirectory()
chdir(tmp_dir_path)
local stdouts = {}
local stderrs = {}
local stdout = setmetatable({tty=false, write = function(_, ...)
for _,v in ipairs({...}) do
if #v > 0 then table.insert(stdouts,v) end
end
end}, {__index = io.stdout})
local stderr = setmetatable({tty=false, write = function(_, ...)
for _,v in ipairs({...}) do
if #v > 0 then table.insert(stderrs,v) end
end
end}, {__index = io.stderr})
for _,c in ipairs(cmds) do
if type(c) == "string" then
local fp = function()execute(c)end
local proc = process.load(fp,nil,nil,"cmd_test:"..c)
process.info(proc).data.io[1] = stdout
process.info(proc).data.io[2] = stderr
while coroutine.status(proc) ~= "dead" do
coroutine.resume(proc)
end
else
c()
end
end
local actual = {}
local scan = nil
scan = function(d)
for it in fs.list(d) do
local path = (d .. '/' .. it):gsub("/+", "/")
local key = path:sub(unicode.len(tmp_dir_path)+1):gsub("/*$",""):gsub("^/*", "")
path = shell.resolve(path)
local isLink, linkPath = fs.isLink(path)
path = fs.realPath(path)
if isLink then
actual[key] = {linkPath}
elseif fs.isDirectory(path) then
actual[key] = true
scan(path)
else
local fh = io.open(path)
actual[key] = fh:read("*a")
fh:close()
end
end
end
chdir(tmp_dir_path)
scan(tmp_dir_path)
chdir(home)
fs.remove(tmp_dir_path)
local details = ' cmds:' .. ser(cmds,true) .. '\n' .. ser(meta,true) .. '\n'
for name,contents in pairs(actual) do
if not files[name] then
io.stderr:write("missing file: [", name, "]\ndetails:", details)
util.bump()
else
util.assert("files did not match: " .. name, files[name], contents, ser(contents) .. details)
end
files[name]=nil
end
util.assert("missing files", files, {}, ser(actual) .. details)
util.assert("exit code", sh.getLastExitCode(), sh.internal.command_result_as_code(exit_code), details)
local function output_check(captures, pattern)
if type(pattern) == "string" then
pattern = {pattern}
captures = {table.concat(captures)}
end
for _,c in ipairs(captures) do
if pattern and pattern[_] then
util.assert("output capture mismatch pos["..tostring(_).."]", not not c:match(pattern[_]), true,
string.format("[%d][%s]: captured output:[%s]", _, details, c))
else
util.assert("unexpected output", nil, c, details .. c)
end
end
end
output_check(stdouts, meta[1])
output_check(stderrs, meta[2])
end
function util.assert_process_output(cmd, expected_output)
util.bump(true)
local piped_file = mktmp('-q')
local full_cmd = cmd .. " > " .. piped_file
os.execute(full_cmd)
assert(fs.exists(piped_file))
local piped_handle = io.open(piped_file)
local piped_data = piped_handle:read("*a")
piped_handle:close()
fs.remove(piped_file)
if (piped_data ~= expected_output) then
io.stderr:write("failed command: ",full_cmd,"\n")
io.stderr:write(string.format("lengths: %i, %i:", piped_data:len(),
expected_output:len()))
io.stderr:write(string.format("%s", piped_data:gsub("\n", "\\n")))
io.stderr:write("[does not equal]")
io.stderr:write(string.format("%s\n", expected_output:gsub("\n", "\\n")))
util.bump()
end
end
return util; |
item_death_orb = class({})
function item_death_orb:OnSpellStart()
local charges = self:GetCurrentCharges()
local caster = self:GetCaster()
local heal = 24
CustomEntitiesLegacy:GiveManaAndEnergy(caster, charges, true, true)
if charges == 100 then
CustomEntitiesLegacy:TrueHeal(caster, heal)
end
end |
function EFFECT:Init( data )
local pos = data:GetOrigin()
local emitter = ParticleEmitter( pos )
if ( !emitter ) then return end
local particle = emitter:Add( "effects/rb655_health_over_bg", pos + Vector( math.random( -16, 16 ), math.random( -16, 16 ), math.random( 0, 72 ) ) )
if ( particle ) then
particle:SetLifeTime( 0 )
particle:SetDieTime( 2 )
particle:SetGravity( Vector( 0, 0, 100 ) )
particle:SetVelocity( Vector( 0, 0, 0 ) )
particle:SetStartSize( math.random( 4, 6 ) )
particle:SetEndSize( math.random( 0, 1 ) )
particle:SetStartAlpha( math.random( 200, 255 ) )
particle:SetEndAlpha( 0 )
particle:SetColor( 255, 0, 0 )
--particle:SetAngleVelocity( Angle( math.Rand( -180, 180 ), math.Rand( -180, 180 ), math.Rand( -180, 180 ) ) )
end
emitter:Finish()
end
function EFFECT:Think()
return false
end
function EFFECT:Render()
end
|
return {'lab','labarum','labbekak','labbekakken','labber','labberdaan','labberen','labberlot','labberlotten','labberlottig','labboon','label','labelen','labeling','labelprinter','labeur','labeuren','labeurgrond','labeurpaard','labiaal','labiaat','labiaten','labiel','labiliteit','labo','laborant','laborante','laboratorium','laboratoriumachtig','laboratoriumapparatuur','laboratoriumdier','laboratoriumexperiment','laboratoriumglaswerk','laboratoriumjas','laboratoriumomstandigheden','laboratoriumonderzoek','laboratoriumproef','laboratoriumrapport','laboratoriumtest','laboratoriumuitslag','laboratoriumwerk','laboreren','laborieus','labourregering','labrador','labyrint','labyrintisch','labaria','laboratoriumsituatie','laboratoriumschaal','labelbaas','laboratoriumdiagnostiek','laboratoriumpersoneel','labojas','laboratoriumanalyse','labee','lablans','labots','labrie','laban','labordus','labrijn','labree','labberdanen','labberde','labbert','labbonen','labelde','labelden','labellen','labels','labelt','labeltje','labeltjes','labeurde','labeurgronden','labeurt','labiale','labialen','labiele','labieler','labielere','labielst','labielste','labos','laboranten','laboratoria','laboratoriumjassen','laboratoriumonderzoeken','laboratoriumrapporten','laboratoriums','laboratoriumsituaties','laboratoriumtesten','laboratoriumtests','laboreerde','laboreerden','laboreert','laborerende','laborieuze','labradors','labyrinten','labyrintische','labarums','labberlottige','labeurpaarden','laboratoriumachtige','laboratoriumdieren','laboratoriumexperimenten','laboratoriumproeven','laboratoriumuitslagen','labs','labarias','labourregeringen','laboratoriumanalyses','laboratoriumfaciliteiten','laboratoriumschaaltjes'} |
object_building_mustafar_particle_must_jedi_rock_throw_10 = object_building_mustafar_particle_shared_must_jedi_rock_throw_10:new {
}
ObjectTemplates:addTemplate(object_building_mustafar_particle_must_jedi_rock_throw_10, "object/building/mustafar/particle/must_jedi_rock_throw_10.iff")
|
local modelFile = ...
local root = remodel.readModelFile(modelFile)[1]
local modelFileName = string.match(modelFile, "([^/\\]+)%.rbxmx?$")
assert(modelFileName, "Could not get name for model file")
local function getTree(instance)
local tree = {}
local obj = instance
while obj do
table.insert(tree, 1, obj.Name)
obj = obj.Parent
end
return tree
end
local MODULE_FORMAT = table.concat({
"[Pointer.new(%s)] = function()",
"\tlocal script = Pointer.new(%s)",
"",
"\t%s",
"end",
}, "\n")
local function moduleNode(instance)
local pathArray = "{ [[" .. table.concat(getTree(instance), "]], [[") .. "]] }"
return string.format(
MODULE_FORMAT,
pathArray,
pathArray,
string.gsub(remodel.getRawProperty(instance, "Source"), "\n", "\n\t")
)
end
local function modulesToNodes(instance)
local nodes = {
instance.ClassName == "ModuleScript" and moduleNode(instance) or nil
}
for _, child in ipairs(instance:GetChildren()) do
for _, childNext in ipairs(modulesToNodes(child)) do
table.insert(nodes, childNext)
end
end
return nodes
end
-- Transform the module into a list of functions
local nodes = modulesToNodes(root)
-- Get the module runtime script
local runtime = remodel.readFile("ci/build/runtime.lua")
-- Replace the --[[@MODEL_NAME]] marker with the rbxm file's name
runtime = string.gsub(runtime, "%-%-%[%[@MODEL_NAME%]%]", modelFileName)
-- Replace the --[[@MODULES]] marker with a list of functions
local i, j = string.find(runtime, "%-%-%[%[@MODULES%]%]")
local output = table.concat({
string.sub(runtime, 1, i - 1),
"\t" .. string.gsub(table.concat(nodes, ",\n"), "\n", "\n\t"),
string.sub(runtime, j + 1),
}, "\n")
-- Output folder
remodel.writeFile(modelFileName .. ".lua", output)
print(modelFileName .. ".lua")
|
-- Generated by CSharp.lua Compiler
local System = System
local SystemIO = System.IO
local UnityEngine = UnityEngine
local UnityEngineNetworking = UnityEngine.Networking
local UnityEngineSceneManagement = UnityEngine.SceneManagement
local DictStringString = System.Dictionary(System.String, System.String)
System.namespace("", function (namespace)
namespace.class("Util", function (namespace)
local Awake, StartCor, StopCor, WaitForSec, WaitForSecCor, WaitForFrame, SetImageByUrl, SetImageByUrl1,
GetFileTypeByFileName, WaitForFrameCor, GetUrl, GetUrlCor, PostUrl, PostUrlCor, FloatProcessToStr, PlaySound,
Typewriter, TypewriterCor, LoadingScene, LoadingSceneEnu, GetTimeStrBySec, GetTimeStrByNum, ChangeMaterial, ChangeLayer,
PerFrameDo, PerFrameDoCor, PerFrameLoad, PerFrameLoadCor, GetJpgData, upLoadImage, headers, LargeNumToString,
GetFileTypeByFileName1, LimitStr, LimitStr1, GetStrLenPixe, Base64ToTexture2D, Texture2DToBase64, CreateSpriteByTexture2D, WaitForLandScape,
WaitForLandScapeCor, WaitForPortrait, WaitForPortraitCor, class, static
static = function (this)
headers = DictStringString()
end
Awake = function (this)
class.instance = this
UnityEngine.Object.DontDestroyOnLoad(this:getgameObject())
end
StartCor = function (this, cor)
return this:StartCoroutine(cor)
end
StopCor = function (this, cor)
this:StopCoroutine(cor)
end
WaitForSec = function (this, sec, cb)
return this:StartCoroutine(WaitForSecCor(this, sec, cb))
end
WaitForSecCor = function (this, sec, cb)
return System.yieldIEnumerator(function (this, sec, cb)
System.yield(UnityEngine.WaitForSeconds(sec))
local default = cb
if default ~= nil then
default()
end
end, System.Object, this, sec, cb)
end
WaitForFrame = function (this, frameNum, cb)
return this:StartCoroutine(WaitForFrameCor(this, frameNum, cb))
end
SetImageByUrl = function (this, url, img, defaultImgPath)
img:setsprite(UnityEngine.Resources.Load(defaultImgPath, typeof(UnityEngine.Sprite)))
if System.String.IsNullOrEmpty(url) then
return nil
end
return GetUrl(this, url, nil, function (handler)
-- Debug.Log(url);
local tex = UnityEngine.Texture2D(1024, 1024)
UnityEngine.ImageConversion.LoadImage(tex, handler:getdata())
-- Debug.LogError(tex.width+"///"+tex.height);
local sprite = UnityEngine.Sprite.Create(tex, UnityEngine.Rect(0, 0, tex:getwidth(), tex:getheight()), UnityEngine.Vector2(0.5, 0.5))
--Debug.LogError( sprite.texture.width+"/"+ sprite.texture.height);
if UnityEngine.op_Inequality(img, nil) then
img:setsprite(sprite)
end
end, function (e)
UnityEngine.Debug.LogError(e)
end, 2, 0)
end
SetImageByUrl1 = function (this, url, cb)
return GetUrl(this, url, nil, function (handler)
-- Debug.Log(url);
local tex = UnityEngine.Texture2D(1024, 1024)
UnityEngine.ImageConversion.LoadImage(tex, handler:getdata())
-- Debug.LogError(tex.width+"///"+tex.height);
local sprite = UnityEngine.Sprite.Create(tex, UnityEngine.Rect(0, 0, tex:getwidth(), tex:getheight()), UnityEngine.Vector2(0.5, 0.5))
-- imageWidth = tex.width;
-- imageHeight = tex.height;
local default = cb
if default ~= nil then
default(sprite)
end
end, function (e)
UnityEngine.Debug.LogError(e)
end, 2, 0)
end
GetFileTypeByFileName = function (this, resFormat)
System.throw(System.NotImplementedException())
end
WaitForFrameCor = function (this, frameNum, cb)
return System.yieldIEnumerator(function (this, frameNum, cb)
for i = 0, frameNum - 1 do
System.yield(UnityEngine.WaitForEndOfFrame())
end
local default = cb
if default ~= nil then
default()
end
end, System.Object, this, frameNum, cb)
end
GetUrl = function (this, url, processAction, doneAction, errorAction, tryTime, timeout)
return this:StartCoroutine(GetUrlCor(this, url, processAction, doneAction, errorAction, tryTime, timeout))
end
GetUrlCor = function (this, url, processAction, doneAction, errorAction, tryTime, timeout)
return System.yieldIEnumerator(function (this, url, processAction, doneAction, errorAction, tryTime, timeout)
tryTime = tryTime - 1
local unityWebRequest = UnityEngineNetworking.UnityWebRequest.Get(url)
unityWebRequest:settimeout(timeout)
local oper = unityWebRequest:SendWebRequest()
if unityWebRequest:getisNetworkError() or unityWebRequest:getisHttpError() then
if errorAction ~= nil then
if tryTime == 0 then
UnityEngine.Debug.LogError(unityWebRequest:geterror())
errorAction(unityWebRequest:geterror())
UnityEngine.Debug.Log("基于网络的第0次请求失败")
else
GetUrl(this, url, processAction, doneAction, errorAction, tryTime, timeout)
end
end
else
while not oper:getisDone() do
System.yield(nil)
if processAction ~= nil then
processAction(oper:getprogress())
-- Debug.Log("当前oper:"+ oper.progress);
end
if unityWebRequest:getisNetworkError() or unityWebRequest:getisHttpError() then
-- Debug.Log("断网时当前oper:"+ oper.progress);
if errorAction ~= nil then
if tryTime == 0 then
UnityEngine.Debug.LogError(unityWebRequest:geterror())
errorAction(unityWebRequest:geterror())
break
else
GetUrl(this, url, processAction, doneAction, errorAction, tryTime, timeout)
break
end
end
end
end
if doneAction ~= nil then
if not (unityWebRequest:getisNetworkError() or unityWebRequest:getisHttpError()) then
local default = processAction
if default ~= nil then
default(1)
end
local default = doneAction
if default ~= nil then
default(unityWebRequest:getdownloadHandler())
end
else
if errorAction ~= nil then
if tryTime == 0 then
UnityEngine.Debug.LogError(unityWebRequest:geterror())
errorAction(unityWebRequest:geterror())
UnityEngine.Debug.Log("非网络的第0次请求失败")
else
GetUrl(this, url, processAction, doneAction, errorAction, tryTime, timeout)
end
end
end
end
end
end, System.Object, this, url, processAction, doneAction, errorAction, tryTime, timeout)
end
PostUrl = function (this, url, form, processAction, doneAction, errorAction, tryTime, timeout)
return this:StartCoroutine(PostUrlCor(this, url, form, processAction, doneAction, errorAction, tryTime, timeout))
end
PostUrlCor = function (this, url, form, processAction, doneAction, errorAction, tryTime, timeout)
return System.yieldIEnumerator(function (this, url, form, processAction, doneAction, errorAction, tryTime, timeout)
tryTime = tryTime - 1
local unityWebRequest = UnityEngineNetworking.UnityWebRequest.Post(url, form)
unityWebRequest:settimeout(timeout)
local oper = unityWebRequest:SendWebRequest()
if unityWebRequest:getisNetworkError() or unityWebRequest:getisHttpError() then
if errorAction ~= nil then
if tryTime == 0 then
UnityEngine.Debug.LogError(unityWebRequest:geterror())
errorAction(unityWebRequest:geterror())
else
PostUrl(this, url, form, processAction, doneAction, errorAction, tryTime, timeout)
end
end
else
while not oper:getisDone() do
System.yield(nil)
if processAction ~= nil then
processAction(oper:getprogress())
end
if unityWebRequest:getisNetworkError() or unityWebRequest:getisHttpError() then
if errorAction ~= nil then
if tryTime == 0 then
-- Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest:geterror())
break
else
PostUrl(this, url, form, processAction, doneAction, errorAction, tryTime, timeout)
break
end
end
end
end
if doneAction ~= nil then
if not (unityWebRequest:getisNetworkError() or unityWebRequest:getisHttpError()) then
local default = processAction
if default ~= nil then
default(1)
end
local default = doneAction
if default ~= nil then
default(unityWebRequest:getdownloadHandler())
end
else
if errorAction ~= nil then
if tryTime == 0 then
--Debug.LogError(unityWebRequest.error);
errorAction(unityWebRequest:geterror())
else
PostUrl(this, url, form, processAction, doneAction, errorAction, tryTime, timeout)
end
end
end
end
end
end, System.Object, this, url, form, processAction, doneAction, errorAction, tryTime, timeout)
end
FloatProcessToStr = function (this, f)
f = f * 100
return UnityEngine.Mathf.RoundToInt(f) .. "%"
end
PlaySound = function (this, path, clipName, volume, is3D)
local clip = UnityEngine.Resources.Load(SystemIO.Path.Combine(path, clipName), typeof(UnityEngine.AudioClip))
if UnityEngine.op_Equality(this.asr3D, nil) then
this.asr3D = UnityEngine.GameObject("__Audio__"):AddComponent(UnityEngine.AudioSource)
this.asr2D = this.asr3D:getgameObject():AddComponent(UnityEngine.AudioSource)
this.asr3D:setspatialBlend(1)
this.asr2D:setspatialBlend(0)
this.asr3D:setrolloffMode(2 --[[AudioRolloffMode.Custom]])
end
local asr = this.asr2D
if is3D then
asr = this.asr3D
end
asr:PlayOneShot(clip, volume)
end
Typewriter = function (this, content, dertTime, text, cb)
return this:StartCoroutine(TypewriterCor(this, content, dertTime, text, cb))
end
TypewriterCor = function (this, content, dertTime, text, cb)
return System.yieldIEnumerator(function (this, content, dertTime, text, cb)
if UnityEngine.op_Inequality(text, nil) then
local temp = ""
for i = 0, #content - 1 do
temp = temp .. string.char(content:get(i))
text:settext(temp)
System.yield(UnityEngine.WaitForSeconds(dertTime))
end
end
local default = cb
if default ~= nil then
default()
end
end, System.Object, this, content, dertTime, text, cb)
end
LoadingScene = function (this, sceneName, loadingCb, doneCb)
return this:StartCoroutine(LoadingSceneEnu(this, sceneName, loadingCb, doneCb))
end
LoadingSceneEnu = function (this, sceneName, loadingCb, doneCb)
return System.yieldIEnumerator(function (this, sceneName, loadingCb, doneCb)
if doneCb ~= nil then
UnityEngineSceneManagement.SceneManager.addsceneLoaded(doneCb)
end
local oper = UnityEngineSceneManagement.SceneManager.LoadSceneAsync(sceneName, 0 --[[LoadSceneMode.Single]])
oper:setallowSceneActivation(false)
local cur = 0
local real = 0
while true do
if oper:getprogress() * 100 >= real then
real = oper:getprogress() * 100
if real >= 90 then
real = 100
end
end
if cur < real then
cur = cur + 1
local default = loadingCb
if default ~= nil then
default(cur / 100)
end
end
if cur >= 100 then
break
end
System.yield(nil)
end
oper:setallowSceneActivation(true)
end, System.Object, this, sceneName, loadingCb, doneCb)
end
GetTimeStrBySec = function (this, sec)
local t = System.ToInt32(math.Round(sec))
local h = System.div(t, 3600)
local m = System.div(t, 60)
local s = System.mod(t, 60)
return GetTimeStrByNum(this, h) .. ":" .. GetTimeStrByNum(this, m) .. ":" .. GetTimeStrByNum(this, s)
end
GetTimeStrByNum = function (this, num)
if num < 10 then
return "0" .. num
end
return num:ToString()
end
ChangeMaterial = function (this, obj, path, matName)
local material = UnityEngine.Resources.Load(SystemIO.Path.Combine(path, matName), typeof(UnityEngine.Material))
obj:GetComponent(UnityEngine.MeshRenderer):getmaterials():get(0):CopyPropertiesFromMaterial(material)
--更改材质球
end
ChangeLayer = function (this, go, layerName)
local layer = UnityEngine.LayerMask.NameToLayer(layerName)
go:setlayer(layer)
for _, child in System.each(go:gettransform()) do
child = System.cast(UnityEngine.Transform, child)
ChangeLayer(this, child:getgameObject(), layerName)
end
end
PerFrameDo = function (this, perCount, totalCount, perDoneCb, allDoneCb)
return this:StartCoroutine(PerFrameDoCor(this, perCount, totalCount, perDoneCb, allDoneCb))
end
PerFrameDoCor = function (this, perCount, totalCount, perDoneCb, allDoneCb)
return System.yieldIEnumerator(function (this, perCount, totalCount, perDoneCb, allDoneCb)
local curNum = 0
while curNum < totalCount do
System.yield(nil)
do
local i = 0
while i < perCount and curNum < totalCount do
perDoneCb()
curNum = curNum + 1
i = i + 1
end
end
end
local default = allDoneCb
if default ~= nil then
default()
end
end, System.Object, this, perCount, totalCount, perDoneCb, allDoneCb)
end
PerFrameLoad = function (this, go, perCount, totalCount, perDoneCb, allDone)
return this:StartCoroutine(PerFrameLoadCor(this, go, perCount, totalCount, perDoneCb, allDone))
end
PerFrameLoadCor = function (this, go, perCount, totalCount, perDoneCb, allDone)
return System.yieldIEnumerator(function (this, go, perCount, totalCount, perDoneCb, allDone)
local curNum = 0
while curNum < totalCount do
System.yield(nil)
do
local i = 0
while i < perCount and curNum < totalCount do
local g = UnityEngine.Object.Instantiate(go)
perDoneCb(g)
curNum = curNum + 1
i = i + 1
end
end
end
allDone()
end, System.Object, this, go, perCount, totalCount, perDoneCb, allDone)
end
GetJpgData = function (this, te)
local data = nil
data = UnityEngine.ImageConversion.EncodeToJPG(te, 5)
--int quelity = 75;
--while (quelity > 10)
--{
-- data = te.EncodeToJPG(quelity);
-- int size = data.Length / 1024;
-- if (size > 15)
-- {
-- quelity -= 5;
-- }
-- else
-- {
-- break;
-- }
--}
return data
end
upLoadImage = function (this, url, base64)
return System.yieldIEnumerator(function (this, url, base64)
local form = UnityEngine.WWWForm()
form:AddField("id", UnityEngine.PlayerPrefs.GetString("userId"))
form:AddField("headImg", base64)
--form.AddField("headImg", PlayerPrefs.GetString("headImg"));
System.using(UnityEngine.WWW(url, form:getdata(), headers), function (www)
System.yield(www)
if www:getisDone() and www:geterror() == nil then
UnityEngine.Debug.Log("success")
UnityEngine.Debug.Log(www:gettext())
else
UnityEngine.Debug.Log(www:geterror())
end
end)
end, System.Object, this, url, base64)
end
LargeNumToString = function (this, num)
if num > 9999 then
return math.Round(num / 10000, 2) .. "万"
else
return num:ToString()
end
end
GetFileTypeByFileName1 = function (this, fileNameOrFormat)
fileNameOrFormat = fileNameOrFormat:ToLower()
local f = fileNameOrFormat
if f:Contains(".") then
f = fileNameOrFormat:Substring(fileNameOrFormat:LastIndexOf(".") + 1)
end
repeat
local default = f
if default == "jpg" or default == "jpeg" or default == "bmp" or default == "png" or default == "gif" or default == "psd" or default == "tga" or default == "mpg" then
return 3 --[[FileType.Img]]
elseif default == "mov" or default == "mpeg" or default == "mp4" or default == "avi" or default == "asf" then
return 4 --[[FileType.Video]]
elseif default == "ab" then
return 1 --[[FileType.Model]]
elseif default == "txt" then
return 2 --[[FileType.Text]]
elseif default == "pdf" then
return 6 --[[FileType.PDF]]
elseif default == "html" then
return 7 --[[FileType.H5]]
elseif default == "doc" or default == "docx" or default == "课件" then
return 8 --[[FileType.Doc]]
end
until 1
return 0 --[[FileType.None]]
end
LimitStr = function (this, str, limitLen, endWith, font, fontSize)
local strLen = GetStrLenPixe(this, str, font, fontSize)
if strLen <= limitLen then
return str
else
local curLen = 0
local endWithLen = GetStrLenPixe(this, endWith, font, fontSize)
for i = 0, #str - 1 do
local info = UnityEngine.CharacterInfo()
local _
_, info = font:GetCharacterInfo(str:get(i), nil, fontSize)
curLen = curLen + info:getadvance()
if curLen + endWithLen > limitLen then
return str:Substring(0, i) .. endWith
end
end
end
return nil
end
-- <summary>
-- 将指定字符串按指定长度进行截取并加上指定的后缀
-- </summary>
-- <param name= "oldStr "> 需要截断的字符串 </param>
-- <param name= "maxLength "> 字符串的最大长度 </param>
-- <param name= "endWith "> 超过长度的后缀 </param>
-- <returns> 如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串 </returns>
LimitStr1 = function (this, oldStr, maxLength, endWith)
--判断原字符串是否为空
if System.String.IsNullOrEmpty(oldStr) then
return oldStr .. endWith
end
--返回字符串的长度必须大于1
if maxLength < 1 then
System.throw(System.Exception("返回的字符串长度必须大于[0] "))
end
--判断原字符串是否大于最大长度
if #oldStr > maxLength then
--截取原字符串
local strTmp = oldStr:Substring(0, maxLength)
--判断后缀是否为空
if System.String.IsNullOrEmpty(endWith) then
return strTmp
else
return strTmp .. endWith
end
end
return oldStr
end
GetStrLenPixe = function (this, str, font, fontSize)
local len = 0
for _, ch in System.each(str) do
local info = UnityEngine.CharacterInfo()
local _
_, info = font:GetCharacterInfo(ch, nil, fontSize)
len = len + info:getadvance()
end
return len
end
Base64ToTexture2D = function (this, Base64STR)
local pic = UnityEngine.Texture2D(190, 190, 4 --[[TextureFormat.RGBA32]], false)
local data = System.Convert.FromBase64String(Base64STR)
UnityEngine.ImageConversion.LoadImage(pic, data)
return pic
end
Texture2DToBase64 = function (this, t2d)
local bytesArr = UnityEngine.ImageConversion.EncodeToJPG(t2d)
local strbaser64 = System.Convert.ToBase64String(bytesArr)
return strbaser64
end
CreateSpriteByTexture2D = function (this, tex)
return UnityEngine.Sprite.Create(tex, UnityEngine.Rect(0, 0, tex:getwidth(), tex:getheight()), UnityEngine.Vector2(0.5, 0.5))
end
WaitForLandScape = function (this, cb)
return StartCor(this, WaitForLandScapeCor(this, cb))
end
WaitForLandScapeCor = function (this, cb)
return System.yieldIEnumerator(function (this, cb)
while true do
System.yield(nil)
if UnityEngine.Screen.getwidth() > UnityEngine.Screen.getheight() then
break
end
end
local default = cb
if default ~= nil then
default()
end
end, System.Object, this, cb)
end
WaitForPortrait = function (this, cb)
return StartCor(this, WaitForPortraitCor(this, cb))
end
WaitForPortraitCor = function (this, cb)
return System.yieldIEnumerator(function (this, cb)
while true do
System.yield(nil)
if UnityEngine.Screen.getwidth() < UnityEngine.Screen.getheight() then
break
end
end
local default = cb
if default ~= nil then
default()
end
end, System.Object, this, cb)
end
class = {
base = function (out)
return {
out.UnityEngine.MonoBehaviour
}
end,
Awake = Awake,
StartCor = StartCor,
StopCor = StopCor,
WaitForSec = WaitForSec,
WaitForFrame = WaitForFrame,
SetImageByUrl = SetImageByUrl,
SetImageByUrl1 = SetImageByUrl1,
GetFileTypeByFileName = GetFileTypeByFileName,
GetUrl = GetUrl,
PostUrl = PostUrl,
FloatProcessToStr = FloatProcessToStr,
PlaySound = PlaySound,
Typewriter = Typewriter,
LoadingScene = LoadingScene,
GetTimeStrBySec = GetTimeStrBySec,
ChangeMaterial = ChangeMaterial,
ChangeLayer = ChangeLayer,
PerFrameDo = PerFrameDo,
PerFrameLoad = PerFrameLoad,
LargeNumToString = LargeNumToString,
GetFileTypeByFileName1 = GetFileTypeByFileName1,
LimitStr = LimitStr,
LimitStr1 = LimitStr1,
Base64ToTexture2D = Base64ToTexture2D,
Texture2DToBase64 = Texture2DToBase64,
CreateSpriteByTexture2D = CreateSpriteByTexture2D,
WaitForLandScape = WaitForLandScape,
WaitForPortrait = WaitForPortrait,
static = static
}
return class
end)
end)
System.namespace("", function (namespace)
end)
|
function use_imgui()
includedirs "3rd/imgui"
links "imgui"
end
project "imgui"
location "imgui"
kind "StaticLib"
language "C++"
targetdir ("../bin/" .. outputdir)
objdir ("../bin/obj/" .. outputdir)
files
{
"%{prj.name}/imconfig.h",
"%{prj.name}/imgui.h",
"%{prj.name}/imgui.cpp",
"%{prj.name}/imgui_draw.cpp",
"%{prj.name}/imgui_internal.h",
"%{prj.name}/imgui_widgets.cpp",
"%{prj.name}/imstb_rectpack.h",
"%{prj.name}/imstb_textedit.h",
"%{prj.name}/imstb_truetype.h",
"%{prj.name}/imgui_demo.cpp"
}
filter "system:windows"
systemversion "latest"
cppdialect "C++17"
staticruntime "On"
filter { "system:windows", "configurations:Release"}
buildoptions "/MT"
|
require 'Lua/Utils/class'
require 'Lua/Utils/util'
require 'Lua/Utils/vLog' |
-- Global to all starfalls
local checkluatype = SF.CheckLuaType
local dgetmeta = debug.getmetatable
--- Angle Type
-- @name Angle
-- @class type
-- @libtbl ang_methods
-- @libtbl ang_meta
SF.RegisterType("Angle", nil, nil, debug.getregistry().Angle, nil, function(checktype, ang_meta)
return function(ang)
return setmetatable({ ang:Unpack() }, ang_meta)
end,
function(obj)
checktype(obj, ang_meta, 2)
return Angle(obj[1], obj[2], obj[3])
end
end)
return function(instance)
local checkpermission = instance.player ~= SF.Superuser and SF.Permissions.check or function() end
local ang_methods, ang_meta, awrap, unwrap = instance.Types.Angle.Methods, instance.Types.Angle, instance.Types.Angle.Wrap, instance.Types.Angle.Unwrap
local vec_meta, vwrap, vunwrap = instance.Types.Vector, instance.Types.Vector.Wrap, instance.Types.Vector.Unwrap
local function wrap(tbl)
return setmetatable(tbl, ang_meta)
end
--- Creates an Angle struct.
-- @name builtins_library.Angle
-- @class function
-- @param p - Pitch
-- @param y - Yaw
-- @param r - Roll
-- @return Angle
instance.env.Angle = function (p, y, r)
if p~=nil then checkluatype(p, TYPE_NUMBER) else p = 0 end
if y~=nil then checkluatype(y, TYPE_NUMBER) else y = p end
if r~=nil then checkluatype(r, TYPE_NUMBER) else r = p end
return wrap({ p, y, r })
end
-- Lookup table.
-- Index 1->6 have associative pyr for use in __index. Saves lots of checks
-- String based indexing returns string, just a pass through.
local pyr = { p = 1, y = 2, r = 3, pitch = 1, yaw = 2, roll = 3 }
--- __newindex metamethod
function ang_meta.__newindex(t, k, v)
if pyr[k] then
rawset(t, pyr[k], v)
else
rawset(t, k, v)
end
end
--- __index metamethod
-- Can be indexed with: 1, 2, 3, p, y, r, pitch, yaw, roll. 1,2,3 is most efficient.
function ang_meta.__index(t, k)
local method = ang_methods[k]
if method then
return method
elseif pyr[k] then
return rawget(t, pyr[k])
end
end
local table_concat = table.concat
--- tostring metamethod
-- @return string representing the angle.
function ang_meta.__tostring(a)
return table_concat(a, ' ', 1, 3)
end
--- __mul metamethod ang1 * b or ang1 * ang2.
-- @param b Number or Angle to multiply by.
-- @return resultant angle.
function ang_meta.__mul(a, b)
if isnumber(b) then
return wrap({ a[1] * b, a[2] * b, a[3] * b })
elseif isnumber(a) then
return wrap({ b[1] * a, b[2] * a, b[3] * a })
elseif dgetmeta(a) == ang_meta and dgetmeta(b) == ang_meta then
return wrap({ a[1] * b[1], a[2] * b[2], a[3] * b[3] })
elseif dgetmeta(a) == ang_meta then
checkluatype(b, TYPE_NUMBER)
else
checkluatype(a, TYPE_NUMBER)
end
end
--- __div metamethod ang1 / b or ang1 / ang2.
-- @param b Number or Angle to divided by.
-- @return resultant angle.
function ang_meta.__div(a, b)
if isnumber(b) then
return wrap({ a[1] / b, a[2] / b, a[3] / b })
elseif isnumber(a) then
return wrap({ a / b[1], a / b[2], a / b[3] })
elseif dgetmeta(a) == ang_meta and dgetmeta(b) == ang_meta then
return wrap({ a[1] / b[1], a[2] / b[2], a[3] / b[3] })
elseif dgetmeta(a) == ang_meta then
checkluatype(b, TYPE_NUMBER)
else
checkluatype(a, TYPE_NUMBER)
end
end
--- __unm metamethod -ang.
-- @return resultant angle.
function ang_meta.__unm(a)
return wrap({ -a[1], -a[2], -a[3] })
end
--- __eq metamethod ang1 == ang2.
-- @param a Angle to check against.
-- @return bool
function ang_meta.__eq(a, b)
return a[1]==b[1] and a[2]==b[2] and a[3]==b[3]
end
--- __add metamethod ang1 + ang2.
-- @param a Angle to add.
-- @return resultant angle.
function ang_meta.__add(a, b)
return wrap({ a[1] + b[1], a[2] + b[2], a[3] + b[3] })
end
--- __sub metamethod ang1 - ang2.
-- @param a Angle to subtract.
-- @return resultant angle.
function ang_meta.__sub(a, b)
return wrap({ a[1]-b[1], a[2]-b[2], a[3]-b[3] })
end
--- Returns if p,y,r are all 0.
-- @return boolean
function ang_methods:isZero()
return self[1]==0 and self[2]==0 and self[3]==0
end
--- Return the Forward Vector ( direction the angle points ).
-- @return vector normalised.
function ang_methods:getForward()
return vwrap(unwrap(self):Forward())
end
--- Return the Right Vector relative to the angle dir.
-- @return vector normalised.
function ang_methods:getRight()
return vwrap(unwrap(self):Right())
end
--- Return the Up Vector relative to the angle dir.
-- @return vector normalised.
function ang_methods:getUp()
return vwrap(unwrap(self):Up())
end
--- Return Rotated angle around the specified axis.
-- @param v Vector axis
-- @param deg Number of degrees or nil if radians.
-- @param rad Number of radians or nil if degrees.
-- @return The modified angle
function ang_methods:rotateAroundAxis(v, deg, rad)
if rad then
checkluatype (rad, TYPE_NUMBER)
deg = math.deg(rad)
else
checkluatype (deg, TYPE_NUMBER)
end
local ret = Angle()
ret:Set(unwrap(self))
ret:RotateAroundAxis(vunwrap(v), deg)
return awrap(ret)
end
--- Round the angle values. Self-Modifies.
-- @param idp (Default 0) The integer decimal place to round to.
-- @return nil
function ang_methods:round(idp)
self[1] = math.Round(self[1], idp)
self[2] = math.Round(self[2], idp)
self[3] = math.Round(self[3], idp)
end
--- Copies p,y,r from angle and returns a new angle
-- @return The copy of the angle
function ang_methods:clone()
return wrap({ self[1], self[2], self[3] })
end
--- Copies p,y,r from angle to another.
-- @param b The angle to copy from.
-- @return nil
function ang_methods:set(b)
self[1] = b[1]
self[2] = b[2]
self[3] = b[3]
end
--- Sets p,y,r to 0. This is faster than doing it manually.
-- @return nil
function ang_methods:setZero()
self[1] = 0
self[2] = 0
self[3] = 0
end
--- Set's the angle's pitch and returns it.
-- @param p The pitch
-- @return The modified angle
function ang_methods:setP(p)
self[1] = p
return self
end
--- Set's the angle's yaw and returns it.
-- @param y The yaw
-- @return The modified angle
function ang_methods:setY(y)
self[2] = y
return self
end
--- Set's the angle's roll and returns it.
-- @param r The roll
-- @return The modified angle
function ang_methods:setR(r)
self[3] = r
return self
end
end
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
local Clockwork = Clockwork;
local GROUP_SUPER = 1;
local GROUP_ADMIN = 2;
local GROUP_OPER = 3;
local GROUP_USER = 4;
if (CLIENT) then
local SYSTEM = Clockwork.system:New("ManageGroups");
SYSTEM.image = "clockwork/system/groups";
SYSTEM.toolTip = "ManageGroupsHelp";
SYSTEM.groupType = GROUP_USER;
SYSTEM.groupPage = 1;
SYSTEM.groupPlayers = nil;
SYSTEM.doesCreateForm = false;
-- Called to get whether the local player has access to the system.
function SYSTEM:HasAccess()
if (!Clockwork.config:Get("use_own_group_system"):Get()) then
local commandTable = Clockwork.command:FindByID("PlySetGroup");
if (commandTable and Clockwork.player:HasFlags(Clockwork.Client, commandTable.access)) then
return true;
end;
end;
end;
-- Called when the system should be displayed.
function SYSTEM:OnDisplay(systemPanel, systemForm)
if (self.groupType == GROUP_USER) then
local label = vgui.Create("cwInfoText", systemPanel);
label:SetText(L("ManageGroupsSelectingGroup"));
label:SetInfoColor("blue");
label:DockMargin(0, 0, 0, 8);
systemPanel.panelList:AddItem(label);
local userGroupsForm = vgui.Create("cwBasicForm", systemPanel);
userGroupsForm:SetText(L("ManageGroupsUserGroups"));
userGroupsForm:SetPadding(8);
userGroupsForm:SetAutoSize(true);
systemPanel.panelList:AddItem(userGroupsForm);
local userGroups = {
L("ManageGroupsSuperAdmins"),
L("ManageGroupsAdmins"),
L("ManageGroupsOperators")
};
for k, v in pairs(userGroups) do
local groupButton = vgui.Create("DButton", systemPanel);
groupButton:SetToolTip(L("ManageGroupsManageWithin", v));
groupButton:SetText(v);
groupButton:SetWide(systemPanel:GetParent():GetWide());
-- Called when the button is clicked.
function groupButton.DoClick(button)
self.groupPlayers = nil;
self.groupType = k;
self:Rebuild();
end;
userGroupsForm:AddItem(groupButton);
end;
else
local backButton = vgui.Create("DButton", systemPanel);
backButton:SetText(L("ManageGroupsBackToGroups"));
backButton:SetWide(systemPanel:GetParent():GetWide());
-- Called when the button is clicked.
function backButton.DoClick(button)
self.groupType = GROUP_USER;
self:Rebuild();
end;
systemPanel.navigationForm:AddItem(backButton);
if (!self.noRefresh) then
Clockwork.datastream:Start("SystemGroupGet", {self.groupType, self.groupPage});
else
self.noRefresh = nil;
end;
if (self.groupPlayers) then
if (#self.groupPlayers > 0) then
for k, v in pairs(self.groupPlayers) do
local label = vgui.Create("cwInfoText", systemPanel);
label:SetText(v.steamName);
label:SetButton(true);
label:SetToolTip(L("ManageGroupsSteamIDInfo", v.steamID));
label:SetInfoColor("blue");
systemPanel.panelList:AddItem(label);
-- Called when the button is clicked.
function label.DoClick(button)
local commandTable = Clockwork.command:FindByID("PlyDemote");
if (commandTable and Clockwork.player:HasFlags(Clockwork.Client, commandTable.access)) then
Derma_Query(L("ManageGroupsDemoteText", v.steamName), L("ManageGroupsDemoteTitle"), L("Yes"), function()
Clockwork.datastream:Start("SystemGroupDemote", {v.steamID, v.steamName, self.groupType});
end, "No", function() end);
end;
end;
end;
if (self.pageCount > 1) then
local pageForm = vgui.Create("cwBasicForm", systemPanel);
pageForm:SetText(L("PageCount", self.groupPage, self.pageCount));
pageForm:SetPadding(8);
pageForm:SetAutoSize(true);
systemPanel.panelList:AddItem(pageForm);
if (self.isNext) then
local nextButton = pageForm:Button("Next");
-- Called when the button is clicked.
function nextButton.DoClick(button)
Clockwork.datastream:Start("SystemGroupGet", {self.groupType, self.groupPage + 1});
end;
end;
if (self.isBack) then
local backButton = pageForm:Button("Back");
-- Called when the button is clicked.
function backButton.DoClick(button)
Clockwork.datastream:Start("SystemGroupGet", {self.groupType, self.groupPage - 1});
end;
end;
end;
else
local label = vgui.Create("cwInfoText", systemPanel);
label:SetText(L("ManageGroupsNoUsers"));
label:SetInfoColor("orange");
systemPanel.panelList:AddItem(label);
end;
else
local label = vgui.Create("cwInfoText", systemPanel);
label:SetText(L("ManageGroupsGettingUsers"));
label:SetInfoColor("blue");
systemPanel.panelList:AddItem(label);
end;
end;
end;
SYSTEM:Register();
Clockwork.datastream:Hook("SystemGroupRebuild", function(data)
local systemTable = Clockwork.system:FindByID("ManageGroups");
if (systemTable and systemTable:IsActive()) then
systemTable:Rebuild();
end;
end);
Clockwork.datastream:Hook("SystemGroupGet", function(data)
if (type(data) == "table") then
local systemTable = Clockwork.system:FindByID("ManageGroups");
if (systemTable) then
systemTable.groupPlayers = data.players;
systemTable.groupPage = data.page;
systemTable.pageCount = data.pageCount;
systemTable.noRefresh = true;
systemTable.isBack = data.isBack;
systemTable.isNext = data.isNext;
systemTable:Rebuild();
end;
else
local systemTable = Clockwork.system:FindByID("ManageGroups");
if (systemTable) then
systemTable.groupPlayers = {};
systemTable.groupPage = 1;
systemTable.noRefresh = true;
if (systemTable:IsActive()) then
systemTable:Rebuild();
end;
end;
end;
end);
else
Clockwork.datastream:Hook("SystemGroupDemote", function(player, data)
local commandTable = Clockwork.command:FindByID("PlyDemote");
if (commandTable and type(data) == "table"
and Clockwork.player:HasFlags(player, commandTable.access)) then
local target = Clockwork.player:FindByID(data[1]);
if (target) then
Clockwork.player:RunClockworkCommand(player, "PlyDemote", data[1]);
timer.Simple(1, function()
if (IsValid(player)) then
Clockwork.datastream:Start(player, "SystemGroupRebuild", true);
end;
end);
else
local schemaFolder = Clockwork.kernel:GetSchemaFolder();
local playersTable = Clockwork.config:Get("mysql_players_table"):Get();
local cwUserGroup = "user";
if (data[3] == GROUP_SUPER) then
cwUserGroup = "superadmin";
elseif (data[3] == GROUP_ADMIN) then
cwUserGroup = "admin";
elseif (data[3] == GROUP_OPER) then
cwUserGroup = "operator";
end;
local queryObj = Clockwork.database:Update(playersTable);
queryObj:SetValue("_UserGroup", "user");
queryObj:AddWhere("_Schema = ?", schemaFolder);
queryObj:AddWhere("_SteamID = ?", data[1]);
queryObj:SetCallback(function(result)
Clockwork.datastream:Start(player, "SystemGroupRebuild", true);
end);
queryObj:Push();
Clockwork.player:NotifyAll({"PlayerDemotedUserToGroup", player:Name(), data[2], cwUserGroup, "user"});
end;
end;
end);
Clockwork.datastream:Hook("SystemGroupGet", function(player, data)
if (type(data) != "table") then
return;
end;
local groupType = tonumber(data[1]);
local groupPage = tonumber(data[2]);
if (groupPage) then
local groupPlayers = {};
local sendPlayers = {};
local finishIndex = groupPage * 8;
local startIndex = finishIndex - 7;
local groupName = "user";
local pageCount = 0;
if (groupType == GROUP_SUPER) then
groupName = "superadmin";
elseif (groupType == GROUP_ADMIN) then
groupName = "admin";
elseif (groupType == GROUP_OPER) then
groupName = "operator";
end;
local schemaFolder = Clockwork.kernel:GetSchemaFolder();
local playersTable = Clockwork.config:Get("mysql_players_table"):Get();
local queryObj = Clockwork.database:Select(playersTable);
queryObj:SetCallback(function(result)
if (Clockwork.database:IsResult(result)) then
for k, v in pairs(result) do
groupPlayers[#groupPlayers + 1] = {
steamName = v._SteamName,
steamID = v._SteamID
};
end;
end;
table.sort(groupPlayers, function(a, b)
return a.steamName < b.steamName;
end);
pageCount = math.ceil(#groupPlayers / 8);
for k, v in pairs(groupPlayers) do
if (k >= startIndex and k <= finishIndex) then
sendPlayers[#sendPlayers + 1] = v;
end;
end;
if (#sendPlayers > 0) then
Clockwork.datastream:Start(player, "SystemGroupGet", {
pageCount = pageCount,
players = sendPlayers,
isNext = (groupPlayers[finishIndex + 1] != nil),
isBack = (groupPlayers[startIndex - 1] != nil),
page = groupPage
});
else
Clockwork.datastream:Start(player, "SystemGroupGet", false);
end;
end);
queryObj:AddWhere("_Schema = ?", schemaFolder);
queryObj:AddWhere("_UserGroup = ?", groupName);
queryObj:Pull();
end;
end);
end; |
--[[ Copyright (C) 2018 Google Inc.
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.
]]
local events = require 'dmlab.system.events'
local tensor = require 'dmlab.system.tensor'
local game_rewards = {}
game_rewards.REASONS = {
-- `playerId` touched reward pickup.
'PICKUP_REWARD',
-- `playerId` touched goal pickup.
'PICKUP_GOAL',
-- Level triggered a reward at `playerId`.
'TARGET_SCORE',
-- `playerId` tagged self.
'TAG_SELF',
-- `playerId` tagged `otherPlayerId`
'TAG_PLAYER',
-- `playerId` picked up enemy flag.
'CTF_FLAG_BONUS',
-- `playerId` captured the opposing team's flag.
'CTF_CAPTURE_BONUS',
-- `playerId` is part of a team that has captured the opposing team's flag.
'CTF_TEAM_BONUS',
-- `playerId` tagged opponent(`otherPlayerId`) flag carrier.
'CTF_FRAG_CARRIER_BONUS',
-- `playerId` returned their team flag to the team's base.
'CTF_RECOVERY_BONUS',
-- `playerId` is on the same team as the flag carrier and tagged opponent
-- (`otherPlayerId`) who damaged our flag carrier.
'CTF_CARRIER_DANGER_PROTECT_BONUS',
-- `playerId` tagged opponent(`otherPlayerId`) while `playerId` or
-- `otherPlayerId` is near `playerId`'s flag.
'CTF_FLAG_DEFENSE_BONUS',
-- `playerId` tagged opponent(`otherPlayerId`) while `playerId` or
-- `otherPlayerId` is near `playerId`'s flag carrier.
'CTF_CARRIER_PROTECT_BONUS',
-- `playerId` returned the team flag just before payerId's team captured
-- the opposing team's flag.
'CTF_RETURN_FLAG_ASSIST_BONUS',
-- `playerId` tagged opponent team's flag carrier just before a capturing
-- event occurred.
'CTF_FRAG_CARRIER_ASSIST_BONUS',
}
function game_rewards:initScoreOveride(kwargs)
kwargs.reward = {}
kwargs.reward.red = {}
kwargs.reward.blue = {}
for _, reason in ipairs(self.REASONS) do
kwargs.reward[reason] = false
kwargs.reward.red[reason] = false
kwargs.reward.blue[reason] = false
end
end
function game_rewards:overrideScore(kwargs, rewardInfo)
local playerId = rewardInfo.playerId
local reason = rewardInfo.reason
local team = rewardInfo.team
local location = rewardInfo.location or {0, 0, 0}
local otherPlayerId = rewardInfo.otherPlayerId or -1
local score = kwargs.reward and kwargs.reward[team] and
kwargs.reward[team][reason] or kwargs.reward[reason] or
rewardInfo.score
score = tonumber(score)
local d = tensor.DoubleTensor
events:add('reward', reason, team, d{score}, d{playerId}, d(location),
d{otherPlayerId})
return score
end
return game_rewards
|
-------------------------------------------------
-- Calendar Widget for Awesome Window Manager
-- Shows the current month and supports scroll up/down to switch month
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/calendar-widget
-- @author Pavel Makhov
-- @copyright 2019 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local beautiful = require("beautiful")
local wibox = require("wibox")
local gears = require("gears")
local calendar_widget = {}
local styles = {}
local function rounded_shape(size)
return function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, size)
end
end
styles.month = {
padding = 4,
bg_color = '#2E3440',
border_width = 0,
}
styles.normal = {
markup = function(t) return t end,
shape = rounded_shape(4)
}
styles.focus = {
fg_color = '#000000',
bg_color = '#88C0D0',
markup = function(t) return '<b>' .. t .. '</b>' end,
shape = rounded_shape(4)
}
styles.header = {
fg_color = '#E5E9F0',
markup = function(t) return '<b>' .. t .. '</b>' end,
bg_color = '#2E3440'
}
styles.weekday = {
fg_color = '#88C0D0',
markup = function(t) return '<b>' .. t .. '</b>' end,
bg_color = '#2E3440',
}
local function decorate_cell(widget, flag, date)
if flag == 'monthheader' and not styles.monthheader then
flag = 'header'
end
-- highlight only today's day
if flag == 'focus' then
local today = os.date('*t')
if today.month ~= date.month then
flag = 'normal'
end
end
local props = styles[flag] or {}
if props.markup and widget.get_text and widget.set_markup then
widget:set_markup(props.markup(widget:get_text()))
end
-- Change bg color for weekends
local d = { year = date.year, month = (date.month or 1), day = (date.day or 1) }
local weekday = tonumber(os.date('%w', os.time(d)))
local default_bg = (weekday == 0 or weekday == 6) and '#3B4252' or '#2E3440'
local ret = wibox.widget {
{
{
widget,
halign = 'center',
widget = wibox.container.place
},
margins = (props.padding or 2) + (props.border_width or 0),
widget = wibox.container.margin
},
shape = props.shape,
shape_border_color = props.border_color or '#b9214f',
shape_border_width = props.border_width or 0,
fg = props.fg_color or '#D8DEE9',
bg = props.bg_color or default_bg,
widget = wibox.container.background
}
return ret
end
local cal = wibox.widget {
date = os.date('*t'),
font = beautiful.get_font(),
fn_embed = decorate_cell,
long_weekdays = true,
widget = wibox.widget.calendar.month
}
local popup = awful.popup {
ontop = true,
visible = false,
shape = gears.shape.rounded_rect,
preferred_positions = top,
offset = { y = 5 },
border_width = 1,
border_color = '#4C566A',
widget = cal
}
popup:buttons(
awful.util.table.join(
awful.button({}, 4, function()
local a = cal:get_date()
a.month = a.month + 1
cal:set_date(nil)
cal:set_date(a)
popup:set_widget(cal)
end),
awful.button({}, 5, function()
local a = cal:get_date()
a.month = a.month - 1
cal:set_date(nil)
cal:set_date(a)
popup:set_widget(cal)
end)
)
)
function calendar_widget.toggle()
if popup.visible then
-- to faster render the calendar refresh it and just hide
cal:set_date(nil) -- the new date is not set without removing the old one
cal:set_date(os.date('*t'))
popup:set_widget(nil) -- just in case
popup:set_widget(cal)
popup.visible = not popup.visible
else
if not beautiful.calendar_placement then
awful.placement.top(popup, { margins = { top = 30 }, parent = awful.screen.focused() })
elseif beautiful.calendar_placement == 'top' then
awful.placement.top(popup, { margins = { top = 30 }, parent = awful.screen.focused() })
elseif beautiful.calendar_placement == 'top_right' then
awful.placement.top_right(popup, { margins = { top = 30, right = 10}, parent = awful.screen.focused() })
elseif beautiful.calendar_placement == 'bottom_right' then
awful.placement.bottom_right(popup, { margins = { bottom = 20, right = 10}, parent = awful.screen.focused() })
else
awful.placement.top(popup, { margins = { top = 30 }, parent = awful.screen.focused() })
end
popup.visible = true
end
end
return calendar_widget
|
local luview = require 'luview'
local lunum = require 'lunum'
local utils = require 'test.utils'
local window = luview.Window()
local box = luview.BoundingBox()
local tess = luview.Tesselation3D()
window:set_color(0.2, 0.2, 0.2)
tess:set_color(0.2, 0.8, 0.2)
tess:set_alpha(0.4)
tess:set_linewidth(5.0)
local shade = luview.ShaderProgram()
utils.load_shader("lambertian", shade)
--tess:set_shader(shade)
while window:render_scene({box, tess}) == "continue" do end
|
fx_version 'cerulean'
games { 'gta5' }
author 'FireStudio'
client_scripts {
'fs_client.lua'
}
server_scripts {
'fs_server.lua'
} |
-----------------------------------
-- Area: Western Adoulin (256)
-- NPC: Levil
-- Type: Quest and SoA Missions NPC
-- !pos -87.204 3.350 12.655
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local arceliaAppears = player:getCurrentMission(SOA) == tpz.mission.id.soa.ARCIELA_APPEARS_AGAIN
if arceliaAppears and player:getFameLevel(ADOULIN) >= 4 then
if player:getCharVar("SOA") == 0 then
player:startEvent(6)
else
player:startEvent(7)
end
else
player:startEvent(40)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if (csid == 6 or csid == 7) and option == 1 then
player:setCharVar("SOA", 0)
player:completeMission(SOA,tpz.mission.id.soa.ARCIELA_APPEARS_AGAIN)
player:addMission(SOA,tpz.mission.id.soa.BUILDING_PROSPECTS)
elseif csid == 6 and option == 0 then
player:setCharVar("SOA", 1)
end
end
|
local help_message = [[
This is a module file for the container quay.io/biocontainers/ebisearch:0.0.3--py27_1, which exposes the
following programs:
- ebi_metagenomics
- ebisearch
- flake8
- pycodestyle
- pyflakes
This container was pulled from:
https://quay.io/repository/biocontainers/ebisearch
If you encounter errors in ebisearch or need help running the
tools it contains, please contact the developer at
https://quay.io/repository/biocontainers/ebisearch
For errors in the container or module file, please
submit a ticket at
gzynda@tacc.utexas.edu
https://portal.tacc.utexas.edu/tacc-consulting
]]
help(help_message,"\n")
whatis("Name: ebisearch")
whatis("Version: ctr-0.0.3--py27_1")
whatis("Category: ['Bioinformatics']")
whatis("Keywords: ['Biocontainer']")
whatis("Description: The ebisearch package")
whatis("URL: https://quay.io/repository/biocontainers/ebisearch")
set_shell_function("ebi_metagenomics",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg ebi_metagenomics $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg ebi_metagenomics $*')
set_shell_function("ebisearch",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg ebisearch $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg ebisearch $*')
set_shell_function("flake8",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg flake8 $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg flake8 $*')
set_shell_function("pycodestyle",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg pycodestyle $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg pycodestyle $*')
set_shell_function("pyflakes",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg pyflakes $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/ebisearch/ebisearch-0.0.3--py27_1.simg pyflakes $*')
|
--[[
ModuleName : TIMER
Path : module/timer
Author : louiejin
CreateTime : 2019-08-16 23:39:14
Description :
--]]
local add_timer = IMPL_TIMER.add_timer
local remove_timer = IMPL_TIMER.remove_timer
function table_remove_timer(tbl, timerid)
remove_timer(timerid)
if not tbl.__timers then return end
tbl.__timers[timerid] = nil
end
function table_remove_all_timers(tbl)
local timerid_map = tbl.__timers
if not tbl.__timers then return end
for timerid, _ in pairs(timerid_map) do
remove_timer(timerid)
end
tbl.__timers = nil
end
-- 关联Object
Object.remove_timer = table_remove_timer
Object.remove_all_timers = table_remove_all_timers
local add_timer_func_map = {}
function add_timer_func_map.call_after(delay, callback)
return add_timer(delay, 0, 1, callback)
end
function add_timer_func_map.call_after_fre(delay, interval, count, callback)
return add_timer(delay, interval, count, callback)
end
function add_timer_func_map.call_fre(interval, callback)
return add_timer(interval, interval, - 1, callback)
end
local function time2delay(time)
return time - TIME.get_time_millis()
end
function add_timer_func_map.call_at(time, callback)
return add_timer(time2delay(time), 0, 1, callback)
end
function add_timer_func_map.call_at_fre(time, interval, count, callback)
return add_timer(time2delay(time), interval, count, callback)
end
local function table_add_timerid(tbl, timerid)
if not tbl.__timers then
tbl.__timers = {}
end
tbl.__timers[timerid] = true
return timerid
end
function __init__(module, updated)
--[[
TIMER.table_call_after(tbl, delay, callback)
TIMER.table_call_after_fre(tbl, delay, interval, count, callback)
TIMER.table_call_fre(tbl, interval, callback, key)
TIMER.table_call_at(tbl, time, callback)
TIMER.table_call_at_fre(tbl, time, interval, count, callback)
对应的删除函数:
TIMER.table_remove_timer(tbl, timerKey)
TIMER.table_remove_all_timers(tbl)
--]]
for funcname, func in pairs(add_timer_func_map) do
module["table_" .. funcname] = function(tbl, ...)
return table_add_timerid(tbl, func(...))
end
end
--[[
Object:call_after(delay, callback)
Object:call_after_fre(delay, interval, count, callback)
Object:call_fre(interval, callback, key)
Object:call_at(time, callback)
Object:call_at_fre(time, interval, count, callback)
对应的删除函数:
Object:remove_timer(timerKey)
Object:table_remove_all_timers()
--]]
for funcname, func in pairs(add_timer_func_map) do
Object[funcname] = function(obj, ...)
return table_add_timerid(obj, func(...))
end
end
end
|
-- change lectionary_styles to .sil
-- switch to new project and latest sile
-- process usx to input form, test for year B
-- support <eject/>
-- add headings to year C, test
-- get lectionary test data
-- port to windows
-- SILE.debugFlags["break"] = true
-- SILE.debugFlags.dump = true
local plain = SILE.require("classes/plain");
local twocol = std.tree.clone(plain);
twocol.id = "twocol"
twocol:loadPackage("masters")
twocol:defineMaster({ id = "right", firstContentFrame = "content", frames = {
content = {
left = "18%",
right = "90%",
top = "10%",
bottom = "top(footnotes)"
},
runningHead = {
left = "left(content)",
right = "right(content)",
top = "top(content) - 5%",
bottom = "top(content)-2%"
},
footnotes = {
left="left(content)",
right = "right(content)",
height = "0",
bottom="92%"}
}})
twocol:loadPackage("twoside", { oddPageMaster = "right", evenPageMaster = "left" });
twocol:mirrorMaster("right", "left")
twocol.pageTemplate = SILE.scratch.masters["right"]
function twocol:newPage()
twocol:switchPage()
-- print("newPage oddPage="..twocol:oddPage())
return plain.newPage(self)
end
SILE.scratch.headers = {}
SILE.scratch.headers.newHeader = false
SILE.scratch.headers.pageno = 0
SILE.registerCommand("h",
function(options, content)
SILE.scratch.headers.top = content
SILE.scratch.headers.newHeader = true
end, "Text to appear on the top of the left page")
function twocol:endPage()
SILE.scratch.headers.pageno = SILE.scratch.headers.pageno + 1
io.write("["..SILE.scratch.headers.pageno.."] ")
SILE.typesetNaturally(
SILE.getFrame("runningHead"),
-- running header is centered, ommitted on first page of section
-- page number is at outside margin
function()
SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue)
SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue)
if not twocol:oddPage() then
SILE.Commands["bodyfont"](
{},
function()
SILE.typesetter:typeset(SILE.scratch.headers.pageno.."")
end)
end
SILE.call("hss")
if not SILE.scratch.headers.newHeader and SILE.scratch.headers.top then
SILE.Commands["hfont"](
{},
function()
SILE.process(SILE.scratch.headers.top)
end)
end
SILE.call("hss")
if twocol:oddPage() then
SILE.Commands["bodyfont"](
{},
function()
SILE.typesetter:typeset(SILE.scratch.headers.pageno.."")
end)
end
end)
SILE.scratch.headers.newHeader = false
end
local typesetter = SILE.defaultTypesetter {};
SILE.typesetter = typesetter
local function twocol_func(options, content)
SU.debug("typesetter", " start twocols")
typesetter:startTwoCol()
SILE.process(content)
typesetter:leaveHmode()
typesetter.allTwoColMaterialProcessed = true
while typesetter:pageBuilder() do
typesetter:initNextFrame()
end
typesetter:endTwoCol()
end
-- in order to not have extra space between paragraphs, make
-- font size + parskip = baselineskip
SILE.settings.set("document.parskip", SILE.nodefactory.newVglue("2pt"))
SILE.settings.set("document.baselineskip", SILE.nodefactory.newVglue("14pt"))
SILE.registerCommand("lineskip", function ( options, content )
SILE.typesetter:leaveHmode();
SILE.typesetter:pushVglue(SILE.settings.get("document.baselineskip"))
end, "Skip vertically by a line")
SILE.registerCommand("twocol", twocol_func,
"Temporarily switch to two balanced columns")
-- If we are near the end of a page this is a good place to break
local plus90 = SILE.nodefactory.newVglue(
{height = SILE.length.new({length = 90})})
local minus90 = SILE.nodefactory.newVglue(
{height = SILE.length.new({length = -90})})
SILE.registerCommand("gdbreak", function(o,c)
SILE.typesetter:leaveHmode()
SILE.typesetter:pushPenalty({ flagged= 1, penalty= -500 })
SILE.typesetter:pushVglue(plus90)
SILE.typesetter:pushPenalty({ flagged= 1, penalty= -500 })
SILE.typesetter:pushVglue(minus90)
end, "good place to break")
function typesetter:init()
self.left = 0
self.frame = SILE.frames["content"]
local ret = SILE.defaultTypesetter.init(self, self.frame)
self.gapWidth = .05 * self.frame:width()
return ret
end
function typesetter:startTwoCol()
SILE.typesetter:leaveHmode()
self.columnWidth = (self.frame:width() - self.gapWidth) / 2
SILE.settings.set("typesetter.breakwidth", SILE.length.new({ length = self.columnWidth }))
local oq = self.state.outputQueue
self.left = #oq + 1
self.allTwoColMaterialProcessed = false
end
function typesetter:endTwoCol()
SILE.settings.set("typesetter.breakwidth", SILE.length.new({ length = self.frame:width() }))
self.left = 0
end
-- Output one page.
-- Return true if page is complete.
function typesetter:pageBuilder(independent)
-- if not two column material present, use default typesetter
if self.left == 0 then
return SILE.defaultTypesetter.pageBuilder(self, independent)
end
-- process all two column material before attempting to build page
if not self.allTwoColMaterialProcessed then return false end
local oq = self.state.outputQueue
-- make 2col material start at first non-zero height vbox
while self.left <= #oq do
local box = oq[self.left]
if box:isVbox() and box.height and box.height.length > 0 then break end
self.left = self.left+1
end
if self.left > #oq then
SU.debug("columns", " pageBuilder RETURN empty oq / false")
self:endTwoCol()
return false
end
SU.debug("columns", "pageBuilder left="..self.left..", #oq="..#oq)
local currentHeight = typesetter:totalHeight(1, self.left)
local targetHeight = SILE.length.new({ length = self.frame:height() })
targetHeight = targetHeight - currentHeight
local p
self.right, self.rightEnd, p = tcpb.findBestTwoColBreak(
oq, self.left, targetHeight)
if self.right then
assert(self.right > self.left)
assert(self.rightEnd)
assert(self.rightEnd >= self.right)
assert(self.rightEnd <= #oq+1)
end
-- if can't fit any two column content on page then
-- output all the one column content and eject
if not self.right then
assert(self.left > 1)
self:outputLinesToPage2(1, self.left)
self.left = 1
SU.debug("columns",
" pageBuilder RETURN can't fit 2col material on page / true")
return true
end
-- gather all the two column material between [self.left,self.rightEnd) that
-- will fit on current page and place it in a single box at self.left
typesetter:createTwoColVbox()
self.rightEnd = self.left + 1
-- if we have processed all the two column material then
-- exit two column mode but do not output page because more
-- material may still fit.
if self.rightEnd == #oq+1 then
SU.debug("columns",
" pageBuilder RETURN end 2c, page not full / false")
self:endTwoCol()
return false
end
-- page is full, output it.
-- stay in two col mode to output the rest
local totalHeight = typesetter:totalHeight(1, self.rightEnd)
local glues, gTotal = self:accumulateGlues(1, self.rightEnd)
self:adjustGlues(targetHeight, totalHeight, glues, gTotal)
self:outputLinesToPage2(1, self.rightEnd);
self.left = 1
SU.debug("columns",
"pageBuilder RETURN produced 2c page, more 2c material to process / true")
return true
end
function typesetter:createTwoColVbox()
local oq = self.state.outputQueue
local vbox = SILE.nodefactory.newVbox({})
vbox.outputYourself = twoColBoxOutputYourself
while self.rightEnd > self.right and isDiscardable(oq[self.rightEnd-1]) do
self.rightEnd = self.rightEnd - 1
end
vbox.rightCol = typesetter:extract(self.right, self.rightEnd)
typesetter:removeDiscardable(vbox.rightCol)
--typesetter:dump("rightCol", vbox.rightCol)
while self.left <= #oq and isDiscardable(oq[self.left]) do
self.left = self.left + 1
end
vbox.leftCol = typesetter:extract(self.left, self.right)
typesetter:removeDiscardable(vbox.leftCol)
--typesetter:dump("rightCol", vbox.leftCol)
vbox.height = 0
vbox.depth = tcpb.columnHeight(vbox.leftCol, 1, #vbox.leftCol)
vbox.depth.stretch = 0
vbox.depth.shrink = 0
table.insert(oq, self.left, vbox)
end
function typesetter:extract(first, last)
local oq = self.state.outputQueue
local col, i = {}, nil
for i=first,last-1 do
col[#col+1] = oq[first]
-- if col[#col]:isVglue() then col[#col]:setGlue(0) end
table.remove(oq, first)
end
return col
end
function typesetter:removeDiscardable(col)
while #col > 0 and isDiscardable(col[1]) do table.remove(col, 1) end
while #col > 0 and isDiscardable(col[#col]) do table.remove(col, #col) end
end
function isDiscardable(box) return box:isPenalty() or box:isVglue() end
function twoColBoxOutputYourself(vbox, typesetter, line)
local y0 = typesetter.frame.state.cursorY
SU.debug("oyv", "y0="..y0)
-- line up right column baseline with left column baseline
typesetter.frame:moveY(vbox.leftCol[1].height.length)
if #vbox.rightCol > 0 then
typesetter.frame:moveY(-vbox.rightCol[1].height.length)
end
local horizOffset = typesetter.columnWidth + typesetter.gapWidth
columnOutputYourself(vbox.rightCol, typesetter, horizOffset, line, "right")
typesetter.frame.state.cursorY = y0
columnOutputYourself(vbox.leftCol, typesetter, 0, line, "left")
end
-- output one column of a custom two column vbox
function columnOutputYourself(col, typesetter, horizOffset, line, side)
SU.debug("oyv", "output "..side.." column")
local i
for i=1,#col do
typesetter.frame:newLine()
typesetter.frame:moveX(horizOffset)
local box = col[i]
box:outputYourself(typesetter, box)
end
end
function typesetter:dump(heading, oq)
if SILE.debugFlags["dump"] then
print(heading)
for i=1,#oq do
print(i, oq[i])
end
print()
end
end
function typesetter:totalHeight(left, right)
return tcpb.columnHeight(self.state.outputQueue, left, right)
end
-- first = first oq item to output
-- last = first oq item to not output
function typesetter:outputLinesToPage2(first, last)
if last <= first then return end
local oq = self.state.outputQueue
assert(last > first)
assert(last-1 <= #oq)
if SILE.debugFlags["outputLinesToPage2"] then
print("outputLinesToPage2")
for i=first,last do
print(i, oq[i])
end
end
SU.debug("pagebuilder", "OUTPUTTING frame "..self.frame.id);
local i
for i = first,last-1 do
local line = oq[i]
assert(line, "empty oq element at position "..i.." of "..#oq)
if not self.frame.state.totals.pastTop and not (line:isVglue() or line:isPenalty()) then
self.frame.state.totals.pastTop = true
end
if self.frame.state.totals.pastTop then
line:outputYourself(self, line)
end
end
self:removeFromOutputQueue(first, last)
end
function typesetter:removeFromOutputQueue(first, last)
local i
for i=1,last-first do
table.remove(self.state.outputQueue, first)
end
end
-- look at page, find all glues, return them and their total height
function typesetter:accumulateGlues(first, last)
local glues = {}
local totalGlueHeight = SILE.length.new()
local oq = self.state.outputQueue
local i
for i=first,last-1 do
if oq[i]:isVglue() then
table.insert(glues,oq[i]);
totalGlueHeight = totalGlueHeight + oq[i].height
end
end
return glues, totalGlueHeight
end
-- stretch vertical glues to match targetHeight
function typesetter:adjustGlues(targetHeight, totalHeight, glues, gTotal)
local adjustment = (targetHeight - totalHeight)
if type(adjustment) == "table" then adjustment = adjustment.length end
if (adjustment > gTotal.stretch) then adjustment = gTotal.stretch end
if (adjustment / gTotal.stretch > 0) then
for i,g in pairs(glues) do
g:setGlue(adjustment * g.height.stretch / gTotal.stretch)
end
end
SU.debug("pagebuilder", "Glues for self page adjusted by "..(adjustment/gTotal.stretch) )
end
tcpb = {}
local overfull = 1073741820
-- Look at all the material left..#oq.
-- Find 'best' place into two columns that fit on current page.
-- Return right, rightEnd, penalty.
-- Penalty will be ovefull if there is no way to fit anything on page.
function tcpb.findBestTwoColBreak(oq, left, targetHeight)
assert(left >= 1 and left <= #oq)
if SILE.debugFlags.twocol then
print("findBestTwoColBreak left="..left..","..
"targetHeight="..targetHeight..", ("..#oq..")")
for i=left,#oq do
print(i, oq[i])
end
end
local right, rightEnd, penalty = nil, nil, overfull -- outputs
local _right, _rightEnd, _penalty, _height
for _right=left+1,#oq+1 do
if _right == #oq+1 or oq[_right]:isVbox() then
local _rightEnd, _penalty, _height = tcpb.findBestTwoColBreak2(
oq, left, _right, targetHeight)
if _height > targetHeight then break end
if _rightEnd and _penalty <= penalty then
right, rightEnd, penalty = _right, _rightEnd, _penalty
end
end
end
SU.debug("twocol",
" ****** right="..right..", rightEnd="..rightEnd..", penalty="..penalty)
return right, rightEnd, penalty
end
-- warning! right may be as large as #oq+1
-- returns rightEnd, penalty, height
function tcpb.findBestTwoColBreak2(oq, left, right, targetHeight)
SU.debug("twocol",
" findBestTwoColBreak2 left="..left..
", right="..right..", targetHeight="..targetHeight)
local rightEnd, penalty, leftHeight = nil, overfull, nil -- outputs
leftHeight = tcpb.columnHeight(oq, left, right)
if leftHeight > targetHeight then return rightEnd, penalty, leftHeight end
local leftPenalty = tcpb.columnPenalty(oq, right)
for _rightEnd=right,#oq+1 do
if _rightEnd == #oq+1 or oq[_rightEnd]:isVbox() then
local rightHeight = tcpb.columnHeight(oq, right, _rightEnd)
if rightHeight > leftHeight then
SU.debug("twocol", " rightHeight > leftHeight")
break
end
local rightPenalty = tcpb.columnPenalty(oq, _rightEnd)
local pageBottomGap = targetHeight - leftHeight
local interColumnGap = leftHeight - rightHeight
local remainingLines = tcpb.countLines(oq, _rightEnd)
local _penalty = tcpb.calculatePenalty(leftPenalty, rightPenalty,
pageBottomGap, interColumnGap, remainingLines)
SU.debug("twocol", " *** ".._penalty.." "..right.."/".._rightEnd)
if _rightEnd and _penalty <= penalty then
rightEnd, penalty = _rightEnd, _penalty
end
end
end
SU.debug("twocol", " *** ", penalty.." "..right.."/"..rightEnd..", h="..leftHeight)
return rightEnd, penalty, leftHeight
end
function tcpb.countLines(oq, first)
local count = 0
for i=first,#oq do
if oq[i]:isVbox() then count = count+1 end
end
return count
end
-- return penalty
function tcpb.calculatePenalty(leftPenalty, rightPenalty, pageBottomGap, interColumnGap, remainingLines)
local penalty
if leftPenalty > 100 or rightPenalty > 100 then
penalty = overfull
else
penalty = pageBottomGap.length + interColumnGap.length + 1000*remainingLines
end
return penalty
end
function tcpb.columnHeight(oq, first, last)
local h = SILE.length.new({})
local i
for i=first,last-1 do
h = h + oq[i].height + oq[i].depth
end
return h
end
-- return height, penalty
function tcpb.columnPenalty(oq, last)
local p = 0
last = last-1
while last >= 1 and oq[last]:isVglue() do last = last-1 end
if last >= 1 and oq[last]:isPenalty() then p = oq[last].penalty end
return p
end
return twocol |
local player = require("scripts.playerCreator")
local newScore = require("scripts.elements.scoreLog")
local json = require( "json" )
local scoresTable = {}
local filePath = system.pathForFile( "scores.json", system.DocumentsDirectory )
local scoreManager = {}
function scoreManager.add(finalScore)
local dateTime = os.date("%d") .. "/" .. os.date("%m") .. " - " .. os.date("%H") .. ":" .. os.date("%M") .. ":" .. os.date("%S")
local scoreLog = newScore.new(
dateTime,
finalScore
)
if scoresTable[1].score == 0 then
scoresTable[1] = nil
scoresTable[1] = scoreLog
else
scoreManager.compare(scoreLog)
end
end
function scoreManager.compare(scoreLog)
for i=1 , 5 do
if scoreLog.score > scoresTable[i].score then
local tmp = scoresTable[i]
scoresTable[i] = nil
scoresTable[i] = scoreLog
scoreManager.compare(tmp)
break
elseif scoreLog.score < scoresTable[i].score then
i = i + 1
else
scoresTable[i] = nil
scoresTable[i] = scoreLog
break
end
end
end
function scoreManager.loadScores()
local file = io.open( filePath, "r" )
if file then
local contents = file:read( "*a" )
io.close( file )
scoresTable = json.decode( contents )
end
if ( scoresTable == nil or #scoresTable == 0 ) then
local firstDateTime = "00/00 - 00:00:00"
local scoreInicial = 0
scoresTable = {
newScore.new(
firstDateTime,
scoreInicial
),
newScore.new(
firstDateTime,
scoreInicial
),
newScore.new(
firstDateTime,
scoreInicial
),
newScore.new(
firstDateTime,
scoreInicial
),
newScore.new(
firstDateTime,
scoreInicial
)
}
end
end
function scoreManager.saveScores()
for i = #scoresTable, 6, -1 do
table.remove( scoresTable, i )
end
local file = io.open( filePath, "w" )
if file then
file:write( json.encode( scoresTable ) )
io.close( file )
end
end
function scoreManager.print(scoreGroup)
local positionX = display.contentCenterX
local positionY
if scoresTable[1].score == 0 then
for i = 1, 5 do
positionY = 130 + ( i * 80 )
if ( scoresTable[i] ) then
local rankNum = display.newText(
scoreGroup,
i .. ") " .. scoresTable[i].dateTime .. " - ",
positionX,
positionY,
native.systemFont,
50
)
rankNum:setFillColor( 1 )
rankNum.anchorX = 1
local thisScore = display.newText(
scoreGroup,
scoresTable[i].score,
positionX,
positionY,
native.systemFont,
50
)
thisScore.anchorX = 0
thisScore:setFillColor( 1 )
i = i + 1
end
end
else
for i = 1, 5 do
positionY = 130 + ( i * 80 )
local rankNum = display.newText(
scoreGroup,
i.. ") ".. scoresTable[i].dateTime .. " - ",
positionX,
positionY,
native.systemFont,
50
)
rankNum:setFillColor( 1 )
rankNum.anchorX = 1
local thisScore = display.newText(
scoreGroup,
scoresTable[i].score,
positionX,
positionY,
native.systemFont,
50
)
thisScore.anchorX = 0
thisScore:setFillColor( 1 )
end
end
end
return scoreManager |
local Codegen = require("kotaro.parser.codegen")
local raw = {
{
_id = "equip_melee",
ordering = 10000,
},
{
_id = "equip_head",
ordering = 12000,
},
{
_id = "equip_shield",
ordering = 14000,
},
{
_id = "equip_body",
ordering = 16000,
},
{
_id = "equip_leg",
ordering = 18000,
},
{
_id = "equip_cloak",
ordering = 19000,
},
{
_id = "equip_back",
ordering = 20000,
},
{
_id = "equip_wrist",
ordering = 22000,
},
{
_id = "equip_ranged",
ordering = 24000,
},
{
_id = "equip_ammo",
ordering = 25000,
},
{
_id = "equip_ring",
ordering = 32000,
},
{
_id = "equip_neck",
ordering = 34000,
},
{
_id = "drink",
ordering = 52000,
},
{
_id = "scroll",
ordering = 53000,
},
{
_id = "spellbook",
ordering = 54000,
},
{
_id = "book",
ordering = 55000,
},
{
_id = "rod",
ordering = 56000,
},
{
_id = "food",
ordering = 57000,
},
{
_id = "misc_item",
ordering = 59000,
},
{
_id = "furniture",
ordering = 60000,
},
{
_id = "furniture_well",
ordering = 60001,
},
{
_id = "furniture_altar",
ordering = 60002,
},
{
_id = "remains",
ordering = 62000,
},
{
_id = "junk",
ordering = 64000,
},
{
_id = "gold",
ordering = 68000,
},
{
_id = "platinum",
ordering = 69000,
},
{
_id = "container",
ordering = 72000,
},
{
_id = "ore",
ordering = 77000,
},
{
_id = "tree",
ordering = 80000,
},
{
_id = "cargo_food",
ordering = 91000,
},
{
_id = "cargo",
ordering = 92000,
},
{
_id = "bug",
ordering = 99999999,
parents = {
"elona.bug"
}
},
}
local raw2 = {
{
_id = "equip_melee_broadsword",
ordering = 10001,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_long_sword",
ordering = 10002,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_short_sword",
ordering = 10003,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_club",
ordering = 10004,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_hammer",
ordering = 10005,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_staff",
ordering = 10006,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_lance",
ordering = 10007,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_halberd",
ordering = 10008,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_hand_axe",
ordering = 10009,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_axe",
ordering = 10010,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_melee_scythe",
ordering = 10011,
parents = {
"elona.equip_melee"
}
},
{
_id = "equip_head_helm",
ordering = 12001,
parents = {
"elona.equip_head"
}
},
{
_id = "equip_head_hat",
ordering = 12002,
parents = {
"elona.equip_head"
}
},
{
_id = "equip_shield_shield",
ordering = 14003,
parents = {
"elona.equip_shield"
}
},
{
_id = "equip_body_mail",
ordering = 16001,
parents = {
"elona.equip_body"
}
},
{
_id = "equip_body_robe",
ordering = 16003,
parents = {
"elona.equip_body"
}
},
{
_id = "equip_leg_heavy_boots",
ordering = 18001,
parents = {
"elona.equip_leg"
}
},
{
_id = "equip_leg_shoes",
ordering = 18002,
parents = {
"elona.equip_leg"
}
},
{
_id = "equip_back_girdle",
ordering = 19001,
parents = {
"elona.equip_cloak"
}
},
{
_id = "equip_back_cloak",
ordering = 20001,
parents = {
"elona.equip_back"
}
},
{
_id = "equip_wrist_gauntlet",
ordering = 22001,
parents = {
"elona.equip_wrist"
}
},
{
_id = "equip_wrist_glove",
ordering = 22003,
parents = {
"elona.equip_wrist"
}
},
{
_id = "equip_ranged_bow",
ordering = 24001,
parents = {
"elona.equip_ranged"
}
},
{
_id = "equip_ranged_crossbow",
ordering = 24003,
parents = {
"elona.equip_ranged"
}
},
{
_id = "equip_ranged_gun",
ordering = 24020,
parents = {
"elona.equip_ranged"
}
},
{
_id = "equip_ranged_laser_gun",
ordering = 24021,
parents = {
"elona.equip_ranged"
}
},
{
_id = "equip_ranged_thrown",
ordering = 24030,
parents = {
"elona.equip_ranged"
}
},
{
_id = "equip_ammo_arrow",
ordering = 25001,
parents = {
"elona.equip_ammo"
}
},
{
_id = "equip_ammo_bolt",
ordering = 25002,
parents = {
"elona.equip_ammo"
}
},
{
_id = "equip_ammo_bullet",
ordering = 25020,
parents = {
"elona.equip_ammo"
}
},
{
_id = "equip_ammo_energy_cell",
ordering = 25030,
parents = {
"elona.equip_ammo"
}
},
{
_id = "equip_ring_ring",
ordering = 32001,
parents = {
"elona.equip_ring"
}
},
{
_id = "equip_neck_armor",
ordering = 34001,
parents = {
"elona.equip_neck"
}
},
{
_id = "drink_potion",
ordering = 52001,
parents = {
"elona.drink"
}
},
{
_id = "drink_alcohol",
ordering = 52002,
parents = {
"elona.drink"
}
},
{
_id = "scroll_deed",
ordering = 53100,
parents = {
"elona.scroll"
}
},
{
_id = "food_flour",
ordering = 57001,
parents = {
"elona.food"
}
},
{
_id = "food_noodle",
ordering = 57002,
parents = {
"elona.food"
}
},
{
_id = "food_vegetable",
ordering = 57003,
parents = {
"elona.food"
}
},
{
_id = "food_fruit",
ordering = 57004,
parents = {
"elona.food"
}
},
{
_id = "crop_herb",
ordering = 58005,
parents = {
"elona.food"
}
},
{
_id = "crop_seed",
ordering = 58500,
parents = {
"elona.food"
}
},
{
_id = "misc_item_crafting",
ordering = 59500,
parents = {
"elona.misc_item"
}
},
{
_id = "furniture_well",
ordering = 60001,
},
{
_id = "furniture_altar",
ordering = 60002,
},
{
_id = "furniture_bed", -- sleeping bag/furniture
ordering = 60004, -- sleeping bag/furniture
},
{
_id = "furniture_instrument",
ordering = 60005,
parents = {
"elona.furniture"
}
},
{
-- This is only used to generate items that appear in random
-- overworld field maps.
_id = "junk_in_field", -- subcategory 64000
ordering = 64000, -- subcategory 64000
},
{
_id = "junk_town",
ordering = 64100,
parents = {
"elona.junk"
}
},
{
_id = "ore_valuable",
ordering = 77001,
parents = {
"elona.ore"
}
},
{
_id = "bug",
ordering = 99999999,
parents = {
"elona.bug"
}
},
}
local items = {}
for _, v in ipairs(raw) do
items[v.ordering] = "elona." .. v._id
end
local items2 = {}
for _, v in ipairs(raw2) do
items2[v.ordering] = "elona." .. v._id
end
local conv_item_category = {}
function conv_item_category:new()
return setmetatable({}, {__index = conv_item_category})
end
function conv_item_category:applies_to(node)
if node:type() ~= "constructor_expression" then
return false
end
local target = node:index("category")
local target2 = node:index("subcategory")
if (not target or target:type() ~= "expression") and (not target2 or target2:type() ~= "expression") then
return false
end
return true
end
function conv_item_category:execute(node)
local categories = node:index("categories")
local function do_insert(category, items)
local id = items[category]
assert(id, tostring(category))
local found = false
for _, c in ipairs(categories:primary_expression():children()) do
if c:type() == "expression" and c:evaluate() == id then
found = true
break
end
end
if not found then
categories:insert_node(Codegen.gen_expression("\"" .. id .. "\""))
end
end
if node:index("category") then
local category = node:index("category"):evaluate()
do_insert(category, items)
end
if node:index("subcategory") then
local subcategory = node:index("subcategory"):evaluate()
do_insert(subcategory, items2)
end
end
return {
execute = function(self, ast)
return ast:rewrite(conv_item_category:new())
end
}
|
object_mobile_nym_themepark_smuggler = object_mobile_shared_nym_themepark_smuggler:new {
}
ObjectTemplates:addTemplate(object_mobile_nym_themepark_smuggler, "object/mobile/nym_themepark_smuggler.iff")
|
IgnoredArea = mondelefant.new_class()
IgnoredArea.table = 'ignored_area'
IgnoredArea.primary_key = { "member_id", "area_id" }
function IgnoredArea:by_pk(member_id, area_id)
return self:new_selector()
:add_where{ "member_id = ?", member_id }
:add_where{ "area_id = ?", area_id }
:optional_object_mode()
:exec()
end
function IgnoredArea:destroy_by_member_id(member_id)
local ignored_areas = self:new_selector()
:add_where{ "member_id = ?", member_id }
:exec()
for i, ignored_area in ipairs(ignored_areas) do
ignored_area:destroy()
end
end |
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Igniter"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Igniter"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "A", "Length", "Extinguish" })
self.IgniteLength = 10
self:Setup(false, 2048)
end
function ENT:Setup(trgply,Range)
self.TargetPlayers = trgply
if Range then self:SetBeamLength(Range) end
end
function ENT:DoTrace()
local vStart = self:GetPos()
local vForward = self:GetUp()
local trace = {}
trace.start = vStart
trace.endpos = vStart + (vForward * self:GetBeamLength())
trace.filter = { self }
local trace = util.TraceLine( trace )
local cvarTargetPlayers = GetConVarNumber('sbox_wire_igniters_allowtrgply') > 0
if not IsValid(trace.Entity) then return false end
if not gamemode.Call("CanProperty", self:GetPlayer(), "ignite", trace.Entity) then return false end
if (trace.Entity:IsPlayer() and (not self.TargetPlayers or not cvarTargetPlayers)) then return false end
if (trace.Entity:IsWorld()) then return false end
return trace.Entity
end
function ENT:TriggerInput(iname, value)
if (iname == "A") then
if (value ~= 0) then
local target = self:DoTrace()
if target == false then return false end
target:Extinguish()
target:Ignite( self.IgniteLength, 0 )
end
elseif (iname == "Length") then
self.IgniteLength = math.min(value,GetConVarNumber("sbox_wire_igniters_maxlen"))
elseif (iname == "Extinguish") then
if value ~= 0 then
local target = self:DoTrace()
if target == false then return false end
target:Extinguish()
end
end
end
duplicator.RegisterEntityClass("gmod_wire_igniter", WireLib.MakeWireEnt, "Data", "TargetPlayers", "Range")
|
--[[
Title: Taurus main loop
Author(s): WangTian
Date: 2009/4/28
Desc: Entry point and game loop
commands line
| *name* | *desc* |
| worldpath | initial world path |
use the lib:
------------------------------------------------------------
NPL.activate("(gl)script/apps/Taurus/main_loop.lua");
set the bootstrapper to point to this file, see config/bootstrapper.xml
Or run application with command line: bootstrapper="script/apps/Taurus/bootstrapper.xml"
------------------------------------------------------------
]]
NPL.load("(gl)script/kids/ParaWorldCore.lua"); -- ParaWorld platform includes
-- if asset is not found locally, we will look in this place
-- TODO: read this from config file.
ParaAsset.SetAssetServerUrl("http://update.61.com/haqi/assetupdate/");
--ParaAsset.SetAssetServerUrl("http://192.168.0.228/assetdownload/update/");
ParaEngine.GetAttributeObject():GetChild("AssetManager"):SetField("UseLocalFileFirst", true);
-- uncomment this line to display our logo page.
-- main_state="logo";
System.options.isAB_SDK = true;
ParaEngine.GetAttributeObject():CallField("BringWindowToTop");
-- pause here to debug.
--NPL.load("(gl)script/ide/Debugger/IPCDebugger.lua");
--IPCDebugger.Start();
--IPCDebugger.WaitForBreak()
-- some init stuffs that are only called once at engine start up, but after System.init()
local bTaurus_Init;
local function Taurus_Init()
if(bTaurus_Init) then return end
bTaurus_Init = true;
System.SystemInfo.SetField("name", "Taurus")
System.options.isKid = true;
-- in case back buffer is not big enough, we will use UI scaling.
local att = ParaEngine.GetAttributeObject();
att:SetField("IgnoreWindowSizeChange",false);
ParaUI.SetMinimumScreenSize(960,560,true);
--att:SetField("ToggleSoundWhenNotFocused", false);
--att:SetField("AutoLowerFrameRateWhenNotFocused", false);
-- load default theme
NPL.load("(gl)script/apps/Taurus/DefaultTheme.lua");
Taurus_LoadDefaultTheme();
-- always use compression. The current compression method is super light-weighted and is mostly for data encrption purposes.
NPL.SetUseCompression(true, true);
-- set compression key and method.
-- NPL.SetCompressionKey({key = "this can be nil", size = 64, UsePlainTextEncoding = 1});
-- install the Taurus app, if it is not installed yet.
local app = System.App.AppManager.GetApp("Taurus_GUID")
if(not app) then
app = System.App.Registration.InstallApp({app_key="Taurus_GUID"}, "script/apps/Taurus/IP.xml", true);
end
-- change the login machanism to use our own login module
System.App.Commands.SetDefaultCommand("Login", "Profile.Taurus.Login");
-- change the load world command to use our own module
System.App.Commands.SetDefaultCommand("LoadWorld", "File.EnterTaurusWorld");
-- change the handler of system command line.
System.App.Commands.SetDefaultCommand("SysCommandLine", "Profile.Taurus.SysCommandLine");
-- change the handler of enter to chat.
System.App.Commands.SetDefaultCommand("EnterChat", "Profile.Taurus.EnterChat");
-- change the handler of drop files
System.App.Commands.SetDefaultCommand("SYS_WM_DROPFILES", "Profile.Taurus.SYS_WM_DROPFILES");
ParaIO.LoadReplaceFile("AssetsReplaceFile.txt", false);
-- load all worlds configuration file
NPL.load("(gl)script/apps/Aries/Scene/WorldManager.lua");
MyCompany.Aries.WorldManager:Init("script/apps/Aries/Scene/AriesGameWorlds.config.xml");
-- enable asset file watcher in Taurus by default.
NPL.load("(gl)script/ide/FileSystemWatcher.lua");
commonlib.FileSystemWatcher.EnableAssetFileWatcher()
-- register shared aries mcml control for testing.
NPL.load("(gl)script/apps/Aries/mcml/pe_locationtracker.lua");
local mcml_controls = commonlib.gettable("MyCompany.Aries.mcml_controls");
Map3DSystem.mcml_controls.RegisterUserControl("pe:locationtracker", mcml_controls.pe_locationtracker);
Map3DSystem.mcml_controls.RegisterUserControl("pe:arrowpointer", mcml_controls.pe_arrowpointer);
NPL.load("(gl)script/kids/3DMapSystemApp/DebugApp/app_main.lua");
Map3DSystem.App.Debug.DoLoadConfigFile();
end
-- this script is activated every 0.5 sec. it uses a finite state machine (main_state).
-- State nil is the inital game state. state 0 is idle.
local function activate()
if(main_state==0) then
-- this is the main game loop
elseif(main_state==nil) then
-- initialization
main_state = System.init();
if(main_state~=nil) then
Taurus_Init();
---- sample code to immediately load the world if app platform is not used.
--local res = System.LoadWorld({
--worldpath="worlds/MyWorlds/1111111111111",
---- use exclusive desktop mode
--bExclusiveMode = true,
--})
--
---- show login window
--NPL.load("(gl)script/apps/Taurus/Login/MainLogin.lua");
--MyCompany.Taurus.MainLogin.Show();
--local params = {worldpath = "worlds/MyWorlds/1111111111111"}
--System.App.Commands.Call(System.App.Commands.GetLoadWorldCommand(), params);
--if(params.res) then
---- succeed loading
--end
local params = {
worldpath = ParaEngine.GetAppCommandLineByParam("worldpath", "worlds/MyWorlds/flatgrassland"),
-- only give the guest right, to prevent switching character and editing.
role = "administrator",
}
if(ParaWorld.GetWorldDirectory() ~= params.worldpath) then
System.App.Commands.Call(System.App.Commands.GetLoadWorldCommand(), params);
else
log("world is already loaded.\n")
end
end
elseif(main_state == "logo") then
if(not IsServerMode) then
NPL.load("(gl)script/kids/3DMapSystemUI/Desktop/LogoPage.lua");
System.UI.Desktop.LogoPage.Show(79, {
{name = "LogoPage_PE_bg", bg="Texture/whitedot.png", alignment = "_fi", left=0, top=0, width=0, height=0, color="255 255 255 255", anim="script/kids/3DMapSystemUI/Desktop/Motion/Bg_motion.xml"},
{name = "LogoPage_PE_logoTxt", bg="Texture/3DMapSystem/brand/ParaEngineLogoText.png", alignment = "_rb", left=-320-20, top=-20-5, width=320, height=20, color="255 255 255 255", anim="script/kids/3DMapSystemUI/Desktop/Motion/Bg_motion.xml"},
{name = "LogoPage_PE_logo", bg="Texture/Taurus/FrontPage_32bits.png;0 111 512 290", alignment = "_ct", left=-512/2, top=-290/2, width=512, height=290, color="255 255 255 0", anim="script/apps/Taurus/Desktop/Motion/Logo_motion.xml"},
})
else
main_state = nil;
end
end
end
NPL.this(activate); |
-- @file enums.lua
-- Header definitions for Hiredis - exposes enums to Lua FFI.
local enums_string = [[
typedef enum {
REDIS_SSL_CTX_NONE = 0,
REDIS_SSL_CTX_CREATE_FAILED,
REDIS_SSL_CTX_CERT_KEY_REQUIRED,
REDIS_SSL_CTX_CA_CERT_LOAD_FAILED,
REDIS_SSL_CTX_CLIENT_CERT_LOAD_FAILED,
REDIS_SSL_CTX_PRIVATE_KEY_LOAD_FAILED
} redisSSLContextError;
enum redisConnectionType {
REDIS_CONN_TCP,
REDIS_CONN_UNIX,
REDIS_CONN_USERFD
};
]]
return enums_string
|
--[[WTF=GAMESTATE:GetCurrentSong():GetLastSecond()-GAMESTATE:GetCurMusicSeconds()
Hi=SecondsToMSSMsMs(GAMESTATE:GetCurrentSong():GetLastSecond()-GAMESTATE:GetCurMusicSeconds())
kuy=SecondsToMSSMsMs(GAMESTATE:GetCurrentSong():GetLastSecond())
Clockmin = math.floor((GAMESTATE:GetCurrentSong():GetLastSecond()-GAMESTATE:GetCurMusicSeconds())/60)
Clocksec = math.floor((GAMESTATE:GetCurrentSong():GetLastSecond()-GAMESTATE:GetCurMusicSeconds())-Clockmin*60)
ClockWTF = (string.format('%.2f',((GAMESTATE:GetCurrentSong():GetLastSecond()-GAMESTATE:GetCurMusicSeconds())-Clockmin*60) - Clocksec))*100
COLON = ""
if MonthOfYear() == 4-1 and DayOfMonth() == 1 then
COLON = ":"
if ClockWTF < 10 then
RClockWTF = '0'..ClockWTF
else
RClockWTF = ClockWTF
end
if ClockWTF >= 50 then
clocknow = " : : "
else
if Clocksec < 10 then
clocknow = Clockmin..COLON.."0"..Clocksec..COLON..RClockWTF
else
clocknow = Clockmin..COLON..Clocksec..COLON..RClockWTF
end
end
else
if ClockWTF >= 50 then
COLON = ":"
else
COLON = " "
end
if ClockWTF < 10 then
RClockWTF = '0'..ClockWTF
else
RClockWTF = ClockWTF
end
if Clocksec < 10 then
clocknow = Clockmin..COLON.."0"..Clocksec..COLON..RClockWTF
else
clocknow = Clockmin..COLON..Clocksec..COLON..RClockWTF
end
end
if WTF <= 0 then
self:settext("0"..COLON.."00"..COLON.."00")
elseif P >= 50 and P <= 55 then
self:diffusealpha(0)
elseif P >= 55 and P <= 100 then
self:diffusealpha(1)
self:settext(clocknow)
elseif P >= 100 then
self:settext("0"..COLON.."00"..COLON.."00")
else
self:settext(clocknow)
end]]
local plused = false;
local dat = 0;
local Change = math.random(10,25)
local hang = 12;
local NumF = TFO(todayis(31,10),"_terror pro 20px","_determination mono 24px");--NumF;
LoadActor("../../_save/SampleText.lua")
local Os = 0;
if DayOfMonth() ~= day or MonthOfYear()-1 ~= mon or Year() ~= year then
Os = 0
Od = DayOfMonth()
Om = MonthOfYear()-1
Oy = Year()
else
Os = sec
Od = day
Om = mon
Oy = year
end
local t = Def.ActorFrame{};
t[#t+1] = Def.ActorFrame{
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X-hang*3.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*0;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*0;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
STD = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
STT = self
end;
};
};
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X-hang*2.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*1;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*1;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
NDD = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
NDT = self
end;
};
};
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X-hang*1.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*2;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*2;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
RDD = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
RDT = self
end;
};
};
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X-hang*0.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*3;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*3;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
THD = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
THT = self
end;
};
};
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X+hang*0.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*4;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*4;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
FID = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
FIT = self
end;
};
};
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X+hang*1.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*5;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*5;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
SID = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
SIT = self
end;
};
};
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X+hang*2.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*6;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*6;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
SED = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
SET = self
end;
};
};
Def.ActorFrame{
OnCommand=cmd(y,60;x,SCREEN_CENTER_X+hang*3.5;zoom,0.8);
DMessageCommand=cmd(sleep,0.1*7;decelerate,0.5;rotationx,180);
TMessageCommand=cmd(sleep,0.1*7;decelerate,0.5;rotationx,360;sleep,0.00001;rotationx,0);
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back');
OnCommand=function(self)
EAD = self
end;
};
LoadFont(NumF) .. {
InitCommand=cmd(diffuse,color("#0011FF");cullmode,'back';rotationx,180);
OnCommand=function(self)
EAT = self
end;
};
};
};
t[#t+1] = LoadFont(NumF) .. {
InitCommand=cmd(Center);
OnCommand=cmd(playcommand,"Neptune");
NeptuneCommand=function(self)
Remind = math.max(GAMESTATE:GetCurrentSong():GetLastSecond() - GAMESTATE:GetCurMusicSeconds(),0)
Clockmin = math.floor((Remind)/60)
Clocksec = math.floor((Remind)-Clockmin*60)
ClockWTF = (string.format('%.2f',((Remind)-Clockmin*60) - Clocksec))*100
if ClockWTF >= 50 then
COLON = ":"
else
COLON = ""
end
if ClockWTF == 100 then
OutCW = 99
elseif ClockWTF < 100 then
OutCW = ClockWTF
end
STD:settext(math.floor(Clockmin/10))
NDD:settext(Clockmin-(math.floor(Clockmin/10))*10)
RDD:settext(COLON)
THD:settext(math.floor(Clocksec/10))
FID:settext(Clocksec-(math.floor(Clocksec/10))*10)
SID:settext(COLON)
SED:settext(math.floor(OutCW/10))
EAD:settext(OutCW-(math.floor(OutCW/10))*10)
if GAMESTATE:GetCurMusicSeconds() >= GAMESTATE:GetCurrentSong():GetLastSecond() and not plused then
plused = true
Os = Os + GAMESTATE:GetCurrentSong():GetLastSecond()
local file = RageFileUtil.CreateRageFile()
file:Open("/Themes/News/BGAnimations/_save/SampleText.lua", 2 ) --2 = write
file:PutLine("--Time all SET")
file:PutLine("sec = "..Os)
file:PutLine("day = "..Od)
file:PutLine("mon = "..Om)
file:PutLine("year = "..Oy)
file:PutLine("--End of SampleText")
file:Close();
elseif GAMESTATE:GetCurMusicSeconds() < GAMESTATE:GetCurrentSong():GetLastSecond() and plused then
plused = false
end
outsec = Os + math.min(math.max(GAMESTATE:GetCurMusicSeconds(),0),GAMESTATE:GetCurrentSong():GetLastSecond()) - TFO( GAMESTATE:GetCurMusicSeconds() > GAMESTATE:GetCurrentSong():GetLastSecond(), GAMESTATE:GetCurrentSong():GetLastSecond(),0)
outsech = math.floor(outsec/3600)
outsecm = (math.floor(outsec/60))-outsech*60
outsecs = math.floor(outsec)-(outsech*60*60+outsecm*60)
outsecw = (outsec - math.floor(outsec))*100
if outsecw == 100 then
RW = 99
elseif outsecw < 100 then
RW = outsecw
end
if outsecw > 50 then
RC = ""
else
RC = ":"
end
STT:settext(math.floor(outsech/10))
NDT:settext(outsech-(math.floor(outsech/10))*10)
RDT:settext(RC)
THT:settext(math.floor(outsecm/10))
FIT:settext(outsecm-(math.floor(outsecm/10))*10)
SIT:settext(RC)
SET:settext(math.floor(outsecs/10))
EAT:settext(outsecs-(math.floor(outsecs/10))*10)
if GAMESTATE:GetCurMusicSeconds() >= Change then
Change = Change + math.random(8,20)
if dat == 0 then
MESSAGEMAN:Broadcast("D")
dat = 1
elseif dat == 1 then
MESSAGEMAN:Broadcast("T")
dat = 0
end
elseif GAMESTATE:GetCurMusicSeconds() < 10 and Change > 25 then
Change = 0
end
--self:settext(outsec)
self:sleep(0.02)
self:queuecommand("Neptune")
end;
};
return t; |
local username = ""
local passsword = ""
local server = require "resty.websocket.server"
local wsocket, err = server:new{
timeout = 5000, --TODO:配置超时时间
max_playload_len = 65535
}
if not wsocket then
ngx.log(ngx.ERR, "failed to new websocket: ", err)
return ngx.exit(444)
end
wsocket:send_text("connecting to the port 23 ... \n")
local webtelnet = dofile ("webtelnet.lua")
--NOTE: 不会根据package.path进行搜索,而是根据相对路径搜索,而此处的应该是相对此nginx进程的相对路径(openresty根目录)
if not webtelnet.connect() then
ngx.log(ngx.ERR, "failed to connect port 23")
wsocket:send_text("failed to connect telnet!\n")
wsocket:send_close()
return ngx.exit(444)
end
wsocket:send_text("connect success.\n")
-- local welcome
-- while true do
local auto_out = webtelnet.input() --NOTE: 这一段是自动登录,就算不需要,也不能注释这一行
-- if auto_out ~= "" then
-- if string.find(auto_out, "ogin:") then
-- auto_out = webtelnet.input(username .. "\r\n")
-- end
-- if string.find(auto_out, "assword:") then
-- welcome = webtelnet.input(passsword .. "\r\n")
-- break
-- end
-- end
-- end
-- wsocket:send_text(welcome)
-- local tellog = require "tellog"
local skip = true
while true do
local data, typ, err = wsocket:recv_frame()
if wsocket.fatal then
ngx.log(ngx.ERR, "failed to receive frame: ", err)
return ngx.exit(444)
end
local bytes, err, etype = true
if not data then
etype, bytes, err = "ping", wsocket:send_ping()
elseif typ == "close" then
webtelnet.close()
break
elseif typ == "ping" then
etype, bytes, err = "pong" wsocket:send_pong()
elseif typ == "pong" then
ngx.log(ngx.INFO, "client ponged")
elseif typ == "text" then
local res, restart = webtelnet.input(data)
if restart then
break
end
-- if skip then
-- res = res .. tellog.getAll()
-- skip = nil
-- else
-- tellog.addLog(res)
-- end
--NOTE: 如果websocket是纯转发,那么这里就需要注释掉,如果是堆积发送,那么不需要注释
-- res = string.gsub(res, data, "", 1)
etype, bytes, err = "text", wsocket:send_text(res)
end
if not bytes then
ngx.log(ngx.ERR, "failed to send " .. etype, err)
return ngx.exit(444)
end
end
wsocket:send_close()
|
include("LensSupport")
local LENS_NAME = "ML_BUILDER"
local ML_LENS_LAYER = LensLayers.HEX_COLORING_APPEAL_LEVEL
-- Should the builder lens auto apply, when a builder is selected.
local AUTO_APPLY_BUILDER_LENS:boolean = true
-- CQUI
local function CQUI_OnSettingsUpdate()
AUTO_APPLY_BUILDER_LENS = GameConfiguration.GetValue("CQUI_AutoapplyBuilderLens");
end
-- ===========================================================================
-- Builder Lens Support
-- ===========================================================================
local function isAncientClassicalWonder(wonderTypeID)
-- print("Checking wonder " .. wonderTypeID .. " if ancient or classical")
for row in GameInfo.Buildings() do
if row.Index == wonderTypeID then
-- Make hash, and get era
if row.PrereqTech ~= nil then
prereqTechHash = DB.MakeHash(row.PrereqTech);
eraType = GameInfo.Technologies[prereqTechHash].EraType;
elseif row.PrereqCivic ~= nil then
prereqCivicHash = DB.MakeHash(row.PrereqCivic);
eraType = GameInfo.Civics[prereqCivicHash].EraType;
else
-- Wonder has no prereq
return true;
end
-- print("Era = " .. eraType);
if eraType == nil then
-- print("Could not find era for wonder " .. wonderTypeID)
return true
elseif eraType == "ERA_ANCIENT" or eraType == "ERA_CLASSICAL" then
return true;
end
end
end
return false;
end
local function playerCanRemoveFeature(playerID, plotIndex)
local pPlot = Map.GetPlotByIndex(plotIndex)
local pPlayer = Players[playerID];
local featureInfo = GameInfo.Features[pPlot:GetFeatureType()]
if featureInfo ~= nil then
if not featureInfo.Removable then return false; end
-- Check for remove tech
if featureInfo.RemoveTech ~= nil then
local tech = GameInfo.Technologies[featureInfo.RemoveTech]
local playerTech:table = pPlayer:GetTechs();
if tech ~= nil then
return playerTech:HasTech(tech.Index);
else
return false;
end
else
return true;
end
end
return false;
end
local function BuilderCanConstruct(improvementInfo)
for improvementBuildUnits in GameInfo.Improvement_ValidBuildUnits() do
if improvementBuildUnits ~= nil and improvementBuildUnits.ImprovementType == improvementInfo.ImprovementType and
improvementBuildUnits.UnitType == "UNIT_BUILDER" then
return true
end
end
return false
end
local function plotCanHaveImprovement(playerID, plotIndex)
local pPlot = Map.GetPlotByIndex(plotIndex)
local pPlayer = Players[playerID]
-- Handler for a generic tile
for improvementInfo in GameInfo.Improvements() do
if improvementInfo ~= nil and improvementInfo.Buildable then
-- Does the player the prereq techs and civis
if BuilderCanConstruct(improvementInfo) and playerCanHave(playerID, improvementInfo) then
local improvementValid:boolean = false;
-- Check for valid feature
for validFeatureInfo in GameInfo.Improvement_ValidFeatures() do
if validFeatureInfo ~= nil and validFeatureInfo.ImprovementType == improvementInfo.ImprovementType then
-- Does this plot have this feature?
local featureInfo = GameInfo.Features[validFeatureInfo.FeatureType]
if featureInfo ~= nil and pPlot:GetFeatureType() == featureInfo.Index then
if playerCanHave(playerID, featureInfo) and playerCanHave(playerID, validFeatureInfo) then
print("(feature) Plot " .. pPlot:GetIndex() .. " can have " .. improvementInfo.ImprovementType)
improvementValid = true;
break;
end
end
end
end
-- Check for valid terrain
if not improvementValid then
for validTerrainInfo in GameInfo.Improvement_ValidTerrains() do
if validTerrainInfo ~= nil and validTerrainInfo.ImprovementType == improvementInfo.ImprovementType then
-- Does this plot have this terrain?
local terrainInfo = GameInfo.Terrains[validTerrainInfo.TerrainType]
if terrainInfo ~= nil and pPlot:GetTerrainType() == terrainInfo.Index then
if playerCanHave(playerID, terrainInfo) and playerCanHave(playerID, validTerrainInfo) then
print("(terrain) Plot " .. pPlot:GetIndex() .. " can have " .. improvementInfo.ImprovementType)
improvementValid = true;
break;
end
end
end
end
end
-- Check for valid resource
if not improvementValid then
for validResourceInfo in GameInfo.Improvement_ValidResources() do
if validResourceInfo ~= nil and validResourceInfo.ImprovementType == improvementInfo.ImprovementType then
-- Does this plot have this terrain?
local resourceInfo = GameInfo.Resources[validResourceInfo.ResourceType]
if resourceInfo ~= nil and pPlot:GetResourceType() == resourceInfo.Index then
if playerCanHave(playerID, resourceInfo) and playerCanHave(playerID, validResourceInfo) then
print("(resource) Plot " .. pPlot:GetIndex() .. " can have " .. improvementInfo.ImprovementType)
improvementValid = true;
break;
end
end
end
end
end
-- Special check for coastal requirement
if improvementInfo.Coast and (not pPlot:IsCoastalLand()) then
print(plotIndex .. " plot is not coastal")
improvementValid = false;
end
if improvementValid then
return true
end
end
end
end
return false;
end
local function plotHasCorrectImprovement(plot)
local plotIndex = plot:GetIndex()
local playerID = Game.GetLocalPlayer()
-- If the plot has a resource, and the player has discovered it, get the improvement specific to that
if playerHasDiscoveredResource(playerID, plotIndex) then
local resourceInfo = GameInfo.Resources[plot:GetResourceType()]
if resourceInfo ~= nil then
local improvementType;
for validResourceInfo in GameInfo.Improvement_ValidResources() do
if validResourceInfo ~= nil and validResourceInfo.ResourceType == resourceInfo.ResourceType then
improvementType = validResourceInfo.ImprovementType;
if improvementType ~= nil and GameInfo.Improvements[improvementType] ~= nil then
local improvementID = GameInfo.Improvements[improvementType].RowId - 1;
if plot:GetImprovementType() == improvementID then
return true
end
end
end
end
end
else
-- This plot has either no resource or a undiscovered resource
-- hence assuming correct resource type
return true
end
return false
end
local function plotHasRemovableFeature(plot)
local featureInfo = GameInfo.Features[plot:GetFeatureType()];
if featureInfo ~= nil and featureInfo.Removable then
return true;
end
return false;
end
local function plotHasImprovableHill(plot)
local terrainInfo = GameInfo.Terrains[plot:GetTerrainType()];
local improvInfo = GameInfo.Improvements["IMPROVEMENT_MINE"];
local playerID = Game.GetLocalPlayer()
if (terrainInfo ~= nil and terrainInfo.Hills
and playerCanHave(playerID, improvInfo)) then
return true
end
return false;
end
local function plotHasImprovableWonder(plot)
-- List of wonders that can have an improvement on them.
local permitWonderList = {
"FEATURE_CLIFFS_DOVER"
}
local featureInfo = GameInfo.Features[plot:GetFeatureType()];
if featureInfo ~= nil then
for i, wonderType in ipairs(permitWonderList) do
if featureInfo.FeatureType == wonderType then
return true
end
end
end
return false
end
local function IsAdjYieldWonder(featureInfo)
-- List any wonders here that provide yield bonuses, but not mentioned in Features.xml
local specialWonderList = {
"FEATURE_TORRES_DEL_PAINE"
}
if featureInfo ~= nil and featureInfo.NaturalWonder then
for adjYieldInfo in GameInfo.Feature_AdjacentYields() do
if adjYieldInfo ~= nil and adjYieldInfo.FeatureType == featureInfo.FeatureType then
return true
end
end
for i, featureType in ipairs(specialWonderList) do
if featureType == featureInfo.FeatureType then
return true
end
end
end
return false
end
local function plotNextToBuffingWonder(plot)
for pPlot in PlotRingIterator(plot, 1, SECTOR_NONE, DIRECTION_CLOCKWISE) do
local featureInfo = GameInfo.Features[pPlot:GetFeatureType()]
if IsAdjYieldWonder(featureInfo) then
return true
end
end
return false
end
local function plotHasRecomFeature(plot)
local playerID = Game.GetLocalPlayer()
local featureInfo = GameInfo.Features[plot:GetFeatureType()]
local farmImprovInfo = GameInfo.Improvements["IMPROVEMENT_FARM"]
local lumberImprovInfo = GameInfo.Improvements["IMPROVEMENT_LUMBER_MILL"]
if featureInfo ~= nil then
-- 1. Is it a floodplain?
if featureInfo.FeatureType == "FEATURE_FLOODPLAINS" and
playerCanHave(playerID, farmImprovInfo) then
return true
end
-- 2. Is it a forest next to a river?
if featureInfo.FeatureType == "FEATURE_FOREST" and plot:IsRiver() and
playerCanHave(playerID, lumberImprovInfo) then
return true
end
-- 3. Is it a tile next to buffing wonder?
if plotNextToBuffingWonder(plot) then
return true
end
-- 4. Is it wonder, that can have an improvement?
if plotHasImprovableWonder(plot) then
if featureInfo.FeatureType == "FEATURE_FOREST" and
playerCanHave(playerID, lumberImprovInfo) then
return true
end
if plotCanHaveFarm(plot) then
return true
end
end
end
return false
end
local function playerHasBuilderWonderModifier(playerID)
return playerHasModifier(playerID, "MODIFIER_PLAYER_ADJUST_UNIT_WONDER_PERCENT");
end
local function playerHasBuilderDistrictModifier(playerID)
return playerHasModifier(playerID, "MODIFIER_PLAYER_ADJUST_UNIT_DISTRICT_PERCENT");
end
-- ===========================================================================
-- Exported functions
-- ===========================================================================
local function OnGetColorPlotTable()
-- print("Highlight Builder Lens Hexes")
local mapWidth, mapHeight = Map.GetGridSize()
local ResourceColor:number = UI.GetColorValue("COLOR_RESOURCE_BUILDER_LENS")
local HillColor:number = UI.GetColorValue("COLOR_HILL_BUILDER_LENS")
local RecomFeatureColor:number = UI.GetColorValue("COLOR_RECOMFEATURE_BUILDER_LENS")
local FeatureColor:number = UI.GetColorValue("COLOR_FEATURE_BUILDER_LENS")
local GenericColor:number = UI.GetColorValue("COLOR_GENERIC_BUILDER_LENS")
local NothingColor:number = UI.GetColorValue("COLOR_NOTHING_BUILDER_LENS")
local localPlayer:number = Game.GetLocalPlayer()
-- Make sure each color has its associated table
local colorPlot = {};
colorPlot[ResourceColor] = {}
colorPlot[HillColor] = {}
colorPlot[RecomFeatureColor] = {}
colorPlot[FeatureColor] = {}
colorPlot[GenericColor] = {}
colorPlot[NothingColor] = {}
for i = 0, (mapWidth * mapHeight) - 1, 1 do
local pPlot:table = Map.GetPlotByIndex(i)
if pPlot:GetOwner() == Game.GetLocalPlayer() then
-- IMPASSABLE
--------------------------------------
if pPlot:IsImpassable() then
table.insert(colorPlot[NothingColor], i)
-- NATIONAL PARK
--------------------------------------
elseif pPlot:IsNationalPark() then
table.insert(colorPlot[NothingColor], i)
-- IMPROVEMENTS
--------------------------------------
elseif plotHasImprovement(pPlot) then
if pPlot:IsImprovementPillaged() then
table.insert(colorPlot[HillColor], i)
elseif not plotHasCorrectImprovement(pPlot) then
table.insert(colorPlot[ResourceColor], i)
-- else
-- table.insert(colorPlot[NothingColor], i)
end
-- NATURAL WONDER
--------------------------------------
elseif plotHasNaturalWonder(pPlot) then
if plotHasImprovableWonder(pPlot) then
table.insert(colorPlot[RecomFeatureColor], i)
else
table.insert(colorPlot[NothingColor], i)
end
-- PLAYER WONDER - CHINESE UA
--------------------------------------
elseif plotHasWonder(pPlot) then
-- Check for a UA similiar to china's
if playerHasBuilderWonderModifier(localPlayer) and (not pPlot:IsWonderComplete())
and isAncientClassicalWonder(pPlot:GetWonderType()) then
table.insert(colorPlot[ResourceColor], i)
-- else
-- table.insert(colorPlot[NothingColor], i)
end
-- DISTRICT - AZTEC UA
--------------------------------------
elseif plotHasDistrict(pPlot) then
-- Check for a UA similiar to Aztec's
if (not pPlot:IsCity()) and (not districtComplete(localPlayer, i)) and
playerHasBuilderDistrictModifier(localPlayer) then
table.insert(colorPlot[ResourceColor], i)
-- else
-- table.insert(colorPlot[NothingColor], i)
end
-- VISIBLE RESOURCE
--------------------------------------
elseif plotHasResource(pPlot) and playerHasDiscoveredResource(localPlayer, i) then
-- Is the resource improvable?
if plotResourceImprovable(pPlot) then
table.insert(colorPlot[ResourceColor], i)
else
table.insert(colorPlot[NothingColor], i)
end
-- FEATURE - Note: This includes natural wonders, since wonder is also a "feature". Check Features.xml
--------------------------------------
elseif plotHasFeature(pPlot) then
-- Recommended Feature
if plotHasRecomFeature(pPlot) then
table.insert(colorPlot[RecomFeatureColor], i)
-- Harvestable feature
elseif playerCanRemoveFeature(localPlayer, i) then
table.insert(colorPlot[FeatureColor], i)
else
table.insert(colorPlot[NothingColor], i)
end
-- Below this we assume comman tiles that are
-- only useful if within working range of city
--------------------------------------
elseif plotWithinWorkingRange(localPlayer, i) then
-- HILL - MINE
--------------------------------------
if plotHasImprovableHill(pPlot) then
if plotNextToBuffingWonder(pPlot) then
table.insert(colorPlot[RecomFeatureColor], i)
else
table.insert(colorPlot[HillColor], i)
end
-- GENERIC TILE
--------------------------------------
elseif plotCanHaveImprovement(localPlayer, i) then
if plotNextToBuffingWonder(pPlot) then
table.insert(colorPlot[RecomFeatureColor], i)
--elseif plotCanHaveFarm(plot) then
else
table.insert(colorPlot[GenericColor], i)
end
-- NOTHING TO DO
--------------------------------------
else
table.insert(colorPlot[NothingColor], i)
end
end
end
end
return colorPlot
end
-- Called when a builder is selected
local function ShowBuilderLens()
LuaEvents.MinimapPanel_SetActiveModLens(LENS_NAME)
UILens.ToggleLayerOn(ML_LENS_LAYER)
end
local function ClearBuilderLens()
-- print("Clearing builder lens")
if UILens.IsLayerOn(ML_LENS_LAYER) then
UILens.ToggleLayerOff(ML_LENS_LAYER);
end
LuaEvents.MinimapPanel_SetActiveModLens("NONE");
end
local function OnUnitSelectionChanged( playerID:number, unitID:number, hexI:number, hexJ:number, hexK:number, bSelected:boolean, bEditable:boolean )
if playerID == Game.GetLocalPlayer() then
local unitType = GetUnitType(playerID, unitID);
if unitType then
if bSelected then
if unitType == "UNIT_BUILDER" and AUTO_APPLY_BUILDER_LENS then
ShowBuilderLens();
end
-- Deselection
else
if unitType == "UNIT_BUILDER" and AUTO_APPLY_BUILDER_LENS then
ClearBuilderLens();
end
end
end
end
end
local function OnUnitChargesChanged( playerID: number, unitID : number, newCharges : number, oldCharges : number )
local localPlayer = Game.GetLocalPlayer()
if playerID == localPlayer then
local unitType = GetUnitType(playerID, unitID)
if unitType and unitType == "UNIT_BUILDER" and AUTO_APPLY_BUILDER_LENS then
if newCharges == 0 then
ClearBuilderLens();
end
end
end
end
-- Multiplayer support for simultaneous turn captured builder
local function OnUnitCaptured( currentUnitOwner, unit, owningPlayer, capturingPlayer )
local localPlayer = Game.GetLocalPlayer()
if owningPlayer == localPlayer then
local unitType = GetUnitType(owningPlayer, unitID)
if unitType and unitType == "UNIT_BUILDER" and AUTO_APPLY_BUILDER_LENS then
ClearBuilderLens();
end
end
end
local function OnUnitRemovedFromMap( playerID: number, unitID : number )
local localPlayer = Game.GetLocalPlayer()
local lens = {}
LuaEvents.MinimapPanel_GetActiveModLens(lens)
if playerID == localPlayer then
if lens[1] == LENS_NAME and AUTO_APPLY_BUILDER_LENS then
ClearBuilderLens();
end
end
end
local function OnInitialize()
Events.UnitSelectionChanged.Add( OnUnitSelectionChanged );
Events.UnitCaptured.Add( OnUnitCaptured );
Events.UnitChargesChanged.Add( OnUnitChargesChanged );
Events.UnitRemovedFromMap.Add( OnUnitRemovedFromMap );
-- CQUI Handlers
LuaEvents.CQUI_SettingsUpdate.Add( CQUI_OnSettingsUpdate );
Events.LoadScreenClose.Add( CQUI_OnSettingsUpdate ); -- Astog: Update settings when load screen close
end
local BuilderLensEntry = {
LensButtonText = "LOC_HUD_BUILDER_LENS",
LensButtonTooltip = "LOC_HUD_BUILDER_LENS_TOOLTIP",
Initialize = OnInitialize,
GetColorPlotTable = OnGetColorPlotTable
}
-- minimappanel.lua
if g_ModLenses ~= nil then
g_ModLenses[LENS_NAME] = BuilderLensEntry
end
-- modallenspanel.lua
if g_ModLensModalPanel ~= nil then
g_ModLensModalPanel[LENS_NAME] = {}
g_ModLensModalPanel[LENS_NAME].LensTextKey = "LOC_HUD_BUILDER_LENS"
g_ModLensModalPanel[LENS_NAME].Legend = {
{"LOC_TOOLTIP_BUILDER_LENS_IMP", UI.GetColorValue("COLOR_RESOURCE_BUILDER_LENS")},
{"LOC_TOOLTIP_RECOMFEATURE_LENS_HILL", UI.GetColorValue("COLOR_RECOMFEATURE_BUILDER_LENS")},
{"LOC_TOOLTIP_BUILDER_LENS_HILL", UI.GetColorValue("COLOR_HILL_BUILDER_LENS")},
{"LOC_TOOLTIP_BUILDER_LENS_FEATURE", UI.GetColorValue("COLOR_FEATURE_BUILDER_LENS")},
{"LOC_TOOLTIP_BUILDER_LENS_GENERIC", UI.GetColorValue("COLOR_GENERIC_BUILDER_LENS")},
{"LOC_TOOLTIP_BUILDER_LENS_NOTHING", UI.GetColorValue("COLOR_NOTHING_BUILDER_LENS")}
}
end
|
--- This is the networked variant of LocalDetectorEvent. It simply runs
-- detection.determine_and_network_search
-- @classmod DetectorEvent
-- 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')
-- endregion
local DetectorEvent = {}
simple_serializer.inject(DetectorEvent)
function DetectorEvent:init()
if type(self.detector_advn_nm) ~= 'string' then
error(string.format('expected detector_advn_nm is string but got %s (type=%s)',
tostring(self.detector_advn_nm), type(self.detector_advn_nm)), 3)
end
if type(self.tags) ~= 'table' then
error(string.format('expected tags is table but got %s (type=%s)',
tostring(self.tags), type(self.tags)), 3)
end
for k,v in pairs(self.tags) do
if type(k) ~= 'string' then
error(string.format('expected tags keys are strings but tags[%s] = %s (type of key is %s)',
tostring(k), tostring(v), type(k)), 3)
end
if v ~= true then
error(string.format('expected tags values are true but tags[\'%s\'] = %s (type of value is %s)',
k, tostring(v), type(v)), 3)
end
end
end
function DetectorEvent:process(game_ctx, local_ctx, networking)
if local_ctx.id ~= 0 then return end
detection.determine_and_network_search(game_ctx, local_ctx, networking,
self.detector_advn_nm, self.tags)
end
prototype.support(DetectorEvent, 'event')
prototype.support(DetectorEvent, 'serializable')
return class.create('DetectorEvent', DetectorEvent)
|
--[[
Стейт персонажа. Код (функция) будет вызываться каждый тик персонажа, если данный стейт установлен ему как активный.
Разовую активность стейтов можно установить в data.states, а пассивную в data.constates.
В DS синтаксисе это делается с помощью тегов <state> и <constate>, размещенных в шапке персонажа, либо во фрейме.
<constate> state_name </constate> -- вариант без передаваемых значений
<state> state_name
var: true var2: 42 var3: "string"
</state> -- вариант с передачей переменных стейту
В коде это делается таблицами
data.constates = { { state_name } } -- без переменных
data.states = {
{ state_name }, -- без переменных
{ state_name, var = true, var2 = 42, var3 = "string" } -- с переменными
}
state_name - название стейта. канонически является числом, однако, может быть и строкой.
Функция, при вызове, принимает 2 переменных:
- дата сегмент персонажа (в текущем примере именован как data)
- переменные, переданные через тело стейта (в примере vars)
]]
return function (obj, data, params) -- обязательная конструкция, означающая начало стейта
if data.y > 50 then -- если персонаж на высоте больше 50
data.normalWeight = data.normalWeight or data.weight -- сохраняем текущий вес персонажа
data.weight = 0.5 -- в 2 раза уменьшаем вес персонажа (будто он в невесомости)
else -- иначе (или когда спустился)
data.weight = data.normalWeight -- нормализуем вес
data.normalWeight = nil -- обнуляем переменную, в которую сохраняли вес
end
end
-- Данный стейт заставит персонажа испытывать чувство невесомости при отдалении от земли
|
local SpaceShip = class("SpaceShip", Entity)
SpaceShip:include( Rotatable )
function SpaceShip:initialize()
Entity.initialize( self )
Rotatable.initialize( self )
local imgpath = FOLDER.ASSETS.."spaceship.png"
-- resource batch loading test
local b = resource.beginBatch()
resource.addImageToBatch(b, imgpath)
resource.loadBatch(b, function()
self._img = Sprite({
image = resource.getImage(imgpath),
origin_relative = Vector(0.5, 0.5)
})
end)
end
function SpaceShip:update( dt )
self._pos.x = 200*math.sin(currentTime())
end
function SpaceShip:draw()
if (self._img) then
local x, y = self:getPos()
self._img:draw( x, y, 0 )
end
end
return SpaceShip |
--[[
Name: "sv_auto.lua".
Product: "nexus".
--]]
local MOUNT = MOUNT;
NEXUS:IncludePrefixed("sh_auto.lua");
-- A function to load the surface texts.
function MOUNT:LoadSurfaceTexts()
self.surfaceTexts = NEXUS:RestoreSchemaData( "mounts/texts/"..game.GetMap() );
end;
-- A function to save the surface texts.
function MOUNT:SaveSurfaceTexts()
NEXUS:SaveSchemaData("mounts/texts/"..game.GetMap(), self.surfaceTexts);
end; |
local export = {}
local gsub = mw.ustring.gsub
local match = mw.ustring.match
local conv = {
-- consonants
['𑒏']='क', ['𑒐']='ख', ['𑒑']='ग', ['𑒒']='घ', ['𑒓']='ङ',
['𑒔']='च', ['𑒕']='छ', ['𑒖']='ज', ['𑒗']='झ', ['𑒘']='ञ',
['𑒙']='ट', ['𑒚']='ठ', ['𑒛']='ड', ['𑒜']='ढ', ['𑒝']='ण',
['𑒞']='त', ['𑒟']='थ', ['𑒠']='द', ['𑒡']='ध', ['𑒢']='न',
['𑒣']='प', ['𑒤']='फ', ['𑒥']='ब', ['𑒦']='भ', ['𑒧'] = 'म',
['𑒨']='य', ['𑒩']='र', ['𑒪']='ल', ['𑒫']='व', ['𑒪𑓃']='ळ',
['𑒬']='श', ['𑒭']='ष', ['𑒮']='स', ['𑒯']='ह',
['𑒛𑓃']='ड़', ['𑒜𑓃']='ढ़', ['𑓃']='़',
-- vowel diacritics
['𑒱']='ि', ['𑒳']='ु', ['𑒹']='े', ['𑒺']='ॆ', ['𑒼']='ो', ['𑒽']='ॊ', ['𑒰']='ा', ['𑒲']='ी', ['𑒴']='ू', ['𑒵']='ृ', ['𑒶']='ॄ', ['𑒻']='ै', ['𑒾']='ौ', ['𑒷']='ॢ', ['𑒸']='ॣ',
['ॏ']='ॏ', ['ऺ']='ऺ', ['ॅ']='ॅ',
-- vowels
['𑒁']='अ', ['𑒂']='आ', ['𑒃']='इ', ['𑒄']='ई', ['𑒅']='उ', ['𑒆']='ऊ', ['𑒇']='ऋ', ['𑒈']='ॠ',
['𑒉']='ऌ', ['𑒊']='ॡ', ['𑒋']='ए', ['𑒌']='ऐ', ['𑒍']='ओ', ['𑒎']='औ',
['ऎ']='ऎ', ['ऒ']='ऒ',
['व़']='व़', ['य़']='य़', ['ॵ']='ॵ', ['ॴ']='ॴ', ['ऍ']='ऍ', ['इऺ']='इऺ', ['उऺ']='उऺ',
['२']='’', ['ऽ']='ऽ',
-- chandrabindu
['𑒿']='ँ',
-- anusvara
['𑓀']='ं',
-- gvang
['𑓅']='ँ',
-- visarga
['𑓁']='ः',
-- virama
['𑓂']='्',
-- om
['𑓇']='ॐ',
-- numerals
['𑓐']='०', ['𑓑']='१', ['𑓒']='२', ['𑓓']='३', ['𑓔']='४', ['𑓕']='५', ['𑓖']='६', ['𑓗']='७', ['𑓘']='८', ['𑓙']='९',
-- punctuation
['।']='।', -- danda
['॥']='॥', -- double danda
['+']='+', -- compound separator
-- abbreviation sign
['॰']='॰',
}
function export.tr(text, lang, sc)
text = mw.ustring.gsub(
text,
".",
function(c)
return conv[c]
end)
return text
end
return export |
local utils = {}
utils.exec_in_normal = function(callback, ...)
vim.api.nvim_command [[stopinsert]]
callback(...)
end
utils.set_cursor_to_end = function()
utils.exec_in_normal(vim.api.nvim_input, 'A')
end
utils.set_cursor_to_start = function()
utils.exec_in_normal(vim.api.nvim_input, 'I')
end
utils.set_cursor_to_word_end = function()
utils.exec_in_normal(vim.api.nvim_input, 'ei')
end
utils.set_cursor_to_word_start = function()
utils.exec_in_normal(vim.api.nvim_input, 'bi')
end
utils.clear_line = function()
utils.exec_in_normal(vim.api.nvim_input, '0C')
end
utils.undo = function()
utils.exec_in_normal(vim.api.nvim_input, 'ui')
end
utils.redo = function()
utils.exec_in_normal(vim.api.nvim_input, '<c-r>i')
end
return utils
|
local theme={colors={normal={blue={0.58823529411765,0.53333333333333,0.24313725490196,1},green={0.53333333333333,0.24313725490196,0.58823529411765,1},cyan={0.58823529411765,0.24313725490196,0.29803921568627,1},white={0.50588235294118,0.70980392156863,0.67450980392157,1},red={0.24313725490196,0.58823529411765,0.53333333333333,1},magenta={0.29803921568627,0.58823529411765,0.24313725490196,1},black={0.011764705882353,0.10196078431373,0.086274509803922,1},yellow={0.24313725490196,0.29803921568627,0.58823529411765,1}},primary={background={0.011764705882353,0.10196078431373,0.086274509803922,1},foreground={0.50588235294118,0.70980392156863,0.67450980392157,1}},bright={blue={0.37254901960784,0.61176470588235,0.57254901960784,1},green={0.043137254901961,0.20392156862745,0.17647058823529,1},cyan={0.24313725490196,0.58823529411765,0.35686274509804,1},white={0.82352941176471,0.90588235294118,0.89411764705882,1},red={0.24313725490196,0.47450980392157,0.58823529411765,1},magenta={0.65490196078431,0.8078431372549,0.7843137254902,1},black={0.16862745098039,0.4078431372549,0.36862745098039,1},yellow={0.094117647058824,0.30588235294118,0.27058823529412,1}},cursor={text={0.011764705882353,0.10196078431373,0.086274509803922,1},cursor={0.50588235294118,0.70980392156863,0.67450980392157,1}}}}
return theme.colors |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.