content
stringlengths 5
1.05M
|
---|
--[[
################################################################################
#
# Copyright (c) 2014-2019 Ultraschall (http://ultraschall.fm)
#
# 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.
#
################################################################################
]]
-------------------------------------
--- ULTRASCHALL - API - FUNCTIONS ---
-------------------------------------
--- ReaMote Module ---
-------------------------------------
if type(ultraschall)~="table" then
-- update buildnumber and add ultraschall as a table, when programming within this file
local retval, string = reaper.BR_Win32_GetPrivateProfileString("Ultraschall-Api-Build", "Functions-Build", "", reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
local retval, string = reaper.BR_Win32_GetPrivateProfileString("Ultraschall-Api-Build", "ReaMote-Module-Build", "", reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
local retval, string2 = reaper.BR_Win32_GetPrivateProfileString("Ultraschall-Api-Build", "API-Build", "", reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
if string=="" then string=10000
else
string=tonumber(string)
string=string+1
end
if string2=="" then string2=10000
else
string2=tonumber(string2)
string2=string2+1
end
reaper.BR_Win32_WritePrivateProfileString("Ultraschall-Api-Build", "Functions-Build", string, reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
reaper.BR_Win32_WritePrivateProfileString("Ultraschall-Api-Build", "API-Build", string2, reaper.GetResourcePath().."/UserPlugins/ultraschall_api/IniFiles/ultraschall_api.ini")
ultraschall={}
ultraschall.API_TempPath=reaper.GetResourcePath().."/UserPlugins/ultraschall_api/temp/"
end
function ultraschall.AutoSearchReaMoteClients()
--[[
<US_DocBloc version="1.0" spok_lang="en" prog_lang="*">
<slug>AutoSearchReaMoteClients</slug>
<requires>
Ultraschall=4.00
Reaper=5.977
SWS=2.10.0.1
JS=0.986
Lua=5.3
</requires>
<functioncall>ultraschall.AutoSearchReaMoteClients()</functioncall>
<description>
Auto-searches for new ReaMote-clients
</description>
<chapter_context>
ReaMote
</chapter_context>
<target_document>US_Api_Functions</target_document>
<source_document>Modules/ultraschall_functions_ReaMote_Module.lua</source_document>
<tags>reamote, scan, search, clients</tags>
</US_DocBloc>
--]]
local hwnd, hwnd1, hwnd2, retval, prefspage, reopen, id
local use_prefspage=227
id=1076
hwnd = ultraschall.GetPreferencesHWND()
if hwnd~=nil then reaper.JS_Window_Destroy(hwnd) reopen=true end
retval, prefspage = reaper.BR_Win32_GetPrivateProfileString("REAPER", "prefspage", "-1", reaper.get_ini_file())
reaper.ViewPrefs(use_prefspage, 0)
hwnd = ultraschall.GetPreferencesHWND()
hwnd1=reaper.JS_Window_FindChildByID(hwnd, 0)
hwnd2=reaper.JS_Window_FindChildByID(hwnd1, id)
reaper.JS_WindowMessage_Send(hwnd2, "WM_LBUTTONDOWN", 1,1,1,1)
reaper.JS_WindowMessage_Send(hwnd2, "WM_LBUTTONUP", 1,1,1,1)
if hwnd~=nil then reaper.JS_Window_Destroy(hwnd) end
retval = reaper.BR_Win32_WritePrivateProfileString("REAPER", "prefspage", prefspage, reaper.get_ini_file())
reaper.ViewPrefs(prefspage, 0)
if reopen~=true then
hwnd = ultraschall.GetPreferencesHWND()
if hwnd~=nil then reaper.JS_Window_Destroy(hwnd) end
end
end
function ultraschall.AutoSearchReaMoteSlaves()
local hwnd, hwnd1, hwnd2, retval, prefspage, reopen, id
local use_prefspage=227
id=1076
hwnd = ultraschall.GetPreferencesHWND()
if hwnd~=nil then reaper.JS_Window_Destroy(hwnd) reopen=true end
retval, prefspage = reaper.BR_Win32_GetPrivateProfileString("REAPER", "prefspage", "-1", reaper.get_ini_file())
reaper.ViewPrefs(use_prefspage, 0)
hwnd = ultraschall.GetPreferencesHWND()
hwnd1=reaper.JS_Window_FindChildByID(hwnd, 0)
hwnd2=reaper.JS_Window_FindChildByID(hwnd1, id)
reaper.JS_WindowMessage_Send(hwnd2, "WM_LBUTTONDOWN", 1,1,1,1)
reaper.JS_WindowMessage_Send(hwnd2, "WM_LBUTTONUP", 1,1,1,1)
if hwnd~=nil then reaper.JS_Window_Destroy(hwnd) end
retval = reaper.BR_Win32_WritePrivateProfileString("REAPER", "prefspage", prefspage, reaper.get_ini_file())
reaper.ViewPrefs(prefspage, 0)
if reopen~=true then
hwnd = ultraschall.GetPreferencesHWND()
if hwnd~=nil then reaper.JS_Window_Destroy(hwnd) end
end
end
--ultraschall.AutoSearchReaMoteSlaves()
|
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
--
-- Created by IntelliJ IDEA.
-- User: Noneatme
-- Date: 05.02.2015
-- Time: 13:38
-- To change this template use File | Settings | File Templates.
--
cMarketGUI = inherit(cSingleton);
--[[
]]
-- ///////////////////////////////
-- ///// show //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:show()
if(localPlayer:getData("loggedIn")) then
if(self.enabled) then
self:hide()
end
if not(clientBusy) then
self:createElements()
self.enabled = true
end
end
end
-- ///////////////////////////////
-- ///// hide //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:hide()
if(self.guiEle["window"]) then
self.guiEle["window"]:hide();
self.guiEle["window"]:destructor()
delete(self.guiEle["window"])
self.guiEle["window"] = false;
self.enabled = false;
end
end
-- ///////////////////////////////
-- ///// hideTemp //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:hideTemp()
if(self.guiEle["window"]) then
self.guiEle["window"]:hide(true);
showCursor(true)
end
end
-- ///////////////////////////////
-- ///// showTemp //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:showTemp()
if(self.guiEle["window"]) then
clientBusy = false
self.guiEle["window"]:show(false, true);
end
end
-- ///////////////////////////////
-- ///// updateTime //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:updateTime()
self.guiEle["label2"]:setText(self.Time);
end
-- ///////////////////////////////
-- ///// getLast7Days //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:getLast7Days()
local timestamp = getRealTime().timestamp;
local days = {}
for i = 1, 7, 1 do
local time = getRealTime(timestamp-((24*60*60)*(i-1)))
local day = time.monthday;
local month = time.month+1;
if(day < 10) then day = "0"..day end
if(month < 10) then month = "0"..month end
days[i] = day.."."..month;
end
return days;
end
-- ///////////////////////////////
-- ///// drawRaten //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:drawRaten()
local rt = self.tabEle["tab_4"][2];
rt:clear()
rt:dxDrawLine(55, 35, 55, 300, tocolor(255, 255, 255, 200), 2)
rt:dxDrawLine(55, 300, 530, 300, tocolor(255, 255, 255, 200), 2)
-- rt:dxDrawLine(15, 5, 15, 340, tocolor(255, 255, 255, 200), 2)
rt:dxDrawText("(y)Anzahl", 30, 15, 100, 20, tocolor(255, 255, 255, 200), 1, "default-bold")
rt:dxDrawText("(x)Tag", 60, 305, 100, 20, tocolor(255, 255, 255, 200), 1, "default-bold")
-- Stueckzahl --
local increm = 35;
for i = 0, 7, 1 do
rt:dxDrawLine(35, 300-increm*i, 55, 300-increm*i, tocolor(255, 255, 255, 200), 2)
end
-- Tag --
local increm = 60;
rt:dxDrawLine(55, 300, 55, 320, tocolor(255, 255, 255, 200), 2)
for i = 1, 7, 1 do
rt:dxDrawLine(55+increm*i, 300, 55+increm*i, 320, tocolor(255, 255, 255, 200), 2)
end
-- Draw Tag --
local days = self:getLast7Days()
local increm = 60;
for i = 7, 1, -1 do
rt:dxDrawText(days[i], 40+(increm*i), 320, 80, 300, tocolor(255, 255, 255, 200), 1, "default-bold")
end
if(self.m_tblItemKaufpreis) then
local function getMaxItemCount()
local curheight = 0;
for index, anz in pairs(self.m_tblItemKaufpreis) do
if(anz > curheight) then
curheight = anz;
end
end
return curheight;
end
local maxAnzahl = getMaxItemCount();
local maxH = 250;
for i = 7, 1, -1 do
local anzahl = self.m_tblItemKaufpreis[i];
local prozent = (anzahl/maxAnzahl)*100;
local curH = maxH*(prozent/100);
if(type(curH) == "number") and (type(prozent) == "number") and (anzahl ~= 0) then
rt:dxDrawLine(55+increm*i, 300, 55+increm*i, 300-curH, tocolor(55, 255, 55, 200), 6)
rt:dxDrawText(anzahl, 25+increm*i, 280-curH, 45+increm*i+40, 280-curH+20, tocolor(255, 255, 255, 200), 1, "default-bold", "center", "center")
end
end
rt:dxDrawText("0", 10, 292, 100, 20, tocolor(255, 255, 255, 200), 1, "default-bold")
rt:dxDrawText(math.floor(maxAnzahl/2), 10, 152, 100, 20, tocolor(255, 255, 255, 200), 1, "default-bold")
rt:dxDrawText(maxAnzahl, 10, 25, 100, 20, tocolor(255, 255, 255, 200), 1, "default-bold")
end
end
-- ///////////////////////////////
-- ///// openMarketWithItem //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:openMarketWithItem(iID)
if(self.enabled) then
local kat = self.m_tblItemsCategories[iID]
if(kat) and (iID) then
local katName = self.m_tblItemCategorieNames[iID]
local itemName = self.m_tblCurSItems[iID].Name
if(katName) and (itemName) then
self:onKategorySelect(katName)
self:onItemSelect(itemName)
end
end
else
self.onEnabledFunc = function() self:openMarketWithItem(iID) end
self:doToggle()
end
end
-- ///////////////////////////////
-- ///// generateItemPages //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:generateItemPages()
self.tabEle["tab_1"] =
{
new(CDxImage, 15, -5, 128, 128, "res/images/items/unknown.png", tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --1
new(CDxLabel, "Item auswaehlen", 165, -5, 328, 48, tocolor(255, 255, 255, 255), 2, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --2
new(CDxLabel, "Beschreibung: ", 165, 40, 328, 68, tocolor(255, 255, 255, 255), 0.9, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --3
new(CDxLabel, "Guenstigster Preis:", 165, 80, 228, 28, tocolor(255, 255, 255, 150), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --4
new(CDxLabel, "$0", 165, 100, 80, 28, tocolor(255, 255, 255, 255), 1.3, CDxWindow.gFont, "center", "center", self.guiEle["tab_1"]), --5
new(CDxButton, "Kaufen", 350, 95, 120, 28, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --6
new(CDxButton, "Nachfrage", 475, 95, 120, 28, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --7
-- ANGEBOT UND NACHFRAGE --
-- Spacer --
new(CDxLabel, string.rep("_", 64), 15, 101, 590, 48, tocolor(0, 0, 0, 255), 2, "default-bold", "left", "top", self.guiEle["tab_1"]), --8
new(CDxLabel, string.rep("_", 64), 15, 100, 590, 48, tocolor(255, 255, 255, 150), 2, "default-bold", "left", "top", self.guiEle["tab_1"]), --9
-- --
new(CDxLabel, "Angebot", 25, 137, 250, 50, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --10
new(CDxList, 15, 155, 580, 100, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --11
new(CDxLabel, "Nachfrage", 25, 257, 250, 50, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --12
new(CDxList, 15, 275, 580, 100, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --13
}
self.tabEle["tab_2"] =
{
new(CDxLabel, "Details zum Item:", 5, -5, 228, 48, tocolor(255, 255, 255, 255), 2, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --1
new(CDxList, 5, 35, 590, 350, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --2
}
self.tabEle["tab_3"] =
{
new(CDxLabel, "Eigene Angebote:", 5, -5, 228, 48, tocolor(255, 255, 255, 255), 2, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --1
new(CDxList, 5, 35, 590, 320, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --2
new(CDxButton, "Item Anbieten", 5, 360, 140, 28, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]), --3
new(CDxButton, "Angebot entfernen", 150, 360, 150, 28, tocolor(255, 255, 255, 255), self.guiEle["tab_1"]),
}
self.tabEle["tab_4"] =
{
new(CDxLabel, "Aktionen der letzten 7 Tage:", 5, -5, 228, 48, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_1"]), --1
new(CDxRenderTarget, 5, 35, 590, 350, self.guiEle["tab_1"]),
}
self.tabEle["tab_1"][11]:addColumn("ID");
self.tabEle["tab_1"][11]:addColumn("Anzahl");
self.tabEle["tab_1"][11]:addColumn("Preis/Item");
self.tabEle["tab_1"][11]:addColumn("Person");
self.tabEle["tab_1"][11]:addColumn("Datum");
self.tabEle["tab_1"][13]:addColumn("ID");
self.tabEle["tab_1"][13]:addColumn("Anzahl");
self.tabEle["tab_1"][13]:addColumn("Preis/Item");
self.tabEle["tab_1"][13]:addColumn("Person");
self.tabEle["tab_1"][13]:addColumn("Datum");
self.tabEle["tab_2"][2]:addColumn("Detail")
self.tabEle["tab_2"][2]:addColumn("Wert")
self.tabEle["tab_3"][2]:addColumn("ID");
self.tabEle["tab_3"][2]:addColumn("Typ");
self.tabEle["tab_3"][2]:addColumn("Stueckzahl");
self.tabEle["tab_3"][2]:addColumn("Preis");
self.tabEle["tab_3"][2]:addColumn("Datum");
self.tabEle["tab_3"][3]:addClickFunction(self.m_funcItemAnbietenClick)
self.tabEle["tab_1"][6]:setDisabled(true)
self.tabEle["tab_3"][4]:setDisabled(true)
self.tabEle["tab_3"][4]:addClickFunction(self.m_funcItemEigenesAngebotEntfernen)
self.tabEle["tab_3"][2]:addClickFunction(function() if(self.tabEle["tab_3"][2]:getRowData(1)) then self.tabEle["tab_3"][4]:setDisabled(false) else self.tabEle["tab_3"][4]:setDisabled(true) end end);
self.tabEle["tab_1"][7]:addClickFunction(self.m_funcItemAnfrageClick)
self.tabEle["tab_1"][7]:setDisabled(true)
self.tabEle["tab_3"][4]:setDisabled(true)
self.tabEle["tab_1"][6]:setDisabled(true)
self.tabEle["tab_1"][11]:addClickFunction(self.m_funcItemListAngebotClick)
self.tabEle["tab_1"][13]:addClickFunction(self.m_funcItemListNachfrageClick)
self.tabEle["tab_1"][6]:addClickFunction(self.m_funcItemKaufenClick)
self:drawRaten()
end
-- ///////////////////////////////
-- ///// useIntroPage //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:genIntroPage()
self.guiEle["tablist_intro"] = new(CDxTabbedPane, 190, 5, 605, 425, tocolor(255, 255, 255, 255), self.guiEle["window"])
self.guiEle["tab_tablist_1"] = new(CDxTab, "Startseite", self.guiEle["tablist_intro"]);
self.guiEle["tab_tablist_2"] = new(CDxTab, "Meine Angebote", self.guiEle["tablist_intro"]);
self.guiEle["tab_tablist_3"] = new(CDxTab, "Meine Nachfragen", self.guiEle["tablist_intro"]);
self.guiEle["tab_tablist_4"] = new(CDxTab, "Hilfe", self.guiEle["tablist_intro"]);
self.tabEle2["tab_tablist_1"] =
{
new(CDxLabel, "Willkommen im ".._Gsettings.serverName.." Market! \nHier kannst du Items anbieten, verkaufen oder den Wechselkurs betrachten.", 15, 1, 550, 50, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_tablist_1"]), --10
new(CDxLabel, "Zurzeit befinden sich 0 Angebote und 0 Anfragen im Markt.", 15, 45, 550, 50, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_tablist_1"]), --10
new(CDxLabel, "Neuste Angebote:", 15, 65, 550, 50, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_tablist_1"]),
new(CDxList, 15, 90, 575, 290, tocolor(255, 255, 255, 255), self.guiEle["tab_tablist_1"])
}
self.tabEle2["tab_tablist_2"] =
{
new(CDxLabel, "Hier kannst du all deine zurzeitigen Angebote betrachten.", 15, 1, 550, 50, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_tablist_2"]), --10
new(CDxList, 15, 30, 575, 350, tocolor(255, 255, 255, 255), self.guiEle["tab_tablist_2"])
}
self.tabEle2["tab_tablist_3"] =
{
new(CDxLabel, "Hier kannst du all deine zurzeitigen Nachfragen betrachten.", 15, 1, 550, 50, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_tablist_2"]), --10
new(CDxList, 15, 30, 575, 350, tocolor(255, 255, 255, 255), self.guiEle["tab_tablist_3"])
}
self.tabEle2["tab_tablist_4"] =
{
new(CDxLabel, "Der ".._Gsettings.serverName.." Market ist ein Virtueller Markt wo du Items anbieten und kaufen kannst.\n\nEr ist ausserdem der einzige Ort, wo du spezielle Items wie Scanner erwerben kannst.\n\nItem Verkaufen\nUm ein Item im Markt anzubieten, musst du erst ein Item deiner Wahl suchen. In dem Reiter 'Eigene Angebote' kannst du nun auf 'Item Anbieten' klicken. Bitte beachte das nicht jedes Item verkauft und gekauft werden kann, da es sich auch um Illegale Items handeln kann.\n\nNachfrage\nUm eine Nachfrage zu schreiben, klicke nachdem du ein Item angewaehlt hast auf den Knopf 'Nachfrage'. Du wirst im Vorraus den Preis fuer das Item bezahlen und es erhalten, sobald eine Person dein Angebot akzeptiert hat.\n\n\nSollte ein Fehler im System entstehen, kannst du dich an einem Administrator deiner Wahl wenden. Dir wird anschliessend dein Verlust erstattet.", 15, 1, 550, 350, tocolor(255, 255, 255, 255), 1, CDxWindow.gFont, "left", "top", self.guiEle["tab_tablist_1"]), --10
}
self.tabEle2["tab_tablist_1"][4]:addDoubleClickFunction(function(dxList)
local id = self.m_tblItemNames[dxList:getRowData(2)];
self:openMarketWithItem(id)
end)
self.tabEle2["tab_tablist_2"][2]:addDoubleClickFunction(function(dxList)
local id = self.m_tblItemNames[dxList:getRowData(2)];
self:openMarketWithItem(id)
end)
self.tabEle2["tab_tablist_3"][2]:addDoubleClickFunction(function(dxList)
local id = self.m_tblItemNames[dxList:getRowData(2)];
self:openMarketWithItem(id)
end)
self.tabEle2["tab_tablist_1"][4]:addColumn("Icon", true)
self.tabEle2["tab_tablist_1"][4]:addColumn("Itemname")
self.tabEle2["tab_tablist_1"][4]:addColumn("Anzahl")
self.tabEle2["tab_tablist_1"][4]:addColumn("Preis (insg.)")
self.tabEle2["tab_tablist_1"][4]:addColumn("Datum")
self.tabEle2["tab_tablist_1"][4]:addColumn("Spieler")
self.tabEle2["tab_tablist_1"][4]:addColumn("ID")
self.tabEle2["tab_tablist_2"][2]:addColumn("Icon", true)
self.tabEle2["tab_tablist_2"][2]:addColumn("Itemname")
self.tabEle2["tab_tablist_2"][2]:addColumn("Anzahl")
self.tabEle2["tab_tablist_2"][2]:addColumn("Preis (insg.)")
self.tabEle2["tab_tablist_2"][2]:addColumn("Datum")
self.tabEle2["tab_tablist_2"][2]:addColumn("ID")
self.tabEle2["tab_tablist_3"][2]:addColumn("Icon", true)
self.tabEle2["tab_tablist_3"][2]:addColumn("Itemname")
self.tabEle2["tab_tablist_3"][2]:addColumn("Anzahl")
self.tabEle2["tab_tablist_3"][2]:addColumn("Preis (insg.)")
self.tabEle2["tab_tablist_3"][2]:addColumn("Datum")
self.tabEle2["tab_tablist_3"][2]:addColumn("ID")
for tabname, tbl in pairs(self.tabEle2) do
for index, ele in pairs(tbl) do
self.guiEle[tabname]:add(ele)
end
end
self.guiEle["tablist_intro"]:addTab(self.guiEle["tab_tablist_1"], {115, tocolor(125, 125, 125, 55)})
self.guiEle["tablist_intro"]:addTab(self.guiEle["tab_tablist_2"], {155, tocolor(125, 125, 125, 55)})
self.guiEle["tablist_intro"]:addTab(self.guiEle["tab_tablist_3"], {155, tocolor(125, 125, 125, 55)})
self.guiEle["tablist_intro"]:addTab(self.guiEle["tab_tablist_4"], {95, tocolor(125, 125, 125, 55)})
self.guiEle["tablist_intro"]:setVisible(false)
end
-- ///////////////////////////////
-- ///// useItemPage //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:genItemPage()
self.guiEle["tablist"] = new(CDxTabbedPane, 190, 5, 605, 425, tocolor(255, 255, 255, 255), self.guiEle["window"])
self.guiEle["tab_1"] = new(CDxTab, "Angebot / Nachfrage", self.guiEle["tablist"]);
self.guiEle["tab_2"] = new(CDxTab, "Informationen", self.guiEle["tablist"]);
self.guiEle["tab_3"] = new(CDxTab, "Eigene Angebote", self.guiEle["tablist"]);
self.guiEle["tab_4"] = new(CDxTab, "Raten", self.guiEle["tablist"]);
self.tabEle["tab_1"] = {};
self.tabEle["tab_2"] = {};
self.tabEle["tab_3"] = {};
self.tabEle["tab_4"] = {};
self:generateItemPages(iItemID, sItemName)
self.guiEle["tablist"]:addTab(self.guiEle["tab_1"], {175, tocolor(125, 125, 125, 55)})
self.guiEle["tablist"]:addTab(self.guiEle["tab_2"], {125, tocolor(125, 125, 125, 55)})
self.guiEle["tablist"]:addTab(self.guiEle["tab_3"], {125, tocolor(125, 125, 125, 55)})
self.guiEle["tablist"]:addTab(self.guiEle["tab_4"], {75, tocolor(125, 125, 125, 55)})
for tabname, tbl in pairs(self.tabEle) do
for index, ele in pairs(tbl) do
self.guiEle[tabname]:add(ele)
end
end
self.guiEle["tablist"]:setVisible(false)
end
-- ///////////////////////////////
-- ///// updateItemPages //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:updateItemPages(item, angebote, tblEigeneAngebote)
local id = tonumber(item['ID'])
if(fileExists("res/images/items/"..id..".png")) then
self.tabEle["tab_1"][1]:setImage("res/images/items/"..id..".png");
else
self.tabEle["tab_1"][1]:setImage("res/images/items/unknown.png");
end
self.tabEle["tab_1"][11]:clearRows()
self.tabEle["tab_1"][13]:clearRows()
self.tabEle["tab_2"][2]:clearRows();
self.tabEle["tab_3"][2]:clearRows();
self.tabEle["tab_1"][2]:setText(string.gsub(item['Name'], "\\", ""))
self.tabEle["tab_1"][3]:setText("Beschreibung: "..item['Description']);
self.guiEle["tablist"]:selectTab(1)
self.tabEle["tab_2"][2]:addRow("Itemname|"..(item['Name'] or "Unbekannt"))
self.tabEle["tab_2"][2]:addRow("Item ID|"..(item['ID'] or "Unbekannt"))
local handelbar, benutzbar, konsumgueter, illegal, deletable = "Nein", "Nein", "Nein", "Nein", "Nein";
if(tonumber(item['Useable']) == 1) then
benutzbar = "Ja"
end
if(tonumber(item['Consume']) == 1) then
konsumgueter = "Ja"
end
if(tonumber(item['Tradeable']) == 1) then
handelbar = "Ja"
end
if(tonumber(item['Deleteable']) == 1) then
deletable = "Ja"
end
if(tonumber(item['Illegal']) == 1) then
illegal = "Ja"
end
self.tabEle["tab_2"][2]:addRow("Standartkosten|$"..((item['Cost'] or "Unbekannt")))
self.tabEle["tab_2"][2]:addRow("Max. Anzahl|"..((item['Stacksize'] or "Unbekannt")))
self.tabEle["tab_2"][2]:addRow("Kann gehandelt werden|"..(handelbar))
self.tabEle["tab_2"][2]:addRow("Kann benutzt werden|"..(benutzbar))
self.tabEle["tab_2"][2]:addRow("Kann konsumiert werden|"..(konsumgueter))
self.tabEle["tab_2"][2]:addRow("Kann geloescht werden|"..(deletable))
self.tabEle["tab_2"][2]:addRow("Illegal|"..(illegal))
self.tabEle["tab_2"][2]:addRow("Gewicht|"..((item['Gewicht'] or "Unbekannt")))
-- ANGEBOTE --
local minPreis = math.huge;
if(angebote) then
table.sort( angebote, function( a,b ) return tonumber(a['Preis']) < tonumber(b['Preis']) end )
for index, tbl in pairs(angebote) do
local id = tbl['AngebotID'];
local itemID = tbl['ItemID'];
local type = tonumber(tbl['AngebotType']);
local player = tbl['Name'];
local anzahl = tbl['Anzahl'];
local preis = tbl['Preis'];
local time = tbl['StartTimestamp'];
if(preis < minPreis) and (type == 1) then
minPreis = preis
end
local list = self.tabEle["tab_1"][11];
if(type == 1) then -- Angebot
list = self.tabEle["tab_1"][11]
elseif(type == 2) then -- Nachfrage
list = self.tabEle["tab_1"][13]
end
list:addRow(id.."|"..anzahl.."|$"..preis.."|"..player.."|"..formatTimestamp(time))
end
end
if(tblEigeneAngebote) then
for index, tbl in pairs(tblEigeneAngebote) do
table.sort( tbl, function( a,b ) return tonumber(a['AngebotType']) < tonumber(b['AngebotType']) end )
local id = tbl['AngebotID'];
local typ = tbl['AngebotType']
if(tonumber(typ == 1)) then typ = "Angebot" else typ = "Nachfrage" end
local stck = tbl['Anzahl']
local preis = "$"..tbl['Preis'];
local datum = getRealTime(tonumber(tbl['StartTimestamp']));
local time = datum.monthday.."."..(datum.month+1).."."..(datum.year+1900).." "..(datum.hour)..":"..datum.minute..":"..datum.second;
self.tabEle["tab_3"][2]:addRow(id.."|"..typ.."|"..stck.."|"..preis.."|"..time)
end
end
local bBool = false;
if(tonumber(item['Tradeable']) == 0) or (tonumber(item['Illegal']) == 1) then
bBool = true
end
self.tabEle['tab_1'][6]:setDisabled(bBool)
self.tabEle['tab_1'][7]:setDisabled(bBool)
self.tabEle['tab_3'][3]:setDisabled(bBool)
self.tabEle['tab_3'][4]:setDisabled(bBool)
if(minPreis == math.huge) then
minPreis = "-"
end
self.tabEle["tab_1"][5]:setText(minPreis.."$")
self:showTabPane("item")
end
-- ///////////////////////////////
-- ///// showTabPane //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:showTabPane(sPane)
if(sPane == "startseite") then
self.guiEle["tablist"]:setVisible(false)
self.guiEle["tablist_intro"]:setVisible(true)
else
self.guiEle["tablist"]:setVisible(true)
self.guiEle["tablist_intro"]:setVisible(false)
end
end
-- ///////////////////////////////
-- ///// createElements //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:createElements()
if not(self.guiEle["window"]) then
self.guiEle["window"] = new(CDxWindow, _Gsettings.serverName.." Market", 800, 450, true, true, "Center|Middle", 0, 0, {tocolor(125, 125, 255, 255), "res/images/dxGui/misc/icons/market.png", "Markt"}, "Hier kannst du alles Kaufen und Verkaufen was du möchtest.")
self.guiEle["window"].xtraHide = function(...) self:hide(...) end
self.guiEle["kategorie_view"] = new(CDxList, 5, 5, 180, 200, tocolor(255, 255, 255, 255), self.guiEle["window"])
self.guiEle["kategorie_view"]:addColumn("Kategorien")
self.guiEle["kategorie_view"]:addClickFunction(self.m_funcClickKategory)
self.guiEle["item_view"] = new(CDxList, 5, 210, 180, 184, tocolor(255, 255, 255, 255), self.guiEle["window"])
self.guiEle["item_view"]:addColumn("Icon", true)
self.guiEle["item_view"]:addColumn("Itemname")
self.guiEle["item_view"]:addClickFunction(self.m_funcClickItem);
self.guiEle["item_edit"] = new(CDxEdit, "Suche...", 5, 400, 180, 25, "text", tocolor(255, 255, 255, 255), self.guiEle["window"])
self.guiEle["item_edit"]:addEditFunction(self.m_funcSearchItem);
self.guiEle["item_edit"]:addClickFunction(self.m_funcSearchItemClick);
self:genItemPage()
self:genIntroPage()
self:showTabPane("startseite")
for index, ele in pairs(self.guiEle) do
if(index ~= "window") then
self.guiEle["window"]:add(ele)
end
end
self.guiEle["window"]:show();
self.guiEle["tablist"]:selectTab(4)
self.enabled = true;
--[[
if(self.m_tblCurSItems) then
self:onItemsReceive(self.m_tblCurSItems, self.m_tblCurSCats)
end]]
end
end
-- ///////////////////////////////
-- ///// updateStartseitenItems //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:updateStartseitenItems(m_tblLastAngebote, m_tblCountAngebote, m_tblCountAnfragen, tbl_eigenAngebote)
-- LABEL --
--[[
self.tabEle2["tab_tablist_1"][4]:addColumn("Icon", true)
self.tabEle2["tab_tablist_1"][4]:addColumn("Itemname")
self.tabEle2["tab_tablist_1"][4]:addColumn("Anzahl")
self.tabEle2["tab_tablist_1"][4]:addColumn("Preis")
self.tabEle2["tab_tablist_1"][4]:addColumn("Datum")
self.tabEle2["tab_tablist_1"][4]:addColumn("Spieler")
self.tabEle2["tab_tablist_1"][4]:addColumn("ID")
]]
self.tabEle2["tab_tablist_1"][2]:setText("Zurzeit befinden sich "..m_tblCountAngebote[1]['C1'].." Angebote und "..m_tblCountAnfragen[1]['C1'].." Anfragen im Markt.")
-- TAB 1--
self.tabEle2["tab_tablist_1"][4]:clearRows()
for index, row in pairs(m_tblLastAngebote) do
local itemID = tonumber(row['ItemID'])
local name = row['Name'];
local itemSTR = "res/images/none.png";
local anzahl = tonumber(row['Anzahl'])
local preis = anzahl*(tonumber(row['Preis']))
local time = row['StartTimestamp']
local id = row['AngebotID']
if(fileExists("res/images/items/"..itemID..".png")) then
itemSTR = "res/images/items/"..itemID..".png"
end
self.tabEle2["tab_tablist_1"][4]:addRow(itemSTR.."|"..self.m_tblCurSItems[itemID].Name.."|"..anzahl.."|$"..preis.."|"..formatTimestamp(time).."|"..name.."|"..id, 1)
end
-- TAB 2--
for index, row in pairs(tbl_eigenAngebote) do
local itemID = tonumber(row['ItemID'])
local name = row['Name'];
local itemSTR = "res/images/none.png";
local anzahl = tonumber(row['Anzahl'])
local preis = anzahl*(tonumber(row['Preis']))
local time = row['StartTimestamp']
local id = row['AngebotID']
if(fileExists("res/images/items/"..itemID..".png")) then
itemSTR = "res/images/items/"..itemID..".png"
end
if(row['AngebotType'] == 1) then -- Angebot
self.tabEle2["tab_tablist_2"][2]:addRow(itemSTR.."|"..self.m_tblCurSItems[itemID].Name.."|"..anzahl.."|$"..preis.."|"..formatTimestamp(time).."|"..id, 1)
else -- Nachfrage
self.tabEle2["tab_tablist_3"][2]:addRow(itemSTR.."|"..self.m_tblCurSItems[itemID].Name.."|"..anzahl.."|$"..preis.."|"..formatTimestamp(time).."|"..id, 1)
end
end
-- TAB 3 --
end
-- ///////////////////////////////
-- ///// onItemsReceive //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemsReceive(tblItems, tblCategorys, ...)
if not(self.enabled) then --m_tblLastAngebote, m_tblCountAngebote, m_tblCountAnfragen, tbl_eigenAngebote
self:show()
end
self.m_bWaitForServer = false;
loadingSprite:setEnabled(false)
-- Clear Items and Categorys --
self.guiEle["kategorie_view"]:clearRows();
self.guiEle["item_view"]:clearRows();
self.m_tblCatIDS = {}
self.m_tblCatItems = {}
self.m_tblCatNames = {}
self.m_tblItemsCategories = {}
self.m_tblItemCategorieNames = {}
table.sort( tblCategorys, function( a,b ) return a['Name'] < b['Name'] end )
for index, kat in pairs(tblCategorys) do
self.m_tblCatIDS[kat['Name']] = tonumber(kat['ID'])
self.guiEle["kategorie_view"]:addRow(kat['Name'])
self.m_tblCatNames[kat['ID']] = kat['Name']
end
for index, item in pairs(tblItems) do
local kat = tonumber(item['Category']);
if(kat) then
if not(self.m_tblCatItems[kat]) then
self.m_tblCatItems[kat] = {}
end
table.insert(self.m_tblCatItems[kat], item);
table.sort( self.m_tblCatItems[kat], function( a, b ) return a['Name'] < b['Name'] end )
self.m_tblItemsCategories[item.ID] = kat;
self.m_tblItemCategorieNames[item.ID] = self.m_tblCatNames[kat];
end
self.m_tblItemNames[item.Name] = item.ID
end
self.m_tblCurSItems = tblItems;
self.m_tblCurSCats = tblCategorys
-- STARTSEITE --
self:updateStartseitenItems(...)
if(self.onEnabledFunc) then
self.onEnabledFunc()
self.onEnabledFunc = false;
end
end
-- ///////////////////////////////
-- ///// onItemsReceive //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemInformationReceive(iItemID, tblInformations)
-- Clear Items and Categorys --
self.tabEle["tab_2"][2]:clearRows();
end
-- ///////////////////////////////
-- ///// clearTabs //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:clearTabs()
for tabname, tbl in pairs(self.tabEle) do
for index, ele in pairs(tbl) do
delete(ele);
end
end
end
-- ///////////////////////////////
-- ///// getItemFromName //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:getItemFromName(sName)
for kat_id, items in pairs(self.m_tblCatItems) do
if(items) then
for index, item in pairs(items) do
local name = item["Name"];
if(name == sName) then
return item;
end
end
end
end
return false;
end
-- ///////////////////////////////
-- ///// getItemImage //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:getItemImage(iID)
local image = "res/images/none.png";
if(fileExists("res/images/items/"..iID..".png")) then
image = "res/images/items/"..iID..".png";
end
return image;
end
-- ///////////////////////////////
-- ///// onKategorySelect //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onKategorySelect(iCat)
self.guiEle["item_view"]:clearRows();
local data = self.guiEle["kategorie_view"]:getRowData(1);
if(iCat) then
data = iCat
end
if(data) and not(_Gsettings.persistentMarketCategories[data]) then
local kat_id = self.m_tblCatIDS[data];
local items = self.m_tblCatItems[kat_id]
if(items) then
for index, item in pairs(items) do
self.guiEle["item_view"]:addRow(self:getItemImage(item.ID).."|"..item["Name"], 1);
end
end
else
if(data == "- Neuwagen") or (data == "- Gebrauchtwagen") then
local vehicles = {}
for i = 400, 611, 1 do
if(getVehicleNameFromModel(i)) then
vehicles[i] = getVehicleNameFromModel(i);
end
end
table.sort(vehicles, function( a,b ) return a < b end)
for index, bla in pairs(vehicles) do
if(bla) then
if(type(bla) == "string") and (string.len(bla) > 0) then
local image = "res/images/none.png";
self.guiEle["item_view"]:addRow(image.."|"..bla, 1);
end
end
end
end
end
end
-- ///////////////////////////////
-- ///// onItemSelect //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemSelect(iCat)
local item_name = self.guiEle["item_view"]:getRowData(2);
if(iCat) then
item_name = iCat
end
local item = self:getItemFromName(item_name);
self.m_sCurrentItem = item;
if not(self.m_bWaitForServer) then
if(item) and (item['ID']) then
triggerServerEvent("onPlayerMarketItemAngeboteReqeust", localPlayer, item['ID'])
self.m_bWaitForServer = true;
loadingSprite:setEnabled(true)
end
else
showInfoBox("error", "Warten auf Server...")
end
end
-- ///////////////////////////////
-- ///// onItemEditSearch //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemEditSearch()
local text = self.guiEle["item_edit"]:getText()
if(string.len(text) > 0) then
self.guiEle["item_view"]:clearRows();
local found_table = {}
-- Suche --
for kat_id, items in pairs(self.m_tblCatItems) do
if(items) then
for index, item in pairs(items) do
local name = item["Name"];
if(string.find(string.lower(name), string.lower(text))) then
table.insert(found_table, item);
end
end
end
end
table.sort( found_table, function( a,b ) return a['Name'] < b['Name'] end )
for index, item in pairs(found_table) do
self.guiEle["item_view"]:addRow(self:getItemImage(item.ID).."|"..item["Name"], 1);
end
else
self:onKategorySelect();
self:showTabPane("startseite")
end
end
-- ///////////////////////////////
-- ///// onItemEditClick //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemEditClick()
local text = self.guiEle["item_edit"]:getText()
if(text == "Suche...") then
self.guiEle["item_edit"]:setText("");
end
end
-- ///////////////////////////////
-- ///// toggle //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:doToggle()
if(self.enabled) then
self:hide();
clientBusy = false;
else
if not(clientBusy) and not(self.m_bWaitForServer) then
self.m_bWaitForServer = true;
loadingSprite:setEnabled(true)
triggerServerEvent("onPlayerMarketItemsReqeust", localPlayer)
end
end
end
-- ///////////////////////////////
-- ///// onItemAngeboteReceive////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemAngeboteReceive(tblAngebote, tblEigeneAngebote, tblMarketPurchases)
if(self.m_bWaitForServer) then
self.m_bWaitForServer = false;
loadingSprite:setEnabled(false)
self:updateItemPages(self.m_sCurrentItem, tblAngebote, tblEigeneAngebote);
if(tblMarketPurchases) then
self.m_tblItemKaufpreis = tblMarketPurchases;
end
self:drawRaten()
end
end
-- ///////////////////////////////
-- ///// onAnfrageStart //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onAnfrageStart(...)
if(self.m_sCurrentItem) then
self:hideTemp()
local function ja()
local anzahl = tonumber(confirmDialog.guiEle["edit"]:getText())
if(anzahl) and (anzahl > 0) and (anzahl < 999999) then
setTimer(function()
local function ja2()
local preis = tonumber(confirmDialog.guiEle["edit"]:getText())
if(preis) and (preis > 0) and (preis < 99999999) then
setTimer(function()
local function nein3()
self:showTemp()
end
local function ja3()
triggerServerEvent("onPlayerMarketAngebotNachfrage", localPlayer, self.m_sCurrentItem['ID'], anzahl, preis);
self:showTemp()
self.m_bWaitForServer = true;
end
confirmDialog:showConfirmDialog("Diese Anfrage wird dich $"..preis*anzahl.." kosten. Wenn jemand deine Anfrage annimmt, erhaelst du das Item.\nDiese Anfrage kannst du jederzeit entfernen.", ja3, nein3, true, false)
end, 50, 1)
else
showInfoBox("error", "Ungueltige Anzahl!")
self:showTemp()
end
end
local function nein2()
self:showTemp()
end
confirmDialog:showConfirmDialog("Wieviel Geld (in $) moechtest du pro Item ausgeben?\nStandartpreis fuer dieses Item: $"..(self.m_sCurrentItem['Cost'] or 0), ja2, nein2, true, true)
end, 50, 1)
else
showInfoBox("error", "Ungueltige Anzahl!")
self:showTemp()
end
end
local function nein()
self:showTemp()
end
confirmDialog:showConfirmDialog("Du schreibst nun eine Anfrage. Wieviel von diesem Item moechtest du kaufen?", ja, nein, true, true);
else
showInfoBox("error", "Bitte waehle ein Item aus!")
end
end
-- ///////////////////////////////
-- ///// onItemAnbietenClick//////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemAnbietenClick()
if(self.m_sCurrentItem) then
self:hideTemp()
local function ja()
local anzahl = tonumber(confirmDialog.guiEle["edit"]:getText())
if(anzahl) and (anzahl > 0) and (anzahl < 999999) or (confirmDialog.guiEle["edit"]:getText() == "all") then
if(confirmDialog.guiEle["edit"]:getText() == "all") then anzahl = "all" end
setTimer(function()
local function ja2()
local preis = tonumber(confirmDialog.guiEle["edit"]:getText())
if(preis) and (preis > 0) and (preis < 99999999) then
setTimer(function()
local function nein3()
self:showTemp()
end
local function ja3()
triggerServerEvent("onPlayerMarketAngebotAnbiete", localPlayer, self.m_sCurrentItem['ID'], anzahl, preis);
self:showTemp()
self.m_bWaitForServer = true;
end
confirmDialog:showConfirmDialog("Dieses Angebot wird dich "..anzahl.." "..self.m_sCurrentItem['Name'].." kosten.. Wenn jemand deine Angebot annimmt, erhaelst du das Geld.\nDieses Angebot kannst du jederzeit entfernen.", ja3, nein3, true, false)
end, 50, 1)
else
showInfoBox("error", "Ungueltige Anzahl!")
self:showTemp()
end
end
local function nein2()
self:showTemp()
end
confirmDialog:showConfirmDialog("Wieviel Geld (in $) moechtest du pro Item erhalten?\nStandartpreis fuer dieses Item: $"..(self.m_sCurrentItem['Cost'] or 0), ja2, nein2, true, true)
end, 50, 1)
else
showInfoBox("error", "Ungueltige Anzahl!")
self:showTemp()
end
end
local function nein()
self:showTemp()
end
confirmDialog:showConfirmDialog("Du schreibst nun ein Angebot. Wieviel von diesem Item moechtest du anbieten? Schreibe 'all' fuer alles.", ja, nein, true, true);
else
showInfoBox("error", "Bitte waehle ein Item aus!")
end
end
-- ///////////////////////////////
-- /onEigenesAngebotEntfernenClick
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onEigenesAngebotEntfernenClick()
local data = tonumber(self.tabEle["tab_3"][2]:getRowData(1))
if(data) then
self:hideTemp()
local function ja()
triggerServerEvent("onPlayerMarketVorhandenesAngebotRemove", localPlayer, data)
self:showTemp()
self.m_bWaitForServer = true;
end
local function nein()
self:showTemp()
end
confirmDialog:showConfirmDialog("Dieses Angebot entfernen?\nDu erhaelst 75% des Uhrsprunges erstattet.", ja, nein, true, false)
end
end
-- ///////////////////////////////
-- /onItemListAngebotClick
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemListAngebotClick()
local list = self.tabEle["tab_1"][11]
if(list:getRowData(1) ~= "nil") then
self.tabEle["tab_1"][6]:setText("Kaufen")
self.m_iSelectedItemBuyList = list;
end
end
-- ///////////////////////////////
-- /onItemListNachfrageClick
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemListNachfrageClick()
local list = self.tabEle["tab_1"][13]
if(list:getRowData(1) ~= "nil") then
self.tabEle["tab_1"][6]:setText("Verkaufen")
self.m_iSelectedItemBuyList = list;
end
end
-- ///////////////////////////////
-- //////onItemKaufClick //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:onItemKaufClick()
if not(self.m_bWaitForServer) then
local list = self.m_iSelectedItemBuyList;
if(list) then
local angebotID = tonumber(list:getRowData(1))
local anzahl = tonumber(list:getRowData(2))
if(angebotID) then
self:hideTemp()
local function ja()
self:showTemp()
loadingSprite:setEnabled(true)
self.m_bWaitForServer = true;
triggerServerEvent("onPlayerMarketItemAngebotPurchase", localPlayer, angebotID, self.m_sCurrentItem['ID'], confirmDialog.guiEle["edit"]:getText());
end
local function nein()
self:showTemp()
end
confirmDialog:showConfirmDialog("Wieviel moechtest du von diesem Item moechtest du (ver)kaufen? Max: "..anzahl, ja, nein, true, true)
else
showInfoBox("error", "Du musst ein Item auswaehlen!")
end
else
showInfoBox("error", "Du musst ein Item auswaehlen!")
end
else
showInfoBox("error", "Warten auf Server...")
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cMarketGUI:constructor(...)
-- Klassenvariablen --
self.guiEle = {}
self.enabled = false;
self.tabEle = {}
self.tabEle2 = {}
self.m_tblItems = {}
self.m_tblCategories = {}
self.m_tblCatIDS = {}
self.m_tblCurItems = {}
self.m_tblItemNames = {}
self.m_tblItemKaufpreis =
{
[1] = 0,
[2] = 0,
[3] = 0,
[4] = 0,
[5] = 0,
[6] = 0,
[7] = 0,
}
-- Funktionen --
self.m_funcClickKategory = function() self:onKategorySelect() end
self.m_funcClickItem = function() self:onItemSelect() end
self.m_funcSearchItem = function(...) self:onItemEditSearch(...) end
self.m_funcSearchItemClick = function(...) self:onItemEditClick(...) end
self.m_funcItemsReceive = function(...) self:onItemsReceive(...) end
self.m_funcGetItemAngebote = function(...) self:onItemAngeboteReceive(...) end
self.toggleFunc = function(...) self:doToggle(...) end
self.m_funcItemAnfrageClick = function(...) self:onAnfrageStart(...) end
self.m_funcItemAnbietenClick = function(...) self:onItemAnbietenClick(...) end
self.m_funcItemEigenesAngebotEntfernen = function(...) self:onEigenesAngebotEntfernenClick(...) end
self.m_funcItemListAngebotClick = function(...) self:onItemListAngebotClick(...) end
self.m_funcItemListNachfrageClick = function(...) self:onItemListNachfrageClick(...) end
self.m_funcItemKaufenClick = function(...) self:onItemKaufClick(...) end
-- Events --
addEvent("onClientPlayerMarketItemsReceive", true)
addEvent("onClientPlayerMarketItemAngeboteReceive", true)
addEventHandler("onClientPlayerMarketItemsReceive", getLocalPlayer(), self.m_funcItemsReceive)
addEventHandler("onClientPlayerMarketItemAngeboteReceive", getLocalPlayer(), self.m_funcGetItemAngebote)
bindKey(_Gsettings.keys.Market, "down", self.toggleFunc)
end
-- EVENT HANDLER --
|
local Library = require "CoronaLibrary"
-- Create library
local lib = Library:new{ name = 'CoronaProvider.native.popup.quickLook', publisherId = 'com.coronalabs' }
-- native.showPopup
function lib.showPopup()
native.showAlert( 'Not Supported', 'The quickLook popup is currently not supported on this platform, please build for an iOS device', { 'OK' } )
end
-- native.canShowPopup
function lib.canShowPopup()
return false
end
-- Return an instance
return lib
|
local Location = {
rootPath = "plugins.cyber_engine_tweaks.mods.cityhack."
}
function Location.ListAll()
local db = sqlite3.open(Location.rootPath.."main.db")
-- db:exec[[
-- CREATE TABLE test (id INTEGER PRIMARY KEY, content);
-- INSERT INTO test VALUES (NULL, 'Hello World');
-- INSERT INTO test VALUES (NULL, 'Hello Lua');
-- INSERT INTO test VALUES (NULL, 'Hello Sqlite3')
-- ]]
for row in db:nrows("SELECT * FROM locations") do
print(row.id, row.name)
end
end
return Location |
--[[
KahLua KonferSK - a suicide kings loot distribution addon.
WWW: http://kahluamod.com/ksk
Git: https://github.com/kahluamods/konfersk
IRC: #KahLua on irc.freenode.net
E-mail: [email protected]
Please refer to the file LICENSE.txt for the Apache License, Version 2.0.
Copyright 2008-2020 James Kean Johnston. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]
local MAJOR= "KKonferSK"
local MINOR = tonumber("@revision@")
local MINOR = 1 -- @debug-delete@
local K,KM = LibStub:GetLibrary("KKore")
local H = LibStub:GetLibrary("KKoreHash")
local KUI = LibStub:GetLibrary("KKoreUI")
local KRP = LibStub:GetLibrary("KKoreParty")
local KLD = LibStub:GetLibrary("KKoreLoot")
local KK = LibStub:GetLibrary("KKoreKonfer")
local DB = LibStub:GetLibrary("AceDB-3.0")
if (not K) then
error("KSK: could not find KahLua Kore.", 2)
end
if (tonumber(KM) < 3) then
error("KSK: outdated KahLua Kore. Please update all KahLua addons.")
end
if (not H) then
error("KSK: could not find Kore Hash library.", 2)
end
if (not DB) then
error("KSK: could not find Kore Database library.", 2)
end
if (not KUI) then
error("KSK: could not find Kore UI library.", 2)
end
if (not KRP) then
error("KSK: could not find Kore Raid/Party library.", 2)
end
if (not KK) then
error("KSK: could not find Kore Konfer library.", 2)
end
if (not KLD) then
error("KSK: could not find Kore Loot Distribution library.", 2)
end
local L = LibStub("AceLocale-3.0"):GetLocale(MAJOR, false)
-- Local aliases for global or Lua library functions
local _G = _G
local tinsert = table.insert
local tonumber = tonumber
local strfmt = string.format
local strsub = string.sub
local strlower = string.lower
local match = string.match
local pairs, ipairs, type = pairs, ipairs, type
local printf = K.printf
local LOOT_METHOD_UNKNOWN = KRP.LOOT_METHOD_UNKNWON
local LOOT_METHOD_FREEFORALL = KRP.LOOT_METHOD_FREEFORALL
local LOOT_METHOD_GROUP = KRP.LOOT_METHOD_GROUP
local LOOT_METHOD_PERSONAL = KRP.LOOT_METHOD_PERSONAL
local LOOT_METHOD_MASTER = KRP.LOOT_METHOD_MASTER
ksk = K:NewAddon(nil, MAJOR, MINOR, L["Suicide Kings loot distribution system."], L["MODNAME"], L["CMDNAME"] )
if (not ksk) then
error("KahLua KonferSK: addon creation failed.", 2)
end
_G["KSK"] = ksk
ksk.KUI = KUI
ksk.L = L
ksk.KRP = KRP
ksk.KLD = KLD
ksk.H = H
ksk.DB = DB
ksk.KK = KK
ksk.CHAT_MSG_PREFIX = "KSKC"
ksk.addon_handle = "kskc"
local MakeFrame = KUI.MakeFrame
-- We will be using both KKoreParty and KKoreLoot.
KRP:RegisterAddon(ksk.addon_handle)
KLD:RegisterAddon(ksk.addon_handle)
KK:RegisterAddon(ksk.addon_handle)
-------------------------------------------------------------------------------
--
-- KSK "global" variables. All variables, whether they can be nil or not, that
-- can possibly be set in the ksk namespace, must be listed here, along with
-- their default value. A description of what the variable controls and which
-- user interface element is affected by the variable must accompany each such
-- global variable. This includes variables used in other files. They must all
-- be declared and described here.
--
-------------------------------------------------------------------------------
-- The version number of this release of KSK. This is set by the prep script
-- when it sets MINOR above. For debug / development releases this is always
-- set to 1. This is used in the version check code as well as the mod info
-- display and mod registration.
ksk.version = MINOR
-- The KSK "protocol" version number. This is used in every addon message
-- that KSK sends. As a general principle someone with a version of the mod
-- that has a higher protocol version number should be able to decode messages
-- from a lower version protocol, but so far we have made no attempt to code
-- this backwards compatibility into each protocol message. So at the moment
-- these protocol versions must match exactly in order for two KSK mods to
-- talk to each other.
-- 1 - internal only (version check)
-- 2 - initial protocol
-- 3 - dates now in UTC seconds since epoch for history
-- 4 - OROLL now has extra param for allowing offspec rolls
-- 5 - resurect guild config and rank priorities
-- 6 - alt tethered now a list option not global
ksk.protocol = 7
-- The format and "shape" of the KSK stored variables database. As various new
-- features have been added or bugs fixed, this changes. The code in the file
-- KSK-Utility.lua (ksk.UpdateDatabaseVersion()) will update older databases
-- dating all the way back to version 1. Once a database version has been
-- upgraded it cannot be reverted.
ksk.dbversion = 5
-- Whether or not KSK has been fully initialised. This can take a while as
-- certain bits of information are not immediately available on login.
-- None of the event handlers or callback functions except those participating
-- in actual initialisation should execute if this is false.
ksk.initialised = false
-- Maximum number of disenchanters that can be defined in a config
ksk.MAX_DENCHERS = 4
-- Constants used to define the various UI tabs and sub-tabs. These should
-- never be changed by code.
ksk.LISTS_TAB = 1
ksk.LISTS_MEMBERS_PAGE = 1
ksk.LISTS_CONFIG_PAGE = 2
ksk.LOOT_TAB = 2
ksk.LOOT_ASSIGN_PAGE = 1
ksk.LOOT_ITEMS_PAGE = 2
ksk.LOOT_HISTORY_PAGE = 3
ksk.USERS_TAB = 3
ksk.SYNC_TAB = 4
ksk.CONFIG_TAB = 5
ksk.CONFIG_LOOT_PAGE = 1
ksk.CONFIG_ROLLS_PAGE = 2
ksk.CONFIG_ADMIN_PAGE = 3
ksk.NON_ADMIN_THRESHOLD = ksk.USERS_TAB
ksk.NON_ADMIN_CONFIG_THRESHOLD = ksk.CONFIG_ROLLS_PAGE
-- Constants used too define the index into each table element for the loot
-- history.
ksk.HIST_WHEN = 1
ksk.HIST_WHAT = 2
ksk.HIST_WHO = 3
ksk.HIST_HOW = 4
ksk.HIST_POS = 5
-- Table of users currently in the group. This is indexed by KSK uid and
-- contains the full player name. This in turn can be used to access
-- KRP.players, also indexed by the full name, which contains the detailed
-- info about the raid / party member.
ksk.users = nil
-- Table of disenchanters currently available.
ksk.denchers = nil
-- Handle to the return value from database initialisation. This is set early
-- on in the initialisation process. No code other than that initialisation
-- code should ever touch this.
ksk.db = nil
-- The faction and realm database. This is the root of all stored configuration
-- variables and is set during initialisation. This is a convenience alias for
-- ksk.db.factionrealm.
ksk.frdb = nil
-- Convenience alias for ksk.db.factionrealm.configs
ksk.configs = nil
-- The ID of the currently selected configuration or nil if none (rare).
ksk.currentid = nil
-- The config database for the currently selected configuration or nil if no
-- config is currently active. This is a convenience alias for
-- ksk.db.factionreal.configs[ksk.currentid].
ksk.cfg = nil
-- The number of raiders currently in the raid group that are missing from the
-- users list, and the actual list of such missing players. Each entry in the
-- missing table is itself a table with the members "name" and "class", where
-- "name" is the full player-realm name of the player and class is the KKore
-- class number (for example K.CLASS_DRUID) of the missing player. These are
-- set to 0 and nil respectively when not in a raid.
ksk.nmissing = 0
ksk.missing = {}
-- Cached session data. This is a table, with one entry per defined config in
-- the config file, and stores convenience data frequently accessed from each
-- config. Typically these are computed values and therefore not stored in the
-- actual database that is saved each time the user logs out. The table is
-- indexed by config id.
ksk.csdata = {}
-- Convenience alias for ksk.csdata[ksk.currentid]. Can never be nil once
-- initialisation has completed.
ksk.csd = nil
-- The sorted list of lists. This is almost never nil, even if the config has
-- no defined lists (it will just be an empty table). When not empty it
-- contains the sorted list of lists for the current config. It is refreshed
-- when the lists UI is refreshed by ksk.RefreshListsUI().
ksk.sortedlists = nil
-- Set to true if the main KSK window was automatically opened.
ksk.autoshown = nil
-- The default values for a new configuration.
ksk.defaults = {
auto_bid = true,
silent_bid = false,
tooltips = true,
announce_where = 0,
def_list = "0",
def_rank = 0,
auto_loot = true,
boe_to_ml = true, -- Assign BoE items to Master-Looter
disenchant = true, -- Assign to disenchanter
use_decay = false,
chat_filter = true, -- Enable chat message filter
history = true, -- Record loot history
roll_timeout = 10,
roll_extend = 5,
try_roll = false,
bid_threshold = 0,
disenchant_below = false,
offspec_rolls = true,
suicide_rolls = false,
ann_bidchanges = true,
ann_winners_raid = true,
ann_winners_guild = true,
ann_bid_progress = true,
ann_bid_usage = true,
ann_roll_usage = true,
ann_countdown = true,
ann_roll_ties = true,
ann_cancel = true,
ann_no_bids = true,
ann_missing = true,
hide_absent = false,
use_ranks = false,
rank_prio = {},
denchers = {},
}
-- The main UI window handle, which is a KUI frame.
ksk.mainwin = nil
-- The global popup window. There can only be one popup window active at a
-- time and if that window is currently up, this will be the frame for it.
-- Otherwise it is nil.
ksk.popupwindow = nil
-- The global quickframe cache. Each UI panel should maintain its own
-- quickframe cache. This is only for the very top level UI frames.
ksk.qf = {}
-------------------------------------------------------------------------------
local admin_hooks_registered = nil
local ml_hooks_registered = nil
local chat_filters_installed = nil
local sentoloot = nil
local ucolor = K.ucolor
local ecolor = K.ecolor
local icolor = K.icolor
local function debug(lvl,...)
K.debug(L["MODNAME"], lvl, ...)
end
local function err(msg, ...)
local str = L["MODTITLE"] .. " " .. L["error: "] .. strfmt(msg, ...)
printf(ecolor, "%s", str)
end
local function info(msg, ...)
local str = L["MODTITLE"] .. ": " .. strfmt(msg, ...)
printf(icolor, "%s", str)
end
ksk.debug = debug
ksk.err = err
ksk.info = info
ksk.white = K.white
ksk.red = K.red
ksk.green = K.green
ksk.yellow = K.yellow
ksk.class = KRP.ClassString
ksk.shortclass = KRP.ShortClassString
ksk.aclass = KRP.AlwaysClassString
ksk.shortaclass = KRP.ShortAlwaysClassString
local white = K.white
local class = KRP.ClassString
-- cfg is known to be valid before this is called
local function get_my_ids(cfg)
local uid = ksk.FindUser(K.player.name, cfg)
if (not uid) then
return nil, nil
end
local ia, main = ksk.UserIsAlt(uid, nil, cfg)
if (ia) then
return uid, main
else
return uid, uid
end
end
function ksk.UpdateUserSecurity(conf)
local conf = conf or ksk.currentid
if (not conf or not ksk.frdb or not ksk.frdb.configs
or not ksk.frdb.configs[conf] or not ksk.csdata
or not ksk.csdata[conf]) then
return false
end
local csd = ksk.csdata[conf]
local cfg = ksk.frdb.configs[conf]
csd.myuid, csd.mymainid = get_my_ids(conf)
csd.is_admin = nil
if (csd.myuid) then
if (cfg.owner == csd.myuid or cfg.owner == csd.mymainid) then
csd.is_admin = 2
elseif (ksk.UserIsCoadmin(csd.myuid, conf)) then
csd.is_admin = 1
elseif (ksk.UserIsCoadmin(csd.mymainid, conf)) then
csd.is_admin = 1
end
end
if (ksk.initialised and conf == ksk.currentid) then
ksk.ConfigAdmin(csd.is_admin ~= nil and true or false)
end
return true
end
function ksk.AmIML()
if (KRP.is_ml and ksk.csd.is_admin) then
return true
end
return false
end
function ksk.IsAdmin(uid, cfg)
local cfg = cfg or ksk.currentid
if (not cfg or not ksk.configs or not ksk.configs[cfg]) then
return nil, nil
end
local uid = uid or ksk.FindUser(K.player.name, cfg)
if (not uid) then
return nil, nil
end
if (ksk.configs[cfg].owner == uid) then
return 2, uid
end
if (ksk.UserIsCoadmin(uid, cfg)) then
return 1, uid
end
local isalt, main = ksk.UserIsAlt(uid, nil, cfg)
if (isalt) then
if (ksk.configs[cfg].owner == main) then
return 2, main
end
if (ksk.UserIsCoadmin(main, cfg)) then
return 1, main
end
end
return nil, nil
end
local ts_datebase = nil
local ts_evtcount = 0
function ksk.GetEventID(cfg)
local cfg = cfg or ksk.currentid
if (not ts_datebase or ts_evtcount >= 9999) then
local now = K.time()
ts_datebase = tonumber(date("%y%m%d%H%M", now) .. "0000")
ts_evtcount = 0
while ((ts_datebase + ts_evtcount) < (ksk.configs[cfg].lastevent or 0)) do
ts_evtcount = ts_evtcount + 100
end
end
ts_evtcount = ts_evtcount + 1
ksk.configs[cfg].lastevent = ts_datebase + ts_evtcount
return ksk.configs[cfg].lastevent
end
local function check_config()
if (ksk.frdb.tempcfg) then
info(strfmt(L["no active configuration. Either create one with %s or wait for a guild admin to broadcast the guild list."], white(strfmt("/%s %s", L["CMDNAME"], L["CMD_CREATECONFIG"]))))
return true
end
return false
end
local function ksk_version()
printf (ucolor, L["%s<%s>%s %s (version %d) - %s"],
"|cffff2222", K.KAHLUA, "|r", L["MODTITLE"], MINOR,
L["Suicide Kings loot distribution system."])
end
local function ksk_versioncheck()
ksk:VersionCheck()
end
local function ksk_usage()
ksk_version()
printf(ucolor, L["Usage: "] .. white(strfmt(L["/%s [command [arg [arg...]]]"], L["CMDNAME"])))
printf(ucolor, white(strfmt("/%s [%s]", L["CMDNAME"], L["CMD_LISTS"])))
printf(ucolor, L[" Open the list management window."])
printf(ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_USERS"])))
printf(ucolor, L[" Opens the user list management window."])
printf(ucolor, white(strfmt("/%s %s [%s | %s]", L["CMDNAME"], L["CMD_LOOT"], L["SUBCMD_ASSIGN"], L["SUBCMD_ITEMS"])))
printf(ucolor, L[" Opens the loot management window."])
printf(ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_SYNC"])))
printf(ucolor, L[" Opens the sync manager window."])
printf(ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_SUSPEND"])))
printf(ucolor, strfmt(L[" Suspend %s (no auto-open on loot, no missing member warnings etc)."], L["MODTITLE"]))
printf(ucolor, white(strfmt("/%s %s", L["CMDNAME"], L["CMD_RESUME"])))
printf(ucolor, strfmt(L[" Resume normal %s operations."], L["MODTITLE"]))
printf(ucolor, white(strfmt("/%s %s [%s | %s]", L["CMDNAME"], L["CMD_CONFIG"], L["SUBCMD_LOOT"], L["SUBCMD_ADMIN"])))
printf(ucolor, L[" Set up various options and manage configurations."])
printf(ucolor, white(strfmt(L["/%s %s name"], L["CMDNAME"], L["CMD_SELECTCONFIG"])))
printf(ucolor, L[" Selects the specified configuration as the current one."])
printf(ucolor, white(strfmt(L["/%s %s name"], L["CMDNAME"], L["CMD_CREATECONFIG"])))
printf(ucolor, L[" Create the specified configuration."])
printf(ucolor, white(strfmt(L["/%s %s name"], L["CMDNAME"], L["CMD_DELETECONFIG"])))
printf(ucolor, L[" Delete the specified configuration."])
printf(ucolor, white(strfmt(L["/%s %s oldname newname"], L["CMDNAME"], L["CMD_COPYCONFIG"])))
printf(ucolor, L[" Copies the specified configuration to a new one, with options."])
printf(ucolor, white(strfmt(L["/%s %s oldname newname"], L["CMDNAME"], L["CMD_RENAMECONFIG"])))
printf(ucolor, L[" Renames the specified configuration."])
-- User list management commands
printf(ucolor, white(strfmt(L["/%s %s name class"], L["CMDNAME"], L["CMD_CREATEUSER"])))
printf(ucolor,L[" Adds a new user to the users list."])
printf(ucolor, white(strfmt(L["/%s %s name"], L["CMDNAME"], L["CMD_DELETEUSER"])))
printf(ucolor,L[" Removes a user from the users list."])
printf(ucolor, white(strfmt(L["/%s %s oldname newname"], L["CMDNAME"], L["CMD_RENAMEUSER"])))
printf(ucolor,L[" Renames a user after a paid name change."])
printf(ucolor,white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDITEM"])))
printf(ucolor,L[" Adds a new item to the item list."])
printf(ucolor,white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDLOOT"])))
printf(ucolor,L[" Adds a new item to the loot list."])
end
local function common_verify_input(input, cmd, exist, bypass, tbl, nexmsg, exmsg)
if (not bypass and ksk.CheckPerm()) then
return true
end
local found = false
local nname, pos
local retid = 0
local kcmd = L["CMDNAME"]
if (not input or input == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s name"], kcmd, cmd)))
return true
end
nname, pos = K.GetArgs(input)
if (not nname or nname == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s name"], kcmd, cmd)))
return true
end
if (pos ~= 1e9) then
err(L["Usage: "] .. white(strfmt(L["/%s %s name"], kcmd, cmd)))
return true
end
if (type(tbl) == "string" and tbl == "special") then
return false, nname
end
local low = strlower(nname)
if (tbl) then
for k,v in pairs(tbl) do
if (strlower(v.name) == low) then
found = true
retid = k
end
end
end
if (exist) then
if (not found) then
err(nexmsg, white(nname))
return true
end
else
if (found) then
err(exmsg, white(nname))
return true
end
end
return false, nname, found, retid
end
local function common_verify_input2(input, cmd, exist, bypass, tbl, nexmsg, exmsg)
if (not bypass and ksk.CheckPerm()) then
return true
end
if (not tbl) then
return true
end
local oldname, newname, pos
local found = 0
local retid = 0
local kcmd = L["CMDNAME"]
if (not input or input == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s oldname newname"], kcmd, cmd)))
return true
end
oldname, newname, pos = K.GetArgs(input, 2)
if (not oldname or oldname == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s oldname newname"], kcmd, cmd)))
return true
end
if (not newname or newname == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s oldname newname"], kcmd, cmd)))
return true
end
if (pos ~= 1e9) then
err(L["Usage: "] .. white(strfmt(L["/%s %s oldname newname"], kcmd, cmd)))
return true
end
if (oldname == newname) then
return true
end
if (type(tbl) == "string" and tbl == "special") then
return false, oldname, newname
end
local lnew = strlower(newname)
local lold = strlower(oldname)
if (tbl) then
for k,v in pairs(tbl) do
if (strlower(v.name) == lnew) then
found = k
end
if (strlower(v.name) == lold) then
retid = k
end
end
end
if (retid == 0) then
err(nexmsg, white(oldname))
return true
end
if (not exist) then
if (found ~= 0) then
err(exmsg, white(newname))
return true
end
end
return false, oldname, newname, retid, found
end
local function ksk_createconfig(input)
local cmd = L["CMD_CREATECONFIG"]
local rv, nname, _, cfgid = common_verify_input(input, cmd, false, true,
ksk.configs, nil,
L["configuration %q already exists. Try again."])
if (rv) then
return true
end
return ksk.CreateNewConfig(nname, false)
end
local function ksk_selectconfig(input)
local cmd = L["CMD_SELECTCONFIG"]
local rv, nname, _, cfgid = common_verify_input(input, cmd, true, false,
ksk.configs,
L["configuration %q does not exist. Try again."], nil)
if (rv) then
return true
end
ksk.SetDefaultConfig(cfgid)
return false
end
local function ksk_deleteconfig(input)
local cmd = L["CMD_DELETECONFIG"]
local rv, nname, _, cfgid = common_verify_input(input, cmd, true, true,
ksk.configs,
L["configuration %q does not exist. Try again."], nil)
if (rv) then
return true
end
ksk.DeleteConfig(cfgid)
return false
end
local function ksk_renameconfig(input)
local cmd = L["CMD_RENAMECONFIG"]
local rv, _, newname, cfgid, _ = common_verify_input2(input, cmd, true,
false, ksk.configs,
L["configuration %q does not exist. Try again."],
L["configuration %q already exists. Try again."])
if (rv) then
return true
end
return ksk.RenameConfig(cfgid, newname)
end
local function ksk_copyconfig(input)
local cmd = L["CMD_COPYCONFIG"]
local rv, _, newname, cfgid, newid = common_verify_input2(input, cmd, true,
false, ksk.configs,
L["configuration %q does not exist. Try again."],
L["configuration %q already exists. Try again."])
if (rv) then
return true
end
return ksk.CopyConfigSpace(cfgid, newname, newid)
end
local function ksk_createuser(input)
if (ksk.CheckPerm()) then
return true
end
local kcmd = L["CMDNAME"]
local cmd = L["CMD_CREATEUSER"]
local nname, nclass, pos
local classid = nil
if (not input or input == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s name class"], kcmd, cmd)))
return true
end
nname, nclass, pos = K.GetArgs(input, 2)
if (not nname or nname == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s name class"], kcmd, cmd)))
return true
end
if (not nclass or nclass == "") then
err(L["Usage: "] .. white(strfmt(L["/%s %s name class"], kcmd, cmd)))
return true
end
if (pos ~= 1e9) then
err(L["Usage: "] .. white(strfmt(L["/%s %s name class"], kcmd, cmd)))
return true
end
local lclass = strlower(nclass)
for k,v in pairs(K.IndexClass) do
if (v.l == lclass) then
classid = k
end
end
if (not classid) then
err(L["invalid class %q specified. Valid classes are:"], white(lclass))
for k,v in pairs(K.IndexClass) do
if (v.l) then
printf(" |cffffffff%s|r", v.l)
end
end
return true
end
if (not ksk.CreateNewUser(nname, classid)) then
return true
end
return false
end
local function ksk_deleteuser(input)
local cmd = L["CMD_DELETEUSER"]
local rv, nname, _, userid = common_verify_input(input, cmd, true, false,
ksk.cfg.users, L["user %q does not exist. Try again."], nil)
if (rv) then
return true
end
if (not ksk.DeleteUserCmd(userid)) then
return true
end
return false
end
local function ksk_renameuser(input)
if (not ksk.cfg.users) then
return false
end
local cmd = L["CMD_RENAMEUSER"]
local rv, _, newname, userid, found = common_verify_input2(input, cmd, true,
false, ksk.cfg.users,
L["user %q does not exist. Try again."],
L["user %q already exists. Try again."])
if (rv) then
return true
end
return ksk.RenameUser(userid, newname)
end
local function ksk_config(input)
if (ksk.CheckPerm()) then
return true
end
local tab = ksk.CONFIG_TAB
local subpanel = ksk.CONFIG_LOOT_PAGE
if (input == L["SUBCMD_LOOT"] or input == "" or not input) then
subpanel = ksk.CONFIG_LOOT_PAGE
elseif (input == L["SUBCMD_ROLLS"]) then
subpanel = ksk.CONFIG_ROLLS_PAGE
elseif (input == L["SUBCMD_ADMIN"]) then
subpanel = ksk.CONFIG_ADMIN_PAGE
elseif (input == L["CMD_LISTS"]) then
tab = ksk.LISTS_TAB
subpanel = ksk.LISTS_CONFIG_PAGE
else
printf(ucolor,L["Usage: "] .. white(strfmt("/%s %s [%s | %s | %s | %s]", L["CMDNAME"], L["CMD_CONFIG"], L["SUBCMD_LOOT"], L["SUBCMD_ROLLS"], L["SUBCMD_ADMIN"], L["CMD_LISTS"])))
printf(ucolor,L[" %s - set up loot related options"], white(L["SUBCMD_LOOT"]))
printf(ucolor,L[" %s - set up roll related options"], white(L["SUBCMD_ROLL"]))
printf(ucolor,L[" %s - set up config spaces and permissions options"], white(L["SUBCMD_ADMIN"]))
printf(ucolor,L[" %s - configure lists and list options"], white(L["CMD_LISTS"]))
return
end
ksk.mainwin:Show()
ksk.mainwin:SetTab(tab, subpanel)
end
local function ksk_main()
ksk.mainwin:Show()
if (ksk.bossloot) then
ksk.mainwin:SetTab(ksk.LOOT_TAB, ksk.LOOT_ASSIGN_PAGE)
else
ksk.mainwin:SetTab(ksk.LISTS_TAB, ksk.LISTS_MEMBERS_PAGE)
end
end
local function ksk_users()
if (ksk.CheckPerm()) then
return true
end
ksk.mainwin:Show()
ksk.mainwin:SetTab(ksk.USERS_TAB, nil)
end
local function ksk_importgusers()
if (ksk.CheckPerm()) then
return true
end
ksk.ImportGuildUsers(ksk.mainwin:IsShown())
end
local function ksk_show()
ksk.mainwin:Show()
end
local function ksk_createlist(input)
local cmd = L["CMD_CREATELIST"]
local rv, nname, _, listid = common_verify_input(input, cmd, false, false,
ksk.cfg.lists, nil,
L["roll list %q already exists. Try again."])
if (rv) then
return true
end
return ksk.CreateNewList(nname)
end
local function ksk_selectlist(input)
local cmd = L["CMD_SELECTLIST"]
local rv, nname, _, listid = common_verify_input(input, cmd, true, false,
ksk.cfg.lists,
L["roll list %q does not exist. Try again."], nil)
if (rv) then
return true
end
ksk.SelectList(listid)
return false
end
local function ksk_deletelist(input)
local cmd = L["CMD_DELETELIST"]
local rv, nname, _, listid = common_verify_input(input, cmd, true, false,
ksk.cfg.lists,
L["roll list %q does not exist. Try again."], nil)
if (rv) then
return true
end
ksk.DeleteListCmd(listid)
return false
end
local function ksk_renamelist(input)
local cmd = L["CMD_RENAMELIST"]
local rv, _, newname, listid, _ = common_verify_input2(input, cmd, true,
false, ksk.cfg.lists,
L["roll list %q does not exist. Try again."],
L["roll list %q already exists. Try again."])
if (rv) then
return true
end
return ksk.RenameList(listid, newname)
end
local function ksk_copylist(input)
local cmd = L["CMD_COPYLIST"]
local rv, _, newname, listid, _ = common_verify_input2(input, cmd, true,
false, ksk.cfg.lists,
L["roll list %q does not exist. Try again."],
L["roll list %q already exists. Try again."])
if (rv) then
return true
end
return ksk.CopyList(listid, newname, ksk.currentid)
end
local function ksk_loot(input)
local subpanel = ksk.LOOT_ASSIGN_PAGE
if (input == L["SUBCMD_ASSIGN"] or input == "" or not input) then
subpanel = ksk.LOOT_ASSIGN_PAGE
elseif (input == L["SUBCMD_ITEMS"]) then
if (ksk.CheckPerm()) then
return true
end
subpanel = ksk.LOOT_ITEMS_PAGE
elseif (input == L["SUBCMD_HISTORY"]) then
if (ksk.CheckPerm()) then
return true
end
subpanel = ksk.LOOT_HISTORY_PAGE
else
printf(ucolor,L["Usage: "] .. white(strfmt("/%s %s [%s | %s | %s]", L["CMDNAME"], L["CMD_LOOT"], L["SUBCMD_ASSIGN"], L["SUBCMD_ITEMS"], L["SUBCMD_HISTORY"])))
printf(ucolor,L[" %s - open the loot assignment window"], white(L["SUBCMD_ASSIGN"]))
printf(ucolor,L[" %s - open the item editor window"], white(L["SUBCMD_ITEMS"]))
printf(ucolor,L[" %s - open the item history window"], white(L["SUBCMD_HISTORY"]))
return
end
ksk.mainwin:Show()
ksk.mainwin:SetTab(ksk.LOOT_TAB, subpanel)
end
local function ksk_lists(input)
ksk.mainwin:Show()
ksk.mainwin:SetTab(ksk.LISTS_TAB, ksk.LISTS_MEMBERS_PAGE)
end
local function ksk_sync(input)
if (ksk.CheckPerm()) then
return true
end
ksk.mainwin:Show()
ksk.mainwin:SetTab(ksk.SYNC_TAB)
end
local function ksk_items(input)
if (ksk.CheckPerm()) then
return true
end
ksk.mainwin:Show()
ksk.mainwin:SetTab(ksk.LOOT_TAB, ksk.LOOT_ITEMS_PAGE)
end
local function ksk_history(input)
if (ksk.CheckPerm()) then
return true
end
ksk.mainwin:Show()
ksk.mainwin:SetTab(ksk.LOOT_TAB, ksk.LOOT_HISTORY_PAGE)
end
local function ksk_additem(input)
if (ksk.CheckPerm()) then
return true
end
if (not input or input == "" or input == L["CMD_HELP"]) then
err(L["Usage: "] .. white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDITEM"])))
return true
end
local itemid, pos = K.GetArgs(input)
if (itemid ~= "") then
-- Convert to numeric itemid if an item link was specified
local ii = tonumber(itemid)
if (ii == nil) then
itemid = match(itemid, "item:(%d+)")
end
end
if ((not itemid) or (itemid == "") or (pos ~= 1e9) or (tonumber(itemid) == nil)) then
err(L["Usage: "] .. white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDITEM"])))
return true
end
if (ksk.cfg.items[itemid]) then
err(L["item %s already exists."], ksk.cfg.items[itemid].ilink)
return true
end
local iname, ilink = GetItemInfo(tonumber(itemid))
if (iname == nil or iname == "") then
err(L["item %d is an invalid item."], itemid)
return true
end
ksk.AddItem(itemid, ilink)
end
local function ksk_addloot(input)
if (ksk.CheckPerm()) then
return true
end
if (not ksk.AmIML()) then
err(L["can only add items when in a raid and you are the master looter."])
return true
end
if (not input or input == "" or input == L["CMD_HELP"]) then
err(L["Usage: "] .. white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDLOOT"])))
return true
end
local itemid, pos = K.GetArgs(input)
if (itemid ~= "") then
-- Convert to numeric itemid if an item link was specified
local ii = tonumber(itemid)
if (ii == nil) then
itemid = match(itemid, "item:(%d+)")
end
end
if ((not itemid) or (itemid == "") or (pos ~= 1e9) or (tonumber(itemid) == nil)) then
err(L["Usage: "] .. white(strfmt(L["/%s %s [itemid | itemlink]"], L["CMDNAME"], L["CMD_ADDLOOT"])))
return true
end
local iname, ilink = GetItemInfo(tonumber(itemid))
if (iname == nil or iname == "") then
err(L["item %d is an invalid item."], itemid)
return true
end
ksk.AddLoot(ilink)
end
local function ksk_test(input)
end
local function ksk_debug(input)
input = input or "1"
if (input == "") then
input = "1"
end
local dl = tonumber(input)
if (dl == nil) then
dl = 0
end
K.debugging[L["MODNAME"]] = dl
end
local function ksk_status(input)
end
local function ksk_resetpos(input)
if (ksk.mainwin) then
ksk.mainwin:SetPoint("TOPLEFT", UIParent, "TOPLEFT", 100, -100)
end
end
local function ksk_suspend(input)
KK.SetSuspended(ksk.addon_handle, true)
end
local function ksk_resume(input)
KK.SetSuspended(ksk.addon_handle, false)
end
local function ksk_refresh(input)
KRP.UpdateGroup(true, true, false)
end
K.debugging[L["MODNAME"]] = 9 -- @debug-delete@
local kcmdtab = {}
kcmdtab["debug"] = ksk_debug
kcmdtab["status"] = ksk_status
kcmdtab["refresh"] = ksk_refresh
kcmdtab[L["CMD_RESETPOS"]] = ksk_resetpos
kcmdtab[L["CMD_VERSION"]] = ksk_version
kcmdtab[L["CMD_VERSIONCHECK"]] = ksk_versioncheck
kcmdtab["vc"] = ksk_versioncheck
kcmdtab[L["CMD_SHOW"]] = ksk_show
kcmdtab[L["CMD_LISTS"]] = ksk_lists
kcmdtab[L["CMD_USERS"]] = ksk_users
kcmdtab[L["CMD_LOOT"]] = ksk_loot
kcmdtab[L["CMD_CONFIG"]] = ksk_config
kcmdtab[L["CMD_SYNC"]] = ksk_sync
kcmdtab[L["CMD_SUSPEND"]] = ksk_suspend
kcmdtab[L["CMD_RESUME"]] = ksk_resume
kcmdtab[L["SUBCMD_ITEMS"]] = ksk_items
kcmdtab[L["SUBCMD_HISTORY"]] = ksk_history
kcmdtab[L["CMD_ADDITEM"]] = ksk_additem
kcmdtab[L["CMD_ADDLOOT"]] = ksk_addloot
kcmdtab[L["CMD_SELECTCONFIG"]] = ksk_selectconfig
kcmdtab[L["CMD_CREATECONFIG"]] = ksk_createconfig
kcmdtab[L["CMD_DELETECONFIG"]] = ksk_deleteconfig
kcmdtab[L["CMD_RENAMECONFIG"]] = ksk_renameconfig
kcmdtab[L["CMD_COPYCONFIG"]] = ksk_copyconfig
kcmdtab[L["CMD_CREATEUSER"]] = ksk_createuser
kcmdtab[L["CMD_DELETEUSER"]] = ksk_deleteuser
kcmdtab[L["CMD_RENAMEUSER"]] = ksk_renameuser
kcmdtab[L["CMD_IMPORTGUILDUSERS"]] = ksk_importgusers
kcmdtab["igu"] = ksk_importgusers
kcmdtab[L["CMD_SELECTLIST"]] = ksk_selectlist
kcmdtab[L["CMD_CREATELIST"]] = ksk_createlist
kcmdtab[L["CMD_DELETELIST"]] = ksk_deletelist
kcmdtab[L["CMD_RENAMELIST"]] = ksk_renamelist
kcmdtab[L["CMD_COPYLIST"]] = ksk_copylist
kcmdtab["test"] = ksk_test
function ksk:OnSlashCommand(input)
if (not input or input == "") then
if (check_config()) then
return true
end
ksk_main()
return
end
local cmd, pos = K.GetArgs(input)
if (not cmd or cmd == "") then
if (check_config()) then
return true
end
ksk_main()
return
end
strlower(cmd)
if (cmd == L["CMD_HELP"] or cmd == "?") then
ksk_usage()
return
end
if (not kcmdtab[cmd]) then
err(L["%q is not a valid command. Type %s for help."], white(cmd), white(strfmt("/%s %s", L["CMDNAME"], L["SUBCMD_HELP"])))
return
end
local arg
if (pos == 1e9) then
arg = ""
else
arg = strsub(input, pos)
end
if (cmd ~= L["CMD_CREATECONFIG"] and cmd ~= L["CMD_VERSION"] and cmd ~= L["CMD_VERSIONCHECK"] and cmd ~= "vc" and cmd ~= "debug" and cmd ~= "status" and check_config()) then
return true
end
kcmdtab[cmd](arg)
end
--
-- Function: ksk.RefreshCSData()
-- Purpose : Re-calculate session temporary config values based on the
-- current stored values in each config.
-- Returns : Nothing.
--
function ksk.RefreshCSData()
if (not ksk.configs) then
return
end
for k,v in pairs(ksk.configs) do
if (not ksk.csdata[k]) then
ksk.csdata[k] = {}
ksk.csdata[k].reserved = {}
end
ksk.UpdateUserSecurity(k)
end
for k,v in pairs(ksk.csdata) do
if (not ksk.configs[k]) then
ksk.csdata[k] = nil
end
end
if (ksk.currentid) then
ksk.csd = ksk.csdata[ksk.currentid]
ksk.ConfigAdmin(ksk.csd.is_admin ~= nil and true or false)
end
end
function ksk.CheckPerm(cfg)
local cfg = cfg or ksk.currentid
if (not cfg or not ksk.configs or not ksk.configs[cfg]
or not ksk.csdata[cfg]) then
return true
end
if (not ksk.csdata[cfg].is_admin) then
err(L["you do not have permission to do that in this configuration."])
return true
end
return false
end
function ksk.CanChangeConfigType()
if (K.player.is_guilded == false) then
return false
else
if (K.player.is_gm == true) then
return true
end
if (K.UserIsRanked(K.player.name)) then
return true
end
end
return false
end
local function update_bcast_button()
ksk.UpdateUserSecurity()
if (ksk.csd.is_admin) then
if (ksk.cfg.cfgtype == KK.CFGTYPE_GUILD) then
ksk.qf.bcastbutton:SetEnabled(true)
return
elseif (ksk.AmIML() or KRP.is_aorl or KRP.is_pl or
ksk.UserIsRanked(ksk.currentid, K.player.name)) then
ksk.qf.bcastbutton:SetEnabled(true)
return
end
end
ksk.qf.bcastbutton:SetEnabled(false)
end
function ksk.MakeAliases()
ksk.frdb = ksk.db.factionrealm
ksk.configs = ksk.db.factionrealm.configs
if (ksk.currentid) then
ksk.cfg = ksk.db.factionrealm.configs[ksk.currentid]
else
ksk.cfg = nil
end
end
function ksk.FullRefreshUI(reset)
ksk.RefreshConfigUI(reset)
ksk.RefreshListsUI(reset)
ksk.RefreshLootUI(reset)
ksk.RefreshUsersUI(reset)
ksk.RefreshSyncUI(reset)
end
function ksk.FullRefresh(reset)
K.UpdatePlayerAndGuild(true)
ksk.UpdateUserSecurity()
ksk.RefreshCSData()
ksk.FullRefreshUI(reset)
KRP.UpdateGroup(true, true, false)
-- JKJ FIXME: this logic should move into the refresh functions above.
local en = true
local kct = ksk.mainwin.currenttab
local kmt = ksk.mainwin.tabs
if (not ksk.csd.is_admin) then
en = false
if ((kct >= ksk.NON_ADMIN_THRESHOLD) or
(kct == ksk.LISTS_TAB and kmt[ksk.LISTS_TAB].currenttab > ksk.LISTS_MEMBERS_PAGE) or
(kct == ksk.LOOT_TAB and kmt[ksk.LOOT_TAB].currenttab > ksk.LOOT_ASSIGN_PAGE))
then
ksk.mainwin:SetTab(ksk.LOOT_TAB, ksk.LOOT_ASSIGN_PAGE)
ksk.mainwin:SetTab(ksk.LISTS_TAB, ksk.LISTS_MEMBERS_PAGE)
end
end
ksk.qf.userstab:SetShown(en)
ksk.qf.synctab:SetShown(en)
ksk.qf.configtab:SetShown(en)
ksk.qf.iedittab:SetShown(en)
ksk.qf.historytab:SetShown(en)
ksk.qf.listcfgtab:SetShown(en)
if (ksk.cfg.cfgtype == KK.CFGTYPE_PUG) then
en = (KRP.is_aorl or KRP.is_pl) and ksk.csd.is_admin
end
ksk.qf.bcastbutton:SetEnabled(en)
-- Only the config owner can see most of the config tab
en = false
if (ksk.csd.is_admin ~= 2) then
if (kct == ksk.CONFIG_TAB and kmt[ksk.CONFIG_TAB].currenttab > ksk.NON_ADMIN_CONFIG_THRESHOLD) then
ksk.mainwin:SetTab(ksk.CONFIG_TAB, ksk.CONFIG_LOOT_PAGE)
end
else
en = true
end
ksk.qf.cfgadmintab:SetShown(en)
if (reset) then
ksk.SelectListByIdx(1)
end
end
local function player_info_updated(evt, ...)
if (ksk.initialised) then
ksk.UpdateUserSecurity()
end
RequestRaidInfo()
ksk.FullRefreshUI(false)
end
local function guild_info_updated(evt, ...)
local iv = { text = L["None"], value = 0 }
local rvals = {}
tinsert (rvals, iv)
if (K.player.is_guilded) then
for i = 1, K.guild.numranks do
iv = {text = K.guild.ranks[i], value = i }
tinsert (rvals, iv)
end
end
oldr = ksk.qf.lootrank:GetValue() or 0
ksk.qf.lootrank:UpdateItems (rvals)
ksk.qf.lootrank:SetValue (oldr)
oldr = ksk.qf.defrankdd:GetValue() or 0
ksk.qf.defrankdd:UpdateItems (rvals)
ksk.qf.defrankdd:SetValue (oldr)
oldr = ksk.qf.gdefrankdd:GetValue() or 0
ksk.qf.gdefrankdd:UpdateItems (rvals)
ksk.qf.gdefrankdd:SetValue (oldr)
oldr = ksk.qf.itemrankdd:GetValue() or 0
ksk.qf.itemrankdd:UpdateItems (rvals)
ksk.qf.itemrankdd:SetValue (oldr)
ksk.qf.cfgtype:SetEnabled(ksk.UserIsRanked(ksk.currentid, K.player.name))
end
function ksk.RefreshRaid()
KRP.UpdateGroup(true, true, false)
end
function ksk.AddItemToBossLoot(ilink, quant, lootslot)
ksk.bossloot = ksk.bossloot or {}
local lootslot = lootslot or 0
local itemid = match(ilink, "item:(%d+)")
local _, _, _, _, _, _, _, _, slot, _, _, icls, isubcls = GetItemInfo(ilink)
local filt, boe = K.GetItemClassFilter(ilink)
local ti = { itemid = itemid, ilink = ilink, slot = lootslot, quant = quant, boe = boe }
if (icls == K.classfilters.weapon) then
if (filt == K.classfilters.allclasses) then
ti.strict = K.classfilters.weapons[isubcls]
ti.relaxed = ti.strict
else
ti.strict = filt
ti.relaxed = filt
end
elseif (icls == K.classfilters.armor) then
if (filt == K.classfilters.allclasses) then
ti.strict = K.classfilters.strict[isubcls]
ti.relaxed = K.classfilters.relaxed[isubcls]
if (slot == "INVTYPE_CLOAK") then
--
-- Most cloaks are reported as type cloth, so we dont want to
-- filter out other classes that can legitimately use the cloak.
-- So we set cloaks to relaxed, even if we have strict class
-- armour filtering on.
--
ti.strict = ti.relaxed
end
else
ti.strict = filt
ti.relaxed = filt
end
else
ti.strict = filt
ti.relaxed = filt
end
tinsert(ksk.bossloot, ti)
end
local function extract_cmd(msg)
local lm = strlower(msg)
lm = lm:gsub("^%s*", "")
lm = lm:gsub("%s*$", "")
if ((lm == L["WHISPERCMD_BID"]) or
(lm == L["WHISPERCMD_RETRACT"]) or
(lm == L["WHISPERCMD_SUICIDE"]) or
(lm == L["WHISPERCMD_SUICIDE_ALTERNATE"]) or
(lm == L["WHISPERCMD_STANDBY"]) or
(lm == L["WHISPERCMD_HELP"]) or
(lm == "bid") or (lm == "retract") or (lm == "suicide") or
(lm == "position") or (lm == "standby") or (lm == "help")) then
return lm
end
end
local function whisper_filter(self, evt, msg, ...)
if (extract_cmd(msg)) then
return true
end
end
local titlematch = "^" .. L["MODTITLE"] .. ": "
local abbrevmatch = "^" .. L["MODABBREV"] .. ": "
local function reply_filter(self, evt, msg, snd, ...)
local sender = K.CanonicalName(snd, nil)
if (strmatch(msg, titlematch)) then
if (evt == "CHAT_MSG_WHISPER_INFORM") then
return true
elseif (sender == K.player.name) then
return true
end
end
if (strmatch(msg, abbrevmatch)) then
if (evt == "CHAT_MSG_WHISPER_INFORM") then
return true
elseif (sender == K.player.name) then
return true
end
end
end
local function get_user_pos(uid, lp)
local cuid = uid
local rpos = 0
local ulist = lp.users
if (lp.tethered) then
if (ksk.cfg.users[uid] and ksk.cfg.users[uid].main) then
cuid = ksk.cfg.users[uid].main
end
end
for k,v in ipairs(ulist) do
if (ksk.users) then
local ir = false
if (ksk.users[v]) then
ir = true
else
if (lp.tethered and ksk.cfg.users[v].alts) then
for kk,vv in pairs(ksk.cfg.users[v].alts) do
if (ksk.users[vv]) then
ir = true
break
end
end
end
end
if (ir) then
rpos = rpos + 1
end
end
if (v == cuid) then
return k, rpos
end
end
return 0, 0
end
local function chat_msg_whisper(evt, msg, snd, ...)
local sender = K.CanonicalName(snd, nil)
local cmd = extract_cmd(msg)
if (cmd) then
if (cmd == "bid" or cmd == L["WHISPERCMD_BID"]) then
return ksk.NewBidder(sender)
elseif (cmd == "retract" or cmd == L["WHISPERCMD_RETRACT"]) then
return ksk.RetractBidder(sender)
elseif (cmd == "suicide" or cmd == L["WHISPERCMD_SUICIDE"] or cmd == L["WHISPERCMD_SUICIDE_ALTERNATE"]) then
local uid = ksk.FindUser(sender)
if (not uid) then
ksk:SendWhisper(strfmt(L["%s: you are not on any roll lists (yet)."], L["MODABBREV"]), sender)
return
end
local sentheader = false
local ndone = 0
for k,v in pairs(ksk.sortedlists) do
local lp = ksk.cfg.lists[v.id]
local apos, rpos = get_user_pos(uid, lp)
if (apos) then
ndone = ndone + 1
if (not sentheader) then
ksk:SendWhisper(strfmt(L["LISTPOSMSG"], L["MODABBREV"], ksk.cfg.name, L["MODTITLE"]), sender)
sentheader = true
end
if (ksk.users) then
ksk:SendWhisper(strfmt(L["%s: %s - #%d (#%d in raid)"], L["MODABBREV"], lp.name, apos, rpos), sender)
else
ksk:SendWhisper(strfmt("%s: %s - #%d", L["MODABBREV"], lp.name, apos), sender)
end
end
end
if (ndone > 0) then
ksk:SendWhisper(strfmt(L["%s: (End of list)"], L["MODABBREV"]), sender)
else
ksk:SendWhisper(strfmt(L["%s: you are not on any roll lists (yet)."], L["MODABBREV"]), sender)
end
elseif (cmd == "help" or cmd == L["WHISPERCMD_HELP"]) then
ksk:SendWhisper(strfmt(L["HELPMSG1"], L["MODABBREV"], L["MODTITLE"], L["MODABBREV"]), sender)
ksk:SendWhisper(strfmt(L["HELPMSG2"], L["MODABBREV"], L["WHISPERCMD_BID"]), sender)
ksk:SendWhisper(strfmt(L["HELPMSG3"], L["MODABBREV"], L["WHISPERCMD_RETRACT"]), sender)
ksk:SendWhisper(strfmt(L["HELPMSG4"], L["MODABBREV"], L["WHISPERCMD_SUICIDE"]), sender)
ksk:SendWhisper(strfmt(L["HELPMSG5"], L["MODABBREV"], L["WHISPERCMD_STANDBY"]), sender)
end
end
end
--
-- Fired whenever our admin status for the currently selected config changes,
-- or when we refresh due to a config change or other events. This registers
-- messages that only an admin cares about.
--
function ksk.ConfigAdmin(onoff)
if (onoff and admin_hooks_registered ~= true) then
admin_hooks_registered = true
ksk:RegisterEvent("CHAT_MSG_WHISPER", chat_msg_whisper)
elseif (not onoff and admin_hooks_registered == true) then
admin_hooks_registered = false
ksk:UnregisterEvent("CHAT_MSG_WHISPER")
end
local ef = nil
if (onoff) then
if (chat_filters_installed ~= true) then
if (ksk.cfg.settings.chat_filter) then
chat_filters_installed = true
ef = ChatFrame_AddMessageEventFilter
end
end
end
if (not onoff or not ksk.cfg.settings.chat_filter) then
if (chat_filters_installed) then
chat_filters_installed = nil
ef = ChatFrame_RemoveMessageEventFilter
end
end
if (ef) then
ef("CHAT_MSG_WHISPER", whisper_filter)
ef("CHAT_MSG_WHISPER_INFORM", reply_filter)
ef("CHAT_MSG_RAID", reply_filter)
ef("CHAT_MSG_GUILD", reply_filter)
ef("CHAT_MSG_RAID_LEADER", reply_filter)
end
end
local function ksk_suspended(onoff)
ksk.frdb.suspended = onoff
if (onoff) then
KRP:SuspendAddon(ksk.addon_handle)
KLD:SuspendAddon(ksk.addon_handle)
KK:SuspendAddon(ksk.addon_handle)
else
KRP:ActivateAddon(ksk.addon_handle)
KLD:ActivateAddon(ksk.addon_handle)
KK:ActivateAddon(ksk.addon_handle)
end
end
--
-- This section contains the callback functions we register with KRP and KLD.
-- These add in KSK specific variables to various data structures since those
-- Kore addons now handle all raid group and loot tracking functions. We also
-- trap a number of their messages for keeping local track of loot states etc.
--
--
-- Called by KRP whenever it is starting a round of updates for the group.
-- We use this to reset the private data member called users, which is a
-- map of KSK user ID's to player names. This is useful in many places in
-- KSK to determine whether or not the given UID is in the raid, for example,
-- as well as other uses. So when we start the round of updates we null out
-- that table as it is about to be re-populated.
--
local function krp_update_group_start(_, _, pvt, ...)
ksk.users = {}
end
--
-- This is called by KRP whenever it refreshes the raid groups and a new player
-- is added to the players list. We are called with the player info as it
-- currently exists. For ease of use later we store the KSK user ID if it
-- exists in the player structure.
--
-- This must be called whenever we change configs as the info we add to each
-- player is unique to the current config.
--
local function krp_new_player(_, _, pvt, player)
if (ksk.frdb.tempcfg) then
return
end
local nm = player.name
local unkuser = nil
player["ksk_uid"] = nil
player["ksk_dencher"] = nil
player["ksk_missing"] = nil
local uid = ksk.FindUser(nm) or "0fff"
if (uid == "0fff") then
local classid = player.class
uid = uid .. ":" .. classid .. ":" .. nm
unkuser = { name = nm, class = classid }
if (not ksk.missing[uid]) then
ksk.nmissing = ksk.nmissing + 1
ksk.missing[uid] = unkuser
if (KRP.in_party and KRP.is_ml and ksk.csd.is_admin) then
info(L["NOTICE: user %q is in the raid but not in the user list."], class(nm, classid))
end
end
ksk.qf.addmissing:SetEnabled(ksk.csd.is_admin ~= nil)
player["ksk_missing"] = true
player["ksk_uid"] = nil
else
ksk.users[uid] = player.name
player["ksk_uid"] = uid
player["ksk_missing"] = nil
for i = 1, ksk.MAX_DENCHERS do
if (ksk.cfg.settings.denchers[i] == uid and player.online) then
player["ksk_dencher"] = true
end
end
end
end
function ksk.UpdateDenchers()
assert(ksk.users)
ksk.denchers = {}
for k, v in pairs(KRP.players) do
if (v["ksk_dencher"]) then
tinsert(ksk.denchers, k)
end
end
end
--
-- Called by KRP when it is done updating all of the group info.
--
local function krp_update_group_end(_, _, pvt, in_p, in_r, in_bg)
if (ksk.frdb.tempcfg) then
return
end
if (in_p) then
ksk.UpdateDenchers()
else
ksk.users = nil
ksk.nmissing = 0
ksk.missing = {}
ksk.ResetBossLoot()
end
ksk.RefreshListsUIForRaid(in_p)
ksk.qf.addmissing:SetEnabled((in_p and ksk.nmissing > 0) and true or false)
ksk.RefreshAllMemberLists()
update_bcast_button()
end
--
-- Fired when there has been a change in group leadership.
--
local function krp_leader_changed(_, _, pvt, leader)
update_bcast_button()
end
--
-- This is fired when the state changes from in raid to out, or out to in.
--
local function krp_in_group_changed(_, _, pvt, in_party, in_raid, in_bg)
if (ksk.frdb.tempcfg) then
return
end
if (in_party) then
if (ksk.csd.is_admin) then
ksk:SendAM("REQRS", "BULK")
end
if (KRP.is_ml and not ksk.csd.is_admin) then
if (not ksk.csd.admin_warned) then
ksk.csd.admin_warned = true
info(L["you are the master looter but not an administrator of this configuration. You will be unable to loot effectively. Either change master looter or have the owner of the configuration assign you as an administrator."])
end
end
end
end
local function kld_start_loot_info(_, _, pvt)
if (not ksk.AmIML()) then
return
end
ksk.ResetBossLoot()
end
--
-- This is called by KLD whenever a new item is added to the loot table.
-- We need to set whether or not we want to skip dealing with this item.
-- We also check to see whether or not this item is in the KSK items database
-- to be ignored or auto-disenchanted.
--
local function kld_loot_item(_, _, pvt, item)
if (not ksk.AmIML()) then
return
end
ksk.announcedloot = ksk.announcedloot or {}
local skipit = false
local dencher = nil
local itemid = nil
local give = nil
if (item["itemid"]) then
itemid = item["itemid"]
end
if (not item.ilink or item.ilink == "" or not itemid) then
skipit = true
end
if (item.locked) then
skipit = true
end
if (ksk.denchers) then
for k, v in pairs(ksk.denchers) do
if (not dencher) then
-- Check to ensure that the dencher can receive the loot from master
if (item.candidates[v]) then
dencher = v
break
end
end
end
end
if (not dencher) then
if (item.candidates[KRP.master_looter]) then
dencher = KRP.master_looter
end
end
if (itemid and ksk.cfg.items[itemid]) then
if (ksk.cfg.items[itemid].ignore) then
skipit = true
elseif (ksk.cfg.items[itemid].autodench) then
if (dencher) then
skipit = true
give = dencher
end
elseif (ksk.cfg.items[itemid].automl) then
if (item.candidates[KRP.master_looter]) then
skipit = true
give = KRP.master_looter
end
end
elseif (itemid and ksk.iitems[itemid]) then
if (ksk.iitems[itemid].ignore) then
skipit = true
end
end
local bthresh = tonumber(ksk.cfg.settings.bid_threshold or "0")
local iqual = tonumber(item.quality or "0")
if (ksk.cfg.settings.disenchant_below and not skipit) then
if (dencher and bthresh ~= 0 and iqual < bthresh) then
skipit = true
give = dencher
end
end
if (not skipit) then
if (bthresh ~= 0 and iqual < bthresh) then
skipit = true
end
end
item["ksk_skipit"] = skipit
item["ksk_give"] = give
if (give) then
KLD.GiveMasterLoot(item.lootslot, give)
end
if (not skipit) then
ksk.AddItemToBossLoot(item.ilink, item.quantity, item.lootslot)
end
end
--
-- This is fired when a corpse has been looted and we have retrieved all of
-- the lootable items. It can also be fired when we have changed the various
-- user lists and we want to refresh the loot so that the callbacks can access
-- the new data.
--
local function kld_end_loot_info()
if (not ksk.AmIML()) then
return
end
local nbossloot
local ilist = {}
if (not KLD.unit_name or not KLD.items or not ksk.bossloot) then
ksk.bossloot = nil
nbossloot = 0
else
nbossloot = #ksk.bossloot
for k, v in ipairs(ksk.bossloot) do
local ti = {v.ilink, v.quant }
tinsert(ilist, ti)
end
end
if (nbossloot == 0) then
ksk.ResetBossLoot()
end
ksk.RefreshBossLoot(nil)
if (nbossloot > 0) then
local uname = KLD.unit_name
local uguid = KLD.unit_guid
local realguid = KLD.unit_realguid
sentoloot = true
ksk:SendAM("OLOOT", "ALERT", uname, uguid, realguid, ilist)
if (ksk.cfg.settings.auto_bid == true) then
if (not ksk.mainwin:IsVisible()) then
ksk.autoshown = true
end
ksk.mainwin:Show()
ksk.mainwin:SetTab(ksk.LOOT_TAB, ksk.LOOT_ASSIGN_PAGE)
end
if (ksk.cfg.settings.announce_where ~= 0) then
ksk.announcedloot = ksk.announcedloot or {}
local sendfn = ksk.SendGuildText
if (ksk.cfg.settings.announce_where == 2) then
sendfn = ksk.SendText
end
local dloot = true
if (uguid ~= 0) then
if (ksk.announcedloot[uguid]) then
dloot = false
end
ksk.announcedloot[uguid] = true
else
ksk.lastannouncetime = ksk.lastannouncetime or time()
local now = time()
local elapsed = difftime(now, ksk.lastannounce)
if (elapsed < 60) then
dloot = false
end
end
if (dloot) then
sendfn(ksk, strfmt(L["Loot from %s: "], uname))
for k,v in ipairs(ksk.bossloot) do
sendfn(ksk, v.ilink)
end
ksk.lastannouncetime = time()
end
end
end
end
local function kld_looting_ended(_, _, pvt)
if (not ksk.AmIML()) then
return
end
ksk.CloseLoot()
ksk.ResetBossLoot()
if (ksk.autoshown) then
ksk.autoshown = nil
ksk.mainwin:Hide()
end
if (sentoloot) then
ksk:SendAM("CLOOT", "ALERT")
end
sentoloot = nil
end
local function ksk_initialised()
if (ksk.initialised) then
return
end
ksk.initialised = true
K:RegisterMessage("PLAYER_INFO_UPDATED", player_info_updated)
K:RegisterMessage("GUILD_INFO_UPDATED", guild_info_updated)
--
-- We prefer to use callbacks to messages because callbacks are not called
-- if the mod isn't currently active.
--
local kh = ksk.addon_handle
KLD:AddonCallback(kh, "start_loot_info", kld_start_loot_info)
KLD:AddonCallback(kh, "loot_item", kld_loot_item)
KLD:AddonCallback(kh, "end_loot_info", kld_end_loot_info)
KLD:AddonCallback(kh, "looting_ended", kld_looting_ended)
KRP:AddonCallback(kh, "update_group_start", krp_update_group_start)
KRP:AddonCallback(kh, "update_group_end", krp_update_group_end)
KRP:AddonCallback(kh, "new_player", krp_new_player)
KRP:AddonCallback(kh, "in_group_changed", krp_in_group_changed)
KRP:AddonCallback(kh, "leader_changed", krp_leader_changed)
KRP:AddonCallback(kh, "role_changed", krp_leader_changed)
ksk_suspended(ksk.frdb.suspended)
ksk.SetDefaultConfig(ksk.frdb.defconfig, true, true)
ksk.FullRefresh(true)
ksk.ConfigAdmin(ksk.csd.is_admin ~= nil and true or false)
--
-- Broadcasts a list of all configurations we have, and the latest events
-- we have for each user. The recipients of the message use this to trim
-- old events from their lists to save space.
--
ksk.SyncCleanup()
end
--
-- In the past KKore used to have embedded and very slightly modified versions
-- of the Ace3 libraries. These have been removed and we now simply use the
-- originals. However, one of the changes we made was to AceDB-3.0, where we
-- used the string "-" as a seperator between the name and realm, whereas
-- AceDB uses the string " - ". The upshot of this is, if we do not fix the
-- key names in the options variable, using AceDB will mean that any existing
-- saved data will be inaccessible, although present in the savedvariables
-- file. This function attempts to fix the database before AceDB initialises.
-- However this only works per character and realm so if the user have many of
-- those, each one will need to be converted. We will eventually be able to
-- remove this but only after quite a long time.
--
local function fix_acedb()
if (not KKonferSKDB) then
return
end
local realm = GetRealmName()
local player = UnitName("player")
local faction = UnitFactionGroup("player")
local my_player = player .. "-" .. realm
local db_player = player .. " - " .. realm
local my_fr = faction .. "-" .. realm
local db_fr = faction .. " - " .. realm
local pk = rawget(KKonferSKDB, "profileKeys")
if (pk) then
local pkn = rawget(pk, my_player)
if (pkn) then
rawset(pk, db_player, pkn)
rawset(pk, my_player, nil)
end
end
pk = rawget(KKonferSKDB, "factionrealm")
if (pk) then
local pkn = rawget(pk, my_fr)
if (pkn) then
rawset(pk, db_fr, pkn)
rawset(pk, my_fr, nil)
end
end
end
--
-- "Register" KSK with the list of all other Konfer addons.
--
ksk.konfer = {
handle = ksk.addon_handle,
name = L["MODNAME"],
title = L["MODTITLE"],
desc = L["Suicide Kings loot distribution system."],
cmd = L["CMDNAME"],
version = ksk.version,
suspendcmd = L["CMD_SUSPEND"],
resumecmd = L["CMD_RESUME"],
raid = true, -- Works in raids
party = true, -- Works in parties
bg = false, -- Does not work in battlegrounds
is_suspended = function(handle)
return ksk.frdb.suspended or false
end,
set_suspended = function(handle, onoff)
local onoff = onoff or false
ksk_suspended(onoff)
ksk.FullRefresh(true)
end,
open_on_loot = function(handle)
if (ksk.cfg and ksk.cfg.settings and ksk.cfg.settings.auto_bid) then
return true
end
return false
end,
}
function ksk:OnLateInit()
if (ksk.initialised) then
return
end
fix_acedb()
ksk.db = DB:New("KKonferSKDB", nil, "Default")
ksk.frdb = ksk.db.factionrealm
if (not ksk.frdb.configs) then
ksk.frdb.nconfigs = 0
ksk.frdb.configs = {}
ksk.configs = ksk.frdb.configs
ksk.frdb.tempcfg = true -- Must be set true before call to CreateNewConfig
ksk.CreateNewConfig(" ", true, true, "1")
ksk.frdb.dbversion = ksk.dbversion
end
-- A lot of utility functions depend on this being set so ensure it is done
-- early before we call any other functions.
ksk.configs = ksk.frdb.configs
-- ksk.SetDefaultConfig (called next) depends on ksk.csdata being set up
-- and correct, so "refresh" that now.
ksk.RefreshCSData()
-- Set up all of the various global aliases and the like.
ksk.SetDefaultConfig(ksk.frdb.defconfig, true, true)
ksk.UpdateDatabaseVersion()
KK.RegisterKonfer(ksk)
ksk.InitialiseUI()
K.RegisterComm(ksk, ksk.CHAT_MSG_PREFIX)
ksk_initialised()
end
|
local realtime = {}
local json = require('json')
local gpgs = require('plugin.gpgs.v2')
local newButton = require('classes.button').newButton
local _W, _H = display.actualContentWidth, display.actualContentHeight
local _CX, _CY = display.contentCenterX, display.contentCenterY
function realtime:newPlayer(params)
local player = display.newCircle(params.g, params.x, params.y, 30)
player.color = {0.5 + math.random() / 2, 0.5 + math.random() / 2, 0.5 + math.random() / 2}
player:setFillColor(unpack(player.color))
local super = self
function player:send()
gpgs.multiplayer.realtime.sendUnreliably({
roomId = super.roomId,
payload = json.encode({id = super.playerId, color = self.color, x = self.x, y = self.y})
})
end
player:send()
function player:touch(event)
if event.phase == 'began' then
self.xStart, self.yStart = self.x, self.y
display.getCurrentStage():setFocus(self)
self.isFocused = true
elseif self.isFocused then
if event.phase == 'moved' then
self.x, self.y = self.xStart + event.x - event.xStart, self.yStart + event.y - event.yStart
self:send()
else
display.getCurrentStage():setFocus(nil)
self.isFocused = false
end
end
end
player:addEventListener('touch')
return player
end
function realtime:newParticipant(params)
local participant = display.newCircle(params.g, params.x, params.y, 30)
participant:setFillColor(unpack(params.color))
participant.id = params.id
function participant:update(updateParams)
self.x, self.y = updateParams.x, updateParams.y
end
return participant
end
function realtime:show()
self.playerId = ''
self.participants = {}
display.remove(self.group)
self.group = display.newGroup()
local background = display.newRect(self.group, _CX, _CY, _W, _H)
background:setFillColor(0, 0.2, 0.4)
print(json.prettify(gpgs.multiplayer.getLimits() or '{}'))
gpgs.multiplayer.invitations.setListener(function(event)
print('Invitations event:', json.prettify(event))
end)
gpgs.multiplayer.realtime.setListeners({
message = function(event)
print('Message event:', json.prettify(event))
local participantData = json.decode(event.payload)
if not self.participants[participantData.id] then
participantData.g = self.group
self.participants[participantData.id] = self:newParticipant(participantData)
else
self.participants[participantData.id]:update(participantData)
end
end,
peer = function(event)
print('Peer event:', json.prettify(event))
end,
room = function(event)
print('Room event:', json.prettify(event))
if event.phase == 'created' then
self.roomId = event.roomId
gpgs.multiplayer.realtime.showWaitingRoom({
roomId = event.roomId
})
elseif event.phase == 'connected' then
self.roomId = event.roomId
self:startGameplay()
elseif event.phase == 'left' then
self:hide()
end
end
})
gpgs.players.load({
listener = function(event)
if not event.isError then
self.playerId = event.players[1].id
end
end
})
newButton({
g = self.group, index = 1,
label = 'Show invitations',
onRelease = function()
gpgs.multiplayer.invitations.show(function(event)
print('Show invitations event:', json.prettify(event))
if event.invitation then
gpgs.multiplayer.realtime.join(event.invitation.id)
end
end)
end
})
newButton({
g = self.group, index = 2,
label = 'Select players',
onRelease = function()
gpgs.multiplayer.realtime.showSelectPlayers({
listener = function(event)
print('Select players event:', json.prettify(event))
if event.playerIds then
gpgs.multiplayer.realtime.create({
playerIds = event.playerIds
})
end
end
})
end
})
newButton({
g = self.group, index = 3,
label = 'Get room',
onRelease = function()
if self.roomId then
local room = gpgs.multiplayer.realtime.getRoom(self.roomId)
print('Room:', json.prettify(room))
print('Room AutoMatchWaitEstimateSeconds:', room.getAutoMatchWaitEstimateSeconds())
local participantIds = room.getParticipantIds()
for i = 1, #participantIds do
print('Participant ' .. i .. ':', json.prettify(room.getParticipant(participantIds[i])))
print('Participant ' .. i .. ' status:', room.getParticipantStatus(participantIds[i]))
end
end
end
})
newButton({
g = self.group, index = 4,
label = 'Leave',
onRelease = function()
if self.roomId then
gpgs.multiplayer.realtime.leave(self.roomId)
end
end
})
end
function realtime:startGameplay()
self.player =self:newPlayer({g = self.group, x = _CX, y = _CY})
end
function realtime:hide()
self.group:removeSelf()
self.player = nil
self.roomId = nil
self.participants = nil
gpgs.multiplayer.invitations.removeListener()
gpgs.multiplayer.realtime.removeListeners()
end
return realtime
|
local dap = require('dap')
dap.adapters.cppdbg = {
id = 'cppdbg',
type = "executable",
command = os.getenv('HOME') .. '/.config/nvim/lua/user/dap/debugger/ms-vscode.cpptools-1.7.1/debugAdapters/bin/OpenDebugAD7',
}
dap.configurations.cpp = {
-- launch exe
{
name = "Launch file",
type = "cppdbg",
request = "launch",
program = function()
return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/', 'file')
end,
cwd = '${workspaceFolder}',
stopOnEntry = true,
setupCommands = {
{
description = 'enable pretty printing',
text = '-enable-pretty-printing',
ignoreFailures = false
},
},
},
-- attach process
{
name = "Attach process",
type = "cppdbg",
request = "attach",
processId = require('dap.utils').pick_process,
program = function()
return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/', 'file')
end,
cwd = "${workspaceFolder}",
setupCommands = {
{
description = 'enable pretty printing',
text = '-enable-pretty-printing',
ignoreFailures = false
},
},
},
-- attach server
{
name = 'Attach to gdbserver :1234',
type = 'cppdbg',
request = 'launch',
MIMode = 'gdb',
miDebuggerServerAddress = 'localhost:1234',
miDebuggerPath = '/usr/bin/gdb', cwd = '${workspaceFolder}',
program = function()
return vim.fn.input('Path to executable: ', vim.fn.getcwd() .. '/', 'file')
end,
setupCommands = {
{
text = '-enable-pretty-printing',
description = 'enable pretty printing',
ignoreFailures = false
},
},
},
}
-- setup other language
dap.configurations.c = dap.configurations.cpp
|
-- TRT: Copy of request-transformer-advanced plugin
local multipart = require "multipart"
local cjson = require "cjson"
local pl_template = require "pl.template"
local pl_tablex = require "pl.tablex"
local jwt_decoder = require "kong.plugins.jwt.jwt_parser"
local table_insert = table.insert
local req_set_uri_args = ngx.req.set_uri_args
local req_get_uri_args = ngx.req.get_uri_args
local req_set_header = ngx.req.set_header
local req_get_headers = ngx.req.get_headers
local req_read_body = ngx.req.read_body
local req_set_body_data = ngx.req.set_body_data
local req_get_body_data = ngx.req.get_body_data
local req_clear_header = ngx.req.clear_header
local req_set_method = ngx.req.set_method
local encode_args = ngx.encode_args
local ngx_decode_args = ngx.decode_args
local ngx_log = ngx.log
local type = type
local str_find = string.find
local pcall = pcall
local pairs = pairs
local error = error
local rawset = rawset
local pl_copy_table = pl_tablex.deepcopy
local _M = {}
local template_cache = setmetatable( {}, { __mode = "k" })
local template_environment
local DEBUG = ngx.DEBUG
local CONTENT_LENGTH = "content-length"
local CONTENT_TYPE = "content-type"
local HOST = "host"
local JSON, MULTI, ENCODED = "json", "multi_part", "form_encoded"
local EMPTY = pl_tablex.readonly({})
-- JSON serialization for printing various objects
--
-- Arguments:
-- @o: The object to print
-- Returns:
-- The object as string
local function serialize(o)
if not o then
return " is null"
elseif type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. serialize(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
-- NPE safe logger
--
-- Arguments:
-- @char: String to log
-- @v: Value to log
-- Returns:
-- VOID
local function log(char, v)
ngx_log(DEBUG, char..serialize(v))
end
-- Attempts to split a value by period. This returns as 2 values:
-- 1st (top level)
-- 2nd (rest)
-- i.e. query.metadata.value -> top = "query", rest = "metadata.value"
--
-- Arguments:
-- @: String value
-- Returns:
-- Split string by top and rest
local function splitByPeriod(value)
if (value) then
local top, rest = value:match("^([^.]+)%.*(.-)$")
return top, rest
end
return EMPTY
end
-- Check existance via plaintext
--
-- Arguments:
-- @stringValue: String value to check
-- @subString: Sub-string to check existance of
-- Returns
-- Boolean
local function stringContains(stringValue, subString)
if (stringValue and subString) then
return string.find(stringValue, subString, 1, true) ~= nil
end
return false
end
-- Retrieve nested JSON value via dot notation
--
-- Arguments:
-- @json: JSON Map to retrieve from
-- @path: Dot Notated JSON path
-- Returns:
-- Value of JSON path or nil
local function getValueFromJsonPath(json, path)
local value
if (json and path) then
if (stringContains(path, ".")) then
-- This is still nested
local parent, rest = splitByPeriod(path)
value = json[parent]
if (value) then
return getValueFromJsonPath(value, rest)
end
return nil
else
-- No longer nested
return json[path]
end
end
return value
end
-- Safe method to decodes a JWT token
--
-- Arguments:
-- @token: The value of the Authorization Bearer header (ideally JWT)
-- Returns:
-- Empty Map or Map of JWT claims/headers
local function getJwtFromAuth(token)
-- decode token to get roles claim
local jwt, err = jwt_decoder:new(token)
if err then
log("Couldn't get JWT: ", err)
jwt = {}
end
return jwt
end
-- Silly function to assign globals to transformation path
--
-- Globals:
-- query: The query on the request
-- header: The headers on the request
-- body: The body on the request
-- url: The URL on the request
-- Arguments:
-- @parent: Top level path value, corresponds to request values (query, header, body, jwt, url)
-- Returns:
-- JSON of request value
local function getMapValue(parent, path)
local map = {}
if (parent == "query") then
map = template_environment.query_params
elseif (parent == "header") then
map = template_environment.headers
elseif (parent == "body") then
-- Schema validation shouldn't allow you to get here...
req_read_body()
map = req_get_body_data()
elseif (parent == "jwt") then
local jwt = {}
if (template_environment.headers.Authorization
and stringContains(template_environment.headers.Authorization, "Bearer ")) then
local authorization = template_environment.headers.Authorization
local token = string.gsub(authorization, "Bearer ", "")
jwt = getJwtFromAuth(token)
end
map = jwt
elseif (parent == "url") then
-- Schema validation shouldn't allow you to get here...
log("URL field is not supported for path, ", path)
end
return map
end
-- Retrieves nested value from request variables
--
-- Arguments:
-- @path: Dot notation path (i.e. header.Some-Field)
-- Returns:
-- Request value
local function getRequestValue(path)
local parent, rest = splitByPeriod(path)
local requestValue
if (parent) then
local map = getMapValue(parent, path)
-- Set global...
requestValue = getValueFromJsonPath(map, rest)
end
return requestValue
end
-- Sets nested value for request variables
--
-- Arguments:
-- @json: JSON Map to retrieve from
-- @path: Dot Notated JSON path
-- @value: Value to set in dot notated JSON path
-- Returns:
-- Void
local function setValueFromJsonPath(json, path, value)
if (json and path and value) then
if (stringContains(path, ".")) then
-- This is still nested
local parent, rest = splitByPeriod(path)
local newJson = json[parent]
if (newJson) then
setValueFromJsonPath(newJson, rest, value)
return
end
json[path] = value
else
-- No longer nested
json[path] = value
end
end
end
-- Sets nested value for request variables
--
-- Arguments:
-- @path: Dot notation path (i.e. header.Some-Field)
-- @value: Value to set in request fields
-- Returns:
-- Void
local function setRequestValue(path, value)
local parent, rest = splitByPeriod(path)
if (parent) then
if (parent == "query") then
local querystring = pl_copy_table(template_environment.query_params)
setValueFromJsonPath(querystring, rest, value)
req_set_uri_args(querystring)
elseif (parent == "header") then
req_set_header(rest, value)
else
log("Not supported. Cannot set requestValue for path, ", path)
end
else
log("Cannot set requestValue for path, ", path)
end
end
local function parse_json(body)
if body then
local status, res = pcall(cjson.decode, body)
if status then
return res
end
end
end
local function decode_args(body)
if body then
return ngx_decode_args(body)
end
return {}
end
local function get_content_type(content_type)
if content_type == nil then
return
end
if str_find(content_type:lower(), "application/json", nil, true) then
return JSON
elseif str_find(content_type:lower(), "multipart/form-data", nil, true) then
return MULTI
elseif str_find(content_type:lower(), "application/x-www-form-urlencoded", nil, true) then
return ENCODED
end
end
-- meta table for the sandbox, exposing lazily loaded values
local __meta_environment = {
__index = function(self, key)
local lazy_loaders = {
headers = function(self)
return req_get_headers() or EMPTY
end,
query_params = function(self)
return req_get_uri_args() or EMPTY
end,
uri_captures = function(self)
return (ngx.ctx.router_matches or EMPTY).uri_captures or EMPTY
end,
shared = function(self)
return ((kong or EMPTY).ctx or EMPTY).shared or EMPTY
end,
}
local loader = lazy_loaders[key]
if not loader then
-- we don't have a loader, so just return nothing
return
end
-- set the result on the table to not load again
local value = loader()
rawset(self, key, value)
return value
end,
__new_index = function(self)
error("This environment is read-only.")
end,
}
template_environment = setmetatable({
-- here we can optionally add functions to expose to the sandbox, eg:
-- tostring = tostring, -- for example
}, __meta_environment)
local function clear_environment(conf)
rawset(template_environment, "headers", nil)
rawset(template_environment, "query_params", nil)
rawset(template_environment, "uri_captures", nil)
rawset(template_environment, "shared", nil)
end
local function param_value(source_template, config_array)
if not source_template or source_template == "" then
return nil
end
-- find compiled templates for this plugin-configuration array
local compiled_templates = template_cache[config_array]
if not compiled_templates then
compiled_templates = {}
-- store it by `config_array` which is part of the plugin `conf` table
-- it will be GC'ed at the same time as `conf` and hence invalidate the
-- compiled templates here as well as the cache-table has weak-keys
template_cache[config_array] = compiled_templates
end
-- Find or compile the specific template
local compiled_template = compiled_templates[source_template]
if not compiled_template then
compiled_template = pl_template.compile(source_template)
compiled_templates[source_template] = compiled_template
end
return compiled_template:render(template_environment)
end
local function iter(config_array)
return function(config_array, i, previous_name, previous_value)
i = i + 1
local current_pair = config_array[i]
if current_pair == nil then -- n + 1
return nil
end
local current_name, current_value = current_pair:match("^([^:]+):*(.-)$")
if current_value == "" then
return i, current_name
end
local res, err = param_value(current_value, config_array)
if err then
return error("[request-transformer] failed to render the template ",
current_value, ", error:", err)
end
ngx_log(DEBUG, "[request-transformer] template `", current_value,
"` rendered to `", res, "`")
return i, current_name, res
end, config_array, 0
end
local function append_value(current_value, value)
local current_value_type = type(current_value)
if current_value_type == "string" then
return { current_value, value }
elseif current_value_type == "table" then
table_insert(current_value, value)
return current_value
else
return { value }
end
end
local function transform_headers(conf)
-- Remove header(s)
for _, name, value in iter(conf.remove.headers) do
if template_environment.headers[name] then
req_clear_header(name)
end
end
-- Rename headers(s)
for _, old_name, new_name in iter(conf.rename.headers) do
if template_environment.headers[old_name] then
local value = template_environment.headers[old_name]
req_set_header(new_name, value)
req_clear_header(old_name)
end
end
-- Replace header(s)
for _, name, value in iter(conf.replace.headers) do
if template_environment.headers[name] then
req_set_header(name, value)
if name:lower() == HOST then -- Host header has a special treatment
ngx.var.upstream_host = value
end
end
end
-- Add header(s)
for _, name, value in iter(conf.add.headers) do
if not template_environment.headers[name] then
req_set_header(name, value)
if name:lower() == HOST then -- Host header has a special treatment
ngx.var.upstream_host = value
end
end
end
-- Append header(s)
for _, name, value in iter(conf.append.headers) do
if name:lower() ~= HOST then
req_set_header(name, append_value(req_get_headers()[name], value))
end
end
end
local function transform_querystrings(conf)
if not (#conf.remove.querystring > 0 or #conf.rename.querystring or
#conf.replace.querystring > 0 or #conf.add.querystring > 0 or
#conf.append.querystring > 0) then
return
end
local querystring = pl_copy_table(template_environment.query_params)
-- Remove querystring(s)
for _, name, value in iter(conf.remove.querystring) do
querystring[name] = nil
end
-- Rename querystring(s)
for _, old_name, new_name in iter(conf.rename.querystring) do
local value = querystring[old_name]
querystring[new_name] = value
querystring[old_name] = nil
end
for _, name, value in iter(conf.replace.querystring) do
if querystring[name] then
querystring[name] = value
end
end
-- Add querystring(s)
for _, name, value in iter(conf.add.querystring) do
if not querystring[name] then
querystring[name] = value
end
end
-- Append querystring(s)
for _, name, value in iter(conf.append.querystring) do
querystring[name] = append_value(querystring[name], value)
end
req_set_uri_args(querystring)
end
local function transform_json_body(conf, body, content_length)
local removed, renamed, replaced, added, appended = false, false, false, false, false
local content_length = (body and #body) or 0
local parameters = parse_json(body)
if parameters == nil then
if content_length > 0 then
return false, nil
end
parameters = {}
end
if content_length > 0 and #conf.remove.body > 0 then
for _, name, value in iter(conf.remove.body) do
parameters[name] = nil
removed = true
end
end
if content_length > 0 and #conf.rename.body > 0 then
for _, old_name, new_name in iter(conf.rename.body) do
local value = parameters[old_name]
parameters[new_name] = value
parameters[old_name] = nil
renamed = true
end
end
if content_length > 0 and #conf.replace.body > 0 then
for _, name, value in iter(conf.replace.body) do
if parameters[name] then
parameters[name] = value
replaced = true
end
end
end
if #conf.add.body > 0 then
for _, name, value in iter(conf.add.body) do
if not parameters[name] then
parameters[name] = value
added = true
end
end
end
if #conf.append.body > 0 then
for _, name, value in iter(conf.append.body) do
local old_value = parameters[name]
parameters[name] = append_value(old_value, value)
appended = true
end
end
if removed or renamed or replaced or added or appended then
return true, cjson.encode(parameters)
end
end
local function transform_url_encoded_body(conf, body, content_length)
local renamed, removed, replaced, added, appended = false, false, false, false, false
local parameters = decode_args(body)
if content_length > 0 and #conf.remove.body > 0 then
for _, name, value in iter(conf.remove.body) do
parameters[name] = nil
removed = true
end
end
if content_length > 0 and #conf.rename.body > 0 then
for _, old_name, new_name in iter(conf.rename.body) do
local value = parameters[old_name]
parameters[new_name] = value
parameters[old_name] = nil
renamed = true
end
end
if content_length > 0 and #conf.replace.body > 0 then
for _, name, value in iter(conf.replace.body) do
if parameters[name] then
parameters[name] = value
replaced = true
end
end
end
if #conf.add.body > 0 then
for _, name, value in iter(conf.add.body) do
if parameters[name] == nil then
parameters[name] = value
added = true
end
end
end
if #conf.append.body > 0 then
for _, name, value in iter(conf.append.body) do
local old_value = parameters[name]
parameters[name] = append_value(old_value, value)
appended = true
end
end
if removed or renamed or replaced or added or appended then
return true, encode_args(parameters)
end
end
local function transform_multipart_body(conf, body, content_length, content_type_value)
local removed, renamed, replaced, added, appended = false, false, false, false, false
local parameters = multipart(body and body or "", content_type_value)
if content_length > 0 and #conf.rename.body > 0 then
for _, old_name, new_name in iter(conf.rename.body) do
if parameters:get(old_name) then
local value = parameters:get(old_name).value
parameters:set_simple(new_name, value)
parameters:delete(old_name)
renamed = true
end
end
end
if content_length > 0 and #conf.remove.body > 0 then
for _, name, value in iter(conf.remove.body) do
parameters:delete(name)
removed = true
end
end
if content_length > 0 and #conf.replace.body > 0 then
for _, name, value in iter(conf.replace.body) do
if parameters:get(name) then
parameters:delete(name)
parameters:set_simple(name, value)
replaced = true
end
end
end
if #conf.add.body > 0 then
for _, name, value in iter(conf.add.body) do
if not parameters:get(name) then
parameters:set_simple(name, value)
added = true
end
end
end
if removed or renamed or replaced or added or appended then
return true, parameters:tostring()
end
end
local function transform_body(conf)
local content_type_value = req_get_headers()[CONTENT_TYPE]
local content_type = get_content_type(content_type_value)
if content_type == nil or #conf.rename.body < 1 and
#conf.remove.body < 1 and #conf.replace.body < 1 and
#conf.add.body < 1 and #conf.append.body < 1 then
return
end
-- Call req_read_body to read the request body first
req_read_body()
local body = req_get_body_data()
local is_body_transformed = false
local content_length = (body and #body) or 0
if content_type == ENCODED then
is_body_transformed, body = transform_url_encoded_body(conf, body, content_length)
elseif content_type == MULTI then
is_body_transformed, body = transform_multipart_body(conf, body, content_length, content_type_value)
elseif content_type == JSON then
is_body_transformed, body = transform_json_body(conf, body, content_length)
end
if is_body_transformed then
req_set_body_data(body)
req_set_header(CONTENT_LENGTH, #body)
end
end
local function transform_method(conf)
if conf.http_method then
req_set_method(ngx["HTTP_" .. conf.http_method:upper()])
if conf.http_method == "GET" or conf.http_method == "HEAD" or conf.http_method == "TRACE" then
local content_type_value = req_get_headers()[CONTENT_TYPE]
local content_type = get_content_type(content_type_value)
if content_type == ENCODED then
-- Also put the body into querystring
-- Read the body
req_read_body()
local body = req_get_body_data()
local parameters = decode_args(body)
-- Append to querystring
local querystring = req_get_uri_args()
for name, value in pairs(parameters) do
querystring[name] = value
end
req_set_uri_args(querystring)
end
end
end
end
local function transform_uri(conf)
if conf.replace.uri then
local res, err = param_value(conf.replace.uri, conf.replace)
if err then
return error("[request-transformer] failed to render the template ",
conf.replace.uri, ", error:", err)
end
ngx_log(DEBUG, "[request-transformer] template `", conf.replace.uri,
"` rendered to `", res, "`")
if res then
ngx.var.upstream_uri = res
end
end
end
-- Performs any kinds of request transformations
--
-- Arguments:
-- @conf: The configuration setup in the plugin
-- Returns:
-- VOID
local function transform_request(conf)
if conf.transform and #conf.transform > 0 then
for i, line in ipairs(conf.transform) do
local from = line.from
local to = line.to
log("from: ", from)
log("to: ", to)
-- We shouldn't get to this point, but we're not handling arrays here
if (not stringContains(from, "*") and not stringContains(to, "*")) then
local fromValue = getRequestValue(from)
setRequestValue(to, fromValue)
end
end
end
end
function _M.execute(conf)
clear_environment()
transform_request(conf)
transform_uri(conf)
transform_method(conf)
transform_headers(conf)
transform_body(conf)
transform_querystrings(conf)
end
return _M
|
-- ======================================================================
-- Shuttle Search
-- Advent of Code 2020 Day 13 -- Eric Wastl -- https://adventofcode.com
--
-- lua implementation by Dr. Dean Earl Wright III
-- ======================================================================
-- ======================================================================
-- c r t . l u a
-- ======================================================================
-- Chinese remainder theorem
-- From https://rosettacode.org/wiki/Chinese_remainder_theorem#Lua
-- with revisions
-- ----------------------------------------------------------------------
-- local
-- ----------------------------------------------------------------------
local crt = {}
-- ----------------------------------------------------------------------
-- constants
-- ----------------------------------------------------------------------
-- ======================================================================
-- Crt
-- ======================================================================
local function prodf(a, ...) return a and a * prodf(...) or 1 end
local function prodt(t) return prodf(table.unpack(t)) end
local function mulInv(a, b)
local b0, x0, x1 = b, 0, 1
if b == 1 then
return 1
end
while a > 1 do
local q =a // b
a, b = b, a % b
x0, x1 = x1 -q * x0, x0
end
if x1 < 0 then
x1 = x1 + b0
end
return x1
end
function crt.chineseRemainder(n, a)
local prod = prodt(n)
local p
local sum = 0
for i = 1, #n do
p = prod // n[i]
sum = sum + a[i] * mulInv(p, n[i]) * p
end
return sum % prod
end
-- ----------------------------------------------------------------------
-- module initialization
-- ----------------------------------------------------------------------
return crt
-- ======================================================================
-- end c r t . l u a end
-- ======================================================================
|
local asserts = require 'testing.asserts'
local PositionTrigger = require 'common.position_trigger'
local set = require 'common.set'
local test_runner = require 'testing.test_runner'
local tests = {}
local HAPPINESS_LAYER = [[
..LL.LL..
.L..L..L.
..L...L..
...L.L...
....L....
]]
local UNHAPPY_POSITION = {50, 50} -- bottom left
local HAPPY_POSITION = {150, 350} -- left-most `L`
-- Update without any triggers.
function tests.testEmptyUpdate()
local triggers = PositionTrigger.new()
triggers:update(HAPPY_POSITION)
end
-- Create and remove a trigger multiple times.
function tests.testRemove()
local fired = false
local triggers = PositionTrigger.new()
for i = 1, 3 do
-- Create.
assert(not triggers:exists("testTrigger"))
triggers:start{
name = 'testTrigger',
maze = HAPPINESS_LAYER,
triggerWhenEnter = 'L',
callback = function() fired = true end,
}
assert(not fired)
assert(triggers:exists("testTrigger"))
-- Remove.
triggers:remove("testTrigger")
assert(not fired)
assert(not triggers:exists("testTrigger"))
end
end
-- Set up two triggers and verify the enter one fires when the first update is
-- on the trigger, and the exit one fires when the second update is off the
-- trigger.
function tests.testFirstUpdateTrigger()
local triggers = PositionTrigger.new()
-- Create trigger to fire .
-- Ensure it doesn't fire immediately.
local firedEnter = false
local firedExit = false
triggers:start{
name = 'testEnterTrigger',
maze = HAPPINESS_LAYER,
triggerWhenEnter = 'L',
callback = function() firedEnter = true end,
}
triggers:start{
name = 'testExitTrigger',
maze = HAPPINESS_LAYER,
triggerWhenExit = 'L',
callback = function() firedExit = true end,
}
assert(not firedEnter)
assert(not firedExit)
assert(triggers:exists("testEnterTrigger"))
assert(triggers:exists("testExitTrigger"))
-- Update position to one that should fire and check that it fired on enter
-- trigger, but not on exit trigger.
triggers:update(HAPPY_POSITION)
assert(firedEnter)
assert(not triggers:exists("testEnterTrigger"))
assert(not firedExit)
assert(triggers:exists("testExitTrigger"))
-- Update position to one that's outside, and check that the exit trigger
-- fired.
triggers:update(UNHAPPY_POSITION)
assert(firedExit)
assert(not triggers:exists("testExitTrigger"))
end
-- Set up two triggers and verify that neither fire when the first update is
-- off the trigger, the enter one fires when the second update is on the
-- trigger, and the exit one fires when the third update is off the trigger.
function tests.testSecondUpdateTrigger()
local triggers = PositionTrigger.new()
-- Create trigger to fire .
-- Ensure it doesn't fire immediately.
local firedEnter = false
local firedExit = false
triggers:start{
name = 'testEnterTrigger',
maze = HAPPINESS_LAYER,
triggerWhenEnter = 'L',
callback = function() firedEnter = true end,
}
triggers:start{
name = 'testExitTrigger',
maze = HAPPINESS_LAYER,
triggerWhenExit = 'L',
callback = function() firedExit = true end,
}
assert(not firedEnter)
assert(not firedExit)
assert(triggers:exists("testEnterTrigger"))
assert(triggers:exists("testExitTrigger"))
-- Update position to one that's outside, and check that nothing triggers.
triggers:update(UNHAPPY_POSITION)
assert(not firedEnter)
assert(not firedExit)
assert(triggers:exists("testEnterTrigger"))
assert(triggers:exists("testExitTrigger"))
-- Update position to one that should fire and check that it fired on enter
-- trigger, but not on exit trigger.
triggers:update(HAPPY_POSITION)
assert(firedEnter)
assert(not triggers:exists("testEnterTrigger"))
assert(not firedExit)
assert(triggers:exists("testExitTrigger"))
-- Update position to one that's outside, and check that the exit trigger
-- fired.
triggers:update(UNHAPPY_POSITION)
assert(firedExit)
assert(not triggers:exists("testExitTrigger"))
end
-- When we return true from the callback, the trigger should be reset so that
-- it fires again.
function tests.testPersist()
local triggers = PositionTrigger.new()
local fired = false
triggers:start{
name = 'testTrigger',
maze = HAPPINESS_LAYER,
triggerWhenEnter = 'L',
callback = function()
fired = true
return true -- request trigger to persist.
end,
}
-- Update position and assert trigger gets triggered.
assert(not fired)
triggers:update(HAPPY_POSITION)
assert(fired)
-- Reset trigger, move off the position and back on.
-- Assert trigger gets triggered again.
fired = false
triggers:update(UNHAPPY_POSITION)
assert(not fired)
triggers:update(HAPPY_POSITION)
assert(fired)
end
--[[ Test starting and triggering multiple triggers in the same maze.
Key word argements:
* `maze` (string) text representation of the maze.
* `triggers` (array) values for triggerWhenEnter and triggerWhenExit for
series of triggers.
* `updatePositions` (array) {x,y} positions used in call to triggers:update().
* `fired` (array) indices of {x,y} positions used in call to
triggers:update().
--]]
local function testMultiple(kwargs)
local triggers = PositionTrigger.new()
-- Create triggers.
local fired = {}
for i = 1, #kwargs.triggers do
triggers:start{
name = "testTrigger" .. tostring(i),
maze = kwargs.maze,
triggerWhenEnter = kwargs.triggers[i].triggerWhenEnter,
triggerWhenExit = kwargs.triggers[i].triggerWhenExit,
callback = function()
fired[i] = true
return kwargs.triggers[i].persist
end
}
end
-- Repeatedly call triggers:update() and verify that the appropriate triggers
-- have been fired.
for j = 1, #kwargs.updatePositions do
local currentPosition = kwargs.updatePositions[j]
triggers:update(currentPosition)
-- Ensure exactly the correct triggers have fired.
assert(set.isSame(fired, kwargs.fired[j]))
-- Reset which triggers were fired.
fired = {}
end
end
-- Set up multiple triggers that complete in the order they're created.
function tests.testMultipleInOrder()
testMultiple{
maze = 'CD\n' ..
'AB',
triggers = {
{triggerWhenEnter = 'A'}, -- trigger 1
{triggerWhenEnter = 'B'}, -- trigger 2
{triggerWhenEnter = 'C'}, -- trigger 3
{triggerWhenEnter = 'D'}, -- trigger 4
},
updatePositions = {
{0, 0},
{100, 0},
{0, 100},
{100, 100},
},
fired = {
{[1] = true},
{[2] = true},
{[3] = true},
{[4] = true},
},
}
end
-- Set up multiple triggers, where some trigger at the same time.
function tests.testMultipleSimultaneous()
testMultiple{
maze = 'AA\n' ..
'AB',
triggers = {
{triggerWhenEnter = 'A'}, -- trigger 1
{triggerWhenEnter = 'B'}, -- trigger 2
},
updatePositions = {
{100, 100},
{100, 0},
{100, 0},
},
fired = {
{[1] = true},
{[2] = true},
{},
},
}
end
-- Set up multiple triggers, where some trigger on exit.
function tests.testMultipleEnterExit()
testMultiple{
maze = 'AB',
triggers = {
{triggerWhenEnter = 'A'}, -- trigger 1
{triggerWhenExit = 'B'}, -- trigger 2
{triggerWhenExit = 'A'}, -- trigger 3
},
updatePositions = {
{100, 0},
{0, 0},
{100, 0},
},
fired = {
{},
{[1] = true, [2] = true},
{[3] = true},
},
}
end
-- Set up multiple triggers, where some are reset after they trigger.
function tests.testMultiplePersist()
testMultiple{
maze = 'AB',
triggers = {
{triggerWhenEnter = 'A', persist = true}, -- trigger 1
{triggerWhenEnter = 'B', persist = true}, -- trigger 2
{triggerWhenExit = 'A', persist = true}, -- trigger 3
{triggerWhenExit = 'B', persist = true}, -- trigger 4
},
updatePositions = {
{0, 0},
{100, 0},
{100, 0},
{0, 0},
{100, 0},
},
fired = {
{[1] = true},
{[2] = true, [3] = true},
{},
{[1] = true, [4] = true},
{[2] = true, [3] = true},
},
}
end
return test_runner.run(tests)
|
------------------------------------------------------------------------
-- Animation Functions
------------------------------------------------------------------------
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB
--Lua functions
local random, next, unpack, strsub = random, next, unpack, strsub
--WoW API / Variables
E.AnimShake = {{-9,7,-7,12}, {-5,9,-9,5}, {-5,7,-7,5}, {-9,9,-9,9}, {-5,7,-7,5}, {-9,7,-9,5}}
E.AnimShakeH = {-5,5,-2,5,-2,5}
function E:FlashLoopFinished(requested)
if not requested then self:Play() end
end
function E:RandomAnimShake(index)
local s = E.AnimShake[index]
return random(s[1], s[2]), random(s[3], s[4])
end
function E:SetUpAnimGroup(obj, Type, ...)
if not Type then Type = 'Flash' end
if strsub(Type, 1, 5) == 'Flash' then
obj.anim = obj:CreateAnimationGroup('Flash')
obj.anim.fadein = obj.anim:CreateAnimation('ALPHA', 'FadeIn')
obj.anim.fadein:SetFromAlpha(0)
obj.anim.fadein:SetToAlpha(1)
obj.anim.fadein:SetOrder(2)
obj.anim.fadeout = obj.anim:CreateAnimation('ALPHA', 'FadeOut')
obj.anim.fadeout:SetFromAlpha(1)
obj.anim.fadeout:SetToAlpha(0)
obj.anim.fadeout:SetOrder(1)
if Type == 'FlashLoop' then
obj.anim:SetScript('OnFinished', E.FlashLoopFinished)
end
elseif strsub(Type, 1, 5) == 'Scale' then
obj.anim = obj:CreateAnimationGroup("Scale")
obj.anim.scaleOut = obj.anim:CreateAnimation("Scale")
obj.anim.scaleOut:SetDuration(0)
obj.anim.scaleOut:SetScale(1.5, 1.5)
obj.anim.scaleOut:SetOrder(1)
obj.anim.scaleIn = obj.anim:CreateAnimation("Scale")
obj.anim.scaleIn:SetDuration(0.35)
obj.anim.scaleIn:SetScale(1/1.5, 1/1.5)
obj.anim.scaleIn:SetOrder(2)
elseif strsub(Type, 1, 5) == 'Shake' then
local shake = obj:CreateAnimationGroup(Type)
shake:SetLooping('REPEAT')
shake.path = shake:CreateAnimation('Path')
if Type == 'Shake' then
shake.path:SetDuration(0.7)
obj.shake = shake
elseif Type == 'ShakeH' then
shake.path:SetDuration(2)
obj.shakeh = shake
end
for i = 1, 6 do
shake.path[i] = shake.path:CreateControlPoint()
shake.path[i]:SetOrder(i)
if Type == 'Shake' then
shake.path[i]:SetOffset(E:RandomAnimShake(i))
else
shake.path[i]:SetOffset(E.AnimShakeH[i], 0)
end
end
else
local x, y, duration, customName = ...
if not customName then customName = 'anim' end
local anim = obj:CreateAnimationGroup('Move_In')
obj[customName] = anim
anim.in1 = anim:CreateAnimation('Translation')
anim.in1:SetDuration(0)
anim.in1:SetOrder(1)
anim.in1:SetOffset(E:Scale(x), E:Scale(y))
anim.in2 = anim:CreateAnimation('Translation')
anim.in2:SetDuration(duration)
anim.in2:SetOrder(2)
anim.in2:SetSmoothing('OUT')
anim.in2:SetOffset(E:Scale(-x), E:Scale(-y))
anim.out1 = obj:CreateAnimationGroup('Move_Out')
anim.out1:SetScript('OnFinished', function() obj:Hide() end)
anim.out2 = anim.out1:CreateAnimation('Translation')
anim.out2:SetDuration(duration)
anim.out2:SetOrder(1)
anim.out2:SetSmoothing('IN')
anim.out2:SetOffset(E:Scale(x), E:Scale(y))
end
end
function E:ScaleAnimation(object, duration)
if not object.anim then
E:SetUpAnimGroup(object, "Scale")
end
if not object.anim.playing then
object.anim.scaleOut:SetDuration(duration)
object.anim.scaleIn:SetDuration(duration)
object.anim:Play()
object.anim.playing = true
end
end
function E:StopScaleAnimation(object)
if object.anim and object.anim.playing then
object.anim:Stop()
object.anim.playing = nil;
end
end
function E:Shake(obj)
if not obj.shake then
E:SetUpAnimGroup(obj, 'Shake')
end
obj.shake:Play()
end
function E:StopShake(obj)
if obj.shake then
obj.shake:Finish()
end
end
function E:ShakeHorizontal(obj)
if not obj.shakeh then
E:SetUpAnimGroup(obj, 'ShakeH')
end
obj.shakeh:Play()
end
function E:StopShakeHorizontal(obj)
if obj.shakeh then
obj.shakeh:Finish()
end
end
function E:Flash(obj, duration, loop)
if not obj.anim then
E:SetUpAnimGroup(obj, loop and 'FlashLoop' or 'Flash')
end
if not obj.anim:IsPlaying() then
obj.anim.fadein:SetDuration(duration)
obj.anim.fadeout:SetDuration(duration)
obj.anim:Play()
end
end
function E:StopFlash(obj)
if obj.anim and obj.anim:IsPlaying() then
obj.anim:Stop()
end
end
function E:SlideIn(obj, customName)
if not customName then customName = 'anim' end
if not obj[customName] then return end
obj[customName].out1:Stop()
obj[customName]:Play()
obj:Show()
end
function E:SlideOut(obj, customName)
if not customName then customName = 'anim' end
if not obj[customName] then return end
obj[customName]:Finish()
obj[customName]:Stop()
obj[customName].out1:Play()
end
local FADEFRAMES, FADEMANAGER = {}, CreateFrame('FRAME')
FADEMANAGER.delay = 0.05
function E:UIFrameFade_OnUpdate(elapsed)
FADEMANAGER.timer = (FADEMANAGER.timer or 0) + elapsed
if FADEMANAGER.timer > FADEMANAGER.delay then
FADEMANAGER.timer = 0
for frame, info in next, FADEFRAMES do
-- Reset the timer if there isn't one, this is just an internal counter
if frame:IsVisible() then
info.fadeTimer = (info.fadeTimer or 0) + (elapsed + FADEMANAGER.delay)
else
info.fadeTimer = info.timeToFade + 1
end
-- If the fadeTimer is less then the desired fade time then set the alpha otherwise hold the fade state, call the finished function, or just finish the fade
if info.fadeTimer < info.timeToFade then
if info.mode == 'IN' then
frame:SetAlpha((info.fadeTimer / info.timeToFade) * info.diffAlpha + info.startAlpha)
else
frame:SetAlpha(((info.timeToFade - info.fadeTimer) / info.timeToFade) * info.diffAlpha + info.endAlpha)
end
else
frame:SetAlpha(info.endAlpha)
-- If there is a fadeHoldTime then wait until its passed to continue on
if info.fadeHoldTime and info.fadeHoldTime > 0 then
info.fadeHoldTime = info.fadeHoldTime - elapsed
else
-- Complete the fade and call the finished function if there is one
E:UIFrameFadeRemoveFrame(frame)
if info.finishedFunc then
if info.finishedArgs then
info.finishedFunc(unpack(info.finishedArgs))
else -- optional method
info.finishedFunc(info.finishedArg1, info.finishedArg2, info.finishedArg3, info.finishedArg4, info.finishedArg5)
end
if not info.finishedFuncKeep then
info.finishedFunc = nil
end
end
end
end
end
if not next(FADEFRAMES) then
FADEMANAGER:SetScript('OnUpdate', nil)
end
end
end
-- Generic fade function
function E:UIFrameFade(frame, info)
if not frame or frame:IsForbidden() then return end
frame.fadeInfo = info
if not info.mode then
info.mode = 'IN'
end
if info.mode == 'IN' then
if not info.startAlpha then info.startAlpha = 0 end
if not info.endAlpha then info.endAlpha = 1 end
if not info.diffAlpha then info.diffAlpha = info.endAlpha - info.startAlpha end
else
if not info.startAlpha then info.startAlpha = 1 end
if not info.endAlpha then info.endAlpha = 0 end
if not info.diffAlpha then info.diffAlpha = info.startAlpha - info.endAlpha end
end
frame:SetAlpha(info.startAlpha)
if not frame:IsProtected() then
frame:Show()
end
if not FADEFRAMES[frame] then
FADEFRAMES[frame] = info -- read below comment
FADEMANAGER:SetScript('OnUpdate', E.UIFrameFade_OnUpdate)
else
FADEFRAMES[frame] = info -- keep these both, we need this updated in the event its changed to another ref from a plugin or sth, don't move it up!
end
end
-- Convenience function to do a simple fade in
function E:UIFrameFadeIn(frame, timeToFade, startAlpha, endAlpha)
if not frame or frame:IsForbidden() then return end
if frame.FadeObject then
frame.FadeObject.fadeTimer = nil
else
frame.FadeObject = {}
end
frame.FadeObject.mode = 'IN'
frame.FadeObject.timeToFade = timeToFade
frame.FadeObject.startAlpha = startAlpha
frame.FadeObject.endAlpha = endAlpha
frame.FadeObject.diffAlpha = endAlpha - startAlpha
E:UIFrameFade(frame, frame.FadeObject)
end
-- Convenience function to do a simple fade out
function E:UIFrameFadeOut(frame, timeToFade, startAlpha, endAlpha)
if not frame or frame:IsForbidden() then return end
if frame.FadeObject then
frame.FadeObject.fadeTimer = nil
else
frame.FadeObject = {}
end
frame.FadeObject.mode = 'OUT'
frame.FadeObject.timeToFade = timeToFade
frame.FadeObject.startAlpha = startAlpha
frame.FadeObject.endAlpha = endAlpha
frame.FadeObject.diffAlpha = startAlpha - endAlpha
E:UIFrameFade(frame, frame.FadeObject)
end
function E:UIFrameFadeRemoveFrame(frame)
if frame and FADEFRAMES[frame] then
if frame.FadeObject then
frame.FadeObject.fadeTimer = nil
end
FADEFRAMES[frame] = nil
end
end
|
function GetBindingByKey(k)
end;
function SetBinding(keybind, action)
end;
function IsAltKeyDown()
end;
function IsControlKeyDown()
end;
function IsShiftKeyDown()
end;
|
local cmd ={}
function cmd.add( )
local a = 4772.22465
a=math.modf(a)
print("aaaa!!!!!!!!!!fsdfsdfaaadfdsf?"..a.." ")
end
function cmd.sub( )
end
return cmd |
-- Author: Lpsd (https://github.com/Lpsd/)
-- See the LICENSE file @ root directory
-- *******************************************************************
Event = inherit(Class)
-- *******************************************************************
function Event:constructor(eventName, allowRemoteTrigger)
self.name = eventName
self.allowRemoteTrigger = allowRemoteTrigger
self.handlers = {}
dxDebug("Event added", eventName)
end
function Event:addHandler(dxElement, handlerFunction)
if (not dxElement) or (not dxElement.__dx) then
if (dxElement ~= root) then
return dxDebug("[Event:addHandler] Invalid dx-element supplied") and false
end
end
if (type(handlerFunction) ~= "function") then
return dxDebug("[Event:addHandler] Invalid handler function supplied") and false
end
if (not self.handlers[dxElement]) then
self.handlers[dxElement] = {}
end
local index = (#self.handlers[dxElement] + 1)
self.handlers[dxElement][index] = handlerFunction
return true
end
function Event:removeHandler(dxElement, handlerFunction)
if (not dxElement) or (not dxElement.__dx) then
if (dxElement ~= root) then
return dxDebug("[Event:removeHandler] Invalid dx-element supplied") and false
end
end
if (type(handlerFunction) ~= "function") then
return dxDebug("[Event:removeHandler] Invalid handler function supplied") and false
end
if (not self.handlers[dxElement]) then
return false
end
for i, func in ipairs(self.handlers[dxElement]) do
if (func == handlerFunction) then
self.handlers[dxElement][i] = nil
return true
end
end
return false
end
-- *******************************************************************
function Event:getHandlerFunctions(sourceElement)
local functions = {}
if (not sourceElement) or (not sourceElement.__dx) then
if (sourceElement ~= root) then
return dxDebug("[Event:getHandlerFunctions] Invalid dx-element supplied") and false
end
end
if (not self.handlers[sourceElement]) then
return false
end
if (sourceElement == root) then
for element, funcList in pairs(self.handlers) do
for i, func in ipairs(funcList) do
functions[#functions+1] = func
end
end
else
for i, func in ipairs(self.handlers[sourceElement]) do
functions[#functions+1] = func
end
end
return functions
end |
local language = "korean";
local PLUGIN = PLUGIN;
PLUGIN:AddPluginLanguage("speed", "속도", language);
PLUGIN:AddPluginLanguage("stamina", "지구력", language);
PLUGIN:AddPluginLanguage("speed_desc", "얼마나 빠르게 뛸 수 있는지에 대한 능력치입니다.", language);
PLUGIN:AddPluginLanguage("stamina_desc", "얼마나 오래 뛸 수 있는지에 대한 능력치입니다.", language); |
---------------------------
-- Vendor Upgrade System --
---------------------------
local old_vendor_mods = string.split((minetest.setting_get("fancy_vend_old_vendor_mods") or ""), ",")
local old_vendor_mods_table = {}
for i in pairs(old_vendor_mods) do
old_vendor_mods_table[old_vendor_mods[i]] = true
end
local base_upgrade_template = {
description = "Shop Upgrade (Try and place to upgrade)",
legacy_facedir_simple = true,
paramtype2 = "facedir",
groups = {choppy = 2, oddly_breakable_by_hand = 2, not_in_creative_inventory = 1},
is_ground_content = false,
light_source = 8,
sounds = default.node_sound_wood_defaults(),
drop = fancy_vend.drop_vendor,
tiles = {
"player_vend.png", "player_vend.png",
"player_vend.png", "player_vend.png",
"player_vend.png", "upgrade_front.png",
},
on_place = function(itemstack)
return ItemStack(fancy_vend.drop_vendor.." "..itemstack:get_count())
end,
allow_metadata_inventory_move = function(pos, _, _, _, _, count, player)
local meta = minetest.get_meta(pos)
if player:get_player_name() ~= meta:get_string("owner") then return 0 end
return count
end,
allow_metadata_inventory_put = function(pos, _, _, stack, player)
local meta = minetest.get_meta(pos)
if player:get_player_name() ~= meta:get_string("owner") then return 0 end
return stack:get_count()
end,
allow_metadata_inventory_take = function(pos, _, _, stack, player)
local meta = minetest.get_meta(pos)
if player:get_player_name() ~= meta:get_string("owner") then return 0 end
return stack:get_count()
end,
}
local clear_craft_vendors = {}
if old_vendor_mods_table["currency"] then
local currency_template = table.copy(base_upgrade_template)
currency_template.can_dig = function(pos, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:is_empty("stock") and
inv:is_empty("customers_gave") and
inv:is_empty("owner_wants") and
inv:is_empty("owner_gives") and
(meta:get_string("owner") == player:get_player_name() or
minetest.check_player_privs(player:get_player_name(), {protection_bypass = true}))
end
currency_template.on_rightclick = function(pos, _, clicker)
local meta = minetest.get_meta(pos)
local list_name = "nodemeta:"..pos.x..","..pos.y..","..pos.z
if clicker:get_player_name() == meta:get_string("owner") then
minetest.show_formspec(clicker:get_player_name(),"fancy_vend:currency_shop_formspec",
"size[8,9.5]"..
"label[0,0;".."Customers gave:".."]"..
"list["..list_name..";customers_gave;0,0.5;3,2;]"..
"label[0,2.5;".."Your stock:".."]"..
"list["..list_name..";stock;0,3;3,2;]"..
"label[5,0;".."You want:".."]"..
"list["..list_name..";owner_wants;5,0.5;3,2;]"..
"label[5,2.5;".."In exchange, you give:".."]"..
"list["..list_name..";owner_gives;5,3;3,2;]"..
"list[current_player;main;0,5.5;8,4;]"
)
end
end
minetest.register_node(":currency:shop", currency_template)
table.insert(clear_craft_vendors, "currency:shop")
end
if old_vendor_mods_table["easyvend"] then
local nodes = {"easyvend:vendor", "easyvend:vendor_on", "easyvend:depositor", "easyvend:depositor_on"}
for i in pairs(nodes) do
minetest.register_node(":"..nodes[i], base_upgrade_template)
table.insert(clear_craft_vendors, nodes[i])
end
end
if old_vendor_mods_table["vendor"] then
local nodes = {"vendor:vendor", "vendor:depositor"}
for i in pairs(nodes) do
minetest.register_node(":"..nodes[i], base_upgrade_template)
table.insert(clear_craft_vendors, nodes[i])
end
end
if old_vendor_mods_table["money"] then
local money_template = table.copy(base_upgrade_template)
money_template.can_dig = function(pos, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
return inv:is_empty("main") and
(meta:get_string("owner") == player:get_player_name() or
minetest.check_player_privs(player:get_player_name(), {protection_bypass = true}))
end
money_template.on_rightclick = function(pos, _, clicker)
local meta = minetest.get_meta(pos)
local list_name = "nodemeta:"..pos.x..","..pos.y..","..pos.z
if clicker:get_player_name() == meta:get_string("owner") then
minetest.show_formspec(clicker:get_player_name(),"fancy_vend:money_shop_formspec",
"size[8,10;]"..
"list["..list_name..";main;0,0;8,4;]"..
"list[current_player;main;0,6;8,4;]"
)
end
end
local nodes = {"money:barter_shop", "money:shop", "money:admin_shop", "money:admin_barter_shop"}
for i in pairs(nodes) do
minetest.register_node(":"..nodes[i], money_template)
table.insert(clear_craft_vendors, nodes[i])
end
end
for i_n in pairs(clear_craft_vendors) do
local currency_crafts = minetest.get_all_craft_recipes(i_n)
if currency_crafts then
for i in pairs(currency_crafts) do
minetest.clear_craft(currency_crafts[i])
end
end
end
|
-- Pikmin (NTSC v1.1)
local core = require("games.core")
local game = {
memorymap = {}
}
core.loadGenericControllerMap(0x8039D400, game)
return game |
TOOL.Base = "base_brush"
TOOL.Description = "Kill players on touch."
--------------------------------------------------------------------------------
TOOL.TextureColor = Color(255,0,0,200)
TOOL.TextureText = "Kill"
--------------------------------------------------------------------------------
function TOOL:EntSetup( ent )
ent:SetSolidFlags( FSOLID_CUSTOMBOXTEST )
if SERVER then ent:SetTrigger( true ) end
end
function TOOL:EntStartTouch( ent )
if ent:IsPlayer() then
ent:Kill()
return
end
end
function TOOL:EntShouldCollide( ent )
return false
end
--------------------------------------------------------------------------------
|
local ADDON_NAME, Mod = ...
local MAX_ICON_INDEX = 8
local CLASS_MARKS = {
-- Stars
["ROGUE"] = 1,
["WARRIOR"] = 1,
-- Circles
["DRUID"] = 2,
-- Diamonds
["WARLOCK"] = 3,
["DEMONHUNTER"] = 3,
["PALADIN"] = 3,
-- Triangles
["MONK"] = 4,
["HUNTER"] = 4,
-- Moons
["PRIEST"] = 5,
-- Squares
["SHAMAN"] = 6,
["MAGE"] = 6,
-- CROSSES
["DEATHKNIGHT"] = 7
-- Skulls
}
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PVP_MATCH_ACTIVE")
frame:RegisterEvent("GROUP_ROSTER_UPDATE")
frame:SetScript("OnEvent", function (self, event, ...)
local handler = self[event]
handler(self, ...)
end)
function frame:ADDON_LOADED(addonName)
if addonName ~= ADDON_NAME then
return;
end
-- Register additional events here as needed
end
function frame:PVP_MATCH_ACTIVE(...)
Mod:MarkPlayers()
end
function frame:GROUP_ROSTER_UPDATE(...)
-- Wait 1.5 seconds for the players to load in. If we don't wait, the API will return nil for the player's class and a proper mark won't be found
C_Timer.After(1.5, function ()
Mod:MarkPlayers()
end)
end
local function GetClassMark(unitId)
local className, classId = UnitClassBase(unitId)
local mark = CLASS_MARKS[className]
if mark == nil then
print("WARNING: Could not find a class mark for class " .. (className or "unknown"), className, unitId)
-- Return a skull which is not used by any class
return 8
end
return mark
end
function Mod:MarkPlayers(force)
-- A function to log debug messages if force is true
function Log (...)
if force then
print(...)
end
end
-- Check which kind of instance the user is in
local instanceName, instanceType = GetInstanceInfo()
-- Only mark players if we're in an arena match or rbg
if not force and instanceType ~= "arena" and instanceType ~= "ratedbg" then
Log("User is not in an arena or ratedbg, and force is not true. Skipping marks.")
return;
end
-- Keep track of which marks have been used
local usedMarks = { }
-- Keep track of units that don't get assigned a mark on first pass because of duplicate mark usage
local skippedUnits = { }
local function TryMarkUnit(unit, markOverride)
Log("Attempting to mark unit", unit)
if not UnitExists(unit) then
Log("Unit "..(unit or "nil").." does not exist")
return;
end
-- Check if the unit is already using a mark
local existingMark = GetRaidTargetIndex(unit)
if existingMark then
Log("Unit", unit, "is already marked with", existingMark)
usedMarks[existingMark] = unit
return;
end
-- Get the desired mark for this unit and apply it if it hasn't been used
local mark = markOverride or GetClassMark(unit)
if usedMarks[mark] == nil then
Log("Setting mark for unit "..unit.." to "..mark)
SetRaidTarget(unit, mark)
usedMarks[mark] = unit
else
Log("Desired mark", mark, "for unit", unit, "is already in use")
table.insert(skippedUnits, unit)
end
end
if instanceType == "ratedbg" then
-- Only 10 players in RBGs
for i = 1, 10 do
local unit = "raid" .. i
local role = UnitGroupRolesAssigned(unit)
-- Only mark healers and tanks in RBGs
if role == "HEALER" or role == "TANK" then
TryMarkUnit("raid" .. i)
else
Log("Unit", unit, "is not a tank or healer. Skipping mark.")
end
end
else
-- We mark all players in the party
local units = {
"player",
"party1",
"party2",
"party3",
"party4"
}
for i = 1, #units do
TryMarkUnit(units[i])
end
end
-- Iterate over any players who weren't assigned a mark because of duplicate classes
-- (e.g. if two shamans, one was assigned a square and the other was skipped because it can't also be assigned a square)
for key, unit in pairs(skippedUnits) do
local unit = skippedUnits[i]
-- Find a mark that hasn't been used yet
for i = 1, MAX_ICON_INDEX do
if not usedMarks[i] then
TryMarkUnit(unit, i)
break;
end
end
end
end
|
-- Wifi static setup
wifi.setmode(wifi.STATION)
ssid='MB'
password= '******'
station_cfg={}
station_cfg.ssid=ssid
station_cfg.pwd=password
station_cfg.save=true
wifi.sta.config(station_cfg)
wifi.sta.connect()
tmr.alarm(1,2000, 1, function()
if wifi.sta.getip()==nil then
print(" Wait for IP --> "..wifi.sta.status())
else
print("New IP address is "..wifi.sta.getip())
tmr.stop(1)
dofile("boot.lua")
end
end)
print('init.lua ready')
--if file.open("list_AP.lua") then
-- print(file.read())
-- file.close()
--end
function listap(t)
for k,v in pairs(t) do
print(k.." : "..v)
end
end
wifi.sta.getap(listap)
print(wifi.sta.getapinfo())
print(wifi.sta.getconfig())
|
WiFiLED = {}
node.compile("WiFiLED_ws2812.lua")
dofile("WiFiLED_ws2812.lc")
node.compile("WiFiLED_mqtt.lua")
dofile("WiFiLED_mqtt.lc")
---[[
node.compile("WiFiLED_webServer.lua")
dofile("WiFiLED_webServer.lc");--]]
--dofile("WiFiLED_webServer.lua");
node.compile("WiFiLED_endUserSetup.lua")
dofile("WiFiLED_endUserSetup.lc")
local function init()
print("*** Initialising ***")
initWs2812()
local wifiMode = wifi.getdefaultmode()
local wifiStatus = wifi.sta.status()
startWifiEventMonitoring()
if wifiMode == wifi.SOFTAP or wifiMode == wifi.STATIONAP then
print("In either SOFTAP or STATIONAP mode, so starting config portal")
startEndUserSetup()
end
if(wifiStatus == wifi.STA_GOTIP) then
print(" ... already connected, so starting server")
startServer()
connectToMQTT()
end
end
function startWifiEventMonitoring()
print("... starting wifi event monitoring")
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function()
print("Connected wifi")
end)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function()
print("Disconnected wifi")
end)
wifi.eventmon.register(wifi.eventmon.STA_AUTHMODE_CHANGE, function()
print("Wifi AuthMode changed")
end)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function()
print("IP address: " .. wifi.sta.getip())
startServer()
connectToMQTT()
end)
wifi.eventmon.register(wifi.eventmon.STA_DHCP_TIMEOUT, function()
print(" - DHCP timeout ... please check your network DHCP settings and restart")
end)
wifi.eventmon.register(wifi.eventmon.AP_STACONNECTED, function()
print(" - New access point client connected ... no action currently defined")
end)
wifi.eventmon.register(wifi.eventmon.AP_STADISCONNECTED, function()
print(" - Access point client disconnected ... no action currently defined")
end)
--wifi.eventmon.register(wifi.eventmon.AP_PROBEREQRECVED, ...)
end
init() |
local ForceCamera = {
onfoot = 1,
invehicles = 4
}
-- types: (0)close (1)near (2)far (3) cinematic?? (4)first person
Citizen.CreateThread(function()
SetFollowPedCamViewMode(ForceCamera.onfoot)
SetFollowVehicleCamViewMode(ForceCamera.invehicles)
while true do
Citizen.Wait(0)
if NetworkIsPlayerActive(PlayerId()) then
if IsPedOnFoot(GetPlayerPed(-1)) then
DisableControlAction(0, 0, true)
SetFollowPedCamViewMode(ForceCamera.onfoot)
SetFollowVehicleCamViewMode(ForceCamera.invehicles)
else
DisableControlAction(0, 0, true)
SetFollowPedCamViewMode(ForceCamera.invehicles)
SetFollowVehicleCamViewMode(ForceCamera.invehicles)
end
end
end
end)
|
local __exports = LibStub:NewLibrary("ovale/Scripts", 10000)
if not __exports then return end
local __class = LibStub:GetLibrary("tslib").newClass
local AceConfig = LibStub:GetLibrary("AceConfig-3.0", true)
local AceConfigDialog = LibStub:GetLibrary("AceConfigDialog-3.0", true)
local __Options = LibStub:GetLibrary("ovale/Options")
local OvaleOptions = __Options.OvaleOptions
local __Localization = LibStub:GetLibrary("ovale/Localization")
local L = __Localization.L
local __PaperDoll = LibStub:GetLibrary("ovale/PaperDoll")
local OvalePaperDoll = __PaperDoll.OvalePaperDoll
local __Ovale = LibStub:GetLibrary("ovale/Ovale")
local Ovale = __Ovale.Ovale
local aceEvent = LibStub:GetLibrary("AceEvent-3.0", true)
local format = string.format
local gsub = string.gsub
local lower = string.lower
local pairs = pairs
local OvaleScriptsBase = Ovale:NewModule("OvaleScripts", aceEvent)
local DEFAULT_NAME = "Ovale"
local DEFAULT_DESCRIPTION = L["Script défaut"]
local CUSTOM_NAME = "custom"
local CUSTOM_DESCRIPTION = L["Script personnalisé"]
local DISABLED_NAME = "Disabled"
local DISABLED_DESCRIPTION = L["Disabled"]
do
local defaultDB = {
code = "",
source = "Ovale",
showHiddenScripts = false
}
local actions = {
code = {
name = L["Code"],
type = "execute",
func = function()
local appName = __exports.OvaleScripts:GetName()
AceConfigDialog:SetDefaultSize(appName, 700, 550)
AceConfigDialog:Open(appName)
end
}
}
for k, v in pairs(defaultDB) do
OvaleOptions.defaultDB.profile[k] = v
end
for k, v in pairs(actions) do
OvaleOptions.options.args.actions.args[k] = v
end
OvaleOptions:RegisterOptions(__exports.OvaleScripts)
end
local OvaleScriptsClass = __class(OvaleScriptsBase, {
constructor = function(self)
self.script = {}
OvaleScriptsBase.constructor(self)
end,
OnInitialize = function(self)
self:CreateOptions()
self:RegisterScript(nil, nil, DEFAULT_NAME, DEFAULT_DESCRIPTION, nil, "script")
self:RegisterScript(Ovale.playerClass, nil, CUSTOM_NAME, CUSTOM_DESCRIPTION, Ovale.db.profile.code, "script")
self:RegisterScript(nil, nil, DISABLED_NAME, DISABLED_DESCRIPTION, nil, "script")
self:RegisterMessage("Ovale_StanceChanged")
end,
OnDisable = function(self)
self:UnregisterMessage("Ovale_StanceChanged")
end,
Ovale_StanceChanged = function(self, event, newStance, oldStance)
end,
GetDescriptions = function(self, scriptType)
local descriptionsTable = {}
for name, script in pairs(self.script) do
if ( not scriptType or script.type == scriptType) and ( not script.specialization or OvalePaperDoll:IsSpecialization(script.specialization) or script.specialization == "all") then
if name == DEFAULT_NAME then
descriptionsTable[name] = script.desc .. " (" .. self:GetScriptName(name) .. ")"
else
descriptionsTable[name] = script.desc
end
end
end
return descriptionsTable
end,
RegisterScript = function(self, className, specialization, name, description, code, scriptType)
if not className or className == Ovale.playerClass then
self.script[name] = self.script[name] or {}
local script = self.script[name]
script.type = scriptType or "script"
script.desc = description or name
script.specialization = specialization
script.code = code or ""
end
end,
UnregisterScript = function(self, name)
self.script[name] = nil
end,
SetScript = function(self, name)
local oldSource = Ovale.db.profile.source
if oldSource ~= name then
Ovale.db.profile.source = name
self:SendMessage("Ovale_ScriptChanged")
end
end,
GetDefaultScriptName = function(self, className, specialization)
local name
if className == "DEATHKNIGHT" then
if specialization == "blood" then
name = "icyveins_deathknight_blood"
elseif specialization == "frost" then
name = "sc_death_knight_frost_t19"
elseif specialization == "unholy" then
name = "sc_death_knight_unholy_t19"
end
elseif className == "DEMONHUNTER" then
if specialization == "vengeance" then
name = "icyveins_demonhunter_vengeance"
elseif specialization == "havoc" then
name = "sc_demon_hunter_havoc_t19"
end
elseif className == "DRUID" then
if specialization == "restoration" then
name = DISABLED_NAME
elseif specialization == "guardian" then
name = "icyveins_druid_guardian"
elseif specialization == "feral" then
name = "shmoodude_druid_feral"
end
elseif className == "MONK" then
if specialization == "mistweaver" then
name = DISABLED_NAME
elseif specialization == "brewmaster" then
name = "icyveins_monk_brewmaster"
end
elseif className == "PALADIN" then
if specialization == "holy" then
name = "icyveins_paladin_holy"
elseif specialization == "protection" then
name = "icyveins_paladin_protection"
end
elseif className == "PRIEST" then
if specialization == "discipline" then
name = "icyveins_priest_discipline"
elseif specialization == "holy" then
name = DISABLED_NAME
end
elseif className == "SHAMAN" then
if specialization == "restoration" then
name = DISABLED_NAME
end
elseif className == "WARRIOR" then
if specialization == "protection" then
name = "icyveins_warrior_protection"
end
end
if not name and specialization then
name = format("sc_%s_%s_t19", lower(className), specialization)
end
if not (name and self.script[name]) then
name = DISABLED_NAME
end
return name
end,
GetScriptName = function(self, name)
return (name == DEFAULT_NAME) and self:GetDefaultScriptName(Ovale.playerClass, OvalePaperDoll:GetSpecialization()) or name
end,
GetScript = function(self, name)
name = self:GetScriptName(name)
if name and self.script[name] then
return self.script[name].code
end
end,
CreateOptions = function(self)
local options = {
name = Ovale:GetName() .. " " .. L["Script"],
type = "group",
args = {
source = {
order = 10,
type = "select",
name = L["Script"],
width = "double",
values = function(info)
local scriptType = not Ovale.db.profile.showHiddenScripts and "script"
return __exports.OvaleScripts:GetDescriptions(scriptType)
end,
get = function(info)
return Ovale.db.profile.source
end,
set = function(info, v)
self:SetScript(v)
end
},
script = {
order = 20,
type = "input",
multiline = 25,
name = L["Script"],
width = "full",
disabled = function()
return Ovale.db.profile.source ~= CUSTOM_NAME
end,
get = function(info)
local code = __exports.OvaleScripts:GetScript(Ovale.db.profile.source)
code = code or ""
return gsub(code, " ", " ")
end,
set = function(info, v)
__exports.OvaleScripts:RegisterScript(Ovale.playerClass, nil, CUSTOM_NAME, CUSTOM_DESCRIPTION, v, "script")
Ovale.db.profile.code = v
self:SendMessage("Ovale_ScriptChanged")
end
},
copy = {
order = 30,
type = "execute",
name = L["Copier sur Script personnalisé"],
disabled = function()
return Ovale.db.profile.source == CUSTOM_NAME
end,
confirm = function()
return L["Ecraser le Script personnalisé préexistant?"]
end,
func = function()
local code = __exports.OvaleScripts:GetScript(Ovale.db.profile.source)
__exports.OvaleScripts:RegisterScript(Ovale.playerClass, nil, CUSTOM_NAME, CUSTOM_DESCRIPTION, code, "script")
Ovale.db.profile.source = CUSTOM_NAME
Ovale.db.profile.code = __exports.OvaleScripts:GetScript(CUSTOM_NAME)
self:SendMessage("Ovale_ScriptChanged")
end
},
showHiddenScripts = {
order = 40,
type = "toggle",
name = L["Show hidden"],
get = function(info)
return Ovale.db.profile.showHiddenScripts
end,
set = function(info, value)
Ovale.db.profile.showHiddenScripts = value
end
}
}
}
local appName = self:GetName()
AceConfig:RegisterOptionsTable(appName, options)
AceConfigDialog:AddToBlizOptions(appName, L["Script"], Ovale:GetName())
end,
})
__exports.OvaleScripts = OvaleScriptsClass()
|
--[[
Provides Elasticserach endpoint authorization based on rules in Lua and authenticated user
See the `nginx_authorize_by_lua.conf` for the Nginx config.
Synopsis:
$ /usr/local/openresty/nginx/sbin/nginx -p $PWD/nginx/ -c $PWD/nginx_authorize_by_lua.conf
$ curl -i -X HEAD 'http://localhost:8080'
HTTP/1.1 401 Unauthorized
curl -i -X HEAD 'http://all:all@localhost:8080'
HTTP/1.1 200 OK
curl -i -X GET 'http://all:all@localhost:8080'
HTTP/1.1 403 Forbidden
curl -i -X GET 'http://user:user@localhost:8080'
HTTP/1.1 200 OK
curl -i -X GET 'http://user:user@localhost:8080/_search'
HTTP/1.1 200 OK
curl -i -X POST 'http://user:user@localhost:8080/_search'
HTTP/1.1 200 OK
curl -i -X GET 'http://user:user@localhost:8080/_aliases'
HTTP/1.1 200 OK
curl -i -X POST 'http://user:user@localhost:8080/_aliases'
HTTP/1.1 403 Forbidden
curl -i -X POST 'http://user:user@localhost:8080/myindex/mytype/1' -d '{"title" : "Test"}'
HTTP/1.1 403 Forbidden
curl -i -X DELETE 'http://user:user@localhost:8080/myindex/'
HTTP/1.1 403 Forbidden
curl -i -X POST 'http://admin:admin@localhost:8080/myindex/mytype/1' -d '{"title" : "Test"}'
HTTP/1.1 200 OK
curl -i -X DELETE 'http://admin:admin@localhost:8080/myindex/mytype/1'
HTTP/1.1 200 OK
curl -i -X DELETE 'http://admin:admin@localhost:8080/myindex/'
HTTP/1.1 200 OK
]]--
-- authorization rules
local restrictions = {
all = {
["^/$"] = { "HEAD" }
},
user = {
["^/$"] = { "GET" },
["^/?[^/]*/?[^/]*/_search"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/_msearch"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/_validate/query"] = { "GET", "POST" },
["/_aliases"] = { "GET" },
["/_cluster.*"] = { "GET" },
["/app.*"] = { "GET" },
["/ui.*"] = { "GET" },
["/bundles.*"] = { "GET" },
["/api.*"] = { "GET" },
["/plugins.*"] = { "GET" },
["/es_admin.*"] = { "GET", "POST" },
["/static.*"] = { "GET" }
},
admin = {
["^/?[^/]*/?[^/]*/_bulk"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/_refresh"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/?[^/]*/_create"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/?[^/]*/_update"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/?.*"] = { "GET", "POST", "PUT", "DELETE" },
["^/?[^/]*/?[^/]*$"] = { "GET", "POST", "PUT", "DELETE" },
["/_aliases"] = { "GET", "POST" },
["/_cluster.*"] = { "GET" },
["/app.*"] = { "GET" },
["/ui.*"] = { "GET" },
["/bundles.*"] = { "GET" },
["/api.*"] = { "GET", "POST" },
["/plugins.*"] = { "GET" },
["/es_admin.*"] = { "GET", "POST" },
["/static.*"] = { "GET" },
["/admin.*"] = { "GET" }
},
g2p = {
["^/$"] = { "GET" },
["^/demo-ui.*$"] = { "GET" },
["^/*.j*$"] = { "GET" },
["^/?[^/]*/?[^/]*/_search"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/_msearch"] = { "GET", "POST" },
["^/?[^/]*/?[^/]*/_validate/query"] = { "GET", "POST" },
["/_aliases"] = { "GET" },
["/_cluster.*"] = { "GET" },
["/app.*"] = { "GET" },
["/ui.*"] = { "GET" },
["/bundles.*"] = { "GET" },
["/api.*"] = { "GET", "POST" },
["/plugins.*"] = { "GET" },
["/es_admin.*"] = { "GET" },
["/es_admin.*/_search"] = { "GET", "POST" },
["/es_admin.*/_msearch"] = { "GET", "POST" },
["/es_admin.*/_mget"] = { "GET", "POST" },
["/static.*"] = { "GET" },
["/kibana"] = { "GET", "POST" },
["/v1.*"] = { "GET", "POST" }
}
}
-- get authenticated user as role
local role = ngx.var.remote_user
ngx.log(ngx.DEBUG, role)
-- exit 403 when no matching role has been found
if restrictions[role] == nil then
-- ngx.header.content_type = 'text/plain'
-- ngx.log(ngx.WARN, "Unknown role ["..role.."]")
-- ngx.status = 403
-- ngx.say("403 Forbidden: You don\'t have access to this resource.")
-- return ngx.exit(403)
role = 'g2p'
end
-- get URL
local uri = ngx.var.uri
ngx.log(ngx.DEBUG, uri)
-- get method
local method = ngx.req.get_method()
ngx.log(ngx.DEBUG, method)
local allowed = false
for path, methods in pairs(restrictions[role]) do
-- path matched rules?
local p = string.match(uri, path)
local m = nil
-- method matched rules?
for _, _method in pairs(methods) do
m = m and m or string.match(method, _method)
end
if p and m then
allowed = true
-- ngx.log(ngx.NOTICE, method.." "..uri.." matched: "..tostring(m).." "..tostring(path).." for "..role)
break
end
ngx.log(ngx.WARN, method.." "..uri.." NO matched: m:"..tostring(m).." path:"..tostring(path).." for "..role)
end
if not allowed then
ngx.header.content_type = 'text/plain'
ngx.log(ngx.WARN, "Role ["..role.."] not allowed to access the resource ["..method.." "..uri.."]")
ngx.status = 403
ngx.say("403 Forbidden: You don\'t have access to this resource.")
return ngx.exit(403)
end
|
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local packages = script.Parent.Parent
local Isotope = require(packages:WaitForChild("isotope"))
local math = require(packages:WaitForChild("math"))
local BoardFrame = {}
BoardFrame.__index = BoardFrame
setmetatable(BoardFrame, Isotope)
function BoardFrame.new(config)
local self = Isotope.new()
setmetatable(self, BoardFrame)
self.Color = self:Import(config.Color, Color3.new(0.3,0,0))
self.Size = self:Import(config.Size, UDim2.fromScale(1,1))
self.Position = self:Import(config.Position, UDim2.fromScale(0.5,0.5))
self.AnchorPoint = self:Import(config.AnchorPoint, Vector2.new(0.5,0.5))
self.PixelsPerStud = self:Import(config.PixelsPerStud, 20)
self.CanvasPosition = self:Import(config.CanvasPosition, Vector2.new(0,0))
self.CanvasTransparency = self:Import(config.CanvasTransparency, 0)
self.CanvasColor = self:Import(config.CanvasColor, Color3.new(1,1,1))
self.CanvasMaterial = self:Import(config.CanvasMaterial, "SmoothPlastic")
self.CanvasMaterialVariant = self:Import(config.CanvasMaterialVariant, "")
self.LockPosition = self:Import(config.LockPosition, false)
self.LockZoom = self:Import(config.LockZoom, false)
self.Zoom = self:Import(config.Zoom, 1)
self.MinZoom = self:Import(config.MinZoom, 1)
self.MaxZoom = self:Import(config.MaxZoom, 10)
self.ZoomSpeed = self:Import(config.ZoomSpeed, 4)
self.Delta = self._Fuse.Value(1/60)
self.AbsoluteSize = self._Fuse.Value(Vector2.new(0,0))
self.CanvasSize = self._Fuse.Computed(self.AbsoluteSize, self.PixelsPerStud, function(absSize, pxRatio)
return absSize / pxRatio
end) --self:Import(config.CanvasSize, Vector2.new(60,40))
self.SizeRatio = self._Fuse.Computed(self.AbsoluteSize, function(absSize)
return absSize.X / absSize.Y
end)
self.CameraHeight = self:Import(config.CameraHeight, 100)
self.CameraFieldOfView = self._Fuse.Computed(self.Zoom, self.CanvasSize, self.CameraHeight, function(zoom, canvasSize, z)
local y = canvasSize.Y
local goalY = y / zoom
local angle = math.atan2(goalY*0.5, z)*2
return math.deg(angle)
end)
self.CameraWindowSize = self._Fuse.Computed(self.CameraHeight, self.CameraFieldOfView, self.SizeRatio, function(height, fov, ratio)
local y = 2*math.tan(math.rad(fov*0.5))*height
local x = y * ratio
return Vector2.new(math.abs(x),math.abs(y))
end)
self.AbsoluteCanvasPosition = self._Fuse.Computed(self.CanvasPosition, self.CameraWindowSize, self.CanvasSize, function(pos, winSize, canSize)
local min = pos - winSize/2
local max = pos + winSize/2
local x = pos.X
local y = pos.Y
local canMin = -canSize/2
local canMax = canSize/2
if min.X < canMin.X and max.X > canMax.X then
x = 0
else
if min.X < canMin.X then x += canMin.X - min.X end
if max.X > canMax.X then x -= max.X - canMax.X end
end
if min.Y < canMin.Y and max.Y > canMax.Y then
y = 0
else
if min.Y < canMin.Y then y += canMin.Y - min.Y end
if max.Y > canMax.Y then y -= max.Y - canMax.Y end
end
return Vector2.new(x,y)
end)
self.CameraCFrame = self._Fuse.Computed(self.AbsoluteCanvasPosition, self.CameraHeight, self.CameraFieldOfView, function(canvasPos, height, fov)
local pos = Vector3.new(canvasPos.X, canvasPos.Y, height)
return CFrame.new(pos, Vector3.new(canvasPos.X, canvasPos.Y, 0))
end)
self.Camera = self._Fuse.new "Camera" {
CFrame = self.CameraCFrame,
FieldOfView = self.CameraFieldOfView,--:Tween(0.1, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut),
}
self.WorldModel = self._Fuse.new "WorldModel" {
Name = "Canvas",
}
local parameters = {
Parent = self:Import(config.Parent, nil),
Name = self:Import(config.Name, "BoardFrame"),
ClipsDescendants = true,
Size = self.Size,
Position = self.Position,
AnchorPoint = self.AnchorPoint,
Transparency = 1,
CurrentCamera = self.Camera,
[self._Fuse.Children] = {
self.WorldModel,
self.Camera,
}
}
for k, v in pairs(config) do
if parameters[k] == nil and self[k] == nil then
parameters[k] = v
end
end
-- print("Parameters", parameters, self)
self.Instance = self._Fuse.new("ViewportFrame")(parameters)
self._Maid:GiveTask(self.Instance.Destroying:Connect(function() self:Destroy() end))
self.Canvas = self._Fuse.new "Part" {
Name = "CanvasPart",
Shape = Enum.PartType.Block,
Parent = self.WorldModel,
Material = self._Fuse.Computed(self.CanvasMaterial, function(matName)
return Enum.Material[matName]
end),
MaterialVariant = self.CanvasMaterialVariant,
Transparency = self.CanvasTransparency,
Color = self.CanvasColor,
CFrame = CFrame.new(Vector3.new(0,0,-1), Vector3.new(0,0,1)),
Size = self._Fuse.Computed(self.CanvasSize, function(size)
return Vector3.new(size.X, size.Y, 0.01)
end),
}
self.PreviousMousePosition = self._Fuse.Value(Vector2.new(0,0))
self.MousePosition = self._Fuse.Value(Vector2.new(0,0))
self.MouseDelta = self._Fuse.Computed(self.MousePosition, self.PreviousMousePosition, function(mPos, pMPos)
return pMPos - mPos
end)
self.IsHovering = self._Fuse.Computed(self.MousePosition, function(mPos)
local sGui = self.Instance:FindFirstAncestorWhichIsA("BasePlayerGui")
if not sGui then return false end
local guis = sGui:GetGuiObjectsAtPosition(mPos.X, mPos.Y)
for i, gui in ipairs(guis) do
if gui == self.Instance then
return true
end
end
return false
end)
self._Maid:GiveTask(UserInputService.PointerAction:Connect(function(wheel, pan, pinch)
if not self.LockZoom:Get() and self.IsHovering:Get() then
local currentZoom = self.Zoom:Get()
local zoomSpeed = self.ZoomSpeed:Get()
local delta = self.Delta:Get()
local alpha = (wheel + pinch)
zoomSpeed *= alpha
local goal = currentZoom * (1 + zoomSpeed)
-- print("Goal", goal, "Alpha", alpha, "Speed", zoomSpeed)
local newZoom = currentZoom + delta * (goal - currentZoom)
self.Zoom:Set(
math.clamp(
newZoom,
self.MinZoom:Get(),
self.MaxZoom:Get()
)
)
end
end))
self._Maid:GiveTask(RunService.RenderStepped:Connect(function(delta)
self.Delta:Set(delta)
self.AbsoluteSize:Set(self.Instance.AbsoluteSize)
self.PreviousMousePosition:Set(self.MousePosition:Get())
self.MousePosition:Set(UserInputService:GetMouseLocation())
if self.IsHovering:Get() and UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) and not self.LockPosition:Get() then
local mouseDelta = self.MouseDelta:Get()--UserInputService:GetMouseDelta()
-- print("Dragging", mouseDelta)
local cameraWindowSize = self.CameraWindowSize:Get()
local vportSize = self.AbsoluteSize:Get()
local mouseOffset = mouseDelta * Vector2.new(1,-1)
local worldOffset = cameraWindowSize * mouseOffset / vportSize
-- local delta = self.Delta:Get()
-- print("World", worldOffset, "Mouse", mouseScaleOffset, "Pos", mousePos)
self.CanvasPosition:Set(self.AbsoluteCanvasPosition:Get() + worldOffset)
end
end))
self:Construct()
-- print("Returning canvas")
return self.Instance
end
return BoardFrame |
include("terms")
prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
dim = 10 --[[25]]--
deg = {}
stampa = 6
numbmin = 50
numbmax = 10000
number = 1
sum = 0
for i = 1,dim do
if (i < 5) then
max = 3
else
max = 2
end
if (sum < stampa and number < numbmax) then
deg[i] = math.random(max) - 1
else
deg[i] = 0
end
sum = sum + deg[i]
if (deg[i] > 0) then
for j = 1,deg[i] do
number = number * prime[i]
end
end
end
if (number < numbmin) then
number = 1
sum = 5
temp = 1 + math.random(3)
for i = 1,dim do
if (i >= temp and i <= temp + 4) then
deg[i] = 1
number = number * prime[i]
else
deg[i] = 0
end
end
end
if (deg[5] == 0) then
deg[5] = 1
number = number * prime[5]
sum = sum + 1
end
answ = ""
term = number
for i = 1, dim do
if (deg[i] ~= 0) then
for j = 1, deg[i] do
term = term/prime[i]
answ = answ .. " " .. lib.check_number(prime[i],20)
end
end
end
|
FACTION.name = "Refugee"
FACTION.description = "A regular human citizen enslaved by the Universal Union."
FACTION.color = Color(150, 125, 100, 255)
FACTION.models = {
"models/willardnetworks/citizens/female_01.mdl",
"models/willardnetworks/citizens/female_02.mdl",
"models/willardnetworks/citizens/female_03.mdl",
"models/willardnetworks/citizens/female_04.mdl",
"models/willardnetworks/citizens/female_07.mdl",
"models/willardnetworks/citizens/female_06.mdl",
"models/willardnetworks/citizens/male01.mdl",
"models/willardnetworks/citizens/male02.mdl",
"models/willardnetworks/citizens/male03.mdl",
"models/willardnetworks/citizens/male04.mdl",
"models/willardnetworks/citizens/male05.mdl",
"models/willardnetworks/citizens/male06.mdl",
"models/willardnetworks/citizens/male07.mdl",
"models/willardnetworks/citizens/male08.mdl",
"models/willardnetworks/citizens/male09.mdl",
"models/willardnetworks/citizens/male10.mdl",
}
FACTION.isDefault = true
function FACTION:OnCharacterCreated(client, character)
local id = Schema:ZeroNumber(math.random(1, 99999), 5)
local inventory = character:GetInventory()
character:SetData("cid", id)
inventory:Add("suitcase", 1)
local Timestamp = os.time()
local TimeString = os.date( "%H:%M:%S - %d/%m/%Y" , Timestamp )
inventory:Add("transfer_papers", 1, {
citizen_name = character:GetName(),
unique = math.random(0000000,999999999),
issue_date = tostring(TimeString)
})
end
FACTION_CITIZEN = FACTION.index
|
---[[---------------------------------------]]---
-- logging - Doom Nvim logging system --
-- Author: NTBBloodbath --
-- License: MIT --
---[[---------------------------------------]]---
function Log_init()
if Doom.logging ~= 0 then
local today = os.date('%Y-%m-%d %H:%M:%S')
local boot_msg = '['
.. today
.. '] - Starting Doom Nvim '
.. Doom.version
.. ' ...'
Try({
function()
if Doom.logging == 3 then
print(boot_msg)
end
Cmd('silent !echo " " >> ' .. Doom_logs)
Cmd(
'silent !echo "' .. boot_msg .. '" >> ' .. Doom_logs
)
end,
Catch({
function(_)
print('Cannot write on_start log message')
Cmd('!touch ' .. Doom_logs)
end,
}),
})
end
end
function Log_message(msg_type, msg, level)
--[[
+ : Doom Nvim internal
* : External command
? : Prompt
! : Error
!!! : CRITICAL
--]]
local output = ''
if Doom.logging ~= 0 then
-- Generate log message
if msg_type == '!' then
output = '[!] - ' .. msg
elseif msg_type == '+' then
output = '[+] - ' .. msg
elseif msg_type == '*' then
output = '[*] - ' .. msg
elseif msg_type == '?' then
output = '[?] - ' .. msg
elseif msg_type == '!!!' then
output = '[!!!] - ' .. msg
end
Try({
function()
if Doom.logging >= level then
if Doom.logging == 3 then
print(output)
end
Cmd(
'silent !echo "' .. output .. '" >> ' .. Doom_logs
)
end
end,
Catch({
function(_)
local err_msg = '[!] - Cannot save: ' .. msg .. ''
print(err_msg)
Cmd(
'silent !echo "' .. err_msg .. '" >> ' .. Doom_logs
)
end,
}),
})
end
end
-- Dump messages to doom.log file
function Dump_messages()
if Doom.logging ~= 0 then
Cmd(
'silent !echo "[---] - Dumping :messages" >> ' .. Doom_logs
)
Cmd('redir >> ' .. Doom_logs)
Cmd('silent messages')
Cmd('redir END')
Cmd('silent !echo " " >> ' .. Doom_logs)
Cmd(
'silent !echo "[---] - End of dump" >> ' .. Doom_logs
)
end
end
|
-- Set vim as local variable for lua diagnostics
local vim = vim
-- Create local variable to shorten keymapping commands
local map = vim.api.nvim_set_keymap
local opts = {noremap = true, silent = true}
-- Mappings
--Remap space as leader key
-- map("n", "<Space>", "<Nop>", opts)
vim.g.mapleader = " "
vim.g.maplocalleader = " "
-- Fast escape from insert mode
map("i", "jk", "<Esc>", opts)
map("n", "<CR>", "<cmd>nohl<CR>", opts)
--Remap for dealing with word wrap
map("n", "k", "v:count == 0 ? 'gk' : 'k'", {noremap = true, expr = true, silent = true})
map("n", "j", "v:count == 0 ? 'gj' : 'j'", {noremap = true, expr = true, silent = true})
-- Y yank until the end of line (note: this is now a default on master)
map("n", "Y", "y$", {noremap = true})
-- -- Enforcing Purity for myself to not use arrow keys
-- map("n", "<UP>", ":resize +2<CR>", opts)
-- map("n", "<Down>", ":resize -2<CR>", opts)
-- map("n", "<Left>", ":vertical resize +2<CR>", opts)
-- map("n", "<Right>", ":vertical resize -2<CR>", opts)
-- -- Terminal
-- map("t", "<Esc>", "<C-\\><C-n>", opts)
-- map("t", "jk", "<C-\\><C-n>", opts)
-- map("n", "<C-\\>", ":sp<bar>term<CR><C-w>J:resize10<CR>", opts)
-- Mappings to move lines
-- https://stackoverflow.com/questions/5379837/is-it-possible-to-mapping-alt-hjkl-in-insert-mode
map("v", "<M-j>", ":m '>+1<CR>gv=gv", opts)
map("v", "<M-k>", ":m '<-2<CR>gv=gv", opts)
map("n", "<C-e>", "3<C-e>", opts)
map("n", "<C-y>", "3<C-y>", opts)
-- Use Ctrl+H,J,K,L to navigate panes
map("n", "<C-h>", "<C-w>h", opts)
map("n", "<C-j>", "<C-w>j", opts)
map("n", "<C-k>", "<C-w>k", opts)
map("n", "<C-l>", "<C-w>l", opts)
-- better indenting
map("v", "<", "<gv", opts)
map("v", ">", ">gv", opts)
-- better search
map("n", "n", "nzzzv", opts)
map("n", "N", "Nzzzv", opts)
-- Tabbing through buffers
map("n", "<Tab>", ":bn<CR>", opts) -- Next buffer in list
map("n", "<S-Tab>", ":bp<CR>", opts) -- Previous buffer in list
map("n", "<leader><Tab>", ":b#<CR>", opts) -- Previous buffer you were in
-- Deletes current buffer
map("n", "<leader>bd", ":b#<bar>bd#<CR>", opts)
map("n", "<C-g>", ":FloatermNew lazygit<CR>", opts)
|
local c = require('cassiopeia.palette')
local Highlight = require('cassiopeia.utils').Highlight
local Link = require('cassiopeia.utils').Link
-- https://github.com/neoclide/coc.nvim
Link('CocCodeLens' , 'Gray' )
Link('CocErrorHighlight' , 'Gray' )
Link('CocErrorSign' , 'Gray' )
Link('CocErrorVirtualText' , 'Gray' )
Link('CocExplorerBufferBufname' , 'Gray' )
Link('CocExplorerBufferBufnr' , 'Yellow' )
Link('CocExplorerBufferExpandIcon' , 'Blue' )
Link('CocExplorerBufferFullpath' , 'Gray' )
Link('CocExplorerBufferModified' , 'Red' )
Link('CocExplorerBufferNameVisible', 'Green' )
Link('CocExplorerBufferRoot' , 'Red' )
Link('CocExplorerFileDirectory' , 'Green' )
Link('CocExplorerFileExpandIcon' , 'Blue' )
Link('CocExplorerFileFullpath' , 'Gray' )
Link('CocExplorerFileGitStage' , 'Blue' )
Link('CocExplorerFileGitUnstage' , 'Yellow' )
Link('CocExplorerFileRoot' , 'Red' )
Link('CocExplorerFileRootName' , 'Orange' )
Link('CocExplorerFileSize' , 'Blue' )
Link('CocExplorerTimeAccessed' , 'Purple' )
Link('CocExplorerTimeCreated' , 'Purple' )
Link('CocExplorerTimeModified' , 'Purple' )
Link('CocFloating' , 'Pmenu' )
Link('CocInfoHighlight' , 'Gray' )
Link('CocHintHighlight' , 'Undercurled' )
Link('CocInfoSign' , 'Gray' )
Link('CocInfoVirtualText' , 'Gray' )
Link('CocWarningHighlight' , 'Gray' )
Link('CocWarningSign' , 'Gray' )
Link('CocWarningVirtualText' , 'Gray' )
Link('CocHintVirtualText' , 'Gray' )
Link('CocHoverRange' , 'Underlined' )
Highlight('CocErrorFloat' , {fg = c.red , bg = c.bg2 })
Highlight('CocGitAddedSign' , {fg = c.green , bg = c.bg1 })
Highlight('CocGitChangeRemovedSign', {fg = c.purple, bg = c.bg1 })
Highlight('CocGitChangedSign' , {fg = c.blue , bg = c.bg1 })
Highlight('CocGitRemovedSign' , {fg = c.red , bg = c.bg1 })
Highlight('CocGitTopRemovedSign' , {fg = c.red , bg = c.bg1 })
Highlight('CocHighlightText' , {fg = c.none , bg = c.bg1 })
Highlight('CocHintFloat' , {fg = c.green , bg = c.bg2 })
Highlight('CocHintSign' , {fg = c.purple, bg = c.bg1 })
Highlight('CocWarningFloat' , {fg = c.yellow, bg = c.bg2 })
Highlight('CocInfoFloat' , {fg = c.blue , bg = c.bg2 })
|
-- type = github -- DO NOT REMOVE THIS LINE!
local name = "jcli"
local release = "v0.0.38"
local version = "0.0.38"
local org = "jenkins-zh"
local repo = "jenkins-cli"
local base_url = "https://github.com/" .. org .. "/" .. repo
food = {
name = name,
description = "Jenkins CLI allows you manage your Jenkins as an easy way",
license = "MIT",
homepage = "https://jenkins-zh.cn",
version = version,
packages = {
{
os = "darwin",
arch = "amd64",
url = base_url .. "/releases/download/" .. release .. "/" .. name .. "-darwin-amd64.tar.gz",
sha256 = "841d32e45332b40bf8351e5bab5e0ee2c92954aa6663558607ea95658b44ad85",
resources = {
{
path = name,
installpath = "bin/" .. name,
executable = true
}
}
},
{
os = "linux",
arch = "amd64",
url = base_url .. "/releases/download/" .. release .. "/" .. name .. "-linux-amd64.tar.gz",
sha256 = "be49cc9bf7a9b2a9cc76ad5fef1b9a5e123b4ffe0145f9c18cf8aa5f0801c4ac",
resources = {
{
path = name,
installpath = "bin/" .. name,
executable = true
}
}
},
{
os = "windows",
arch = "amd64",
url = base_url .. "/releases/download/" .. release .. "/" .. name .. "-windows-amd64.zip",
sha256 = "bc87351c754f7cb315f1760a091fb38aacf993ff8ade23d453447504b38c8a3d",
resources = {
{
path = name .. ".exe",
installpath = "bin\\" .. name .. ".exe"
}
}
}
}
}
|
describe("Opening/reading tz files", function()
local tzfile = require "luatz.tzfile"
it("should be able to open a version 3 file", function()
-- The tz file for America/Godthab from 2015g
-- One of the smallest tzif3 files I have
tzfile.read_tzfile("spec/Godthab.tz")
end)
end)
|
print(type("Hello world"))
print(type(10.4*3))
print(type(1))
print(type(print))
print(type(true))
print(type(nil))
print(type(type(X)))
print(type(a)) -- nil ('a' is not initialized)
a = 10
print(type(a)) -- number
a = "a is a tring"
print(type(a)) -- string
a = print -- yes, this is valid!
print(type(a)) --function |
local m = {}
math.randomseed( os.time() )
local random = math.random
local fmt = string.format
m.uuid = function( )
return string.gsub(
"aaabbaaa-aaaa-7aaa-baaa-abaaaaaaabaa",
'[ab]',
function( character )
return fmt( '%X', ( character == 'a' ) and random( 0, 0xf ) or random( 8, 0xb ) )
end
)
end
return m
|
local GridSector = require("core.module.view.GridSector");
local function Grid(width, height)
local grid = display.newGroup();
grid.sector_width = 100;
grid.sector_height = 100;
grid.sectors = {};
grid.hints = { row = {}, col = {} };
function grid:init(nonogram)
self.sector_width = width / nonogram.width;
self.sector_height = height / nonogram.height;
self:initGrid(nonogram);
self:initHints(nonogram);
end
function grid:initGrid(nonogram)
for r = 1, nonogram.rows do
grid.sectors[r] = {};
for c = 1, nonogram.cols do
local sector = GridSector(r, c, self.sector_width, self.sector_height);
sector.x = (c - 0.5) * self.sector_width - width * 0.5;
sector.y = (r - 0.5) * self.sector_height - height * 0.5;
grid.sectors[r][c] = sector;
grid:insert(sector);
end
end
end
function grid:initHints(nonogram)
self:initRowHints(nonogram);
self:initColumnHints(nonogram);
end
function grid:initRowHints(nonogram)
for r = 1, nonogram.rows do
local lines = nonogram:getUnbrokenLinesInRow(r);
local row_y = (r - 0.5) * self.sector_height - height * 0.5;
local row_hint = display.newText(grid, table.concat(lines, " "), -width * 0.5 - 20, row_y, "Arial", 30);
row_hint.anchorX = 1.0;
end
end
function grid:initColumnHints(nonogram)
for c = 1, nonogram.cols do
local lines = nonogram:getUnbrokenLinesInColumn(c);
local col_x = (c - 0.5) * self.sector_width - width * 0.5;
local col_hint = display.newText(grid, table.concat(lines, "\n"), col_x, -height * 0.5 - 20, "Arial", 30);
col_hint.anchorY = 1.0;
end
end
function grid:markSectorAsFilled(row, col)
self.sectors[row][col]:markAsFilled();
end
function grid:markSectorAsEmpty(row, col)
self.sectors[row][col]:markAsEmpty();
end
return grid;
end
return Grid; |
-- notify.lua -- Desktop notifications for mpv.
-- Just put this file into your ~/.mpv/lua folder and mpv will find it.
--
-- Copyright (c) 2014 Roland Hieber
--
-- 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.
-------------------------------------------------------------------------------
-- helper functions
-------------------------------------------------------------------------------
function print_debug(s)
-- print("DEBUG: " .. s) -- comment out for no debug info
return true
end
-- url-escape a string, per RFC 2396, Section 2
function string.urlescape(str)
s, c = string.gsub(str, "([^A-Za-z0-9_.!~*'()/-])",
function(c)
return ("%%%02x"):format(c:byte())
end)
return s;
end
-- escape string for html
function string.htmlescape(str)
str = string.gsub(str, "<", "<")
str = string.gsub(str, ">", ">")
str = string.gsub(str, "&", "&")
str = string.gsub(str, "\"", """)
str = string.gsub(str, "'", "'")
return str
end
-- escape string for shell inclusion
function string.shellescape(str)
return "'"..string.gsub(str, "'", "'\"'\"'").."'"
end
-- converts string to a valid filename on most (modern) filesystems
function string.safe_filename(str)
s, c = string.gsub(str, "([^A-Za-z0-9_.-])",
function(c)
return ("%02x"):format(c:byte())
end)
return s;
end
-------------------------------------------------------------------------------
-- here we go.
-------------------------------------------------------------------------------
local CACHE_DIR = os.getenv("XDG_CACHE_HOME")
CACHE_DIR = CACHE_DIR or os.getenv("HOME").."/.cache"
CACHE_DIR = CACHE_DIR.."/mpv/coverart"
print_debug("making " .. CACHE_DIR)
os.execute("mkdir -p -- " .. string.shellescape(CACHE_DIR))
function tmpname()
return "/tmp/mpv-coverart." .. math.random(0,0xffffff)
end
-- scale an image file
-- @return boolean of success
function scale_image(src, dst)
convert_cmd = ("convert -scale x64 -- %s %s"):format(
string.shellescape(src), string.shellescape(dst))
print_debug("executing " .. convert_cmd)
if os.execute(convert_cmd) then
return true
end
return false
end
-- look for a list of possible cover art images in the same folder as the file
-- @param absolute filename name of currently played file, or nil if no match
function get_folder_cover_art(filename)
if not filename or string.len(filename) < 1 then
return nil
end
print_debug("get_folder_cover_art: filename is " .. filename)
cover_extensions = { "png", "jpg", "jpeg", "gif" }
cover_names = { "cover", "folder", "front", "back", "insert" }
path = string.match(filename, "^(.*/)[^/]+$")
for k,name in pairs(cover_names) do
for k,ext in pairs(cover_extensions) do
morenames = { name, string.upper(name),
string.upper(string.sub(name, 1, 1)) .. string.sub(name, 2, -1) }
moreexts = { ext, string.upper(ext) }
for k,name in pairs(morenames) do
for k,ext in pairs(moreexts) do
fn = path .. name .. "." .. ext
--print_debug("get_folder_cover_art: trying " .. fn)
f = io.open(fn, "r")
if f then
f:close()
print_debug("get_folder_cover_art: match at " .. fn)
return fn
end
end
end
end
end
return nil
end
function notify_current_track()
data = mp.get_property_native("metadata")
function get_metadata(data, keys)
for k,v in pairs(keys) do
if data[v] and string.len(data[v]) > 0 then
return data[v]
end
end
return ""
end
-- srsly MPV, why do we have to do this? :-(
artist = get_metadata(data, {"artist", "ARTIST"})
album = get_metadata(data, {"album", "ALBUM"})
title = get_metadata(data, {"title", "TITLE"})
print_debug("notify_current_track: relevant metadata:")
print_debug("artist: " .. artist)
print_debug("album: " .. album)
summary = ""
body = ""
params = ""
scaled_image = ""
delete_scaled_image = false
-- first try finding local cover art
abs_filename = os.getenv("PWD") .. "/" .. mp.get_property_native("path")
cover_image = get_folder_cover_art(abs_filename)
if cover_image and cover_image ~= "" then
scaled_image = tmpname()
scale_image(cover_image, scaled_image)
delete_scaled_image = true
end
if scaled_image and string.len(scaled_image) > 1 then
print("found cover art in " .. cover_image)
params = " -i " .. string.shellescape(scaled_image)
else
params = " -i mpv"
end
if(artist == "") then
summary = string.shellescape("Now playing:")
else
summary = string.shellescape(string.htmlescape(artist))
end
if title == "" then
body = string.shellescape(mp.get_property_native("filename"))
else
if album == "" then
body = string.shellescape(string.htmlescape(title))
else
body = string.shellescape(("%s<br/><i>%s</i>"):format(
string.htmlescape(title), string.htmlescape(album)))
end
end
command = ("notify-desktop -a mpv %s -- %s %s > /dev/null"):format(params, summary, body)
print_debug("command: " .. command)
os.execute(command)
if delete_scaled_image and not os.remove(scaled_image) then
print("could not remove" .. scaled_image .. ", please remove it manually")
end
end
-- insert main() here
mp.register_event("file-loaded", notify_current_track)
|
require'gitsigns'.setup{
numhl = true
}
|
Locales['fr'] = {
['invoices'] = 'factures',
['invoices_item'] = '$%s',
['received_invoice'] = 'vous avez ~r~reçu~s~ une facture',
['paid_invoice'] = 'vous avez ~g~payé~s~ une facture de ~r~$%s~s~',
['received_payment'] = 'vous avez ~g~reçu~s~ un paiement de ~g~$%s~s~',
['player_not_online'] = 'le joueur n\'est pas connecté',
['no_money'] = 'you do not have enough money to pay this bill',
['target_no_money'] = 'the player ~r~does not~s~ have enough money to pay the bill!',
}
|
-- walkabout.lua
-- A slider-based sequencer
-- PolyPerc output - and MIDI
--
-- enc2 = select sequence #
-- enc3 = set step value
-- key2 = decrement step #
-- key3 = increment step #
--
-- key1 = hold for ALT
--
-- alt-enc1 = select setting
-- enc1 = change setting
--
-- sequencer values auto-saved
-- on select or shutdown to
-- "data/ddg/walkabout.data"
--
-- V1.1:
-- MIDI output on the first
-- device encountered, on
-- channel 1
engine.name = "PolyPerc"
local ControlSpec = require 'controlspec'
local Control = require 'params/control'
local Option = require 'params/option'
-- constants
local NUMSTEPS = 8
local NUMSEQS = 8
-- table starters...
local sq = {
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}
}
local ed = {}
local st = {}
local midi_device
local midi_msg
-- -----------------------
-- initialization routine
-- -----------------------
function init()
-- sq (sequence) data setup
walkabout_load()
-- ed (editor) data setup
ed.cseq = 1
ed.step = 1
ed.onedown = false
ed.view = Option.new("view", {"view", "start/stop", "tempo", "direction"})
-- st (stepper) data setup
st.curdir = 1
st.curloc = 0
st.dir = Option.new("dir", {"fwd","bwd","udn","rot","rnd"})
st.dirString = {"forward", "backward", "up-down", "rotate", "random"}
st.running = Option.new("running", {"off", "on"})
st.running.action =
function(r)
if (r == 1) then counter:stop()
else counter:start() end
end
st.tempo = Control.new("tempo", ControlSpec.new(40, 280, 'lin', 1, 120, 'bpm'))
st.tempo.action =
function(t)
counter.time = (60 / t) / 4
end
counter = metro.alloc(count, 0.125, -1)
counter2 = metro.alloc(noteoff_count)
-- comment out the next line if you don't want to start running
st.running:set(2)
end
-- ------------------------------------------------------
-- deal with a 'pulse', moving the sequencer by one step.
-- ------------------------------------------------------
function count()
local dir = st.dir:get()
if (dir == 1) then
st.curloc = (st.curloc + 1) % NUMSTEPS
st.curdir = 1
elseif (dir == 2) then
st.curloc = (st.curloc - 1) % NUMSTEPS
st.curdir = -1
elseif (dir == 3) then
st.curloc = (st.curloc + st.curdir)
if (st.curloc > (NUMSTEPS - 1)) then
st.curloc = NUMSTEPS - 2
st.curdir = -1
end
if (st.curloc < 0) then
st.curloc = 1
st.curdir = 1
end
elseif (dir == 4) then
st.curloc = (st.curloc + st.curdir)
if (st.curloc < 0) then
st.curloc = 0
st.curdir = 1
elseif (st.curloc > (NUMSTEPS - 1)) then
st.curloc = NUMSTEPS - 1
st.curdir = -1
end
elseif (dir == 5) then
st.curloc = math.random(0, NUMSTEPS - 1)
st.curdir = 1
end
play()
redraw()
end
-- ----------------------------------------------
-- play the current note in the current sequence.
-- ----------------------------------------------
function play()
local m = sq[ed.cseq][st.curloc + 1]
if (m > 0) then
engine.hz(midi_to_hz(m + 36))
if (midi_device) then
print("note on: " .. m + 36)
midi_msg = {144, m + 36, 127}
midi_device:send(midi_msg)
counter2:start(0.01, 1)
end
end
end
-- ---------------------------
-- deal with a note-off timer.
-- ---------------------------
function noteoff_count()
if (midi_device and midi_msg) then
print("note off: " .. midi_msg[2])
midi_msg[3] = 0
midi_device:send(midi_msg)
midi_msg = nil
end
end
-- -----------------------------------
-- convert a midi note to a frequency.
-- -----------------------------------
function midi_to_hz(note)
return (440/32) * (2 ^ ((note - 9) / 12))
end
-- -----------------------------------------------
-- deal with a new midi device add (incl startup).
-- -----------------------------------------------
function midi.add(dev)
if not midi_device then
print("adding device:" .. dev.name)
dev.event = midi_event
dev.remove = midi_remove
midi_device = dev
end
end
-- ---------------------------
-- deal with a device removal.
-- ---------------------------
function midi_remove()
print("dev.remove called...")
midi_device = nil
end
-- --------------------------------------------
-- deal with a MIDI event receipt (future use).
-- --------------------------------------------
local function midi_event(data)
print("Midi event received...")
end
-- ------------------------
-- deal with encoder input.
-- ------------------------
function enc(c, v)
local move = 0
if (c == 1) then
if (ed.onedown) then
if (v > 0) then ed.view:delta(1)
else ed.view:delta(-1) end
redraw()
else
status_entry(v)
redraw()
end
elseif (c == 2) then
if (v > 0) then move = 1 end
if (v < 0) then move = -1 end
ed.cseq = util.clamp(ed.cseq + move, 1, NUMSEQS)
redraw()
elseif (c == 3) then
sq[ed.cseq][ed.step] = util.clamp(sq[ed.cseq][ed.step] + v, 0, 36)
redraw()
end
end
-- ---------------------------------
-- conditional entry of status info.
-- ---------------------------------
function status_entry(v)
local ev = ed.view:get()
if (ev == 1) then
return
elseif (ev == 2) then
st.running:delta(v)
elseif (ev == 3) then
st.tempo:delta(v)
elseif (ev == 4) then
if (v > 0) then st.dir:delta(1)
else st.dir:delta(-1) end
end
end
-- --------------------
-- deal with key input.
-- --------------------
function key(c, v)
if (c == 1) then
ed.onedown = (v == 1)
redraw()
end
if (c == 2 and v == 1) then
ed.step = util.clamp(ed.step - 1, 1, NUMSTEPS)
redraw()
end
if (c == 3 and v == 1) then
ed.step = util.clamp(ed.step + 1, 1, NUMSTEPS)
redraw()
end
end
-- ------------------------------
-- the standard drawing function.
-- ------------------------------
function redraw()
screen.clear()
screen.font_face(4)
screen.font_size(10)
draw_status()
for i = 1, NUMSTEPS do
local l = (16 * (i - 1)) + 8
screen.rect(l, 15, 8, 36)
screen.stroke()
screen.rect(l, 15 + (36 - sq[ed.cseq][i]), 8, sq[ed.cseq][i])
screen.fill()
end
screen.move(16 * (ed.step - 1) + 8, 60)
screen.text(" ^")
screen.move(16 * (st.curloc) + 8, 63)
screen.text("x")
screen.update()
end
-- -------------------------------------
-- conditional drawing of status header.
-- -------------------------------------
function draw_status()
if (ed.onedown) then
screen.move(5, 10)
screen.text(ed.view:string())
else
local v = ed.view:get()
screen.move(5, 10)
if (v == 1) then
screen.text("sq:" .. ed.cseq
.. " edit step:" .. ed.step
.. "(" .. sq[ed.cseq][ed.step] .. ")"
.. " dir: " .. st.dir:string())
elseif (v == 2) then
screen.text("running: " .. st.running:string())
elseif (v == 3) then
screen.text("tempo: " .. st.tempo:get("tempo"))
elseif (v == 4) then
screen.text("direction: " .. st.dirString[st.dir:get()])
end
end
end
-- ------------------------------
-- save the data during shutdown.
-- ------------------------------
function cleanup()
walkabout_save()
end
-- -----------------------------
-- save the set data to storage.
-- -----------------------------
function walkabout_save()
if (not isdir(data_dir .. "ddg")) then
os.execute("mkdir " .. data_dir .. "ddg")
end
local fd=io.open(data_dir .. "ddg/walkabout.data","w+")
io.output(fd)
for x=1,NUMSEQS do
for y=1,NUMSTEPS do
io.write(sq[x][y] .. "\n")
end
end
io.close(fd)
end
-- -------------------------------
-- load the set data from storage.
-- -------------------------------
function walkabout_load()
local fd=io.open(data_dir .. "ddg/walkabout.data","r")
if fd then
print("datafile found")
io.input(fd)
for x=1,NUMSEQS do
for y=1,NUMSTEPS do
sq[x][y] = tonumber(io.read())
end
end
io.close(fd)
else
print("datafile not found")
end
end
-- -------------------------------------------------
-- check if a file or directory exists in this path.
-- -------------------------------------------------
function exists(file)
local ok, err, code = os.rename(file, file)
if not ok then
if code == 13 then
-- Permission denied, but it exists
return true
end
end
return ok, err
end
-- -----------------------------------------
-- Check if a directory exists in this path.
-- -----------------------------------------
function isdir(path)
-- "/" works on both Unix and Windows
return exists(path.."/")
end
|
object_mobile_smuggler_broker_gotan = object_mobile_shared_smuggler_broker_gotan:new {
}
ObjectTemplates:addTemplate(object_mobile_smuggler_broker_gotan, "object/mobile/smuggler_broker_gotan.iff")
|
-- DieRoll
function setup()
--[[
The quat userdata isn't available until the GL state has been initialised so we can't extend it before setup.
This routine adds all the extensions to it now.
--]]
extendQuat()
viewer.mode = FULLSCREEN
--[[
This section defines a texture for the die. It is a single texture containing images for each of th4 sides.
--]]
local dieimg = image(600,100)
setContext(dieimg)
background(255, 255, 255, 255)
noFill()
stroke(200)
strokeWidth(10)
noSmooth()
for k=1,6 do
rect(100*(k-1)-5,-5,110,110)
end
noStroke()
fill(200)
for k=0,5 do
for j=0,3 do
rect(100*k+90*math.floor(j/2),90*(j%2),10,10)
end
end
fill(255, 255, 255, 255)
ellipseMode(RADIUS)
for k=0,5 do
for j=0,3 do
ellipse(100*k+10+80*math.floor(j/2),10+80*(j%2),6)
end
end
fill(0, 0, 0, 255)
ellipseMode(CENTER)
noStroke()
-- fill(255, 0, 0, 255)
ellipse(100*(5-1)+50,50,15)
fill(0, 0, 0, 255)
for k=1,2 do
ellipse(100*(k-1)+50,50,15)
end
for _,k in ipairs({1,2,3,4,6}) do
-- fill(255, 0, 0, 255)
ellipse(100*(k-1)+25,25,15)
fill(0, 0, 0, 255)
ellipse(100*(k-1)+75,75,15)
end
for _,k in ipairs({1,4,6}) do
ellipse(100*(k-1)+75,25,15)
ellipse(100*(k-1)+25,75,15)
end
ellipse(525,50,15)
ellipse(575,50,15)
setContext()
-- End of setting up the texture
--[[
I had a lot of code invested in meshes, so when Craft came along with its models then rather than ditch that code I adapted it to define models insteqd of meshes. The simplest way was to define a class that mimiced a mesh in that it has the same attributes and methods but doesn't go to the bother of creating the underlying userdata. Rather it gathers all the information and then at the end exports it to a model.
--]]
local __die = PseudoMesh()
local number = 4
local i,j,l,a
a = {vec3(1,0,0),vec3(0,1,0),vec3(0,0,1)}
--[[
This loop defines the corners of the rounded cube.
--]]
for k=0,7 do
i=2*(k%2)-1
j=2*(math.floor(k/2)%2)-1
l=2*math.floor(k/4)-1
__die:addSphereSegment({
startLatitude=0,
endLatitude=90,
startLongitude=0,
endLongitude=90,
axes={i*a[1],j*a[2],l*a[3]},
solid=false,
centre = i*a[1] + j*a[2] + l*a[3],
radius = .3,
number = 2*number,
texOrigin = vec2(0,0),
texSize = vec2(.01,.01)
})
end
local tx = 0
for l=1,3 do
--[[
This places the sides and the rounded edges. It works in pairs, since opposite edges share a lot of code.
The first loop does the edges, the second the faces.
--]]
for k=0,3 do
j = 2*math.floor(k/2)-1
i = -j*(2*(k%2)-1)
__die:addCylinder({
axes = a,
centre = i*a[2] + j*a[3],
height = 2,
radius = .3,
startAngle = k*90+180,
deltaAngle = 90,
faceted = false,
size = number,
texOrigin = vec2(0,0),
texSize = vec2(.01,.01)
})
end
for k=-1,1,2 do
__die:addPolygon({
vertices = {
k*(1+.3)*a[1]+a[2]+a[3],
k*(1+.3)*a[1]-a[2]+a[3],
k*(1+.3)*a[1]-a[2]-a[3],
k*(1+.3)*a[1]+a[2]-a[3]
},
viewFrom = -a[1],
texCoords = {
vec2(tx,0),
vec2(tx+1/6,0),
vec2(tx+1/6,1),
vec2(tx,1)
}
})
tx = tx + 1/6
end
table.insert(a,1,table.remove(a))
end
-- End of defining the rounded cube model
--[[
This part sets up the scene. As with meshes, I had a lot of pre-Craft code for setting and manipulating the viewport. The ViewCraft class adapted that for Craft. It can be used with my touch handler to add natural moving and rotating of the camera.
--]]
scene = craft.scene()
scene.camera:add(ViewCraft,nil,nil,{useGravity = false, eye = vec3(0,15,-5), up = vec3(0,0,-1), currentGravity = quat(1,0,0,0)})
--[[
Now we create our two entities based on the die model.
--]]
dieA = scene:entity()
dieA.model = __die:toModel()
local m = craft.material(asset.builtin.Materials.Standard)
m.map = dieimg
dieA.material = m
dieA.position = vec3(-3,0,0)
dieB = scene:entity()
dieB.model = __die:toModel()
local m = craft.material(asset.builtin.Materials.Standard)
m.map = dieimg
dieB.material = m
dieB.position = vec3(3,0,0)
--[[
Our dice will rotate until the screen is tapped at which point they will rotate to show a particular face.
--]]
speed = 100 -- speed of rotation
qa = quat(1,0,0,0) -- initial rotation of first die
qb = quat(1,0,0,0) -- initial rotation of second die
sla,sta = qpath(qa) -- this defines a path in rotation space for the first die
slb,stb = qpath(qb) -- this defines a path in rotation space for the first die
--[[
When we want a die to show a particular value we need to rotate to that face. These define the rotations that show each side. The method 'rotateToquat' returns a quaternion that rotates the first vector to the second. It's like the 'quat.fromToRotation' except that doesn't work in all cases.
--]]
sides = {
vec3(0,-1,0):rotateToquat(vec3(0,1,0)),
vec3(0,0,-1):rotateToquat(vec3(0,1,0)),
vec3(1,0,0):rotateToquat(vec3(0,1,0)),
vec3(0,0,1):rotateToquat(vec3(0,1,0)),
vec3(-1,0,0):rotateToquat(vec3(0,1,0)),
vec3(0,1,0):rotateToquat(vec3(0,1,0)),
}
--[[
The program has three states:
1. The dice are rotating aimlessly
2. The dice rotate to show a given face and then stop
3. The experiment runs repeatedly without rotations
--]]
state = 1
--[[
The program simulates a series of experiments, so keeps track of how many dice rolls meet the success criteria. At the moment, it is counting doubles and computing the corresponding experimental probability.
--]]
trials = 0
successes = 0
trial = function(a,b) return a == b end
end
function draw()
--[[
Get the current rotations of the dice.
--]]
qa = sla(ElapsedTime)
qb = slb(ElapsedTime)
--[[
What we do next depends on what state we're in
--]]
if state == 1 then
--[[
In state 1 we are freely rotating around so we just need to get a new path in rotation spacw when we reach the end of the current one.
--]]
if ElapsedTime > sta then
sla,sta = qpath(qa)
end
if ElapsedTime > stb then
slb,stb = qpath(qb)
end
elseif state == 3 then
--[[
In state 3 we run a new experiment each draw so choose new faces and rotate to show them and update our totals.
--]]
local n,m = math.random(1,6),math.random(1,6)
--[[
Having chosen the faces to show, we define the rotations to show them. Once we show the right face, we can vary it a little by rotating about the forward facing axis. This is purely aesthetic.
--]]
qa = quat.angleAxis(math.random(0,3)*90,vec3(0,1,0))*sides[n]
qb = quat.angleAxis(math.random(0,3)*90,vec3(0,1,0))*sides[m]
--[[
Update our experiment totals.
--]]
if trial(n,m) then
successes = successes + 1
end
trials = trials + 1
end
background(72, 55, 55, 255)
-- update the rotations of the dice
dieA.rotation = qa
dieB.rotation = qb
-- update and draw the scene
scene:update(DeltaTime)
scene:draw()
-- reset the view so that we go back to 2D mode for adding text
viewMatrix(matrix())
ortho()
pushStyle()
fill(255, 255, 255, 255)
fontSize(30)
textMode(CORNER)
--[[
This set of commands writes some useful stuff on the screen about our experiments
--]]
local tw,th,a,lh
a = 100
lh = 150
text("Trials:",a,lh)
tw,th = textSize("Trials: ")
a = a + tw
text(trials,a,lh)
tw,th = textSize("100000")
a = a + tw
text("Successes:",a,lh)
tw,th = textSize("Successes: ")
a = a + tw
text(successes,a,lh)
tw,th = textSize("100000")
a = a + tw
text("Probability:",a,lh)
tw,th = textSize("Probability: ")
a = a + tw
text(math.floor(successes/math.max(1,trials)*10000)/10000,a,lh)
--]]
-- [[
tw,th = textSize("100000")
a = a + tw
text("FPS:",a,lh)
tw,th = textSize("FPS: ")
a = a + tw
text(math.floor(1/DeltaTime),a,lh)
--]]
popStyle()
end
function touched(t)
if t.state == ENDED then
if t.tapCount == 2 then
--[[
A double tap switches between the single experiment mode and the multiple experiment one
--]]
if state == 3 then
state = 2
else
state = 3
end
else
if state == 1 then
--[[
A single tap in state 1 (freely rotating) starts us rotating to show a given face
--]]
local n,m = math.random(1,6),math.random(1,6) -- pick a face for each die
-- define a path of rotations from our current rotation to one that shows the selected face
sla,sta = qpath(qa,quat.angleAxis(math.random(0,3)*90,vec3(0,1,0))*sides[n])
slb,stb = qpath(qb,quat.angleAxis(math.random(0,3)*90,vec3(0,1,0))*sides[m])
-- when both faces are shown, update the information for display
tween.delay(math.max(sta,stb) - ElapsedTime,function()
if trial(n,m) then
successes = successes + 1
end
trials = trials + 1
end)
state = 2
elseif state == 2 then
-- If we're in state 2, start feely rotating again
sla,sta = qpath(qa)
slb,stb = qpath(qb)
state = 1
end
end
end
end
--[[
This function defines a path in the space of rotations from a given starting point to an ending point. If the ending point isn't given, one is chosen at random. It returns a function that defines the path and the length of time that path will take (this keeps the rotation rate constant and means that a path between nearby rotations will be quicker than between far away ones).
--]]
function qpath(q,qt)
-- If a target isn't given, pick one at random
qt = qt or quat.angleAxis(360*math.random(),RandomVec3())
-- Work out the length of the path
local s = math.acos(q:dot(qt))/2
-- 'slerp' stands for spherical interpolation
local sl = q:make_slerp(qt)
local st = ElapsedTime
return function(t) return sl(math.min(1,(t-st)/s)) end, st + s
end
--[[
Small utility function that picks a unit vec3 at random, uniformly distributed on the sphere.
--]]
function RandomVec3()
local th = 2*math.pi*math.random()
local z = 2*math.random() - 1
local r = math.sqrt(1 - z*z)
return vec3(r*math.cos(th),r*math.sin(th),z)
end
|
function table_concat(t)
result = ""
for k, v in ipairs(t) do
result = result .. v
end
return result
end
print(table_concat({"hello", " ", "world"}))
|
--Start of Global Scope---------------------------------------------------------
local counter = 0
local SCAN_FILE_PATH = "resources/TestScenario.xml"
print("Input File: ", SCAN_FILE_PATH)
--------------------------------------------------------------------------------
-- Check device capabilities
assert(View,"View not available, check capability of connected device")
assert(Scan,"Scan not available, check capability of connected device")
assert(Scan.Transform,"Transform not available, check capability of connected device")
assert(Scan.EdgeHitFilter,"EdgeHitFilter not available, check capability of connected device")
-- Create a viewer instance
viewer = View.create()
assert(viewer,"Error: View could not be created.")
viewer:setID("viewer3D")
-- Create a transform instance to convert the Scan to a PointCloud
transform = Scan.Transform.create()
assert(transform,"Error: Transform could not be created.")
-- Create the filter
edgeHitFilter = Scan.EdgeHitFilter.create()
assert(edgeHitFilter,"Error: EdgeHitFilter could not be created")
Scan.EdgeHitFilter.setMaxDistNeighbor(edgeHitFilter, 30)
Scan.EdgeHitFilter.setEnabled(edgeHitFilter, true)
-- Create provider. Providing starts automatically with the register call
-- which is found below the callback function
provider = Scan.Provider.File.create()
assert(provider,"Error: Scan provider could not be created.")
-- Set the file path
Scan.Provider.File.setFile(provider, SCAN_FILE_PATH)
-- Set the DataSet of the recorded data which should be used.
Scan.Provider.File.setDataSetID(provider, 1)
--End of Global Scope-----------------------------------------------------------
--Start of Function and Event Scope---------------------------------------------
--------------------------------------------------------------------------------
-- Compares the distances of two scans of the specified echo
--------------------------------------------------------------------------------
function compareScans(inputScan, filteredScan, iEcho, printDetails)
-- get the beam and echo counts
local beamCountInput = Scan.getBeamCount(inputScan)
local echoCountInput = Scan.getEchoCount(inputScan)
local beamCountFiltered = Scan.getBeamCount(filteredScan)
local echoCountFiltered = Scan.getEchoCount(filteredScan)
local count = 0
-- Checks
if ( iEcho <= echoCountInput and iEcho <= echoCountFiltered ) then
if ( beamCountInput == beamCountFiltered ) then
-- Print beams with different distances
if ( printDetails ) then
print("The following beams have different distance values:")
end
local inputDistance = Scan.toVector(inputScan, "DISTANCE", iEcho-1)
local filteredDistance = Scan.toVector(filteredScan, "DISTANCE", iEcho-1)
for iBeam=1, beamCountInput do
local d1 = inputDistance[iBeam]
local d2 = filteredDistance[iBeam]
if ( math.abs(d1-d2) > 0.01 ) then
if ( printDetails ) then
print(string.format(" beam %4d: %10.2f --> %10.2f", iBeam, d1, d2))
end
count = count + 1
end
end
end
end
return count
end
-- Callback function to process new scans
function handleNewScan(scan)
counter = counter + 1
-- Clone input scan
inputScan = Scan.clone(scan)
-- Filter edge hits; the input scan if modified in place
filteredScan = Scan.EdgeHitFilter.filter(edgeHitFilter, scan)
-- and show the changed distances of echo #1
local hits = 0
if ( inputScan ~= nil ) then
hits = compareScans(inputScan, filteredScan, 1, false)
print(DateTime.getTime(), string.format("Scan %6d: EdgeHits = %d", counter, hits))
end
-- Transform to PointCloud to view in the PointCloud viewer on the webpage
if nil ~= Scan.Transform then
local pointCloud = Scan.Transform.transformToPointCloud(transform, filteredScan)
View.addPointCloud(viewer, pointCloud)
View.present(viewer)
end
end
-- Register callback function to "OnNewScan" event.
-- This call also starts the playback of scans
Scan.Provider.File.register(provider, "OnNewScan", handleNewScan)
--End of Function and Event Scope------------------------------------------------ |
require "_Utils"
local common = require "_ConvCommon"
local types = require "_ConvCommonTypes"
local convert = require "_ConvCommonConvert"
return { test = "feature",
collate =
{
start = "features",
},
element =
{ name = "feature",
map_attribs =
{
name = "name",
api = "api",
comment = "notation",
number = "version",
protect = "define",
},
},
children =
{
convert.ToNewReqRem(false, false),
convert.ToNewReqRem(true, false),
},
}
|
--[[
单个信号
--]]
local single_signal = class("single_signal"){
name = "",
all_connect = {},
}
function single_signal:connect(object,conn_func_name)
local i = #self.all_connect + 1
local conn = {
object = object,
fname = conn_func_name,
index = i
}
table.insert(self.all_connect,conn)--先到先得
self.all_connect[object] = conn--快速删除,免得搜索
end
function single_signal:release(...)
for i,connect in ipairs(self.all_connect) do
local obj = connect.object
local conn_func = obj[connect.fname]
conn_func(obj,...)--执行对应连接函数
end
end
function single_signal:local_release(list)
for object in ipairs(list) do
local conn = self.all_connect[object]
if conn then
local conn_func = obj[conn.fname]
conn_func(object)
end
end
end
function single_signal:disconnect(object)
local conn = self.all_connect[object]
if conn then
self.all_connect[conn.index] = nil
self.all_connect[object] = nil
end
end
return single_signal |
--[[-------------------------------------------------------------------------
Copyright (c) 2008, zork
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of rFilter2 nor the names of its contributors may
be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE,
DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------]]
local addon = CreateFrame"Frame"
local _G = getfenv(0)
local rf2_player_name, _ = UnitName("player")
local _, rf2_player_class = UnitClass("player")
-----------------------------------------------------
-- EDIT YOUR BUFFS/DEBUFFS IN HERE
-- IMPORTANT, TAGS HAVE TO BE UNIQUE!!!
-----------------------------------------------------
-- to enable the icons OOC, put this to 1 while moving the icons and to 0 when ready
-- 0 = off // 1 = on
local testmode = 0
--alpha when buff/debuff/cd not active
--values between 0 and one are allowed
local alpha_when_not_active = 0
local alpha_when_in_combat = 0
--make icon grey when buff noch active
--0 = off // 1 = on
local use_grey_vertex = 1
local bordertexture = "Interface\\AddOns\\rActionButtonStyler\\media\\gloss"
--DEFAULT_CHAT_FRAME:AddMessage("found "..rf2_player_name.." : "..rf2_player_class)
if rf2_player_name == "Grombur" and rf2_player_class == "HUNTER" then
rf2_spell_list = {
buffs = {
[1] = { tag = "rapid", spellid = 3045, unit = "player", size = 24, fontsize = 18, posx = -64, posy = -270, framestrata = "BACKGROUND", anchor = "UIParent"},
--[2] = { tag = "commanding", spellid = 469, unit = "player", size = 32, fontsize = 24, posx = 40, posy = 0, framestrata = "BACKGROUND", anchor = "UIParent"},
},
debuffs = {
[1] = { tag = "mark", spellid = 14325, ismine = 0, unit = "target", size = 24, fontsize = 18, posx = -32, posy = -270, framestrata = "LOW", anchor = "UIParent"},
[2] = { tag = "serpent", spellid = 49000, ismine = 0, unit = "target", size = 24, fontsize = 18, posx = 0, posy = -270, framestrata = "LOW", anchor = "UIParent"},
[3] = { tag = "scorpid", spellid = 27060, ismine = 0, unit = "target", size = 24, fontsize = 18, posx = 32, posy = -270, framestrata = "LOW", anchor = "UIParent"},
--14325 mark
--49000 serpentsting
--27060 poison
},
cooldowns = {
--[1] = { tag = "wrath", spellid = 19574, size = 32, fontsize = 24, posx = 0, posy = 80, framestrata = "BACKGROUND", anchor = "UIParent"},
--[2] = { tag = "rapid", spellid = 3045, size = 32, fontsize = 24, posx = 40, posy = 80, framestrata = "BACKGROUND", anchor = "UIParent"},
--[3] = { tag = "arcane", spellid = 27019, size = 32, fontsize = 24, posx = 80, posy = 80, framestrata = "BACKGROUND", anchor = "UIParent"},
},
}
elseif rf2_player_name == "Rothar" and rf2_player_class == "WARRIOR" then
rf2_spell_list = {
buffs = {
[1] = { tag = "commanding", spellid = 469, unit = "player", size = 24, fontsize = 16, posx = -64, posy = -280, framestrata = "LOW", anchor = "UIParent"},
[2] = { tag = "battle", spellid = 2048, unit = "player", size = 24, fontsize = 16, posx = -32, posy = -280, framestrata = "LOW", anchor = "UIParent"},
[3] = { tag = "SLAM", spellid = 46916, unit = "player", size = 55, fontsize = 32, posx = 0, posy = -80, framestrata = "LOW", anchor = "UIParent"},
--[3] = { tag = "snb", spellid = 50227, unit = "player", size = 48, fontsize = 32, posx = 0 , posy = -30, framestrata = "LOW", anchor = "UIParent"},
--[4] = { tag = "block", spellid = 2565, unit = "player", size = 32, fontsize = 20, posx = -50 , posy = -30, framestrata = "LOW", anchor = "UIParent"},
--[5] = { tag = "gnomeblocker", spellid = 35169, unit = "player", size = 32, fontsize = 20, posx = 50 , posy = -30, framestrata = "LOW", anchor = "UIParent"},
--[6] = { tag = "fireblood", spellid = 40459, unit = "player", size = 32, fontsize = 20, posx = 0 , posy = 20, framestrata = "LOW", anchor = "UIParent"},
--[4] = { tag = "freehero", spellid = 58398, unit = "player", size = 32, fontsize = 20, posx = 0 , posy = -80, framestrata = "LOW", anchor = "UIParent"},
--[3] = { tag = "snb", spellid = 50227, size = 20, fontsize = 15, posx = 30, posy = -260, framestrata = "BACKGROUND", anchor = "UIParent"},
--[3] = { tag = "rampage", spellid = 30033, size = 18, fontsize = 14, posx = -25, posy = -260, framestrata = "BACKGROUND", anchor = "UIParent"},
--[3] = { tag = "berserker", spellid = 18499, size = 32, fontsize = 24, posx = 160, posy = 0, framestrata = "BACKGROUND", anchor = "UIParent"},
},
debuffs = {
[1] = { tag = "sunder", spellid = 25225, ismine = 0, unit = "target", size = 24, fontsize = 16, posx = 0, posy = -280, framestrata = "LOW", anchor = "UIParent"},
[2] = { tag = "demo", spellid = 25203, ismine = 0, unit = "target", size = 24, fontsize = 16, posx = 64, posy = -280, framestrata = "LOW", anchor = "UIParent"},
[3] = { tag = "clap", spellid = 25264, ismine = 0, unit = "target", size = 24, fontsize = 16, posx = 32, posy = -280, framestrata = "LOW", anchor = "UIParent"},
[4] = { tag = "rend", spellid = 47465, ismine = 1, unit = "target", size = 24, fontsize = 16, posx = -96, posy = -280, framestrata = "LOW", anchor = "UIParent"},
--[4] = { tag = "scorpid", spellid = 3043,ismine = 0, unit = "target", size = 18, fontsize = 16, posx = 60, posy = -300, framestrata = "LOW", anchor = "UIParent"},
--[5] = { tag = "fearie", spellid = 26993, ismine = 0, unit = "target", size = 18, fontsize = 16, posx = 90, posy = -300, framestrata = "LOW", anchor = "UIParent"},
--[6] = { tag = "fearieferal", spellid = 27011, ismine = 0, unit = "target", size = 18, fontsize = 16, posx = 90, posy = -300, framestrata = "LOW", anchor = "UIParent"},
--[7] = { tag = "curseofreck", spellid = 27226, ismine = 0, size = 18, fontsize = 14, posx = 50, posy = -230, framestrata = "BACKGROUND", anchor = "UIParent"},
--[8] = { tag = "curseoftong", spellid = 11719, ismine = 0, size = 18, fontsize = 14, posx = 75, posy = -230, framestrata = "BACKGROUND", anchor = "UIParent"},
},
cooldowns = {
--[1] = { tag = "bloodrage", spellid = 2687, size = 32, fontsize = 24, posx = 0, posy = 0, framestrata = "BACKGROUND", anchor = "UIParent"},
--[2] = { tag = "berserkercool", spellid = 18499, size = 32, fontsize = 24, posx = 50, posy = 0, framestrata = "BACKGROUND", anchor = "UIParent"},
--[3] = { tag = "revenge", spellid = 30357, size = 32, fontsize = 24, posx = 0, posy = 80, framestrata = "BACKGROUND", anchor = "UIParent"},
--[4] = { tag = "shieldslam", spellid = 30356, size = 32, fontsize = 24, posx = 40, posy = 80, framestrata = "BACKGROUND", anchor = "UIParent"},
},
}
else
rf2_spell_list = {
buffs = {
},
debuffs = {
},
cooldowns = {
},
}
end
-----------------------------------------------------
-- DO NOT TOUCH ANYTHING BELOW THIS LINE !!!
-----------------------------------------------------
addon:SetScript("OnEvent", function()
if(event=="PLAYER_LOGIN") then
for index,value in ipairs(rf2_spell_list.buffs) do
local string = rf2_spell_list.buffs[index]
addon:rf2_create_icon(string.spellid,"rf2_"..string.tag,string.size,string.fontsize,string.posx,string.posy,string.framestrata,string.anchor)
end
for index,value in ipairs(rf2_spell_list.debuffs) do
local string = rf2_spell_list.debuffs[index]
addon:rf2_create_icon(string.spellid,"rf2_"..string.tag,string.size,string.fontsize,string.posx,string.posy,string.framestrata,string.anchor)
end
for index,value in ipairs(rf2_spell_list.cooldowns) do
local string = rf2_spell_list.cooldowns[index]
addon:rf2_create_icon(string.spellid,"rf2_"..string.tag,string.size,string.fontsize,string.posx,string.posy,string.framestrata,string.anchor)
end
addon:rf2_onUpdate()
end
end)
function addon:rf2_create_icon(spellId,frameName,size,fontsize,posX,posY,framestrata,anchor)
local spellName, spellRank, SpellIcon, SpellCost, spellIsFunnel, spellPowerType, spellCastTime, spellMinRange, spellMaxRange = GetSpellInfo(spellId)
local f = CreateFrame("Frame",frameName,UIParent)
f:SetFrameStrata(framestrata)
f:SetWidth(size)
f:SetHeight(size)
local t = f:CreateTexture(frameName.."_icon","BACKGROUND")
t:SetTexture(SpellIcon)
t:SetTexCoord(0.1,0.9,0.1,0.9)
t:SetAllPoints(f)
f.texture = t
local t2 = f:CreateTexture(nil,"LOW")
t2:SetTexture(bordertexture)
t2:SetVertexColor(0.15,0.1,0.05,0.93)
t2:SetPoint("TOPLEFT", f, "TOPLEFT", -2, 2)
t2:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 2, -2)
f.texture = t2
local time = f:CreateFontString(frameName.."_time", "ARTWORK")
time:SetPoint("CENTER", f, "CENTER", 0, 1)
time:SetFont(NAMEPLATE_FONT,fontsize,"OUTLINE")
time:SetTextColor(1, 1, 0)
time:SetText("")
time:Show()
local num = f:CreateFontString(frameName.."_num", "OVERLAY")
num:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 4, -4)
num:SetFont(NAMEPLATE_FONT,floor(fontsize*0.9),"OUTLINE")
num:SetTextColor(0.8, 0.8, 0.8)
num:SetText("")
num:Show()
f:SetPoint("CENTER",posX,posY)
f:Show()
end
function addon:rf2_onUpdate()
local f = CreateFrame("Frame", "rf2_OnUpdateFrame")
local totalElapsed = 0
local function rf2_OnUpdateFunc(self, elapsed)
totalElapsed = totalElapsed + elapsed
local rf2_update_timer = 1
if (totalElapsed < rf2_update_timer) then
return
else
totalElapsed = totalElapsed - floor(totalElapsed)
for index,value in ipairs(rf2_spell_list.buffs) do
local string = rf2_spell_list.buffs[index]
addon:rf2_check_buff(string.tag,string.spellid,string.unit)
end
for index,value in ipairs(rf2_spell_list.debuffs) do
local string = rf2_spell_list.debuffs[index]
addon:rf2_check_debuff(string.tag,string.spellid,string.unit,string.ismine)
end
for index,value in ipairs(rf2_spell_list.cooldowns) do
local string = rf2_spell_list.cooldowns[index]
addon:rf2_check_cooldown(string.tag,string.spellid)
end
end
end
f:SetScript("OnUpdate", rf2_OnUpdateFunc)
f:Show()
end
function addon:rf2_check_buff(frameTag,spellId,unit)
local spellName, spellRank, SpellIcon, SpellCost, spellIsFunnel, spellPowerType, spellCastTime, spellMinRange, spellMaxRange = GetSpellInfo(spellId)
if unit == nil then
unit = "player"
end
local f = _G["rf2_"..frameTag]
f:SetAlpha(alpha_when_not_active)
if UnitAffectingCombat("player") == 1 then
f:SetAlpha(alpha_when_in_combat)
end
local f2 = _G["rf2_"..frameTag.."_time"]
local f3 = _G["rf2_"..frameTag.."_num"]
f2:SetText("")
f3:SetText("")
local f4 = _G["rf2_"..frameTag.."_icon"]
if use_grey_vertex == 1
then
local shaderSupported = f4:SetDesaturated(1)
end
for i = 1, 40 do
local name, rank, texture, applications, debuffType, duration, timeleft, isMine, isStealable = UnitBuff(unit, i)
--local name, rank, texture, applications, duration, timeleft = UnitBuff(unit, i)
if name == spellName then
timeleft = timeleft-GetTime()
--DEFAULT_CHAT_FRAME:AddMessage("found "..name.." timeleft "..timeleft-GetTime().." duration "..duration.." now "..GetTime())
local floortime = ""
if timeleft ~= nil then
if timeleft >= 60 then
floortime = floor((timeleft/60)+1).."m"
elseif timeleft <= 1 then
floortime = floor(timeleft*10)/10
else
floortime = floor(timeleft+0.5)
end
end
local floornum = ""
if applications ~= nil then
floornum = floor(applications)
if floornum <= 1 then
floornum = ""
end
end
f:SetAlpha(1)
f2:SetText(floortime)
f3:SetText(floornum)
if use_grey_vertex == 1
then
local shaderSupported = f4:SetDesaturated(nil)
end
end
end
if testmode == 1
then
f:SetAlpha(1)
f2:SetText("99")
f3:SetText("9")
end
end
function addon:rf2_check_debuff(frameTag,spellId,unit,myspell)
local spellName, spellRank, SpellIcon, SpellCost, spellIsFunnel, spellPowerType, spellCastTime, spellMinRange, spellMaxRange = GetSpellInfo(spellId)
if unit == nil then
unit = "target"
end
local f = _G["rf2_"..frameTag]
f:SetAlpha(alpha_when_not_active)
if UnitAffectingCombat("player") == 1 then
f:SetAlpha(alpha_when_in_combat)
end
local f2 = _G["rf2_"..frameTag.."_time"]
local f3 = _G["rf2_"..frameTag.."_num"]
f2:SetText("")
f3:SetText("")
local f4 = _G["rf2_"..frameTag.."_icon"]
if use_grey_vertex == 1
then
local shaderSupported = f4:SetDesaturated(1)
end
for i = 1, 40 do
local name, _, texture, applications, debufftype, duration, timeleft, ismine = UnitDebuff(unit, i)
if ismine == 1 or ismine == "player" then
ismine = 1
else
ismine = "x"
end
if ((name == spellName and myspell == 0) or (name == spellName and myspell == ismine)) then
timeleft = timeleft-GetTime()
--DEFAULT_CHAT_FRAME:AddMessage("found "..name.." timeleft "..timeleft.." duration "..duration.." now "..GetTime())
local floortime = ""
if timeleft ~= nil then
if timeleft >= 60 then
floortime = floor((timeleft/60)+1).."m"
elseif timeleft <= 1 then
floortime = floor(timeleft*10)/10
else
floortime = floor(timeleft+0.5)
end
end
local floornum = ""
if applications ~= nil then
floornum = floor(applications)
if floornum == 0 then
floornum = ""
end
end
f:SetAlpha(1)
f2:SetText(floortime)
f3:SetText(floornum)
if use_grey_vertex == 1
then
local shaderSupported = f4:SetDesaturated(nil)
end
end
end
if testmode == 1
then
f:SetAlpha(1)
f2:SetText("99")
f3:SetText("9")
end
end
function addon:rf2_check_cooldown(frameTag,spellId)
local spellName, spellRank, SpellIcon, SpellCost, spellIsFunnel, spellPowerType, spellCastTime, spellMinRange, spellMaxRange = GetSpellInfo(spellId)
local f = _G["rf2_"..frameTag]
f:SetAlpha(alpha_when_not_active)
local f2 = _G["rf2_"..frameTag.."_time"]
local f3 = _G["rf2_"..frameTag.."_num"]
f2:SetText("")
f3:SetText("")
local f4 = _G["rf2_"..frameTag.."_icon"]
if use_grey_vertex == 1
then
local shaderSupported = f4:SetDesaturated(1)
end
local spellCooldownStartTime, spellCooldownDuration, spellEnabled = GetSpellCooldown(spellName);
local localstartime = 0
if spellCooldownStartTime ~= nil then
localstartime = spellCooldownStartTime
end
local floortime = 0
if spellCooldownDuration ~= nil then
floortime = spellCooldownDuration
end
local floornum = ""
if spellEnabled ~= nil then
floornum = floor(spellEnabled)
if floornum == 0 then
floornum = "1"
else
floornum = ""
end
end
local now = GetTime()
local cooldown = (localstartime+floortime-now)
cooldown = floor(cooldown+0.5)
if cooldown > 1 then
f:SetAlpha(1)
f2:SetText(cooldown)
f3:SetText(floornum)
if use_grey_vertex == 1
then
local shaderSupported = f4:SetDesaturated(nil)
end
end
if testmode == 1
then
f:SetAlpha(1)
f2:SetText("99")
f3:SetText("9")
end
end
addon:RegisterEvent"PLAYER_LOGIN" |
local Native = require('lib.native.native')
---@class HeroAttribute
local HeroAttribute = {
Str = Native.ConvertHeroAttribute(1), --HERO_ATTRIBUTE_STR
Int = Native.ConvertHeroAttribute(2), --HERO_ATTRIBUTE_INT
Agi = Native.ConvertHeroAttribute(3), --HERO_ATTRIBUTE_AGI
}
return HeroAttribute
|
local lstage = require 'lstage'
local stage2=lstage.stage(
function(name)
local index = 0
for ix=0, 10000000 do
index = index + 1
end
print(name)
end,4)
local stage1=lstage.stage(
function(name)
local index = 0
for ix=0, 10000000 do
index = index + 1
end
stage2:push('s2')
end,4)
for i=1,10 do
stage1:push('s1')
end
lstage.pool:add(2)
lstage.dispatchevents()
lstage.channel():get()
|
include("terms")
style =
{["off_color"] = "fff",
["on_color"] = "cff",
["line_color"] = "000",
["line_width"] = "2"};
dot_style = {["font_size"] = "40"}
text_style = {["font_size"] = "16"}
ang = {"aOb", "bOc", "cOd", "dOf", "fOg", "gOa"}
symb = "\(\angle\)"
ind = math.random(5)
reply = ""
answ = ""
if (ind == 1) then
first = ang[4]
second = ang[5]
results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 1 && result[4] == 1 && result[5] == 0"
reply = "answer == '" .. msg[1] .. "' " ..
"|| answer == '" .. msg[6] .. "'" ;
ans = "answer = '" .. msg[1] .. "' ";
end
if (ind == 2) then
first = ang[6]
second = ang[1]
results = "result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 0 && result[5] == 1"
reply = "answer == '" .. msg[2] .. "' " ..
"|| answer == '" .. msg[5] .. "'" ;
ans = "answer = '" .. msg[2] .. "' ";
end
if (ind == 3) then
first = ang[1]
second = ang[5]
results = "result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 0 && result[4] == 1 && result[5] == 0"
reply = "answer == '" .. msg[3] .. "' " ..
"|| answer == '" .. msg[6] .. "'" ;
ans = "answer = '" .. msg[3] .. "' ";
end
if (ind == 4) then
first = ang[2]
second = ang[5]
results = "result[0] == 0 && result[1] == 1 && result[2] == 0 && result[3] == 0 && result[4] == 1 && result[5] == 0"
reply = "answer == '" .. msg[4] .. "' " ..
"|| answer == '" .. msg[4] .. "'" ;
ans = "answer = '" .. msg[4] .. "' ";
end
if (ind == 5) then
first = ang[4]
second = ang[6]
results = "result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 1 && result[4] == 0 && result[5] == 1"
reply = "answer == '" .. msg[5] .. "' " ..
"|| answer == '" .. msg[5] .. "'" ;
ans = "answer = '" .. msg[5] .. "' ";
end
mycanvas = function(no)
lib.start_canvas(300, 220, "center", results)
ow = 15
ov = 140
v = 90
lib.add_straight_path(2*ov, 2*ow, {{-ov+ow, v-ow}, {ov, 0}}, style, false, true)
lib.add_text(2*ov, v, "a", text_style, false, false)
lib.add_straight_path(ow+ov, ow, {{0, v}, {ov-ow, -v+ow}}, style, false, true)
lib.add_text(2*ov-ow, 2*ow, "b", text_style, false, false)
lib.add_straight_path(ow+ov, ow, {{0, v}, {-ov+ow, -v+ow}}, style, false, true)
lib.add_text(ov+5, 2*ow, "c", text_style, false, false)
lib.add_straight_path(2*ow, 2*ow, {{ov-ow, v-ow}, {-ov+ow, 0}}, style, false, true)
lib.add_text(3*ow, 3*ow, "d", text_style, false, false)
lib.add_straight_path(2*ow, ow+v, {{ov-ow, 0}, {-ov+ow, v-ow}}, style, false, true)
lib.add_text(3*ow, v+2*ow-5, "f", text_style, false, false)
lib.add_straight_path(2*ow, 2*v, {{ov-ow, -v+ow}, {ov, 0}}, style, false, true)
lib.add_text(3*ow, 2*v, "g", text_style, false, false)
lib.add_text(ow+ov, v+2, ".", dot_style, false, false)
lib.add_text(ow+ov, v+2*ow, "O", text_style, false, false)
lib.end_canvas()
end
|
-- is there a parameter (http://flashair/?parameter=324) given?
if arg[1] then
--there is an argument given
else
--no argument given
end
|
object_draft_schematic_space_chassis_shared_blacksun_heavy_vaksai = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_blacksun_heavy_vaksai.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_blacksun_heavy_vaksai, "object/draft_schematic/space/chassis/shared_blacksun_heavy_vaksai.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_havoc = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_havoc.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_havoc, "object/draft_schematic/space/chassis/shared_havoc.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_hutt_light_heavy = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_hutt_light_heavy.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_hutt_light_heavy, "object/draft_schematic/space/chassis/shared_hutt_light_heavy.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_naboo_n1 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_naboo_n1.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_naboo_n1, "object/draft_schematic/space/chassis/shared_naboo_n1.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_player_gunship_imperial = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_player_gunship_imperial.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_player_gunship_imperial, "object/draft_schematic/space/chassis/shared_player_gunship_imperial.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_player_gunship_neutral = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_player_gunship_neutral.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_player_gunship_neutral, "object/draft_schematic/space/chassis/shared_player_gunship_neutral.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_player_gunship_rebel = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_player_gunship_rebel.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_player_gunship_rebel, "object/draft_schematic/space/chassis/shared_player_gunship_rebel.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_arc170_s01 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_arc170_s01.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_arc170_s01, "object/draft_schematic/space/chassis/shared_texture_kit_arc170_s01.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_arc170_s02 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_arc170_s02.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_arc170_s02, "object/draft_schematic/space/chassis/shared_texture_kit_arc170_s02.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_awing_s06 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_awing_s06.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_awing_s06, "object/draft_schematic/space/chassis/shared_texture_kit_awing_s06.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_bwing_s06 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_bwing_s06.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_bwing_s06, "object/draft_schematic/space/chassis/shared_texture_kit_bwing_s06.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_bwing_s07 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_bwing_s07.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_bwing_s07, "object/draft_schematic/space/chassis/shared_texture_kit_bwing_s07.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_hutt_heavy_s01_s07 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_hutt_heavy_s01_s07.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_hutt_heavy_s01_s07, "object/draft_schematic/space/chassis/shared_texture_kit_hutt_heavy_s01_s07.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_xwing_s06 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_xwing_s06.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_xwing_s06, "object/draft_schematic/space/chassis/shared_texture_kit_xwing_s06.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_xwing_s07 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_xwing_s07.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_xwing_s07, "object/draft_schematic/space/chassis/shared_texture_kit_xwing_s07.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_ywing_longprobe_s06 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_ywing_longprobe_s06.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_ywing_longprobe_s06, "object/draft_schematic/space/chassis/shared_texture_kit_ywing_longprobe_s06.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_ywing_s06 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_ywing_s06.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_ywing_s06, "object/draft_schematic/space/chassis/shared_texture_kit_ywing_s06.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_z95_s06 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_z95_s06.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_z95_s06, "object/draft_schematic/space/chassis/shared_texture_kit_z95_s06.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_texture_kit_z95_s07 = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_texture_kit_z95_s07.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_texture_kit_z95_s07, "object/draft_schematic/space/chassis/shared_texture_kit_z95_s07.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_tiedefender = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_tiedefender.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_tiedefender, "object/draft_schematic/space/chassis/shared_tiedefender.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_tiefighter_heavy = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_tiefighter_heavy.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_tiefighter_heavy, "object/draft_schematic/space/chassis/shared_tiefighter_heavy.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_twing = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_twing.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_twing, "object/draft_schematic/space/chassis/shared_twing.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_space_chassis_shared_z95_heavy = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/space/chassis/shared_z95_heavy.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_space_chassis_shared_z95_heavy, "object/draft_schematic/space/chassis/shared_z95_heavy.iff")
------------------------------------------------------------------------------------------------------------------------------------
|
local function test1()
local function f()
return 1, 2, 3
end
local i, j, k = f()
return i + j + k == 6
end
local function test2()
local function f1()
return 2, 3
end
local function f2(a, b, c)
return a + b + c
end
local i, j = f2(1, f1())
return i == 6 and j == nil
end
local function test3()
local function inner(...)
local a, b = ...
return a + b
end
return inner(2, 3, 4) == 5
end
local function test4()
local function inner(a, ...)
return a + ...
end
return inner(2, 3) == 5
end
local function test5()
local function inner(a, ...)
return a, ...
end
local a, b, c, d
a, b, c, d = 42, inner(1, 2, 3)
return a == 42 and b == 1 and c == 2 and d == 3
end
local function test6()
local function inner(p, ...)
local a, b, c
a, b, c = p, ...
return a, b, c
end
local a, b, c
a, b, c = inner(1, 2, 3)
return a == 1 and b == 2 and c == 3
end
return
test1() and
test2() and
test3() and
test4() and
test5() and
test6()
|
-- Apartment 3: -609.56690000, 51.28212000, 96.60023000
exports('GetHLApartment3Object', function()
return HLApartment3
end)
HLApartment3 = {
interiorId = 146689,
Ipl = {
Interior = {
ipl = "mpbusiness_int_placement_interior_v_mp_apt_h_01_milo__2",
Load = function() EnableIpl(HLApartment3.Ipl.Interior.ipl, true) end,
Remove = function() EnableIpl(HLApartment3.Ipl.Interior.ipl, false) end
},
},
Strip = {
A = "Apart_Hi_Strip_A", B = "Apart_Hi_Strip_B", C = "Apart_Hi_Strip_C",
Enable = function (details, state, refresh)
SetIplPropState(HLApartment3.interiorId, details, state, refresh)
end
},
Booze = {
A = "Apart_Hi_Booze_A", B = "Apart_Hi_Booze_B", C = "Apart_Hi_Booze_C",
Enable = function (details, state, refresh)
SetIplPropState(HLApartment3.interiorId, details, state, refresh)
end
},
Smoke = {
A = "Apart_Hi_Smokes_A", B = "Apart_Hi_Smokes_B", C = "Apart_Hi_Smokes_C",
Enable = function (details, state, refresh)
SetIplPropState(HLApartment3.interiorId, details, state, refresh)
end
},
LoadDefault = function()
HLApartment3.Ipl.Interior.Load()
HLApartment3.Strip.Enable({HLApartment3.Strip.A, HLApartment3.Strip.B, HLApartment3.Strip.C}, false)
HLApartment3.Booze.Enable({HLApartment3.Booze.A, HLApartment3.Booze.B, HLApartment3.Booze.C}, false)
HLApartment3.Smoke.Enable({HLApartment3.Smoke.A, HLApartment3.Smoke.B, HLApartment3.Smoke.C}, false)
RefreshInterior(HLApartment3.interiorId)
end
}
|
object_tangible_event_perk_life_day_tree_dressed = object_tangible_event_perk_shared_life_day_tree_dressed:new {
}
ObjectTemplates:addTemplate(object_tangible_event_perk_life_day_tree_dressed, "object/tangible/event_perk/life_day_tree_dressed.iff")
|
loaded = { internal=true }
disp = function(v)
return rawprint(dump(v))
end
|
require 'paths'
local M = { }
function M.parse(arg)
local cmd = torch.CmdLine()
cmd:text()
cmd:text('Torch-7 Training script')
cmd:text()
cmd:text('Options:')
------------- General options ---------------------
cmd:option('-cache', 'checkpoint/', 'subdirectory in which to save/log experiments')
cmd:option('-data', '/path/to/dataset/folder', 'dataset folder')
cmd:option('-subset', 'LO19', 'LO19 | LN83 | LN84 | LG36 | L498')
------------- Data options ------------------------
cmd:option('-manualSeed', 2, 'Manually set RNG seed')
cmd:option('-GPU', 1, 'Default preferred GPU')
cmd:option('-nGPU', 1, 'Number of GPUs to use by default')
cmd:option('-nDonkeys', 8, 'number of donkeys to initialize (data loading threads)')
cmd:option('-imageSize', 960, 'image size')
cmd:option('-imageCrop', 720, 'cropping size')
cmd:option('-nClasses', 3, 'number of classes in the dataset')
cmd:option('-kernelSize', 5, 'size for LCN')
------------- Training options --------------------
cmd:option('-nEpochs', 120, 'Number of total epochs to run')
cmd:option('-epochSize', 100, 'Number of iterations per epoch')
cmd:option('-epochNumber', 1, 'Manual epoch number (useful on restarts)')
cmd:option('-batchSize', 64, 'mini-batch size (1 = pure stochastic)')
cmd:option('-iterSize', 1, 'Number of batches per iteration')
------------- Testing/Eval options ----------------
cmd:option('-nEpochsTest', 1, 'Number of epochs to perform one testing')
cmd:option('-nEpochsEval', 1, 'Number of epochs to perform one evaluation')
cmd:option('-nEpochsSave', 1, 'Number of epochs to save model')
cmd:option('-saveBest', false, 'If Save the best model')
------------- Optimization options ----------------
cmd:option('-LR', 0.0, 'learning rate; if set, overrides default LR/WD recipe')
cmd:option('-momentum', 0.9, 'momentum')
cmd:option('-weightDecay', 5e-4, 'weight decay')
------------- Model options -----------------------
cmd:option('-netType', 'simple_cnn', 'your deep-net implementation')
cmd:option('-dataset', 'single_dataset', 'Select a customized dataset loader')
cmd:option('-retrain', 'none', 'provide path to model to retrain with')
------------- Run Options -------------------------
cmd:option('-train', false, 'run train procedure, note that not every -dataset support trainDataLoader')
cmd:option('-eval', false, 'run eval procedure, note that not every -dataset support evalDataLoader')
cmd:option('-test', false, 'run test procedure, note that not every -dataset support testDataLoader')
cmd:option('-pipeline', 'standard','run a standard/customized train,test,eval procedure')
cmd:text()
------------ Options from sepcified network -------------
local netType = ''
for i=1, #arg do
if arg[i] == '-netType' then
netType = arg[i+1]
end
end
if netType ~= '' then
cmd:text('Network "'..netType..'" options:')
local config = netType
-- all models should inherit from a basic model
local basicnet = paths.dofile('models/basic_model.lua')
local net = paths.dofile('models/' .. config .. '.lua')
setmetatable(net, {__index=basicnet})
net.arguments(cmd)
cmd:text()
end
local opt = cmd:parse(arg or {})
if (not opt.train) and (not opt.eval) and (not opt.test) then
cmd:error('Must specify at least one running scheme: train, eval or test.')
end
-- append dataset to cache name
opt.cache = path.join(opt.cache, opt.dataset)
-- add commandline specified options
opt.save = paths.concat(
opt.cache,
cmd:string(opt.netType, opt,
{netType=true, retrain=true, cache=true, data=true}))
-- add date/time
opt.save = paths.concat(opt.save, '' .. os.date():gsub(' ',''))
return opt
end
return M
|
HealthSystem = class(Xile.System)
local Health = Xile.Data.Health
function HealthSystem:init(removeEntity)
self:base().init(self)
removeEntity = removeEntity or function() end
local nodes = self:nodes(Asteroid,Health)
self.update = function(self,time)
local a
for node in nodes() do
h = node(Health)
if h.value <= 0 then
removeEntity(node(Asteroid).entity)
end
end
end
end
|
function add(a, b)
return a + b;
end
return add(2, 3)
|
object_tangible_collection_meatlump_listening_location_object_04 = object_tangible_collection_shared_meatlump_listening_location_object_04:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_meatlump_listening_location_object_04, "object/tangible/collection/meatlump_listening_location_object_04.iff") |
-- Copyright (C) 2011 - 2013 David Reid. See included LICENCE file.
function GTGUI.Element:LabelledCollisionGroupSelectorItem(name)
self.Label = GTGUI.Server.CreateElement(self, "labelled-collision-group-selector-item-label");
self.Cross = GTGUI.Server.CreateElement(self, "labelled-collision-group-selector-item-cross");
self.Label:SetText(name);
return self;
end
function GTGUI.Element:LabelledCollisionGroupSelector(title)
self:LabelledElement(title);
-- The right side contains a list of labels with delete buttons on the right side of them. Below these
-- is a drop-down box for the user to pick from.
self.SelectedItemsContainer = GTGUI.Server.CreateElement(self.Right);
self.SelectedItemsContainer:SetStyle("horizontal-align", "right");
self.DropDownBox = GTGUI.Server.CreateElement(self.Right, "picking-dropdown-box");
self.DropDownBox:PickingDropDownBox("Add");
self.DropDownBox:SetStyle("margin-top", "4px");
self.DropDownBox:AppendItem("All"):OnPressed(function()
-- This is a special option. No other option can be used with this one.
self:RemoveAllSelectedGroups();
self:AddSelectedGroup("All");
end);
self.DropDownBox:AppendItem("None"):OnPressed(function()
-- This is a special option. No other option can be used with this one.
self:RemoveAllSelectedGroups();
self:AddSelectedGroup("None");
end);
-- We now want to loop over each collision group in Game.CollisionGroup and add it to the list.
if Game.CollisionGroups then
for key,value in pairs(Game.CollisionGroups) do
if key ~= "All" and key ~= "None" then
self.DropDownBox:AppendItem(key):OnPressed(function()
self:AddSelectedGroup(key);
end);
end
end
else
self.DropDownBox:AppendItem("No Groups");
end
function self:RemoveAllSelectedGroups(blockEvent)
-- We just loop over each child and called the OnSelectionRemoved event, and then delete all children in one go.
if not blockEvent then
for id,element in pairs(self.SelectedItemsContainer.Children) do
if element.Label then
self:OnSelectionRemoved({name = element.Label:GetText()});
end
end
end
self.SelectedItemsContainer:DeleteAllChildren();
end
function self:RemoveSelectedGroupByName(name, blockEvent)
local groupToDelete = self:GetSelectedGroupByName(name);
if groupToDelete then
if not blockEvent then
self:OnSelectionRemoved({name = name});
end
GTGUI.Server.DeleteElement(groupToDelete);
end
end
function self:AddSelectedGroup(name, blockEvent)
-- If we already have a selection of the same name, we just return the existing one instead of re-adding it.
local existingItem = self:GetSelectedGroupByName(name);
if existingItem then
return existingItem;
end
-- If we have an "All" or "None" group, that also needs to be deleted.
self:RemoveSelectedGroupByName("All");
self:RemoveSelectedGroupByName("None");
local newItem = GTGUI.Server.CreateElement(self.SelectedItemsContainer, "labelled-collision-group-selector-item");
newItem:LabelledCollisionGroupSelectorItem(name);
newItem.Cross:OnPressed(function()
self:RemoveSelectedGroupByName(name);
end);
if not blockEvent then
self:OnSelectionAdded({name = name});
end
return newItem;
end
function self:GetSelectedGroupByName(name)
for id,element in pairs(self.SelectedItemsContainer.Children) do
if element.Label and element.Label:GetText() == name then
return element;
end
end
return nil;
end
-- Event handler called when a selection is added.
function self:OnSelectionAdded(arg1)
self.Callbacks:BindOrCall("OnSelectionAdded", arg1);
end
-- Event handler called when a selection is removed.
function self:OnSelectionRemoved(arg1)
self.Callbacks:BindOrCall("OnSelectionRemoved", arg1);
end
return self;
end
|
--require 'torch'
local mytester
local torchtest = torch.TestSuite()
local msize = 100
local precision
-- Lua 5.2 compatibility
local loadstring = loadstring or load
local unpack = unpack or table.unpack
local function maxdiff(x,y)
local d = x-y
if x:type() == 'torch.DoubleTensor' or x:type() == 'torch.FloatTensor' then
return d:abs():max()
else
local dd = torch.Tensor():resize(d:size()):copy(d)
return dd:abs():max()
end
end
-- workarounds for non-existant functions
function torch.HalfTensor:__sub(other)
return (self:real() - other:real()):half()
end
function torch.HalfTensor:mean(dim)
return self:real():mean(dim):half()
end
function torch.HalfTensor:abs()
return self:real():abs():half()
end
function torch.HalfTensor:max()
return self:real():max()
end
function torch.HalfTensor:add(a, b)
return (self:real():add(a, b:real())):half()
end
function torch.HalfTensor:reshape(a, b)
return (self:real():reshape(a, b)):half()
end
function torch.HalfTensor:fill(a)
return self:real():fill(a):half()
end
function torchtest.dot()
local types = {
['torch.DoubleTensor'] = 1e-8, -- for ddot
['torch.FloatTensor'] = 1e-4, -- for sdot
}
for tname, prec in pairs(types) do
local v1 = torch.randn(100):type(tname)
local v2 = torch.randn(100):type(tname)
local res1 = torch.dot(v1,v2)
local res2 = 0
for i = 1,v1:size(1) do
res2 = res2 + v1[i] * v2[i]
end
local err = math.abs(res1-res2)
mytester:assertlt(err, prec, 'error in torch.dot (' .. tname .. ')')
end
end
local genericSingleOpTest = [[
-- [res] torch.functionname([res,] x)
-- contiguous
local m1 = torch.randn(100,100)
local res1 = torch.functionname(m1[{ 4,{} }])
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.functionname(m1[4][i])
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerrc = 0
for i = 1, err:size(1) do
if err[i] > maxerrc then
maxerrc = err[i]
end
end
-- non-contiguous
local m1 = torch.randn(100,100)
local res1 = torch.functionname(m1[{ {}, 4 }])
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.functionname(m1[i][4])
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerrnc = 0
for i = 1, err:size(1) do
if err[i] > maxerrnc then
maxerrnc = err[i]
end
end
return maxerrc, maxerrnc
--]]
function torchtest.sin()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'sin'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.sinh()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'sinh'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.asin()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'asin'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.cos()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'cos'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.cosh()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'cosh'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.acos()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'acos'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.tan()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'tan'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.tanh()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'tanh'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.atan()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'atan'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.log()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'log'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.sqrt()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'sqrt'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.rsqrt()
local function TH_rsqrt(x)
return 1 / math.sqrt(x)
end
local f
local t = genericSingleOpTest:gsub('functionname', 'rsqrt'):gsub('math.rsqrt', 'TH_rsqrt')
local env = { TH_rsqrt=TH_rsqrt, torch=torch, math=math }
if not setfenv then -- Lua 5.2
f = load(t, 'test', 't', env)
else
f = loadstring(t)
setfenv(f, env)
end
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.sigmoid()
-- can't use genericSingleOpTest, since `math.sigmoid` doesn't exist, have to use
-- `torch.sigmoid` instead
local inputValues = {-1000,-1,0,0.5,1,2,1000}
local expectedOutput = {0.0000, 0.2689, 0.5, 0.6225, 0.7311, 0.8808, 1.000}
local precision_4dps = 0.0002
-- float
local inputFT = torch.FloatTensor(inputValues)
local expectedFT = torch.FloatTensor(expectedOutput)
mytester:assertlt((torch.sigmoid(inputFT) - expectedFT):abs():max(), precision_4dps, 'error in torch.sigmoid - single')
mytester:assertlt((inputFT - torch.FloatTensor(inputValues)):abs():max(), precision_4dps, 'error in torch.sigmoid - single')
local sigmoidFT = torch.FloatTensor(inputValues):sigmoid()
mytester:assertlt((sigmoidFT - expectedFT):abs():max(), precision_4dps, 'error in torch.sigmoid - single')
-- double
local inputDT = torch.DoubleTensor(inputValues)
local expectedDT = torch.DoubleTensor(expectedOutput)
mytester:assertlt((torch.sigmoid(inputDT) - expectedDT):abs():max(), precision_4dps, 'error in torch.sigmoid - double')
mytester:assertlt((inputDT - torch.DoubleTensor(inputValues)):abs():max(), precision_4dps, 'error in torch.sigmoid - double')
local sigmoidDT = torch.DoubleTensor(inputValues):sigmoid()
mytester:assertlt((sigmoidDT - expectedDT):abs():max(), precision_4dps, 'error in torch.sigmoid - double')
end
function torchtest.exp()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'exp'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.floor()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'floor'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.ceil()
local f = loadstring(string.gsub(genericSingleOpTest, 'functionname', 'ceil'))
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.frac()
local function TH_frac(x)
return math.fmod(x, 1)
end
local f
local t = genericSingleOpTest:gsub('functionname', 'frac'):gsub('math.frac', 'TH_frac')
local env = { TH_frac=TH_frac, torch=torch, math=math }
if not setfenv then -- Lua 5.2
f = load(t, 'test', 't', env)
else
f = loadstring(t)
setfenv(f, env)
end
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.trunc()
local function TH_trunc(x)
return x - math.fmod(x, 1)
end
local f
local t = genericSingleOpTest:gsub('functionname', 'trunc'):gsub('math.trunc', 'TH_trunc')
local env = { TH_trunc=TH_trunc, torch=torch, math=math }
if not setfenv then -- Lua 5.2
f = load(t, 'test', 't', env)
else
f = loadstring(t)
setfenv(f, env)
end
local maxerrc, maxerrnc = f()
mytester:assertlt(maxerrc, precision, 'error in torch.functionname - contiguous')
mytester:assertlt(maxerrnc, precision, 'error in torch.functionname - non-contiguous')
end
function torchtest.round()
-- [res] torch.round([res,] x)
-- contiguous
local m1 = torch.randn(100,100)
local res1 = torch.round(m1[{ 4,{} }])
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.floor(m1[4][i]+0.5)
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerrc = 0
for i = 1, err:size(1) do
if err[i] > maxerrc then
maxerrc = err[i]
end
end
mytester:assertlt(maxerrc, precision, 'error in torch.round - contiguous')
-- non-contiguous
local m1 = torch.randn(100,100)
local res1 = torch.round(m1[{ {}, 4 }])
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.floor(m1[i][4]+0.5)
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerrnc = 0
for i = 1, err:size(1) do
if err[i] > maxerrnc then
maxerrnc = err[i]
end
end
mytester:assertlt(maxerrnc, precision, 'error in torch.round - non-contiguous')
end
function torchtest.max() -- torch.max([resval, resind,] x [,dim])
-- TH_TENSOR_BASE
local m1 = torch.Tensor(8,2):fill(3):select(2, 1)
local resval, resind = torch.max(m1, 1)
mytester:assert(resind[1] == 1)
-- torch.max( x )
-- contiguous
local m1 = torch.randn(100,100)
local res1 = torch.max(m1)
local res2 = m1[1][1]
for i = 1,m1:size(1) do
for j = 1,m1:size(2) do
if m1[i][j] > res2 then
res2 = m1[i][j]
end
end
end
local err = res1 - res2
mytester:assertlt(err, precision, 'error in torch.max - contiguous')
-- non-contiguous
local m1 = torch.randn(10,10,10)
local m2 = m1[{{}, 4, {}}]
local res1 = torch.max(m2)
local res2 = m2[1][1]
for i = 1,m2:size(1) do
for j = 1,m2:size(2) do
if m2[i][j] > res2 then
res2 = m2[i][j]
end
end
end
local err = res1 - res2
mytester:assertlt(err, precision, 'error in torch.max - non-contiguous')
-- torch.max([resval, resind,] x ,dim])
function lua_max(t, dim)
assert(t:nDimension() == 2)
max_val = t:narrow(dim, 1, 1):clone()
max_ind = t:narrow(dim, 1, 1):clone():long():fill(1)
other = 3 - dim
for i = 1, t:size(other) do
for j = 1, t:size(dim) do
val = t:select(other, i):select(dim, j)
max = max_val:select(other, i):select(dim, 1)
if val > max then
max_val:select(other, i):fill(val)
max_ind:select(other, i):fill(j)
end
end
end
return max_val, max_ind
end
local m1 = torch.randn(100,100)
for dim = 1,2 do
local res1val, res1ind = torch.max(m1, dim)
local res2val, res2ind = lua_max(m1, dim)
mytester:asserteq((res1val-res2val):abs():max(), 0, 'error in torch.max')
mytester:asserteq((res1ind-res2ind):abs():max(), 0, 'error in torch.max')
end
-- NaNs
for index in pairs{1, 5, 100} do
local m1 = torch.randn(100)
m1[index] = 0/0
local res1val, res1ind = torch.max(m1, 1)
mytester:assert(res1val[1] ~= res1val[1], 'error in torch.max (value) - NaNs')
mytester:assert(res1ind[1] == index, 'error in torch.max (index) - NaNs')
local res1val = torch.max(m1)
mytester:assert(res1val ~= res1val, 'error in torch.max - NaNs')
end
-- dim == nDim -1
local a = torch.Tensor({{1,2},{3,4}}):select(2, 1)
local aval, aind = torch.max(a, 1)
mytester:assert(aval[1] == 3)
mytester:assert(aind[1] == 2)
local b = torch.Tensor({{{1,2},{3,4}},{{5,6},{7,8}}}):select(3, 1)
local bval, bind = torch.max(b, 2)
mytester:assert(bval[1][1] == 3)
mytester:assert(bind[1][1] == 2)
mytester:assert(bval[2][1] == 7)
mytester:assert(bind[2][1] == 2)
end
function torchtest.min() -- torch.min([resval, resind,] x [,dim])
-- torch.min( x )
-- contiguous
local m1 = torch.randn(100,100)
local res1 = torch.min(m1)
local res2 = m1[1][1]
for i = 1,m1:size(1) do
for j = 1,m1:size(2) do
if m1[i][j] < res2 then
res2 = m1[i][j]
end
end
end
local err = res1 - res2
mytester:assertlt(err, precision, 'error in torch.min - contiguous')
-- non-contiguous
local m1 = torch.randn(10,10,10)
local m2 = m1[{{}, 4, {}}]
local res1 = torch.min(m2)
local res2 = m2[1][1]
for i = 1,m2:size(1) do
for j = 1,m2:size(2) do
if m2[i][j] < res2 then
res2 = m2[i][j]
end
end
end
local err = res1 - res2
mytester:assertlt(err, precision, 'error in torch.min - non-contiguous')
-- torch.max([resval, resind,] x ,dim])
function lua_min(t, dim)
assert(t:nDimension() == 2)
max_val = t:narrow(dim, 1, 1):clone()
max_ind = t:narrow(dim, 1, 1):clone():long():fill(1)
other = 3 - dim
for i = 1, t:size(other) do
for j = 1, t:size(dim) do
val = t:select(other, i):select(dim, j)
max = max_val:select(other, i):select(dim, 1)
if val < max then
max_val:select(other, i):fill(val)
max_ind:select(other, i):fill(j)
end
end
end
return max_val, max_ind
end
local m1 = torch.randn(100,100)
for dim = 1,2 do
local res1val, res1ind = torch.min(m1, dim)
local res2val, res2ind = lua_min(m1, dim)
mytester:asserteq((res1val-res2val):abs():max(), 0, 'error in torch.max')
mytester:asserteq((res1ind-res2ind):abs():max(), 0, 'error in torch.max')
end
-- NaNs
for index in pairs{1, 5, 100} do
local m1 = torch.randn(100)
m1[index] = 0/0
local res1val, res1ind = torch.min(m1, 1)
mytester:assert(res1val[1] ~= res1val[1], 'error in torch.min (value) - NaNs')
mytester:assert(res1ind[1] == index, 'error in torch.min (index) - NaNs')
local res1val = torch.min(m1)
mytester:assert(res1val ~= res1val, 'error in torch.min - NaNs')
end
-- TH_TENSOR_BASE
local m1 = torch.Tensor(4):fill(3)
local resval, resind = torch.min(m1, 1)
mytester:assert(resind[1] == 1)
end
function torchtest.cmax()
-- Two tensors.
local a = torch.rand(msize, msize)
local b = torch.rand(msize, msize)
local c = torch.cmax(a, b)
local expected_c = torch.zeros(msize, msize)
expected_c:map2(a, b, function(_, a, b) return math.max(a, b) end)
mytester:assertTensorEq(expected_c, c, 0,
'error in torch.cmax(tensor, tensor)')
-- Tensor and scalar.
local v = torch.uniform()
c = torch.cmax(a, v)
expected_c:map(a, function(_, a) return math.max(a, v) end)
mytester:assertTensorEq(expected_c, c, 0,
'error in torch.cmax(tensor, scalar).')
end
function torchtest.cmin()
-- Two tensors.
local a = torch.rand(msize, msize)
local b = torch.rand(msize, msize)
local c = torch.cmin(a, b)
local expected_c = torch.zeros(msize, msize)
expected_c:map2(a, b, function(_, a, b) return math.min(a, b) end)
mytester:assertTensorEq(expected_c, c, 0,
'error in torch.cmin(tensor, tensor)')
-- Tensor and scalar.
local v = torch.uniform()
c = torch.cmin(a, v)
expected_c:map(a, function(_, a) return math.min(a, v) end)
mytester:assertTensorEq(expected_c, c, 0,
'error in torch.cmin(tensor, scalar).')
end
function torchtest.lerp()
local function TH_lerp(a, b, weight)
return a + weight * (b-a);
end
local a = torch.rand(msize, msize)
local b = torch.rand(msize, msize)
local w = math.random()
local result = torch.lerp(a, b, w)
local expected = a:new()
expected:map2(a, b, function(_, a, b) return TH_lerp(a, b, w) end)
mytester:assertTensorEq(expected, result, precision, 'error in torch.lerp(tensor, tensor, weight)')
local a = (math.random()*2-1) * 100000
local b = (math.random()*2-1) * 100000
local w = math.random()
local result = torch.lerp(a, b, w)
local expected = TH_lerp(a, b, w)
mytester:assertalmosteq(expected, result, precision, 'error in torch.lerp(scalar, scalar, weight)')
end
for i, v in ipairs{{10}, {5, 5}} do
torchtest['allAndAny' .. i] =
function ()
local x = torch.ones(unpack(v)):byte()
mytester:assert(x:all(), 'error in all()')
mytester:assert(x:any(), 'error in any()')
x[3] = 0
mytester:assert(not x:all(), 'error in all()')
mytester:assert(x:any(), 'error in any()')
x:zero()
mytester:assert(not x:all(), 'error in all()')
mytester:assert(not x:any(), 'error in any()')
x:fill(2)
mytester:assert(x:all(), 'error in all()')
mytester:assert(x:any(), 'error in any()')
end
end
function torchtest.mv()
local m1 = torch.randn(100,100)
local v1 = torch.randn(100)
local res1 = torch.mv(m1,v1)
local res2 = res1:clone():zero()
for i = 1,m1:size(1) do
for j = 1,m1:size(2) do
res2[i] = res2[i] + m1[i][j] * v1[j]
end
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.mv')
end
function torchtest.fill()
local types = {
'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.FloatTensor',
'torch.DoubleTensor',
'torch.LongTensor',
}
for k,t in ipairs(types) do
-- [res] torch.fill([res,] tensor, value)
local m1 = torch.ones(100,100):type(t)
local res1 = m1:clone()
res1[{ 3,{} }]:fill(2)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ 3,i }] = 2
end
local err = (res1-res2):double():abs():max()
mytester:assertlt(err, precision, 'error in torch.fill - contiguous')
local m1 = torch.ones(100,100):type(t)
local res1 = m1:clone()
res1[{ {},3 }]:fill(2)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = 2
end
local err = (res1-res2):double():abs():max()
mytester:assertlt(err, precision, 'error in torch.fill - non contiguous')
end
end
function torchtest.add()
local types = {
'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.FloatTensor',
'torch.DoubleTensor',
'torch.LongTensor',
}
for k,t in ipairs(types) do
-- [res] torch.add([res,] tensor1, tensor2)
local m1 = torch.randn(100,100):type(t)
local v1 = torch.randn(100):type(t)
local res1 = torch.add(m1[{ 4,{} }],v1)
local res2 = res1:clone():zero()
for i = 1,m1:size(2) do
res2[i] = m1[4][i] + v1[i]
end
local err = (res1-res2):double():abs():max()
mytester:assertlt(err, precision, 'error in torch.add - contiguous' .. ' ' .. t)
local m1 = torch.randn(100,100):type(t)
local v1 = torch.randn(100):type(t)
local res1 = torch.add(m1[{ {},4 }],v1)
local res2 = res1:clone():zero()
for i = 1,m1:size(1) do
res2[i] = m1[i][4] + v1[i]
end
local err = (res1-res2):double():abs():max()
mytester:assertlt(err, precision, 'error in torch.add - non contiguous' .. ' ' .. t)
-- [res] torch.add([res,] tensor, value)
local m1 = torch.randn(10,10):type(t)
local res1 = m1:clone()
res1[{ 3,{} }]:add(2)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ 3,i }] = res2[{ 3,i }] + 2
end
local err = (res1-res2):double():abs():max()
mytester:assertlt(err, precision, 'error in torch.add - scalar, contiguous' .. ' ' .. t)
local m1 = torch.randn(10,10)
local res1 = m1:clone()
res1[{ {},3 }]:add(2)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = res2[{ i,3 }] + 2
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.add - scalar, non contiguous' .. ' ' .. t)
-- [res] torch.add([res,] tensor1, value, tensor2)
end
end
function torchtest.csub()
local rngState = torch.getRNGState()
torch.manualSeed(123)
local a = torch.randn(100,90)
local b = a:clone():normal()
local res_add = torch.add(a, -1, b)
local res_csub = a:clone()
res_csub:csub(b)
mytester:assertlt((res_add - res_csub):abs():max(), 0.00001)
local _ = torch.setRNGState(rngState)
end
function torchtest.csub_scalar()
local rngState = torch.getRNGState()
torch.manualSeed(123)
local a = torch.randn(100,100)
local scalar = 123.5
local res_add = torch.add(a, -scalar)
local res_csub = a:clone()
res_csub:csub(scalar)
mytester:assertlt((res_add - res_csub):abs():max(), 0.00001)
local _ = torch.setRNGState(rngState)
end
function torchtest.neg()
local rngState = torch.getRNGState()
torch.manualSeed(123)
local a = torch.randn(100,90)
local zeros = torch.Tensor():resizeAs(a):zero()
local res_add = torch.add(zeros, -1, a)
local res_neg = a:clone()
res_neg:neg()
mytester:assertlt((res_add - res_neg):abs():max(), 0.00001)
local _ = torch.setRNGState(rngState)
end
function torchtest.cinv()
local rngState = torch.getRNGState()
torch.manualSeed(123)
local a = torch.randn(100,89)
local zeros = torch.Tensor():resizeAs(a):zero()
local res_pow = torch.pow(a, -1)
local res_inv = a:clone()
res_inv:cinv()
mytester:assertlt((res_pow - res_inv):abs():max(), 0.00001)
local _ = torch.setRNGState(rngState)
end
function torchtest.mul()
local types = {
'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.FloatTensor',
'torch.DoubleTensor',
'torch.LongTensor',
}
for k,t in ipairs(types) do
local m1 = torch.randn(10,10):type(t)
local res1 = m1:clone()
res1[{ {},3 }]:mul(2)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = res2[{ i,3 }] * 2
end
local err = (res1-res2):double():abs():max()
mytester:assertlt(err, precision, 'error in torch.mul - scalar, non contiguous' .. ' ' .. t)
end
end
function torchtest.div()
local types = {
'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.FloatTensor',
'torch.DoubleTensor',
'torch.LongTensor',
}
for k,t in ipairs(types) do
local m1 = torch.Tensor(10,10):uniform(0,10):type(t)
local res1 = m1:clone()
res1[{ {},3 }]:div(2)
local res2 = m1:clone()
for i = 1,m1:size(1) do
local ok = pcall(function() res2[{ i,3 }] = res2[{ i,3 }] / 2 end)
if not ok then
res2[{ i,3 }] = torch.floor(res2[{ i,3 }] / 2)
end
end
local err = (res1-res2):double():abs():max()
mytester:assertlt(err, precision, 'error in torch.div - scalar, non contiguous' .. ' ' .. t)
end
end
function torchtest.lshift()
local m1 = torch.LongTensor(10,10):random(0,100)
local res1 = m1:clone()
local q = 2
local f = math.pow(2, q)
res1[{ {},3 }]:lshift(q)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = res2[{ i,3 }] * f
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.lshift - scalar, non contiguous')
local m1 = torch.LongTensor(10,10):random(0,100)
local res1 = m1:clone()
local q = 2
res1:lshift(q)
local res2 = m1:clone()
for i = 1,m1:size(1) do
for j = 1,m1:size(1) do
res2[{ i,j }] = res2[{ i,j }] * f
end
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.lshift - scalar, contiguous')
end
function torchtest.rshift()
local m1 = torch.LongTensor(10,10):random(0,100)
local res1 = m1:clone()
local q = 2
local f = math.pow(2, q)
res1[{ {},3 }]:rshift(q)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = math.floor(res2[{ i,3 }] / f)
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.rshift - scalar, non contiguous')
local m1 = torch.LongTensor(10,10):random(0,100)
local res1 = m1:clone()
local q = 2
res1:rshift(q)
local res2 = m1:clone()
for i = 1,m1:size(1) do
for j = 1,m1:size(1) do
res2[{ i,j }] = math.floor(res2[{ i,j }] / f)
end
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.rshift - scalar, contiguous')
end
function torchtest.fmod()
local m1 = torch.Tensor(10,10):uniform(-10, 10)
local res1 = m1:clone()
local q = 2.1
res1[{ {},3 }]:fmod(q)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = math.fmod(res2[{ i,3 }], q)
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.fmod - scalar, non contiguous')
end
function torchtest.remainder()
local m1 = torch.Tensor(10, 10):uniform(-10, 10)
local res1 = m1:clone()
local q = 2.1
res1[{ {},3 }]:remainder(q)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = res2[{ i,3 }] % q
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.remainder - scalar, non contiguous')
end
function torchtest.bitand()
local m1 = torch.LongTensor(10,10):random(0,100)
local res1 = m1:clone()
local val = 32 -- This should be a power of 2
res1[{ {},3 }]:bitand(val - 1)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = res2[{ i,3 }] % val
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.bitand - scalar, non contiguous')
local m1 = torch.LongTensor(10,10):random(0,100)
local res1 = m1:clone()
res1:bitand(val - 1)
local res2 = m1:clone()
for i = 1,m1:size(1) do
for j = 1,m1:size(1) do
res2[{ i,j }] = res2[{ i,j }] % val
end
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.bitand - scalar, contiguous')
end
function torchtest.bitor()
local m1 = torch.LongTensor(10,10):random(0,10000)
local res1 = m1:clone()
local val = 32 -- This should be a power of 2
res1[{ {},3 }]:bitor(val-1)
local res2 = m1:clone()
for i = 1,m1:size(1) do
res2[{ i,3 }] = math.floor(res2[{ i,3 }] / val) * val + (val - 1)
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.bitor - scalar, non contiguous')
local m1 = torch.LongTensor(10,10):random(0,10000)
local res1 = m1:clone()
res1:bitor(val - 1)
local res2 = m1:clone()
for i = 1,m1:size(1) do
for j = 1,m1:size(1) do
res2[{ i,j }] = math.floor(res2[{ i,j }] / val) * val + (val - 1)
end
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.bitor - scalar, contiguous')
end
function torchtest.cbitxor()
local t1 = torch.LongTensor(10,10):random(0,10000)
local t2 = torch.LongTensor(10,10):random(10001,20000)
-- Perform xor swap and check results
local t3 = torch.cbitxor(t1, t2)
local r1 = torch.cbitxor(t3, t2)
local r2 = torch.cbitxor(t3, t1)
local err1 = (r1 - t1):abs():max()
local err2 = (r2 - t2):abs():max()
mytester:assertlt(err1 + err2, precision, 'error in torch.cbitxor contiguous')
end
function torchtest.mm()
-- helper function
local function matrixmultiply(mat1,mat2)
local n = mat1:size(1)
local m = mat1:size(2)
local p = mat2:size(2)
local res = torch.zeros(n,p)
for i = 1, n do
for j = 1, p do
local sum = 0
for k = 1, m do
sum = sum + mat1[i][k]*mat2[k][j]
end
res[i][j] = sum
end
end
return res
end
-- contiguous case
local n, m, p = 10, 10, 5
local mat1 = torch.randn(n,m)
local mat2 = torch.randn(m,p)
local res = torch.mm(mat1,mat2)
local res2 = matrixmultiply(mat1,mat2)
mytester:assertTensorEq(res,res2,precision,'error in torch.mm')
-- non contiguous case 1
local n, m, p = 10, 10, 5
local mat1 = torch.randn(n,m)
local mat2 = torch.randn(p,m):t()
local res = torch.mm(mat1,mat2)
local res2 = matrixmultiply(mat1,mat2)
mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous')
-- non contiguous case 2
local n, m, p = 10, 10, 5
local mat1 = torch.randn(m,n):t()
local mat2 = torch.randn(m,p)
local res = torch.mm(mat1,mat2)
local res2 = matrixmultiply(mat1,mat2)
mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous')
-- non contiguous case 3
local n, m, p = 10, 10, 5
local mat1 = torch.randn(m,n):t()
local mat2 = torch.randn(p,m):t()
local res = torch.mm(mat1,mat2)
local res2 = matrixmultiply(mat1,mat2)
mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous')
-- test with zero stride
local n, m, p = 10, 10, 5
local mat1 = torch.randn(n,m)
local mat2 = torch.randn(m,1):expand(m,p)
local res = torch.mm(mat1,mat2)
local res2 = matrixmultiply(mat1,mat2)
mytester:assertTensorEq(res,res2,precision,'error in torch.mm, non contiguous, zero stride')
end
function torchtest.bmm()
local num_batches = 10
local M, N, O = 23, 8, 12
local b1 = torch.randn(num_batches, M, N)
local b2 = torch.randn(num_batches, N, O)
local res = torch.bmm(b1, b2)
for i = 1, num_batches do
local r = torch.mm(b1[i], b2[i])
mytester:assertTensorEq(r, res[i], precision, 'result matrix ' .. i .. ' wrong')
end
end
function torchtest.addbmm()
local num_batches = 10
local M, N, O = 12, 8, 5
local b1 = torch.randn(num_batches, M, N)
local b2 = torch.randn(num_batches, N, O)
local res = torch.bmm(b1, b2)
local res2 = torch.Tensor():resizeAs(res[1]):zero()
res2:addbmm(b1,b2)
mytester:assertTensorEq(res2, res:sum(1)[1], precision, 'addbmm result wrong')
res2:addbmm(1,b1,b2)
mytester:assertTensorEq(res2, res:sum(1)[1]*2, precision, 'addbmm result wrong')
res2:addbmm(1,res2,.5,b1,b2)
mytester:assertTensorEq(res2, res:sum(1)[1]*2.5, precision, 'addbmm result wrong')
local res3 = torch.addbmm(1,res2,0,b1,b2)
mytester:assertTensorEq(res3, res2, precision, 'addbmm result wrong')
local res4 = torch.addbmm(1,res2,.5,b1,b2)
mytester:assertTensorEq(res4, res:sum(1)[1]*3, precision, 'addbmm result wrong')
local res5 = torch.addbmm(0,res2,1,b1,b2)
mytester:assertTensorEq(res5, res:sum(1)[1], precision, 'addbmm result wrong')
local res6 = torch.addbmm(.1,res2,.5,b1,b2)
mytester:assertTensorEq(res6, res2*.1 + res:sum(1)*.5, precision, 'addbmm result wrong')
end
function torchtest.baddbmm()
local num_batches = 10
local M, N, O = 12, 8, 5
local b1 = torch.randn(num_batches, M, N)
local b2 = torch.randn(num_batches, N, O)
local res = torch.bmm(b1, b2)
local res2 = torch.Tensor():resizeAs(res):zero()
res2:baddbmm(b1,b2)
mytester:assertTensorEq(res2, res, precision, 'baddbmm result wrong')
res2:baddbmm(1,b1,b2)
mytester:assertTensorEq(res2, res*2, precision, 'baddbmm result wrong')
res2:baddbmm(1,res2,.5,b1,b2)
mytester:assertTensorEq(res2, res*2.5, precision, 'baddbmm result wrong')
local res3 = torch.baddbmm(1,res2,0,b1,b2)
mytester:assertTensorEq(res3, res2, precision, 'baddbmm result wrong')
local res4 = torch.baddbmm(1,res2,.5,b1,b2)
mytester:assertTensorEq(res4, res*3, precision, 'baddbmm result wrong')
local res5 = torch.baddbmm(0,res2,1,b1,b2)
mytester:assertTensorEq(res5, res, precision, 'baddbmm result wrong')
local res6 = torch.baddbmm(.1,res2,.5,b1,b2)
mytester:assertTensorEq(res6, res2*.1 + res*.5, precision, 'baddbmm result wrong')
end
function torchtest.clamp()
local m1 = torch.rand(100):mul(5):add(-2.5) -- uniform in [-2.5, 2.5]
-- just in case we're extremely lucky:
local min_val = -1
local max_val = 1
m1[1] = min_val
m1[2] = max_val
local res1 = m1:clone()
res1:clamp(min_val, max_val)
local res2 = m1:clone()
for i = 1,m1:size(1) do
if res2[i] > max_val then
res2[i] = max_val
elseif res2[i] < min_val then
res2[i] = min_val
end
end
local err = (res1-res2):abs():max()
mytester:assertlt(err, precision, 'error in torch.clamp - scalar, non contiguous')
end
function torchtest.pow() -- [res] torch.pow([res,] x)
-- base - tensor, exponent - number
-- contiguous
local m1 = torch.randn(100,100)
local res1 = torch.pow(m1[{ 4,{} }], 3)
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.pow(m1[4][i], 3)
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
if err[i] > maxerr then
maxerr = err[i]
end
end
mytester:assertlt(maxerr, precision, 'error in torch.pow - contiguous')
-- non-contiguous
local m1 = torch.randn(100,100)
local res1 = torch.pow(m1[{ {}, 4 }], 3)
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.pow(m1[i][4], 3)
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
if err[i] > maxerr then
maxerr = err[i]
end
end
mytester:assertlt(maxerr, precision, 'error in torch.pow - non-contiguous')
-- base - number, exponent - tensor
-- contiguous
local m1 = torch.randn(100,100)
local res1 = torch.pow(3, m1[{ 4,{} }])
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.pow(3, m1[4][i])
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
if err[i] > maxerr then
maxerr = err[i]
end
end
mytester:assertlt(maxerr, precision, 'error in torch.pow - contiguous')
-- non-contiguous
local m1 = torch.randn(100,100)
local res1 = torch.pow(3, m1[{ {}, 4 }])
local res2 = res1:clone():zero()
for i = 1,res1:size(1) do
res2[i] = math.pow(3, m1[i][4])
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
err[i] = math.abs(res1[i] - res2[i])
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
if err[i] > maxerr then
maxerr = err[i]
end
end
mytester:assertlt(maxerr, precision, 'error in torch.pow - non-contiguous')
end
function torchtest.cdiv()
local types = {
'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.FloatTensor',
'torch.DoubleTensor',
'torch.LongTensor',
}
for k,t in ipairs(types) do
-- [res] torch.cdiv([res,] tensor1, tensor2)
-- contiguous
local m1 = torch.Tensor(10, 10, 10):uniform(0,10):type(t)
local m2 = torch.Tensor(10, 10 * 10):uniform(0,10):type(t)
m2[m2:eq(0)] = 2
local sm1 = m1[{4, {}, {}}]
local sm2 = m2[{4, {}}]
local res1 = torch.cdiv(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
local ok = pcall(function() res2[i][j] = sm1[i][j] / sm2[idx1d] end)
if not ok then
res2[i][j] = torch.floor(sm1[i][j] / sm2[idx1d])
end
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cdiv - contiguous' .. ' ' .. t)
-- non-contiguous
local m1 = torch.Tensor(10, 10, 10):uniform(0,10):type(t)
local m2 = torch.Tensor(10 * 10, 10 * 10):uniform(0,10):type(t)
m2[m2:eq(0)] = 2
local sm1 = m1[{{}, 4, {}}]
local sm2 = m2[{{}, 4}]
local res1 = torch.cdiv(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
local ok = pcall(function() res2[i][j] = sm1[i][j] / sm2[idx1d] end)
if not ok then
res2[i][j] = torch.floor(sm1[i][j] / sm2[idx1d])
end
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cdiv - non-contiguous' .. ' ' .. t)
end
end
function torchtest.cfmod()
-- contiguous
local m1 = torch.Tensor(10, 10, 10):uniform(-10, 10)
local m2 = torch.Tensor(10, 10 * 10):uniform(-3, 3)
local sm1 = m1[{4, {}, {}}]
local sm2 = m2[{4, {}}]
local res1 = torch.cfmod(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = math.fmod(sm1[i][j], sm2[idx1d])
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cfmod - contiguous')
-- non-contiguous
local m1 = torch.Tensor(10, 10, 10):uniform(-10, 10)
local m2 = torch.Tensor(10 * 10, 10 * 10):uniform(-3, 3)
local sm1 = m1[{{}, 4, {}}]
local sm2 = m2[{{}, 4}]
local res1 = torch.cfmod(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = math.fmod(sm1[i][j], sm2[idx1d])
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cfmod - non-contiguous')
end
function torchtest.cremainder()
-- contiguous
local m1 = torch.Tensor(10, 10, 10):uniform(-10, 10)
local m2 = torch.Tensor(10, 10 * 10):uniform(-3, 3)
local sm1 = m1[{4, {}, {}}]
local sm2 = m2[{4, {}}]
local res1 = torch.cremainder(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = sm1[i][j] % sm2[idx1d]
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cremainder - contiguous')
-- non-contiguous
local m1 = torch.Tensor(10, 10, 10):uniform(-10, 10)
local m2 = torch.Tensor(10 * 10, 10 * 10):uniform(-3, 3)
local sm1 = m1[{{}, 4, {}}]
local sm2 = m2[{{}, 4}]
local res1 = torch.cremainder(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = sm1[i][j] % sm2[idx1d]
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cremainder - non-contiguous')
end
function torchtest.cmul()
local types = {
'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.FloatTensor',
'torch.DoubleTensor',
'torch.LongTensor',
}
for k,t in ipairs(types) do
-- [res] torch.cmul([res,] tensor1, tensor2)
-- contiguous
local m1 = torch.randn(10, 10, 10):type(t)
local m2 = torch.randn(10, 10 * 10):type(t)
local sm1 = m1[{4, {}, {}}]
local sm2 = m2[{4, {}}]
local res1 = torch.cmul(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = sm1[i][j] * sm2[idx1d]
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cmul - contiguous' .. ' ' .. t)
-- non-contiguous
local m1 = torch.randn(10, 10, 10):type(t)
local m2 = torch.randn(10 * 10, 10 * 10):type(t)
local sm1 = m1[{{}, 4, {}}]
local sm2 = m2[{{}, 4}]
local res1 = torch.cmul(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = sm1[i][j] * sm2[idx1d]
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cmul - non-contiguous' .. ' ' .. t)
end
end
function torchtest.cpow() -- [res] torch.cpow([res,] tensor1, tensor2)
-- contiguous
local m1 = torch.rand(10, 10, 10)
local m2 = torch.rand(10, 10 * 10)
local sm1 = m1[{4, {}, {}}]
local sm2 = m2[{4, {}}]
local res1 = torch.cpow(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = math.pow(sm1[i][j], sm2[idx1d])
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cpow - contiguous')
-- non-contiguous
local m1 = torch.rand(10, 10, 10)
local m2 = torch.rand(10 * 10, 10 * 10)
local sm1 = m1[{{}, 4, {}}]
local sm2 = m2[{{}, 4}]
local res1 = torch.cpow(sm1, sm2)
local res2 = res1:clone():zero()
for i = 1,sm1:size(1) do
for j = 1, sm1:size(2) do
local idx1d = (((i-1)*sm1:size(1)))+j
res2[i][j] = math.pow(sm1[i][j],sm2[idx1d])
end
end
local err = res1:clone():zero()
-- find absolute error
for i = 1, res1:size(1) do
for j = 1, res1:size(2) do
err[i][j] = math.abs(res1[i][j] - res2[i][j])
end
end
-- find maximum element of error
local maxerr = 0
for i = 1, err:size(1) do
for j = 1, err:size(2) do
if err[i][j] > maxerr then
maxerr = err[i][j]
end
end
end
mytester:assertlt(maxerr, precision, 'error in torch.cpow - non-contiguous')
end
function torchtest.sum()
local x = torch.rand(msize,msize)
local mx = torch.sum(x,2)
local mxx = torch.Tensor()
torch.sum(mxx,x,2)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.sum value')
local y = torch.rand(5, 5, 5)
for i=1,3 do
local a = y:sum(i)
local b = y:narrow(i, 1, 1):clone():zero()
for j = 1, 5 do
b:add(y:narrow(i, j, 1))
end
mytester:asserteq(maxdiff(a, b), 0, 'torch.sum value')
end
end
function torchtest.prod()
local x = torch.rand(msize,msize)
local mx = torch.prod(x,2)
local mxx = torch.Tensor()
torch.prod(mxx,x,2)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.prod value')
local y = torch.rand(5, 5, 5)
for i=1,3 do
local a = y:prod(i)
local b = y:narrow(i, 1, 1):clone():fill(1)
for j = 1, 5 do
b:cmul(y:narrow(i, j, 1))
end
mytester:asserteq(maxdiff(a, b), 0, 'torch.sum value')
end
end
function torchtest.cumsum()
local x = torch.rand(msize,msize)
local mx = torch.cumsum(x,2)
local mxx = torch.Tensor()
torch.cumsum(mxx,x,2)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.cumsum value')
end
function torchtest.cumprod()
local x = torch.rand(msize,msize)
local mx = torch.cumprod(x,2)
local mxx = torch.Tensor()
torch.cumprod(mxx,x,2)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.cumprod value')
end
function torchtest.cross()
local x = torch.rand(msize,3,msize)
local y = torch.rand(msize,3,msize)
local mx = torch.cross(x,y)
local mxx = torch.Tensor()
torch.cross(mxx,x,y)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.cross value')
end
function torchtest.zeros()
local mx = torch.zeros(msize,msize)
local mxx = torch.Tensor()
torch.zeros(mxx,msize,msize)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.zeros value')
end
function torchtest.histc()
local x = torch.Tensor{ 2, 4, 2, 2, 5, 4 }
local y = torch.histc(x, 5, 1, 5) -- nbins, min, max
local z = torch.Tensor{ 0, 3, 0, 2, 1 }
mytester:assertTensorEq(y,z,precision,'error in torch.histc')
end
function torchtest.bhistc()
local x = torch.Tensor(3, 6)
x[1] = torch.Tensor{ 2, 4, 2, 2, 5, 4 }
x[2] = torch.Tensor{ 3, 5, 1, 5, 3, 5 }
x[3] = torch.Tensor{ 3, 4, 2, 5, 5, 1 }
local y = torch.bhistc(x, 5, 1, 5) -- nbins, min, max
local z = torch.Tensor(3, 5)
z[1] = torch.Tensor{ 0, 3, 0, 2, 1 }
z[2] = torch.Tensor{ 1, 0, 2, 0, 3 }
z[3] = torch.Tensor{ 1, 1, 1, 1, 2 }
mytester:assertTensorEq(y,z,precision,'error in torch.bhistc in last dimension')
end
function torchtest.ones()
local mx = torch.ones(msize,msize)
local mxx = torch.Tensor()
torch.ones(mxx,msize,msize)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.ones value')
end
function torchtest.diag()
local x = torch.rand(msize,msize)
local mx = torch.diag(x)
local mxx = torch.Tensor()
torch.diag(mxx,x)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.diag value')
end
function torchtest.eye()
local mx = torch.eye(msize,msize)
local mxx = torch.Tensor()
torch.eye(mxx,msize,msize)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.eye value')
end
function torchtest.renorm()
local m1 = torch.randn(10,5)
local res1 = torch.Tensor()
local m2
local function renorm(matrix, value, dim, max_norm)
local m1 = matrix:transpose(dim, 1):contiguous()
-- collapse non-dim dimensions:
m2 = m1:reshape(m1:size(1), m1:nElement()/m1:size(1))
local norms = m2:norm(value,2)
-- clip
local new_norms = norms:clone()
new_norms[torch.gt(norms, max_norm)] = max_norm
new_norms:cdiv(norms:add(1e-7))
-- renormalize
m1:cmul(new_norms:expandAs(m1))
return m1:transpose(dim, 1)
end
-- note that the axis fed to torch.renorm is different (2~=1)
local maxnorm = m1:norm(2,1):mean()
m2 = renorm(m1,2,2,maxnorm)
m1:renorm(2,2,maxnorm)
mytester:assertTensorEq(m1, m2, 0.00001, 'error in renorm')
mytester:assertTensorEq(m1:norm(2,1), m2:norm(2,1), 0.00001, 'error in renorm')
m1 = torch.randn(3,4,5)
m2 = m1:transpose(2,3):contiguous():reshape(15,4)
maxnorm = m2:norm(2,1):mean()
m2 = renorm(m2,2,2,maxnorm)
m1:renorm(2,2,maxnorm)
local m3 = m1:transpose(2,3):contiguous():reshape(15,4)
mytester:assertTensorEq(m3, m2, 0.00001, 'error in renorm')
mytester:assertTensorEq(m3:norm(2,1), m2:norm(2,1), 0.00001, 'error in renorm')
end
function torchtest.multinomialwithreplacement()
local n_row = 3
for n_col=4,5 do
local t=os.time()
torch.manualSeed(t)
local prob_dist = torch.rand(n_row,n_col)
prob_dist:select(2,n_col):fill(0) --index n_col shouldn't be sampled
local n_sample = n_col
local sample_indices = torch.multinomial(prob_dist, n_sample, true)
mytester:assert(prob_dist:dim() == 2, "wrong number of prob_dist dimensions")
mytester:assert(sample_indices:size(2) == n_sample, "wrong number of samples")
for i=1,n_row do
for j=1,n_sample do
mytester:assert(sample_indices[{i,j}] ~= n_col, "sampled an index with zero probability")
end
end
end
end
function torchtest.multinomialwithoutreplacement()
local n_row = 3
for n_col=4,5 do
local t=os.time()
torch.manualSeed(t)
local prob_dist = torch.rand(n_row,n_col)
prob_dist:select(2,n_col):fill(0) --index n_col shouldn't be sampled
local n_sample = 3
local sample_indices = torch.multinomial(prob_dist, n_sample, false)
mytester:assert(prob_dist:dim() == 2, "wrong number of prob_dist dimensions")
mytester:assert(sample_indices:size(2) == n_sample, "wrong number of samples")
for i=1,n_row do
local row_samples = {}
for j=1,n_sample do
local sample_idx = sample_indices[{i,j}]
mytester:assert(
sample_idx ~= n_col, "sampled an index with zero probability"
)
mytester:assert(
not row_samples[sample_idx], "sampled an index twice"
)
row_samples[sample_idx] = true
end
end
end
end
function torchtest.aliasMultinomial()
for i =1,5 do
local n_class = 5
local t=os.time()
torch.manualSeed(t)
local probs = torch.Tensor(n_class):uniform(0,1)
probs:div(probs:sum())
local output = torch.LongTensor(1000, 10000)
local n_samples = output:nElement()
local prob_state = torch.multinomialAliasSetup(probs)
mytester:assert(prob_state[1]:min() > 0, "Index ="..prob_state[1]:min().."alias indices has an index below or equal to 0")
mytester:assert(prob_state[1]:max() <= n_class, prob_state[1]:max().." alias indices has an index exceeding num_class")
local prob_state = torch.multinomialAliasSetup(probs, prob_state)
mytester:assert(prob_state[1]:min() > 0, "Index ="..prob_state[1]:min().."alias indices has an index below or equal to 0(cold)")
mytester:assert(prob_state[1]:max() <= n_class, prob_state[1]:max()..","..prob_state[1]:min().." alias indices has an index exceeding num_class(cold)")
local output = torch.LongTensor(n_samples)
output = torch.multinomialAlias(output, prob_state)
mytester:assert(output:nElement() == n_samples, "wrong number of samples")
mytester:assert(output:min() > 0, "sampled indices has an index below or equal to 0")
mytester:assert(output:max() <= n_class, "indices has an index exceeding num_class")
end
end
function torchtest.multinomialvector()
local n_col = 4
local t=os.time()
torch.manualSeed(t)
local prob_dist = torch.rand(n_col)
local n_sample = n_col
local sample_indices = torch.multinomial(prob_dist, n_sample, true)
local s_dim = sample_indices:dim()
mytester:assert(s_dim == 1, "wrong number of returned dimensions: "..s_dim)
mytester:assert(prob_dist:dim() == 1, "wrong number of prob_dist dimensions")
mytester:assert(sample_indices:size(1) == n_sample, "wrong number of samples")
end
function torchtest.range()
local mx = torch.range(0,1)
local mxx = torch.Tensor()
torch.range(mxx,0,1)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value')
-- Check range for non-contiguous tensors.
local x = torch.zeros(2, 3)
local y = x:narrow(2, 2, 2)
y:range(0, 3)
mytester:assertTensorEq(x, torch.Tensor{{0, 0, 1}, {0, 2, 3}}, 1e-16,
'non-contiguous range failed')
end
function torchtest.rangenegative()
local mx = torch.Tensor({1,0})
local mxx = torch.Tensor()
torch.range(mxx,1,0,-1)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value for negative step')
end
function torchtest.rangeequalbounds()
local mx = torch.Tensor({1})
local mxx = torch.Tensor()
torch.range(mxx,1,1,-1)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value for equal bounds step')
torch.range(mxx,1,1,1)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.range value for equal bounds step')
end
function torchtest.rangefloat()
local mx = torch.FloatTensor():range(0.6, 0.9, 0.1)
mytester:asserteq(mx:size(1), 4, 'wrong size for FloatTensor range')
mx = torch.FloatTensor():range(1, 10, 0.3)
mytester:asserteq(mx:size(1), 31, 'wrong size for FloatTensor range')
end
function torchtest.rangedouble()
local mx = torch.DoubleTensor():range(0.6, 0.9, 0.1)
mytester:asserteq(mx:size(1), 4, 'wrong size for DoubleTensor range')
mx = torch.DoubleTensor():range(1, 10, 0.3)
mytester:asserteq(mx:size(1), 31, 'wrong size for DoubleTensor range')
end
function torchtest.randperm()
local t=os.time()
torch.manualSeed(t)
local mx = torch.randperm(msize)
local mxx = torch.Tensor()
torch.manualSeed(t)
torch.randperm(mxx,msize)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.randperm value')
end
function torchtest.reshape()
local x = torch.rand(10,13,23)
local mx = torch.reshape(x,130,23)
local mxx = torch.Tensor()
torch.reshape(mxx,x,130,23)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.reshape value')
end
local function assertIsOrdered(order, x, mxx, ixx, task)
local areOrdered
if order == 'descending' then
areOrdered = function(a, b) return a >= b end
elseif order == 'ascending' then
areOrdered = function(a, b) return a <= b end
else
error('unknown order "' .. order .. '", must be "ascending" or "descending"')
end
local decreasing = true
for j = 1,msize do
for k = 2,msize do
decreasing = decreasing and areOrdered(mxx[j][k-1], mxx[j][k])
end
end
mytester:assert(decreasing, 'torch.sort (' .. order .. ') values unordered for ' .. task)
local seen = torch.ByteTensor(msize)
local indicesCorrect = true
for k = 1,msize do
seen:zero()
for j = 1,msize do
indicesCorrect = indicesCorrect and (x[k][ixx[k][j]] == mxx[k][j])
seen[ixx[k][j]] = 1
end
indicesCorrect = indicesCorrect and (torch.sum(seen) == msize)
end
mytester:assert(indicesCorrect, 'torch.sort (' .. order .. ') indices wrong for ' .. task)
end
function torchtest.sortAscending()
local x = torch.rand(msize,msize)
local mx,ix = torch.sort(x)
-- Test use of result tensor
local mxx = torch.Tensor()
local ixx = torch.LongTensor()
torch.sort(mxx,ixx,x)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.sort (ascending) value')
mytester:asserteq(maxdiff(ix,ixx),0,'torch.sort (ascending) index')
-- Test sorting of random numbers
assertIsOrdered('ascending', x, mxx, ixx, 'random')
mytester:assertTensorEq(
torch.sort(torch.Tensor{ 50, 40, 30, 20, 10 }),
torch.Tensor{ 10, 20, 30, 40, 50 },
1e-16,
"torch.sort (ascending) simple sort"
)
-- Test that we still have proper sorting with duplicate keys
local x = torch.floor(torch.rand(msize,msize)*10)
torch.sort(mxx,ixx,x)
assertIsOrdered('ascending', x, mxx, ixx, 'random with duplicate keys')
end
function torchtest.sortDescending()
local x = torch.rand(msize,msize)
local mx,ix = torch.sort(x,true)
-- Test use of result tensor
local mxx = torch.Tensor()
local ixx = torch.LongTensor()
torch.sort(mxx,ixx,x,true)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.sort (descending) value')
mytester:asserteq(maxdiff(ix,ixx),0,'torch.sort (descending) index')
-- Test sorting of random numbers
assertIsOrdered('descending', x, mxx, ixx, 'random')
-- Test simple sort task
mytester:assertTensorEq(
torch.sort(torch.Tensor{ 10, 20, 30, 40, 50 },true),
torch.Tensor{ 50, 40, 30, 20, 10 },
1e-16,
"torch.sort (descending) simple sort"
)
-- Test that we still have proper sorting with duplicate keys
assertIsOrdered('descending', x, mxx, ixx, 'random with duplicate keys')
end
function torchtest.topK()
local function topKViaSort(t, k, dim, dir)
local sorted, indices = t:sort(dim, dir)
return sorted:narrow(dim, 1, k), indices:narrow(dim, 1, k)
end
local function compareTensors(t, res1, ind1, res2, ind2, dim, msg)
-- Values should be exactly equivalent
mytester:assertTensorEq(res1, res2, 0, msg)
-- Indices might differ based on the implementation, since there is
-- no guarantee of the relative order of selection
if ind1:eq(ind2):min() == 0 then
-- To verify that the indices represent equivalent elements,
-- gather from the input using the topk indices and compare against
-- the sort indices
local vals = t:gather(dim, ind2)
mytester:assertTensorEq(res1, vals, 0, msg)
end
end
local function compare(t, k, dim, dir, msg)
local topKVal, topKInd = t:topk(k, dim, dir, true)
local sortKVal, sortKInd = topKViaSort(t, k, dim, dir)
compareTensors(t, sortKVal, sortKInd, topKVal, topKInd, dim, msg)
end
local t = torch.rand(math.random(1, msize),
math.random(1, msize),
math.random(1, msize))
for kTries = 1, 3 do
for dimTries = 1, 3 do
for _, transpose in ipairs({true, false}) do
for _, dir in ipairs({true, false}) do
local testTensor = t
local transposeMsg = nil
if transpose then
local dim1 = math.random(1, t:nDimension())
local dim2 = dim1
while dim1 == dim2 do
dim2 = math.random(1, t:nDimension())
end
testTensor = t:transpose(dim1, dim2)
transposeMsg = 'transpose(' .. dim1 .. ', ' .. dim2 .. ')'
end
local dim = math.random(1, testTensor:nDimension())
local k = math.random(1, testTensor:size(dim))
local msg = 'topk(' .. k .. ', ' .. dim .. ', ' .. tostring(dir) .. ', true)'
if transposeMsg then
msg = msg .. ' ' .. transposeMsg
end
compare(testTensor, k, dim, dir, msg)
end
end
end
end
end
function torchtest.kthvalue()
local x = torch.rand(msize, msize, msize)
local x0 = x:clone()
do
local k = math.random(1, msize)
local mx, ix = torch.kthvalue(x, k)
local mxx, ixx = torch.sort(x)
mytester:assertTensorEq(mxx:select(3, k), mx:select(3, 1), 0,
'torch.kthvalue value')
mytester:assertTensorEq(ixx:select(3, k), ix:select(3, 1), 0,
'torch.kthvalue index')
end
do -- test use of result tensors
local k = math.random(1, msize)
local mx = torch.Tensor()
local ix = torch.LongTensor()
torch.kthvalue(mx, ix, x, k)
local mxx, ixx = torch.sort(x)
mytester:assertTensorEq(mxx:select(3, k), mx:select(3, 1), 0,
'torch.kthvalue value')
mytester:assertTensorEq(ixx:select(3, k), ix:select(3, 1), 0,
'torch.kthvalue index')
end
do -- test non-default dim
local k = math.random(1, msize)
local mx, ix = torch.kthvalue(x, k, 1)
local mxx, ixx = torch.sort(x, 1)
mytester:assertTensorEq(mxx:select(1, k), mx[1], 0,
'torch.kthvalue value')
mytester:assertTensorEq(ixx:select(1, k), ix[1], 0,
'torch.kthvalue index')
end
do -- non-contiguous
local y = x:narrow(2, 1, 1)
local y0 = y:clone()
local k = math.random(1, msize)
local my, ix = torch.kthvalue(y, k)
local my0, ix0 = torch.kthvalue(y0, k)
mytester:assertTensorEq(my, my0, 0, 'torch.kthvalue value')
mytester:assertTensorEq(ix, ix0, 0, 'torch.kthvalue index')
end
mytester:assertTensorEq(x, x0, 0, 'torch.kthvalue modified input')
-- simple test case (with repetitions)
local y = torch.Tensor{3,5,4,1,1,5}
mytester:assertTensorEq(torch.kthvalue(y, 3), torch.Tensor{3}, 1e-16,
'torch.kthvalue simple')
mytester:assertTensorEq(torch.kthvalue(y, 2), torch.Tensor{1}, 1e-16,
'torch.kthvalue simple')
end
function torchtest.median()
for _, msize in ipairs{155,156} do
local x = torch.rand(msize, msize)
local x0 = x:clone()
local mx, ix = torch.median(x)
local mxx, ixx = torch.sort(x)
local ind = math.floor((msize+1)/2)
mytester:assertTensorEq(mxx:select(2, ind), mx:select(2, 1), 0,
'torch.median value')
mytester:assertTensorEq(ixx:select(2, ind), ix:select(2, 1), 0,
'torch.median index')
-- Test use of result tensor
local mr = torch.Tensor()
local ir = torch.LongTensor()
torch.median(mr, ir, x)
mytester:assertTensorEq(mr, mx, 0, 'torch.median result tensor value')
mytester:assertTensorEq(ir, ix, 0, 'torch.median result tensor index')
-- Test non-default dim
mx, ix = torch.median(x, 1)
mxx, ixx = torch.sort(x, 1)
mytester:assertTensorEq(mxx:select(1, ind), mx[1], 0,
'torch.median value')
mytester:assertTensorEq(ixx:select(1, ind), ix[1], 0,
'torch.median index')
-- input unchanged
mytester:assertTensorEq(x, x0, 0, 'torch.median modified input')
end
end
function torchtest.mode()
local x = torch.range(1, msize * msize):reshape(msize, msize)
x:select(1, 1):fill(1)
x:select(1, 2):fill(1)
x:select(2, 1):fill(1)
x:select(2, 2):fill(1)
local x0 = x:clone()
-- Pre-calculated results.
local res = torch.Tensor(msize):fill(1)
-- The indices are the position of the last appearance of the mode element.
local resix = torch.LongTensor(msize):fill(2)
resix[1] = msize
resix[2] = msize
local mx, ix = torch.mode(x)
mytester:assertTensorEq(res:view(msize, 1), mx, 0, 'torch.mode value')
mytester:assertTensorEq(resix:view(msize, 1), ix, 0, 'torch.mode index')
-- Test use of result tensor
local mr = torch.Tensor()
local ir = torch.LongTensor()
torch.mode(mr, ir, x)
mytester:assertTensorEq(mr, mx, 0, 'torch.mode result tensor value')
mytester:assertTensorEq(ir, ix, 0, 'torch.mode result tensor index')
-- Test non-default dim
mx, ix = torch.mode(x, 1)
mytester:assertTensorEq(res:view(1, msize), mx, 0, 'torch.mode value')
mytester:assertTensorEq(resix:view(1, msize), ix, 0, 'torch.mode index')
local input = torch.Tensor({
{1, 2, 2, 2, 3, 2},
{1.5, 2, 2, 1.5, 1.5, 5},
})
local value, index = torch.mode(input)
local expected_value = torch.Tensor({{2}, {1.5}})
mytester:assertTensorEq(value, expected_value)
-- input unchanged
mytester:assertTensorEq(x, x0, 0, 'torch.mode modified input')
end
function torchtest.tril()
local x = torch.rand(msize,msize)
local mx = torch.tril(x)
local mxx = torch.Tensor()
torch.tril(mxx,x)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.tril value')
end
function torchtest.triu()
local x = torch.rand(msize,msize)
local mx = torch.triu(x)
local mxx = torch.Tensor()
torch.triu(mxx,x)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.tril value')
end
function torchtest.cat()
for dim = 1, 3 do
local x = torch.rand(13, msize, msize):transpose(1, dim)
local y = torch.rand(17, msize, msize):transpose(1, dim)
local mx = torch.cat(x, y, dim)
mytester:assertTensorEq(mx:narrow(dim, 1, 13), x, 0, 'torch.cat value')
mytester:assertTensorEq(mx:narrow(dim, 14, 17), y, 0, 'torch.cat value')
local mxx = torch.Tensor()
torch.cat(mxx, x, y, dim)
mytester:assertTensorEq(mx, mxx, 0, 'torch.cat value')
local x = torch.rand(1,2,3)
local y = torch.Tensor()
local mx = torch.cat(x,y,dim)
mytester:asserteq(mx:size(1),1,'torch.cat size')
mytester:asserteq(mx:size(2),2,'torch.cat size')
mytester:asserteq(mx:size(3),3,'torch.cat size')
mytester:assertTensorEq(mx, x, 0, 'torch.cat value')
local x = torch.Tensor()
local y = torch.Tensor()
local mx = torch.cat(x,y,dim)
mytester:asserteq(mx:dim(),0,'torch.cat dim')
end
local x = torch.Tensor()
local y = torch.rand(1,2,3)
local mx = torch.cat(x,y)
mytester:asserteq(mx:size(1),1,'torch.cat size')
mytester:asserteq(mx:size(2),2,'torch.cat size')
mytester:asserteq(mx:size(3),3,'torch.cat size')
mytester:assertTensorEq(mx, y, 0, 'torch.cat value')
local x = torch.Tensor()
local y = torch.Tensor()
local mx = torch.cat(x,y)
mytester:asserteq(mx:dim(),0,'torch.cat dim')
end
function torchtest.catArray()
for dim = 1, 3 do
local x = torch.rand(13, msize, msize):transpose(1, dim)
local y = torch.rand(17, msize, msize):transpose(1, dim)
local z = torch.rand(19, msize, msize):transpose(1, dim)
local mx = torch.cat({x, y, z}, dim)
mytester:assertTensorEq(mx:narrow(dim, 1, 13), x, 0, 'torch.cat value')
mytester:assertTensorEq(mx:narrow(dim, 14, 17), y, 0, 'torch.cat value')
mytester:assertTensorEq(mx:narrow(dim, 31, 19), z, 0, 'torch.cat value')
mytester:assertError(function() torch.cat{} end, 'torch.cat empty table')
local mxx = torch.Tensor()
torch.cat(mxx, {x, y, z}, dim)
mytester:assertTensorEq(mx, mxx, 0, 'torch.cat value')
torch.cat(mxx:float(), {x:float(), y:float(), z:float()}, dim)
mytester:assertTensorEq(mx, mxx, 0, 'torch.cat value')
torch.cat(mxx:double(), {x:double(), y:double(), z:double()}, dim)
mytester:assertTensorEq(mx, mxx, 0, 'torch.cat value')
local x = torch.rand(1,2,3)
local y = torch.Tensor()
local mx = torch.cat({x,y},dim)
mytester:asserteq(mx:size(1),1,'torch.cat size')
mytester:asserteq(mx:size(2),2,'torch.cat size')
mytester:asserteq(mx:size(3),3,'torch.cat size')
mytester:assertTensorEq(mx, x, 0, 'torch.cat value')
local x = torch.Tensor()
local y = torch.Tensor()
local mx = torch.cat({x,y},dim)
mytester:asserteq(mx:dim(),0,'torch.cat dim')
end
local x = torch.Tensor()
local y = torch.rand(1,2,3)
local mx = torch.cat({x,y})
mytester:asserteq(mx:size(1),1,'torch.cat size')
mytester:asserteq(mx:size(2),2,'torch.cat size')
mytester:asserteq(mx:size(3),3,'torch.cat size')
mytester:assertTensorEq(mx, y, 0, 'torch.cat value')
local x = torch.Tensor()
local y = torch.Tensor()
local mx = torch.cat({x,y})
mytester:asserteq(mx:dim(),0,'torch.cat dim')
end
function torchtest.catNoDim()
local a
local b
local c
a = torch.Tensor(msize):uniform()
b = torch.Tensor(msize):uniform()
c = torch.cat(a, b)
mytester:assertTensorEq(c:narrow(1, 1, msize), a, 0, 'torch.cat value')
mytester:assertTensorEq(c:narrow(1, msize + 1, msize), b, 0, 'torch.cat value')
a = torch.Tensor(1, msize):uniform()
b = torch.Tensor(1, msize):uniform()
c = torch.cat(a, b)
mytester:assertTensorEq(c:narrow(2, 1, msize), a, 0, 'torch.cat value')
mytester:assertTensorEq(c:narrow(2, msize + 1, msize), b, 0, 'torch.cat value')
a = torch.Tensor(10, msize):uniform()
b = torch.Tensor(10, msize):uniform()
c = torch.cat(a, b)
mytester:assertTensorEq(c:narrow(2, 1, msize), a, 0, 'torch.cat value')
mytester:assertTensorEq(c:narrow(2, msize + 1, msize), b, 0, 'torch.cat value')
end
function torchtest.sin_2()
local x = torch.rand(msize,msize,msize)
local mx = torch.sin(x)
local mxx = torch.Tensor()
torch.sin(mxx,x)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.sin value')
end
function torchtest.linspace()
local from = math.random()
local to = from+math.random()
local mx = torch.linspace(from,to,137)
local mxx = torch.Tensor()
torch.linspace(mxx,from,to,137)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.linspace value')
mytester:assertError(function() torch.linspace(0,1,1) end, 'accepted 1 point between 2 distinct endpoints')
mytester:assertTensorEq(torch.linspace(0,0,1),torch.zeros(1),1e-16, 'failed to generate for torch.linspace(0,0,1)')
-- Check linspace for generating with start > end.
mytester:assertTensorEq(torch.linspace(2,0,3),
torch.Tensor{2,1,0},
1e-16,
'failed to generate for torch.linspace(2,0,3)')
-- Check linspace for non-contiguous tensors.
local x = torch.zeros(2, 3)
local y = x:narrow(2, 2, 2)
y:linspace(0, 3, 4)
mytester:assertTensorEq(x, torch.Tensor{{0, 0, 1}, {0, 2, 3}}, 1e-16,
'non-contiguous linspace failed')
end
function torchtest.logspace()
local from = math.random()
local to = from+math.random()
local mx = torch.logspace(from,to,137)
local mxx = torch.Tensor()
torch.logspace(mxx,from,to,137)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.logspace value')
mytester:assertError(function() torch.logspace(0,1,1) end, 'accepted 1 point between 2 distinct endpoints')
mytester:assertTensorEq(torch.logspace(0,0,1),torch.ones(1),1e-16, 'failed to generate for torch.linspace(0,0,1)')
-- Check logspace for generating with start > end.
mytester:assertTensorEq(torch.logspace(1,0,2),
torch.Tensor{10, 1},
1e-16,
'failed to generate for torch.logspace(1,0,2)')
-- Check logspace for non-contiguous tensors.
local x = torch.zeros(2, 3)
local y = x:narrow(2, 2, 2)
y:logspace(0, 3, 4)
mytester:assertTensorEq(x, torch.Tensor{{0, 1, 10}, {0, 100, 1000}}, 1e-16,
'non-contiguous logspace failed')
end
function torchtest.rand()
torch.manualSeed(123456)
local mx = torch.rand(msize,msize)
local mxx = torch.Tensor()
torch.manualSeed(123456)
torch.rand(mxx,msize,msize)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.rand value')
end
function torchtest.randn()
torch.manualSeed(123456)
local mx = torch.randn(msize,msize)
local mxx = torch.Tensor()
torch.manualSeed(123456)
torch.randn(mxx,msize,msize)
mytester:asserteq(maxdiff(mx,mxx),0,'torch.randn value')
end
function torchtest.gesv()
if not torch.gesv then return end
local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23},
{-6.05, -3.30, 5.36, -4.44, 1.08},
{-0.45, 2.58, -2.70, 0.27, 9.04},
{8.32, 2.71, 4.35, -7.17, 2.14},
{-9.67, -5.14, -7.26, 6.08, -6.87}}):t()
local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03},
{-1.56, 4.00, -8.67, 1.75, 2.86},
{9.81, -4.09, -4.57, -8.61, 8.99}}):t()
local mx = torch.gesv(b,a)
mytester:assertlt(b:dist(a*mx),1e-12,'torch.gesv')
local ta = torch.Tensor()
local tb = torch.Tensor()
local mxx = torch.gesv(tb,ta,b,a)
local mxxx = torch.gesv(b,a,b,a)
mytester:asserteq(maxdiff(mx,tb),0,'torch.gesv value temp')
mytester:asserteq(maxdiff(mx,b),0,'torch.gesv value flag')
mytester:asserteq(maxdiff(mx,mxx),0,'torch.gesv value out1')
mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gesv value out2')
end
function torchtest.gesv_reuse()
if not torch.gesv then return end
local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23},
{-6.05, -3.30, 5.36, -4.44, 1.08},
{-0.45, 2.58, -2.70, 0.27, 9.04},
{8.32, 2.71, 4.35, -7.17, 2.14},
{-9.67, -5.14, -7.26, 6.08, -6.87}}):t()
local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03},
{-1.56, 4.00, -8.67, 1.75, 2.86},
{9.81, -4.09, -4.57, -8.61, 8.99}}):t()
local mx = torch.gesv(b,a)
local ta = torch.Tensor()
local tb = torch.Tensor()
torch.gesv(tb,ta,b,a)
mytester:asserteq(maxdiff(mx,tb),0,'torch.gesv value temp')
torch.gesv(tb,ta,b,a)
mytester:asserteq(maxdiff(mx,tb),0,'torch.gesv value reuse')
end
function torchtest.trtrs()
if not torch.trtrs then return end
local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23},
{-6.05, -3.30, 5.36, -4.44, 1.08},
{-0.45, 2.58, -2.70, 0.27, 9.04},
{8.32, 2.71, 4.35, -7.17, 2.14},
{-9.67, -5.14, -7.26, 6.08, -6.87}}):t()
local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03},
{-1.56, 4.00, -8.67, 1.75, 2.86},
{9.81, -4.09, -4.57, -8.61, 8.99}}):t()
local U = torch.triu(a)
local L = torch.tril(a)
-- solve Ux = b
local x = torch.trtrs(b, U)
mytester:assertlt(b:dist(U*x),1e-12,'torch.trtrs')
x = torch.trtrs(b, U, 'U', 'N', 'N')
mytester:assertlt(b:dist(U*x),1e-12,'torch.trtrs')
-- solve Lx = b
x = torch.trtrs(b, L, 'L')
mytester:assertlt(b:dist(L*x),1e-12,'torch.trtrs')
x = torch.trtrs(b, L, 'L', 'N', 'N')
mytester:assertlt(b:dist(L*x),1e-12,'torch.trtrs')
-- solve U'x = b
x = torch.trtrs(b, U, 'U', 'T')
mytester:assertlt(b:dist(U:t()*x),1e-12,'torch.trtrs')
x = torch.trtrs(b, U, 'U', 'T', 'N')
mytester:assertlt(b:dist(U:t()*x),1e-12,'torch.trtrs')
-- solve U'x = b by manual transposition
y = torch.trtrs(b, U:t(), 'L', 'N')
mytester:assertlt(x:dist(y),1e-12,'torch.trtrs')
-- solve L'x = b
x = torch.trtrs(b, L, 'L', 'T')
mytester:assertlt(b:dist(L:t()*x),1e-12,'torch.trtrs')
x = torch.trtrs(b, L, 'L', 'T', 'N')
mytester:assertlt(b:dist(L:t()*x),1e-12,'torch.trtrs')
-- solve L'x = b by manual transposition
y = torch.trtrs(b, L:t(), 'U', 'N')
mytester:assertlt(x:dist(y),1e-12,'torch.trtrs')
end
function torchtest.trtrs_reuse()
if not torch.trtrs then return end
local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23},
{-6.05, -3.30, 5.36, -4.44, 1.08},
{-0.45, 2.58, -2.70, 0.27, 9.04},
{8.32, 2.71, 4.35, -7.17, 2.14},
{-9.67, -5.14, -7.26, 6.08, -6.87}}):t()
local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03},
{-1.56, 4.00, -8.67, 1.75, 2.86},
{9.81, -4.09, -4.57, -8.61, 8.99}}):t()
local mx = torch.trtrs(b,a)
local ta = torch.Tensor()
local tb = torch.Tensor()
torch.trtrs(tb,ta,b,a)
mytester:asserteq(maxdiff(mx,tb),0,'torch.trtrs value temp')
tb:zero()
torch.trtrs(tb,ta,b,a)
mytester:asserteq(maxdiff(mx,tb),0,'torch.trtrs value reuse')
end
function torchtest.gels_uniquely_determined()
if not torch.gels then return end
local expectedNorm = 0
local a=torch.Tensor({{ 1.44, -9.96, -7.55, 8.34},
{-7.84, -0.28, 3.24, 8.09},
{-4.39, -3.24, 6.27, 5.28},
{4.53, 3.83, -6.64, 2.06}}):t()
local b=torch.Tensor({{8.58, 8.26, 8.48, -5.28},
{9.35, -4.43, -0.70, -0.26}}):t()
local a_copy = a:clone()
local b_copy = b:clone()
local mx = torch.gels(b,a)
mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a')
mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b')
mytester:assertalmosteq((torch.mm(a,mx)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
local ta = torch.Tensor()
local tb = torch.Tensor()
local mxx = torch.gels(tb,ta,b,a)
mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a')
mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b')
mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
local mxxx = torch.gels(b,a,b,a)
mytester:assertalmosteq((torch.mm(a_copy,b)-b_copy):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
mytester:asserteq(maxdiff(mx,tb),0,'torch.gels value temp')
mytester:asserteq(maxdiff(mx,b),0,'torch.gels value flag')
mytester:asserteq(maxdiff(mx,mxx),0,'torch.gels value out1')
mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gels value out2')
end
function torchtest.gels_reuse()
if not torch.gels then return end
local expectedNorm = 0
local a=torch.Tensor({{ 1.44, -9.96, -7.55, 8.34},
{-7.84, -0.28, 3.24, 8.09},
{-4.39, -3.24, 6.27, 5.28},
{4.53, 3.83, -6.64, 2.06}}):t()
local b=torch.Tensor({{8.58, 8.26, 8.48, -5.28},
{9.35, -4.43, -0.70, -0.26}}):t()
local ta = torch.Tensor()
local tb = torch.Tensor()
torch.gels(tb,ta,b,a)
mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
torch.gels(tb,ta,b,a)
mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
torch.gels(tb,ta,b,a)
mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
end
function torchtest.gels_overdetermined()
if not torch.gels then return end
local expectedNorm = 17.390200628863
local a=torch.Tensor({{ 1.44, -9.96, -7.55, 8.34, 7.08, -5.45},
{-7.84, -0.28, 3.24, 8.09, 2.52, -5.70},
{-4.39, -3.24, 6.27, 5.28, 0.74, -1.19},
{4.53, 3.83, -6.64, 2.06, -2.47, 4.70}}):t()
local b=torch.Tensor({{8.58, 8.26, 8.48, -5.28, 5.72, 8.93},
{9.35, -4.43, -0.70, -0.26, -7.36, -2.52}}):t()
local a_copy = a:clone()
local b_copy = b:clone()
local mx = torch.gels(b,a)
mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a')
mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b')
mytester:assertalmosteq((torch.mm(a, mx)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
local ta = torch.Tensor()
local tb = torch.Tensor()
local mxx = torch.gels(tb,ta,b,a)
mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a')
mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b')
mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
local mxxx = torch.gels(b,a,b,a)
mytester:assertalmosteq((torch.mm(a_copy,b)-b_copy):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
mytester:asserteq(maxdiff(mx,tb),0,'torch.gels value temp')
mytester:asserteq(maxdiff(mx,b),0,'torch.gels value flag')
mytester:asserteq(maxdiff(mx,mxx),0,'torch.gels value out1')
mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gels value out2')
end
function torchtest.gels_underdetermined()
if not torch.gels then return end
local expectedNorm = 0
local a=torch.Tensor({{ 1.44, -9.96, -7.55},
{-7.84, -0.28, 3.24},
{-4.39, -3.24, 6.27},
{4.53, 3.83, -6.64}}):t()
local b=torch.Tensor({{8.58, 8.26, 8.48},
{9.35, -4.43, -0.70}}):t()
local a_copy = a:clone()
local b_copy = b:clone()
local mx = torch.gels(b,a)
mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a')
mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b')
mytester:assertalmosteq((torch.mm(a,mx)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
local ta = torch.Tensor()
local tb = torch.Tensor()
local mxx = torch.gels(tb,ta,b,a)
mytester:asserteq(maxdiff(a,a_copy),0,'torch.gels changed a')
mytester:asserteq(maxdiff(b,b_copy),0,'torch.gels changed b')
mytester:assertalmosteq((torch.mm(a,tb)-b):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
local mxxx = torch.gels(b,a,b,a)
mytester:assertalmosteq((torch.mm(a_copy,b)-b_copy):norm(), expectedNorm, 1e-8, 'torch.gels wrong answer')
mytester:asserteq(maxdiff(mx,tb),0,'torch.gels value temp')
mytester:asserteq(maxdiff(mx,b),0,'torch.gels value flag')
mytester:asserteq(maxdiff(mx,mxx),0,'torch.gels value out1')
mytester:asserteq(maxdiff(mx,mxxx),0,'torch.gels value out2')
end
function torchtest.eig()
if not torch.eig then return end
local a=torch.Tensor({{ 1.96, 0.00, 0.00, 0.00, 0.00},
{-6.49, 3.80, 0.00, 0.00, 0.00},
{-0.47, -6.39, 4.17, 0.00, 0.00},
{-7.20, 1.50, -1.51, 5.70, 0.00},
{-0.65, -6.34, 2.67, 1.80, -7.10}}):t():clone()
local e = torch.eig(a)
local ee,vv = torch.eig(a,'V')
local te = torch.Tensor()
local tv = torch.Tensor()
local eee,vvv = torch.eig(te,tv,a,'V')
mytester:assertlt(maxdiff(e,ee),1e-12,'torch.eig value')
mytester:assertlt(maxdiff(ee,eee),1e-12,'torch.eig value')
mytester:assertlt(maxdiff(ee,te),1e-12,'torch.eig value')
mytester:assertlt(maxdiff(vv,vvv),1e-12,'torch.eig value')
mytester:assertlt(maxdiff(vv,tv),1e-12,'torch.eig value')
end
function torchtest.eig_reuse()
if not torch.eig then return end
local X = torch.randn(4,4)
X = X:t()*X
local e, v = torch.zeros(4,2), torch.zeros(4,4)
torch.eig(e, v, X,'V')
local Xhat = v * torch.diag(e:select(2,1)) * v:t()
mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong')
mytester:assert(not v:isContiguous(), 'V is contiguous')
torch.eig(e, v, X, 'V')
local Xhat = torch.mm(v, torch.mm(e:select(2,1):diag(), v:t()))
mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong')
mytester:assert(not v:isContiguous(), 'V is contiguous')
end
function torchtest.eig_noncontig()
if not torch.eig then return end
local X = torch.randn(4,4)
X = X:t()*X
local e = torch.zeros(4,2,2)[{ {}, 2, {} }]
local v = torch.zeros(4,2,4)[{ {}, 2, {} }]
mytester:assert(not v:isContiguous(), 'V is contiguous')
mytester:assert(not e:isContiguous(), 'E is contiguous')
torch.eig(e, v, X,'V')
local Xhat = v * torch.diag(e:select(2,1)) * v:t()
mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong')
end
function torchtest.test_symeig()
if not torch.symeig then return end
local xval = torch.rand(100,3)
local cov = torch.mm(xval:t(), xval)
local rese = torch.zeros(3)
local resv = torch.zeros(3,3)
-- First call to symeig
mytester:assert(resv:isContiguous(), 'resv is not contiguous') -- PASS
torch.symeig(rese, resv, cov:clone(), 'V')
local ahat = resv*torch.diag(rese)*resv:t()
mytester:assertTensorEq(cov, ahat, 1e-8, 'VeV\' wrong') -- PASS
-- Second call to symeig
mytester:assert(not resv:isContiguous(), 'resv is contiguous') -- FAIL
torch.symeig(rese, resv, cov:clone(), 'V')
local ahat = torch.mm(torch.mm(resv, torch.diag(rese)), resv:t())
mytester:assertTensorEq(cov, ahat, 1e-8, 'VeV\' wrong') -- FAIL
end
function torchtest.symeig_noncontig()
if not torch.symeig then return end
local X = torch.rand(5,5)
X = X:t()*X
local e = torch.zeros(4,2):select(2,2)
local v = torch.zeros(4,2,4)[{ {}, 2, {} }]
mytester:assert(not v:isContiguous(), 'V is contiguous')
mytester:assert(not e:isContiguous(), 'E is contiguous')
torch.symeig(e, v, X,'V')
local Xhat = v * torch.diag(e) * v:t()
mytester:assertTensorEq(X, Xhat, 1e-8, 'VeV\' wrong')
end
function torchtest.svd()
if not torch.svd then return end
local a=torch.Tensor({{8.79, 6.11, -9.15, 9.57, -3.49, 9.84},
{9.93, 6.91, -7.93, 1.64, 4.02, 0.15},
{9.83, 5.04, 4.86, 8.83, 9.80, -8.99},
{5.45, -0.27, 4.85, 0.74, 10.00, -6.02},
{3.16, 7.98, 3.01, 5.80, 4.27, -5.31}}):t():clone()
local u,s,v = torch.svd(a)
local uu = torch.Tensor()
local ss = torch.Tensor()
local vv = torch.Tensor()
local uuu,sss,vvv = torch.svd(uu,ss,vv,a)
mytester:asserteq(maxdiff(u,uu),0,'torch.svd')
mytester:asserteq(maxdiff(u,uuu),0,'torch.svd')
mytester:asserteq(maxdiff(s,ss),0,'torch.svd')
mytester:asserteq(maxdiff(s,sss),0,'torch.svd')
mytester:asserteq(maxdiff(v,vv),0,'torch.svd')
mytester:asserteq(maxdiff(v,vvv),0,'torch.svd')
end
function torchtest.svd_reuse()
if not torch.svd then return end
local X = torch.randn(4,4)
local U, S, V = torch.svd(X)
local Xhat = torch.mm(U, torch.mm(S:diag(), V:t()))
mytester:assertTensorEq(X, Xhat, 1e-8, 'USV\' wrong')
mytester:assert(not U:isContiguous(), 'U is contiguous')
torch.svd(U, S, V, X)
local Xhat = torch.mm(U, torch.mm(S:diag(), V:t()))
mytester:assertTensorEq(X, Xhat, 1e-8, 'USV\' wrong')
end
function torchtest.svd_noncontig()
if not torch.svd then return end
local X = torch.randn(5,5)
local U = torch.zeros(5,2,5)[{ {}, 2, {} }]
local S = torch.zeros(5,2)[{ {}, 2 }]
local V = torch.zeros(5,2,5)[{ {}, 2, {} }]
mytester:assert(not U:isContiguous(), 'U is contiguous')
mytester:assert(not S:isContiguous(), 'S is contiguous')
mytester:assert(not V:isContiguous(), 'V is contiguous')
torch.svd(U, S, V, X)
local Xhat = torch.mm(U, torch.mm(S:diag(), V:t()))
mytester:assertTensorEq(X, Xhat, 1e-8, 'USV\' wrong')
end
function torchtest.inverse()
if not torch.inverse then return end
local M = torch.randn(5,5)
local MI = torch.inverse(M)
local E = torch.eye(5)
mytester:assert(not MI:isContiguous(), 'MI is contiguous')
mytester:assertalmosteq(maxdiff(E,torch.mm(M,MI)), 0, 1e-8, 'inverse value')
mytester:assertalmosteq(maxdiff(E,torch.mm(MI,M)), 0, 1e-8, 'inverse value')
local MII = torch.Tensor(5,5)
torch.inverse(MII, M)
mytester:assert(not MII:isContiguous(), 'MII is contiguous')
mytester:asserteq(maxdiff(MII, MI), 0, 'inverse value in-place')
-- second call, now that MII is transposed
torch.inverse(MII, M)
mytester:assert(not MII:isContiguous(), 'MII is contiguous')
mytester:asserteq(maxdiff(MII, MI), 0, 'inverse value in-place')
end
function torchtest.conv2()
local x = torch.rand(math.floor(torch.uniform(50,100)),math.floor(torch.uniform(50,100)))
local k = torch.rand(math.floor(torch.uniform(10,20)),math.floor(torch.uniform(10,20)))
local imvc = torch.conv2(x,k)
local imvc2 = torch.conv2(x,k,'V')
local imfc = torch.conv2(x,k,'F')
local ki = k:clone();
local ks = k:storage()
local kis = ki:storage()
for i=ks:size(),1,-1 do kis[ks:size()-i+1]=ks[i] end
local imvx = torch.xcorr2(x,ki)
local imvx2 = torch.xcorr2(x,ki,'V')
local imfx = torch.xcorr2(x,ki,'F')
mytester:asserteq(maxdiff(imvc,imvc2),0,'torch.conv2')
mytester:asserteq(maxdiff(imvc,imvx),0,'torch.conv2')
mytester:asserteq(maxdiff(imvc,imvx2),0,'torch.conv2')
mytester:asserteq(maxdiff(imfc,imfx),0,'torch.conv2')
mytester:assertlt(math.abs(x:dot(x)-torch.xcorr2(x,x)[1][1]),1e-10,'torch.conv2')
local xx = torch.Tensor(2,x:size(1),x:size(2))
xx[1]:copy(x)
xx[2]:copy(x)
local kk = torch.Tensor(2,k:size(1),k:size(2))
kk[1]:copy(k)
kk[2]:copy(k)
local immvc = torch.conv2(xx,kk)
local immvc2 = torch.conv2(xx,kk,'V')
local immfc = torch.conv2(xx,kk,'F')
mytester:asserteq(maxdiff(immvc[1],immvc[2]),0,'torch.conv2')
mytester:asserteq(maxdiff(immvc[1],imvc),0,'torch.conv2')
mytester:asserteq(maxdiff(immvc2[1],imvc2),0,'torch.conv2')
mytester:asserteq(maxdiff(immfc[1],immfc[2]),0,'torch.conv2')
mytester:asserteq(maxdiff(immfc[1],imfc),0,'torch.conv2')
end
function torchtest.conv3()
local x = torch.rand(math.floor(torch.uniform(20,40)),
math.floor(torch.uniform(20,40)),
math.floor(torch.uniform(20,40)))
local k = torch.rand(math.floor(torch.uniform(5,10)),
math.floor(torch.uniform(5,10)),
math.floor(torch.uniform(5,10)))
local imvc = torch.conv3(x,k)
local imvc2 = torch.conv3(x,k,'V')
local imfc = torch.conv3(x,k,'F')
local ki = k:clone();
local ks = k:storage()
local kis = ki:storage()
for i=ks:size(),1,-1 do kis[ks:size()-i+1]=ks[i] end
local imvx = torch.xcorr3(x,ki)
local imvx2 = torch.xcorr3(x,ki,'V')
local imfx = torch.xcorr3(x,ki,'F')
mytester:asserteq(maxdiff(imvc,imvc2),0,'torch.conv3')
mytester:asserteq(maxdiff(imvc,imvx),0,'torch.conv3')
mytester:asserteq(maxdiff(imvc,imvx2),0,'torch.conv3')
mytester:asserteq(maxdiff(imfc,imfx),0,'torch.conv3')
mytester:assertlt(math.abs(x:dot(x)-torch.xcorr3(x,x)[1][1][1]),4*1e-10,'torch.conv3')
local xx = torch.Tensor(2,x:size(1),x:size(2),x:size(3))
xx[1]:copy(x)
xx[2]:copy(x)
local kk = torch.Tensor(2,k:size(1),k:size(2),k:size(3))
kk[1]:copy(k)
kk[2]:copy(k)
local immvc = torch.conv3(xx,kk)
local immvc2 = torch.conv3(xx,kk,'V')
local immfc = torch.conv3(xx,kk,'F')
mytester:asserteq(maxdiff(immvc[1],immvc[2]),0,'torch.conv3')
mytester:asserteq(maxdiff(immvc[1],imvc),0,'torch.conv3')
mytester:asserteq(maxdiff(immvc2[1],imvc2),0,'torch.conv3')
mytester:asserteq(maxdiff(immfc[1],immfc[2]),0,'torch.conv3')
mytester:asserteq(maxdiff(immfc[1],imfc),0,'torch.conv3')
end
function torchtest.xcorr3_xcorr2_eq()
local ix = math.floor(torch.uniform(20,40))
local iy = math.floor(torch.uniform(20,40))
local iz = math.floor(torch.uniform(20,40))
local kx = math.floor(torch.uniform(5,10))
local ky = math.floor(torch.uniform(5,10))
local kz = math.floor(torch.uniform(5,10))
local x = torch.rand(ix,iy,iz)
local k = torch.rand(kx,ky,kz)
local o3 = torch.xcorr3(x,k)
local o32 = torch.zeros(o3:size())
for i=1,o3:size(1) do
for j=1,k:size(1) do
o32[i]:add(torch.xcorr2(x[i+j-1],k[j]))
end
end
mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq')
end
function torchtest.fxcorr3_fxcorr2_eq()
local ix = math.floor(torch.uniform(20,40))
local iy = math.floor(torch.uniform(20,40))
local iz = math.floor(torch.uniform(20,40))
local kx = math.floor(torch.uniform(5,10))
local ky = math.floor(torch.uniform(5,10))
local kz = math.floor(torch.uniform(5,10))
local x = torch.rand(ix,iy,iz)
local k = torch.rand(kx,ky,kz)
local o3 = torch.xcorr3(x,k,'F')
local o32 = torch.zeros(o3:size())
for i=1,x:size(1) do
for j=1,k:size(1) do
o32[i+j-1]:add(torch.xcorr2(x[i],k[k:size(1)-j + 1],'F'))
end
end
mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq')
end
function torchtest.conv3_conv2_eq()
local ix = math.floor(torch.uniform(20,40))
local iy = math.floor(torch.uniform(20,40))
local iz = math.floor(torch.uniform(20,40))
local kx = math.floor(torch.uniform(5,10))
local ky = math.floor(torch.uniform(5,10))
local kz = math.floor(torch.uniform(5,10))
local x = torch.rand(ix,iy,iz)
local k = torch.rand(kx,ky,kz)
local o3 = torch.conv3(x,k)
local o32 = torch.zeros(o3:size())
for i=1,o3:size(1) do
for j=1,k:size(1) do
o32[i]:add(torch.conv2(x[i+j-1],k[k:size(1)-j+1]))
end
end
mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq')
end
function torchtest.fconv3_fconv2_eq()
local ix = math.floor(torch.uniform(20,40))
local iy = math.floor(torch.uniform(20,40))
local iz = math.floor(torch.uniform(20,40))
local kx = math.floor(torch.uniform(5,10))
local ky = math.floor(torch.uniform(5,10))
local kz = math.floor(torch.uniform(5,10))
local x = torch.rand(ix,iy,iz)
local k = torch.rand(kx,ky,kz)
local o3 = torch.conv3(x,k,'F')
local o32 = torch.zeros(o3:size())
for i=1,x:size(1) do
for j=1,k:size(1) do
o32[i+j-1]:add(torch.conv2(x[i],k[j],'F'))
end
end
mytester:assertlt(maxdiff(o3,o32),precision,'torch.conv3_conv2_eq')
end
function torchtest.logical()
local x = torch.rand(100,100)*2-1;
local xx = x:clone()
local xgt = torch.gt(x,1)
local xlt = torch.lt(x,1)
local xeq = torch.eq(x,1)
local xne = torch.ne(x,1)
local neqs = xgt+xlt
local all = neqs + xeq
mytester:asserteq(neqs:sum(), xne:sum(), 'torch.logical')
mytester:asserteq(x:nElement(),all:double():sum() , 'torch.logical')
end
function torchtest.RNGState()
local state = torch.getRNGState()
local stateCloned = state:clone()
local before = torch.rand(1000)
mytester:assert(state:ne(stateCloned):long():sum() == 0, 'getRNGState should have value semantics, but appears to have reference semantics')
torch.setRNGState(state)
local after = torch.rand(1000)
mytester:assertTensorEq(before, after, 1e-16, 'getRNGState/setRNGState not generating same sequence')
end
function torchtest.RNGStateAliasing()
torch.manualSeed(1)
local unused = torch.uniform()
-- Fork the random number stream at this point
local gen = torch.Generator()
torch.setRNGState(gen, torch.getRNGState())
local target_value = torch.rand(1000)
--Dramatically alter the internal state of the main generator
local also_unused = torch.rand(100000)
local forked_value = torch.rand(gen, 1000)
mytester:assertTensorEq(target_value, forked_value, 1e-16, "RNG has not forked correctly.")
end
function torchtest.serializeGenerator()
local generator = torch.Generator()
torch.manualSeed(generator, 123)
local differentGenerator = torch.Generator()
torch.manualSeed(differentGenerator, 124)
local serializedGenerator = torch.serialize(generator)
local deserializedGenerator = torch.deserialize(serializedGenerator)
local generated = torch.random(generator)
local differentGenerated = torch.random(differentGenerator)
local deserializedGenerated = torch.random(deserializedGenerator)
mytester:asserteq(generated, deserializedGenerated, 'torch.Generator changed internal state after being serialized')
mytester:assertne(generated, differentGenerated, 'Generators with different random seed should not produce the same output')
end
function torchtest.testBoxMullerState()
torch.manualSeed(123)
local odd_number = 101
local seeded = torch.randn(odd_number)
local state = torch.getRNGState()
local midstream = torch.randn(odd_number)
torch.setRNGState(state)
local repeat_midstream = torch.randn(odd_number)
torch.manualSeed(123)
local reseeded = torch.randn(odd_number)
mytester:assertTensorEq(midstream, repeat_midstream, 1e-16, 'getRNGState/setRNGState not generating same sequence of normally distributed numbers')
mytester:assertTensorEq(seeded, reseeded, 1e-16, 'repeated calls to manualSeed not generating same sequence of normally distributed numbers')
end
function torchtest.testCholesky()
local x = torch.rand(10,10)
local A = torch.mm(x, x:t())
---- Default Case
local C = torch.potrf(A)
local B = torch.mm(C:t(), C)
mytester:assertTensorEq(A, B, 1e-14, 'potrf did not allow rebuilding the original matrix')
---- Test Upper Triangular
local U = torch.potrf(A, 'U')
B = torch.mm(U:t(), U)
mytester:assertTensorEq(A, B, 1e-14, 'potrf (upper) did not allow rebuilding the original matrix')
---- Test Lower Triangular
local L = torch.potrf(A, 'L')
B = torch.mm(L, L:t())
mytester:assertTensorEq(A, B, 1e-14, 'potrf (lower) did not allow rebuilding the original matrix')
end
function torchtest.potrs()
if not torch.potrs then return end
local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23},
{-6.05, -3.30, 5.36, -4.44, 1.08},
{-0.45, 2.58, -2.70, 0.27, 9.04},
{8.32, 2.71, 4.35, -7.17, 2.14},
{-9.67, -5.14, -7.26, 6.08, -6.87}}):t()
local b=torch.Tensor({{4.02, 6.19, -8.22, -7.57, -3.03},
{-1.56, 4.00, -8.67, 1.75, 2.86},
{9.81, -4.09, -4.57, -8.61, 8.99}}):t()
---- Make sure 'a' is symmetric PSD
a = torch.mm(a, a:t())
---- Upper Triangular Test
local U = torch.potrf(a, 'U')
local x = torch.potrs(b, U, 'U')
mytester:assertlt(b:dist(a*x),1e-12,"torch.potrs; uplo='U'")
---- Lower Triangular Test
local L = torch.potrf(a, 'L')
x = torch.potrs(b, L, 'L')
mytester:assertlt(b:dist(a*x),1e-12,"torch.potrs; uplo='L")
end
function torchtest.potri()
if not torch.potrs then return end
local a=torch.Tensor({{6.80, -2.11, 5.66, 5.97, 8.23},
{-6.05, -3.30, 5.36, -4.44, 1.08},
{-0.45, 2.58, -2.70, 0.27, 9.04},
{8.32, 2.71, 4.35, -7.17, 2.14},
{-9.67, -5.14, -7.26, 6.08, -6.87}}):t()
---- Make sure 'a' is symmetric PSD
a = torch.mm(a, a:t())
---- Compute inverse directly
local inv0 = torch.inverse(a)
---- Default case
local chol = torch.potrf(a)
local inv1 = torch.potri(chol)
mytester:assertlt(inv0:dist(inv1),1e-12,"torch.potri; uplo=''")
---- Upper Triangular Test
chol = torch.potrf(a, 'U')
inv1 = torch.potri(chol, 'U')
mytester:assertlt(inv0:dist(inv1),1e-12,"torch.potri; uplo='U'")
---- Lower Triangular Test
chol = torch.potrf(a, 'L')
inv1 = torch.potri(chol, 'L')
mytester:assertlt(inv0:dist(inv1),1e-12,"torch.potri; uplo='L'")
end
function torchtest.pstrf()
local function checkPsdCholesky(a, uplo, inplace)
local u, piv, args, a_reconstructed
if inplace then
u = torch.Tensor(a:size())
piv = torch.IntTensor(a:size(1))
args = {u, piv, a}
else
args = {a}
end
if uplo then table.insert(args, uplo) end
u, piv = torch.pstrf(unpack(args))
if uplo == 'L' then
a_reconstructed = torch.mm(u, u:t())
else
a_reconstructed = torch.mm(u:t(), u)
end
piv = piv:long()
local a_permuted = a:index(1, piv):index(2, piv)
mytester:assertTensorEq(a_permuted, a_reconstructed, 1e-14,
'torch.pstrf did not allow rebuilding the original matrix;' ..
'uplo=' .. tostring(uplo))
end
local dimensions = { {5, 1}, {5, 3}, {5, 5}, {10, 10} }
for _, dim in pairs(dimensions) do
local m = torch.Tensor(unpack(dim)):uniform()
local a = torch.mm(m, m:t())
-- add a small number to the diagonal to make the matrix numerically positive semidefinite
for i = 1, m:size(1) do
a[i][i] = a[i][i] + 1e-7
end
checkPsdCholesky(a, nil, false)
checkPsdCholesky(a, 'U', false)
checkPsdCholesky(a, 'L', false)
checkPsdCholesky(a, nil, true)
checkPsdCholesky(a, 'U', true)
checkPsdCholesky(a, 'L', true)
end
end
function torchtest.testNumel()
local b = torch.ByteTensor(3, 100, 100)
mytester:asserteq(b:nElement(), 3*100*100, "nElement not right")
mytester:asserteq(b:numel(), 3*100*100, "numel not right")
end
-- Generate a tensor of size `size` whose values are ascending integers from
-- `start` (or 1, if `start is not given)
local function consecutive(size, start)
local sequence = torch.ones(torch.Tensor(size):prod(1)[1]):cumsum(1)
if start then
sequence:add(start - 1)
end
return sequence:resize(unpack(size))
end
function torchtest.index()
local badIndexMsg = "Lookup with valid index should return correct result"
local reference = consecutive{3, 3, 3}
mytester:assertTensorEq(reference[1], consecutive{3, 3}, 1e-16, badIndexMsg)
mytester:assertTensorEq(reference[2], consecutive({3, 3}, 10), 1e-16, badIndexMsg)
mytester:assertTensorEq(reference[3], consecutive({3, 3}, 19), 1e-16, badIndexMsg)
mytester:assertTensorEq(reference[{1}], consecutive{3, 3}, 1e-16, badIndexMsg)
mytester:assertTensorEq(reference[{2}], consecutive({3, 3}, 10), 1e-16, badIndexMsg)
mytester:assertTensorEq(reference[{3}], consecutive({3, 3}, 19), 1e-16, badIndexMsg)
mytester:assertTensorEq(reference[{1,2}], consecutive({3}, 4), 1e-16, badIndexMsg)
mytester:assertTensorEq(reference[{{1,2}}], consecutive({2, 3, 3}), 1e-16, badIndexMsg)
mytester:asserteq(reference[{3, 3, 3}], 27, badIndexMsg)
mytester:assertTensorEq(reference[{}], consecutive{3, 3, 3}, 1e-16, badIndexMsg)
local shouldErrorMsg = "Lookup with too many indices should error"
mytester:assertError(function() return reference[{1, 1, 1, 1}] end, shouldErrorMsg)
mytester:assertError(function() return reference[{1, 1, 1, {1, 1}}] end, shouldErrorMsg)
mytester:assertError(function() return reference[{3, 3, 3, 3, 3, 3, 3, 3}] end, shouldErrorMsg)
end
function torchtest.newIndex()
local badIndexMsg = "Assignment to valid index should produce correct result"
local reference = consecutive{3, 3, 3}
-- This relies on __index__() being correct - but we have separate tests for that
local function checkPartialAssign(index)
local reference = torch.zeros(3, 3, 3)
reference[index] = consecutive{3, 3, 3}[index]
mytester:assertTensorEq(reference[index], consecutive{3, 3, 3}[index], 1e-16, badIndexMsg)
reference[index] = 0
mytester:assertTensorEq(reference, torch.zeros(3, 3, 3), 1e-16, badIndexMsg)
end
checkPartialAssign{1}
checkPartialAssign{2}
checkPartialAssign{3}
checkPartialAssign{1,2}
checkPartialAssign{2,3}
checkPartialAssign{1,3}
checkPartialAssign{}
local shouldErrorMsg = "Assignment with too many indices should error"
mytester:assertError(function() reference[{1, 1, 1, 1}] = 1 end, shouldErrorMsg)
mytester:assertError(function() reference[{1, 1, 1, {1, 1}}] = 1 end, shouldErrorMsg)
mytester:assertError(function() reference[{3, 3, 3, 3, 3, 3, 3, 3}] = 1 end, shouldErrorMsg)
end
function torchtest.indexCopy()
local nCopy, nDest = 3, 20
local dest = torch.randn(nDest,4,5)
local src = torch.randn(nCopy,4,5)
local idx = torch.randperm(nDest):narrow(1, 1, nCopy):long()
local dest2 = dest:clone()
dest:indexCopy(1, idx, src)
for i=1,idx:size(1) do
dest2[idx[i]]:copy(src[i])
end
mytester:assertTensorEq(dest, dest2, 0.000001, "indexCopy tensor error")
local dest = torch.randn(nDest)
local src = torch.randn(nCopy)
local idx = torch.randperm(nDest):narrow(1, 1, nCopy):long()
local dest2 = dest:clone()
dest:indexCopy(1, idx, src)
for i=1,idx:size(1) do
dest2[idx[i]] = src[i]
end
mytester:assertTensorEq(dest, dest2, 0.000001, "indexCopy scalar error")
end
function torchtest.indexAdd()
local nCopy, nDest = 3, 20
local dest = torch.randn(nDest,4,5)
local src = torch.randn(nCopy,4,5)
local idx = torch.randperm(nDest):narrow(1, 1, nCopy):long()
local dest2 = dest:clone()
dest:indexAdd(1, idx, src)
for i=1,idx:size(1) do
dest2[idx[i]]:add(src[i])
end
mytester:assertTensorEq(dest, dest2, 0.000001, "indexAdd tensor error")
local dest = torch.randn(nDest)
local src = torch.randn(nCopy)
local idx = torch.randperm(nDest):narrow(1, 1, nCopy):long()
local dest2 = dest:clone()
dest:indexAdd(1, idx, src)
for i=1,idx:size(1) do
dest2[idx[i]] = dest2[idx[i]] + src[i]
end
mytester:assertTensorEq(dest, dest2, 0.000001, "indexAdd scalar error")
end
-- Fill idx with valid indices.
local function fillIdx(idx, dim, dim_size, elems_per_row, m, n, o)
for i = 1, (dim == 1 and 1 or m) do
for j = 1, (dim == 2 and 1 or n) do
for k = 1, (dim == 3 and 1 or o) do
local ii = {i, j, k}
ii[dim] = {}
idx[ii] = torch.randperm(dim_size)[{{1, elems_per_row}}]
end
end
end
end
function torchtest.gather()
local m, n, o = torch.random(10, 20), torch.random(10, 20), torch.random(10, 20)
local elems_per_row = torch.random(10)
local dim = torch.random(3)
local src = torch.randn(m, n, o)
local idx_size = {m, n, o}
idx_size[dim] = elems_per_row
local idx = torch.LongTensor():resize(unpack(idx_size))
fillIdx(idx, dim, src:size(dim), elems_per_row, m, n, o)
local actual = torch.gather(src, dim, idx)
local expected = torch.Tensor():resize(unpack(idx_size))
for i = 1, idx_size[1] do
for j = 1, idx_size[2] do
for k = 1, idx_size[3] do
local ii = {i, j, k}
ii[dim] = idx[i][j][k]
expected[i][j][k] = src[ii]
end
end
end
mytester:assertTensorEq(actual, expected, 0, "Wrong values for gather")
idx[1][1][1] = 23
mytester:assertError(function() torch.gather(src, dim, idx) end,
"Invalid index not detected")
end
function torchtest.gatherMax()
local src = torch.randn(3, 4, 5)
local expected, idx = src:max(3)
local actual = torch.gather(src, 3, idx)
mytester:assertTensorEq(actual, expected, 0, "Wrong values for gather")
end
function torchtest.scatter()
local m, n, o = torch.random(10, 20), torch.random(10, 20), torch.random(10, 20)
local elems_per_row = torch.random(10)
local dim = torch.random(3)
local idx_size = {m, n, o}
idx_size[dim] = elems_per_row
local idx = torch.LongTensor():resize(unpack(idx_size))
fillIdx(idx, dim, ({m, n, o})[dim], elems_per_row, m, n, o)
local src = torch.Tensor():resize(unpack(idx_size)):normal()
local actual = torch.zeros(m, n, o):scatter(dim, idx, src)
local expected = torch.zeros(m, n, o)
for i = 1, idx_size[1] do
for j = 1, idx_size[2] do
for k = 1, idx_size[3] do
local ii = {i, j, k}
ii[dim] = idx[i][j][k]
expected[ii] = src[i][j][k]
end
end
end
mytester:assertTensorEq(actual, expected, 0, "Wrong values for scatter")
idx[1][1][1] = 34
mytester:assertError(function() torch.zeros(m, n, o):scatter(dim, idx, src) end,
"Invalid index not detected")
end
function torchtest.scatterFill()
local m, n, o = torch.random(10, 20), torch.random(10, 20), torch.random(10, 20)
local elems_per_row = torch.random(10)
local dim = torch.random(3)
local val = torch.uniform()
local idx_size = {m, n, o}
idx_size[dim] = elems_per_row
local idx = torch.LongTensor():resize(unpack(idx_size))
fillIdx(idx, dim, ({m, n, o})[dim], elems_per_row, m, n, o)
local actual = torch.zeros(m, n, o):scatter(dim, idx, val)
local expected = torch.zeros(m, n, o)
for i = 1, idx_size[1] do
for j = 1, idx_size[2] do
for k = 1, idx_size[3] do
local ii = {i, j, k}
ii[dim] = idx[i][j][k]
expected[ii] = val
end
end
end
mytester:assertTensorEq(actual, expected, 0, "Wrong values for scatter")
idx[1][1][1] = 28
mytester:assertError(function() torch.zeros(m, n, o):scatter(dim, idx, val) end,
"Invalid index not detected")
end
function torchtest.maskedCopy()
local nCopy, nDest = 3, 10
local dest = torch.randn(nDest)
local src = torch.randn(nCopy)
local mask = torch.ByteTensor{0,0,0,0,1,0,1,0,1,0}
local dest2 = dest:clone()
dest:maskedCopy(mask, src)
local j = 1
for i=1,nDest do
if mask[i] == 1 then
dest2[i] = src[j]
j = j + 1
end
end
mytester:assertTensorEq(dest, dest2, 0.000001, "maskedCopy error")
-- make source bigger than number of 1s in mask
src = torch.randn(nDest)
local ok = pcall(dest.maskedCopy, dest, mask, src)
mytester:assert(ok, "maskedCopy incorrect complaint when"
.. " src is bigger than mask's one count")
src = torch.randn(nCopy - 1) -- make src smaller. this should fail
local ok = pcall(dest.maskedCopy, dest, mask, src)
mytester:assert(not ok, "maskedCopy not erroring when"
.. " src is smaller than mask's one count")
end
function torchtest.maskedSelect()
local nSrc = 10
local src = torch.randn(nSrc)
local mask = torch.rand(nSrc):mul(2):floor():byte()
local dst = torch.Tensor()
dst:maskedSelect(src, mask)
local dst2 = {}
for i=1,nSrc do
if mask[i] == 1 then
table.insert(dst2, src[i])
end
end
mytester:assertTensorEq(dst, torch.DoubleTensor(dst2), 0.000001, "maskedSelect error")
end
function torchtest.maskedFill()
local nDst = 10
local dst = torch.randn(nDst)
local mask = torch.rand(nDst):mul(2):floor():byte()
local val = math.random()
local dst2 = dst:clone()
dst:maskedFill(mask, val)
for i=1,nDst do
if mask[i] == 1 then
dst2[i] = val
end
end
mytester:assertTensorEq(dst, dst2, 0.000001, "maskedFill error")
end
function torchtest.abs()
local size = 1000
local range = 1000
local original = torch.rand(size):mul(range)
-- Tensor filled with {-1,1}
local switch = torch.rand(size):mul(2):floor():mul(2):add(-1)
local types = {'torch.DoubleTensor', 'torch.FloatTensor', 'torch.LongTensor', 'torch.IntTensor'}
for k,t in ipairs(types) do
local data = original:type(t)
local switch = switch:type(t)
local input = torch.cmul(data, switch)
mytester:assertTensorEq(input:abs(), data, 1e-16, 'Error in abs() for '..t)
end
-- Checking that the right abs function is called for LongTensor
local bignumber
if torch.LongTensor():elementSize() > 4 then
bignumber = 2^31 + 1
else
bignumber = 2^15 + 1
end
local input = torch.LongTensor{-bignumber}
mytester:assertgt(input:abs()[1], 0, 'torch.abs(3)')
end
function torchtest.classInModule()
-- Need a global for this module
_mymodule123 = {}
local x = torch.class('_mymodule123.myclass')
mytester:assert(x ~= nil, 'Could not create class in module')
-- Remove the global
_G['_mymodule123'] = nil
debug.getregistry()['_mymodule123.myclass']=nil
end
function torchtest.classNoModule()
local x = torch.class('_myclass123')
mytester:assert(x ~= nil, 'Could not create class in module')
debug.getregistry()['_myclass123'] = nil
end
function torchtest.type()
local objects = {torch.DoubleTensor(), {}, nil, 2, "asdf"}
local types = {'torch.DoubleTensor', 'table', 'nil', 'number', 'string'}
for i,obj in ipairs(objects) do
mytester:assert(torch.type(obj) == types[i], "wrong type "..types[i])
end
end
function torchtest.isTypeOfInheritance()
do
local A = torch.class('A')
local B, parB = torch.class('B', 'A')
local C, parC = torch.class('C', 'A')
end
local a, b, c = A(), B(), C()
mytester:assert(torch.isTypeOf(a, 'A'), 'isTypeOf error, string spec')
mytester:assert(torch.isTypeOf(a, A), 'isTypeOf error, constructor')
mytester:assert(torch.isTypeOf(b, 'B'), 'isTypeOf error child class')
mytester:assert(torch.isTypeOf(b, B), 'isTypeOf error child class ctor')
mytester:assert(torch.isTypeOf(b, 'A'), 'isTypeOf error: inheritance')
mytester:assert(torch.isTypeOf(b, A), 'isTypeOf error: inheritance')
mytester:assert(not torch.isTypeOf(c, 'B'), 'isTypeOf error: common parent')
mytester:assert(not torch.isTypeOf(c, B), 'isTypeOf error: common parent')
debug.getregistry()['A'] = nil
debug.getregistry()['B'] = nil
debug.getregistry()['C'] = nil
end
function torchtest.isTypeOfPartial()
do
local TorchDummy = torch.class('TorchDummy')
local OtherTorchDummy = torch.class('OtherTorchDummy')
local TorchMember = torch.class('TorchMember')
local OtherTorchMember = torch.class('OtherTorchMember')
local FirstTorchMember = torch.class('FirstTorchMember',
'TorchMember')
local SecondTorchMember = torch.class('SecondTorchMember',
'TorchMember')
local ThirdTorchMember = torch.class('ThirdTorchMember',
'OtherTorchMember')
end
local td, otd = TorchDummy(), OtherTorchDummy()
local tm, ftm, stm, ttm = TorchMember(), FirstTorchMember(),
SecondTorchMember(), ThirdTorchMember()
mytester:assert(not torch.isTypeOf(td, 'OtherTorchDummy'),
'isTypeOf error: incorrect partial match')
mytester:assert(not torch.isTypeOf(otd, 'TorchDummy'),
'isTypeOf error: incorrect partial match')
mytester:assert(torch.isTypeOf(tm, 'TorchMember'),
'isTypeOf error, string spec')
mytester:assert(torch.isTypeOf(tm, TorchMember),
'isTypeOf error, constructor')
mytester:assert(torch.isTypeOf(ftm, 'FirstTorchMember'),
'isTypeOf error child class')
mytester:assert(torch.isTypeOf(ftm, FirstTorchMember),
'isTypeOf error child class ctor')
mytester:assert(torch.isTypeOf(ftm, 'TorchMember'),
'isTypeOf error: inheritance')
mytester:assert(torch.isTypeOf(ftm, TorchMember),
'isTypeOf error: inheritance')
mytester:assert(not torch.isTypeOf(stm, 'FirstTorchMember'),
'isTypeOf error: common parent')
mytester:assert(not torch.isTypeOf(stm, FirstTorchMember),
'isTypeOf error: common parent')
mytester:assert(not torch.isTypeOf(ttm, TorchMember),
'isTypeOf error: inheritance')
mytester:assert(not torch.isTypeOf(ttm, 'TorchMember'),
'isTypeOf error: inheritance')
debug.getregistry()['TorchDummy'] = nil
debug.getregistry()['OtherTorchDummy'] = nil
debug.getregistry()['TorchMember'] = nil
debug.getregistry()['OtherTorchMember'] = nil
debug.getregistry()['FirstTorchMember'] = nil
debug.getregistry()['SecondTorchMember'] = nil
debug.getregistry()['ThirdTorchMember'] = nil
end
function torchtest.isTypeOfPattern()
local t = torch.LongTensor()
mytester:assert(torch.isTypeOf(t, torch.LongTensor),
'isTypeOf error: incorrect match')
mytester:assert(not torch.isTypeOf(t, torch.IntTensor),
'isTypeOf error: incorrect match')
mytester:assert(torch.isTypeOf(t, 'torch.LongTensor'),
'isTypeOf error: incorrect match')
mytester:assert(not torch.isTypeOf(t, 'torch.Long'),
'isTypeOf error: incorrect match')
mytester:assert(torch.isTypeOf(t, 'torch.*Tensor'),
'isTypeOf error: incorrect match')
mytester:assert(torch.isTypeOf(t, '.*Long'),
'isTypeOf error: incorrect match')
mytester:assert(not torch.isTypeOf(t, 'torch.IntTensor'),
'isTypeOf error: incorrect match')
end
function torchtest.isTensor()
for k,v in ipairs({"real", "half"}) do
torchtest_isTensor(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_isTensor(func)
local t = func(torch.randn(3,4))
mytester:assert(torch.isTensor(t), 'error in isTensor')
mytester:assert(torch.isTensor(t[1]), 'error in isTensor for subTensor')
mytester:assert(not torch.isTensor(t[1][2]), 'false positive in isTensor')
mytester:assert(torch.Tensor.isTensor(t), 'alias not working')
end
function torchtest.isStorage()
for k,v in ipairs({"real", "half"}) do
torchtest_isStorage(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_isStorage(func)
local t = torch.randn(3,4)
mytester:assert(torch.isStorage(t:storage()), 'error in isStorage')
mytester:assert(not torch.isStorage(t), 'false positive in isStorage')
end
function torchtest.view()
for k,v in ipairs({"real", "half"}) do
torchtest_view(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_view(func)
local tensor = func(torch.rand(15))
local template = func(torch.rand(3,5))
local target = template:size():totable()
mytester:assertTableEq(tensor:viewAs(template):size():totable(), target, 'Error in viewAs')
mytester:assertTableEq(tensor:view(3,5):size():totable(), target, 'Error in view')
mytester:assertTableEq(tensor:view(torch.LongStorage{3,5}):size():totable(), target, 'Error in view using LongStorage')
mytester:assertTableEq(tensor:view(-1,5):size():totable(), target, 'Error in view using dimension -1')
mytester:assertTableEq(tensor:view(3,-1):size():totable(), target, 'Error in view using dimension -1')
local tensor_view = tensor:view(5,3)
tensor_view:fill(torch.rand(1)[1])
mytester:asserteq((tensor_view-tensor):abs():max(), 0, 'Error in view')
local target_tensor = func(torch.Tensor())
mytester:assertTableEq(target_tensor:viewAs(tensor, template):size():totable(), target, 'Error in viewAs')
mytester:assertTableEq(target_tensor:view(tensor, 3,5):size():totable(), target, 'Error in view')
mytester:assertTableEq(target_tensor:view(tensor, torch.LongStorage{3,5}):size():totable(), target, 'Error in view using LongStorage')
mytester:assertTableEq(target_tensor:view(tensor, -1,5):size():totable(), target, 'Error in view using dimension -1')
mytester:assertTableEq(target_tensor:view(tensor, 3,-1):size():totable(), target, 'Error in view using dimension -1')
target_tensor:fill(torch.rand(1)[1])
mytester:asserteq((target_tensor-tensor):abs():max(), 0, 'Error in viewAs')
end
function torchtest.expand()
for k,v in ipairs({"real", "half"}) do
torchtest_expand(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_expand(func)
local result = func(torch.Tensor())
local tensor = func(torch.rand(8,1))
local template = func(torch.rand(8,5))
local target = template:size():totable()
mytester:assertTableEq(tensor:expandAs(template):size():totable(), target, 'Error in expandAs')
mytester:assertTableEq(tensor:expand(8,5):size():totable(), target, 'Error in expand')
mytester:assertTableEq(tensor:expand(torch.LongStorage{8,5}):size():totable(), target, 'Error in expand using LongStorage')
result:expandAs(tensor,template)
mytester:assertTableEq(result:size():totable(), target, 'Error in expandAs using result')
result:expand(tensor,8,5)
mytester:assertTableEq(result:size():totable(), target, 'Error in expand using result')
result:expand(tensor,torch.LongStorage{8,5})
mytester:assertTableEq(result:size():totable(), target, 'Error in expand using result and LongStorage')
mytester:asserteq((result:mean(2):view(8,1)-tensor):abs():max(), 0, 'Error in expand (not equal)')
end
function torchtest.repeatTensor()
for k,v in ipairs({"real", "half"}) do
torchtest_repeatTensor(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_repeatTensor(func, mean)
local result = func(torch.Tensor())
local tensor = func(torch.rand(8,4))
local size = {3,1,1}
local sizeStorage = torch.LongStorage(size)
local target = {3,8,4}
mytester:assertTableEq(tensor:repeatTensor(unpack(size)):size():totable(), target, 'Error in repeatTensor')
mytester:assertTableEq(tensor:repeatTensor(sizeStorage):size():totable(), target, 'Error in repeatTensor using LongStorage')
result:repeatTensor(tensor,unpack(size))
mytester:assertTableEq(result:size():totable(), target, 'Error in repeatTensor using result')
result:repeatTensor(tensor,sizeStorage)
mytester:assertTableEq(result:size():totable(), target, 'Error in repeatTensor using result and LongStorage')
mytester:asserteq((result:mean(1):view(8,4)-tensor):abs():max(), 0, 'Error in repeatTensor (not equal)')
end
function torchtest.isSameSizeAs()
for k,v in ipairs({"real", "half"}) do
torchtest_isSameSizeAs(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_isSameSizeAs(func)
local t1 = func(torch.Tensor(3, 4, 9, 10))
local t2 = func(torch.Tensor(3, 4))
local t3 = func(torch.Tensor(1, 9, 3, 3))
local t4 = func(torch.Tensor(3, 4, 9, 10))
mytester:assert(t1:isSameSizeAs(t2) == false, "wrong answer ")
mytester:assert(t1:isSameSizeAs(t3) == false, "wrong answer ")
mytester:assert(t1:isSameSizeAs(t4) == true, "wrong answer ")
end
function torchtest.isSetTo()
for k,v in ipairs({"real", "half"}) do
torchtest_isSetTo(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_isSetTo(func)
local t1 = func(torch.Tensor(3, 4, 9, 10))
local t2 = func(torch.Tensor(3, 4, 9, 10))
local t3 = func(torch.Tensor()):set(t1)
local t4 = t3:reshape(12, 90)
mytester:assert(t1:isSetTo(t2) == false, "tensors do not share storage")
mytester:assert(t1:isSetTo(t3) == true, "tensor is set to other")
mytester:assert(t3:isSetTo(t1) == true, "isSetTo should be symmetric")
mytester:assert(t1:isSetTo(t4) == false, "tensors have different view")
mytester:assert(not func(torch.Tensor()):isSetTo(func(torch.Tensor())),
"Tensors with no storages should not appear to be set " ..
"to each other")
end
function torchtest.equal()
-- Contiguous, 1D
local t1 = torch.Tensor{3, 4, 9, 10}
local t2 = t1:clone()
local t3 = torch.Tensor{1, 9, 3, 10}
local t4 = torch.Tensor{3, 4, 9}
local t5 = torch.Tensor()
mytester:assert(t1:equal(t2) == true, "wrong answer ")
mytester:assert(t1:equal(t3) == false, "wrong answer ")
mytester:assert(t1:equal(t4) == false, "wrong answer ")
mytester:assert(t1:equal(t5) == false, "wrong answer ")
mytester:assert(torch.equal(t1, t2) == true, "wrong answer ")
mytester:assert(torch.equal(t1, t3) == false, "wrong answer ")
mytester:assert(torch.equal(t1, t4) == false, "wrong answer ")
mytester:assert(torch.equal(t1, t5) == false, "wrong answer ")
-- Non contiguous, 2D
local s = torch.Tensor({{1, 2, 3, 4}, {5, 6, 7, 8}})
local s1 = s[{{}, {2, 3}}]
local s2 = s1:clone()
local s3 = torch.Tensor({{2, 3}, {6, 7}})
local s4 = torch.Tensor({{0, 0}, {0, 0}})
mytester:assert(not s1:isContiguous(), "wrong answer ")
mytester:assert(s1:equal(s2) == true, "wrong answer ")
mytester:assert(s1:equal(s3) == true, "wrong answer ")
mytester:assert(s1:equal(s4) == false, "wrong answer ")
mytester:assert(torch.equal(s1, s2) == true, "wrong answer ")
mytester:assert(torch.equal(s1, s3) == true, "wrong answer ")
mytester:assert(torch.equal(s1, s4) == false, "wrong answer ")
end
function torchtest.isSize()
for k,v in ipairs({"real", "half"}) do
torchtest_isSize(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_isSize(func)
local t1 = func(torch.Tensor(3, 4, 5))
local s1 = torch.LongStorage({3, 4, 5})
local s2 = torch.LongStorage({5, 4, 3})
mytester:assert(t1:isSize(s1) == true, "wrong answer ")
mytester:assert(t1:isSize(s2) == false, "wrong answer ")
mytester:assert(t1:isSize(t1:size()) == true, "wrong answer ")
end
function torchtest.elementSize()
local byte = torch.ByteStorage():elementSize()
local char = torch.CharStorage():elementSize()
local short = torch.ShortStorage():elementSize()
local int = torch.IntStorage():elementSize()
local long = torch.LongStorage():elementSize()
local float = torch.FloatStorage():elementSize()
local double = torch.DoubleStorage():elementSize()
local half = torch.HalfStorage():elementSize()
mytester:asserteq(byte, torch.ByteTensor():elementSize())
mytester:asserteq(char, torch.CharTensor():elementSize())
mytester:asserteq(short, torch.ShortTensor():elementSize())
mytester:asserteq(int, torch.IntTensor():elementSize())
mytester:asserteq(long, torch.LongTensor():elementSize())
mytester:asserteq(float, torch.FloatTensor():elementSize())
mytester:asserteq(double, torch.DoubleTensor():elementSize())
mytester:asserteq(half, torch.HalfTensor():elementSize())
mytester:assertne(byte, 0)
mytester:assertne(char, 0)
mytester:assertne(short, 0)
mytester:assertne(int, 0)
mytester:assertne(long, 0)
mytester:assertne(float, 0)
mytester:assertne(double, 0)
mytester:assertne(half, 0)
-- These tests are portable, not necessarily strict for your system.
mytester:asserteq(byte, 1)
mytester:asserteq(char, 1)
mytester:assert(short >= 2)
mytester:assert(int >= 2)
mytester:assert(int >= short)
mytester:assert(long >= 4)
mytester:assert(long >= int)
mytester:assert(double >= float)
mytester:assert(half <= float)
end
function torchtest.split()
for k,v in ipairs({"real", "half"}) do
torchtest_split(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_split(func)
local result = {}
local tensor = func(torch.rand(7,4))
local splitSize = 3
local targetSize = {{3,4},{3,4},{1,4}}
local dim = 1
local splits = tensor:split(splitSize, dim)
local start = 1
for i, split in ipairs(splits) do
mytester:assertTableEq(split:size():totable(), targetSize[i], 'Size error in split '..i)
mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.00001, 'Content error in split '..i)
start = start + targetSize[i][dim]
end
torch.split(result, tensor, splitSize, dim)
local start = 1
for i, split in ipairs(result) do
mytester:assertTableEq(split:size():totable(), targetSize[i], 'Result size error in split '..i)
mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.000001, 'Result content error in split '..i)
start = start + targetSize[i][dim]
end
mytester:asserteq(#splits, #result, 'Non-consistent output size from split')
for i, split in ipairs(splits) do
mytester:assertTensorEq(split,result[i], 0, 'Non-consistent outputs from split')
end
end
function torchtest.chunk()
for k,v in ipairs({"real", "half"}) do
torchtest_chunk(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_chunk(func)
local result = {}
local tensor = func(torch.rand(4,7))
local nChunk = 3
local targetSize = {{4,3},{4,3},{4,1}}
local dim = 2
local splits = tensor:chunk(nChunk, dim)
local start = 1
for i, split in ipairs(splits) do
mytester:assertTableEq(split:size():totable(), targetSize[i], 'Size error in chunk '..i)
mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.00001, 'Content error in chunk '..i)
start = start + targetSize[i][dim]
end
torch.split(result, tensor, nChunk, dim)
local start = 1
for i, split in ipairs(result) do
mytester:assertTableEq(split:size():totable(), targetSize[i], 'Result size error in chunk '..i)
mytester:assertTensorEq(tensor:narrow(dim, start, targetSize[i][dim]), split, 0.000001, 'Result content error in chunk '..i)
start = start + targetSize[i][dim]
end
end
function torchtest.table()
local convStorage = {
['real'] = 'FloatStorage',
['half'] = 'HalfStorage'
}
for k,v in ipairs(convStorage) do
torchtest_totable(torch.getmetatable(torch.Tensor():type())[k], v)
end
end
function torchtest_totable(func, storageType)
local table0D = {}
local tensor0D = func(torch.Tensor(table0D))
mytester:assertTableEq(torch.totable(tensor0D), table0D, 'tensor0D:totable incorrect')
local table1D = {1, 2, 3}
local tensor1D = func(torch.Tensor(table1D))
local storage = torch[storageType](table1D)
mytester:assertTableEq(tensor1D:totable(), table1D, 'tensor1D:totable incorrect')
mytester:assertTableEq(storage:totable(), table1D, 'storage:totable incorrect')
mytester:assertTableEq(torch.totable(tensor1D), table1D, 'torch.totable incorrect for Tensors')
mytester:assertTableEq(torch.totable(storage), table1D, 'torch.totable incorrect for Storages')
local table2D = {{1, 2}, {3, 4}}
local tensor2D = func(torch.Tensor(table2D))
mytester:assertTableEq(tensor2D:totable(), table2D, 'tensor2D:totable incorrect')
local tensor3D = func(torch.Tensor({{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}))
local tensorNonContig = tensor3D:select(2, 2)
mytester:assert(not tensorNonContig:isContiguous(), 'invalid test')
mytester:assertTableEq(tensorNonContig:totable(), {{3, 4}, {7, 8}},
'totable() incorrect for non-contiguous tensors')
end
function torchtest.permute()
for k,v in ipairs({"real", "half"}) do
torchtest_permute(torch.getmetatable(torch.Tensor():type())[v])
end
end
function torchtest_permute(func)
local orig = {1,2,3,4,5,6,7}
local perm = torch.randperm(7):totable()
local x = torch.Tensor(unpack(orig)):fill(0)
local new = x:permute(unpack(perm)):size():totable()
mytester:assertTableEq(perm, new, 'Tensor:permute incorrect')
mytester:assertTableEq(x:size():totable(), orig, 'Tensor:permute changes tensor')
end
function torchtest.serialize()
local tableObj = {6, a = 42}
local tensObj = torch.randn(3,4,5)
-- Test serializing a table
local serString = torch.serialize(tableObj)
local serStorage = torch.serializeToStorage(tableObj)
mytester:assertTableEq(tableObj, torch.deserialize(serString))
mytester:assertTableEq(tableObj, torch.deserializeFromStorage(serStorage))
-- Test serializing a Tensor
serString = torch.serialize(tensObj)
serStorage = torch.serializeToStorage(tensObj)
mytester:assertTensorEq(tensObj, torch.deserialize(serString), 1e-10)
mytester:assertTensorEq(tensObj, torch.deserializeFromStorage(serStorage), 1e-10)
end
function torchtest.storageview()
local s1 = torch.LongStorage({3, 4, 5})
local s2 = torch.LongStorage(s1, 2)
mytester:assert(s2:size() == 2, "should be size 2")
mytester:assert(s2[1] == s1[2], "should have 4 at position 1")
mytester:assert(s2[2] == s1[3], "should have 5 at position 2")
s2[1] = 13
mytester:assert(13 == s1[2], "should have 13 at position 1")
end
function torchtest.nonzero()
local nSrc = 12
local types = {
'torch.ByteTensor',
'torch.CharTensor',
'torch.ShortTensor',
'torch.IntTensor',
'torch.FloatTensor',
'torch.DoubleTensor',
'torch.LongTensor',
}
local shapes = {
torch.LongStorage{12},
torch.LongStorage{12, 1},
torch.LongStorage{1, 12},
torch.LongStorage{6, 2},
torch.LongStorage{3, 2, 2},
}
for _, type in ipairs(types) do
local tensor = torch.rand(nSrc):mul(2):floor():type(type)
for _, shape in ipairs(shapes) do
tensor = tensor:reshape(shape)
local dst1 = torch.nonzero(tensor)
local dst2 = tensor:nonzero()
-- Does not work. Torch uses the first argument to determine what
-- type the Tensor is expected to be. In our case the second argument
-- determines the type of Tensor.
--local dst3 = torch.LongTensor()
--torch.nonzero(dst3, tensor)
-- However, there are workarounds to this issue when it is desired to
-- use an existing tensor for the result:
local dst4 = torch.LongTensor()
tensor.nonzero(dst4, tensor)
if shape:size() == 1 then
local dst = {}
for i = 1 , nSrc do
if tensor[i] ~= 0 then
table.insert(dst, i)
end
end
mytester:assertTensorEq(dst1:select(2, 1), torch.LongTensor(dst), 0.0,
"nonzero error")
mytester:assertTensorEq(dst2:select(2, 1), torch.LongTensor(dst), 0.0,
"nonzero error")
--mytester:assertTensorEq(dst3:select(2, 1), torch.LongTensor(dst),
-- 0.0, "nonzero error")
mytester:assertTensorEq(dst4:select(2, 1), torch.LongTensor(dst), 0.0,
"nonzero error")
elseif shape:size() == 2 then
-- This test will allow through some false positives. It only checks
-- that the elements flagged positive are indeed non-zero.
for i=1,dst1:size()[1] do
mytester:assert(tensor[dst1[i][1]][dst1[i][2]] ~= 0)
end
elseif shape:size() == 3 then
-- This test will allow through some false positives. It only checks
-- that the elements flagged positive are indeed non-zero.
for i=1,dst1:size()[1] do
mytester:assert(tensor[dst1[i][1]][dst1[i][2]][dst1[i][3]] ~= 0)
end
end
end
end
end
function torchtest.testheaptracking()
local oldheaptracking = torch._heaptracking
if oldheaptracking == nil then
oldheaptracking = false
end
torch.setheaptracking(true)
mytester:assert(torch._heaptracking == true, 'Heap tracking expected true')
torch.setheaptracking(false)
mytester:assert(torch._heaptracking == false, 'Heap tracking expected false')
-- put heap tracking to its original state
torch.setheaptracking(oldheaptracking)
end
function torchtest.bernoulli()
local size = torch.LongStorage{10, 10}
local t = torch.ByteTensor(size)
local function isBinary(t)
return torch.ne(t, 0):cmul(torch.ne(t, 1)):sum() == 0
end
local p = 0.5
t:bernoulli(p)
mytester:assert(isBinary(t), 'Sample from torch.bernoulli is not binary')
local p = torch.rand(size)
t:bernoulli(p)
mytester:assert(isBinary(t), 'Sample from torch.bernoulli is not binary')
end
function torchtest.logNormal()
local t = torch.FloatTensor(10, 10)
local mean, std = torch.uniform(), 0.1 * torch.uniform()
local tolerance = 0.02
t:logNormal(mean, std)
local logt = t:log()
mytester:assertalmosteq(logt:mean(), mean, tolerance, 'mean is wrong')
mytester:assertalmosteq(logt:std(), std, tolerance, 'tolerance is wrong')
end
function torch.test(tests)
torch.setheaptracking(true)
math.randomseed(os.time())
if torch.getdefaulttensortype() == 'torch.FloatTensor' then
precision = 1e-4
elseif torch.getdefaulttensortype() == 'torch.DoubleTensor' then
precision = 1e-8
end
mytester = torch.Tester()
mytester:add(torchtest)
mytester:run(tests)
return mytester
end
|
local skynet = require "skynet"
local libdb = require "libdbproxy"
local libcenter = require "libcenter"
local libagentpool = require "libwsagentpool"
local faci = require "faci.module"
local key_seq = 1
local module = faci.get_module("login")
local dispatch = module.dispatch
local forward = module.forward
local event = module.event
local login_auth = require "login.login_auth"
local login_result_code=require "loginresultcode"
function forward.login(fd, msg, source)
local sdkid = msg.sdkid --ƽ̨ID
local account = msg.account
local password = msg.password
local msgresult={}
msgresult.account=msg.account
msgresult._cmd=msg._cmd
msgresult._check=msg._check
--key
key_seq = key_seq + 1
--local key = env.id*10000 + key_seq
local key = key_seq
--login auth
local isok, uid = login_auth(sdkid, msg)
if not isok then
ERROR("+++++++++++ account: ",inspect(account), " login login_auth fail +++++++++")
log.debug("%s login fail, wrong password ", account)
msgresult.result = login_result_code.LOGIN_WRONG_PASSWORD
return msgresult
end
--center
local data = {
node = skynet.getenv("nodename"),
fd = fd,
gate = source,
key = key,
}
if not libcenter.login(uid, data) then
ERROR("+++++++++++", uid, " login fail, center login +++++++++")
msgresult.result = login_result_code.LOGIN_CENTER_FAIL
return msgresult
end
--game
local data = {
fd = fd,
gate = source,
account = {
uid = uid,
account = {
account = msg.account,
password = msg.password,
}
}
}
local ret, agent = libagentpool.login(data)
if not ret then
libcenter.logout(uid, key)
ERROR("++++++++++++", uid, " login fail, load data err +++++++++")
msgresult.result = login_result_code.LOGIN_LOAD_DATA_FAIL
return msgresult
end
--center
local data = {
agent = agent,
key = key,
}
if not libcenter.register(uid, data) then
libagentpool.recycle(agent)
libcenter.logout(uid, key)
ERROR("++++++++++++", uid, " login fail, register center fail +++++++++")
msgresult.result =login_result_code.LOGIN_REGISTER_CENTER_FAIL
return msgresult
end
--gate
local data = {
uid = uid,
fd = fd,
agent = agent,
key = key
}
if not skynet.call(source, "lua", "register", data) then
libcenter.logout(uid, key)
ERROR("++++++++++++", uid, " login fail, register gate fail +++++++++")
msgresult.result = login_result_code.LOGIN_REGISTER_GATE_FILE
return msgresult
end
msgresult.uid = uid
msgresult.result = 0
--INFO("++++++++++++++++login success uid:", uid, " account: ", account, "++++++++++++++++++")
local ok, info = libcenter.watch({})
DEBUG("account: ", account, ' uid: ', uid, " logined: ", info.logined or 0, ' logining: ', info.logining or 0)
return msgresult
end |
local serverstockvalues = {
[1] = { ["name"] = "Pixerium Coin", ["value"] = 0.0, ["identifier"] = "CRYPIX", ["lastchange"] = 0.00, ["amountavailable"] = 0.0 },
[2] = { ["name"] = "Ammunation", ["value"] = 1000.0, ["identifier"] = "STRAMM", ["lastchange"] = 0.00, ["amountavailable"] = 100.0 },
[3] = { ["name"] = "LS Customs", ["value"] = 1000.0, ["identifier"] = "STRLSC", ["lastchange"] = 0.00, ["amountavailable"] = 100.0 },
[4] = { ["name"] = "7/11", ["value"] = 1000.0, ["identifier"] = "STR711", ["lastchange"] = 0.00, ["amountavailable"] = 100.0 },
[5] = { ["name"] = "Bank of America", ["value"] = 1000.0, ["identifier"] = "STRBOA", ["lastchange"] = 0.00, ["amountavailable"] = 100.0 },
[6] = { ["name"] = "Clothing LS", ["value"] = 1000.0, ["identifier"] = "STRCLS", ["lastchange"] = 0.00, ["amountavailable"] = 100.0 },
}
clientstockamount = {
[1] = { ["value"] = 5.00 },
[2] = { ["value"] = 0.00 },
[3] = { ["value"] = 0.00 },
[4] = { ["value"] = 0.00 },
[5] = { ["value"] = 0.00 },
[6] = { ["value"] = 0.00 },
}
RegisterNetEvent("Crypto:GivePixerium")
AddEventHandler("Crypto:GivePixerium", function(amount)
clientstockamount[1]["value"] = clientstockamount[1]["value"] + amount
Citizen.Trace("Retreived crypto")
updateServerClientStocks()
TriggerEvent("customNotification", "You have received Pixerium")
end)
RegisterNetEvent("Crypto:RemovePixerium")
AddEventHandler("Crypto:RemovePixerium", function(amount)
clientstockamount[1]["value"] = clientstockamount[1]["value"] - amount
updateServerClientStocks()
Citizen.Trace("Lost crypto")
end)
--[[
RegisterCommand("omglol", function(source, args)
TriggerServerEvent('stocksreplace', json.encode(clientstockamount))
end)
--]]
RegisterNetEvent('stocks:payupdate');
AddEventHandler('stocks:payupdate', function()
local payamount = 0
for i = 2, #clientstockamount do
local mystock = clientstockamount[i]["value"]
if mystock > 0 then
local currentlyPaying = serverstockvalues[i]["value"] / 200
local totalpay = (currentlyPaying * mystock) / 100
local mypayout = math.ceil(totalpay * 100)
local haslost = 0.0
payamount = payamount + mypayout
if serverstockvalues[i]["value"] < 1000.0 then
if mystock > 3 then
if math.random(100) > 90 then
local stockloss = math.ceil(((mystock / 100) / 3) * 100) / 100
clientstockamount[i]["value"] = mystock - stockloss
TriggerServerEvent("stocks:bleedstocks",i,stockloss)
haslost = haslost - stockloss
end
end
if mystock > 20 then
if math.random(100) > 90 then
local stockloss = math.ceil(((mystock / 100) / 3) * 100) / 100
clientstockamount[i]["value"] = mystock - stockloss
TriggerServerEvent("stocks:bleedstocks",i,stockloss)
haslost = haslost - stockloss
end
end
end
if haslost < 0 then
TriggerEvent("chatMessagess", "EMAIL ", 8, "Interest pay out of $" .. mypayout .. " for stock ID " .. serverstockvalues[i]["identifier"] .. ". The company also cut your shares by " .. haslost .. " to increase profits. ")
else
TriggerEvent("chatMessagess", "EMAIL ", 8, "Interest pay out of $" .. mypayout .. " for stock ID " .. serverstockvalues[i]["identifier"])
end
end
end
payamount = math.floor(payamount)
if payamount > 0 then
TriggerServerEvent("server:givepayJob", "Stock Payment", payamount)
end
end)
RegisterNetEvent('stocks:servervalueupdate');
AddEventHandler('stocks:servervalueupdate', function(sentvalues)
serverstockvalues = sentvalues
end)
RegisterNetEvent('stocks:clientvalueupdate');
AddEventHandler('stocks:clientvalueupdate', function(sentvalues)
clientstockamount = sentvalues
end)
RegisterNetEvent('stocks:jailed');
AddEventHandler('stocks:jailed', function()
for i=2,#clientstockamount do
if clientstockamount[i]["value"] > 1.0 then
local loss = math.floor((clientstockamount[i]["value"] / 20) * 100) / 100
TriggerServerEvent("stocks:reducestock",i,loss)
end
end
end)
RegisterNetEvent('stocks:newstocks');
AddEventHandler('stocks:newstocks', function(amountBuying,identifier)
clientstockamount[identifier]["value"] = clientstockamount[identifier]["value"] + amountBuying
updateServerClientStocks()
end)
RegisterNetEvent('stocks:losestocks');
AddEventHandler('stocks:losestocks', function(amountBuying,identifier)
clientstockamount[identifier] = clientstockamount[identifier] - amountBuying
updateServerClientStocks()
end)
function updateServerClientStocks()
TriggerServerEvent("stocks:clientvalueupdate",clientstockamount)
end
RegisterNetEvent('pixerium:check');
AddEventHandler('pixerium:check', function(costs,functionCall,server)
if clientstockamount[1]["value"] >= costs then
clientstockamount[1]["value"] = clientstockamount[1]["value"] - costs
updateServerClientStocks()
if server then
TriggerServerEvent(functionCall)
else
TriggerEvent(functionCall)
end
else
TriggerEvent("chatMessagess", "EMAIL ", 8, "You need " .. costs .." pixerium!")
end
end)
RegisterNetEvent('stocks:buyitem');
AddEventHandler('stocks:buyitem', function(typeSent)
local costs = 15
if typeSent == "weapon" then
costs = 5
end
if typeSent == "bigweapon" then
costs = 25
end
if typeSent == "crack" then
costs = 10
end
if clientstockamount[1]["value"] >= costs then
clientstockamount[1]["value"] = clientstockamount[1]["value"] - costs
updateServerClientStocks()
TriggerEvent("stocks:timedEvent",typeSent)
else
TriggerEvent("chatMessagess", "EMAIL ", 8, "You need 25 pixerium for big guns or 5 for small, come back when you have it, Pepega.")
end
end)
RegisterNUICallback('stocksTradeToPlayer', function(data, cb)
local index = 0
local amount = 0
local sending = math.ceil(tonumber(data.amount) * 100) / 100
for i=1,#serverstockvalues do
if data.identifier == serverstockvalues[i]["identifier"] then
index = i
amount = clientstockamount[i]["value"]
end
end
if index == 0 then
-- not enough to do the trade
TriggerEvent("DoShortHudText","Incorrect Identifier.",2)
TriggerEvent("stocks:refreshstocks")
return
end
if amount < tonumber(data.amount) then
-- not enough to do the trade
TriggerEvent("DoShortHudText","Not enough stock.",2)
TriggerEvent("stocks:refreshstocks")
return
end
clientstockamount[index]["value"] = clientstockamount[index]["value"] - sending
Citizen.Trace("removing " .. sending .. " shares from index " .. index )
TriggerServerEvent('phone:stockTradeAttempt', index, data.playerid, sending )
Citizen.Wait(500)
TriggerEvent("stocks:refreshstocks")
end)
RegisterNetEvent('stocks:refreshstocks');
AddEventHandler('stocks:refreshstocks', function()
--[[for i = 1, #serverstockvalues do
local colortype = 1
if i == 1 or i == 3 or i == 5 then
colortype = 2
end
local lastchangestock = "<div class='change stockred'>▼" .. serverstockvalues[i]["lastchange"] .. "</div>"
if serverstockvalues[i]["lastchange"] > -0.01 then
lastchangestock = "<div class='change stockgreen'>▲" .. serverstockvalues[i]["lastchange"] .. "</div>"
end
SendNUIMessage({
openSection = "addstock",
namesent = serverstockvalues[i]["name"],
identifier = serverstockvalues[i]["identifier"],
lastchange = lastchangestock,
valuesent = serverstockvalues[i]["value"],
amountsold = serverstockvalues[i]["amountsold"],
clientstock = clientstockamount[i]["value"],
colorsent = colortype,
available = serverstockvalues[i]["amountavailable"]
})
end--]]
sendStocksToPhone(true);
end)
function sendStocksToPhone(isRefresh)
local stocksData = {}
for i = 1, #serverstockvalues do
table.insert(stocksData, {
identifier = serverstockvalues[i]["identifier"],
name = serverstockvalues[i]["name"],
value = serverstockvalues[i]["value"],
change = serverstockvalues[i]["lastchange"],
available = serverstockvalues[i]["amountavailable"],
clientStockValue = clientstockamount[i]["value"]
})
end
SendNUIMessage({ openSection = "addStocks", stocksData = stocksData})
if isRefresh then
updateServerClientStocks()
end
end
RegisterNUICallback('btnStocks', function()
TriggerServerEvent('stocks:retrieve')
sendStocksToPhone();
--[[
for i = 1, #serverstockvalues do
local colortype = 1
if i == 1 or i == 3 or i == 5 then
colortype = 2
end
local lastchangestock = "<div class='change stockred'>▼" .. serverstockvalues[i]["lastchange"] .. "</div>"
if serverstockvalues[i]["lastchange"] > -0.01 then
lastchangestock = "<div class='change stockgreen'>▲" .. serverstockvalues[i]["lastchange"] .. "</div>"
end
SendNUIMessage({
openSection = "addstock",
namesent = serverstockvalues[i]["name"],
identifier = serverstockvalues[i]["identifier"],
lastchange = lastchangestock,
valuesent = serverstockvalues[i]["value"],
amountsold = serverstockvalues[i]["amountsold"],
clientstock = clientstockamount[i]["value"],
colorsent = colortype,
available = serverstockvalues[i]["amountavailable"]
})
end--]]
end)
function requestUpdate()
TriggerServerEvent("stocks:retrieve")
end
|
local _, ns = ...
local C = ns.C
C["skins"] = {
details = {
enabled = true,
barHeight = 18,
barSpacing = 1,
barsToDisplayMax = 7,
width = 250,
point = "BOTTOMRIGHT",
}
}
|
local CardWidth = 38
local CardHeight = 61
local function checkCollision(x1,y1,w1,h1, x2,y2,w2,h2)
return x1 < x2+w2 and
x2 < x1+w1 and
y1 < y2+h2 and
y2 < y1+h1
end
local function ReverseTable(t)
local reversedTable = {}
local itemCount = #t
for k, v in ipairs(t) do
reversedTable[itemCount + 1 - k] = v
end
return reversedTable
end
--[[
suit:
@type: string
@values: "diamonds", "hearts", "spades", "clubs"
@purpose: specifies the card's suit
value:
@type: string
@values: ("2"-"10"), "a", "k", "q", "j"
@purpose: specifies the card's value
x, y:
@type: number
@purpose: specifies position on screen
w, h:
@type: number
@purpose: specifies width and height of card
visible:
@type: boolean
@purpose: tells renderer whether to draw the card or not
dragx, dragy:
@type: number
@purpose: holds the location of touch positions when being dragged in relation to the card
dragged:
@type: boolean
@purpose: specifies whether the card is being dragged or not
inhand:
@type: boolean
@purpose: specifies whether the card is in hand or not
tweento:
@type: boolean
@purpose: specifies whether the card's tween animations are active
firstTrouchID, lastTouchID, currentTouchID:
@type: number
@purpose: placeholders for when more advanced touch capabilities are added
selected:
@type: boolean
@purpose: specifies if the card is in a selection box
touched, held:
@type: boolean
@purpose: placeholder for when more advanced touch capabilities are added
type:
@type: string
@purpose: specifies to external object handlers the type of object
tapTimer:
@type: timer [timer.lua]
@purpose: placeholder for when more advanced touch capabilities are added
]]--
local card = {
suit = "diamonds",
value = "2",
x = 0,
y = 0,
w = CardWidth,
h = CardHeight,
visible = true,
dragx = 0,
dragy = 0,
dragged = false,
inhand = false,
tweento = false,
firstTouchID = -1,
lastTouchID = 1,
currentTouchID = -1,
selected = false,
touched = false,
held = false,
type = "card",
tapTimer = timer.new(0.5),
networkID = "",
netSelected = false,
--[[
this:getPosition()
@purpose: returns the x and y values of the object
@return: this.x, this.y
]]--
getPosition = function( self )
return self.x, self.y
end,
--[[
this:onHold()
@purpose: runs an action when the card is held
@return: void
]]--
onHold = function( self )
local cardsToStack = {}
for i, v in pairs( Game.Objects ) do
if v ~= self then
if checkCollision(self.x, self.y, self.w, self.h, v.x, v.y, v.w, v.h) then
table.insert( cardsToStack, v )
end
end
end
if #cardsToStack > 0 then
local cards = {} --a table to pass to the new deck
for i, v in pairs( cardsToStack ) do
if v.type == "card" then
table.insert( cards, {
suit = v.suit,
value = v.value,
flipped = v.flipped,
networkID = v.networkID
})
v:remove()
elseif v.type == "deck" then
for k, z in pairs( v.cards ) do
table.insert( cards, {
suit = z.suit,
value = z.value,
flipped = z.flipped,
networkID = z.networkID
})
end
v:remove()
end
end
table.insert( cards, {
value = self.value,
suit = self.suit,
flipped = self.flipped,
networkID = self.networkID
})
if Game.IsAdmin() then
Game.InitializeDeck( self.x, self.y, cards )
local sound = love.math.random(1,4)
Game.Sounds.CardPlace[sound]:stop()
Game.Sounds.CardPlace[sound]:play()
self:remove()
else
local n = {}
for i, v in pairs( cards ) do
table.insert( n, v.networkID )
for k, z in pairs( Game.Objects ) do
if z.networkID == v.networkID then
z:remove()
end
end
end
Game.SendToHost("STACK", {
c = cards,
x = self.x,
y = self.y,
})
end
return
end
end,
--[[
this:onSingleTap()
@purpose: flip card to opposite side
@return: void
]]--
onSingleTap = function( self )
self.flipped = not self.flipped
if Game.IsAdmin() then
Game.SendToClients( "FLIP", {
n = self.networkID,
f = self.flipped,
})
else
Game.SendToHost( "FLIP", {
n = self.networkID,
f = self.flipped,
})
end
if self.inhand then
Game.OrderHand()
end
return
end,
--[[
this:onDoubleTap()
@purpose: none at the moment
@return: void
]]
onDoubleTap = function( self )
return
end,
--[[
this:remove( noskip )
@purpose: removes card from global object pool
@params:
noskip: specifies if object search loop should break
@return: void
]]
remove = function( self, noskip )
for i, v in pairs( Game.Objects ) do
if v == self then
table.remove( Game.Objects, i )
if Game.IsAdmin() then
Game.SendToClients("REMOVE", {n = self.networkID})
else
Game.SendToHost("REMOVE", {n = self.networkID})
end
if not noskip then
break
end
end
end
return
end,
removeSilent = function( self, o )
for i, v in pairs( Game.Objects ) do
if v == self then
table.remove( Game.Objects, i )
end
end
return
end,
--[[
this:drag( x, y )
@purpose: executes when the card is being dragged
@params:
x: the new x location for the card
y: the new y location for the card
@return: void
]]
drag = function( self, x, y )
if not self.dragged then
local sound = love.math.random(1,4)
Game.Sounds.CardSlide[sound]:stop()
Game.Sounds.CardSlide[sound]:play()
end
SHOWDECKCHARMS = false
self.dragged = true
self.x = x-self.dragx
self.y = y-self.dragy
if Game.IsAdmin() then
Game.SendToClients("MOVE", {o = Game.UniqueNetworkID, n = self.networkID, x = self.x, y = self.y})
else
Game.SendToHost("MOVE", {o = Game.UniqueNetworkID, n = self.networkID, x = self.x, y = self.y})
end
if self.x < 200 then
if not SHOWCHARMS and not SHOWHAND then
SHOWCHARMS = true
SHOWDECKCHARMS = false
end
SHOWCHARMSX:to(0)
else
SHOWDECKCHARMS = false
SHOWCHARMSX:to(-75)
end
if self.selected then
for i, v in pairs( Game.Selection ) do
for k, z in pairs( Game.Objects ) do
if z.networkID == v then
z.x = x - z.dragx
z.y = y - z.dragy
end
end
end
end
end,
--[[
this:update( dt )
@purpose: internal update function; updates internal timers and tweens
@params:
dt: delta time (from love.update(dt))
@return: void
]]--
update = function( self, dt )
if self.visible then
if self.dragged then
if self.x >= love.graphics.getWidth()/4 and self.x <= love.graphics.getWidth() * .75 and self.y >= love.graphics.getHeight() - (love.graphics.getHeight() * (150 / love.graphics.getHeight())) then
if not SHOWHAND then
SHOWHAND = true
SHOWHANDY:to(love.graphics.getHeight()-150)
end
else
if SHOWHAND then
SHOWHANDY:to(love.graphics.getHeight()-15)
end
SHOWHAND = false
end
else
if not self.selected then
if SHOWHAND then
SHOWHANDY:to(love.graphics.getHeight()-15)
end
SHOWHAND = false
end
end
if self.touched and not self.dragged then
if self.tapTimer:update( dt ) then
self.held = true
if self.onHold then self:onHold() end
self.tapTimer:stop()
end
end
if self.tweento then
if self.tweentotween:update( dt ) then
self.tweento = false
end
end
end
end,
--[[
this:draw()
@purpose: draws object to the screen
@return: void
]]
draw = function( self )
if self.visible then
if not self.flipped then
love.graphics.draw( Cards[self.suit][self.value], self.x, self.y, 0, 2, 2 )
else
love.graphics.draw( Cards.backs.earth, self.x, self.y, 0, 2, 2 )
end
if self.selected then
love.graphics.setLineWidth(3)
love.graphics.setColor( 0, 255, 0 )
love.graphics.rectangle("line", self.x, self.y, self.w*2, self.h*2 )
love.graphics.setColor( 255, 255, 255 )
love.graphics.setLineWidth(1)
end
if self.netSelected then
love.graphics.setLineWidth(3)
love.graphics.setColor( 0, 255, 255 )
love.graphics.rectangle("line", self.x, self.y, self.w*2, self.h*2 )
love.graphics.setColor( 255, 255, 255 )
love.graphics.setLineWidth(1)
end
end
return
end,
--[[
this:startTouch( id, x, y )
@purpose: initializes a touch event to the object
@params:
id: the touch's unique id
x: x position
y: y position
skipUpdate: whether the card should not re-order itself
]]
startTouch = function( self, id, x, y, skipUpdate )
self.dragx = x-self.x
self.dragy = y-self.y
self.touched = true
self.currentTouchID = id
self.tapTimer:restart()
self.tapTimer:start()
if self.selected then
for i, v in ipairs( Game.Objects ) do
if v.type ~= "deckgroup" and v.selected then
v.dragx = x-v.x
v.dragy = y-v.y
else
--v:bottomDrawOrder()
end
end
end
if not skipUpdate then
self:topDrawOrder()
end
end,
putInHand = function( self )
if #Game.Hand < 13 then
if (Game.IsAdmin()) then
Game.SendToClients("PUTINHAND", {o = Game.UniqueNetworkID, n = self.networkID})
else
Game.SendToHost("PUTINHAND", {o = Game.UniqueNetworkID, n = self.networkID})
end
self.inhand = true
if (self.inhand) then
for i, v in pairs( Game.Hand ) do
if v == self.networkID then
table.remove(Game.Hand, i)
end
end
end
table.insert( Game.Hand, self.networkID )
end
self:topDrawOrder()
end,
endTouch = function( self, id )
if self.touched then
local sound = love.math.random(1,4)
Game.Sounds.CardSlide[sound]:stop()
Game.Sounds.CardSlide[sound]:play()
self.tapTimer:stop()
if not self.held and not self.dragged then
self:onSingleTap()
end
local w = 75
if self.dragged then
if self.x + self.w >= 0 and self.x <= w and self.y + self.h >= 0 and self.y <= w then
if self.selected then
for i, v in pairs( Game.Selection ) do
for k, z in pairs( Game.Objects ) do
if z.networkID == v then
z:remove()
end
end
end
end
self:remove()
end
end
SHOWCHARMSX:to(-75)
if SHOWHAND then
if self.x >= love.graphics.getWidth()/4 and self.x <= love.graphics.getWidth() *.75 then
self:putInHand()
if self.selected and #Game.Selection > 1 then
for i, v in pairs( Game.Selection ) do
for k, z in pairs( Game.Objects ) do
if z.networkID == v then
if z.type == "card" then
z:putInHand()
else
z.tweentox = z.startdx
z.tweentoy = z.startdy
z.tweento = true
end
end
end
end
end
end
SHOWHANDY:to(love.graphics.getHeight()-15)
SHOWHAND = false
end
if self.inhand and self.y < love.graphics.getHeight()*.85 then
self.inhand = false
for i, v in pairs(Game.Hand) do
if v == self.networkID then
if (Game.IsAdmin()) then
Game.SendToClients("TAKEOUTHAND", {o = Game.UniqueNetworkID, n = self.networkID, x = self.x, y = self.y, s = self.suit, v = self.value, f = self.flipped})
else
Game.SendToHost("TAKEOUTHAND", {o = Game.UniqueNetworkID, n = self.networkID, x = self.x, y = self.y, s = self.suit, v = self.value, f = self.flipped})
end
table.remove( Game.Hand, i )
return
end
end
end
for i, v in pairs( Game.Selection ) do
for k, z in pairs( Game.Objects ) do
if z.networkID == v then
z:topDrawOrder()
end
end
end
for i, v in pairs( Game.Objects ) do
v.dragged = false
v.selected = false
v.touched = false
v.held = false
end
love.graphics.setCanvas( Game.SelectionCanvas )
love.graphics.clear()
love.graphics.setCanvas()
Game.Selection = {}
if self.selected then
self:topDrawOrder()
end
self.dragged = false
self.held = false
self.touched = false
self.selected = false
end
end,
cancelTouchManager = function( self, id )
if self.touched then
self.tapTimer:stop()
end
end,
topDrawOrder = function( self )
for i, v in pairs( Game.Objects ) do
if v == self then
table.remove( Game.Objects, i )
table.insert( Game.Objects, self )
break
end
end
end,
bottomDrawOrder = function( self )
for i, v in ipairs( Game.Objects ) do
if v == self then
table.remove( Game.Objects, i )
table.insert( Game.Objects, 1, self )
end
end
end,
}
card.__index = card
function card:new( data )
local data = data or { }
local self = setmetatable(data, card)
self.__index = self
if self.tweentox or self.tweentoy then
self.tweentox = self.tweentox or self.x
self.tweentoy = self.tweentoy or self.y
self.tweento = true
self.tweentotween = tween.new(0.2, self, {x = self.tweentox, y = self.tweentoy}, "inOutExpo")
end
table.insert( Game.Objects, self )
self:topDrawOrder()
return self
end
return card |
hook.Add("RPGM.RegisterCommands", "RPGM.NearbyCommands", function()
local lang = gmodI18n.getAddon("rpgm")
local yellPrefix = RPGM.Config.PrefixStartChar .. lang:getString("yellPrefix") .. RPGM.Config.PrefixEndChar
local whisperPrefix = RPGM.Config.PrefixStartChar .. lang:getString("whisperPrefix") .. RPGM.Config.PrefixEndChar
lang = nil
RPGM.RegisterCommand("yell", {"y", "shout"}, {
RPGM.Classes.TextArgument("Message", false, nil, false, true)
}, function(ply, data)
RPGM.TalkToRange(ply, data[1], RPGM.Config.YellRange, nil, RPGM.Config.YellTagCol, yellPrefix)
RPGM.TalkToPlayer(ply, ply, data[1], RPGM.Config.YellTagCol, yellPrefix)
end)
RPGM.RegisterCommand("whisper", {"w"}, {
RPGM.Classes.TextArgument("Message", false, nil, false, true)
}, function(ply, data)
RPGM.TalkToRange(ply, data[1], RPGM.Config.WhisperRange, nil, RPGM.Config.WhisperTagCol, whisperPrefix)
RPGM.TalkToPlayer(ply, ply, data[1], RPGM.Config.WhisperTagCol, whisperPrefix)
end)
end)
|
-- Preload Modules
require("cjson")
require("resty.sha224")
require("resty.string")
require("config") -- local config
|
-- https://github.com/tarantool/tarantool/issues/6436 Foreign keys
local server = require('test.luatest_helpers.server')
local t = require('luatest')
local g = t.group('gh-6436-foreign-key-test', {{engine = 'memtx'}, {engine = 'vinyl'}})
g.before_all(function(cg)
cg.server = server:new({alias = 'master'})
cg.server:start()
end)
g.after_all(function(cg)
cg.server:stop()
cg.server = nil
end)
g.before_each(function()
end)
g.after_each(function(cg)
cg.server:exec(function()
if box.space.city then box.space.city:drop() end
if box.space.country then box.space.country:drop() end
if box.space.user then box.space.user:drop() end
if box.space.card then box.space.card:drop() end
end)
end)
-- Test with wrong complex foreign key definitions.
g.test_bad_complex_foreign_key = function(cg)
local engine = cg.params.engine
cg.server:exec(function(engine)
local t = require('luatest')
local fmt = {{'planet_id','unsigned'}, {'country_id','unsigned'}, {'name'}}
local country = box.schema.create_space('country', {engine=engine, format=fmt})
country:create_index('pk', {parts={{'planet_id'},{'country_id'}}})
local fmt = {{'city_id'}, {'p_id'}, {'c_id'}}
local function space_opts(foreign_key)
return {engine=engine, format=fmt, foreign_key=foreign_key}
end
local opts = space_opts({space=false,field={}})
t.assert_error_msg_content_equals(
"Illegal parameters, foreign key: space must be string or number",
function() box.schema.create_space('city', opts) end
)
local opts = space_opts({space='country',field='country_id'})
t.assert_error_msg_content_equals(
"Illegal parameters, foreign key: field must be a table with local field -> foreign field mapping",
function() box.schema.create_space('city', opts) end
)
opts = space_opts({space='country',field={}})
t.assert_error_msg_content_equals(
"Illegal parameters, foreign key: field must be a table with local field -> foreign field mapping",
function() box.schema.create_space('city', opts) end
)
opts = space_opts({space='country',field={[false]='country_id'}})
t.assert_error_msg_content_equals(
"Illegal parameters, foreign key: local field must be string or number",
function() box.schema.create_space('city', opts) end
)
opts = space_opts({space='country',field={c_id=false}})
t.assert_error_msg_content_equals(
"Illegal parameters, foreign key: foreign field must be string or number",
function() box.schema.create_space('city', opts) end
)
opts = space_opts({cntr={space='country',field={p_id='planet_id', c_id='country_id'}}})
box.schema.create_space('city', opts)
t.assert_equals(box.space.city.foreign_key,
{ cntr = {field = {c_id = "country_id", p_id = "planet_id"}, space = country.id} }
)
end, {engine})
end
-- Test with complex foreign key by primary index.
g.test_complex_foreign_key_primary = function(cg)
local engine = cg.params.engine
cg.server:exec(function(engine)
local t = require('luatest')
local country = box.schema.create_space('country', {engine=engine})
country:create_index('pk', {parts={{1},{2}}})
country:replace{1, 11, 'Russia'}
country:replace{1, 12, 'France'}
local function city_space_opts(foreign_key)
local fmt = {{name='id', type='unsigned'},
{name='p_id', type='unsigned'},
{name='c_id', type='unsigned'}}
return {engine=engine, format=fmt, foreign_key=foreign_key}
end
local fkey = {space='country',field={p_id='planet_id', c_id='country_id'}}
local city = box.schema.create_space('city', city_space_opts(fkey))
-- Note that the foreign_key was normalized
t.assert_equals(box.space.city.foreign_key,
{ country = {field = {c_id = "country_id", p_id = "planet_id"}, space = country.id} }
)
city:create_index('pk')
t.assert_equals(country:select{}, {{1, 11, 'Russia'}, {1, 12, 'France'}})
t.assert_error_msg_content_equals(
"Can't modify space 'country': space is referenced by foreign key",
function() country:drop() end
)
t.assert_error_msg_content_equals(
"Foreign key 'country' integrity check failed: wrong foreign field name",
function() country:delete{1, 11} end
)
t.assert_equals(country:select{}, {{1, 11, 'Russia'}, {1, 12, 'France'}})
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: foreign index was not found",
function() city:replace{1, 1, 11, 'Moscow'} end
)
local fmt = {{'planet_id','unsigned'}, {'country_id','unsigned'}, {'name'}}
country:format(fmt)
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: foreign tuple was not found",
function() city:replace{1, 1, 500, 'Moscow'} end
)
city:replace{21, 1, 11, 'Moscow'}
end, {engine})
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local city = box.space.city
city:replace{22, 1, 11, 'Tomsk'}
t.assert_equals(city:select{}, {{21, 1, 11, 'Moscow'}, {22, 1, 11, 'Tomsk'}})
end, {engine})
cg.server:eval('box.snapshot()')
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local country = box.space.country
local city = box.space.city
t.assert_error_msg_content_equals(
"Foreign key 'country' integrity check failed: index was not found",
function() country:delete{1, 12} end
)
city:create_index('country', {parts={{'p_id'},{'c_id'}},unique=false})
country:delete{1, 12}
t.assert_error_msg_content_equals(
"Foreign key 'country' integrity check failed: tuple is referenced",
function() country:delete{1, 11} end
)
city:delete{21}
city:delete{22}
country:delete{1, 11}
city:drop()
country:drop()
end, {engine})
end
-- Test with foreign key by secondary index and some variations.
g.test_complex_foreign_key_secondary = function(cg)
local engine = cg.params.engine
cg.server:exec(function(engine)
local t = require('luatest')
local country_fmt = {{name='id', type='unsigned'},
{name='universe_id', type='unsigned'},
{name='planet_name', type='string'},
{name='country_code', type='string'},
{name='name', type='string'}}
--Note: format is not set.
local country = box.schema.create_space('country', {engine=engine})
country:create_index('pk')
country:replace{100, 1, 'earth', 'ru', 'Russia'}
country:replace{101, 1, 'earth', 'rf', 'France'}
local function city_space_opts(foreign_key)
local fmt = {{name='id', type='unsigned'},
{name='p', type='string'},
{name='u', type='unsigned'},
{name='c', type='string'},
{name='name', type='string'}}
return {engine=engine, format=fmt, foreign_key=foreign_key}
end
local fkey = {cntr = {space='country',
field={c='country_code',
u='universe_id',
p='planet_name'}}}
local city = box.schema.create_space('city', city_space_opts(fkey))
fkey.cntr.space = country.id
t.assert_equals(city.foreign_key, fkey);
city:create_index('pk')
t.assert_equals(country:select{}, {{100, 1, 'earth', 'ru', 'Russia'},
{101, 1, 'earth', 'rf', 'France'}})
t.assert_error_msg_content_equals(
"Can't modify space 'country': space is referenced by foreign key",
function() country:drop() end
)
t.assert_equals(country:select{}, {{100, 1, 'earth', 'ru', 'Russia'},
{101, 1, 'earth', 'rf', 'France'}})
t.assert_error_msg_content_equals(
"Foreign key constraint 'cntr' failed: foreign index was not found",
function() city:replace{21, 'earth', 1, 'ru', 'Moscow'} end
)
country:format(country_fmt)
t.assert_error_msg_content_equals(
"Foreign key constraint 'cntr' failed: foreign index was not found",
function() city:replace{21, 'earth', 1, 'ru', 'Moscow'} end
)
country:create_index('name1', {parts={{'universe_id'}},
unique=false})
country:create_index('name2', {parts={{'country_code'},
{'universe_id'}},
unique=false})
country:create_index('name3', {parts={{'planet_name'},
{'country_code'},
{'universe_id'}}})
t.assert_error_msg_content_equals(
"Foreign key constraint 'cntr' failed: foreign tuple was not found",
function() city:replace{21, 'earth', 1, 'de', 'Berlin'} end
)
city:replace{21, 'earth', 1, 'ru', 'Moscow'}
end, {engine})
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local city = box.space.city
city:replace{22, 'earth', 1, 'ru', 'Tomsk'}
t.assert_equals(city:select{}, {{21, 'earth', 1, 'ru', 'Moscow'},
{22, 'earth', 1, 'ru', 'Tomsk'}})
end, {engine})
cg.server:eval('box.snapshot()')
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local country = box.space.country
local city = box.space.city
t.assert_error_msg_content_equals(
"Foreign key 'cntr' integrity check failed: index was not found",
function() country:delete{100} end
)
city:create_index('name', {parts={{'u'},{'c'},{'p'}},unique=false})
country:delete{101}
t.assert_error_msg_content_equals(
"Foreign key 'cntr' integrity check failed: tuple is referenced",
function() country:delete{100} end
)
city:delete{21}
city:delete{22}
country:delete{100}
city:drop()
country:drop()
end, {engine})
end
-- The same test as above but with foreign key by numeric space and field.
g.test_complex_foreign_key_numeric = function(cg)
local engine = cg.params.engine
cg.server:exec(function(engine)
local t = require('luatest')
local country_fmt = {{name='id', type='unsigned'},
{name='universe_id', type='unsigned'},
{name='planet_name', type='string'},
{name='country_code', type='string'},
{name='name', type='string'}}
--Note: format is not set.
local country = box.schema.create_space('country', {engine=engine})
country:create_index('pk')
country:replace{100, 1, 'earth', 'ru', 'Russia'}
country:replace{101, 1, 'earth', 'rf', 'France'}
local function city_space_opts(foreign_key)
local fmt = {{name='id', type='unsigned'},
{name='p', type='string'},
{name='u', type='unsigned'},
{name='c', type='string'},
{name='name', type='string'}}
return {engine=engine, format=fmt, foreign_key=foreign_key}
end
local fkey = {cntr = {space=country.id,
field={[4]=4, [3]=2, [2]=3}}}
local city = box.schema.create_space('city', city_space_opts(fkey))
t.assert_equals(city.foreign_key,
{cntr = {field = {[1] = 2, [2] = 1, [3] = 3},
space = country.id}});
city:create_index('pk')
t.assert_equals(country:select{}, {{100, 1, 'earth', 'ru', 'Russia'},
{101, 1, 'earth', 'rf', 'France'}})
t.assert_error_msg_content_equals(
"Can't modify space 'country': space is referenced by foreign key",
function() country:drop() end
)
t.assert_equals(country:select{}, {{100, 1, 'earth', 'ru', 'Russia'},
{101, 1, 'earth', 'rf', 'France'}})
t.assert_error_msg_content_equals(
"Foreign key constraint 'cntr' failed: foreign index was not found",
function() city:replace{21, 'earth', 1, 'ru', 'Moscow'} end
)
country:format(country_fmt)
t.assert_error_msg_content_equals(
"Foreign key constraint 'cntr' failed: foreign index was not found",
function() city:replace{21, 'earth', 1, 'ru', 'Moscow'} end
)
country:create_index('name1', {parts={{'universe_id'}},
unique=false})
country:create_index('name2', {parts={{'country_code'},
{'universe_id'}},
unique=false})
country:create_index('name3', {parts={{'planet_name'},
{'country_code'},
{'universe_id'}}})
t.assert_error_msg_content_equals(
"Foreign key constraint 'cntr' failed: foreign tuple was not found",
function() city:replace{21, 'earth', 1, 'de', 'Berlin'} end
)
city:replace{21, 'earth', 1, 'ru', 'Moscow'}
end, {engine})
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local city = box.space.city
city:replace{22, 'earth', 1, 'ru', 'Tomsk'}
t.assert_equals(city:select{}, {{21, 'earth', 1, 'ru', 'Moscow'},
{22, 'earth', 1, 'ru', 'Tomsk'}})
end, {engine})
cg.server:eval('box.snapshot()')
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local country = box.space.country
local city = box.space.city
t.assert_error_msg_content_equals(
"Foreign key 'cntr' integrity check failed: index was not found",
function() country:delete{100} end
)
city:create_index('name', {parts={{'u'},{'c'},{'p'}},unique=false})
country:delete{101}
t.assert_error_msg_content_equals(
"Foreign key 'cntr' integrity check failed: tuple is referenced",
function() country:delete{100} end
)
city:delete{21}
city:delete{22}
country:delete{100}
city:drop()
country:drop()
end, {engine})
end
-- Test with foreign key and different types of indexes and fields.
g.test_complex_foreign_key_wrong_type = function(cg)
local engine = cg.params.engine
cg.server:exec(function(engine)
local t = require('luatest')
local fmt = {{'id', 'unsigned'}, {'planet_id','unsigned'},
{'code','string'}, {'name','string'}}
local country = box.schema.create_space('country', {engine=engine, format=fmt})
country:create_index('pk')
country:create_index('code', {parts={{'planet_id'},{'code'}}})
country:replace{100, 1, 'ru','Russia'}
local function city_space_opts(foreign_key)
local fmt = {{'id', 'unsigned'}, {'planet_id'}, {'country_code'}}
return {engine=engine, format=fmt, foreign_key=foreign_key}
end
local fkey = {space='country',field={planet_id='planet_id',country_code='code'}}
local city = box.schema.create_space('city', city_space_opts(fkey))
city:create_index('pk')
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: wrong key type",
function() city:replace{1, 1, 1} end
)
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: wrong key type",
function() city:replace{1,'ru','ru'} end
)
end, {engine})
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local city = box.space.city
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: wrong key type",
function() city:replace{1, 1, 1} end
)
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: wrong key type",
function() city:replace{1,'ru','ru'} end
)
end, {engine})
cg.server:eval('box.snapshot()')
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local city = box.space.city
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: wrong key type",
function() city:replace{1, 1, 1} end
)
t.assert_error_msg_content_equals(
"Foreign key constraint 'country' failed: wrong key type",
function() city:replace{1,'ru','ru'} end
)
end, {engine})
cg.server:exec(function()
local t = require('luatest')
local country = box.space.country
local city = box.space.city
city:create_index('wrong1', {parts={{'country_code', 'unsigned'},{'planet_id', 'unsigned'}}, unique=false})
t.assert_error_msg_content_equals(
"Foreign key 'country' integrity check failed: wrong key type",
function() country:delete{100} end
)
end, {engine})
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local country = box.space.country
local city = box.space.city
t.assert_error_msg_content_equals(
"Foreign key 'country' integrity check failed: wrong key type",
function() country:delete{100} end
)
city.index.wrong1:drop()
city:create_index('wrong2', {parts={{'country_code', 'string'},{'planet_id', 'string'}}, unique=false})
t.assert_error_msg_content_equals(
"Foreign key 'country' integrity check failed: wrong key type",
function() country:delete{100} end
)
end, {engine})
cg.server:eval('box.snapshot()')
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local country = box.space.country
local city = box.space.city
t.assert_error_msg_content_equals(
"Foreign key 'country' integrity check failed: wrong key type",
function() country:delete{100} end
)
city.index.wrong2:drop()
end, {engine})
end
-- Test upsert of a comple foreign key.
g.test_complex_foreign_key_upsert = function(cg)
local engine = cg.params.engine
cg.server:exec(function(engine)
local t = require('luatest')
local card = box.schema.create_space(
'card',
{
engine = engine,
format = {
{ name='card_id1', type='unsigned' },
{ name='card_id2', type='unsigned' },
{ name='name', type='string' },
}
}
)
card:create_index('pk', {parts = {'card_id1', 'card_id2'}})
local user = box.schema.create_space(
'user',
{
engine = engine,
format = {
{ name='user_id', type='unsigned' },
{ name='card_id1', type='unsigned', is_nullable=true },
{ name='card_id2', type='unsigned', is_nullable=true },
{ name='name', type='string' },
},
foreign_key = { space = 'card',
field = { card_id1 = 'card_id1',
card_id2 = 'card_id2' } }
}
)
user:create_index('pk')
card:replace{1, 1, "hehe"}
user:replace{1, 1, 1, "haha"}
t.assert_error_msg_content_equals(
"Foreign key constraint 'card' failed: foreign tuple was not found",
function() user:upsert({1, 1, 1, "haha"}, {{'=', 2, 2}}) end
)
end, {engine})
cg.server:eval('box.snapshot()')
cg.server:exec(function()
local t = require('luatest')
local user = box.space.user
t.assert_error_msg_content_equals(
"Foreign key constraint 'card' failed: foreign tuple was not found",
function() user:upsert({1, 1, 1, "haha"}, {{'=', 2, 2}}) end
)
end)
cg.server:eval('box.snapshot()')
cg.server:restart()
cg.server:exec(function()
local t = require('luatest')
local user = box.space.user
t.assert_error_msg_content_equals(
"Foreign key constraint 'card' failed: foreign tuple was not found",
function() user:upsert({1, 1, 1, "haha"}, {{'=', 2, 2}}) end
)
box.space.user:drop()
box.space.card:drop()
end)
end
|
-- https://github.com/dot123
-- 节点工具
-- start --
--------------------------------
-- 按tag查找布局中的结点
-- @function seekNodeByTag
-- @param node parent 要查找布局的结点
-- @param number tag 要查找的tag
-- @return node
-- end --
function seekNodeByTag(parent, tag)
if not parent then
return
end
if tag == parent:getTag() then
return parent
end
local findNode
local children = parent:getChildren()
local childCount = parent:getChildrenCount()
if childCount < 1 then
return
end
for i=1, childCount do
if "table" == type(children) then
parent = children[i]
elseif "userdata" == type(children) then
parent = children:objectAtIndex(i - 1)
end
if parent then
findNode = seekNodeByTag(parent, tag)
if findNode then
return findNode
end
end
end
return
end
-- start --
--------------------------------
-- 按name查找布局中的结点
-- @function seekNodeByName
-- @param node parent 要查找布局的结点
-- @param string name 要查找的name
-- @return node
-- end --
function seekNodeByName(parent, name)
if not parent then
return
end
if name == parent:getName() then
return parent
end
local findNode
local children = parent:getChildren()
local childCount = parent:getChildrenCount()
if childCount < 1 then
return
end
for i=1, childCount do
if "table" == type(children) then
parent = children[i]
elseif "userdata" == type(children) then
parent = children:objectAtIndex(i - 1)
end
if parent then
findNode = seekNodeByName(parent, name)
if findNode then
return findNode
end
end
end
return
end
-- start --
--------------------------------
-- 根据路径来查找布局中的结点
-- @function seekNodeByPath
-- @param node parent 要查找布局的结点
-- @param string path 要查找的path
-- @return node
-- end --
function seekNodeByPath(parent, path)
if not parent then
return
end
local names = string.split(path, '/')
for i,v in ipairs(names) do
parent = seekNodeByName(parent, v)
if not parent then
return
end
end
return parent
end
local sharedScheduler = cc.Director:getInstance():getScheduler()
-- start --
--------------------------------
-- 计划一个以指定时间间隔执行的全局事件回调,并返回该计划的句柄。
-- @function scheduleGlobal
-- @param function listener 回调函数
-- @param number interval 间隔时间
-- @return mixed#mixed ret (return value: mixed) schedule句柄
--[[--
计划一个以指定时间间隔执行的全局事件回调,并返回该计划的句柄。
~~~ lua
local function onInterval(dt)
end
-- 每 0.5 秒执行一次 onInterval()
local handle = scheduleGlobal(onInterval, 0.5)
~~~
]]
-- end --
function scheduleGlobal(listener, interval)
interval = interval or 0
return sharedScheduler:scheduleScriptFunc(listener, interval, false)
end
-- start --
--------------------------------
-- 取消一个全局计划
-- @function unscheduleGlobal
-- @param mixed schedule句柄
--[[--
取消一个全局计划
unscheduleGlobal() 的参数就是 scheduleGlobal() 的返回值。
]]
-- end --
function unscheduleGlobal(handle)
sharedScheduler:unscheduleScriptEntry(handle)
end
-- start --
--------------------------------
-- 计划一个全局延时回调,并返回该计划的句柄。
-- @function performWithDelayGlobal
-- @param function listener 回调函数
-- @param number time 延迟时间
-- @return mixed#mixed ret (return value: mixed) schedule句柄
--[[--
计划一个全局延时回调,并返回该计划的句柄。
performWithDelayGlobal() 会在等待指定时间后执行一次回调函数,然后自动取消该计划。
]]
-- end --
function performWithDelayGlobal(listener, time)
local handle
handle = sharedScheduler:scheduleScriptFunc(function()
gf:unscheduleGlobal(handle)
listener()
end, time, false)
return handle
end
-- 创建一个调度器
function schedule(node, callback, interval)
interval = interval or 0
local seq = cc.Sequence:create({
cc.DelayTime:create(interval),
cc.CallFunc:create(callback),
})
local action = cc.RepeatForever:create(seq)
node:runAction(action)
return action
end
-- 延时执行
function performWithDelay(node, callback, delay)
delay = delay or 0
local action = cc.Sequence:create({
cc.DelayTime:create(delay),
cc.CallFunc:create(callback),
})
node:runAction(action)
return action
end
-- 对齐
function align(node, size, relativeAlign)
local pos = cc.p(0, 0)
local anchor = cc.p(0, 0)
if relativeAlign == ccui.RelativeAlign.alignParentTopLeft then
-- 上左
pos = cc.p(0, size.height)
anchor = cc.p(0, 1)
elseif relativeAlign == ccui.RelativeAlign.alignParentTopCenterHorizontal then
-- 上中
pos = cc.p(size.width/2, size.height)
anchor = cc.p(0.5, 1)
elseif relativeAlign == ccui.RelativeAlign.alignParentTopRight then
-- 上右
pos = cc.p(size.width, size.height)
anchor = cc.p(1, 1)
elseif relativeAlign == ccui.RelativeAlign.alignParentLeftCenterVertical then
-- 中左
pos = cc.p(0, size.height/2)
anchor = cc.p(0, 0.5)
elseif relativeAlign == ccui.RelativeAlign.centerInParent then
-- 中
pos = cc.p(size.width/2, size.height/2)
anchor = cc.p(0.5, 0.5)
elseif relativeAlign == ccui.RelativeAlign.alignParentRightCenterVertical then
-- 中右
pos = cc.p(size.width, size.height/2)
anchor = cc.p(1, 0.5)
elseif relativeAlign == ccui.RelativeAlign.alignParentLeftBottom then
-- 下左(默认)
elseif relativeAlign == ccui.RelativeAlign.alignParentBottomCenterHorizontal then
-- 下中
pos = cc.p(size.width/2, 0)
anchor = cc.p(0.5, 0)
elseif relativeAlign == ccui.RelativeAlign.alignParentRightBottom then
-- 下右
pos = cc.p(size.width, 0)
anchor = cc.p(1, 0)
end
node:ignoreAnchorPointForPosition(false)
node:setAnchorPoint(anchor)
node:setPosition(pos)
end |
slot0 = class("BackYardThemeTemplateMsgBox", import("....base.BaseSubView"))
slot0.TYPE_TEXT = 1
slot0.TYPE_IMAGE = 2
slot0.getUIName = function (slot0)
return "BackYardThemeTemplateMsgBox"
end
slot0.OnLoaded = function (slot0)
slot0.frame = slot0:findTF("frame/window1")
slot0.content = slot0:findTF("frame/window1/content"):GetComponent(typeof(Text))
slot0.frame1 = slot0:findTF("frame/window2")
slot0.content1 = slot0:findTF("frame/window2/content"):GetComponent(typeof(Text))
slot0.icon = slot0:findTF("frame/window2/mask/icon"):GetComponent(typeof(RawImage))
slot0.cancelBtn = slot0:findTF("frame/btns/cancel")
slot0.cancelBtnTxt = slot0:findTF("frame/btns/cancel/Text"):GetComponent(typeof(Text))
slot0.confirmBtn = slot0:findTF("frame/btns/confirm")
slot0.confirmBtnTxt = slot0:findTF("frame/btns/confirm/Text"):GetComponent(typeof(Text))
end
slot0.OnInit = function (slot0)
onButton(slot0, slot0._tf, function ()
slot0:Hide()
end, SFX_PANEL)
onButton(slot0, slot0.cancelBtn, function ()
slot0:Hide()
if slot0.Hide.onCancel then
slot0.onCancel()
end
end, SFX_PANEL)
onButton(slot0, slot0.confirmBtn, function ()
slot0:Hide()
if slot0.Hide.onYes then
slot0.onYes()
end
end, SFX_PANEL)
end
slot0.SetUp = function (slot0, slot1)
slot0.onYes = slot1.onYes
slot0.onCancel = slot1.onCancel
slot0.cancelBtnTxt.text = slot1.cancelTxt or i18n("word_cancel")
slot0.confirmBtnTxt.text = slot1.confirmTxt or i18n("word_ok")
if (slot1.type or slot0.TYPE_TEXT) == slot0.TYPE_TEXT then
slot0.content.text = slot1.content
elseif slot2 == slot0.TYPE_IMAGE then
slot0.content1.text = slot1.content
BackYardThemeTempalteUtil.GetTexture(slot1.srpiteName, slot1.md5, function (slot0)
if not IsNil(slot0.icon) and slot0 then
slot0.icon.texture = slot0
end
end)
end
setActive(slot0.frame, slot2 == slot0.TYPE_TEXT)
setActive(slot0.frame1, slot2 == slot0.TYPE_IMAGE)
setActive(slot0.cancelBtn, not slot1.hideNo)
slot0.Show(slot0)
end
slot0.Show = function (slot0)
slot0.super.Show(slot0)
pg.UIMgr.GetInstance():BlurPanel(slot0._tf)
end
slot0.Hide = function (slot0)
slot0.icon.texture = nil
slot0.super.Hide(slot0)
pg.UIMgr.GetInstance():UnblurPanel(slot0._tf, slot0._parentTf)
end
slot0.OnDestroy = function (slot0)
slot0:Hide()
end
return slot0
|
local a = vim.api
_G.a = vim.api
tema = a.nvim_create_namespace("temazo")
a.nvim__theme_def(tema, "EndOfBuffer", {background=1234})
a.nvim__theme_def(tema, "Statement", {background=100000, foreground=1234})
function thema_provide(_, ns_id, name)
if name == "Identifier" then
return {foreground=255*256}
end
end
a.nvim__theme_set_provider(tema, thema_provide)
function raster_int(_, row, lastrow, size, win)
if win == 1001 then
a.nvim__theme_set(tema, true)
else
a.nvim__theme_set(0, true)
end
end
a.nvim__set_raster_interrupt(raster_int)
|
Background=Class()
local UPPER_BG_SCALE,LOWER_BG_SCALE=.3,.25
local BACKGROUND_WIDTH=gImages['good_world']:getWidth()*.5
local UPPER_BG_HEIGHT=gImages['good_world']:getHeight()*UPPER_BG_SCALE
local LOWER_BG_HEIGHT=gImages['good_world']:getHeight()*LOWER_BG_SCALE
local BACKGROUND_SCROLL=0
function Background:init()
self.upperBackground=gImages['bad_world']
self.lowerBackground=gImages['good_world']
self.tweenData={y=0,compensateY=0,sy=UPPER_BG_SCALE}
end
function Background:update(dt)
BACKGROUND_SCROLL=(BACKGROUND_SCROLL+BACKGROUND_SPEED*dt)%BACKGROUND_WIDTH
end
function Background:flip()
self.upperBackground,self.lowerBackground=
self.lowerBackground,self.upperBackground
if true then return end
if self.tweening then return end
self.tweening=true
flux.to(self.tweenData,1,{
y=UPPER_BG_HEIGHT
})
:ease('circinout')
:after(self.tweenData,.3,{
compensateY=LOWER_BG_HEIGHT,
sy=-LOWER_BG_SCALE
}):oncomplete(function()
self.tweening=false
self.tweenData={y=0,compensateY=0,sy=UPPER_BG_SCALE}
self.upperBackground,self.lowerBackground=
self.lowerBackground,self.upperBackground
end)
end
function Background:render()
--Tile the background 3 times!
for i=1,3 do
if self.tweening then
love.graphics.draw(
self.upperBackground,
-BACKGROUND_SCROLL+(i-1)*BACKGROUND_WIDTH,
self.tweenData.y+self.tweenData.compensateY,0,
.5,self.tweenData.sy
)
love.graphics.draw(
self.lowerBackground,
-BACKGROUND_SCROLL+(i-1)*BACKGROUND_WIDTH,
LOWER_BG_HEIGHT+self.tweenData.y+UPPER_BG_HEIGHT-2,0,
.5,-LOWER_BG_SCALE
)
love.graphics.draw(
self.lowerBackground,
-BACKGROUND_SCROLL+(i-1)*BACKGROUND_WIDTH,
self.tweenData.y-UPPER_BG_HEIGHT,0,
.5,UPPER_BG_SCALE
)
else
love.graphics.draw(
self.upperBackground,
-BACKGROUND_SCROLL+(i-1)*BACKGROUND_WIDTH,0,
0,
.5,UPPER_BG_SCALE
)
love.graphics.draw(
self.lowerBackground,
-BACKGROUND_SCROLL+(i-1)*BACKGROUND_WIDTH,
LOWER_BG_HEIGHT+UPPER_BG_HEIGHT-2,0,
.5,-LOWER_BG_SCALE
)
end
end
end
function Background:drawBackground(str,i)
end |
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
local spd, ent
function ENT:Initialize()
self:SetModel("models/Items/AR2_Grenade.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_NONE)
local phys = self:GetPhysicsObject()
if phys and phys:IsValid() then
phys:Wake()
end
self:GetPhysicsObject():SetBuoyancyRatio(0)
spd = physenv.GetPerformanceSettings()
spd.MaxVelocity = 2996
physenv.SetPerformanceSettings(spd) -- set grenade's max. speed to it's real life muzzle velocity
end
function ENT:Use(activator, caller)
return false
end
function ENT:OnRemove()
return false
end
function ENT:PhysicsCollide(data, physobj)
ent = data.HitEntity
//if IsValid(ent) and ent:Health() > 0 then
// ent:TakeDamage(30, self.Owner, self.Owner:GetActiveWeapon())
//end
self:EmitSound("weapons/smokegrenade/sg_explode.wav", 100, 100)
ParticleEffect("cstm_smoke", self:GetPos(), Angle(0, 0, 0), nil)
self:Remove()
end
|
module(..., package.seeall)
local native = require "tundra.native"
function apply(env, options)
-- load the generic C toolset first
tundra.unitgen.load_toolset("generic-cpp", env)
-- Also add assembly support.
tundra.unitgen.load_toolset("generic-asm", env)
local vbcc_root = assert(native.getenv("VBCC"), "VBCC environment variable must be set")
env:set_many {
["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".s", ".asm", ".a", ".o" },
["OBJECTSUFFIX"] = ".o",
["LIBPREFIX"] = "",
["LIBSUFFIX"] = ".a",
["VBCC_ROOT"] = vbcc_root,
["CC"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)",
["LIB"] = vbcc_root .. "$(SEP)bin$(SEP)vlink$(HOSTPROGSUFFIX)",
["LD"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)",
["ASM"] = vbcc_root .. "$(SEP)bin$(SEP)vasmm68k_mot$(HOSTPROGSUFFIX)",
["VBCC_SDK_INC"] = vbcc_root .. "$(SEP)include$(SEP)sdk",
["_OS_CCOPTS"] = "",
["_OS_CXXOPTS"] = "",
["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["ASMCOM"] = "$(ASM) -quiet -Fhunk -phxass $(ASMOPTS) $(ASMOPTS_$(CURRENT_VARIANT:u)) $(ASMDEFS:p-D) $(ASMINCPATH:f:p-I) -I$(VBCC_SDK_INC) -o $(@) $(<)",
["PROGOPTS"] = "",
["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) $(LIBS:p-l) -o $(@) $(<)",
["PROGPREFIX"] = "",
["LIBOPTS"] = "",
["LIBCOM"] = "$(LIB) @RESPONSE|@|-r $(LIBOPTS) -o $(@) $(<)",
["ASMINC_KEYWORDS"] = { "INCLUDE", "include" },
["ASMINC_BINARY_KEYWORDS"] = { "INCBIN", "incbin" },
}
end
|
TechBuilding = {
npc_trollsandelves_rock_1 = true
} --what is this doing here
if TrollsAndElvesGameMode == nil then
TrollsAndElvesGameMode = {}
TrollsAndElvesGameMode.__index = TrollsAndElvesGameMode
end
function TrollsAndElvesGameMode:new (o)
o = o or {}
setmetatable(o, self)
TROLLSANDELVES_REFERENCE = o
return o
end
--
-- Advance a player's progression through the tech tree, through updating their tech
-- table following the construction of a structure.
--
function TrollsAndElvesGameMode:TechAdvance(player, building)
-- this first section is just debug output
print(player:GetClassname())
print("Upgrading " .. building)
for k,v in pairs(player) do
if type(v) == "table" then
print(" "..k.." = {")
for k2,v2 in pairs(v) do
if type(v2) == "table" then
v2 = "table"
elseif type(v2) == "userdata" then
v2 = "userdata"
end
print(" "..tostring(k2).."="..tostring(v2))
end
print(" }")
elseif type(v) == "userdata" then
print(" "..k.."= userdata")
else
print(" "..k.."="..v)
end
end
-- here's the actual functional part - mark the building as constructed in the building table
player.TechBuildings[building] = true
if building == "npc_trollsandelves_rock_1" then
local buildmenu = player:GetAssignedHero():FindAbilityByName("trollsandelves_build_menu")
buildmenu:SetHidden(false)
buildmenu:SetLevel(1)
end
end
--
-- Game mode initialization boilerplate
--
function TrollsAndElvesGameMode:InitGameMode()
Msg("Hello World, My name is TrollsAndElves!")
GameRules:EnableCustomGameSetupAutoLaunch(false)
GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_GOODGUYS, 12)
GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_BADGUYS, 12)
--CEntities:FindByClassname(nil, "dota_base_game_mode"):SetFogOfWarDisabled(true)
--Event registration --
ListenToGameEvent('player_chat', Dynamic_Wrap(TrollsAndElvesGameMode,"onChatMessage"), self)
ListenToGameEvent('player_connect_full', Dynamic_Wrap(TrollsAndElvesGameMode,"onPlayerConnect"), self)
ListenToGameEvent("dota_item_purchased", Dynamic_Wrap(TrollsAndElvesGameMode, "OnItemPurchased"), self)
ListenToGameEvent('npc_spawned', Dynamic_Wrap(TrollsAndElvesGameMode, "onNPCSpawned"), self)
-- Start thinkers
--self._scriptBind:BeginThink('TrollsAndElvesThink', Dynamic_Wrap(TrollsAndElvesGameMode, 'Think'), 0.1)
end
--
-- Listen for changes in the current state
--
ListenToGameEvent('game_rules_state_change', function(keys)
-- Grab the current state
local state = GameRules:State_Get()
if state == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP then
for i=1,(PlayerResource:GetPlayerCount() or 1) do
local player = PlayerResource:GetPlayer(i)
PlayerResource:SetCustomTeamAssignment(i, DOTA_TEAM_GOODGUYS)
end
GameRules:LockCustomGameSetupTeamAssignment(true)
GameRules:GetGameModeEntity():SetCustomGameForceHero("npc_dota_hero_invoker")
GameRules:SetCustomGameSetupRemainingTime(1)
end
end, nil)
--
-- Handle a few events when units spawn
--
function TrollsAndElvesGameMode:onNPCSpawned(keys)
local spawnedUnit = EntIndexToHScript(self.entindex)
-- Track spawned heros in the playerid-unit mapping we keep locally
if spawnedUnit:IsRealHero() then
GameRules.ID_TO_HERO[spawnedUnit:GetPlayerID()] = spawnedUnit
end
-- debug spew when we spawn creeps
if spawnedUnit:GetClassname() ~= "npc_dota_creep" then
print(spawnedUnit:GetClassname())
end
-- Handle the trolls specially - we need to give them pre-levelled passive abilities
if spawnedUnit:GetClassname() == "npc_dota_hero_troll_warlord" or spawnedUnit:GetClassname() == "npc_dota_hero_lycan" then
print("Troll detected!")
local ability_1 = spawnedUnit:FindAbilityByName("trollsandelves_troll_invis")
local ability_2 = spawnedUnit:FindAbilityByName("trollsandelves_troll_pillage")
ability_1:SetLevel(1)
ability_2:SetLevel(1)
spawnedUnit:SetHullRadius(56)
end
-- Initialize the builders properly
if spawnedUnit:GetClassname() == "npc_dota_hero_invoker" then --yep capital I
EntityInit:NewByClassname(spawnedUnit:GetPlayerOwner(), "player")
EntityInit:NewByType(spawnedUnit, "Builder")
end
end
--
-- Handle when troll players buy items
--
function TrollsAndElvesGameMode:TrollBuyItem(player, item)
local itemdata = ItemsCustomKV[item]
local playergold = PlayerResource:GetGold(player:GetPlayerID())
local lumbercost = itemdata.LumberCost or 0
local itemcost = itemdata.ItemCost or 0
local playerid = player:GetPlayerID()
local hero = player:GetAssignedHero()
print(itemdata)
print(playergold)
print(player.LumberTotal)
print(itemdata.LumberCost)
print(itemdata.ItemCost)
if player.LumberTotal >= lumbercost and playergold >= itemcost then
PlayerResource:ModifyGold(playerid, -itemcost, false, 0)
player.LumberTotal = player.LumberTotal - lumbercost
FireGameEvent("trollsandelves_lumber", {pid=playerid, lumber=player.LumberTotal})
local item = CreateItem( item, hero, hero )
hero:AddItem(item)
else --ERROR PLEASE
if player.LumberTotal >= lumbercost then
ShowGenericPopupToPlayer(player, "#trollsandelves_error_purchase", "#trollsandelves_error_gold", "", "", DOTA_SHOWGENERICPOPUP_TINT_SCREEN)
else
ShowGenericPopupToPlayer(player, "#trollsandelves_error_purchase", "#trollsandelves_error_lumber", "", "", DOTA_SHOWGENERICPOPUP_TINT_SCREEN)
end
end
end
--
-- For future use (and debug use) for chat commands
--
function TrollsAndElvesGameMode:onChatMessage(keys)
end
--
-- This function is here to exploit a little trick - the server generally hibernates
-- as soon as it starts up, and then wakes up from hibernation as soon as the first
-- player connects. By hooking this, we can then set up the trees properly for the
-- game to start.
--
local treesinit = false
function TrollsAndElvesGameMode:onPlayerConnect(keys)
if treesinit == false then
for k,v in pairs(Entities:FindAllByClassname("ent_dota_tree")) do
local u = CreateUnitByName( "npc_tree_dummy", Vector(0,0,0), true, nil, nil, 2)
u:SetOrigin(v:GetOrigin())
u:AddNewModifier(v, nil, "modifier_phased", {duration = -1})
end
treesinit = true
end
end
--
-- Because we don't have a ModifyLumber function provided like ModifyGold, we need
-- to implement our own version.
--
function TrollsAndElvesGameMode:ModifyLumber(player, sum) --negative to reduce
local lumber = player.LumberTotal
if sum > player.LumberTotal then
player.LumberTotal = player.LumberTotal + sum
return true
else return false
end
end
--
-- We need to handle the purchase of items specially, because they now can cost lumber as well.
--
function TrollsAndElvesGameMode:OnItemPurchased(keys)
local item = ItemsCustomKV[item]
local player = EntIndexToHScript(PlayerResource:GetPlayer(keys.PlayerID))
if item.LumberCost and item.LumberCost > 0 then self:ModifyLumber(player, item.LumberCost) end
end
--
-- The Think function - called every game frame. Try to keep the work done in here down a bit.
--
--TODO: actually get this thing online
function TrollsAndElvesGameMode:Think()
-- Track game time, since the dt passed in to think is actually wall-clock time not simulation time.
local now = GameRules:GetGameTime()
if self.t0 == nil then
self.t0 = now
end
local dt = now - self.t0
self.t0 = now
end
function TrollsAndElvesGameMode.PlayerWantsToSpawn(cmdname, origin, unit)
end
--
-- Building construction code
--
function TrollsAndElvesGameMode.PlayerWantsToBuild(cmdname, building) --maybe add some stuff to do stuff here
print(building)
local player = Convars:GetCommandClient()
player:GetAssignedHero():FindAbilityByName("trollsandelves_construct_building"):SetHidden(false)
if UnitsCustomKV[building] then
player.WantsToBuild = building
else
print("This doesn't seem right")
FireGameEvent("dota_hud_error_message", {reason=0,message="Hello World!"})
end
print(player.WantsToBuild)
end
--
-- Add a building to the building queue for a unit, and handle the cost and checks associated with that.
--
function TrollsAndElvesGameMode.BuildingQueueUnit(cmdname, building, unit)
local unitdata = UnitsCustomKV[unit]
local lumbercost = unitdata.LumberCost
local goldcost = unitdata.GoldCost
local playerowner = Convars:GetCommandClient()
local currentlumber = playerowner.LumberTotal
local currentgold = PlayerResource:GetGold(playerowner:GetPlayerID())
local team = playerowner:GetTeam()
--findclearspace won't work, need to generate an emission point when the building is created
if currentlumber >= lumbercost and currentgold >= goldcost then
playerowner:ModifyGold(-goldcost, true, 0)
playerowner.LumberTotal = currentlumber - lumbercost
local unit = CreateUnitByName(unit, Vector(0,0,0), true, nil, nil, keys.caster:GetTeamNumber())
FindClearSpaceForUnit(unit, keys.caster:GetOrigin(), true)
end
end
function TrollsAndElvesGameMode.UnitSelected(keys)
end
--
-- Console commands - used for debug, in theory
--
Convars:RegisterCommand("tae_use_spell", TrollsAndElvesGameMode.PlayerWantsToSpawn, "Build thing", 0)
Convars:RegisterCommand("tae_building_queue_unit", TrollsAndElvesGameMode.BuildingQueueUnit, "Build thing", 0)
Convars:RegisterCommand("tae_wants_to_build", TrollsAndElvesGameMode.PlayerWantsToBuild, "Build thing", 0)
|
-- Available functions (from XLSFormater Class)
-- SetProgressCalcul1ValueForLua(int val)
-- SetProgressCalcul2ValueForLua(int val)
-- IsAppendOnCurrentExcelFile()
-- Fonction pour manipulation excel
-- first row and first col = 0
-- void OpenExcelApp(bool NewAppIfNot)
-- void OpenXlsFile(string fPath)
-- void SetActiveSheet(string name)
-- void AddSheet()
-- void RenameSheet(string name)
-- void AddCell(int col, int row, string value)
-- string GetCell(int col, int row)
-- void InsertColAfter(int col)
-- void InsertRowAfter(int row)
-- void SetSizeOfCol(int col, int size)
-- void SortRangeByOneColInOrder(int left, int right, int top, int bottom, int col1, bool alpha1)
-- void SortRangeByTwoColInOrder(int left, int right, int top, int bottom, int col1, bool alpha1, int col2, bool alpha2)
-- void SortRangeByThreeColInOrder(int left, int right, int top, int bottom, int col1, bool alpha1, int col2, bool alpha2, int col3, bool alpha3)
-- void Replace( int row, int col, string pattern1, string pattern2)
-- void SetRowColor(int row, int colorIndex)
-- void SetColColor(int col, int colorIndex)
-- void SetRangeColor(int left, int right, int top, int bottom, int colorIndex)
-- void GetColorIndexInNewExcelSheet(
-- // BorderWeight = {Hairline;Medium;Thick;Thin;None}
-- void SetRangeBordure(int left, int right, int top, int bottom, bool EdgeTop, bool EdgeBottom, bool EdgeLeft, bool EdgeRight, bool insideHoriz, bool insideVert, string BorderWeight)
-- void SetRowBordure(int row, bool EdgeTop, bool EdgeBottom, bool EdgeLeft, bool EdgeRight, bool insideHoriz, bool insideVert, string BorderWeight)
-- void SetColBordure(int col, bool EdgeTop, bool EdgeBottom, bool EdgeLeft, bool EdgeRight, bool insideHoriz, bool insideVert, string BorderWeight)
-- void AutoFitCols(int colStart, int colEnd)
-- void AutoFitRows(int rowStart, int rowEnd)
-- // VerticalAlignement = {AlignBottom;AlignCenter;AlignTop}
-- // HorizontalAlignement = {AlignRight;AlignLeft;AlignCenter}
-- void SetRangeAlignement(int left, int right, int top, int bottom, string VerticalAlignement, string HorizontalAlignement)
-- void SetRowsAlignement(int rowStart, int rowEnd, string VerticalAlignement, string HorizontalAlignement)
-- void SetColsAlignement((int colStart, int colEnd, string VerticalAlignement, string HorizontalAlignement)
function Init()
SetAuthor("Aiekick"); -- define the script authot ( will be added in file propriety )
SetSeparator(";"); -- define the separtor used in csv file
SetBufferForCurrentLine("curLine"); -- curLine will be filled with the current line
SetBufferForLastLine("lastLine"); -- lastLine will be filled with the last line
SetFunctionForEachLine("eachRow"); -- eachRow will be called after each row filling of current ilne
SetFunctionForEndFile("endFile"); -- endFile will be callaed at end of the current csv file
end
curLine = {}; -- Current Line
lastLine = {}; -- Last Line
function eachRow()
local row = GetCurrentRowIndex();
end
function endFile()
end
|
if SERVER then
AddCSLuaFile("dronesrewrite/main.lua")
end
include("dronesrewrite/main.lua") |
local FORMNAME = "epic_savegame_load"
-- playername -> id
local player_selections = {}
minetest.register_on_leaveplayer(function(player)
local playername = player:get_player_name()
player_selections[playername] = nil
end)
epic.form.epic_savegame_load = function(topic, playername)
local savegame = epic.savegame.load(playername)
local levels = savegame[topic] or {}
local list = ""
for name in pairs(levels) do
list = list .. minetest.formspec_escape(name) .. ","
end
local formspec = "size[8,8;]" ..
"label[0,0;Epic savegame load]" ..
"textlist[0,0.5;7.8,6.5;levelname;" .. list .. "]" ..
"button_exit[0.1,7.2;8,1;load;Load]"
minetest.show_formspec(playername,
FORMNAME .. ";" .. topic,
formspec
)
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
local parts = formname:split(";")
local name = parts[1]
if name ~= FORMNAME then
return
end
local topic = parts[2]
local playername = player:get_player_name()
if fields.load then
local savegame = epic.savegame.load(playername)
local levels = savegame[topic] or {}
local selected_level = player_selections[playername]
if not selected_level then
return true
end
local selected_pos = nil
local i = 1
for _, pos in pairs(levels) do
if selected_level == i then
selected_pos = pos
end
i = i + 1
end
if not selected_pos then
-- nothing selected
return true
end
local node = epic.get_node(selected_pos)
if node.name ~= "epic:save" then
-- save node disappeared
-- TODO: remove level from topic
return true
end
local meta = minetest.get_meta(selected_pos)
local target_pos = minetest.string_to_pos(meta:get_string("pos"))
if not target_pos then
-- no target position
return true
end
local destination_pos = epic.to_absolute_pos(selected_pos, target_pos)
node = epic.get_node(destination_pos)
if node.name == "epic:epic" then
-- execute epic on position
epic.start(playername, destination_pos)
else
-- teleport just above the position
player:set_pos(vector.add(destination_pos, {x=0, y=0.5, z=0}))
end
end
if fields.levelname then
local lvl_parts = fields.levelname:split(":")
if lvl_parts[1] == "CHG" then
local selected_level = tonumber(lvl_parts[2])
if not selected_level then
return true
end
player_selections[playername] = selected_level
end
end
end)
|
local QuestID = 9
local Quest = Quests[QuestID]
Quest.Texts = {
["Accepted"] = "Sammel 50 Pfandflaschen und gebe sie dem Obdachlosen!",
["Finished"] = "Kehre zum Obdachlosen zur\\ueck!"
}
for k,v in ipairs(Quest:getPeds(2)) do
addEventHandler("onElementClicked", v,
function(button, state, thePlayer)
if (button == "left") and (state == "down") then
if (getDistanceBetweenElements3D(v,thePlayer) < 5) then
local QuestState = thePlayer:isQuestActive(Quest)
if (QuestState and not(QuestState == "Finished")) then
if (thePlayer:getInventory():removeItem(Items[2], 50)) then
thePlayer:refreshInventory()
Quest:playerFinish(thePlayer)
else
thePlayer:showInfoBox("error", "Du besitzt zu wenig Pfandflaschen!")
end
end
end
end
end
)
end
Quest.playerReachedRequirements =
function(thePlayer, bOutput)
if ( thePlayer:isQuestFinished(Quests[8]) ) then
return true
end
return false
end
Quest.getTaskPosition =
function()
--Should return int, dim, x, y, z
return 0, 0, 1487.4013671875, -1699.23046875, 14.046875
end
Quest.onAccept =
function(thePlayer)
outputChatBox("Obdachloser: Oh Junge, Super!", thePlayer, 255,255,255)
return true
end
Quest.onResume =
function(thePlayer)
return true
end
Quest.onProgress =
function(thePlayer)
return true
end
Quest.onFinish =
function(thePlayer)
outputChatBox("Obdachloser: Danke, jetzt hol ich mir erstmal Sprunk!", thePlayer, 255,255,255)
return true
end
Quest.onAbort =
function(thePlayer)
local QuestState = thePlayer:isQuestActive(Quest)
if (QuestState and (QuestState == "Finished")) then
thePlayer:getInventory():addItem(Items[2], 50)
thePlayer:refreshInventory()
end
return true
end
--outputDebugString("Loaded Questscript: server/Classes/Quest/Scripts/"..tostring(QuestID)..".lua") |
local base = require 'hj212.client.handler.base'
local handler = base:subclass('hj212.client.handler.rdata_start')
function handler:process(request)
self:log('info', "Enable RData upload!")
self._client:set_rdata_enable(true)
return true
end
return handler
|
--!strict
local store = require(script.Parent.store)
type IStore<State, Dispatch> = store.IStore<State, Dispatch>
type IDispatch<Store> = store.IDispatch<Store>
export type IThunkAction<ReturnType, Store> = (store: Store) -> ReturnType
export type ThunkAction<ReturnType, State = any> = IThunkAction<ReturnType, ThunkfulStore<State>>
export type IThunkDispatch<Store> = <ReturnType>(
self: Store,
thunkAction: IThunkAction<ReturnType, Store>
) -> ReturnType
export type ThunkDispatch<State = any> = IDispatch<ThunkfulStore<State>> & IThunkDispatch<ThunkfulStore<State>>
export type ThunkfulStore<State = any> = IStore<State, ThunkDispatch<State>>
return nil
|
--[[ ============================================================ ]]--
--[[ | FIVEM ESX DELIVERY PLUGIN REMAKE BY AKKARIIN | ]]--
--[[ ============================================================ ]]--
Config = {}
-- Locales
Config.Locale = 'en'
-- Delivery Base Location
Config.Base = {
-- Blip coords
coords = {x = -314.0, y = -1035.21, z = 30.53},
-- Scooter mark
scooter = {x = -319.17, y = -1032.14, z = 30.53},
-- Van mark
van = {x = -323.17, y = -1030.63, z = 30.53},
-- Truck mark
truck = {x = -326.75, y = -1029.23, z = 30.53},
-- Return vehicle mark
retveh = {x = -271.3, y = -1009.66, z = 29.87},
-- Delete vehicle mark
deleter = {x = -338.26, y = -1023.18, z = 30.38},
-- Heading
heading = 245.0,
}
Config.DecorCode = 0
-- Min and max deliveries jobs
Config.Deliveries = {
min = 5,
max = 7,
}
-- The salary of jobs
Config.Rewards = {
scooter = 800,
van = 1000,
truck = 1500,
}
-- Vehicle model
Config.Models = {
scooter = 'faggio',
van = 'minivan', -- The original game vehicle
-- van = 's1', -- Chinese car Wuling hong guang S1
truck = 'mule3',
vehDoor = {
-- If this value is true, it will open the vehicle trunk when player remove the goods from the vehicle.
usingTrunkForVan = true, -- If you using original game vehicle, set this to false
usingTrunkForTruck = false,
},
}
-- Scale of the arrow, usually not modified it
Config.Scales = {
scooter = 0.6,
van = 3.0,
truck = 4.5,
}
-- Rental money of the vehicles
Config.Safe = {
scooter = 4000,
van = 6000,
truck = 8000,
}
-- Random parking locations
Config.ParkingSpawns = {
{x = -310.50, y = -1011.08, z = 30.39, h = 252.00},
{x = -309.35, y = -1008.24, z = 30.39, h = 251.15},
{x = -311.53, y = -1013.72, z = 30.39, h = 252.00},
{x = -305.17, y = -1013.04, z = 30.39, h = 70.78},
{x = -307.33, y = -1002.65, z = 30.39, h = 248.33},
{x = -322.99, y = -1000.16, z = 30.39, h = 73.11},
{x = -329.65, y = -1004.10, z = 30.39, h = 253.11},
{x = -324.65, y = -1006.08, z = 30.39, h = 69.82},
{x = -326.87, y = -1011.45, z = 30.39, h = 73.49},
}
-- Random delivery locations of scooter
-- Item1 = parking location, Item2 = Place goods location
Config.DeliveryLocationsScooter = {
{Item1 = {x = -153.19, y = -838.31, z = 30.12}, Item2 = {x = -143.85, y = -846.3, z = 30.6}},
{Item1 = {x = 37.72, y = -795.71, z = 30.93}, Item2 = {x = 44.94, y = -803.24, z = 31.52}},
{Item1 = {x = 111.7, y = -809.56, z = 30.71}, Item2 = {x = 102.19, y = -818.22, z = 31.35}},
{Item1 = {x = 132.61, y = -889.41, z = 29.71}, Item2 = {x = 121.25, y = -879.82, z = 31.12}},
{Item1 = {x = 54.41, y = -994.86, z = 28.7}, Item2 = {x = 43.89, y = -997.98, z = 29.34}},
{Item1 = {x = 54.41, y = -994.86, z = 28.7}, Item2 = {x = 57.65, y = -1003.72, z = 29.36}},
{Item1 = {x = 142.87, y = -1026.78, z = 28.67}, Item2 = {x = 135.44, y = -1031.19, z = 29.35}},
{Item1 = {x = 248.03, y = -1005.49, z = 28.61}, Item2 = {x = 254.83, y = -1013.25, z = 29.27}},
{Item1 = {x = 275.68, y = -929.64, z = 28.47}, Item2 = {x = 285.55, y = -937.26, z = 29.39}},
{Item1 = {x = 294.29, y = -877.33, z = 28.61}, Item2 = {x = 301.12, y = -883.47, z = 29.28}},
{Item1 = {x = 247.68, y = -832.03, z = 29.16}, Item2 = {x = 258.66, y = -830.44, z = 29.58}},
{Item1 = {x = 227.21, y = -705.26, z = 35.07}, Item2 = {x = 232.2, y = -714.55, z = 35.78}},
{Item1 = {x = 241.06, y = -667.74, z = 37.44}, Item2 = {x = 245.5, y = -677.7, z = 37.75}},
{Item1 = {x = 257.05, y = -628.21, z = 40.59}, Item2 = {x = 268.54, y = -640.44, z = 42.02}},
{Item1 = {x = 211.33, y = -605.63, z = 41.42}, Item2 = {x = 222.32, y = -596.71, z = 43.87}},
{Item1 = {x = 126.27, y = -555.46, z = 42.66}, Item2 = {x = 168.11, y = -567.17, z = 43.87}},
{Item1 = {x = 254.2, y = -377.17, z = 43.96}, Item2 = {x = 239.06, y = -409.27, z = 47.92}},
{Item1 = {x = 244.49, y = 349.05, z = 105.46}, Item2 = {x = 252.86, y = 357.13, z = 105.53}},
{Item1 = {x = 130.77, y = -307.27, z = 44.58}, Item2 = {x = 138.67, y = -285.45, z = 50.45}},
{Item1 = {x = 54.44, y = -280.4, z = 46.9}, Item2 = {x = 61.86, y = -260.86, z = 52.35}},
{Item1 = {x = 55.15, y = -225.54, z = 50.44}, Item2 = {x = 76.29, y = -233.15, z = 51.4}},
{Item1 = {x = 44.6, y = -138.99, z = 54.66}, Item2 = {x = 50.78, y = -136.23, z = 55.2}},
{Item1 = {x = 32.51, y = -162.61, z = 54.86}, Item2 = {x = 26.84, y = -168.84, z = 55.54}},
{Item1 = {x = -29.6, y = -110.84, z = 56.51}, Item2 = {x = -23.5, y = -106.74, z = 57.04}},
{Item1 = {x = -96.86, y = -86.84, z = 57.44}, Item2 = {x = -87.82, y = -83.55, z = 57.82}},
{Item1 = {x = -146.26, y = -71.46, z = 53.9}, Item2 = {x = -132.92, y = -69.02, z = 55.42}},
{Item1 = {x = -238.41, y = 91.97, z = 68.11}, Item2 = {x = -263.61, y = 98.88, z = 69.3}},
{Item1 = {x = -251.45, y = 20.43, z = 53.9}, Item2 = {x = -273.35, y = 28.21, z = 54.75}},
{Item1 = {x = -322.4, y = -10.06, z = 47.42}, Item2 = {x = -315.48, y = -3.76, z = 48.2}},
{Item1 = {x = -431.22, y = 14.6, z = 45.5}, Item2 = {x = -424.83, y = 21.74, z = 46.27}},
{Item1 = {x = -497.33, y = -8.38, z = 44.33}, Item2 = {x = -500.95, y = -18.65, z = 45.13}},
{Item1 = {x = -406.69, y = -44.87, z = 45.13}, Item2 = {x = -429.07, y = -24.12, z = 46.23}},
{Item1 = {x = -433.94, y = -76.33, z = 40.93}, Item2 = {x = -437.89, y = -66.91, z = 43}},
{Item1 = {x = -583.22, y = -154.84, z = 37.51}, Item2 = {x = -582.8, y = -146.8, z = 38.23}},
{Item1 = {x = -613.68, y = -213.46, z = 36.51}, Item2 = {x = -622.23, y = -210.97, z = 37.33}},
{Item1 = {x = -582.44, y = -322.69, z = 34.33}, Item2 = {x = -583.02, y = -330.38, z = 34.97}},
{Item1 = {x = -658.25, y = -329, z = 34.2}, Item2 = {x = -666.69, y = -329.06, z = 35.2}},
{Item1 = {x = -645.84, y = -419.67, z = 34.1}, Item2 = {x = -654.84, y = -414.21, z = 35.45}},
{Item1 = {x = -712.7, y = -668.08, z = 29.81}, Item2 = {x = -714.58, y = -675.37, z = 30.63}},
{Item1 = {x = -648.24, y = -681.53, z = 30.61}, Item2 = {x = -656.77, y = -678.12, z = 31.46}},
{Item1 = {x = -648.87, y = -904.3, z = 23.8}, Item2 = {x = -660.88, y = -900.72, z = 24.61}},
{Item1 = {x = -529.01, y = -848.03, z = 29.26}, Item2 = {x = -531.0, y = -854.04, z = 29.79}},
}
-- Random delivery locations of van
Config.DeliveryLocationsVan = {
{Item1 = {x = -51.95, y = -1761.67, z = 28.89}, Item2 = {x = -41.15, y = -1751.66, z = 29.42}},
{Item1 = {x = 369.38, y = 317.44, z = 103.21}, Item2 = {x = 375.08, y = 333.65, z = 103.57}},
{Item1 = {x = -702.38, y = -920.38, z = 18.8}, Item2 = {x = -705.7, y = -905.46, z = 19.22}},
{Item1 = {x = -1225.49, y = -893.3, z = 12.13}, Item2 = {x = -1223.77, y = -912.26, z = 12.33}},
{Item1 = {x = -1506.82, y = -383.06, z = 40.64}, Item2 = {x = -1482.29, y = -378.95, z = 40.16}},
{Item1 = {x = 1149.13, y = -985.08, z = 45.64}, Item2 = {x = 1131.86, y = -979.32, z = 46.42}},
{Item1 = {x = 1157.19, y = -331.77, z = 68.64}, Item2 = {x = 1163.79, y = -314.6, z = 69.21}},
{Item1 = {x = -1145.42, y = -1590.97, z = 4.06}, Item2 = {x = -1150.31, y = -1601.7, z = 4.39}},
{Item1 = {x = 48.18, y = -992.62, z = 29.03}, Item2 = {x = 38.41, y = -1005.3, z = 29.48}},
{Item1 = {x = 370.05, y = -1036.4, z = 28.99}, Item2 = {x = 376.7, y = -1028.82, z = 29.34}},
{Item1 = {x = 785.95, y = -761.67, z = 26.33}, Item2 = {x = 797.0, y = -757.31, z = 26.89}},
{Item1 = {x = 41.53, y = -138.21, z = 55.08}, Item2 = {x = 50.96, y = -135.49, z = 55.2}},
{Item1 = {x = 106.8, y = 304.21, z = 109.81}, Item2 = {x = 90.86, y = 298.51, z = 110.21}},
{Item1 = {x = -565.73, y = 268.54, z = 82.55}, Item2 = {x = -562.25, y = 283.98, z = 82.18}},
}
-- Random delivery locations of truck
Config.DeliveryLocationsTruck = {
{Item1 = {x = -1395.82, y = -653.76, z = 28.91}, Item2 = {x = -1413.43, y = -635.47, z = 28.67}},
{Item1 = {x = 164.18, y = -1280.21, z = 29.38}, Item2 = {x = 136.5, y = -1278.69, z = 29.36}},
{Item1 = {x = 75.71, y = 164.41, z = 104.93}, Item2 = {x = 78.55, y = 180.44, z = 104.63}},
{Item1 = {x = -226.62, y = 308.87, z = 92.4}, Item2 = {x = -229.54, y = 293.59, z = 92.19}},
{Item1 = {x = -365.87, y = 297.27, z = 85.04}, Item2 = {x = -370.5, y = 277.98, z = 86.42}},
{Item1 = {x = -403.95, y = 196.11, z = 82.67}, Item2 = {x = -395.17, y = 208.6, z = 83.59}},
{Item1 = {x = -412.26, y = 297.95, z = 83.46}, Item2 = {x = -427.08, y = 294.19, z = 83.23}},
{Item1 = {x = -606.23, y = -901.52, z = 25.39}, Item2 = {x = -592.48, y = -892.76, z = 25.93}},
{Item1 = {x = -837.03, y = -1142.46, z = 7.44}, Item2 = {x = -841.89, y = -1127.91, z = 6.97}},
{Item1 = {x = -1061.56, y = -1382.19, z = 5.44}, Item2 = {x = -1039.38, y = -1396.88, z = 5.55}},
{Item1 = {x = 156.41, y = -1651.21, z = 29.53}, Item2 = {x = 169.11, y = -1633.38, z = 29.29}},
{Item1 = {x = 168.13, y = -1470.07, z = 29.37}, Item2 = {x = 175.78, y = -1461.16, z = 29.24}},
{Item1 = {x = 118.99, y = -1486.21, z = 29.38}, Item2 = {x = 143.54, y = -1481.18, z = 29.36}},
{Item1 = {x = -548.34, y = 308.19, z = 83.34}, Item2 = {x = -546.6, y = 291.46, z = 83.02}},
}
-- Player outfit of scooter
Config.OutfitScooter = {
[1] = {drawables = 0, texture = 0},
[3] = {drawables = 66, texture = 0},
[4] = {drawables = 97, texture = 3},
[5] = {drawables = 0, texture = 0},
[6] = {drawables = 32, texture = 14},
[7] = {drawables = 0, texture = 0},
[8] = {drawables = 15, texture = 0},
[9] = {drawables = 0, texture = 0},
[11] = {drawables = 184, texture = 0},
[12] = {drawables = 18, texture = 5},
[13] = {drawables = 1280, texture = 2},
}
-- Player outfit of scooter (female)
Config.OutfitScooterF = {
[1] = {drawables = 0, texture = 0},
[3] = {drawables = 9, texture = 0},
[4] = {drawables = 11, texture = 3},
[5] = {drawables = 0, texture = 0},
[6] = {drawables = 11, texture = 2},
[7] = {drawables = 0, texture = 0},
[8] = {drawables = 13, texture = 0},
[9] = {drawables = 0, texture = 0},
[11] = {drawables = 295, texture = 0},
[12] = {drawables = 18, texture = 5},
[13] = {drawables = 1280, texture = 2},
}
-- Player outfit of van and truck
Config.OutfitVan = {
[1] = {drawables = 0, texture = 0},
[3] = {drawables = 66, texture = 0},
[4] = {drawables = 97, texture = 3},
[5] = {drawables = 0, texture = 0},
[6] = {drawables = 32, texture = 14},
[7] = {drawables = 0, texture = 0},
[8] = {drawables = 141, texture = 0},
[9] = {drawables = 0, texture = 0},
[11] = {drawables = 230, texture = 3},
[12] = {drawables = 45, texture = 7},
[13] = {drawables = 1280, texture = 2},
}
-- Player outfit of van and truck (female)
Config.OutfitVanF = {
[1] = {drawables = 0, texture = 0},
[3] = {drawables = 14, texture = 0},
[4] = {drawables = 45, texture = 1},
[5] = {drawables = 0, texture = 0},
[6] = {drawables = 27, texture = 0},
[7] = {drawables = 0, texture = 0},
[8] = {drawables = 14, texture = 0},
[9] = {drawables = 0, texture = 0},
[11] = {drawables = 14, texture = 3},
[12] = {drawables = 18, texture = 7},
[13] = {drawables = 1280, texture = 2},
}
-- Random van goods
Config.VanGoodsPropNames = {
"prop_crate_11e",
"prop_cardbordbox_02a",
}
|
require('gitsigns').setup {
-- signs config
current_line_blame = true,
current_line_blame_opts = {
virt_text_pos = 'right_align'
}
}
|
term.clear()
term.setCursorPos(1,1)
io.write("Welcome to ruiz's quarry program!")
term.setCursorPos(1,2)
width = 10
tmpWidth = width
term.setCursorPos(1,3)
height = 3
coords = {gps.locate()}
posX = coords[1]
tmpPosX = posX
posY = coords[2]
posZ = coords[3]
tmpPosZ = posZ
facing = 1
valuables = {"minecraft:gold_ore","minecraft:nether_quartz","minecraft:lapis_lazuli","minecraft:coal","minecraft:iron_ore","minecraft:redstone","minecraft:coal_block","computercraft:disk_expanded","minecraft:diamond","minecraft:obsidian"}
function updateOrientation()
--posX vertice is the one its facing on start--
if facing == 1 and tmpPosX >= tmpWidth then
facing = 2
tmpPosX = 0
turtle.turnRight()
elseif facing == 2 and tmpPosZ >= tmpWidth then
facing = 3
tmpPosZ = 0
turtle.turnRight()
elseif facing == 3 and tmpPosX >= tmpWidth then
facing = 4
tmpPosX = 0
turtle.turnRight()
elseif facing == 4 and tmpPosZ >= tmpWidth - 1 then
facing = 1
tmpPosZ = 0
tmpPosX = 0
tmpWidth = tmpWidth - 1
turtle.turnRight()
end
end
function moveCheck()
if turtle.detect() == true then
turtle.dig()
end
turtle.forward()
end
function updatePos()
moveCheck()
if facing == 1 then
tmpPosX = tmpPosX + 1
posX = posX + 1
elseif facing == 2 then
tmpPosZ = tmpPosZ + 1
posZ = posZ + 1
elseif facing == 3 then
tmpPosX = tmpPosX + 1
posX = posX - 1
elseif facing == 4 then
tmpPosZ = tmpPosZ + 1
posZ = posZ - 1
end
coords[1] = posX
coords[3] = posZ
updateOrientation()
end
function checkLayer()
if tmpWidth <= 1 and ((posX == 0 and posZ == 0) or (posX == width and posZ == 0) or (posX == 0 and posZ == width) or (posX == width and posZ == width)) then
if height > 0 then
turtle.digDown()
turtle.down()
end
tmpWidth = width
height = height - 1
coords[2] = posY
dumpGarbage()
end
end
function dumpGarbage()
turtle.select(1)
for slot = 1,16 do
if turtle.getItemDetail(slot) then
isValuable = false
for key, value in pairs(turtle.getItemDetail(slot)) do
if key == "name" then
for key2, value2 in pairs(valuables) do
if value == value2 then
isValuable = true
end
end
if isValuable == false then
turtle.select(slot)
turtle.drop()
end
end
end
end
end
end
function quarry()
if turtle.getFuelLevel() < 2 then
turtle.refuel()
end
updatePos()
checkLayer()
end
function reproduce()
--Plant more turtles from inv
end
while height >= 0 do
quarry()
print("")
io.write("PosX: ")
io.write(posX)
print("")
io.write("tmpPosX: ")
io.write(tmpPosX)
print("")
io.write("tmpWidth: ")
io.write(tmpWidth)
end |
--[[ Lua code. See documentation: https://api.tabletopsimulator.com/ --]]
-- #include ambulator
local target = 'http://localhost:3000'
local numTries = 0
local waitSeconds = { 5, 10 }
function tryGetScript()
WebRequest.get(target .. '/ambulator', handleResult)
end
function handleResult(data)
if data.is_error == true and numTries < 2 then
numTries = numTries + 1
print('Could not load ambulator...trying again in ' .. waitSeconds[numTries] .. ' seconds')
Wait.time(tryGetScript, waitSeconds[numTries])
elseif numTries >= 2 then
print('Something went wrong - please try reloading ambulator')
else
-- print('WELL Loaded ' .. data.text)
-- print(data)
spawnObjectJSON({
json = data.text
})
end
end
--[[ The onLoad event is called after the game save finishes loading. --]]
function onLoad()
tryGetScript()
end
--[[ The onUpdate event is called once per frame. --]]
function onUpdate()
--[[ print('onUpdate loop!') --]]
end
|
-- Copyright: 2015-2020, Björn Ståhl
-- License: 3-Clause BSD
-- Reference: http://durden.arcan-fe.com
-- Description: Main setup for the Arcan/Durden desktop environment
-- Global used to track input events that should be aligned to clock
-- tick for rate-limit and timing purposes
EVENT_SYNCH = {};
local update_default_font, update_connection_path;
local load_configure_mouse;
local setup_external_connection;
local conn_log, conn_fmt;
local argv_cmds = {};
-- track custom buttons that should be added to each window
local tbar_btns = {
};
-- count initial delay before idle shutdown
local ievcount = 0;
-- replace the normal assert function one that can provide a traceback
local oldass = assert;
function assert(...)
oldass(..., debug.traceback("assertion failed", 2));
end
function durden(argv)
rendertarget_reconfigure(WORLDID, 38.4, 38.4);
system_load("builtin/mouse.lua")(); -- mouse gestures (in distribution)
system_load("suppl.lua")(); -- convenience functions
system_load("gconf.lua")(); -- configuration management
system_load("listen.lua")(); -- rate-limiting for external connection points
system_load("icon.lua")(); -- generate and manage user icons
system_load("shdrmgmt.lua")(); -- shader format parser, builder
system_load("uiprim/uiprim.lua")(); -- ui primitives
system_load("menu.lua")(); -- menu subsystem
system_load("timer.lua")(); -- timers, will hook clock_pulse
system_load("notification.lua")(); -- queue of message+descriptions
CLIPBOARD = system_load("clipboard.lua")(); -- clipboard filtering / mgmt
CLIPBOARD:load("clipboard_data.lua");
update_default_font();
system_load("dispatch.lua")(); -- UI keyboard routing / management
system_load("tiler.lua")(); -- window management
system_load("uimap.lua")(); -- map uiprim/* to tiler etc.
system_load("menus/menus.lua")(); -- root of menu virtual filesystem
system_load("input/devstate.lua")(); -- device detection, repeat rate, ..
system_load("ledm.lua")(); -- led controllers
system_load("display.lua")(); -- multidisplay management
system_load("ipc.lua")(); -- status and command channels
system_load("extevh.lua")(); -- handlers for external events
kbd_repeat(0, 0);
-- if we don't have a keyboard or any other input devices available here
-- there should be some kind of user interface to indicate that
SYMTABLE = system_load("builtin/keyboard.lua")();
SYMTABLE:load_translation();
SYMTABLE:load_keymap("default.lua");
load_configure_mouse();
-- display manager will invoke the callback (tiler_create from tiler.lua)
-- expected methods in the returned structure:
-- set_rendertarget(on or off)
-- activate(), deactivate()
-- tick()
-- resize(w, h, force)
--
-- (currently expected but to be refactored)
-- empty_space(ind)
-- update_scalef(factor, disptbl)
-- set_background()
local nt = display_manager_init(
function(ddisp)
local res = tiler_create(ddisp.w, ddisp.h,
{
scalef = ddisp.ppcm / 38.4,
disptbl = {ppcm = ddisp.ppcm, width = ddisp.w, h = ddisp.h},
sbar_custom = gconfig_statusbar_buttons
}
);
-- default click actions
res.name = ddisp.name;
res.buttons = gconfig_buttons;
res.status_lclick = function() dispatch_symbol("/global"); end
res.status_rclick = function() dispatch_symbol("/target"); end
return res;
end);
-- buttons with the set that is loaded / stored in gconf.lua
nt.buttons = gconfig_buttons;
conn_log, conn_fmt = suppl_add_logfn("connection");
-- tools are quick 'drop-ins' to get additional features like modelviewer
suppl_scan_tools();
suppl_scan_widgets();
-- add hooks for changes to all default font properties
gconfig_listen("font_def", "deffonth", update_default_font);
gconfig_listen("font_sz", "deffonth", update_default_font);
gconfig_listen("font_hint", "font_hint", update_default_font);
gconfig_listen("font_fb", "font_fb", update_default_font);
gconfig_listen("lbar_tpad", "padupd", update_default_font);
gconfig_listen("lbar_bpad", "padupd", update_default_font);
gconfig_listen("extcon_path", "pathupd", update_connection_path);
audio_gain(BADID, gconfig_get("global_gain"));
-- load saved keybindings
dispatch_load(durden_lock_toggle);
iostatem_init();
for i,v in ipairs(argv) do
if (argv_cmds[v]) then
argv_cmds[v]();
end
end
-- process user- configuration commands
local cmd = system_load("autorun.lua", 0);
if (type(cmd) == "function") then
cmd();
end
if (gconfig_get("mouse_block")) then
mouse_block();
end
-- init script, force-write to db
if (gconfig_get("first_run")) then
gconfig_set("first_run", false, true);
system_load("firstrun.lua")();
end
-- for dealing wtih crash recovery windows or saved layout/role-
timer_add_periodic("recover_layout_save", 100, false,
function()
for wnd in all_windows(nil, true) do
if (wnd.config_dirty) then
wnd.config_dirty = nil;
store_key("durden_temp_" .. wnd.config_tgt, image_tracetag(wnd.external));
end
end
end, true);
-- this is forwarded as a global between executions if the crash recovery is
-- made, and contains a user contribution through the fatal handler, as well as
-- a backtrace
if (CRASH_SOURCE and string.len(CRASH_SOURCE) > 0) then
notification_add(
"Durden", nil, "Crash", CRASH_SOURCE, 4);
end
setup_external_connection();
end
argv_cmds["input_lock"] = function()
dispatch_symbol("input_lock_on");
end
argv_cmds["safety_timer"] = function()
timer_add_idle("Safety Shutdown",
1000, true, function()
if (ievcount < 1) then
return shutdown("no device input");
end
end
);
end
update_connection_path = function(key, val)
if (val == ":disabled") then
val = "";
else
setup_external_connection()
end
for tiler in all_tilers_iter() do
for i, wnd in ipairs(tiler.windows) do
durden_devicehint(wnd.external);
end
end
end
local last_extcon;
setup_external_connection = function()
-- can happen if the connection point config entry is changed
if last_extcon then
listen_cancel(last_extcon);
last_extcon = nil;
end
-- no-op
local path = gconfig_get("extcon_path");
if (path == ":disabled") then
return;
end
last_extcon = path;
listen_ratelimit(path,
-- eval
function()
local count = 0;
local wnd_lim = gconfig_get("extcon_wndlimit")
if wnd_lim <= 0 then
conn_log("eval=ok:no_limit");
return true;
end
-- count all externally tagged windows, this does not cover subsegments,
-- though most implementations impose other limits (e.g. only one popup)
for wnd in all_windows(nil, true) do
if wnd.external_connection then
count = count + 1;
end
end
if count < wnd_lim then
conn_log(conn_fmt("eval=ok:wnd_count=%d:total=%d", count, wnd_lim));
return true;
else
conn_log(conn_fmt("eval=fail:wnd_count=%d:total=%d", count, wnd_lim));
return false;
end
end,
-- handler
function(source, status, ...)
local ap = active_display(true);
if ap ~= nil then
rendertarget_attach(ap, source, RENDERTARGET_DETACH);
end
-- this will update the event handler to wait for the register event
-- and switch to the proper type and handler when that is known
local wnd = durden_launch(source, "", "external", nil, wargs);
wnd.external_connection = true;
if not wnd then
delete_image(source)
return
end
-- tell the client to just reconnect on crash to the last one we knew
durden_devicehint(source);
-- enable external- connection specific flags, others have a path on
-- launch (e.g. menus/global/open.lua)
if gconfig_get("gamma_access") == "all" then
target_flags(source, TARGET_ALLOWCM, true)
end
end,
-- grace period
gconfig_get("extcon_startdelay"),
gconfig_get("extcon_rlimit")
);
end
load_configure_mouse = function()
-- needed when we run in nested settings as mouse scale won't match
-- device input from external window manager
if (gconfig_get("mouse_hardlock")) then
toggle_mouse_grab(MOUSE_GRABON);
end
-- safe-load that first uses configured set, fallback to default,
-- and fail-safe with a green box cursor
local load_cursor;
load_cursor = function(name, set)
local vid = load_image(string.format("cursor/%s/%s.png", set, name));
if (not valid_vid(vid)) then
if (set ~= "default") then
return load_cursor(name, "default", 0, 0);
else
warning("cursor set broken, couldn't load " .. name);
vid = fill_surface(8, 8, 0, 255, 0);
end
end
return vid;
end
-- ideally we should switch this over to use the same icon setup and configuration
-- as the normal icon controls now that they exist, should give SDF resampling etc.
-- for a cheaper price and not use terrible scaling in mixed-DPI
local set = gconfig_get("mouse_cursorset");
-- 65531..5 is a hidden max_image_order range (for cursors, overlays..)
mouse_setup(load_cursor("default", set), 65535, 1, true, false);
-- preload cursor states
mouse_add_cursor("drag", load_cursor("drag", set), 0, 0); -- 7, 5
mouse_add_cursor("grabhint", load_cursor("grabhint", set), 0, 0); --, 7, 10);
mouse_add_cursor("rz_diag_l", load_cursor("rz_diag_l", set), 0, 0); --, 6, 5);
mouse_add_cursor("rz_diag_r", load_cursor("rz_diag_r", set), 0, 0); -- , 6, 6);
mouse_add_cursor("rz_down", load_cursor("rz_down", set), 0, 0); -- 5, 13);
mouse_add_cursor("rz_left", load_cursor("rz_left", set), 0, 0); -- 0, 5);
mouse_add_cursor("rz_right", load_cursor("rz_right", set), 0, 0); -- 13, 5);
mouse_add_cursor("rz_up", load_cursor("rz_up", set), 0, 0); -- 5, 0);
switch_default_texfilter(FILTER_NONE);
if (gconfig_get("mouse_block")) then
mouse_block();
end
mouse_reveal_hook(gconfig_get("mouse_reveal"));
end
update_default_font = function(key, val)
local font = (key and key == "font_def") and val or gconfig_get("font_def");
local sz = (key and key == "font_sz") and val or gconfig_get("font_sz");
local hint = (key and key == "font_hint") and val or gconfig_get("font_hint");
local fbf = (key and key == "font_fb") and val or gconfig_get("font_fb");
system_defaultfont(font, sz, hint);
-- with the default font reset, also load a fallback one
if (fbf and resource(fbf, SYS_FONT_RESOURCE)) then
system_defaultfont(fbf, sz, hint, 1);
end
-- centering vertically on fonth will look poor on fonts that has a
-- pronounced ascent / descent and with scale factors etc. it is a lot of tedium
-- to try and probe the metrics. Go with user-definable top and bottom padding.
local vid, lines, w, fonth, asc = render_text("\\f,0\\#ffffff gijy1!`");
local rfh = fonth;
local props = image_surface_properties(vid);
delete_image(vid);
gconfig_set("sbar_sz", fonth + gconfig_get("sbar_tpad") + gconfig_get("sbar_bpad"));
gconfig_set("tbar_sz", fonth + gconfig_get("tbar_tpad") + gconfig_get("tbar_bpad"));
gconfig_set("lbar_sz", fonth + gconfig_get("lbar_tpad") + gconfig_get("lbar_bpad"));
gconfig_set("lbar_caret_h", fonth);
if (not all_tilers_iter) then
return;
end
for disp in all_tilers_iter() do
disp:update_scalef(disp.scalef);
end
-- also propagate to each window so that it may push descriptors and
-- size information to any external connections
for wnd in all_windows() do
wnd:update_font(sz, hint, font);
wnd:set_title();
wnd:resize(wnd.width, wnd.height);
end
end
-- need these event handlers here since it ties together modules that should
-- be separated code-wise, as we want tiler- and other modules to be reusable
-- in less complex projects
local function tile_changed(wnd, neww, newh, efw, efh)
if (not neww or not newh or wnd.block_rz_hint) then
return;
end
if (neww <= 0 or newh <= 0) then
return;
end
if (not valid_vid(wnd.external, TYPE_FRAMESERVER)) then
return;
end
local props = image_storage_properties(wnd.external);
-- edge cases where we want the client to ignore actual sizing
if (wnd.displayhint_block_wh) then
efw = props.width;
efh = props.height;
end
-- in this mode, just tell the client what the size of the area actually is
-- we really want different behavior for drag here as well, but that's
-- something to fix in the float-mode enhancement stage
if (wnd.scalemode == "client") then
efw = wnd.max_w - wnd.pad_left - wnd.pad_right;
efh = wnd.max_h - wnd.pad_top - wnd.pad_bottom;
end
if (wnd.block_rz_hint) then
return;
end
-- ignore resize- step limit (terminal) if we are not in drag resize
if (not mouse_state().drag or not wnd.sz_delta or
(math.abs(props.width - efw) > wnd.sz_delta[1] or
math.abs(props.height - efh) > wnd.sz_delta[2])) then
-- cache what we actually send
wnd:displayhint(efw+wnd.dh_pad_w, efh+wnd.dh_pad_h, wnd.dispmask);
end
end
--
-- triggered by meta- state tracker, we need the hook here to also trigger
-- mouse locking and update border states
--
function durden_lock_toggle(newst, state)
if ((not active_display().selected and
not active_display().lock_override) and newst) then
dispatch_toggle(false);
return;
end
for i in all_tilers_iter() do
i.sbar_ws["msg"]:switch_state(newst and "locked" or "active");
end
end
-- there is a ton of "per window" input state when it comes to everything from
-- active translation tables, to diacretic traversals, to repeat-rate and
-- active analog/digital devices.
local function sel_input(wnd)
local cnt = 0;
SYMTABLE:translation_overlay(wnd.u8_translation);
iostatem_restore(wnd.iostatem);
end
local function desel_input(wnd)
SYMTABLE:translation_overlay({});
wnd.iostatem = iostatem_save();
end
-- separated from launch etc. as we don't want it for subwindows,
-- and later this provides a decent entrypoint for load-balancing
function durden_devicehint(vid)
if (valid_vid(vid, TYPE_FRAMESERVER) and
gconfig_get("extcon_path") ~= ":disabled") then
target_devicehint(vid, gconfig_get("extcon_path"));
end
end
function durden_launch(vid, prefix, title, wnd, wargs)
if (not valid_vid(vid)) then
conn_log("broken_launch:reason=invalid_vid");
return;
end
if (not wnd) then
wnd = active_display():add_hidden_window(vid, wargs);
if (not wnd) then
delete_image(vid);
return;
end
end
-- hidden window creation failed or event during creation triggered
-- destruction immediately, hence the table will be empty
if (not wnd.set_prefix) then
conn_log("broken_launch:reason=wnd_creation");
delete_image(vid);
return;
end
-- window aesthetics
wnd:set_prefix(prefix);
wnd:set_title(title, true);
wnd:add_handler("resize", tile_changed);
wnd:add_handler("select", sel_input);
wnd:add_handler("deselect", desel_input);
show_image(wnd.canvas);
-- may use this function to launch / create some internal window
-- that don't need all the external dispatch stuff, so make sure
if (valid_vid(vid, TYPE_FRAMESERVER)) then
wnd.external = vid;
extevh_register_window(vid, wnd);
EVENT_SYNCH[wnd.external] = {
queue = {},
target = vid
};
if (wnd.wm.selected ~= wnd) then
wnd:set_dispmask(TD_HINT_UNFOCUSED);
end
end
return wnd;
end
--
-- adopted windows has a few edge cases,
-- 1. saved metadata from earlier
-- 2. attached to a display that doesn't necessarily exist
-- 3. complex allocation hierarchy (wayland)
--
local adopt_new = {};
function durden_adopt(vid, kind, title, parent, last)
-- always ignore unknown ones as they are likely pending or external listening
if (kind == "unknown") then
conn_log(conn_fmt("adopt=%d:kind=unknown:reject_wnd", vid));
return false;
end
-- fake trigger the meta guard as we likely come from a working reset/
-- silent restart where the feature is just an annoyance
meta_guard(true, true);
-- need to re-attach so they don't end up racing to the wrong display
local ap = display_attachment();
if (ap ~= nil) then
rendertarget_attach(ap, vid, RENDERTARGET_DETACH);
end
-- otherwise, ignore subsegments - let the client re-request them as needed
if (valid_vid(parent)) then
conn_log(conn_fmt("adopt=%d:kind=%s:reject_subsegment", vid, kind));
return;
end
-- build a new window with the old title etc.
local wnd = durden_launch(vid, title);
if (not wnd) then
conn_log(conn_fmt("adopt=%d:kind=%s:reject_wnd", vid, kind));
return;
end
-- and fake a registered event to make the archetype apply
extevh_default(vid, {
kind = "registered",
segkind = kind,
title = string.len(title) > 0 and title or tostring(kind),
source_audio = BADID
});
conn_log(conn_fmt("adopt=%d:kind=%s:parent=%d", vid, kind, parent));
-- some atypes may still have 'attach_block' where this becomes a noop
if (wnd.ws_attach) then
wnd:ws_attach();
table.insert(adopt_new, wnd);
end
-- wait until last adoption call before doing relayout etc.
if (not last) then
return true;
end
-- sweep the list of newly added windows and reparent if needed
local ds = {};
for i,v in ipairs(adopt_new) do
if (v.desired_parent) then
local lst = v.space:linearize();
for i,j in ipairs(lst) do
if (j.name == v.desired_parent) then
v:reparent(j);
ds[v.space] = true;
break;
end
end
end
end
-- and relayout the dirty spaces
for space in all_spaces_iter() do
space:resize();
end
-- the statusbar and other dependents are not necessarily synched on
-- ws_attach operations, so need to do this manually
for disp in all_tilers_iter() do
disp:tile_update();
-- an ugly hack to reset selection state
disp:switch_ws(2);
disp:switch_ws(1);
end
adopt_new = {};
return true;
end
-- This will likely burst device events in the beginning that we
-- don't really care to show, so wait a few hundred ticks before
-- adding notifications
--
function durden_iostatus_handler(iotbl)
local dev = iotbl.devkind and iotbl.devkind or "unknown";
if (iotbl.action == "added") then
if (dev == "led") then
ledm_added(iotbl);
else
iostatem_added(iotbl);
end
elseif (iotbl.action == "removed") then
if (iotbl.devkind == "led") then
ledm_added(iotbl);
else
iostatem_removed(iotbl);
end
end
end
function durden_display_state(action, id, state)
display_event_handler(action, id);
if (state and state.ledctrl) then
display_set_backlight(id, state.ledctrl, state.ledind);
end
end
function durden_normal_input(iotbl, fromim)
-- we track all iotbl events in full debug mode
if (iotbl.kind == "status") then
durden_iostatus_handler(iotbl);
return;
end
ievcount = ievcount + 1;
-- iostate manager takes care of mapping or translating 'game' devices,
-- device added/removed events, stateful "per window" tracking and
-- "autofire" or "repeat" injections. It may also route to registered
-- input tools. Any processed results might injected back, and that's
-- the 'fromim' tag.
if (not fromim) then
if (iostatem_input(iotbl)) then
return;
end
end
-- then we forward keyboard events into the dispatch function, this applies
-- translations, bindings and symtable mapping. Returns information if the
-- event was consumed by some UI features (ok true) or what the internal string
-- representation is (m1_m2_LEFT) and the patched iotbl. It will also apply any
-- per-display hook active at the moment (lbar, bbar uses those). It also runs
-- the meta-guard evaluation to try and figure out if the user seems unaware of
-- his keybindings.
local ok, outsym, iotbl = dispatch_translate(iotbl);
if (iotbl.digital) then
if (ok) then
return;
end
-- there is a dark side here in that the idle timers are not considered for
-- touch events that do not present a digital ('press') output, only ranges
-- of analog. This means that gesture analysis need to feed back for these
-- kinds of devices, particularly when their noise-floor/ceiling is moving
-- with the environment.
timer_reset_idle();
end
-- after that we have special handling for mouse motion and presses,
-- any forwarded input there is based on event reception in listeners
-- attached to mouse motion or presses.
if (iotbl.mouse) then
if (mouse_blocked()) then
return;
end
mouse_iotbl_input(iotbl);
timer_reset_idle();
return;
end
-- try the input_table function, if it consumes the input, ok - otherwise
-- try and forward to the display fallback input handler (like the wallpaper)
local sel = active_display().selected;
if (not sel or not sel:input_table(iotbl)) then
if (active_display().fallthrough_ioh) then
active_display():fallthrough_ioh(iotbl);
return;
end
end
end
-- special case: (UP, DOWN, LEFT, RIGHT + mouse motion is mapped to
-- manipulate the mouse_select_begin() mouse_select_end() region,
-- ESCAPE cancels the mode, end runs whatever trigger we set (global).
-- see 'select_region_*' global functions + some button to align
-- with selected window (if any, like m1 and m2)
function durden_regionsel_input(iotbl, fromim)
if (iotbl.kind == "status") then
durden_iostatus_handler(iotbl);
return;
end
-- feed iostatem so that we get repeats
if (not fromim) then
if (iostatem_input(iotbl)) then
return;
end
end
local m2_set = function()
local rt = active_display(true);
local mx, my = mouse_xy();
local items = pick_items(mx, my, 1, true, rt);
if (#items > 0) then
mouse_select_set(items[1]);
end
end
if (iotbl.translated and iotbl.active) then
local sym, lutsym = SYMTABLE:patch(iotbl);
if (SYSTEM_KEYS["cancel"] == sym) then
suppl_region_stop(DURDEN_REGIONFAIL_TRIGGER);
elseif (SYSTEM_KEYS["accept"] == sym) then
suppl_region_stop(DURDEN_REGIONSEL_TRIGGER);
elseif (SYSTEM_KEYS["meta_1"] == sym) then
mouse_select_set();
elseif (SYSTEM_KEYS["meta_2"] == sym) then
-- keyboard mouse navigation, could probably be moved to some
m2_set();
elseif (SYSTEM_KEYS["left"] == sym) then
local mx, my = mouse_xy();
mouse_absinput(mx-8, my);
elseif (SYSTEM_KEYS["right"] == sym) then
local mx, my = mouse_xy();
mouse_absinput(mx+8, my);
elseif (SYSTEM_KEYS["next"] == sym) then
local mx, my = mouse_xy();
mouse_absinput(mx, my-8);
elseif (SYSTEM_KEYS["previous"] == sym) then
local mx, my = mouse_xy();
mouse_absinput(mx, my+8);
end
elseif (iotbl.mouse and not mouse_blocked()) then
if (iotbl.digital) then
if iotbl.subid == MOUSE_RBUTTON then
mouse_select_set();
elseif iotbl.subid == MOUSE_MBUTTON then
m2_set();
-- possible uniform-extend on wheel?
else
suppl_region_stop(DURDEN_REGIONSEL_TRIGGER);
end
else
mouse_iotbl_input(iotbl);
end
end
end
-- no keyrepeat, only forward to timer and wm, used for the
-- system/lock=key state.
function durden_locked_input(iotbl)
if (iotbl.kind == "status") then
durden_iostatus_handler(iotbl);
return;
end
if (not iotbl.translated) then
return;
end
timer_reset_idle();
-- notranslate option will still forward to WM and allows meta- guard to work,
-- but nothing else. So it should not be possible to set lock, plug/unplug
-- keyboard, hammer for meta-state and then get rid if locked state.
local ok, outsym, iotbl = dispatch_translate(iotbl, true);
end
-- we don't want to mutate the entry-point as that would interfere with
-- user provided hookscripts from woring properly, provide an indirection
-- and a logging interface for switching
local current_input = durden_normal_input;
function durden_input(...)
return current_input(...)
end
local ilog;
function durden_input_sethandler(handler, name)
if not ilog then
ilog = suppl_add_logfn("idevice");
end
if not handler then
ilog("new input handler: default/normal");
current_input = durden_normal_input;
else
if handler == current_input then
return false
end
ilog("new input handler: " .. name);
current_input = handler;
end
return true
end
function durden_shutdown()
SYMTABLE:store_translation();
CLIPBOARD:save("clipboard_data.lua");
display_manager_shutdown();
iostatem_shutdown();
gconfig_shutdown();
end
-- we ignore multicast for mouse, so target_input rather than input_table
-- works fine here and elsewhere
local function flush_pending()
for k,v in pairs(EVENT_SYNCH) do
if (valid_vid(v.target)) then
if (v.queue) then
for i,j in ipairs(v.queue) do
target_input(v.target, j);
end
v.queue = {};
end
if (v.pending and #v.pending > 0) then
for i,j in ipairs(v.pending) do
target_input(v.target, j);
end
v.pending = nil;
end
end
end
end
function durden_clock_pulse(n, nt)
-- if we experience stalls that give us multiple batched ticks
-- we don't want to forward this to the iostatem_ as that can
-- generate storms of repeats
if (nt == 1) then
local tt = iostatem_tick();
if (tt) then
for k,v in ipairs(tt) do
durden_input(v, true);
end
end
end
-- and mouse may populate the target-pending queue,
mouse_tick(1);
-- anything periodically attached to a single tiler should be done now
display_tick();
-- led devices can have custom or periodic effect, so also need clock
ledm_tick();
-- forward to third parties
flush_pending();
-- this should only be for tracking, so order-independent
dispatch_tick();
end
-- open question is if we should burn this hook to store state and
-- changes to keybinding etc. for better recovery, downside is that
-- there is the possiblity we save a 'guaranteed broken' state.
function durden_fatal(msg)
local lsym = dispatch_last_symbol and dispatch_last_symbol() or "pre-init"
local msg = string.format(
"error: %s\nlast path: %s\ntrace:\n%s",
msg, lsym, debug.traceback()
);
return msg;
end
|
if mods["nixie-tubes"]then
table.insert(data.raw.technology["circuit-network"].effects,{type = "unlock-recipe", recipe = "nixie-tube"})
table.insert(data.raw.technology["circuit-network"].effects,{type = "unlock-recipe", recipe = "nixie-tube-alpha"})
table.insert(data.raw.technology["circuit-network"].effects,{type = "unlock-recipe", recipe = "nixie-tube-small"})
for i, effect in pairs(data.raw.technology["cathodes"].effects) do
if effect.type == "unlock-recipe" and effect.recipe == "nixie-tube" then
table.remove(data.raw.technology["cathodes"].effects, i)
end
end
for i, effect in pairs(data.raw.technology["cathodes"].effects) do
if effect.type == "unlock-recipe" and effect.recipe == "nixie-tube-alpha" then
table.remove(data.raw.technology["cathodes"].effects, i)
end
end
for i, effect in pairs(data.raw.technology["cathodes"].effects) do
if effect.type == "unlock-recipe" and effect.recipe == "nixie-tube-small" then
table.remove(data.raw.technology["cathodes"].effects, i)
end
end
end |
help(
[[
This module loads PARI 2.7.5
PARI/GP is a widely used computer algebra system designed for fast computations
in number theory (factorizations, algebraic number theory, elliptic curves...),
but also contains a large number of other useful functions to compute with
mathematical entities such as matrices, polynomials, power series, algebraic
numbers etc., and a lot of transcendental functions.
]])
whatis("Loads PARI")
local version = "2.7.5"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/pari/"..version
prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib"))
prepend_path("PATH", pathJoin(base, "bin"))
prepend_path("CPATH", base.."/include")
prepend_path("LIBRARY_PATH", base.."/lib")
family('pari')
|
local GameServerItem = class("GameServerItem")
function GameServerItem:ctor(pData)
self.wKindID =0
self.wNodeID =0
self.wSortID =0
self.wServerID =0
self.wServerKind =0
self.wServerType =0
self.wServerLevel =0
self.wServerPort =0
self.lCellScore =0
self.cbEnterMember =0
self.lEnterScore =0
self.dwServerRule =0
self.dwOnLineCount =0
self.dwAndroidCount =0
self.dwFullCount =0
self.szServerAddr = ""
self.szServerName = ""
end
function GameServerItem:onInit(pData)
if pData == nil then
print("GameServerItem-onInit-null")
return
end
local int64 = Integer64.new()
self.wKindID = pData:readword() --名称索引
self.wNodeID = pData:readword() --节点索引
self.wSortID = pData:readword() --排序索引
self.wServerID = pData:readword() --房间索引
self.wServerKind = pData:readword() --房间类型
self.wServerType = pData:readword() --房间类型
self.wServerLevel= pData:readword() --房间等级
self.wServerPort = pData:readword() --房间端口
self.lCellScore = pData:readscore(int64):getvalue() --单元积分
self.cbEnterMember = pData:readbyte() --进入会员
self.lEnterScore = pData:readscore(int64):getvalue() --进入积分
self.dwServerRule = pData:readdword() --房间规则
self.dwOnLineCount= pData:readdword() --在线人数
self.dwAndroidCount = pData:readdword() --机器人数
self.dwFullCount = pData:readdword() --满员人数
self.szServerAddr = pData:readstring(32) --房间地址
self.szServerName = pData:readstring(32) --房间名称
self.dwSurportType = pData:readdword() --支持类型
self.wTableCount = pData:readword() --桌子数目
--self:testlog()
return self
end
function GameServerItem:testlog()
print("**************************************************")
--dump(self, "GameServerItem", 6)
print("**************************************************")
end
function GameServerItem:readScore(dataBuffer)
if self._int64 == nil then
self._int64 = Integer64.new():addTo(self)
end
dataBuffer:readscore(self._int64)
return self._int64:getvalue()
end
return GameServerItem |
local TrailParticle = GameObject:extend()
function TrailParticle:new(zone, x, y, opts)
TrailParticle.super.new(self, zone, x, y, opts)
self.color = opts.color or skill_point_color
self.depth = 75
self.r = opts.r or random(4, 6)
self.timer:tween(opts.d or random(0.3, 0.5), self, {r = 0}, 'linear', function() self.dead = true end)
end
function TrailParticle:update(dt)
TrailParticle.super.update(self, dt)
end
function TrailParticle:draw()
useColor(self.color)
love.graphics.circle('fill', self.x, self.y, self.r)
setColor(255, 255, 255)
end
function TrailParticle:destroy()
TrailParticle.super.destroy(self)
end
return TrailParticle
|
require "lua/tools"
local filename = tmpdir .. "/lualept.png"
local filename2 = tmpdir .. "/lualept-mask.tif"
local filename3 = tmpdir .. "/lualept-masked.png"
local image1 = images .. '/lualept.jpg'
header("Pix2")
local pix = Pix(image1)
print (pad("pix"), pix)
pix:View()
local ok = pix:Write(filename, 'png')
print (pad("pix:Write('" .. filename .. "', 'png')"), ok)
local w, h, d = pix:GetDimensions()
print (pad("dimensions"), w, h, d)
print (pad("area"), w * h)
print (pad("RGB colors"), pix:CountRGBColors())
local hist = pix:GetColorAmapHistogram(1)
print (pad("color histogram #"), #hist)
local pixm = pix:MakeArbMaskFromRGB(-0.5, -0.5, 0.75, 0.05)
pixm:View()
-- pixm:SetInputFormat('tiff-g4')
print (pad("pixm"), pixm)
print (pad("dimensions"), pixm:GetDimensions())
print (pad("pixels"), pixm:CountPixels())
local box = Box(10,w-20,h-100,100)
print (pad("rect"), box)
print (pad("pixels in rect"), pixm:CountPixelsInRect(box))
print (pad("foreground fract"), pixm:ForegroundFraction())
local ok = pixm:Write(filename2,'g4')
print (pad("pixm:Write('" .. filename2 .. "','g4')"), ok)
pix:PaintThroughMask(pixm, 0, 0, LuaLept.RGB(20,192,96))
pix:View()
local ok = pix:Write(filename3,'png')
print (pad("pix:Write('" .. filename3 .. "','png')"), ok)
header()
|
-------------------------------------------------------------------------------
-- Find functions
-------------------------------------------------------------------------------
--- Find library. Finds entities in various shapes.
-- @shared
local find_library, _ = SF.Libraries.Register("find")
-- Register privileges
do
local P = SF.Permissions
P.registerPrivilege("find", "Find", "Allows the user to access the find library")
end
--[[
local find_cooldown
if SERVER then
find_cooldown = CreateConVar("sf_find_cooldown_sv", "0.01", {FCVAR_REPLICATED, FCVAR_ARCHIVE, FCVAR_DONTRECORD})
else
find_cooldown = CreateConVar("sf_find_cooldown_cl", "0.01", {FCVAR_ARCHIVE, FCVAR_DONTRECORD})
end
--]]
local find_cooldown = CreateConVar("sf_find_cooldown", "0.01", {FCVAR_REPLICATED, FCVAR_ARCHIVE, FCVAR_DONTRECORD})
local function updateCooldown(instance)
local data, time = instance.data, CurTime()
if not data.findcooldown then data.findcooldown = 0 end
if data.findcooldown > time then return false end
data.findcooldown = time + find_cooldown:GetFloat()
return true
end
local function convert(results, func)
if func ~= nil then
SF.CheckType(func,"function",1)
end
local wrap = SF.WrapObject
local out = {}
for i=1, #results do
local ent = wrap(results[i])
if not func or func(ent) then
out[#out+1] = ent
end
end
return out
end
local function check_access(perm)
return SF.Permissions.check(SF.instance.player, nil, perm)
end
--- Checks if a find function can be performed
-- @return True if find functions can be used
function find_library.canFind()
if not check_access("find") then
return false
end
local data = SF.instance.data
if not data.findcooldown then data.findcooldown = 0 end
return data.findcooldown <= CurTime()
end
--- Finds entities in a box
-- @param min Bottom corner
-- @param max Top corner
-- @param filter Optional function to filter results
-- @return An array of found entities
function find_library.inBox(min, max, filter)
if not check_access("find") then
SF.throw("Insufficient permissions", 2)
end
SF.CheckType(min,"Vector")
SF.CheckType(max,"Vector")
local instance = SF.instance
if not updateCooldown(instance) then return end
return convert(ents.FindInBox(min, max), filter)
end
--- Finds entities in a sphere
-- @param center Center of the sphere
-- @param radius Sphere radius
-- @param filter Optional function to filter results
-- @return An array of found entities
function find_library.inSphere(center, radius, filter)
if not check_access("find") then
SF.throw("Insufficient permissions", 2)
end
SF.CheckType(center,"Vector")
SF.CheckType(radius,"number")
local instance = SF.instance
if not updateCooldown(instance) then
SF.throw("You cannot run a find right now", 2)
end
return convert(ents.FindInSphere(center, radius), filter)
end
--- Finds entities in a cone
-- @param pos The cone vertex position
-- @param dir The direction to project the cone
-- @param distance The length to project the cone
-- @param radius The angle of the cone
-- @param filter Optional function to filter results
-- @return An array of found entities
function find_library.inCone(pos, dir, distance, radius, filter)
if not check_access("find") then
SF.throw("Insufficient permissions", 2)
end
SF.CheckType(pos,"Vector")
SF.CheckType(dir,"Vector")
SF.CheckType(distance,"number")
SF.CheckType(radius,"number")
local instance = SF.instance
if not updateCooldown(instance) then
SF.throw("You cannot run a find right now", 2)
end
return convert(ents.FindInCone(pos,dir,distance,radius), filter)
end
--- Finds entities by class name
-- @param class The class name
-- @param filter Optional function to filter results
-- @return An array of found entities
function find_library.byClass(class, filter)
if not check_access("find") then
SF.throw("Insufficient permissions", 2)
end
SF.CheckType(class,"string")
local instance = SF.instance
if not updateCooldown(instance) then
SF.throw("You cannot run a find right now", 2)
end
return convert(ents.FindByClass(class), filter)
end
--- Finds entities by model
-- @param model The model file
-- @param filter Optional function to filter results
-- @return An array of found entities
function find_library.byModel(model, filter)
if not check_access("find") then
SF.throw("Insufficient permissions", 2)
end
SF.CheckType(model,"string")
local instance = SF.instance
if not updateCooldown(instance) then
SF.throw("You cannot run a find right now", 2)
end
return convert(ents.FindByModel(model), filter)
end
--- Finds all players (including bots)
-- @param filter Optional function to filter results
-- @return An array of found entities
function find_library.allPlayers(filter)
if not check_access("find") then
SF.throw("Insufficient permissions", 2)
end
local instance = SF.instance
if not updateCooldown(instance) then
SF.throw("You cannot run a find right now", 2)
end
return convert(player.GetAll(), filter)
end
--- Finds all entitites
-- @param filter Optional function to filter results
-- @return An array of found entities
function find_library.all(filter)
if not check_access("find") then
SF.throw("Insufficient permissions", 2)
end
local instance = SF.instance
if not updateCooldown(instance) then
SF.throw("You cannot run a find right now", 2)
end
return convert(ents.GetAll(), filter)
end
|
-- A project defines one build target
project "bzip2"
--kind "WindowedApp"
--kind "ConsoleApp"
--kind "SharedLib"
kind "StaticLib"
language "C++"
files {
"blocksort.c",
"bzcompress.c",
"bzlib.c",
"bzlib.h",
"bzlib_private.h",
"crctable.c",
"decompress.c",
"huffman.c",
"randtable.c",
}
configuration "windows"
do
defines {
"WIN32",
"_WINDOWS",
}
end
configuration "gmake"
do
buildoptions { "-Wall" }
end
configuration "vs*"
do
buildoptions { "/wd4996" }
end
configuration "Debug"
do
defines { "DEBUG" }
flags { "Symbols" }
targetdir "../debug"
end
configuration "Release"
do
defines { "NDEBUG" }
flags { "Optimize" }
targetdir "../release"
end
|
local args = { ... }
if ccemux then
local function help()
print("Usages:")
print("emu close - close this computer")
print("emu open [id] - open another computer")
print("emu data [id] - opens the data folder")
print("emu config - opens the config editor")
print("Run 'help emu' for additional information")
end
if #args == 0 then
help()
else
if args[1] == "close" then
ccemux.closeEmu()
elseif args[1] == "open" then
print("Opened computer ID " .. ccemux.openEmu(tonumber(args[2])))
elseif args[1] == "data" then
local id = nil
if args[2] ~= nil then
id = tonumber(args[2])
if id == nil then
printError("Expected a computer ID")
return
end
end
if ccemux.openDataDir(id) then
print("Opened data folder")
else
print("Unable to open data folder")
end
elseif args[1] == "config" then
local ok, err = ccemux.openConfig()
if ok then
print("Opened config editor")
else
print(err)
end
else
printError("Unrecognized subcommand: " .. args[1])
help()
end
end
else
printError("CCEmuX API is disabled or unavailable.")
end
|
local L = (...)
return {
new = function(self, whack)
self.whack = whack
return self
end,
keypressed = function(self, key)
if (key == "f11") then
love.window.setFullscreen(not love.window.getFullscreen())
elseif (key == "f2") then
love.graphics.newScreenshot(true):encode(os.time() .. ".png")
end
end
} |
--[[
class_name = {}
function class(cname)
return function(base)
if type(base) == 'string' then
base = _G[base]
return function(body)
_G[cname] = define_class(base, body)
class_name[_G[cname] ] = cname
end
elseif class_name[base] then
return function(body)
_G[cname] = define_class(base, body)
class_name[_G[cname] ] = cname
end
else
_G[cname] = define_class(base)
class_name[_G[cname] ] = cname
end
end
end
do
local function init(self) end
local function to_str(self)
return string.format("<%s#0x%s>",class_name[self.class],self.id)
end
function define_class(base, body)
if not body then
body, base = base, body
end
local class = body
class.base = base
if base then setmetatable(class,{__index = base}) end
class.init = class.init or init
class.__meta = {
__index = class,
__add = class["+"],
__sub = class["-"],
__mul = class["*"],
__div = class["/"],
__mod = class["%"],
__pow = class["^"],
__unm = class["-@"],
__concat = class[".."],
__len = class["#"],
__eq = class["=="],
__lt = class["<"],
__le = class["<="],
__call = class["()"],
__tostring = class.__tostring or to_str,
__pairs = class.__pairs,
__ipairs = class.__ipairs,
}
return class
end
end
function new(class, ...)
if type(class) == "string" then
class = _G[class]
end
local obj = {class = class}
obj.id = string.gsub(tostring(obj), "table: (%d*)", "%1")
setmetatable(obj, class.__meta)
obj:init(...)
return obj
end
]]
|
local questions =
{
[1] = {"In which year did the US get its independence?", {"1776"}},
[2] = {"Who is the current president of the US?", {"Trump", "Donald Trump", "Donald J.Trump", "Donald"}},
[3] = {"What luxury British automobile brand was purchased by by Tata motors in 2008?", {"Jaguar"}},
[4] = {"The companies HP, Microsoft and Apple were all started in a what?", {"Garage"}},
[5] = {"Who is the current supreme leader of North Korea?", {"Kim Jong Un", "Kim Jong-Un"}},
[6] = {"Who was the second president of the United States?", {"John Adams"}},
[7] = {"What color do you get when you mix yellow and blue?", {"Green"}},
[8] = {"Who played the fictional anti hero Deadpool in the 2016 movie?", {"Ryan Reynolds", "Reynolds", "Ryan"}},
[9] = {"Who was awarded the first United States patent for the telephone?", {"Alexander Graham Bell", "Bell", "Alexander Bell", "Graham Bell"}},
[10] = {"In What state was President Barack Obama born?", {"Hawaii"}},
[11] = {"In computer science, what does 'GUI' stand for?", {"Graphical user interface"}},
}
isQuestion = false
hasAnwered = {}
local trivia_time = 1000*60*10
function noneAnswered()
isQuestion = false
for k, v in ipairs(getElementsByType("player")) do
if (exports.server:isPlayerLoggedIn(v)) then
outputChatBox("#FF0000[TRIVIA] #ffffffNo one has answered the question, the correct answer was #D68910"..toAnsw[1]..".", v, 0, 0, 0, true)
end
end
setTimer(getQuestion, trivia_time, 1)
end
function getQuestion()
local i = math.random(1,#questions)
toAnsw = questions[i][2]
award = math.floor(math.random(1000,5000))
isQuestion = true
for k, v in ipairs(getElementsByType("player")) do
if (exports.server:isPlayerLoggedIn(v)) then
outputChatBox("#FF0000[TRIVIA] #D68910"..questions[i][1].." #ffffffAnswer the question for $"..exports.server:convertNumber(award).." in thirty seconds! (use /tansw <answer> to participate).", v, 0, 0, 0, true)
end
end
noAnswerTime = setTimer(noneAnswered, 30*1000, 1)
hasAnwered = {}
end
setTimer(getQuestion, trivia_time, 1)
function isCorrectAnswer(answ)
for k, v in ipairs(toAnsw) do
if (string.lower(answ) == string.lower(v)) then
return true, v
end
end
return false
end
addCommandHandler("tansw", function(plr, cmd, ...)
if (isQuestion) then
if not (hasAnwered[plr]) then
local text = table.concat({...}, " ")
if (isCorrectAnswer(text)) then
local bool, answer = isCorrectAnswer(text)
for k, v in ipairs(getElementsByType("player")) do
if (exports.server:isPlayerLoggedIn(v)) then
outputChatBox("#FF0000[TRIVIA] #ffffff"..getPlayerName(plr).." answered with the right answer which is #D68910"..answer..".", v, 0, 0, 0, true)
outputChatBox("#FF0000[TRIVIA] #ffffff"..getPlayerName(plr).." won $"..exports.server:convertNumber(award)..".", v, 0, 0, 0, true)
end
end
exports.AURpayments:addMoney(plr, award, "Custom", "Misc", 0, "AURsamtrivia Won trivia")
killTimer(noAnswerTime)
setTimer(getQuestion, trivia_time, 1)
isQuestion = false
else
outputChatBox("#FF0000[TRIVIA] #ffffffWrong answer.", plr, 0, 0, 0, true)
hasAnwered[plr] = true
end
else
outputChatBox("#FF0000[TRIVIA] #ffffffYou can no longer participate in this question.", plr, 0, 0, 0, true)
end
else
outputChatBox("#FF0000[TRIVIA] #ffffffThere is no trivia going on right now.", plr, 0, 0, 0, true)
end
end)
|
--[[
# torch-hdf5
Torch support for the HDF5 Hierarchical Data Format.
This format is fast and flexible, and is used by many scientific applications (Matlab, R, Python, etc)
]]
local torch = require 'torch'
hdf5 = {}
local function log(msg)
local info = debug.getinfo(1, "Sl")
print(table.concat{info.short_src, ":", info.currentline, " ", msg})
end
hdf5._logger = {
debug = function() end,
warn = log,
error = log,
}
torch.include("hdf5", "config.lua")
if not hdf5._config then
error("Unable to find torch-hdf5 config.lua")
end
torch.include("hdf5", "ffi.lua")
torch.include("hdf5", "file.lua")
torch.include("hdf5", "dataset.lua")
torch.include("hdf5", "datasetOptions.lua")
torch.include("hdf5", "group.lua")
torch.include("hdf5", "testUtils.lua")
hdf5._debugMode = false
--[[ Call this to enable debug mode. ]]
function hdf5.debugMode()
hdf5._debugMode = true
hdf5._logger.debug = log
end
--[[ Return true if we are in debug mode; false otherwise ]]
function hdf5._inDebugMode()
return hdf5._debugMode
end
--[[ Read an object from a path and wrap it in an instance of the appropriate class
Parameters:
* `parent` - wrapper object immediately above the object being loaded, in the hierarchy
* `locationID` - an HDF5 ID relative to which we are to load the object
* `datapath` - path to the object to load, relative to the given location
Returns: An HDF5Group or HDF5DataSet object
]]
function hdf5._loadObject(parent, locationID, datapath)
local objectID = hdf5.C.H5Oopen(locationID, datapath, hdf5.H5P_DEFAULT)
if objectID < 0 then
error("Unable to read from '" .. datapath .. "' in " .. tostring(parent) .. " - no such data path.")
end
local typeID = hdf5.C.H5Iget_type(objectID)
local status = hdf5.C.H5Oclose(objectID)
if status < 0 then
error("hdf5._loadObject: error closing object " .. objectID)
end
if typeID == hdf5.C.H5I_GROUP then
local groupID = hdf5.C.H5Gopen2(locationID, datapath, hdf5.H5P_DEFAULT)
if groupID < 0 then
error("Unable to read group from '" .. datapath .. "' in " .. tostring(parent) .. "!")
end
local group = hdf5.HDF5Group(parent, groupID)
return group
elseif typeID == hdf5.C.H5I_DATASET then
local datasetID = hdf5.C.H5Dopen2(locationID, datapath, hdf5.H5P_DEFAULT);
if datasetID < 0 then
error("Unable to read dataset from '" .. datapath .. "' in " .. tostring(parent) .. "!")
end
local dataspaceID = hdf5.C.H5Dget_space(datasetID)
if dataspaceID < 0 then
error("Unable to get dataspace for dataset '" .. datapath .. "' in " .. tostring(parent) .. "!")
end
local dataset = hdf5.HDF5DataSet(parent, datasetID, dataspaceID)
return dataset
else
error("Unsupported data type at " .. datapath)
end
end
--[[ Shorthand for [hdf5.HDF5File.open()](#hdf5.HDF5File.open). ]]
function hdf5.open(...)
return hdf5.HDF5File.open(...)
end
return hdf5
|
local S = farming.intllib
-- blackberries seed
minetest.register_node("hades_extrafarming:seed_blackberry", {
description = S("Blackberries Seed"),
tiles = {"farming_blackberry_seed.png"},
inventory_image = "farming_blackberry_seed.png",
wield_image = "farming_blackberry_seed.png",
drawtype = "signlike",
groups = {seed = 1, snappy = 3, attached_node = 1, flammable = 2},
paramtype = "light",
paramtype2 = "wallmounted",
walkable = false,
sunlight_propagates = true,
selection_box = farming.select,
on_place = function(itemstack, placer, pointed_thing)
return farming.place_seed(itemstack, placer, pointed_thing, "hades_extrafarming:blackberry_1")
end,
})
minetest.register_craft({
type = "shapeless",
output = "hades_extrafarming:seed_blackberry",
recipe = {"group:food_blackberry"}
})
-- blackberries
minetest.register_craftitem("hades_extrafarming:blackberry", {
description = S("Blackberries"),
inventory_image = "farming_blackberry.png",
groups = {food_blackberries = 1, food_blackberry = 1,
food_berry = 1, flammable = 2, food = 2, eatable = 1},
on_use = minetest.item_eat(1),
})
local def = {
drawtype = "plantlike",
tiles = {"farming_blackberry_1.png"},
paramtype = "light",
sunlight_propagates = true,
walkable = false,
buildable_to = true,
drop = "",
selection_box = farming.select,
groups = {
snappy = 3, flammable = 2, plant = 1, attached_node = 1,
not_in_creative_inventory = 1, growing = 1
},
sounds = hades_sounds.node_sound_leaves_defaults()
}
-- stage 1
minetest.register_node("hades_extrafarming:blackberry_1", table.copy(def))
-- stage 2
def.tiles = {"farming_blackberry_2.png"}
minetest.register_node("hades_extrafarming:blackberry_2", table.copy(def))
-- stage 3
def.tiles = {"farming_blackberry_3.png"}
minetest.register_node("hades_extrafarming:blackberry_3", table.copy(def))
-- stage 4
def.tiles = {"farming_blackberry_4.png"}
def.groups.growing = nil
def.drop = {
items = {
{items = {'hades_extrafarming:blackberry 2'}, rarity = 1},
{items = {'hades_extrafarming:blackberry'}, rarity = 2},
{items = {'hades_extrafarming:blackberry'}, rarity = 3},
}
}
minetest.register_node("hades_extrafarming:blackberry_4", table.copy(def))
-- add to registered_plants
farming.registered_plants["hades_extrafarming:blackberry"] = {
crop = "hades_extrafarming:blackberry",
seed = "hades_extrafarming:seed_blackberry",
minlight = farming.min_light,
maxlight = farming.max_light,
steps = 4
}
|
-- buckets_api/init.lua
-- Load support for Minebase translation.
local S = minetest.get_translator("buckets_api")
minetest.register_craft({
output = "buckets_api:bucket_empty 1",
recipe = {
{"base_ores:steel_ingot", "", "base_ores:steel_ingot"},
{"", "base_ores:steel_ingot", ""},
}
})
buckets = {}
buckets.liquids = {}
local function check_protection(pos, name, text)
if minetest.is_protected(pos, name) then
minetest.log("warning", (name ~= "" and name or "A mod")
.. " tried to " .. text
.. " at protected position "
.. minetest.pos_to_string(pos)
.. " with a bucket")
minetest.record_protection_violation(pos, name)
return true
end
return false
end
function buckets.on_place(itemstack, user, pointed_thing)
-- Must be pointing to node
if pointed_thing.type ~= "node" then
return
end
local node = minetest.get_node_or_nil(pointed_thing.under)
local ndef = node and minetest.registered_nodes[node.name]
-- Call on_rightclick if the pointed node defines it
if ndef and ndef.on_rightclick and
not (user and user:is_player() and
user:get_player_control().sneak) then
return ndef.on_rightclick(
pointed_thing.under,
node, user,
itemstack)
end
local lpos
-- Check if pointing to a buildable node
if ndef and ndef.buildable_to then
-- buildable; replace the node
lpos = pointed_thing.under
else
-- not buildable to; place the liquid above
-- check if the node above can be replaced
lpos = pointed_thing.above
node = minetest.get_node_or_nil(lpos)
local above_ndef = node and minetest.registered_nodes[node.name]
if not above_ndef or not above_ndef.buildable_to then
-- do not remove the bucket with the liquid
return itemstack
end
end
local def = itemstack:get_definition()
if check_protection(lpos, user
and user:get_player_name()
or "", "place " .. def._source) then
return
end
minetest.set_node(lpos, {name = def._source})
return ItemStack(def._empty)
end
function buckets.on_use(itemstack, user, pointed_thing)
if pointed_thing.type == "object" then
pointed_thing.ref:punch(user, 1.0, { full_punch_interval=1.0 }, nil)
return user:get_wielded_item()
elseif pointed_thing.type ~= "node" then
-- do nothing if it's neither object nor node
return
end
-- Check if pointing to a liquid source
local node = minetest.get_node(pointed_thing.under)
local liquiddef = buckets.liquids[node.name]
local item_count = user:get_wielded_item():get_count()
if liquiddef ~= nil
and liquiddef.itemname ~= nil
and node.name == liquiddef.source then
if check_protection(pointed_thing.under,
user:get_player_name(),
"take ".. node.name) then
return
end
-- default set to return filled bucket
local giving_back = liquiddef.itemname
-- check if holding more than 1 empty bucket
if item_count > 1 then
-- if space in inventory add filled bucked, otherwise drop as item
local inv = user:get_inventory()
if inv:room_for_item("main", {name=liquiddef.itemname}) then
inv:add_item("main", liquiddef.itemname)
else
local pos = user:get_pos()
pos.y = math.floor(pos.y + 0.5)
minetest.add_item(pos, liquiddef.itemname)
end
-- set to return empty buckets minus 1
giving_back = "buckets_api:bucket_empty "..tostring(item_count-1)
end
-- force_renew requires a source neighbour
local source_neighbor = false
if liquiddef.force_renew then
source_neighbor =
minetest.find_node_near(pointed_thing.under, 1, liquiddef.source)
end
if not (source_neighbor and liquiddef.force_renew) then
minetest.add_node(pointed_thing.under, {name = "air"})
end
return ItemStack(giving_back)
else
-- non-liquid nodes will have their on_punch triggered
local node_def = minetest.registered_nodes[node.name]
if node_def then
node_def.on_punch(pointed_thing.under, node, user, pointed_thing)
end
return user:get_wielded_item()
end
end
-- Register a new liquid
-- groups = (optional) groups of the bucket item, for example {water_bucket = 1}
-- force_renew = (optional) bool. Force the liquid source to renew if it has a
-- source neighbour, even if defined as 'liquid_renewable = false'.
-- Needed to avoid creating holes in sloping rivers.
-- This function can be called from any mod (that depends on bucket).
function buckets.register_liquid(name, def)
local txt = name:gsub(":", "_")
buckets.liquids[def.source] = {
itemname = name,
source = def.source,
flowing = def.flowing,
force_renew = def.force_renew,
}
buckets.liquids[def.flowing] = buckets.liquids[def.source]
if name then
minetest.register_craftitem(name, {
description = def.description or txt,
short_desciption = def.short_desciption,
groups = def.groups,
inventory_image = def.inventory_image or txt .. ".png",
inventory_overlay = def.inventory_overlay,
wield_image = def.wield_image,
wield_overlay = def.wield_overlay,
palette = def.palette,
color = def.color,
wield_scale = def.wield_scale,
stack_max = 1,
range = def.range,
liquids_pointable = true,
light_source = def.light_source,
node_placement_prediction = def.node_placement_prediction,
sound = def.sound,
on_place = def.on_place or buckets.on_place,
_empty = def.empty or "buckets_api:bucket_empty",
_source = def.source
})
end
end
minetest.register_craftitem("buckets_api:bucket_empty", {
description = S("Empty Bucket"),
inventory_image = "buckets_api_bucket.png",
groups = {tool = 1},
liquids_pointable = true,
on_use = buckets.on_use
})
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.