content
stringlengths
5
1.05M
--[[ 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: cruciformer@gmail.com Please refer to the file LICENSE.txt for the Apache License, Version 2.0. Copyright 2008-2018 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 K = LibStub:GetLibrary("KKore") if (not K) then error ("KahLua KonferSK: could not find KahLua Kore.", 2) end local ksk = K:GetAddon ("KKonferSK") local L = ksk.L local KUI = ksk.KUI local MakeFrame = KUI.MakeFrame -- Local aliases for global or LUA library functions local _G = _G local tinsert = table.insert local tremove = table.remove local setmetatable = setmetatable local tconcat = table.concat local tsort = table.sort local tostring = tostring local strlower = string.lower local GetTime = GetTime local min = math.min local max = math.max local strfmt = string.format local strsub = string.sub local strlen = string.len local strfind = string.find local xpcall, pcall = xpcall, pcall local pairs, next, type = pairs, next, type local select, assert, loadstring = select, assert, loadstring local printf = K.printf local ucolor = K.ucolor local ecolor = K.ecolor local icolor = K.icolor local white = ksk.white local class = ksk.class local aclass = ksk.aclass local debug = ksk.debug local info = ksk.info local err = ksk.err local CFGTYPE_GUILD = ksk.CFGTYPE_GUILD local CFGTYPE_PUG = ksk.CFGTYPE_PUG --[[ This file implements the configuration UI and provides functions for manipulating various config options and refreshing the data. Most of this code can only be run by an administrator although anyone can switch active configurations. The main UI creation function is ksk.InitialiseConfigUI() and it creates the config tab contents and the three pages. The main data refresh function is ksk.RefreshConfigUI(). However, there are a number of sub refresh functions which reset only portions of the UI or stored data, all of which are called by ksk.RefreshConfigUI (). ksk.RefreshConfigLootUI (reset) Refreshes the loot distribution options page of the config tab. ksk.RefreshConfigRollUI (reset) Refreshes the loot rolling options page of the config tab. ksk.RefreshConfigAdminUI (reset) Refreshes the config admin page of the config tab. ]] local admincfg = nil local sortedconfigs = nil local coadmin_selected = nil local sortedadmins = nil local newcfgdlg = nil local copycfgdlg = nil local orankdlg = nil local coadmin_popup = nil local silent_delete = false local qf = {} -- -- We have a finite number of admins, in order to ensure that unique user -- ID's will be created by each admin, so there is no clash when syncing. -- This is the list of admin "prefixes" for the admins. Everything else is -- in lower case in the system so we preserve that, using lower case letters -- and numbers, making the total possible number of admins 36. This is the -- numbering sequence for the admin ID. -- local adminidseq = "0123456789abcdefghijklmnopqrstuvwxyz" -- -- This file contains all of the UI handling code for the config panel, -- as well as all config space manipulation functions. Since this code -- deals with config spaces themselves, its data model is slightly -- different. All of the main config options etc use the standard data -- model but the admin screen has a different notion of the "current" -- configuration. For that screen and that screen only, the configuration -- it works with is dictated by the local variable admincfg, which is set -- when a configuration space is selected in the left hand panel. -- local function config_setenabled (onoff) local onoff = onoff or false if (qf.cfgopts) then local en = false qf.cfgopts.cfgowner:SetEnabled (onoff) qf.cfgopts.tethered:SetEnabled (onoff) qf.cfgopts.cfgtype:SetEnabled (onoff) if (onoff and K.player.is_guilded and K.player.is_gm) then en = true end qf.cfgopts.orankedit:SetEnabled (en) qf.cfgdelbutton:SetEnabled (onoff) qf.cfgrenbutton:SetEnabled (onoff) qf.cfgcopybutton:SetEnabled (onoff) qf.coadadd:SetEnabled (onoff) end end local function refresh_coadmins () if (not admincfg) then qf.coadminscroll.itemcount = 0 qf.coadminscroll:UpdateList () return end local newadmins = {} local ownerlist = {} local tc = ksk.frdb.configs[admincfg] local ul = ksk.frdb.configs[admincfg].users coadmin_selected = nil for k,v in pairs (tc.admins) do tinsert (newadmins, k) end tsort (newadmins, function (a, b) return ul[a].name < ul[b].name end) for k,v in pairs (newadmins) do tinsert (ownerlist, { text = aclass (ul[v]), value = v }) end sortedadmins = newadmins qf.coadminscroll.itemcount = #sortedadmins qf.coadminscroll:UpdateList () qf.coadminscroll:SetSelected (nil) qf.cfgownerdd:UpdateItems (ownerlist) -- Don't throw an OnValueChanged event as that could have been what called us -- and we don't want to create an infinite loop. qf.cfgownerdd:SetValue (tc.owner, true) end -- -- This is a helper function for when a configuration is selected from the -- list of possible configurations in the admin screen. It updates and -- populates the admin options on the right side panel. -- local function config_selectitem (objp, idx, slot, btn, onoff) local onoff = onoff or false config_setenabled (onoff) if (onoff) then admincfg = sortedconfigs[idx].id local lcf = ksk.frdb.configs[admincfg] local en qf.cfgopts.cfgowner:SetValue (lcf.owner) qf.cfgopts.tethered:SetChecked (lcf.tethered) qf.cfgopts.cfgtype:SetValue (lcf.cfgtype) en = ksk.csdata[admincfg].is_admin == 2 and true or false qf.cfgopts.cfgowner:SetEnabled (en) qf.cfgopts.tethered:SetEnabled (en) if (lcf.cfgtype ~= CFGTYPE_GUILD) then qf.cfgopts.orankedit:SetEnabled (false) end qf.coadadd:SetEnabled (en and lcf.nadmins < 36) qf.cfgrenbutton:SetEnabled (en) if (not ksk.CanChangeConfigType ()) then en = false end qf.cfgopts.cfgtype:SetEnabled (en) if (ksk.frdb.nconfigs > 1) then qf.cfgdelbutton:SetEnabled (true) else qf.cfgdelbutton:SetEnabled (false) end else admincfg = nil end if (admincfg and admincfg == ksk.currentid) then refresh_coadmins () end end -- -- Helper function for dealing with the selected item in the coadmin scroll -- list. -- local function coadmin_list_selectitem (objp, idx, slot, btn, onoff) local en = false local onoff = onoff or false if (onoff and admincfg) then local lcf = ksk.frdb.configs[admincfg] coadmin_selected = sortedadmins[idx] if (coadmin_selected ~= lcf.owner) then en = ksk.csdata[admincfg].is_admin == 2 and true or false end else coadmin_selected = nil end qf.coaddel:SetEnabled (en) end -- Low level helper function to add a new co-admin local function add_coadmin (uid, cfgid) assert (uid) assert (cfgid) local pcc = ksk.frdb.configs[cfgid] if (not pcc) then return end local newid for i = 1, 36 do local id = strsub (adminidseq, i, i) local found = false for k,v in pairs (pcc.admins) do if (v.id == id) then found = true break end end if (not found) then newid = id break end end assert (newid, "fatal logic bug somewhere!") -- Must add the event BEFORE we add the admin ksk.AddEvent (cfgid, "MKADM", strfmt("%s:%s", uid, newid)) pcc.nadmins = pcc.nadmins + 1 pcc.admins[uid] = { id = newid } end local function new_space_button() local box if (not newcfgdlg) then newcfgdlg, box = ksk.SingleStringInputDialog ("KSKSetupNewSpace", L["Create Configuration"], L["NEWMSG"], 400, 165) local function verify_with_create (objp, val) if (strlen (val) < 1) then err (L["invalid configuration space name. Please try again."]) objp:Show () objp.ebox:SetFocus () return true end ksk.CreateNewConfig (val, false) newcfgdlg:Hide () ksk.mainwin:Show () return false end newcfgdlg:Catch ("OnAccept", function (this, evt) local rv = verify_with_create (this, this.ebox:GetText ()) return rv end) newcfgdlg:Catch ("OnCancel", function (this, evt) newcfgdlg:Hide () ksk.mainwin:Show () return false end) box:Catch ("OnEnterPressed", function (this, evt, val) return verify_with_create (this, val) end) else box = newcfgdlg.ebox end box:SetText("") ksk.mainwin:Hide () newcfgdlg:Show () box:SetFocus () end local function rename_space_button (cfgid) local function rename_helper (newname, old) local rv = ksk.RenameConfig (old, newname) if (rv) then return true end return false end ksk.RenameDialog (L["Rename Configuration"], L["Old Name"], ksk.frdb.configs[cfgid].name, L["New Name"], 32, rename_helper, cfgid, true) end local function copy_space_button (cfgid, newname, newid, shown) if (not copycfgdlg) then local ypos = 0 local arg = { x = "CENTER", y = "MIDDLE", name = "KSKCopyConfigDialog", title = L["Copy Configuration"], border = true, width = 450, height = 280, canmove = true, canresize = false, escclose = true, blackbg = true, okbutton = { text = K.ACCEPTSTR }, cancelbutton = { text = K.CANCELSTR }, } local ret = KUI:CreateDialogFrame (arg) arg = {} arg = { x = 0, y = ypos, width = 200, height = 20, autosize = false, justifyh = "RIGHT", font = "GameFontNormal", text = L["Source Configuration"], } ret.str1 = KUI:CreateStringLabel (arg, ret) arg.justifyh = "LEFT" arg.text = "" arg.border = true arg.color = {r = 1, g = 1, b = 1, a = 1 } ret.str2 = KUI:CreateStringLabel (arg, ret) ret.str2:ClearAllPoints () ret.str2:SetPoint ("TOPLEFT", ret.str1, "TOPRIGHT", 12, 0) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, width = 200, height = 20, autosize = false, justifyh = "RIGHT", font = "GameFontNormal", text = L["Destination Configuration"], } ret.str3 = KUI:CreateStringLabel (arg, ret) arg.justifyh = "LEFT" arg.text = "" arg.border = true arg.color = {r = 1, g = 1, b = 1, a = 1 } ret.str4 = KUI:CreateStringLabel (arg, ret) ret.str4:ClearAllPoints () ret.str4:SetPoint ("TOPLEFT", ret.str3, "TOPRIGHT", 12, 0) arg = {} arg = { x = 0, y = ypos, width = 200, height = 20, len = 32, } ret.dest = KUI:CreateEditBox (arg, ret) ret.dest:ClearAllPoints () ret.dest:SetPoint ("TOPLEFT", ret.str3, "TOPRIGHT", 12, 0) ret.dest:Catch ("OnValueChanged", function (this, evt, newv) copycfgdlg.newname = newv end) arg = {} ypos = ypos - 24 local xpos = 90 arg = { x = xpos, y = ypos, name = "KSKCopyListDD", dwidth = 175, items = KUI.emptydropdown, itemheight = 16, title = { text = L["Roll Lists to Copy"] }, mode = "MULTI", } ret.ltocopy = KUI:CreateDropDown (arg, ret) arg = {} ypos = ypos - 32 arg = { x = xpos, y = ypos, label = { text = L["Copy Co-admins"] }, } ret.copyadm = KUI:CreateCheckBox (arg, ret) ret.copyadm:Catch ("OnValueChanged", function (this, evt, val) copycfgdlg.do_copyadm = val end) arg = {} ypos = ypos - 24 arg = { x = xpos, y = ypos, label = { text = L["Copy All User Flags"] }, } ret.copyflags = KUI:CreateCheckBox (arg, ret) ret.copyflags:Catch ("OnValueChanged", function (this, evt, val) copycfgdlg.do_copyflags = val end) arg = {} ypos = ypos - 24 arg = { x = xpos, y = ypos, label = { text = L["Copy Configuration Options"] }, } ret.copycfg = KUI:CreateCheckBox (arg, ret) ret.copycfg:Catch ("OnValueChanged", function (this, evt, val) copycfgdlg.do_copycfg = val end) arg = {} ypos = ypos - 24 arg = { x = xpos, y = ypos, label = { text = L["Copy Item Options"] }, } ret.copyitem = KUI:CreateCheckBox (arg, ret) ret.copyitem:Catch ("OnValueChanged", function (this, evt, val) copycfgdlg.do_copyitems = val end) arg = {} ypos = ypos - 24 copycfgdlg = ret ret.OnAccept = function (this) -- -- First things first, see if we need to create the new configuration -- or if we are copying into it. -- if (not copycfgdlg.newname or copycfgdlg.newname == "") then err (L["invalid configuration name. Please try again."]) return end if (copycfgdlg.newid == 0) then copycfgdlg.newid = ksk.FindConfig (copycfgdlg.newname) or 0 end if (copycfgdlg.newid == 0) then local rv, ni = ksk.CreateNewConfig (copycfgdlg.newname, false) if (rv) then return end copycfgdlg.newid = ni end local newid = copycfgdlg.newid local cfgid = copycfgdlg.cfgid assert (ksk.frdb.configs[newid]) local dc = ksk.frdb.configs[newid] local sc = ksk.frdb.configs[cfgid] -- -- Copy the users. We cannot do a blind copy of the user ID's as the user -- may already exist in the configuration with a different ID, so we have -- to search the new configuration for each user. We go through the list -- twice, the first time skipping alts, the second time just dealing with -- alts. For the various user flags, we have to do them individually, as -- we may need to send out events for each change to the new user. -- for k,v in pairs (sc.users) do if (not v.main) then local du = ksk.FindUser (v.name, newid) if (not du) then du = ksk.CreateNewUser (v.name, v.class, newid, true, true) end if (copycfgdlg.do_copyflags) then local fs fs = ksk.UserIsEnchanter (k, v.flags, cfgid) ksk.SetUserEnchanter (du, fs, newid) fs = ksk.UserIsFrozen (k, v.flags, cfgid) ksk.SetUserFrozen (du, fs, newid) end end end for k,v in pairs (sc.users) do if (v.main) then local du = ksk.FindUser (v.name, newid) if (not du) then du = ksk.CreateNewUser (v.name, v.class, newid, true, true) end if (copyflags) then local fs fs = ksk.UserIsEnchanter (k, v.flags, cfgid) ksk.SetUserEnchanter (du, fs, newid) fs = ksk.UserIsFrozen (k, v.flags, cfgid) ksk.SetUserFrozen (du, fs, newid) end local mu = ksk.FindUser (sc.users[v.main].name, newid) assert (mu) ksk.SetUserIsAlt (du, true, mu, newid) end end -- -- Now copy the roll lists (if any) we have been asked to copy. -- for k,v in pairs (copycfgdlg.copylist) do if (v == true) then -- -- We can use the handy SMLST event to set the member list. -- That event was originally intended for the CSV import -- function but it serves our purposes perfectly as we can -- set the entire member list with one event. No need to -- recreate lists or anything like that. -- local sl = sc.lists[k] local dlid = ksk.FindList (sl.name, newid) if (not dlid) then -- -- Need to create the list -- local rv, ri = ksk.CreateNewList (sl.name, newid) assert (not rv) dlid = ri end local dul = {} for kk,vv in ipairs (sl.users) do -- Find the user in the new config local du = ksk.FindUser (sc.users[vv].name, newid) assert (du) tinsert (dul, du) end local dus = tconcat (dul, "") ksk.SetMemberList (dus, dlid, newid) -- -- Copy the list options and prepare a CHLST event -- if (copycfgdlg.do_copycfg) then local dl = dc.lists[dlid] dl.sortorder = sl.sortorder dl.def_rank = sl.def_rank dl.strictcfilter = sl.strictcfilter dl.strictrfilter = sl.strictrfilter if (sl.extralist ~= "0") then dl.extralist = ksk.FindList (sc.lists[sl.extralist].name, newid) or "0" end -- If this changes MUST change in KSK-Comms.lua(CHLST) local es = strfmt ("%s:%d:%d:%s:%s:%s", dlid, dl.sortorder, dl.def_rank, dl.strictcfilter and "Y" or "N", dl.strictrfilter and "Y" or "N", dl.extralist) ksk.AddEvent (newid, "CHLST", es) end end end -- -- Next up are the item options, if we have been asked to copy them. -- We only copy items that do not exist. If the item exists in the -- new config we leave it completely untouched. -- if (copycfgdlg.do_copyitems) then local sil = sc.items local dil = dc.items for k,v in pairs (sil) do if (not dil[k]) then local es = k .. ":" ksk.AddItem (k, v.ilink, newid) K.CopyTable (v, dil[k]) -- -- Obviously the UID for assign to next user will be -- different, so we adjust for that. -- if (v.user) then dil[k].user = ksk.FindUser (sc.users[v.user].name, newid) assert (dil[k].user) end ksk.MakeCHITM (k, dil[k], newid, true) end end end -- -- If we have been asked to preserve all of the config options then -- copy them over now, but we will have to adjust the disenchanter -- UIDs. -- if (copycfgdlg.do_copycfg) then K.CopyTable (sc.settings, dc.settings) for k,v in pairs (sc.settings.denchers) do if (v) then dc.settings.denchers[k] = ksk.FindUser (sc.users[v].name, newid) end end dc.tethered = sc.tethered dc.cfgtype = sc.cfgtype dc.owner = ksk.FindUser (sc.users[sc.owner].name, newid) dc.oranks = sc.oranks end -- -- If they want to copy co-admins do so now. -- if (copycfgdlg.do_copyadm) then for k,v in pairs (sc.admins) do local uid = ksk.FindUser (sc.users[k].name, newid) assert (uid) if (not dc.admins[uid]) then add_coadmin (uid, newid) end end end ksk.FullRefresh (true) copycfgdlg:Hide () if (copycfgdlg.isshown) then ksk.mainwin:Show () end end ret.OnCancel = function (this) copycfgdlg:Hide () if (copycfgdlg.isshown) then ksk.mainwin:Show () end end end copycfgdlg.do_copyadm = false copycfgdlg.do_copyflags = true copycfgdlg.do_copycfg = true copycfgdlg.do_copyraid = false copycfgdlg.do_copyitems = false copycfgdlg.copylist = {} copycfgdlg.newname = newname or "" copycfgdlg.newid = newid or 0 copycfgdlg.cfgid = cfgid -- -- Each time we are called we need to populate the dropdown list so that -- it has the correct list of lists. -- local function set_list (btn) copycfgdlg.copylist[btn.value] = btn.checked end local items = {} for k,v in pairs (ksk.frdb.configs[cfgid].lists) do local ti = { text = v.name, value = k, keep = true, func = set_list } ti.checked = function () return copycfgdlg.copylist[k] end tinsert (items, ti) end tsort (items, function (a,b) return strlower (a.text) < strlower (b.text) end) copycfgdlg.ltocopy:UpdateItems (items) copycfgdlg.copyadm:SetChecked (copycfgdlg.do_copyadm) copycfgdlg.copyflags:SetChecked (copycfgdlg.do_copyflags) copycfgdlg.copycfg:SetChecked (copycfgdlg.do_copycfg) copycfgdlg.copyitem:SetChecked (copycfgdlg.do_copyitems) if (not copycfgdlg.newid or copycfgdlg.newid == 0) then copycfgdlg.str4:Hide () copycfgdlg.dest:Show () copycfgdlg.dest:SetText (copycfgdlg.newname) else copycfgdlg.dest:Hide () copycfgdlg.str4:Show () copycfgdlg.str4:SetText (copycfgdlg.newname) end copycfgdlg.str2:SetText (ksk.frdb.configs[cfgid].name) copycfgdlg.isshown = shown ksk.mainwin:Hide () copycfgdlg:Show () end function ksk.CopyConfigSpace (cfgid, newname, newid) copy_space_button (cfgid, newname, newid, ksk.mainwin:IsShown ()) end local dencher_popup local which_dencher local which_dench_lbl local function select_dencher (btn, lbl, num) if (ksk.popupwindow) then ksk.popupwindow:Hide () ksk.popupwindow = nil end local ulist = {} which_dencher = num which_dench_lbl = lbl tinsert (ulist, { value = 0, text = L["None"] }) for k,v in ipairs (ksk.sortedusers) do local ok = true for i = 1, ksk.MAX_DENCHERS do if (ksk.settings.denchers[i] == v.id) then ok = false end end if (ok and ksk.UserIsEnchanter (v.id)) then local ti = { value = v.id, text = aclass (ksk.users[v.id]) } tinsert (ulist, ti) end end local function pop_func (uid) if (uid == 0) then ksk.settings.denchers[which_dencher] = nil which_dench_lbl:SetText ("") else which_dench_lbl:SetText (aclass (ksk.users[uid])) if (ksk.settings.denchers[which_dencher] ~= uid) then ksk.settings.denchers[which_dencher] = uid end end -- -- If we're in raid, refresh the raid's notion of possible denchers. -- if (ksk.raid) then ksk.raid.denchers = {} for i = 1, ksk.MAX_DENCHERS do local duid = ksk.settings.denchers[i] if (duid) then if (ksk.raid.users[duid]) then tinsert (ksk.raid.denchers, duid) end end end end ksk.popupwindow:Hide () ksk.popupwindow = nil end if (not dencher_popup) then dencher_popup = ksk.PopupSelectionList ("KSKDencherPopup", ulist, L["Select Enchanter"], 225, 400, btn, 16, function (idx) pop_func (idx) end) end dencher_popup:UpdateList (ulist) dencher_popup:ClearAllPoints () dencher_popup:SetPoint ("TOPLEFT", btn, "TOPRIGHT", 0, dencher_popup:GetHeight() /2) dencher_popup:Show () ksk.popupwindow = dencher_popup end local function change_cfg (which, val) if (ksk.settings) then if (ksk.settings[which] ~= val) then ksk.settings[which] = val end end end local function rank_editor () if (not ksk.rankpriodialog) then local ypos = 0 local arg = { x = "CENTER", y = "MIDDLE", name = "KSKRankEditorDialog", title = L["Edit Rank Priorities"], border = true, width = 320, height = ((K.guild.numranks +1) * 28) + 70, canmove = true, canresize = false, escclose = true, blackbg = true, okbutton = { text = K.ACCEPTSTR }, cancelbutton = { text = K.CANCELSTR }, } local ret = KUI:CreateDialogFrame (arg) arg = {} arg = { x = 8, y = 0, height = 20, text = L["Guild Rank"], font = "GameFontNormal", } ret.glbl = KUI:CreateStringLabel (arg, ret) arg.x = 225 arg.text = L["Priority"] ret.plbl = KUI:CreateStringLabel (arg, ret) arg = {} arg = { x = 8, y = 0, width = 215, text = "", } earg = { x = 225, y = 0, width = 36, initialvalue = "1", numeric = true, len = 2, } for i = 1, 10 do local rlbl = "ranklbl" .. tostring(i) local rpe = "rankprio" .. tostring(i) arg.y = arg.y - 24 ret[rlbl] = KUI:CreateStringLabel (arg, ret) earg.x = 225 earg.y = earg.y - 24 ret[rpe] = KUI:CreateEditBox (earg, ret) ret[rlbl]:Hide () ret[rpe]:Hide () end ret.OnCancel = function (this) this:Hide () ksk.mainwin:Show () end ret.OnAccept = function (this) ksk.settings.rank_prio = {} for i = 1, K.guild.numranks do local rpe = "rankprio" .. tostring (i) local tv = ret[rpe]:GetText () if (tv == "") then tv = "1" end local rrp = tonumber (tv) if (rrp < 1) then rrp = 1 end if (rrp > 10) then rrp = 10 end ksk.settings.rank_prio[i] = rrp end this:Hide () ksk.mainwin:Show () end ksk.rankpriodialog = ret end local rp = ksk.rankpriodialog rp:SetHeight (((K.guild.numranks + 1) * 28) + 50) for i = 1, 10 do local rlbl = "ranklbl" .. tostring(i) local rpe = "rankprio" .. tostring(i) rp[rlbl]:Hide () rp[rpe]:Hide () end for i = 1, K.guild.numranks do local rlbl = "ranklbl" .. tostring(i) local rpe = "rankprio" .. tostring(i) rp[rlbl]:SetText (K.guild.ranks[i]) rp[rpe]:SetText (tostring (ksk.settings.rank_prio[i] or 1)) rp[rlbl]:Show () rp[rpe]:Show () end rp:Show () end local function orank_edit_button () if (not orankdlg) then local arg = { x = "CENTER", y = "MIDDLE", name = "KSKiOfficerRankEditDlg", title = L["Set Guild Officer Ranks"], border = true, width = 240, height = 372, canmove = true, canresize = false, escclose = true, blackbg = true, okbutton = { text = K.ACCEPTSTR }, cancelbutton = {text = K.CANCELSTR }, } local y = 24 local ret = KUI:CreateDialogFrame (arg) arg = { width = 170, height = 24 } for i = 1, 10 do y = y - 24 local cbn = "orankcb" .. tostring(i) arg.y = y arg.x = 10 arg.label = { text = " " } ret[cbn] = KUI:CreateCheckBox (arg, ret) end ret.OnCancel = function (this) this:Hide () ksk.mainwin:Show () end ret.OnAccept = function (this) local ccs local oranks = "" for i = 1, K.guild.numranks do ccs = "orankcb" .. tostring(i) if (this[ccs]:GetChecked ()) then oranks = oranks .. "1" else oranks = oranks .. "0" end end oranks = strsub (oranks .. "0000000000", 1, 10) ksk.frdb.configs[admincfg].oranks = oranks ksk.SendAM ("ORANK", "ALERT", oranks) this:Hide () ksk.mainwin:Show () end orankdlg = ret end local rp = orankdlg local lcf = ksk.frdb.configs[admincfg] rp:SetHeight (((K.guild.numranks + 1) * 28) + 10) for i = 1, 10 do local rcb = "orankcb" .. tostring(i) if (K.guild.ranks[i]) then rp[rcb]:SetText (K.guild.ranks[i]) rp[rcb]:Show () rp[rcb]:SetChecked (strsub (lcf.oranks, i, i) == "1") else rp[rcb]:Hide () end end ksk.mainwin:Hide () rp:Show () end function ksk.InitialiseConfigUI () local arg local kmt = ksk.mainwin.tabs[ksk.CONFIG_TAB] -- First set up the quick access frames we will be using. qf.lootopts = kmt.tabs[ksk.CONFIG_LOOT_PAGE].content qf.rollopts = kmt.tabs[ksk.CONFIG_ROLLS_PAGE].content qf.cfgadmin = kmt.tabs[ksk.CONFIG_ADMIN_PAGE].content -- -- Config panel, loot tab -- local ypos = 0 local cf = qf.lootopts arg = { x = 0, y = ypos, label = { text = L["Auto-open Bid Panel When Corpse Looted"] }, tooltip = { title = "$$", text = L["TIP001"] }, } cf.autobid = KUI:CreateCheckBox (arg, cf) cf.autobid:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("auto_bid", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = { text = L["Silent Bidding"] }, tooltip = { title = "$$", text = L["TIP002"] }, } cf.silentbid = KUI:CreateCheckBox (arg, cf) cf.silentbid:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("silent_bid", val) end) arg = {} arg = { x = 225, y = ypos, label = { text = L["Display Tooltips in Loot List"] }, tooltip = { title = "$$", text = L["TIP003"] }, } cf.tooltips = KUI:CreateCheckBox (arg, cf) cf.tooltips:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("tooltips", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = { text = L["Enable Chat Message Filter"] }, tooltip = { title = "$$", text = L["TIP004"] }, } cf.chatfilter = KUI:CreateCheckBox (arg, cf) cf.chatfilter:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("chat_filter", val) -- This will cause the chat filters to be reset ksk.UpdateUserSecurity () end) arg = {} arg = { x = 225, y = ypos, label = { text = L["Record Loot Assignment History"] }, tooltip = { title = "$$", text = L["TIP005"] }, } cf.history = KUI:CreateCheckBox (arg, cf) cf.history:Catch ("OnValueChanged", function (this, evt, val, usr) change_cfg ("history", val) if (usr and not val) then ksk.cfg.history = {} ksk.RefreshHistory () end end) arg = {} ypos = ypos - 24 arg = { x = 4, y = ypos, name = "KSKAnnounceWhereDropDown", label = { text = L["Announce Loot"], pos = "LEFT" }, itemheight = 16, mode = "SINGLE", dwidth = 125, items = { { text = L["Nowhere"], value = 0, tooltip = { title = "$$", text = L["TIP006.1"] }, }, { text = L["In Guild Chat"], value = 1, tooltip = { title = "$$", text = L["TIP006.2"] }, }, { text = L["In Raid Chat"], value = 2, tooltip = { title = "$$", text = L["TIP006.3"] }, }, }, tooltip = { title = "$$", text = L["TIP006"] }, } cf.announcewhere = KUI:CreateDropDown (arg, cf) cf.announcewhere:Catch ("OnValueChanged", function (this, evt, newv) change_cfg ("announce_where", newv) end) arg = {} local function oaf_checked (this) if (ksk.settings) then return ksk.settings[this.value] end return false end local function oaf_func (this) change_cfg (this.value, this.checked) end arg = { x = 275, y = ypos, name = "KSKAnnouncementsDropDown", itemheight = 16, dwidth = 175, mode = "MULTI", title = { text = L["Other Announcements"],}, tooltip = { title = "$$", text = L["TIP007"] }, items = { { text = L["Announce Bid List Changes"], value = "ann_bidchanges", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.1"] }, }, { text = L["Announce Winners in Raid"], value = "ann_winners_raid", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.2"] }, }, { text = L["Announce Winners in Guild Chat"], value = "ann_winners_guild", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.3"] }, }, { text = L["Announce Bid Progression"], value = "ann_bid_progress", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.4"] }, }, { text = L["Usage Message When Bids Open"], value = "ann_bid_usage", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.5"] }, }, { text = L["Announce Bid / Roll Cancelation"], value = "ann_cancel", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.9"] }, }, { text = L["Announce When No Successful Bids"], value = "ann_no_bids", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.10"] }, }, { text = L["Raiders Not on Current List"], value = "ann_missing", checked = oaf_checked, func = oaf_func, tooltip = { title = "$$", text = L["TIP007.11"] }, }, }, } cf.otherannounce = KUI:CreateDropDown (arg, cf) arg = {} ypos = ypos - 30 arg = { x = 4, y = ypos, name = "KSKDefListDropdown", mode = "SINGLE", dwidth = 200, items = KUI.emptydropdown, itemheight = 16, label = { text = L["Use Default Roll List"], pos = "LEFT" }, tooltip = { title = "$$", text = L["TIP010"] }, } cf.deflist = KUI:CreateDropDown (arg, cf) cf.deflist:Catch ("OnValueChanged", function (this, evt, nv) change_cfg ("def_list", nv) end) arg = {} ypos = ypos - 28 -- -- The list items are updated by ksk.RefreshListDropdowns() in KSK-Lists.lua. -- This in turns calls ksk.RefreshConfigListDropdowns() below. -- qf.deflistdd = cf.deflist arg = { x = 4, y = ypos, name = "KSKGDefRankDropdown", mode = "SINGLE", dwidth = 175, items = KUI.emptydropdown, itemheight = 16, label = { text = L["Initial Guild Rank Filter"], pos = "LEFT" }, tooltip = { title = "$$", text = L["TIP011"] }, } cf.gdefrank = KUI:CreateDropDown (arg, cf) -- Must remain visible in ksk.qf so it can be updated from main. ksk.qf.gdefrankdd = cf.gdefrank cf.gdefrank:Catch ("OnValueChanged", function (this, evt, nv) change_cfg ("def_rank", nv) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = {text = L["Hide Absent Members in Loot Lists"] }, tooltip = { title = "$$", text = L["TIP012"] }, } cf.hideabsent = KUI:CreateCheckBox (arg, cf) cf.hideabsent:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("hide_absent", val) ksk.RefreshLootMembers () end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = { text = L["Auto-assign Loot When Bids Close"] }, } cf.autoloot = KUI:CreateCheckBox (arg, cf) cf.autoloot:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("auto_loot", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, name = "KSKBidThresholdDropDown", label = { text = L["Bid / Roll Threshold"], pos = "LEFT" }, itemheight = 16, mode = "COMPACT", dwidth = 135, items = { { text = L["None"], value = 0 }, { text = ITEM_QUALITY2_DESC, value = 2, color = ITEM_QUALITY_COLORS[2] }, { text = ITEM_QUALITY3_DESC, value = 3, color = ITEM_QUALITY_COLORS[3] }, { text = ITEM_QUALITY4_DESC, value = 4, color = ITEM_QUALITY_COLORS[4] }, }, tooltip = { title = "$$", text = L["TIP095"] }, } cf.threshold = KUI:CreateDropDown (arg, cf) cf.threshold:Catch ("OnValueChanged", function (this, evt, newv) change_cfg ("bid_threshold", newv) cf.denchbelow:SetEnabled (newv ~= 0) end) ypos = ypos - 30 arg = { x = 0, y = ypos, label = { text = L["Auto-disenchant Items Below Threshold"] }, tooltip = { title = "$$", text = L["TIP096"] }, } cf.denchbelow = KUI:CreateCheckBox (arg, cf) cf.denchbelow:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("disenchant_below", val) end) ypos = ypos - 24 arg = { x = 0, y = ypos, label = { text = L["Use Guild Rank Priorities"] }, tooltip = { title = "$$", text = L["TIP013"] }, } cf.rankprio = KUI:CreateCheckBox (arg, cf) cf.rankprio:Catch ("OnValueChanged", function (this, evt, val) if (ksk.cfg.cfgtype == CFGTYPE_PUG) then val = false end change_cfg ("use_ranks", val) cf.rankedit:SetEnabled (val) end) arg = {} arg = { x = 180, y = ypos+2, width = 50, height = 24, text = L["Edit"], enabled = false, tooltip = { title = "$$", text = L["TIP014"] }, } cf.rankedit = KUI:CreateButton (arg, cf) cf.rankedit:ClearAllPoints () cf.rankedit:SetPoint ("TOPLEFT", cf.rankprio, "TOPRIGHT", 16, 0) cf.rankedit:Catch ("OnClick", function (this, evt) ksk.mainwin:Hide () K:UpdatePlayerAndGuild () rank_editor () end) arg = {} ypos = ypos - 30 arg = { x = 4, y = ypos, width = 300, font="GameFontNormal", text = L["When there are no successful bids ..."], } cf.nobidlbl = KUI:CreateStringLabel (arg, cf) arg = {} ypos = ypos - 20 arg = { x = 0, y = ypos, label = { text = L["Assign BoE Items to Master Looter"] }, tooltip = { title = "$$", text = L["TIP015"] }, } cf.boetoml = KUI:CreateCheckBox (arg, cf) cf.boetoml:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("boe_to_ml", val) end) arg = {} arg = { x = 275, y = ypos, label = { text = L["Try Open Roll"] }, tooltip = { title = "$$", text = L["TIP016"] }, } cf.tryroll = KUI:CreateCheckBox (arg, cf) cf.tryroll:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("try_roll", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = { text = L["Assign To Enchanter"] }, tooltip = { title = "$$", text = L["TIP017"] }, } cf.dench = KUI:CreateCheckBox (arg, cf) cf.dench:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("disenchant", val) for i = 1, ksk.MAX_DENCHERS do cf["dencher" .. i]:SetEnabled (val) cf["denchbut" .. i]:SetEnabled (val) end end) arg = {} ypos = ypos - 24 arg = { x = 25, y = ypos, border = true, autosize = false, height=20, width = 150, text = "", enabled = false, } local barg = { x = 180, y = ypos+2, width = 50, height = 24, text = L["Select"], enabled = false, tooltip = { title = L["Assign To Enchanter"], text = L["TIP018"] }, } cf.dencher1 = KUI:CreateStringLabel (arg, cf) cf.denchbut1 = KUI:CreateButton (barg, cf) cf.denchbut1:Catch ("OnClick", function (this, evt) select_dencher (this, cf.dencher1, 1) end) arg.x = 250 barg.x = 405 cf.dencher2 = KUI:CreateStringLabel (arg, cf) cf.denchbut2 = KUI:CreateButton (barg, cf) cf.denchbut2:Catch ("OnClick", function (this, evt) select_dencher (this, cf.dencher2, 2) end) ypos = ypos - 24 arg.x = 25 arg.y = ypos barg.x = 180 barg.y = ypos+2 cf.dencher3 = KUI:CreateStringLabel (arg, cf) cf.denchbut3 = KUI:CreateButton (barg, cf) cf.denchbut3:Catch ("OnClick", function (this, evt) select_dencher (this, cf.dencher3, 3) end) arg.x = 250 barg.x = 405 cf.dencher4 = KUI:CreateStringLabel (arg, cf) cf.denchbut4 = KUI:CreateButton (barg, cf) cf.denchbut4:Catch ("OnClick", function (this, evt) select_dencher (this, cf.dencher4, 4) end) arg = {} barg = {} ypos = ypos - 24 -- -- Config panel, roll options tab -- local cf = qf.rollopts ypos = 0 arg = { label = { text = L["Open Roll Timeout"] }, x = 0, y = ypos, minval = 10, maxval = 60, tooltip = { title = "$$", text = L["TIP008"] }, } cf.rolltimeout = KUI:CreateSlider (arg, cf) cf.rolltimeout:Catch ("OnValueChanged", function (this, evt, newv) change_cfg ("roll_timeout", newv) end) arg = { label = { text = L["Roll Timeout Extension"] }, x = 225, y = ypos, minval = 5, maxval = 30, tooltip = { title = "$$", text = L["TIP009"] }, } cf.rollextend = KUI:CreateSlider (arg, cf) cf.rollextend:Catch ("OnValueChanged", function (this, evt, newv) change_cfg ("roll_extend", newv) end) ypos = ypos - 48 arg = { x = 0, y = ypos, label = {text = L["Enable Off-spec (101-200) Rolls"] }, tooltip = { title = "$$", text = L["TIP092"] }, } cf.enableoffspec = KUI:CreateCheckBox (arg, cf) cf.enableoffspec:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("offspec_rolls", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = {text = L["Enable Suicide Rolls by Default"] }, tooltip = { title = "$$", text = L["TIP093"] }, } cf.suicideroll = KUI:CreateCheckBox (arg, cf) cf.suicideroll:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("suicide_rolls", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = {text = L["Usage Message When Rolls Open"] }, tooltip = { title = "$$", text = L["TIP007.6"] }, } cf.rollusage = KUI:CreateCheckBox (arg, cf) cf.rollusage:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("ann_roll_usage", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = {text = L["Announce Open Roll Countdown"] }, tooltip = { title = "$$", text = L["TIP007.7"] }, } cf.countdown = KUI:CreateCheckBox (arg, cf) cf.countdown:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("ann_countdown", val) end) arg = {} ypos = ypos - 24 arg = { x = 0, y = ypos, label = {text = L["Announce Open Roll Ties"] }, tooltip = { title = "$$", text = L["TIP007.8"] }, } cf.ties = KUI:CreateCheckBox (arg, cf) cf.ties:Catch ("OnValueChanged", function (this, evt, val) change_cfg ("ann_roll_ties", val) end) arg = {} ypos = ypos - 24 -- -- Config panel, admin tab -- local cf = qf.cfgadmin local ls = cf.vsplit.leftframe local rs = cf.vsplit.rightframe arg = { height = 50, rightsplit = true, name = "KSKCfgAdminLSHSplit", } ls.hsplit = KUI:CreateHSplit (arg, ls) arg = {} local tl = ls.hsplit.topframe local bl = ls.hsplit.bottomframe arg = { height = 135, name = "KSKCfgAdminRSHSplit", leftsplit = true, topanchor = true, } rs.hsplit = KUI:CreateHSplit (arg, rs) arg = {} local tr = rs.hsplit.topframe local br = rs.hsplit.bottomframe -- Dont set qf.cfgopts to tr just yet. Wait until all of the other child -- elements have been added to it. arg = { height = 35, name = "KSKCfgAdminRSHSplit2", leftsplit = true, } br.hsplit = KUI:CreateHSplit (arg, br) arg = {} local about = br.hsplit.bottomframe local coadmins = br.hsplit.topframe arg = { x = 0, y = 0, width = 80, height = 24, text = L["Create"], tooltip = { title = "$$", text = L["TIP019"] }, } bl.createbutton = KUI:CreateButton (arg, bl) bl.createbutton:Catch ("OnClick", function (this, evt) new_space_button () end) arg = {} arg = { x = 95, y = 0, width = 80, height = 24, text = L["Delete"], tooltip = { title = "$$", text = L["TIP020"] }, } bl.deletebutton = KUI:CreateButton (arg, bl) bl.deletebutton:Catch ("OnClick", function (this, evt) ksk.DeleteConfig (admincfg, true) end) arg = {} qf.cfgdelbutton = bl.deletebutton arg = { x = 0, y = -25, width = 80, height = 24, text = L["Rename"], tooltip = { title = "$$", text = L["TIP021"] }, } bl.renamebutton = KUI:CreateButton (arg, bl) bl.renamebutton:Catch ("OnClick", function (this, evt) rename_space_button (admincfg) end) arg = {} qf.cfgrenbutton = bl.renamebutton arg = { x = 95, y = -25, width = 80, height = 24, text = L["Copy"], tooltip = { title = "$$", text = L["TIP022"] }, } bl.copybutton = KUI:CreateButton (arg, bl) bl.copybutton:Catch ("OnClick", function (this, evt) copy_space_button (admincfg, nil, nil, true) end) arg = {} qf.cfgcopybutton = bl.copybutton -- -- We make the config space panel a scrolling list in case they have lots -- of configs (unlikely but hey, you never know). -- arg = { name = "KSKConfigScrollList", itemheight = 16, newitem = function (objp, num) return KUI.NewItemHelper (objp, num, "KSKConfigButton", 160, 16, nil, nil, nil, nil) end, setitem = function (objp, idx, slot, btn) return KUI.SetItemHelper (objp, btn, idx, function (op, ix) return ksk.frdb.configs[sortedconfigs[ix].id].name end) end, selectitem = config_selectitem, highlightitem = function (objp, idx, slot, btn, onoff) return KUI.HighlightItemHelper (objp, idx, slot, btn, onoff) end, } tl.slist = KUI:CreateScrollList (arg, tl) qf.cfglist = tl.slist arg = {} local bdrop = { bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark", tile = true, tileSize = 32, insets = { left = 0, right = 0, top = 0, bottom = 0 } } tl.slist:SetBackdrop (bdrop) -- -- These are the actual configurable options for a config space. They -- are shown in the top right panel. Below them is some version information -- and contact information. -- arg = { x = 0, y = 0, name = "KSKConfigOWnerDD", itemheight = 16, dwidth = 125, mode = "SINGLE", items = KUI.emptydropdown, label = { pos = "LEFT", text = L["Config Owner"] }, tooltip = { title = "$$", text = L["TIP023"] }, } tr.cfgowner = KUI:CreateDropDown (arg, tr) qf.cfgownerdd = tr.cfgowner tr.cfgowner:Catch ("OnValueChanged", function (this, evt, newv) local lcf = ksk.frdb.configs[admincfg] lcf.owner = newv ksk.FullRefresh (true) end) arg = {} arg = { x = 0, y = -30, label = { text = L["Alts Tethered to Mains"] }, tooltip = { title = "$$", text = L["TIP024"] }, } tr.tethered = KUI:CreateCheckBox (arg, tr) tr.tethered:Catch ("OnValueChanged", function (this, evt, val) local lcf = ksk.frdb.configs[admincfg] lcf.tethered = val ksk.FixupLists (admincfg) ksk.RefreshListsUI (false) end) arg = {} arg = { name = "KSKCfgTypeDropDown", enabled = false, itemheight = 16, x = 4, y = -58, label = { text = L["Config Type"], pos = "LEFT" }, dwidth = 100, mode = "SINGLE", width = 75, tooltip = { title = "$$", text = L["TIP025"] }, items = { { text = L["Guild"], value = CFGTYPE_GUILD }, { text = L["PUG"], value = CFGTYPE_PUG }, }, } tr.cfgtype = KUI:CreateDropDown (arg, tr) tr.cfgtype:Catch ("OnValueChanged", function (this, evt, newv) local lcf = ksk.frdb.configs[admincfg] local en lcf.cfgtype = newv if (newv == CFGTYPE_GUILD and K.player.is_guilded) then qf.cfgopts.orankedit:SetEnabled (true) else qf.cfgopts.orankedit:SetEnabled (false) end if (newv == CFGTYPE_PUG) then lcf.settings.def_rank = 0 lcf.settings.use_ranks = false lcf.settings.ann_winners_guild = false lcf.settings.rank_prio = {} for k, v in pairs (lcf.lists) do v.def_rank = 0 end ksk.RefreshConfigLootUI (false) end end) arg = {} arg = { name = "KSKCfgGuildOfficerButton", x = 4, y = -92, width = 160, height = 24, text = L["Edit Officer Ranks"], enabled = false, tooltip = { title = "$$", text = L["TIP100"] } } tr.orankedit = KUI:CreateButton (arg, tr) tr.orankedit:Catch ("OnClick", function (this, evt) local ct = ksk.frdb.configs[admincfg].cfgtype if (ct == CFGTYPE_GUILD and K.player.is_guilded and K.player.is_gm) then ksk.mainwin:Hide () K:UpdatePlayerAndGuild () orank_edit_button () end end) arg = {} -- NOW we can set qf.cfgopts qf.cfgopts = tr arg = { x = 0, y = 2, height = 12, font = "GameFontNormalSmall", autosize = false, width = 290, text = L["ABOUT1"], } about.str1 = KUI:CreateStringLabel (arg, about) arg = { x = 0, y = -10, height = 12, font = "GameFontNormalSmall", autosize = false, width = 290, text = strfmt(L["ABOUT2"], white ("cruciformer@gmail.com")) } about.str2 = KUI:CreateStringLabel (arg, about) arg = { x = 0, y = -22, height = 12, font = "GameFontNormalSmall", autosize = false, width = 290, text = strfmt(L["ABOUT3"], white ("http://kahluamod.com/ksk")) } about.str2 = KUI:CreateStringLabel (arg, about) arg = { x = "CENTER", y = 0, font = "GameFontNormal", text = L["Co-admins"], border = true, width = 125, justifyh = "CENTER", } coadmins.str1 = KUI:CreateStringLabel (arg, coadmins) arg = {} -- -- There is a finite list of co-admins. We create a scrolling list in case -- some idiots add lots of them. Scrolling lists take up a whole frame so -- we need to create the frame and add the buttons for adding and removing -- co-admins to the right of the frame. -- arg = { x = 200, y = -24, text = L["Add"], width = 90, height = 24, tooltip = { title = "$$", text = L["TIP026"] }, } coadmins.add = KUI:CreateButton (arg, coadmins) coadmins.add:Catch ("OnClick", function (this, evt, ...) local ulist = {} local cc = ksk.frdb.configs[admincfg] local cul = cc.users if (cc.nadmins == 36) then err (L["maximum number of co-admins (36) reached"]) return end if (ksk.popupwindow) then ksk.popupwindow:Hide () ksk.popupwindow = nil end for k,v in pairs (cul) do if (not ksk.UserIsCoadmin (k, admincfg) and not ksk.UserIsAlt (k, nil, admincfg)) then tinsert (ulist, { value = k, text = aclass (cul[k]) }) end end tsort (ulist, function (a, b) return cul[a.value].name < cul[b.value].name end) if (#ulist == 0) then return end local function pop_func (cauid) add_coadmin (cauid, admincfg) ksk.popupwindow:Hide () ksk.popupwindow = nil ksk.RefreshConfigAdminUI (false) end if (not coadmin_popup) then coadmin_popup = ksk.PopupSelectionList ("KSKCoadminAddPopup", ulist, L["Select Co-admin"], 200, 400, this, 16, pop_func) else coadmin_popup:UpdateList (ulist) end coadmin_popup:ClearAllPoints () coadmin_popup:SetPoint ("TOPLEFT", this, "TOPRIGHT", 0, coadmin_popup:GetHeight() / 2) ksk.popupwindow = coadmin_popup coadmin_popup:Show () end) arg = {} qf.coadadd = coadmins.add arg = { x = 200, y = -48, text = L["Delete"], width = 90, height = 24, tooltip = { title = "$$", text = L["TIP027"] }, enabled = false, } coadmins.del = KUI:CreateButton (arg, coadmins) coadmins.del:Catch ("OnClick", function (this, evt, ...) if (not coadmin_selected or not admincfg) then return end ksk.DeleteAdmin (coadmin_selected, admincfg) end) arg = {} qf.coaddel = coadmins.del local sframe = MakeFrame ("Frame", nil, coadmins) coadmins.sframe = sframe sframe:ClearAllPoints () sframe:SetPoint ("TOPLEFT", coadmins, "TOPLEFT", 0, -24) sframe:SetPoint ("BOTTOMLEFT", coadmins, "BOTTOMLEFT", 0, 0) sframe:SetWidth (190) arg = { name = "KSKCoadminScrollList", itemheight = 16, newitem = function (objp, num) return KUI.NewItemHelper (objp, num, "KSKCoadminButton", 160, 16, nil, nil, nil, nil) end, setitem = function (objp, idx, slot, btn) return KUI.SetItemHelper (objp, btn, idx, function (op, ix) local ul = ksk.frdb.configs[admincfg].users return aclass(ul[sortedadmins[ix]]) end) end, selectitem = coadmin_list_selectitem, highlightitem = function (objp, idx, slot, btn, onoff) return KUI.HighlightItemHelper (objp, idx, slot, btn, onoff) end, } coadmins.slist = KUI:CreateScrollList (arg, coadmins.sframe) arg = {} qf.coadminscroll = coadmins.slist end local function real_delete_config (cfgid) if (not silent_delete) then info (L["configuration %q deleted."], white (ksk.frdb.configs[cfgid].name)) end ksk.frdb.configs[cfgid] = nil ksk.csdata[cfgid] = nil ksk.frdb.nconfigs = ksk.frdb.nconfigs - 1 if (ksk.frdb.defconfig == cfgid) then local nid = next(ksk.frdb.configs) ksk.SetDefaultConfig (nid, false, true) admincfg = nid end if (admincfg == cfgid) then admincfg = nil end ksk.FullRefresh (true) end function ksk.DeleteConfig (cfgid, show, private) if (ksk.frdb.nconfigs == 1 and not private) then err (L["cannot delete configuration %q - KonferSK requires at least one configuration."], white (ksk.frdb.configs[cfgid].name)) return true end if (private) then local oldsilent = silent_delete silent_delete = true real_delete_config (cfgid) silent_delete = oldsilent return end local isshown = show or ksk.mainwin:IsShown () ksk.mainwin:Hide () ksk.ConfirmationDialog (L["Delete Configuration"], L["DELMSG"], ksk.frdb.configs[cfgid].name, real_delete_config, cfgid, isshown) return false end function ksk.CreateNewConfig (name, initial, nouser, mykey) local lname = strlower(name) if (strfind (name, ":")) then err (L["invalid configuration name. Please try again."]) return true end for k,v in pairs (ksk.frdb.configs) do if (strlower(v.name) == lname) then err (L["configuration %q already exists. Try again."], white (name)) return true end end ksk.frdb.nconfigs = ksk.frdb.nconfigs + 1 local newkey if (mykey) then newkey = mykey else newkey = ksk.CreateNewID (name) end ksk.frdb.configs[newkey] = {} ksk.csdata[newkey] = {} ksk.csdata[newkey].reserved = {} local sp = ksk.frdb.configs[newkey] sp.name = name sp.tethered = false sp.cfgtype = CFGTYPE_PUG sp.oranks = "1000000000" sp.settings = {} sp.history = {} sp.users = {} sp.nusers = 0 sp.lists = {} sp.nlists = 0 sp.items = {} sp.nitems = 0 sp.admins = {} sp.nadmins = 0 sp.cksum = 0xa49b37d3 sp.lastevent = 0 sp.syncing = false K.CopyTable (ksk.defaults, sp.settings) if (not nouser) then sp.nusers = 1 sp.users["0001"] = { name = K.player.name, class = K.player.class, role = 0, flags = "" } sp.owner = "0001" ksk.csdata[newkey].myuid = uid ksk.info (L["configuration %q created."], white (name)) sp.nadmins = 1 sp.admins["0001"] = { id = "0" } end if (initial) then ksk.SetDefaultConfig (newkey, ksk.frdb.tempcfg, ksk.frdb.tempcfg) return false, newkey end if (ksk.frdb.tempcfg) then ksk.SetDefaultConfig (newkey, true, true) silent_delete = true real_delete_config ("1") silent_delete = false ksk.frdb.tempcfg = nil end -- -- If we have no guild configs, and we are the GM, make this -- a guild config initially. They can change it immediately if this is wrong. -- if (K.player.is_gm) then local ng = 0 for k,v in pairs (ksk.frdb.configs) do if (v.cfgtype == CFGTYPE_GUILD) then ng = ng + 1 end end if (ng == 0) then sp.cfgtype = CFGTYPE_GUILD end end ksk.FullRefresh (true) return false, newkey end function ksk.RenameConfig (cfgid, newname) if (ksk.CheckPerm (cfgid)) then return true end if (not ksk.frdb.configs[cfgid]) then return true end local found = false local lname = strlower (newname) for k,v in pairs (ksk.frdb.configs) do if (strlower(ksk.frdb.configs[k].name) == lname) then found = true end end if (found) then err (L["configuration %q already exists. Try again."], white (newname)) return true end local oldname = ksk.frdb.configs[cfgid].name info (L["NOTICE: configuration %q renamed to %q."], white (oldname), white (newname)) ksk.frdb.configs[cfgid].name = newname ksk.FullRefresh () return false end function ksk.FindConfig (name) local lname = strlower(name) for k,v in pairs (ksk.frdb.configs) do if (strlower(v.name) == lname) then return k end end return nil end function ksk.DeleteAdmin (uid, cfg, nocmd) local cfg = cfg or ksk.currentid local cp = ksk.frdb.configs[cfg] if (not cp) then return end if (not cp.admins[uid]) then return end -- Must send the event BEFORE removing the admin. if (not nocmd) then ksk.AddEvent (cfg, "RMADM", uid, true) end cp.nadmins = cp.nadmins - 1 cp.admins[uid] = nil if (cp.nadmins == 1) then cp.syncing = false cp.lastevent = 0 cp.admins[cp.owner].lastevent = nil cp.admins[cp.owner].sync = nil end if (admincfg and admincfg == ksk.currentid) then refresh_coadmins () end ksk.RefreshSyncUI (true) end -- -- Function: ksk.SetDefaultConfig (cfgid, silent, force) -- Purpose : Set up all of the various global aliases and make the specified -- config the default one. If the current config is already the -- specified config, do nothing unless FORCE is set to true. If -- the work should be silent, set SILENT to true, otherwise a -- message indicating the default change is displayed. -- Returns : Nothing -- function ksk.SetDefaultConfig (cfgid, silent, force) if (not cfgid or not ksk.configs or not ksk.configs[cfgid]) then return end if (not ksk.csdata or not ksk.csdata[cfgid]) then return end if (ksk.frdb.defconfig ~= cfgid or force) then ksk.frdb.defconfig = cfgid ksk.currentid = cfgid ksk.cfg = ksk.frdb.configs[cfgid] if (ksk.initialised) then ksk.qf.synctopbar:SetCurrentCRC () end ksk.settings = ksk.frdb.configs[cfgid].settings ksk.users = ksk.frdb.configs[cfgid].users ksk.lists = ksk.frdb.configs[cfgid].lists ksk.items = ksk.frdb.configs[cfgid].items if (ksk.initialised) then -- If we're not initialised yet then this will just have been called. ksk.RefreshCSData () end ksk.csd = ksk.csdata[cfgid] ksk.sortedlists = nil ksk.missing = {} ksk.nmissing = 0 ksk.UpdateUserSecurity (cfgid) if (ksk.initialised) then ksk.FullRefresh (true) ksk.mainwin:SetTab (ksk.LOOT_TAB, ksk.LOOT_ASSIGN_PAGE) ksk.mainwin:SetTab (ksk.LISTS_TAB, ksk.LISTS_MEMBERS_PAGE) ksk.SelectListByIdx (1) if (not ksk.frdb.tempcfg) then local sidx = nil for k,v in pairs (sortedconfigs) do if (v.id == cfgid) then sidx = k break end end qf.cfglist:SetSelected (sidx, true, true) end if (not silent) then ksk.info (L["NOTICE: default configuration changed to %q."], white (ksk.frdb.configs[cfgid].name)) if (not ksk.csd.is_admin) then ksk.info (L["you are not an administrator of this configuration. Your access to it is read-only."]) end end end end end function ksk.RefreshConfigLists (llist) qf.deflistdd:UpdateItems (llist) qf.deflistdd:SetValue (ksk.settings.def_list or "0") end function ksk.RefreshConfigLootUI (reset) local i local settings = ksk.settings local cf = qf.lootopts local en = true cf.autobid:SetChecked (settings.auto_bid) cf.silentbid:SetChecked (settings.silent_bid) cf.tooltips:SetChecked (settings.tooltips) cf.chatfilter:SetChecked (settings.chat_filter) cf.history:SetChecked (settings.history) cf.announcewhere:SetValue (settings.announce_where) cf.deflist:SetValue (settings.def_list) cf.gdefrank:SetValue (settings.def_rank) cf.hideabsent:SetChecked (settings.hide_absent) cf.autoloot:SetChecked (settings.auto_loot) cf.threshold:SetValue (settings.bid_threshold) cf.denchbelow:SetChecked (settings.disenchant_below) cf.rankprio:SetChecked (settings.use_ranks) cf.boetoml:SetChecked (settings.boe_to_ml) cf.tryroll:SetChecked (settings.try_roll) cf.dench:SetChecked (settings.disenchant) if (ksk.cfg.cfgtype == CFGTYPE_PUG) then en = false end cf.gdefrank:SetEnabled (en) cf.rankprio:SetEnabled (en) ksk.qf.lootrank:SetEnabled (en) ksk.qf.defrankdd:SetEnabled (en) ksk.qf.gdefrankdd:SetEnabled (en) ksk.qf.itemrankdd:SetEnabled (en) for i = 1, ksk.MAX_DENCHERS do if (settings.denchers[i]) then cf["dencher"..i]:SetText (aclass (ksk.users[settings.denchers[i]])) else cf["dencher"..i]:SetText ("") end end end function ksk.RefreshConfigRollUI (reset) local i local settings = ksk.settings local cf = qf.rollopts cf.rolltimeout:SetValue (settings.roll_timeout) cf.rollextend:SetValue (settings.roll_extend) cf.enableoffspec:SetChecked (settings.offspec_rolls) cf.suicideroll:SetChecked (settings.suicide_rolls) cf.rollusage:SetChecked (settings.ann_roll_usage) cf.countdown:SetChecked (settings.ann_countdown) cf.ties:SetChecked (settings.ann_roll_ties) end function ksk.RefreshConfigAdminUI (reset) if (ksk.frdb.tempcfg) then qf.cfglist.itemcount = 0 qf.cfglist:UpdateList () return end local vt = {} local newconfs = {} local oldid = admincfg or ksk.currentid local oldidx = nil admincfg = nil for k,v in pairs(ksk.frdb.configs) do local ent = {id = k } tinsert (newconfs, ent) end tsort (newconfs, function (a, b) return strlower(ksk.configs[a.id].name) < strlower(ksk.configs[b.id].name) end) for k,v in ipairs(newconfs) do vt[k] = { text = ksk.frdb.configs[v.id].name, value = v.id } if (ksk.csdata[v.id].is_admin == 2) then vt[k].color = {r = 0, g = 1, b = 0 } elseif (ksk.csdata[v.id].is_admin == 1) then vt[k].color = {r = 0, g = 1, b = 1 } else vt[k].color = {r = 1, g = 1, b = 1 } end if (v.id == oldid) then oldidx = k end end sortedconfigs = newconfs ksk.mainwin.cfgselector:UpdateItems (vt) -- Don't fire an OnValueChanged event when we set this. ksk.mainwin.cfgselector:SetValue (ksk.currentid, true) qf.cfglist.itemcount = #newconfs qf.cfglist:UpdateList () -- -- There is some magic happening here. By forcing the selection (3rd arg -- true) we force the widget's selectitem function to run. This results -- in config_selectitem() being called. This has a few side effects. The -- first and foremost is, it sets the "admincfg" local variable to the -- selected configuration (if any). Secondly, it forces a refresh of the -- data on the right hand panel that is related to the selected config. -- This includes updating the list of coadmins. That leaves us with a choice -- on how we want to deal with the co-admin list when we have sync events -- or other things changing the coadmin list. We can either have a special -- refresh and reset function just for co-admins, or we can leave it up -- to this code to result in the refresh. It provides better data protection -- and encapsulate usage if we go with the latter, so we no longer have a -- special co-admin update function. Instead, if anything changes the list -- of co-admins it should call this function (RefreshConfigAdminUI). -- qf.cfglist:SetSelected (oldidx, true, true) ksk.RefreshSyncUI (true) end -- -- Refresh the config tab UI elements, optionally resetting all state -- variables. This will only ever really impact admins as they are the only -- ones that can see the tab. However, we do this for everybody to simplify -- the overall logic of the mod. For non-admins this will just be a little -- bit of busy work that will happen so quickly they won't even notice it. -- function ksk.RefreshConfigUI (reset) if (not ksk.currentid) then return end ksk.mainwin.cfgselector:SetValue (ksk.currentid) ksk.RefreshConfigLootUI (reset) ksk.RefreshConfigRollUI (reset) ksk.RefreshConfigAdminUI (reset) end
local skynet = require "skynet" local player_mgr = require "player_mgr" local match = require "match" local M = { tbl = {} } function M.chat(userid, msg) local p = player_mgr:get(userid) if not p then return end local broad = { wChairID = p.seat, nMsgID = msg.nMsgID } player_mgr:broadcast("protocol.ChatAck", broad) end -- 离开请求 function M.GAME_GameLeaveReq(userid, msg) match:GAME_GameLeaveReq(userid, msg) end -- 投票请求 function M.GAME_GameVoteReq(userid, msg) match:GAME_GameVoteReq(userid, msg) end -- 准备、取消准备 function M.GAME_ReadyReq(userid, msg) local p = player_mgr:get(userid) if not p then print("ready can't find player") return end if match.status ~= "ready" then print("nn not ready status") return end p:setReady(msg.bAgree) local broad = { wChairID = p.seat, bAgree = msg.bAgree } player_mgr:broadcast("nn.GAME_ReadyAck", broad) -- 所有人准备好了 if player_mgr:checkReady() then skynet.timeout(50, function() match:start() end) end end -- 开始 function M.GAME_BeginReq(_, _) end -- 抢庄、不抢庄 function M.GAME_GameBankReq(_, _) end -- 下注 function M.GAME_CallScoreReq(userid, msg) local p = player_mgr:get(userid) if not p then print("callscore can't find player") return end if match.status ~= "callscore" then print("nn not callscore status") return end local t = {1,3,5,10} local callscore = t[msg.nScoreIndex] or 1 p:call_score(1) local broad = { nCallScoreUser = p.seat, nCallScore = callscore } player_mgr:broadcast("nn.GAME_CallScoreAck", broad) -- 所有人下完注 if player_mgr:check_call_score() then match:fapai() match:result() end end function M.register() M.tbl = { ["protocol.ChatReq"] = M.chat, ["nn.GAME_GameLeaveReq"] = M.GAME_GameLeaveReq, ["nn.GAME_GameVoteReq"] = M.GAME_GameVoteReq, ["nn.GAME_ReadyReq"] = M.GAME_ReadyReq, ["nn.GAME_BeginReq"] = M.GAME_BeginReq, ["nn.GAME_GameBankReq"] = M.GAME_GameBankReq, ["nn.GAME_CallScoreReq"] = M.GAME_CallScoreReq } end function M.dispatch(userid, name, msg) local f = M.tbl[name] if f then f(userid, msg) else error("nn msg have no handler "..name) end end return M
-- This scriptlet was automatically -- generated from -- scripts/lactose.txt if rs4988235 == "G/G" then comment = "Lactose Tolerant" return risk, comment end if rs4988235 == "G/A" then comment = "Lactose Tolerant" return risk, comment end if rs4954490 == "A/A" then comment = "Lactose Tolerant" return risk, comment end if rs4954490 == "A/G" then comment = "Lactose Tolerant" return risk, comment end if rs869051967 == "C/C" then comment = "Lactose Tolerant" return risk, comment end if rs869051967 == "A/C" then comment = "Lactose Tolerant" return risk, comment end if rs41525747 == "C/C" then comment = "Lactose Tolerant" return risk, comment end if rs41525747 == "C/G" then comment = "Lactose Tolerant" return risk, comment end if rs41380347 == "C/C" then comment = "Lactose Tolerant" return risk, comment end if rs41380347 == "A/C" then comment = "Lactose Tolerant" return risk, comment end if rs145946881 == "G/G" then comment = "Lactose Tolerant" return risk, comment end if rs145946881 == "C/G" then comment = "Lactose Tolerant" return risk, comment end comment = "Lactose Intolerant"
vim.g.indent_blankline_show_current_context = true vim.g.indent_blankline_buftype_exclude = {'terminal'} vim.g.indent_blankline_filetype_exclude = {'help', 'startify', 'alpha', 'dashboard', 'packer', 'neogitstatus', 'NvimTree'} vim.g.indent_blankline_char = '▏' vim.g.indent_blankline_use_treesitter = true vim.g.indent_blankline_show_trailing_blankline_indent = false
local vim = vim local cfg = require("tmux.configuration") local keymaps = require("tmux.keymaps") local wrapper = require("tmux.wrapper") local function winnr(direction) return vim.api.nvim_call_function("winnr", { direction }) end local function resize(axis, direction, step_size) local command = "resize " if axis == "x" then command = "vertical resize " end return vim.api.nvim_command(command .. direction .. step_size) end local function is_only_window() return (winnr("1h") == winnr("1l")) and (winnr("1j") == winnr("1k")) end local function is_tmux_target(border) return wrapper.is_tmux and wrapper.has_neighbor(border) or is_only_window() end local M = {} function M.setup() if cfg.options.resize.enable_default_keybindings then keymaps.register("n", { ["<A-h>"] = [[<cmd>lua require'tmux'.resize_left()<cr>]], ["<A-j>"] = [[<cmd>lua require'tmux'.resize_bottom()<cr>]], ["<A-k>"] = [[<cmd>lua require'tmux'.resize_top()<cr>]], ["<A-l>"] = [[<cmd>lua require'tmux'.resize_right()<cr>]], }) end end function M.to_left() local is_border = winnr() == winnr("1l") if is_border and is_tmux_target("l") then wrapper.resize("h") elseif is_border then resize("x", "+", cfg.options.resize.resize_step_x) else resize("x", "-", cfg.options.resize.resize_step_x) end end function M.to_bottom() local is_border = winnr() == winnr("1j") if is_border and is_tmux_target("j") then wrapper.resize("j") elseif is_border and winnr() ~= winnr("1k") then resize("y", "-", cfg.options.resize.resize_step_y) else resize("y", "+", cfg.options.resize.resize_step_y) end end function M.to_top() local is_border = winnr() == winnr("1j") if is_border and is_tmux_target("j") then wrapper.resize("k") elseif is_border then resize("y", "+", cfg.options.resize.resize_step_y) else resize("y", "-", cfg.options.resize.resize_step_y) end end function M.to_right() local is_border = winnr() == winnr("1l") if is_border and is_tmux_target("l") then wrapper.resize("l") elseif is_border then resize("x", "-", cfg.options.resize.resize_step_x) else resize("x", "+", cfg.options.resize.resize_step_x) end end return M
banned = "EFSo7" function onEnter(newPlayer)
local json = require 'cjson' local common = { -- reserved RUNNING = "RESERVED:RUNNINGJOBS", -- hash RUNNINGSINCE = "RESERVED:RUNNINGTIMES", -- hash FAILED = "RESERVED:FAILEDJOBS", -- hash FAILED_ERROR = "RESERVED:FAILEDERROR", -- hash FAILEDTIME = "RESERVED:FAILEDTIME", -- sorted set CLEANUP = "RESERVED:CLEANUP:", -- list of jobs failed per queue, awaiting cleanup } return common
ITEM.name = "Storm Trooper Uniform" ITEM.description = "A white plastoid composite worn over a black body glove." ITEM.category = "Armor" ITEM.model = "models/props_junk/cardboard_box001a.mdl" ITEM.width = 1 ITEM.height = 1 ITEM.outfitCategory = "Empire" ITEM.newSkin = 1 ITEM.replacements = "models/player/venator/anh2/anh_stormtrooper2.mdl"
-- Clear weather. This is the default weather local clear = StormFox2.Weather.Add( "Clear" ) local windy = 8 -- Description if CLIENT then function clear:GetName(nTime, nTemp, nWind, bThunder, nFraction ) local b_windy = StormFox2.Wind.GetBeaufort(nWind) >= windy if b_windy then return language.GetPhrase("#sf_weather.clear.windy") end return language.GetPhrase("#sf_weather.clear") end else function clear:GetName(nTime, nTemp, nWind, bThunder, nFraction ) local b_windy = StormFox2.Wind.GetBeaufort(nWind) >= windy if b_windy then return "Windy" end return "Clear" end end -- Icon local m1,m2,m3,m4 = (Material("stormfox2/hud/w_clear.png")),(Material("stormfox2/hud/w_clear_night.png")),(Material("stormfox2/hud/w_clear_windy.png")),(Material("stormfox2/hud/w_clear_cold.png")) function clear.GetSymbol( nTime ) -- What the menu should show return m1 end function clear.GetIcon( nTime, nTemp, nWind, bThunder, nFraction) -- What symbol the weather should show local b_day = StormFox2.Time.IsDay(nTime) local b_cold = nTemp < -2 local b_windy = StormFox2.Wind.GetBeaufort(nWind) >= windy if b_windy then return m3 elseif b_cold then return m4 elseif b_day then return m1 else return m2 end end -- Day clear:SetSunStamp("topColor",Color(91, 127.5, 255), SF_SKY_DAY) clear:SetSunStamp("bottomColor",Color(204, 255, 255), SF_SKY_DAY) clear:SetSunStamp("fadeBias",0.2, SF_SKY_DAY) clear:SetSunStamp("duskColor",Color(255, 255, 255), SF_SKY_DAY) clear:SetSunStamp("duskIntensity",1.94, SF_SKY_DAY) clear:SetSunStamp("duskScale",0.29, SF_SKY_DAY) clear:SetSunStamp("sunSize",20, SF_SKY_DAY) clear:SetSunStamp("sunColor",Color(255, 255, 255), SF_SKY_DAY) clear:SetSunStamp("starFade",0, SF_SKY_DAY) --clear:SetSunStamp("fogDensity",0.8, SF_SKY_DAY) -- Night clear:SetSunStamp("topColor",Color(0,0,0), SF_SKY_NIGHT) clear:SetSunStamp("bottomColor",Color(0, 1.5, 5.25), SF_SKY_NIGHT) clear:SetSunStamp("fadeBias",0.12, SF_SKY_NIGHT) clear:SetSunStamp("duskColor",Color(9, 9, 0), SF_SKY_NIGHT) clear:SetSunStamp("duskIntensity",0, SF_SKY_NIGHT) clear:SetSunStamp("duskScale",0, SF_SKY_NIGHT) clear:SetSunStamp("sunSize",0, SF_SKY_NIGHT) clear:SetSunStamp("starFade",100, SF_SKY_NIGHT) --clear:SetSunStamp("fogDensity",1, SF_SKY_NIGHT) -- Sunset -- Old Color(170, 85, 43) clear:SetSunStamp("topColor",Color(130.5, 106.25, 149), SF_SKY_SUNSET) clear:SetSunStamp("bottomColor",Color(204, 98, 5), SF_SKY_SUNSET) clear:SetSunStamp("fadeBias",1, SF_SKY_SUNSET) clear:SetSunStamp("duskColor",Color(248, 103, 30), SF_SKY_SUNSET) clear:SetSunStamp("duskIntensity",3, SF_SKY_SUNSET) clear:SetSunStamp("duskScale",0.6, SF_SKY_SUNSET) clear:SetSunStamp("sunSize",15, SF_SKY_SUNSET) clear:SetSunStamp("sunColor",Color(198, 170, 59), SF_SKY_SUNSET) clear:SetSunStamp("starFade",30, SF_SKY_SUNSET) --clear:SetSunStamp("fogDensity",0.8, SF_SKY_SUNSET) -- Sunrise clear:SetSunStamp("topColor",Color(130.5, 106.25, 149), SF_SKY_SUNRISE) clear:SetSunStamp("bottomColor",Color(204, 98, 5), SF_SKY_SUNRISE) clear:SetSunStamp("fadeBias",1, SF_SKY_SUNRISE) clear:SetSunStamp("duskColor",Color(248, 103, 30), SF_SKY_SUNRISE) clear:SetSunStamp("duskIntensity",3, SF_SKY_SUNRISE) clear:SetSunStamp("duskScale",0.6, SF_SKY_SUNRISE) clear:SetSunStamp("sunSize",15, SF_SKY_SUNRISE) clear:SetSunStamp("sunColor",Color(198, 170, 59), SF_SKY_SUNRISE) clear:SetSunStamp("starFade",30, SF_SKY_SUNRISE) clear:SetSunStamp("fogDensity",0.8, SF_SKY_SUNRISE) -- Cevil clear:CopySunStamp( SF_SKY_NIGHT, SF_SKY_CEVIL ) -- Copy the night sky clear:SetSunStamp("fadeBias",1, SF_SKY_CEVIL) clear:SetSunStamp("sunSize",0, SF_SKY_CEVIL) -- Default variables. These don't change. clear:Set("moonColor", Color( 205, 205, 205 )) clear:Set("moonSize",30) clear:Set("moonTexture", ( Material( "stormfox2/effects/moon/moon.png" ) )) clear:Set("skyVisibility",100) -- Blocks out the sun/moon clear:Set("mapDayLight",100) clear:Set("mapNightLight",0) clear:Set("clouds",0) clear:Set("HDRScale",0.7) clear:Set("fogDistance", 400000) clear:Set("fogIndoorDistance", 3000) --clear:Set("fogEnd",90000) --clear:Set("fogStart",0) -- Static values clear:Set("starSpeed", 0.001) clear:Set("starScale", 2.2) clear:Set("starTexture", "skybox/starfield") clear:Set("enableThunder") -- Tells the generator that this weather_type can't have thunder. -- 2D skyboxes if SERVER then local t_day, t_night, t_sunrise, t_sunset t_day = {"sky_day01_05", "sky_day01_04", "sky_day02_01","sky_day02_03","sky_day02_04","sky_day02_05"} t_sunrise = {"sky_day01_05", "sky_day01_06", "sky_day01_08"} t_sunset = {"sky_day02_02", "sky_day02_01"} t_night = {"sky_day01_09"} clear:SetSunStamp("skyBox",t_day, SF_SKY_DAY) clear:SetSunStamp("skyBox",t_sunrise, SF_SKY_SUNRISE) clear:SetSunStamp("skyBox",t_sunset, SF_SKY_SUNSET) clear:SetSunStamp("skyBox",t_night, SF_SKY_NIGHT) end
local ReplicatedStorage = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local LocalPlayer = Players.LocalPlayer local component = script.Parent local lib = ReplicatedStorage:WaitForChild("lib") local common = ReplicatedStorage:WaitForChild("common") local Selectors = require(common:WaitForChild("Selectors")) local getAssetModel = require(common.util:WaitForChild("getAssetModel")) local Roact = require(lib:WaitForChild("Roact")) local RoactRodux = require(lib:WaitForChild("RoactRodux")) local ModelViewFrame = require(component:WaitForChild("ModelViewFrame")) local AssetButton = Roact.PureComponent:extend("AssetButton") function AssetButton:init(initialProps) self:setState( function() return { hovered = false, } end) end function AssetButton:render() local hovered = self.state.hovered local equipped = self.props.equipped local asset = self.props.asset if not asset then error("Asset not supplied to AssetButton element!") end local children = {} local checkmark if equipped then checkmark = Roact.createElement("ImageLabel", { Size = UDim2.new(0,24,0,24), AnchorPoint = Vector2.new(1,1), Position = UDim2.new(1,-4,1,-4), Image = "rbxassetid://2637717600", ImageColor3 = Color3.fromRGB(2, 183, 87), BackgroundColor3 = Color3.fromRGB(255,255,255), BorderSizePixel = 0, }) end local thumbnailImage if asset.thumbnailImage then thumbnailImage = Roact.createElement("ImageLabel", { Image = asset.thumbnailImage, Size = UDim2.new(1,0,1,0), BackgroundTransparency = 1, }) end local modifiers = {} modifiers.listLayout = Roact.createElement("UIListLayout", { FillDirection = Enum.FillDirection.Horizontal, HorizontalAlignment = Enum.HorizontalAlignment.Right, Padding = UDim.new(0,4), }) if (asset.metadata or {}).isRainbow then modifiers.rainbow = Roact.createElement("ImageLabel", { BackgroundTransparency = 1, Image = "rbxassetid://3213669223", Size = UDim2.new(0,16,0,16), }) end local modifiersFrame = Roact.createElement("Frame",{ BackgroundTransparency = 1, Size = UDim2.new(1,-8,0,16), Position = UDim2.new(1,-4,0,4), AnchorPoint = Vector2.new(1,0), }, modifiers) children.padding = Roact.createElement("UIPadding", { PaddingLeft = UDim.new(0,8), PaddingTop = UDim.new(0,8), PaddingRight = UDim.new(0,8), PaddingBottom = UDim.new(0,8), }) children.gamutGrid = Roact.createElement("ImageLabel", { Size = UDim2.new(1,0,1,0), Image = "rbxassetid://711821509", ScaleType = Enum.ScaleType.Tile, TileSize = UDim2.new(0,256,0,256), BorderColor3 = hovered and Color3.fromRGB(204, 204, 204) or Color3.fromRGB(230, 230, 230), ImageColor3 = Color3.fromRGB(223, 223, 223), BackgroundColor3 = Color3.fromRGB(255,255,255), }, { viewport = Roact.createElement(ModelViewFrame, { model = getAssetModel(self.props.asset.id), Size = UDim2.new(1,0,1,0), ImageColor3 = self.props.blackout and Color3.new(0,0,0) or Color3.new(1,1,1) }, { isEquipped = checkmark, modifiers = modifiersFrame, thumbnailImage = thumbnailImage, }) }) return Roact.createElement("TextButton", { BackgroundColor3 = hovered and Color3.fromRGB(223, 223, 223) or Color3.fromRGB(255,255,255), BorderColor3 = hovered and Color3.fromRGB(204, 204, 204) or Color3.fromRGB(230, 230, 230), AutoButtonColor = false, LayoutOrder = self.props.LayoutOrder or 0, Text = "", [Roact.Event.MouseButton1Click] = function() self.props.onClick(self.props.asset.id,self.props.equipped) end, [Roact.Event.MouseEnter] = function() self:setState( function() return { hovered = true, } end) end, [Roact.Event.MouseLeave] = function() self:setState( function() return { hovered = false, } end) end, }, children) end local function mapStateToProps(state, props) return { equipped = Selectors.isEquipped(state, LocalPlayer, props.asset.id) } end AssetButton = RoactRodux.connect(mapStateToProps,nil)(AssetButton) return AssetButton
local M = {} local buffer = require("termmaker.buffer") local event = require("termmaker.event") local window = require("termmaker.window") local default_opts = { cmd = { vim.env.SHELL }, env = nil, clear_env = false, kill_on_exit = true, window_opts = { window_factory = window.current(), } } -- Terminal represents a single terminal inside neovim. -- -- An instance of Terminal may be visible in a window or may currently be -- hidden. M.Terminal = {} M.Terminal.__index = M.Terminal setmetatable(M.Terminal, { __call = function(cls, ...) return cls.new(...) end, }) function M.Terminal.new(opts) local self = setmetatable({}, M.Terminal) opts = vim.tbl_extend("keep", opts or {}, default_opts) self._buf = nil self._win = nil self._job_id = 0 self._opts = opts if opts.kill_on_exit then event.add_autocmd("ExitPre", function() self:kill() end) end return self end function M.Terminal:open() if not self:has_buffer() then self:_init_buffer() end if not self:has_window() then self:_init_window() end self._win:jump() if self._job_id == 0 then self._job_id = vim.fn.termopen(self._opts.cmd, { env = self._opts.env, clear_env = self._opts.clear_env, on_exit = function() self:_on_exit() end, }) end end function M.Terminal:_init_buffer() self._buf = buffer.Buffer(self._opts.buffer_opts) self._buf:register(buffer.win_leave, function() self:close() return false end) end function M.Terminal:_init_window() self._win = window.Window(self._opts.window_opts) self._win:show_buffer(self._buf) end function M.Terminal:_on_exit() self:close() self._buf:kill() self._job_id = 0 end function M.Terminal:close() if not self:has_window() then return end self._win:restore() self._win = nil end function M.Terminal:kill() self:close() if self._job_id ~= 0 then vim.fn.jobstop(self._job_id) -- Do not wait for the terminal to stop. According to :h jobstop -- Neovim will send SIGKILL if the job did not terminate after a -- timeout. We are thus happy to know, that Neovim does all it can -- to get rid of the job. self._job_id = 0 end end function M.Terminal:toggle() if self:has_window() and self._win:is_current() then -- Only close the window if it is the current window. Otherwise -- it is more likely that the user wanted to select it, which is -- done by open. self:close() else self:open() end end function M.Terminal:has_window() return self._win and self._win:is_valid() end function M.Terminal:has_buffer() return self._buf and self._buf:is_valid() end return M
-- FactoCord.ext modifications start local function log_message(event, msg) print (event.tick .. " [FactoCord] " .. msg) -- game.write_file("server.log", msg .. "\n", true) end local function log_player_message(event, msg_in) local msg = "Player " .. game.players[event.player_index].name .. " " .. msg_in .. "." log_message (event, msg) -- game.write_file("server.log", msg .. "\n", true) end local function log_player_death_message(event, msg_in) local cs = event.cause.name local msg = "" .. game.players[event.player_index].name .. " has been killed by some " .. cs .. "! ROFL!" log_message (event, msg) -- game.write_file("server.log", msg .. "\n", true) end local function log_research_message(event, msg_in) local msg = msg_in .. " \"" .. event.research.name .. "\"" log_message (event, msg) --for _, player in pairs(game.players) do -- player.print{event.research.localised_name[1]} --end -- game.write_file("server.log", msg .. "\n", true) end script.on_event(defines.events.on_player_died, function(event) log_player_death_message(event, "") end) script.on_event(defines.events.on_research_started, function(event) log_research_message(event, "Started research of") end) script.on_event(defines.events.on_research_finished, function(event) log_research_message(event, "Research finished for") end) script.on_event(defines.events.on_rocket_launched, function(event) log_message("A rocket was launched.") end) -- FactoCord.ext modifications end
local scriptLocations = { ["commonAPI"] = "commonAPI.lua", ["autoAcacia"] = "treeFarming/autoAcacia.lua", ["autoTreeV3"] = "treeFarming/autoTreeV3.lua", ["acacia"] = "treeFarming/acacia.lua", ["autoFarm"] = "cropFarming/autoFarm.lua", } return scriptLocations
module(..., package.seeall) require("lua_tda") require "lpeg" require "dialog_utilities" require "core" require "dialog_utilities" joProfile = require "OWLGrEd_UserFields.Profile" syncProfile = require "OWLGrEd_UserFields.syncProfile" styleMechanism = require "OWLGrEd_UserFields.styleMechanism" viewMechanism = require "OWLGrEd_UserFields.viewMechanism" serialize = require "serialize" local report = require("reporter.report") --atver formu ar visiem profiliem projektaa function profileMechanism() report.event("StylePaletteWindow_ManageViewsAndExtensions", { GraphDiagramType = "projectDiagram" }) local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.close()") }) local form = lQuery.create("D#Form", { id = "allProfiles" ,caption = "Profiles in project" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = close_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.close()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#HorizontalBox" ,{ component = { lQuery.create("D#VerticalBox", { id = "VerticalBoxWithListBox" ,component = { lQuery.create("D#ListBox", { id = "ListWithProfiles" ,item = collectProfiles() }) } }) ,lQuery.create("D#VerticalBox", { component = { lQuery.create("D#Button", { caption = "Properties (user fields)" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.openProfileProperties()") }) ,lQuery.create("D#Button", { caption = "Profile views" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.viewMechanism.viewMechanism()") }) ,lQuery.create("D#Row",{component = { lQuery.create("D#Label", {caption = ""}) }}) ,lQuery.create("D#Button", { caption = "New" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.newProfile()") }) ,lQuery.create("D#Button", { caption = "Import" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.import()") }) ,lQuery.create("D#Button", { caption = "Export" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.load()") }) ,lQuery.create("D#Button", { caption = "Default for views" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.defaultForViews()") }) ,lQuery.create("D#Row",{component = { lQuery.create("D#Label", {caption = ""}) }}) ,lQuery.create("D#Button", { caption = "Delete" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.deleteProfile()") }) ,lQuery.create("D#Button", { caption = "Advanced.." ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.advenced()") }) } }) }}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end function advenced() local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeAdvanced()") }) local form = lQuery.create("D#Form", { id = "AdvencedManegement" ,caption = "Advanced profile management" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = close_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeAdvanced()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#HorizontalBox" ,{ component = { lQuery.create("D#VerticalBox", { component = { lQuery.create("D#Row", { component = { lQuery.create("D#Button", { caption = "Save profile snapshot" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.saveProfileSnapshot()") }) ,lQuery.create("D#Label", {caption="Export all profile definitions to OWLGrEd_UserFields/snapshot folder"}) } }) ,lQuery.create("D#Row", { component = { lQuery.create("D#Button", { caption = "Restore from snapshot" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.restoreFromSnapshot()") }) ,lQuery.create("D#Label", {caption="Import all profile definitions from OWLGrEd_UserFields/snapshot folder"}) } }) ,lQuery.create("D#Row", { component = { lQuery.create("D#Button", { caption = "Manage configuration" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.configuration.configurationProperty()") }) ,lQuery.create("D#Label", {caption="Open form for field context and profile tag management"}) } }) } }) }}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end function MakeDir(path) lfs = require("lfs") lfs.mkdir(path) end function restoreFromSnapshot() local start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\snapshot\\" local path = start_folder .. "\\snapshot.txt" serialize.import_from_file(path) local configuration = lQuery("AA#Configuration"):first() lQuery("AA#ContextType"):each(function(obj) obj:remove_link("configuration", obj:find("/configuration")) end) lQuery("AA#ContextType"):link("configuration", configuration) lQuery("AA#TagType"):each(function(obj) obj:remove_link("configuration", obj:find("/configuration")) end) lQuery("AA#TagType"):link("configuration", configuration) lQuery("AA#Configuration"):filter(function(obj) return obj:id() ~= configuration:id() end):delete() lQuery("AA#Profile"):remove_link("configuration", lQuery("AA#Profile/configuration")) lQuery("AA#Profile"):link("configuration", lQuery("AA#Configuration")) -- izmest dublikatus -- atrast visus AA#ContextType -- iziet cauri visiem. Ja ir vairki ar viendu id, tad izdzest to, kam nav AA#Field lQuery("AA#ContextType"):each(function(obj) local id = obj:attr("id") local eq = lQuery("AA#ContextType[id = '" .. id .."']") if eq:size()>1 then if obj:find("/fieldInContext"):is_empty() then obj:delete() else eq:filter(function(ct) return ct:attr("id") ~= obj:attr("id") end):delete() end end end) lQuery("AA#TagType"):each(function(obj) local tt = lQuery("AA#TagType[key='" .. obj:attr("key") .. "'][notation='" .. obj:attr("notation") .. "'][rowType='" .. obj:attr("rowType") .. "']") if tt:size()>1 then obj:delete() end end) --jaatrod profila vards --jaatrod tas profils, kam nav saderibas local profileName lQuery("AA#Profile"):each(function(obj) if lQuery("Extension[id='" .. obj:attr("name") .. "'][type='aa#Profile']"):is_empty() then profileName = obj:attr("name") local ext = lQuery.create("Extension", {id = profileName, type = "aa#Profile"})--:link("aa#owner", lQuery("Extension[id = 'OWL_Fields']")) lQuery("Extension[id = 'OWL_Fields']"):link("aa#subExtension", ext) lQuery("AA#Profile[name='" .. profileName .. "']/view"):each(function(prof) if ext:find("/aa#subExtension[id='" .. prof:attr("name") .. "'][type='aa#View']"):is_empty() then lQuery.create("Extension", {id=prof:attr("name"), type="aa#View"}):link("aa#owner", ext) :link("aa#graphDiagram", lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])")) end end) syncProfile.syncProfile(profileName) end end) styleMechanism.syncExtensionViews() --atjaunot listBox refreshListBox() end function saveProfileSnapshot() local objects_to_export = lQuery("AA#Configuration") local export_spec = { include = { ["AA#Configuration"] = { context = serialize.export_as_table ,profile = serialize.export_as_table ,tagType = serialize.export_as_table } ,["AA#Profile"] = { field = serialize.export_as_table ,view = serialize.export_as_table ,tag = serialize.export_as_table } ,["AA#TagType"] = {} ,["AA#ContextType"] = { fieldInContext = serialize.export_as_table } ,["AA#View"] = { styleSetting = serialize.export_as_table } ,["AA#Field"] = { tag = serialize.export_as_table ,translet = serialize.export_as_table ,selfStyleSetting = serialize.export_as_table ,dependency = serialize.export_as_table ,choiceItem = serialize.export_as_table ,subField = serialize.export_as_table } ,["AA#ChoiceItem"] = { tag = serialize.export_as_table ,styleSetting = serialize.export_as_table ,dependency = serialize.export_as_table } ,["AA#Tag"] = {} ,["AA#Translet"] = {} ,["AA#Dependency"] = {} ,["AA#FieldStyleSetting"] = {} ,["AA#ViewStyleSetting"] = {} }, border = { ["AA#Field"] = { -- fieldType = serialize.make_exporter(function(object) -- return "AA#RowType[typeName=" .. lQuery(object):attr("typeName") .. "]" -- end) } ,["AA#Translet"] = { task = serialize.make_exporter(function(object) return "AA#TransletTask[taskName=" .. lQuery(object):attr("taskName") .. "]" end) } ,["AA#FieldStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } ,["AA#ViewStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } } } MakeDir(tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\snapshot") local start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\snapshot\\" local path = start_folder .. "\\snapshot.txt" serialize.save_to_file(objects_to_export, export_spec, path) end --padara profilu nokluseto prieks skatijumiem function defaultForViews() --izveletais profils local selectedItem = lQuery("D#ListBox[id='ListWithProfiles']/selected") if selectedItem:is_not_empty() then local profileName = selectedItem:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end --nedrikst padarit profilu nokluseto, ja zem ta ir izveidoti lauki if selectedItem:is_not_empty() and lQuery("AA#Profile[name='" .. profileName .. "']/field"):is_empty() then if lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews")=="true" then lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews", false) refreshListBox() else if lQuery("AA#Profile[isDefaultForViews='true']"):is_empty() then lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews", true) refreshListBox() else showNotificationForm() end end --atjaunot listBox --refreshListBox() end end end function showNotificationForm() local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") local close_button = lQuery.create("D#Button", { caption = "No" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noChangeDefaultForViews()") }) local create_button = lQuery.create("D#Button", { caption = "Yes" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.yesChangeDefaultForViews()") }) local form = lQuery.create("D#Form", { id = "changeDefaultForViews" ,caption = "Confirmation" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noChangeDefaultForViews()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption="Do you want to save the profile for auto loading?"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,component = {create_button, close_button}}) } }) dialog_utilities.show_form(form) end function noChangeDefaultForViews() lQuery("D#Event"):delete() utilities.close_form("changeDefaultForViews") end function yesChangeDefaultForViews() local selectedItem = lQuery("D#ListBox[id='ListWithProfiles']/selected") local profileName = selectedItem:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end lQuery("AA#Profile"):attr("isDefaultForViews", false) lQuery("AA#Profile[name='" .. profileName .. "']"):attr("isDefaultForViews", true) noChangeDefaultForViews() refreshListBox() end --atver profila konfiguracijas formu function openProfileProperties() local selectedItem = lQuery("D#ListBox[id='ListWithProfiles']/selected") if selectedItem:is_not_empty() then local profileName = selectedItem:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end if selectedItem:is_not_empty() and lQuery("AA#Profile[name='" .. profileName.. "']"):attr("isDefaultForViews")~="true" then joProfile.Profile(profileName) else pleaseSelectNotDefaultProfile("Please use a profile that is not default for views to enter and manage user field definitions") end else pleseSelectProfile() end end function pleseSelectProfile() local close_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") }) local form = lQuery.create("D#Form", { id = "contextTypesMissing" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption = "Please select a profile"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" --,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end --izdzes profilu no projekta function deleteProfile() --atrast profilu local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local profileName = profileName:attr("value") local viewSize = string.find(profileName, " ") if viewSize~=nil then profileName = string.sub(profileName, 1, viewSize-1) end local profile = lQuery("AA#Profile[name = '" .. profileName .. "']") --izdzest AA# Dalu lQuery(profile):find("/field"):each(function(obj) deleteField(obj) end) --saglabajam stilus lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])"):each(function(diagram) utilities.execute_cmd("SaveDgrCmd", {graphDiagram = diagram}) end) --palaist sinhronizaciju syncProfile.syncProfile(profileName) viewMechanism.deleteViewFromProfile(profileName) --izdzest profilu, extension lQuery(profile):delete() lQuery("Extension[id='" .. profileName .. "'][type='aa#Profile']"):delete() --atjaunot listBox refreshListBox() end end --izdzes lietotaja defineto lauku un visu, kas ir saistits ar to (field-dzesamais lauks) function deleteField(field) lQuery(field):find("/tag"):delete() lQuery(field):find("/translet"):delete() lQuery(field):find("/dependency"):delete() lQuery(field):find("/selfStyleSetting"):delete() lQuery(field):find("/choiceItem/tag"):delete() lQuery(field):find("/choiceItem/styleSetting"):delete() lQuery(field):find("/choiceItem"):delete() --lQuery(field):find("/fieldType"):remove_link("field", field) lQuery(field):find("/subField"):each(function(obj) deleteField(obj) end) lQuery(field):delete() end --atver formu jauno profilu veidosanai function newProfile() local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeNewProfileForm()") }) local create_button = lQuery.create("D#Button", { caption = "Create" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.createNewProfile()") }) local form = lQuery.create("D#Form", { id = "newProfile" ,caption = "Create new profile" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeNewProfileForm()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#InputField", { id = "InputFieldForNewProfile" ,text = "" }) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,horizontalAlignment = 1 ,component = {create_button, close_button}}) } }) dialog_utilities.show_form(form) end --izveido jaunu profilu function createNewProfile() local newProfileValue = lQuery("D#InputField[id='InputFieldForNewProfile']"):attr("text") if newProfileValue ~="" then closeNewProfileForm() --izveidojam profilu local profile = lQuery.create("AA#Profile", {name = newProfileValue}):link("configuration", lQuery("AA#Configuration")) local profileExtension = lQuery.create("Extension", {id = newProfileValue, type = "aa#Profile"}):link("aa#owner", lQuery("Extension[id = 'OWL_Fields']")) --izveidojam nokluseto skatijumu -- lQuery.create("AA#View", {name = "Default", isDefault = 1}):link("profile", profile) -- lQuery.create("Extension", {id = "Default", type = "aa#View"}):link("aa#owner", profileExtension) --atverm profila configuracijas formu -- joProfile.Profile(newProfileValue) --atjaunot listBox refreshListBox() end end --atjauno sarakstu ar profiliem function refreshListBox() lQuery("D#ListBox[id='ListWithProfiles']"):delete() lQuery.create("D#ListBox", { id = "ListWithProfiles" ,item = collectProfiles() }):link("container", lQuery("D#VerticalBox[id='VerticalBoxWithListBox']")) lQuery("D#VerticalBox[id='VerticalBoxWithListBox']"):link("command", utilities.enqued_cmd("D#Command", {info = "Refresh"})) end --savac visus profilus no projekta function collectProfiles() local values = lQuery("AA#Profile"):map( function(obj) return {lQuery(obj):attr("name"), lQuery(obj):attr("isDefaultForViews")} end) return lQuery.map(values, function(profile) local profileName = profile[1] if profile[2]=="true" then profileName = profileName .. " (Default for views)" end return lQuery.create("D#Item", { value = profileName }) end) end function anywhere (p) return lpeg.P{ p + 1 * lpeg.V(1) } end --ielade profilu no teksta faila function import() caption = "Select text file" filter = "text file(*.txt)" start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\examples\\" start_file = "" save = false local path = tda.BrowseForFile(caption, filter, start_folder, start_file, save) if path ~= "" then f = assert(io.open(path, "r")) local t = f:read("*all") f:close() local contextTypeTable = {} local Letter = lpeg.R("az") + lpeg.R("AZ") + lpeg.R("09") + lpeg.S("_/:#.<>='(){}?!@$%^&*-+|") local String = lpeg.C(Letter * (Letter) ^ 0) local ct = lpeg.P("AA#ContextType[id=") local compartTypeTable = {} local ctP = (ct * String * "]") ctP = lpeg.P(ctP) ctP = lpeg.Cs((ctP/(function(a) table.insert(compartTypeTable, a) end) + 1)^0) lpeg.match(ctP, t) local l = 0 for i,v in pairs(compartTypeTable) do if lQuery("AA#ContextType[id='" .. v .. "']"):is_empty() then l = 1 end end if l ~= 1 then local profileName local pat = lpeg.P([["AA#Profile", ["properties"] = { ["name"] = "]]) local p = pat * String * '"' p = anywhere (p) profileName = lpeg.match(p, t) or "" if lQuery("Extension[id='" .. profileName .. "'][type='aa#Profile']"):is_empty() then serialize.import_from_file(path) --izveidojam profilu if profileName == "" then lQuery("AA#Profile"):each(function(obj) if lQuery("Extension[id='" .. obj:attr("name") .. "'][type='aa#Profile']"):is_empty() then profileName = obj:attr("name") end end) end local ext = lQuery.create("Extension", {id = profileName, type = "aa#Profile"})--:link("aa#owner", lQuery("Extension[id = 'OWL_Fields']")) lQuery("Extension[id = 'OWL_Fields']"):link("aa#subExtension", ext) --ja ir saite uz AA#RowType, nonemam tas lQuery("AA#Field"):each(function(obj) local fieldType = obj:find("/fieldType") if fieldType:is_not_empty() then obj:attr("fieldType", fieldType:attr("typeName")) fieldType:remove_link("field", obj) end end) --izveidojam profila skatijumus lQuery("AA#Profile[name='" .. profileName .. "']/view"):each(function(obj) lQuery.create("Extension", {id = obj:attr("name"), type = "aa#View"}):link("aa#owner", ext) :link("aa#graphDiagram", lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])")) end) --saglabajam izmainas lQuery("GraphDiagram:has(/graphDiagramType[id='OWL'])"):each(function(diagram) utilities.execute_cmd("SaveDgrCmd", {graphDiagram = diagram}) end) lQuery("AA#Profile"):remove_link("configuration", lQuery("AA#Profile/configuration")) lQuery("AA#Profile"):link("configuration", lQuery("AA#Configuration")) --sinhronizejam profilu syncProfile.syncProfile(profileName) --sinhronizejam skatijumus styleMechanism.syncExtensionViews() --atjaunot listBox refreshListBox() else -- print("Import was canceled")--!!!!!!!!!!!! -- print("Profile with this name already exists")--!!!!!!!!!! end else contextTypesMissing() -- print("Import was canceled") -- print("Some ContextTypes are missing") -- print("Please create or load corresponding configuration.") end else --print("Import was canceled") end end function pleaseSelectNotDefaultProfile() local close_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") }) local form = lQuery.create("D#Form", { id = "contextTypesMissing" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption = "Please use a profile that is not default for views"}) ,lQuery.create("D#Label", {caption = "to enter and manage user field definitions"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" --,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end function contextTypesMissing() local close_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") }) local form = lQuery.create("D#Form", { id = "contextTypesMissing" ,caption = "Create new profile" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.closeContextTypesMissing()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption = "The profile to be imported requires extend profile configuration"}) ,lQuery.create("D#Label", {caption = "Please import the profiles configuration from"}) ,lQuery.create("D#Label", {caption = "'Advanced..'->'Manage configuration' form"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" --,horizontalAlignment = 1 ,component = {close_button}}) } }) dialog_utilities.show_form(form) end --parada dialoga logu ar jautajumu vai ir jaielade profils automatiski function load() local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local close_button = lQuery.create("D#Button", { caption = "No" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noLoadForm()") }) local create_button = lQuery.create("D#Button", { caption = "Yes" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.yesLoadForm(()") }) local form = lQuery.create("D#Form", { id = "loadProfile" ,caption = "Load profile" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noLoadFormClose()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption="Do you want to save the profile for auto loading?"}) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,component = {create_button, close_button}}) } }) dialog_utilities.show_form(form) end end function noLoadForm() local close_button = lQuery.create("D#Button", { caption = "Close" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.loadProfileNameClose()") }) local create_button = lQuery.create("D#Button", { caption = "Ok" ,eventHandler = utilities.d_handler("Click", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.noLoadFormExport()") }) local form = lQuery.create("D#Form", { id = "exportFileNameForm" ,caption = "Export file name" ,buttonClickOnClose = false ,cancelButton = close_button ,defaultButton = create_button ,eventHandler = utilities.d_handler("Close", "lua_engine", "lua.OWLGrEd_UserFields.profileMechanism.loadProfileNameClose()") ,component = { lQuery.create("D#VerticalBox",{ component = { lQuery.create("D#Label", {caption="Enter export file name"}) ,lQuery.create("D#InputField", { id = "exportFileName", text = lQuery("D#ListBox[id='ListWithProfiles']/selected"):attr("value") .. "_" .. os.date("%m_%d_%Y_%H_%M_%S") }) } }) ,lQuery.create("D#HorizontalBox", { id = "closeButton" ,component = {create_button, close_button}} ) } }) dialog_utilities.show_form(form) end function loadProfileNameClose() lQuery("D#Event"):delete() utilities.close_form("exportFileNameForm") end function noLoadFormClose() lQuery("D#Event"):delete() utilities.close_form("loadProfile") end function noLoadFormExport() export() lQuery("D#Event"):delete() utilities.close_form("loadProfile") end function yesLoadForm() lQuery("D#Event"):delete() utilities.close_form("loadProfile") local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local objects_to_export = lQuery("AA#Profile[name = '" .. profileName:attr("value") .. "']") local export_spec = { include = { ["AA#Profile"] = { field = serialize.export_as_table ,view = serialize.export_as_table ,tag = serialize.export_as_table } ,["AA#View"] = { styleSetting = serialize.export_as_table } ,["AA#Field"] = { tag = serialize.export_as_table ,translet = serialize.export_as_table ,selfStyleSetting = serialize.export_as_table ,dependency = serialize.export_as_table ,choiceItem = serialize.export_as_table ,subField = serialize.export_as_table } ,["AA#ChoiceItem"] = { tag = serialize.export_as_table ,styleSetting = serialize.export_as_table ,dependency = serialize.export_as_table } ,["AA#Tag"] = {} ,["AA#Translet"] = {} ,["AA#Dependency"] = {} ,["AA#FieldStyleSetting"] = {} ,["AA#ViewStyleSetting"] = {} }, border = { ["AA#Field"] = { context = serialize.make_exporter(function(object) return "AA#ContextType[id=" .. lQuery(object):attr("id") .. "]" end) -- ,fieldType = serialize.make_exporter(function(object) -- return "AA#RowType[typeName=" .. lQuery(object):attr("typeName") .. "]" -- end) } ,["AA#Translet"] = { task = serialize.make_exporter(function(object) return "AA#TransletTask[taskName=" .. lQuery(object):attr("taskName") .. "]" end) } ,["AA#FieldStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } ,["AA#ViewStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } } } start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\user\\AutoLoad\\" local path = start_folder .. "\\" .. profileName:attr("value") .. ".txt" serialize.save_to_file(objects_to_export, export_spec, path) end end --saglaba profilu teksta failaa function export() local profileName = lQuery("D#ListBox[id='ListWithProfiles']/selected") if profileName:is_not_empty() then local objects_to_export = lQuery("AA#Profile[name = '" .. profileName:attr("value") .. "']") local export_spec = { include = { ["AA#Profile"] = { field = serialize.export_as_table ,view = serialize.export_as_table ,tag = serialize.export_as_table } ,["AA#View"] = { styleSetting = serialize.export_as_table } ,["AA#Field"] = { tag = serialize.export_as_table ,translet = serialize.export_as_table ,selfStyleSetting = serialize.export_as_table ,dependency = serialize.export_as_table ,choiceItem = serialize.export_as_table ,subField = serialize.export_as_table } ,["AA#ChoiceItem"] = { tag = serialize.export_as_table ,styleSetting = serialize.export_as_table ,dependency = serialize.export_as_table } ,["AA#Tag"] = {} ,["AA#Translet"] = {} ,["AA#Dependency"] = {} ,["AA#FieldStyleSetting"] = {} ,["AA#ViewStyleSetting"] = { customStyleSetting = serialize.export_as_table } ,["AA#CustomStyleSetting"] = {} }, border = { ["AA#Field"] = { context = serialize.make_exporter(function(object) return "AA#ContextType[id=" .. lQuery(object):attr("id") .. "]" end) -- ,fieldType = serialize.make_exporter(function(object) -- return "AA#RowType[typeName=" .. lQuery(object):attr("typeName") .. "]" -- end) } ,["AA#Translet"] = { task = serialize.make_exporter(function(object) return "AA#TransletTask[taskName=" .. lQuery(object):attr("taskName") .. "]" end) } ,["AA#FieldStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } ,["AA#ViewStyleSetting"] = { fieldStyleFeature = serialize.make_exporter(function(object) return "AA#CompartStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) ,elemStyleFeature = serialize.make_exporter(function(object) return "AA#ElemStyleItem[itemName=" .. lQuery(object):attr("itemName") .. "]" end) } } } local deteTime = os.date("%m_%d_%Y_%H_%M_%S") caption = "select folder" start_folder = tda.GetProjectPath() .. "\\Plugins\\OWLGrEd_UserFields\\user\\" local folder = tda.BrowseForFolder(caption, start_folder) if folder ~= "" then local path = folder .. "\\" .. lQuery("D#InputField[id='exportFileName']"):attr("text") .. ".txt" serialize.save_to_file(objects_to_export, export_spec, path) loadProfileNameClose() else --print("Export was canceled") end end end function closeContextTypesMissing() lQuery("D#Event"):delete() utilities.close_form("contextTypesMissing") end function closeAdvanced() lQuery("D#Event"):delete() utilities.close_form("AdvencedManegement") end function close() lQuery("D#Event"):delete() utilities.close_form("allProfiles") end function closeNewProfileForm() lQuery("D#Event"):delete() utilities.close_form("newProfile") end
--- Lua-Telegram-Bot API. -- Supports Bot API 4.8 -- @module telegram local telegram = {} -- Load the submodules. telegram.request = require("telegram.modules.request") -- Load the structures. telegram.structures = require("telegram.structures") --- Upload files using `multipart/form-data`. -- @field filename The filename (string). -- @field data The file content, can be a string, or a io.* file, or a ltn12 source. -- @field len The file's content length, can be ommited when data is just a string. -- @table InputFile --- Set the bot's authorization token -- @tparam string token The bot's authorization token, e.x: (`123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`). function telegram.setToken(token) telegram.request("setToken", token) end --- Get the bot's authorization token -- @treturn ?string The bot's authorization token, e.x: (`123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`). function telegram.getToken() return select(2, telegram.request("getToken")) end --- Set the default timeout used for the API requests -- @tparam number timeout The new timeout value, -1 for no timeout. function telegram.setTimeout(timeout) telegram.request("setTimeout", timeout) end --- Use this method to receive incoming updates using long polling ([wiki](https://en.wikipedia.org/wiki/Push_technology#Long_polling)). -- -- **Notes:** -- -- 1. This method will not work if an outgoing webhook is set up. -- -- 2. In order to avoid getting duplicate updates, recalculate offset after each server response. -- -- @tparam ?number offset Identifier of the first update to be returned. -- Must be greater by one than the highest among the identifiers of previously received updates. -- By default, updates starting with the earliest unconfirmed update are returned. -- An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. -- The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. -- All previous updates will forgotten. -- @tparam ?number limit Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100. -- @tparam ?number timeout Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. -- @tparam ?{string} allowedUpdates An array of the update types you want your bot to receive. -- For example, specify `{“message”, “edited_channel_post”, “callback_query”}` to only receive updates of these types. -- See Update for a complete list of available update types. -- Specify an empty list to receive all updates regardless of type (default). -- If not specified, the previous setting will be used. -- @treturn {Update} Array of Update objects. -- @raise Error on failure. function telegram.getUpdates(offset, limit, timeout, allowedUpdates) local ok, data = telegram.request("getUpdates", {offset=offset, limit=limit, timeout=timeout, allowed_updates=allowedUpdates}, (timeout or 0) + 5) if not ok then return error(data) end for k,v in ipairs(data) do data[k] = telegram.structures.Update(v) end return data end --- A simple method for testing your bot's auth token, get information about the bot's user itself. -- @treturn User The bot's user object. -- @raise Error on failure. function telegram.getMe() local ok, data = telegram.request("getMe") if not ok then return error(data) end return telegram.structures.User(data) end --- Use this method to send text messages. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam string text Text of the message to be sent, 1-4096 characters after entities parsing. -- @tparam ?string parseMode `Markdown` or `HTML` if you want some markdown in the bot's messages. -- @tparam ?boolean disableWebPagePreview Disables link previews for links in this message. -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam ?number replyToMessageID If the message is a reply, ID of the original message. -- @tparam ?InlineKeyboardMarkup|ReplyKeyboardMarkup|ReplyKeyboardRemove|ForceReply|nil replyMarkup Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. -- @treturn Message The sent message. -- @raise Error on failure. function telegram.sendMessage(chatID, text, parseMode, disableWebPagePreview, disableNotification, replyToMessageID, replyMarkup) replyMarkup = replyMarkup and replyMarkup:getData() local ok, data = telegram.request("sendMessage", {chat_id=chatID, text=text, parse_mode=parseMode, disable_web_page_preview=disableWebPagePreview, disable_notification=disableNotification, reply_to_message_id=replyToMessageID, reply_markup=replyMarkup}) if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method to forward messages of any kind. -- @tparam number|string chatID Unique identifier for the target chat or username of the target channel (in the format `@channelusername`). -- @tparam number|string fromChatID Unique identifier for the chat where the original message was sent (or channel username in the format `@channelusername`). -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam number messageID Message identifier in the chat specified in `fromChatID`. -- @treturn Message The sent message. -- @raise Error on failure. function telegram.forwardMessage(chatID, fromChatID, disableNotification, messageID) local ok, data = telegram.request("forwardMessage", {chat_id=chatID, from_chat_id=fromChatID, disable_notification=disableNotification, message_id=messageID}) if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method to send photos. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam InputFile|string photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. [More info on Sending Files](https://core.telegram.org/bots/api#sending-files). -- @tparam ?string caption Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing -- @tparam ?string parseMode `Markdown` or `HTML` if you want some markdown in the file's caption. -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam ?number replyToMessageID If the message is a reply, ID of the original message. -- @tparam ?InlineKeyboardMarkup|ReplyKeyboardMarkup|ReplyKeyboardRemove|ForceReply|nil replyMarkup Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. -- @treturn Message The sent message. -- @raise Error on failure. function telegram.sendPhoto(chatID, photo, caption, parseMode, disableNotification, replyToMessageID, replyMarkup) replyMarkup = replyMarkup and replyMarkup:getData() local parameters = {chat_id=chatID, caption=caption, parse_mode=parseMode, disable_notification=disableNotification, reply_to_message_id=replyToMessageID, reply_markup=replyMarkup} local ok, data if type(photo) == "table" then ok, data = telegram.request("sendPhoto", parameters, nil, {photo=photo}) else parameters.photo = photo ok, data = telegram.request("sendPhoto", parameters) end if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method to send audio files, if you want Telegram clients to display them in the music player. -- Your audio must be in the .MP3 or .M4A format. -- Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. -- For sending voice messages, use the `sendVoice` method instead. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam InputFile|string audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. -- @tparam ?string caption Audio caption, 0-1024 characters after entities parsing. -- @tparam ?string parseMode `Markdown` or `HTML` if you want some markdown in the audio's caption. -- @tparam ?number duration Duration of the audio in seconds. -- @tparam ?string performer Performer. -- @tparam ?string title Track name. -- @tparam ?InputFile|string|nil thumb Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass `attach://<file_attach_name>` if the thumbnail was uploaded using multipart/form-data under `<file_attach_name>`. -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam ?number replyToMessageID If the message is a reply, ID of the original message. -- @tparam ?InlineKeyboardMarkup|ReplyKeyboardMarkup|ReplyKeyboardRemove|ForceReply|nil replyMarkup Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. -- @treturn Message The sent message. -- @raise Error on failure. function telegram.sendAudio(chatID, audio, caption, parseMode, duration, performer, title, thumb, disableNotification, replyToMessageID, replyMarkup) replyMarkup = replyMarkup and replyMarkup:getData() local parameters = {chat_id=chatID, caption=caption, parse_mode=parseMode, duration=duration, performer=performer, title=title, disable_notification=disableNotification, reply_to_message_id=replyToMessageID, reply_markup=replyMarkup} local ok, data if type(audio) == "table" or type(thumb) == "table" then local files = {} if type(audio) == "table" then files.audio = audio else parameters.audio = audio end if type(thumb) == "table" then files.thumb = thumb parameters.thumb = "attach://"..thumb.filename else parameters.thumb = thumb end ok, data = telegram.request("sendAudio", parameters, nil, files) else parameters.audio = audio parameters.thumb = thumb ok, data = telegram.request("sendAudio", parameters) end if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method to send general files. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam InputFile|string document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. [More info on Sending Files](https://core.telegram.org/bots/api#sending-files). -- @tparam ?InputFile|string|nil thumb Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can’t be reused and can be only uploaded as a new file. [More info on Sending Files](https://core.telegram.org/bots/api#sending-files). -- @tparam ?string caption Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. -- @tparam ?string parseMode `Markdown` or `HTML` if you want some markdown in the file's caption. -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam ?number replyToMessageID If the message is a reply, ID of the original message. -- @tparam ?InlineKeyboardMarkup|ReplyKeyboardMarkup|ReplyKeyboardRemove|ForceReply|nil replyMarkup Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. -- @treturn Message The sent message. -- @raise Error on failure. function telegram.sendDocument(chatID, document, thumb, caption, parseMode, disableNotification, replyToMessageID, replyMarkup) replyMarkup = replyMarkup and replyMarkup:getData() local parameters = {chat_id=chatID, caption=caption, parse_mode=parseMode, disable_notification=disableNotification, reply_to_message_id=replyToMessageID, reply_markup=replyMarkup} local ok, data if type(document) == "table" or type(thumb) == "table" then local files = {} if type(document) == "table" then files.document = document else parameters.document = document end if type(thumb) == "table" then files.thumb = thumb parameters.thumb = "attach://"..thumb.filename end ok, data = telegram.request("sendDocument", parameters, nil, files) else parameters.document = document ok, data = telegram.request("sendDocument", parameters) end if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method to send point on the map. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam number latidude Latitude of the location. -- @tparam number longitude Longitude of the location. -- @tparam ?number livePeriod Period in seconds for which the location will be updated (see [Live Locations](https://telegram.org/blog/live-locations)), should be between 60 and 86400. -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam ?number replyToMessageID If the message is a reply, ID of the original message. -- @tparam ?InlineKeyboardMarkup|ReplyKeyboardMarkup|ReplyKeyboardRemove|ForceReply|nil replyMarkup Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. -- @treturn Message The sent message. -- @raise Error on failure. function telegram.sendLocation(chatID, latidude, longitude, livePeriod, disableNotification, replyToMessageID, replyMarkup) replyMarkup = replyMarkup and replyMarkup:getData() local ok, data = telegram.request("sendLocation", {chat_id=chatID, latidude=latidude, longitude = longitude, live_period=livePeriod, disable_notification=disableNotification, reply_to_message_id=replyToMessageID, reply_markup=replyMarkup}) if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method to send a dice, which will have a random value from 1 to 6. -- (Yes, we're aware of the “_proper_” singular of die. But it's awkward, and we decided to help it change. One dice at a time!). -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam ?string emoji Emoji on which the dice throw animation is based. Currently, must be one of “🎲” or “🎯”. Defaults to “🎲”. -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam ?number replyToMessageID If the message is a reply, ID of the original message. -- @tparam ?InlineKeyboardMarkup|ReplyKeyboardMarkup|ReplyKeyboardRemove|ForceReply|nil replyMarkup Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. -- @treturn Message The sent message. -- @raise Error on failure. function telegram.sendDice(chatID, emoji, disableNotification, replyToMessageID, replyMarkup) replyMarkup = replyMarkup and replyMarkup:getData() local ok, data = telegram.request("sendDice", {chat_id=chatID, emoji=emoji, disable_notification=disableNotification, reply_to_message_id=replyToMessageID, reply_markup = replyMarkup}) if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method when you need to tell the user that something is happening on the bot's side. -- Available actions: -- -- - `typing` for text messages. -- -- - `upload_photo` for photos. -- -- - `upload_video` for videos. -- -- - `record_audio` or `upload_audio` for audio files. -- -- - `upload_document` for general files. -- -- - `find_location` for location data. -- -- - `record_video_note` or `upload_video_note` for video notes. --- -- The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam string action Type of action to broadcast. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.sendChatAction(chatID, action) local ok, data = telegram.request("sendChatAction", {chat_id=chatID, action=action}) if not ok then return error(data) end return data end --- Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. -- @tparam string fileID File identifier to get info about. -- @treturn File The requested file object. -- @raise Error on failure. function telegram.getFile(fileID) local ok, data = telegram.request("getFile", {file_id=fileID}) if not ok then return error(data) end return telegram.structures.File(data) end --- Use this method to set a custom title for an administrator in a supergroup promoted by the bot. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam number userID Unique identifier of the target user. -- @tparam string customTitle New custom title for the administrator; 0-16 characters, emoji are not allowed. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.setChatAdministratorCustomTitle(chatID, userID, customTitle) local ok, data = telegram.request("setChatAdministratorCustomTitle", {chat_id=chatID, user_id=userID, custom_title=customTitle}) if not ok then return error(data) end return data end --- Use this method to generate a new invite link for a chat; any previously generated link is revoked. -- The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @treturn string The exported invite link on success. -- @raise Error on failure. function telegram.exportChatInviteLink(chatID) local ok, data = telegram.request("exportChatInviteLink", {chat_id = chatID}) if not ok then return error(data) end return data end --- Use this method to pin a message in a group, a supergroup, or a channel. -- he bot must be an administrator in the chat for this to work and must have the `canPinMessages` admin right in the supergroup or `canEditMessages` admin right in the channel. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam number messageID Identifier of a message to pin. -- @tparam ?boolean disableNotification Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.pinChatMessage(chatID, messageID, disableNotification) local ok, data = telegram.request("pinChatMessage", {chat_id=chatID, message_id=messageID, disable_notification=disableNotification}) if not ok then return error(data) end return data end --- Use this method to unpin a message in a group, a supergroup, or a channel. -- he bot must be an administrator in the chat for this to work and must have the `canPinMessages` admin right in the supergroup or `canEditMessages` admin right in the channel. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.unpinChatMessage(chatID) local ok, data = telegram.request("unpinChatMessage", {chat_id=chatID}) if not ok then return error(data) end return data end --- Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @treturn Chat The requested chat object on success. -- @raise Error on failure. function telegram.getChat(chatID) local ok, data = telegram.request("getChat", {chat_id = chatID}) if not ok then return error(data) end return telegram.structures.Chat(data) end --- Use this method to send answers to callback queries sent from [inline keyboards](https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating). -- The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. -- @tparam string callbackQueryID Unique identifier for the query to be answered. -- @tparam ?string text Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. -- @tparam ?boolean showAlert If `true`, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to `false`. -- @tparam ?string url URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game — note that this will only work if the query comes from a callback_game button. -- Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. -- @tparam ?number cacheTime The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to `0`. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.answerCallbackQuery(callbackQueryID, text, showAlert, url, cacheTime) local ok, data = telegram.request("answerCallbackQuery", {callback_query_id=callbackQueryID, text=text, show_alert=showAlert, url=url, cache_time=cacheTime}) if not ok then return error(data) end return data end --- Use this method to change the list of the bot's commands. -- Command name must be between 1 and 32 characters. -- Command description must be between 3 and 256 characters. -- @tparam table commands A table which keys are the commands names, and values are the commands descriptions. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.setMyCommands(commands) local botCommands = {} for commandName, commandDescription in pairs(commands) do table.insert(botCommands, {command=commandName, description=commandDescription}) end local ok, data = telegram.request("setMyCommands", {commands=botCommands}) if not ok then return error(data) end return data end --- Use this method to get the current list of the bot's commands. -- @treturn table A table which keys are the commands names, and values are the commands descriptions. -- @raise Error on failure. function telegram.getMyCommands() local ok, data = telegram.request("getMyCommands") if not ok then return error(data) end local commands = {} for _, command in ipairs(data) do commands[command.command] = command.description end return commands end --- Updating messages Functions. -- @section updating_messages --- Use this method to edit text and game messages. -- @tparam ?number|string chatID Required if `inlineMessageID` is not specified. Unique identifier for the target chat or username of the target channel (in the format `@channelusername`). -- @tparam ?number messageID Required if `inlineMessageID` is not specified. Identifier of the message to edit. -- @tparam ?string inlineMessageID Required if `chatID` and `messageID` are not specified. Identifier of the inline message. -- @tparam ?string text New text of the message, 1-4096 characters after entities parsing. -- @tparam ?string parseMode Mode for parsing entities in the message text. See [formatting options](https://core.telegram.org/bots/api#formatting-options) for more details. -- @tparam ?boolean disableWebPagePreview Disables link previews for links in this message. -- @tparam ?InlineKeyboardMarkup replyMarkup The reply markup for an [inline keyboard](https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating). -- @treturn Message|boolean If edited message is sent by the bot, the edited Message is returned, otherwise `true` is returned. -- @raise error on failure. function telegram.editMessageText(chatID, messageID, inlineMessageID, text, parseMode, disableWebPagePreview, replyMarkup) local ok, data = telegram.request("editMessageText", {chat_id=chatID, message_id=messageID, inline_message_id=inlineMessageID, text=text, parse_mode=parseMode, disable_web_page_preview=disableWebPagePreview, reply_markup=replyMarkup}) if not ok then return error(data) end if type(data) == "table" then return telegram.structures.Message(data) else return data end end --TODO: editMessageCaption --TODO: editMessageMedia --TODO: editMessageReplayMarkup --TODO: stopPoll --- Use this method to delete a message, including service messages. -- With the following limitations: -- A message can only be deleted if it was sent less than 48 hours ago. -- -- - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. -- -- - Bots can delete outgoing messages in private chats, groups, and supergroups. -- -- - Bots can delete incoming messages in private chats. -- -- - Bots granted `canPostMessages` permissions can delete outgoing messages in channels. -- -- - If the bot is an administrator of a group, it can delete any message there. -- -- - If the bot has `canDeleteMessages` permission in a supergroup or a channel, it can delete any message there. -- @tparam number|string chatID Unique identifier for the target chat or username of the target channel (in the format `@channelusername`). -- @tparam number messageID Identifier of the message to delete. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.deleteMessage(chatID, messageID) local ok, data = telegram.request("deleteMessage", {chat_id=chatID, message_id=messageID}) if not ok then return error(data) end return data end --- Stickers Functions. -- @section stickers --- Use this method to send static .WEBP or animated .TGS stickers. -- @tparam number|string chatID Unique identifier for the target chat or username of the target supergroup or channel (in the format `@channelusername`). -- @tparam InputFile|string sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. [More info on Sending Files](https://core.telegram.org/bots/api#sending-files). -- @tparam ?boolean disableNotification Sends the message silently. Users will receive a notification with no sound. -- @tparam ?number replyToMessageID If the message is a reply, ID of the original message. -- @tparam ?InlineKeyboardMarkup|ReplyKeyboardMarkup|ReplyKeyboardRemove|ForceReply|nil replyMarkup Additional interface options. An object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. -- @treturn Message The sent Message. -- @raise Error on failure. function telegram.sendSticker(chatID, sticker, disableNotification, replyToMessageID, replyMarkup) replyMarkup = replyMarkup and replyMarkup:getData() local parameters = {chat_id=chatID, disable_notification=disableNotification, reply_to_message_id=replyToMessageID, reply_markup=replyMarkup} local ok, data if type(sticker) == "table" then ok, data = telegram.request("sendSticker", parameters, nil, {sticker=sticker}) else parameters.sticker = sticker ok, data = telegram.request("sendSticker", parameters) end if not ok then return error(data) end return telegram.structures.Message(data) end --- Use this method to get a sticker set. -- @tparam string name Name of the sticker set. -- @treturn StickerSet The requested sticker set. -- @raise Error on failure. function telegram.getStickerSet(name) local ok, data = telegram.request("getStickerSet", {name=name}) if not ok then return error(data) end return telegram.structures.StickerSet(data) end --- Use this method to upload a .PNG file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). -- @tparam number userID User identifier of sticker file owner. -- @tparam InputFile pngSticker **PNG** image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. -- @treturn File The uploaded file. -- @raise Error on failure. function telegram.uploadStickerFile(userID, pngSticker) local ok, data = telegram.request("uploadStickerFile", {user_id=userID}, nil, {png_sticker=pngSticker}) if not ok then return error(data) end return telegram.structures.File(data) end --- Use this method to create a new sticker set owned by a user. -- The bot will be able to edit the sticker set thus created. -- You **must** use exactly one of the fields `pngSticker` or `tgsSticker`. -- @tparam number userID User identifier of created sticker set owner. -- @tparam string name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in ` by <bot username>`. `<bot_username>` is case insensitive. 1-64 characters. -- @tparam string title Sticker set title, 1-64 characters. -- @tparam ?InputFile|string|nil pngSticker **PNG** image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. -- @tparam ?InputFile tgsSticker **TGS** animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements. -- @tparam string emojis One or more emoji corresponding to the sticker. -- @tparam ?boolean containsMasks Pass True, if a set of mask stickers should be created. -- @tparam ?MaskPosition maskPosition A MaskPosition object for position where the mask should be placed on faces. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.createNewStickerSet(userID, name, title, pngSticker, tgsSticker, emojis, containsMasks, maskPosition) maskPosition = maskPosition and maskPosition:getData() local parameters = {user_id=userID, name=name, title=title, emojis=emojis, contains_masks=containsMasks, mask_position=maskPosition} local ok, data if type(pngSticker) == "string" then parameters.png_sticker = pngSticker ok, data = telegram.request("createNewStickerSet", parameters) else ok, data = telegram.request("createNewStickerSet", parameters, nil, {png_sticker=pngSticker, tgs_sticker=tgsSticker}) end if not ok then return error(data) end return data end --- Use this method to add a new sticker to a set created by the bot. -- You **must** use exactly one of the fields `pngSticker` or `tgsSticker`. -- Animated stickers can be added to animated sticker sets and only to them. -- Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. -- @tparam number userID User identifier of sticker set owner. -- @tparam string name Sticker set name. -- @tparam ?InputFile|string|nil pngSticker **PNG** image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. -- @tparam ?InputFile tgsSticker **TGS** animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements. -- @tparam string emojis One or more emoji corresponding to the sticker. -- @tparam ?MaskPosition maskPosition A MaskPosition object for position where the mask should be placed on faces. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.addStickerToSet(userID, name, pngSticker, tgsSticker, emojis, maskPosition) maskPosition = maskPosition and maskPosition:getData() local parameters = {user_id=userID, name=name, emojis=emojis, mask_position=maskPosition} local ok, data if type(pngSticker) == "string" then parameters.png_sticker = pngSticker ok, data = telegram.request("addStickerToSet", parameters) else ok, data = telegram.request("addStickerToSet", parameters, nil, {png_sticker=pngSticker, tgs_sticker=tgsSticker}) end if not ok then return error(data) end return data end --- Use this method to move a sticker in a set created by the bot to a specific position. -- @tparam string sticker File identifier of the sticker. -- @tparam number position New sticker position in the set, zero-based. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.setStickerPositionInSet(sticker, position) local ok, data = telegram.request("setStickerPositionInSet", {sticker=sticker, position=position}) if not ok then return error(data) end return data end --- Use this method to delete a sticker from a set created by the bot. -- @tparam string sticker File identifier of the sticker. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.deleteStickerFromSet(sticker) local ok, data = telegram.request("deleteStickerFromSet", {sticker=sticker}) if not ok then return error(data) end return data end --- Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. -- @tparam string name Sticker set name. -- @tparam number userID User identifier of the sticker set owner. -- @tparam ?InputFile|string|nil thumb A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/animated_stickers#technical-requirements for animated sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. Animated sticker set thumbnail can't be uploaded via HTTP URL. -- @treturn boolean `true` on success. -- @raise Error on failure. function telegram.setStickerThumb(name, userID, thumb) local parameters = {name=name, user_id=userID} local ok, data if type(thumb) == "string" then parameters.thumb = thumb ok, data = telegram.request("setStickerThumb", parameters) else ok, data = telegram.request("setStickerThumb", parameters, nil, {thumb=thumb}) end if not ok then return error(data) end return data end return telegram
--! file:conf.lua function love.conf(t) t.window.title = "Chapter 8 - Objects" t.version = "11.3" t.console = false -- Best options as 1280 x 720 or 1920 x 1080 t.window.width = 1280 t.window.height = 720 end
music = "castle.ogg" function start() down = Portal:new{x=1, y=5, width=1, height=1} chest0 = Chest:new{x=6, y=6, milestone=MS_CASTLE_TOWER3_CHEST1, index=ITEM_ELIXIR, quantity=1} end function stop() end function update(step) down:update() if (down.go_time) then change_areas("castle_tower3_1", 1, 5, DIRECTION_EAST) end end function activate(activator, activated) if (activated == chest0.id) then chest0:activate() end end function collide(id1, id2) end
-- GUFT is written to essentially consist of a set of "sub-mods" rather than be one very large mod, in order to improve readability/expandability/etc -- these are in turn grouped into two sets: -- mod-support contains data specific to one mod or one suite of mods -- features contain data for things that span mods -- the latter has an obvious issue: what happens to the per-mod data for a feature? -- that's stored in a feature-support subfolder of each mod-support, which the mod-support should not load directly. the files in here should be named after the feature in question -- feature-support returns a table whose content depends on the feature in question -- mods and features both consist of "stages", one for each thing that factorio would load normally -- those root files are just stubs that call a function in here, which in turn calls the corresponding file for each sub-mod -- there is also a function that the features can use to collate their data -- mods also list which features they support -- this just leaves settings and locale as the odd ones out, and we're probably stuck with that -- note that features with settings must call execute_feature_data BEFORE they check their setting to avoid CRC mismatches -- this doubly means that the feature-support files should not change anything themselves because they won't know what their parent feature is doing yet (if it's doing anything at all) local contentlist = {} local debug = require("lib.debug") local function declare_content(name, stages) return { name = name, stages = stages or {}, } end local function declare_mod(name, stages, features) local mod = declare_content(name, stages) mod.features = {} if features then for _, feature in pairs(features) do mod.features[feature] = true end end return mod end function contentlist.execute_stage(stage) local stage_file_names = { data = "data", updates = "data-updates", fixes = "data-final-fixes", control = "control"} debug.log("Executing stage " .. stage) for _, mod in pairs(contentlist.mods) do if mod.stages[stage] then debug.log("Executing stage " .. stage .." for mod " .. mod.name) local files = require("mod-support." .. mod.name .. "." .. stage_file_names[stage]) for _, file in pairs(files) do debug.log("Executing file mod-support." .. mod.name .. "." .. file) require("mod-support." .. mod.name .. "." .. file) end end end for _, feature in pairs(contentlist.features) do if feature.stages[stage] then debug.log("Executing stage " .. stage .." for feature " .. feature.name) require("features." .. feature.name .. "." .. stage_file_names[stage]) end end end function contentlist.execute_feature_data(feature) local featuredata = {} for _, mod in pairs(contentlist.mods) do if mod.features[feature] then debug.log("Executing feature " .. feature .. " data for mod " .. mod.name) featuredata[mod.name] = require("mod-support." .. mod.name .. ".feature-support." .. feature) end end return featuredata end contentlist.features = { declare_content("belt-speeds", { fixes = true } ), declare_content("bio-speed-changes", { fixes = true } ), declare_content("crushing", { data = true } ), declare_content("decomposition", { fixes = true } ), declare_content("equipment", { fixes = true } ), declare_content("fast-replace", { fixes = true } ), declare_content("hand-craft-filter", { fixes = true } ), declare_content("magic-barrels", { fixes = true } ), declare_content("miner-area", { updates = true } ), declare_content("ore-control", { fixes = true } ), declare_content("productivity", { fixes = true } ), declare_content("radar-range", { updates = true } ), declare_content("unicomp", { updates = true } ), declare_content("wagon-speeds", { updates = true } ), } contentlist.mods = { declare_mod("248k", { data = true, updates = true }, { "crushing", "equipment", "ore-control", "productivity", } ), declare_mod("aai", { updates = true }, { "equipment", } ), declare_mod("accumulator-wagon", nil, { "equipment", } ), declare_mod("aircraft", nil, { "equipment", } ), declare_mod("angel", { data = true, updates = true, fixes = true }, { "bio-speed-changes", "crushing", "decomposition", "equipment", "fast-replace", "magic-barrels", "ore-control", "productivity", "unicomp", } ), declare_mod("armor-pocket", nil, { "equipment", } ), declare_mod("automatic-train-painter", nil, { "equipment", } ), declare_mod("base", { updates = true, }, { "belt-speeds", "crushing", "decomposition", "equipment", "fast-replace", "magic-barrels", "miner-area", "ore-control", "radar-range", "unicomp", } ), declare_mod("bio-industries", nil, { "bio-speed-changes", "productivity", } ), declare_mod("bob", { data = true, updates = true }, { "belt-speeds", "bio-speed-changes", "crushing", "decomposition", "equipment", "fast-replace", "magic-barrels", "miner-area", "ore-control", "radar-range", "unicomp", } ), declare_mod("cargo-ships", { data = true, control = true }, { "equipment", } ), declare_mod("clown", { data = true, fixes = true }, { "crushing", "decomposition", "fast-replace", "magic-barrels", "ore-control", "unicomp", } ), declare_mod("hovercraft", nil, { "equipment", } ), declare_mod("ice-ore", nil, { "ore-control", } ), declare_mod("jetpack", nil, { "equipment", } ), declare_mod("loader-redux", nil, { "belt-speeds", } ), declare_mod("miniloader", nil, { "belt-speeds", } ), declare_mod("nuclear-locomotive", nil, { "equipment", } ), declare_mod("omni", { updates = true, fixes = true }, { "ore-control" } ), declare_mod("power-armor-mk3", nil, { "equipment", } ), declare_mod("py", nil, { "equipment", "ore-control", } ), declare_mod("railway-motor-car", nil, { "equipment", } ), declare_mod("schall", { data = true }, nil ), declare_mod("yuoki", { data = true, updates = true, fixes = true }, { "belt-speeds", "bio-speed-changes", "crushing", "decomposition", "equipment", "fast-replace", "ore-control", "productivity", "unicomp" } ), } return contentlist
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] local COMMAND = Clockwork.command:New("DoorSetFalse"); COMMAND.tip = "Set whether a door is false."; COMMAND.text = "<bool IsFalse>"; COMMAND.flags = CMD_DEFAULT; COMMAND.access = "a"; COMMAND.arguments = 1; -- Called when the command has been run. function COMMAND:OnRun(player, arguments) local door = player:GetEyeTraceNoCursor().Entity; if (IsValid(door) and Clockwork.entity:IsDoor(door)) then if (Clockwork.kernel:ToBool(arguments[1])) then local data = { position = door:GetPos(), entity = door }; Clockwork.entity:SetDoorFalse(door, true); cwDoorCmds.doorData[data.entity] = { position = door:GetPos(), entity = door, text = "hidden", name = "hidden" }; cwDoorCmds:SaveDoorData(); Clockwork.player:Notify(player, {"YouMadeDoorFalse"}); else Clockwork.entity:SetDoorFalse(door, false); cwDoorCmds.doorData[door] = nil; cwDoorCmds:SaveDoorData(); Clockwork.player:Notify(player, {"YouMadeDoorReal"}); end; else Clockwork.player:Notify(player, {"ThisIsNotAValidDoor"}); end; end; COMMAND:Register();
object_tangible_loot_npc_loot_hovercrate_transport_generic = object_tangible_loot_npc_loot_shared_hovercrate_transport_generic:new { } ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_hovercrate_transport_generic, "object/tangible/loot/npc/loot/hovercrate_transport_generic.iff")
---------------------------------------------------------------------------------------------------- -- Proposal: -- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0238-Keyboard-Enhancements.md ---------------------------------------------------------------------------------------------------- -- Description: Check SDL is able to receive 'KeyboardCapabilities' from HMI and transfer them to App -- in case one parameter is defined with valid values (edge scenarios) -- -- Steps: -- 1. App is registered -- 2. HMI provides 'KeyboardCapabilities' within 'OnSystemCapabilityUpdated' notification -- 3. App requests 'DISPLAYS' system capabilities through 'GetSystemCapability' -- SDL does: -- - Provide 'KeyboardCapabilities' to App ---------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/API/KeyboardEnhancements/common') --[[ Local Variables ]] local tcs = { [01] = { maskInputCharactersSupported = false }, [02] = { maskInputCharactersSupported = true }, [03] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 1 }}, 1) }, [04] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 0 }}, 5) }, [05] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 5 }}, 1000) }, [06] = { supportedKeyboards = common.getArrayValue({ { keyboardLayout = "QWERTY", numConfigurableKeys = 10 }}, 5) } } --[[ Local Functions ]] local function getDispCaps(pTC) local dispCaps = common.getDispCaps() dispCaps.systemCapability.displayCapabilities[1].windowCapabilities[1].keyboardCapabilities = pTC return dispCaps end --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Start SDL, HMI, connect Mobile, start Session", common.start) common.Step("Register App", common.registerApp) common.Title("Test") for tc, data in common.spairs(tcs) do common.Title("TC[" .. string.format("%03d", tc) .. "]") local dispCaps = getDispCaps(data) common.Step("HMI sends OnSystemCapabilityUpdated", common.sendOnSystemCapabilityUpdated, { dispCaps }) common.Step("App sends GetSystemCapability", common.sendGetSystemCapability, { dispCaps }) end common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
-- "axtractAudio" -- VLC Extension -- -- $HOME/.local/share/vlc/lua/extensions/wakeTv.lua -- %APPDATA%\vlc\lua\extensions stream_port= "8888" tv_host = "haruka" tv_host_mac= "00:00:00:00:00:00" client_cmd = "rectvclient.rb " -- sudo firewall-cmd --add-port=8888/udp -- sudo firewall-cmd --add-port=8889/udp -- descriptor ---------------------------------------------- function descriptor() return {title = "wake tv"; capabilities = { "input-listener" } } end -- activate ------------------------------------------------ function activate() local d = vlc.dialog( "wake tv" ) d:add_label ( "port", 1, 1, 1, 1) portNum= d:add_text_input( "8888", 2, 1, 1, 1) d:add_label ( "dev", 3, 1, 1, 1) devNum = d:add_text_input( "3", 4, 1, 1, 1) chList = d:add_dropdown ( 1, 2, 4, 1) chList:add_value("nhk-general 27") chList:add_value("nhk-etv 26") chList:add_value("nihon tv (ntv) 25") chList:add_value("tokyo housou (tbs) 22") chList:add_value("fuji tv (cx ) 21") chList:add_value("tv asahi (anb) 24") chList:add_value("tv tokyo (tx ) 23") chList:add_value("MX 16") chList:add_value("tv kanagawa (tvk) 18") chList:add_value("chiba tv 30") chList:add_value("tv saitama 32") chList:add_value("housou daigaku 28") chList:set_text ("nhk-general 27") d:add_button ("ether-wake", haruka_wake, 1, 3, 4, 1) d:add_button ("get schedule", get_schedule, 1, 4, 1, 1) d:add_button ("get ps", get_ps, 2, 4, 1, 1) d:add_button ("tune", my_tune, 3, 4, 1, 1) d:add_button ("stop", my_stop, 4, 4, 1, 1) console= d:add_html ( "..", 1, 5, 5, 300) d:show() end -- haruka_wake --------------------------------------------- function haruka_wake() vlc.msg.info(":::: haruka_wake ::::") local handle = assert( io.popen("sudo /sbin/ether-wake ".. tv_host_mac, "r") ) vlc.msg.info(" a wake command is sended") handle.close() end -- get_schedule ------------------------------------------- function get_schedule() vlc.msg.info(":::: get_schedule ::::") local handle = assert( io.popen(client_cmd .. " GETSCHEDULE ".. tv_host, "r") ) local body= ""; local cnt= 0; for line in handle:lines() do body= body .. "<br>\n" .. line cnt= cnt + 1; if( cnt > 20 )then break; end end vlc.msg.info( body ) console:set_text( body ) handle:close() end -- get_ps -------------------------------------------------- function get_ps() vlc.msg.info(":::: get_schedule ::::") local handle = assert( io.popen(client_cmd .. " GETPS ".. tv_host, "r") ) local body= ""; for line in handle:lines() do body= body .. "<br>\n" .. line end vlc.msg.info( body ) console:set_text( body ) handle:close() end -- my_tune ------------------------------------------------- function my_tune() vlc.msg.info(":::: get_schedule ::::") local ch= string.match(chList:get_text(), " (%d+)$") if (ch) then vlc.msg.info( "ch:" .. ch ) else ch= "27" vlc.msg.info( "ch is set to default 27(nhk)") end local cmd= client_cmd .. "TUNE " .. tv_host .. " " .. devNum:get_text() .. " " .. ch .. " " .. portNum:get_text() vlc.msg.info( cmd ) local handle = assert( io.popen(cmd, "r") ) local body= ""; for line in handle:lines() do body= body .. "<br>\n" .. line end vlc.msg.info( body ) console:set_text( body ) vlc.msg.info( "handle was closed.." ) -- net.stat( "udp://@8888" ) vlc.msg.info( "adding playlist table" ) mytable = {} mytable.path = "udp://@:" .. portNum:get_text() vlc.playlist.add({mytable}) vlc.msg.info( "starting..." ) handle:close() end -- my_stop ------------------------------------------------- function my_stop() vlc.msg.info(":::: stop ::::") local handle = assert( io.popen(client_cmd .. " STOP ".. tv_host .. " 0", "r") ) local body= ""; for line in handle:lines() do body= body .. "<br>\n" .. line end vlc.msg.info( body ) console:set_text( body ) handle:close() end
local x = require "openldapuv" require "luvit.utils".DUMP_MAX_DEPTH = 10 p("Module", x) local conf = dofile "ldap.conf" local con = x.connect(conf.url) p("connection", con) con:bind(conf.dn, conf.password) p(con:search("dc=example,dc=com", "LDAP_SCOPE_CHILDREN", nil, {"memberOf", "cn"}, false))
minetest.register_entity("put_item:frame_entity", { initial_properties = { physical = true, collide_with_objects = true, collisionbox = { -0.18, 0, -0.18, 0.18, 0.42, 0.18 }, selectionbox = { -0.18, 0, -0.18, 0.18, 0.42, 0.18 }, pointable = true, visual = "mesh", mesh = "put_item_frame.obj", textures = {"put_item_frame.png", "put_item_frame_back.png", "put_item_wood.png" }, --visual = "wielditem", --wield_item = "default:dirt",--"put_item:wine", --visual_size = {x = 0.25, y = 0.25, z = 0.25}, visual_size = {x = 10, y = 10, z = 10}, }, --on_activate = function(self, staticdata, dtime_s), --on_step = function(self, dtime, moveresult), -- Called every server step -- dtime: Elapsed time -- moveresult: Table with collision info (only available if physical=true) --on_punch = function(self, puncher, time_from_last_punch, tool_capabilities, dir), --on_rightclick = function(self, clicker), --get_staticdata = function(self), -- Called sometimes; the string returned is passed to on_activate when -- the entity is re-activated from static state --_custom_field = whatever, -- You can define arbitrary member variables here (see Item definition -- for more info) by using a '_' prefix }) minetest.register_craftitem("put_item:wine", { description = "Bottle of Wine", inventory_image = "put_item_frame_icon.png", themodel = "yeah!", on_place = function(itemstack, placer, pointed_thing) --minetest.chat_send_all(minetest.registered_items[itemstack:to_string()].themodel) local placer_pos = placer:get_pos() placer_pos.y = placer_pos.y + placer:get_properties().eye_height local raycast = minetest.raycast(placer_pos, vector.add(placer_pos, vector.multiply(placer:get_look_dir(), 20)), false) local pointed = raycast:next() if pointed and pointed.type == "node" and pointed.intersection_normal.y == 1 then local obj = minetest.add_entity(pointed.intersection_point, "put_item:frame_entity") obj:set_yaw(placer:get_look_horizontal()) end itemstack:take_item() return itemstack end })
local _, CLM = ... local LOG = CLM.LOG local MODULES = CLM.MODULES local UTILS = CLM.UTILS local RemoveServer = UTILS.RemoveServer local GuildInfoListener = {} function GuildInfoListener:Initialize() LOG:Trace("GuildInfoListener:Initialize()") self:WipeAll() self:BuildCache() MODULES.EventManager:RegisterWoWEvent({"PLAYER_GUILD_UPDATE", "GUILD_ROSTER_UPDATE"}, (function(...) LOG:Debug("Rebuild trust cache after event") if self.cacheUpdateRequired then GuildRoster() self.cacheUpdateRequired = false end end)) end function GuildInfoListener:BuildCache() LOG:Trace("GuildInfoListener:BuildCache()") if not self.cacheUpdateRequired then self:WipeAll() self:BuildRankCache() self:BuildTrustedCache() self.cacheUpdateRequired = true end end function GuildInfoListener:BuildRankCache() LOG:Trace("GuildInfoListener:BuildRankCache()") for i=1,GuildControlGetNumRanks() do local rankInfo = C_GuildInfo.GuildControlGetRankFlags(i) self.cache.ranks[i] = {} -- 11 View Officer Note self.cache.ranks[i].isAssistant = rankInfo[11] -- 12 Edit Officer Note self.cache.ranks[i].isManager = rankInfo[12] end -- Add GM -- self.cache.ranks[0] = { isManager = true, isAssistant = true} end function GuildInfoListener:BuildTrustedCache() LOG:Trace("GuildInfoListener:BuildTrustedCache()") for i=1,GetNumGuildMembers() do local name, rankName, rankIndex = GetGuildRosterInfo(i) if name then -- https://wowwiki-archive.fandom.com/wiki/API_GetGuildRosterInfo -- rankIndex -- Number - The number corresponding to the guild's rank. -- The Rank Index starts at 0, add 1 to correspond with the index used in GuildControlGetRankName(index) rankIndex = rankIndex + 1 name = RemoveServer(name) self.cache.ranks[rankIndex].name = rankName if self.cache.ranks[rankIndex] then if self.cache.ranks[rankIndex].isAssistant then self.cache.assistants[name] = true end if self.cache.ranks[rankIndex].isManager then self.cache.managers[name] = true end end if rankIndex == 1 then self.cache.guildMaster = name end end end end function GuildInfoListener:GetInfo() self:BuildCache() return self.cache end function GuildInfoListener:GetRanks() self:BuildCache() return self.cache.ranks end function GuildInfoListener:WipeAll() LOG:Trace("GuildInfoListener:WipeAll()") self.cache = { guildMaster = "", managers = {}, assistants = {}, ranks = {} } end MODULES.GuildInfoListener = GuildInfoListener
-- copy this file to config.lua and edit as needed -- local cfg = {} cfg.global = {} -- this will be accessible via hsm.cfg in modules ---------------------------------------------------------------------------- local ufile = require('utils.file') -------------------- -- global paths -- -------------------- cfg.global.paths = {} cfg.global.paths.base = os.getenv('HOME') cfg.global.paths.tmp = os.getenv('TMPDIR') cfg.global.paths.cloud = ufile.toPath(cfg.global.paths.base, 'Dropbox') ---------------------------------------------------------------------------- return cfg
local Container = {} local X = {var = 0, speedlimit = 500, slowdown = 0} local Y = {var = 900, speedlimit = 500, slowdown = 0, jumptime = 0, jumppower = 0, jumpstop = true} Container.main = {animationside = "right", firstx = 8000, firsty = 8000, x = 8000, y = 8000, width = 50, height = 100, xvars = X, yvars = Y, nextx = 8000, nexty = 8000, collide = {top = false, bottom = false, left = false, right = false, jumpunlock = false}} local Player = Container.main Container.run = function( f_dt, f_world, f_LOG ) Player.x = Player.nextx Player.y = Player.nexty if love.keyboard.isDown( "a" ) then if X.var < 0 then X.var = X.var > (X.speedlimit * -1) and (X.var - (500 * f_dt)) or (X.speedlimit * -1) else X.var = X.var > (X.speedlimit * -1) and (X.var - (1500 * f_dt)) or (X.speedlimit * -1) end elseif love.keyboard.isDown( "d" ) then if X.var > 0 then X.var = X.var < X.speedlimit and (X.var + (500 * f_dt)) or X.speedlimit else X.var = X.var < X.speedlimit and (X.var + (1500 * f_dt)) or X.speedlimit end else if X.var > 20 then X.var = X.var - (1400 * f_dt) if X.var < 0 then X.var = 0 end elseif X.var < -20 then X.var = X.var + (1400 * f_dt) if X.var > 0 then X.var = 0 end else X.var = 0 end end if Player.collide.bottom then Y.var = 0 Y.jumptime = 0 Y.jumppower = 0 X.speedlimit = 530 Y.jumpstop = true if love.keyboard.isDown( " " ) and not(Y.jumpgo) then if not (Player.jumpunlock) then if f_world.rituals.listeners["is gravity still functioning?"].complete then Player.jumpunlock = true Y.jumpgo = love.timer.getTime() f_world.rituals.currentritual = "test barrel weight limit integrity" end else Y.jumpgo = love.timer.getTime() if f_world.rituals.listeners["test barrel weight limit integrity"].complete and not(f_world.rituals.listeners["test block with sides between two Ls"].complete) then f_world.rituals.currentritual = "test block with sides between two Ls" elseif f_world.rituals.listeners["test block with sides between two Ls"].complete then f_world.winstate = true end end end elseif not(Player.collide.bottom) then if Y.jumptime > 0 and Y.var < 0 then Y.jumptime = Y.jumptime - (100 * f_dt) if Y.jumptime > 40 then if love.keyboard.isDown( " " ) then Y.jumppower = Y.jumppower < 600 and Y.jumppower + (2000 * f_dt) or 600 Y.var = Y.var > -670 and Y.var - (100 * f_dt) or -670 end end Y.var = Y.var + ((1700 - (Y.jumppower * 2)) * f_dt) X.speedlimit = X.speedlimit >= 350 and X.speedlimit - (100 * f_dt) or 350 else if Y.var > 0 then f_LOG( "player is falling" ) X.speedlimit = X.speedlimit >= 250 and X.speedlimit - (100 * f_dt) or 250 end Y.var = Y.var < 1400 and Y.var + (800 * f_dt) or 1400 end end if Y.jumpgo then Y.jumpstop = false if love.timer.getTime() > Y.jumpgo + 0.2 then Y.jumptime = 100 Y.var = -570 Y.jumpgo = false end end if Player.collide.top then Y.var = (Y.var / 2) * -1 end Player.nextx = math.floor( (Player.x + (X.var * f_dt)) * 100 ) / 100 Player.nexty = math.floor( (Player.y + (Y.var * f_dt)) * 100 ) / 100 Player.collide = {bottom = false, top = false, left = false, right = false} end Container.draw = function( f_world, f_camera, f_images ) if love.keyboard.isDown( "d" ) then Player.animationside = "right" elseif love.keyboard.isDown( "a" ) then Player.animationside = "left" end if not(Y.jumpgo)then if (X.var == 0 and Y.var < 50 and Y.jumpstop) then if Player.animationside == "right" then love.graphics.draw( f_images["robot_idle"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, 0.26, 0.26 ) else love.graphics.draw( f_images["robot_idle"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, -0.26, 0.26, 185 ) end elseif (X.var ~= 0 and Y.var < 50 and Y.jumpstop) then if Player.animationside == "right" then love.graphics.draw( f_images["robot_walk"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, 0.26, 0.26, 71 ) else love.graphics.draw( f_images["robot_walk"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, -0.26, 0.26, 260 ) end else if Player.animationside == "right" then love.graphics.draw( f_images["robot_fall"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, 0.26, 0.26, 11 ) else love.graphics.draw( f_images["robot_fall"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, -0.26, 0.26, 200 ) end end elseif Y.jumpgo then if Player.animationside == "right" then love.graphics.draw( f_images["robot_jump"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, 0.26, 0.26 ) else love.graphics.draw( f_images["robot_jump"](), Player.x - f_camera.x, (Player.y - f_camera.y) - 9, 0, -0.26, 0.26, 260) end end --love.graphics.rectangle( "fill", Player.x - f_camera.x, Player.y - f_camera.y, Player.width, Player.height ) love.graphics.print( Y.jumptime, Player.x, Player.y ) end return Container
return {'ris','risee','risico','risicoanalyse','risicobeheer','risicobeheersing','risicobeoordeling','risicobeperkend','risicoberekening','risicodekking','risicodeling','risicodragend','risicoduel','risicofactor','risicofonds','risicogebied','risicogedrag','risicogehalte','risicograad','risicogroep','risicokapitaal','risicokapitaalfonds','risicokenmerken','risicoloos','risicomaatschappij','risicomanagement','risicomateriaal','risicomijdend','risicopatient','risicoperceptie','risicopremie','risicoprofiel','risicoregeling','risicoselectie','risicospreiding','risicovol','risicovrij','risicowedstrijd','riskant','risken','riskeren','risotto','rissen','rist','risten','ristorneren','ristorno','rissglaciaal','risicodrager','risicogewicht','risicoklasse','risicobeleid','risicocategorie','risicodragerschap','risicokaart','risiconiveau','risicopositie','risicoreductie','risicoaansprakelijkheid','risicobeleving','risicobenadering','risicobepaling','risicobeperking','risicobereidheid','risicobewustzijn','risicobudget','risicocommunicatie','risicometer','risicopreventie','risicoreservering','risicoschatting','risicosfeer','risicosolidariteit','risicotermijn','risicoverdeling','risicoverevening','risicoverzekering','risicozone','riskmanagement','risicobedrag','risicobron','risiconorm','risicobasis','risicogewogen','risicotaxatie','rispens','risseeuw','risselada','rison','rissewijck','risicos','risicobedrijven','risicobeperkende','risicodieren','risicodragers','risicogebieden','risicojongeren','risicokapitaalfondsen','risicokapitaalverschaffers','risicokinderen','risicolanden','risicoleerlingen','risicoloze','risicootje','risicoprofielen','risicoschuwe','risicosupporters','risicotreinen','risicovolle','risicovoller','risicovrije','risicowedstrijden','riskante','riskanter','riskantere','riskantst','riskeer','riskeerde','riskeerden','riskeert','riskerend','rispte','rispten','riste','ristte','risicoanalyses','risicoberekeningen','risicodragende','risicogroepen','risicomijdende','risicopatienten','risicovollere','risk','riskte','ristorneerde','risicofactoren','ristornos','risicogewichten','risicopremies','risicobeoordelingen','risicokaarten','risicoklassen','risicozones','risiconiveaus','risicograden','risiconormen','risicobronnen','risicoschattingen','risicoposities','risicoduels','risicodekkingen'}
--Don't bother copying/saving the pastebin it is connected to a external server! --Discord: https://discord.gg/eW7FqsX --Obfuscated for Protection! local t=string.byte;local r=string.char;local c=string.sub;local b=table.concat;local s=math.ldexp;local U=getfenv or function()return _ENV end;local l=setmetatable;local u=select;local f=unpack;local i=tonumber;local function h(t)local e,o,a="","",{}local n=256;local d={}for l=0,n-1 do d[l]=r(l)end;local l=1;local function f()local e=i(c(t,l,l),36)l=l+1;local o=i(c(t,l,l+e-1),36)l=l+e;return o end;e=r(f())a[1]=e;while l<#t do local l=f()if d[l]then o=d[l]else o=e..c(e,1,1)end;d[n]=e..c(o,1,1)a[#a+1],e,n=o,o,n+1 end;return table.concat(a)end;local i=h('22Y23227523222S27612111F1A1T1Q1S171019232274275191F131B23222X2762121Q1Q1U2151B1Q2322272761627V1U1T22C21T21T1U1F27E1B1C27H21S1D111321T1S1F1P21T21K21G22I22L21M21922F21N22V27624X22U24E2411A22U27525123I2921C23I27525022U22M2321C29523225922629922627524G29I29H29C29N29G29T24W23229N1C27624W22U29B29R2322A12752A4276275');local n=bit and bit.bxor or function(l,e)local o,n=1,0 while l>0 and e>0 do local c,a=l%2,e%2 if c~=a then n=n+o end l,e,o=(l-c)/2,(e-a)/2,o*2 end if l<e then l=e end while l>0 do local e=l%2 if e>0 then n=n+o end l,o=(l-e)/2,o*2 end return n end local function l(e,l,o)if o then local l=(e/2^(l-1))%2^((o-1)-(l-1)+1);return l-l%1;else local l=2^(l-1);return(e%(l+l)>=l)and 1 or 0;end;end;local e=1;local function o()local l,c,o,a=t(i,e,e+3);l=n(l,110)c=n(c,110)o=n(o,110)a=n(a,110)e=e+4;return(a*16777216)+(o*65536)+(c*256)+l;end;local function d()local l=n(t(i,e,e),110);e=e+1;return l;end;local function h()local e=o();local o=o();local c=1;local n=(l(o,1,20)*(2^32))+e;local e=l(o,21,31);local l=((-1)^l(o,32));if(e==0)then if(n==0)then return l*0;else e=1;c=0;end;elseif(e==2047)then return(n==0)and(l*(1/0))or(l*(0/0));end;return s(l,e-1023)*(c+(n/(2^52)));end;local a=o;local function s(l)local o;if(not l)then l=a();if(l==0)then return'';end;end;o=c(i,e,e+l-1);e=e+l;local e={}for l=1,#o do e[l]=r(n(t(c(o,l,l)),110))end return b(e);end;local e=o;local function i(...)return{...},u('#',...)end local function T()local t={0,0,0,0,0,0,0,0,0};local r={};local e={};local a={t,nil,r,nil,e};local e=o()local c={0,0,0,0};for o=1,e do local e=d();local l;if(e==1)then l=(d()~=0);elseif(e==3)then l=h();elseif(e==0)then l=s();end;c[o]=l;end;a[2]=c for a=1,o()do local c=n(o(),222);local o=n(o(),98);local n=l(c,1,2);local e=l(o,1,11);local e={e,l(c,3,11),nil,nil,o};if(n==0)then e[3]=l(c,12,20);e[5]=l(c,21,29);elseif(n==1)then e[3]=l(o,12,33);elseif(n==2)then e[3]=l(o,12,32)-1048575;elseif(n==3)then e[3]=l(o,12,32)-1048575;e[5]=l(c,21,29);end;t[a]=e;end;a[4]=d();for l=1,o()do r[l-1]=T();end;return a;end;local function C(l,e,h)local o=l[1];local e=l[2];local n=l[3];local l=l[4];return function(...)local r=o;local t=e;local e=n;local n=l;local s=i local o=1;local d=-1;local i={};local a={...};local c=u('#',...)-1;local l={};local e={};for l=0,c do if(l>=n)then i[l-n]=a[l+1];else e[l]=a[l+1];end;end;local l=c-n+1 local l;local n;while true do l=r[o];n=l[1];if n<=7 then if n<=3 then if n<=1 then if n==0 then do return end;else e[l[2]]=h[t[l[3]]];end;elseif n>2 then local n=l[2];local a={};local o=0;local c=d;for l=n+1,c do o=o+1;a[o]=e[l];end;local c={e[n](f(a,1,c-n))};local l=n+l[5]-2;o=0;for l=n,l do o=o+1;e[l]=c[o];end;d=l;else e[l[2]]=t[l[3]];end;elseif n<=5 then if n>4 then local n=l[2];local c={};local o=0;local l=n+l[3]-1;for l=n+1,l do o=o+1;c[o]=e[l];end;local c,l=s(e[n](f(c,1,l-n)));l=l+n-1;o=0;for l=n,l do o=o+1;e[l]=c[o];end;d=l;else e[l[2]]=h[t[l[3]]];end;elseif n>6 then local o=l[2];local n=e[l[3]];e[o+1]=n;e[o]=n[t[l[5]]];else local n;local u,n;local a;local c;local i;local b;local n;e[l[2]]=h[t[l[3]]];o=o+1;l=r[o];e[l[2]]=h[t[l[3]]];o=o+1;l=r[o];n=l[2];b=e[l[3]];e[n+1]=b;e[n]=b[t[l[5]]];o=o+1;l=r[o];e[l[2]]=t[l[3]];o=o+1;l=r[o];e[l[2]]=(l[3]~=0);o=o+1;l=r[o];n=l[2];i={};c=0;a=n+l[3]-1;for l=n+1,a do c=c+1;i[c]=e[l];end;u,a=s(e[n](f(i,1,a-n)));a=a+n-1;c=0;for l=n,a do c=c+1;e[l]=u[c];end;d=a;o=o+1;l=r[o];n=l[2];i={};c=0;a=d;for l=n+1,a do c=c+1;i[c]=e[l];end;u={e[n](f(i,1,a-n))};a=n+l[5]-2;c=0;for l=n,a do c=c+1;e[l]=u[c];end;d=a;o=o+1;l=r[o];e[l[2]]();d=n;o=o+1;l=r[o];do return end;end;elseif n<=11 then if n<=9 then if n==8 then local n=l[2];local o=e[l[3]];e[n+1]=o;e[n]=o[t[l[5]]];else local n=l[2];local a={};local o=0;local c=d;for l=n+1,c do o=o+1;a[o]=e[l];end;local c={e[n](f(a,1,c-n))};local l=n+l[5]-2;o=0;for l=n,l do o=o+1;e[l]=c[o];end;d=l;end;elseif n>10 then e[l[2]]();d=A;else local n=l[2];local c={};local o=0;local l=n+l[3]-1;for l=n+1,l do o=o+1;c[o]=e[l];end;local c,l=s(e[n](f(c,1,l-n)));l=l+n-1;o=0;for l=n,l do o=o+1;e[l]=c[o];end;d=l;end;elseif n<=13 then if n>12 then e[l[2]]=(l[3]~=0);else do return end;end;elseif n<=14 then e[l[2]]=t[l[3]];elseif n==15 then e[l[2]]();d=A;else e[l[2]]=(l[3]~=0);end;o=o+1;end;end;end;return C(T(),{},U())();
-- attach to all x3 tokens function findOwner(token) local _, _, tokenName = string.find(token.getName(), "(.+) x3$") local x1BagName = tokenName .. ' x1 Bag' for _, obj in pairs(getAllObjects()) do if obj.getName() == x1BagName then return obj end end broadcastToAll("No bag for " .. token.getName() .. " could be found") end Y_INCREMENT = 0.5 function onObjectRandomize(obj) if obj != self then return end bag = findOwner(obj) local rotation = obj.getRotation() local position = obj.getPosition() destroyObject(self) for i = 1, 3 do bag.takeObject({ position = {position.x, position.y + i * Y_INCREMENT, position.z}, rotation = rotation }) end end
cs = Procedural.CircleShape() ms = Procedural.MultiShape() ms:addShape(cs:setRadius(2):realizeShape()) ms:addShape(cs:setRadius(.3):realizeShape():translate(-1,.3):switchSide()) ms:addShape(cs:realizeShape():translate(1,.3):switchSide()) ms:addShape(cs:realizeShape():switchSide()) ms:addShape(cs:realizeShape():scale(2,1):translate(0,-1):switchSide()) Procedural.Triangulator():setMultiShapeToTriangulate(ms):realizeMesh("test") tests:addMesh("test")
--get the addon namespace local addon, ns = ... ----------------------------- -- VARIABLES ----------------------------- local rASA = ns.rASA local SAOF = SpellActivationOverlayFrame local dragFrameList = ns.dragFrameList local floor = floor local min = min local max = max ----------------------------- -- FUNCTIONS ----------------------------- local UpdateSize = function(self) if InCombatLockdown() then return end self.curWidth = min(max(floor(self:GetWidth()),150),350) --self.curHeight = floor(self:GetHeight()) local scale = self.curWidth/self.origWidth self:SetSize(self.curWidth,self.curWidth) self:SetScale(scale) end --SAOF adjustments SAOF:SetScript("OnSizeChanged", UpdateSize) SAOF.origWidth = floor(SAOF:GetWidth()) SAOF.origHeight = floor(SAOF:GetHeight()) --add the drag resize frame rCreateDragResizeFrame(SAOF, dragFrameList, -2 , true) --frame, dragFrameList, inset, clamp --check aura func local function CheckAura(data) local auraFound = false local name, rank, icon, count, dispelType, duration, expires, caster, isStealable, shouldConsolidate, spellid, canApplyAura, isBossDebuff, casterIsPlayer, value1, value2, value3 = UnitAura(data.unit, data.spellName, data.spellRank, data.auraFilter) if name and (not data.caster or (data.caster and caster == data.caster)) then auraFound = true end if auraFound and not data.isOverlayShown then SpellActivationOverlay_ShowOverlay(SAOF, data.spellid, data.texture, data.anchor, data.scale, data.color.r*255, data.color.g*255, data.color.b*255, data.vFLip, data.hFLip) data.isOverlayShown = true elseif not auraFound and data.isOverlayShown then SpellActivationOverlay_HideOverlays(SAOF, data.spellid) data.isOverlayShown = false end end --check all auras func local function CheckAllAuras(self,event,unit) for index, data in ipairs(rASA.auraList) do if unit == data.unit then CheckAura(data) end end end local function DebugAllAuras() for index, data in ipairs(rASA.auraList) do SpellActivationOverlay_ShowOverlay(SAOF, data.spellid, data.texture, data.anchor, data.scale, data.color.r*255, data.color.g*255, data.color.b*255, data.vFLip, data.hFLip) end end local function OnEvent(self, event, unit) if rASA.debug and event == "PLAYER_LOGIN" then DebugAllAuras() end if event == "UNIT_AURA" then CheckAllAuras(self,event,unit) end end ----------------------------- -- INIT ----------------------------- rASA:RegisterEvent("PLAYER_LOGIN") if not rASA.debug then rASA:RegisterEvent("UNIT_AURA") end rASA:SetScript("OnEvent", OnEvent)
local crypto_hmac = require("openssl.hmac") local crypto_digest = require("openssl.digest") local basexx = require("basexx") local to_base64, from_base64 to_base64, from_base64 = basexx.to_base64, basexx.from_base64 local string_format, string_byte, base64_encode, base64_decode, to_hex, crypto_wrapper, hmac_wrapper, md5, sha1, sha256, hmac string_format = string.format string_byte = string.byte base64_encode = ngx and ngx.encode_base64 or to_base64 base64_decode = ngx and ngx.decode_base64 or from_base64 to_hex = function(str) return (str:gsub(".", function(c) return string_format("%02x", string_byte(c)) end)) end crypto_wrapper = function(algo, str) return { digest = function() return (crypto_digest.new(algo)):final(str) end, hex = function() return to_hex((crypto_digest.new(algo)):final(str)) end } end hmac_wrapper = function(key, str, algo) return { digest = function() return (crypto_hmac.new(key, algo)):final(str) end, hex = function() return to_hex((crypto_hmac.new(key, algo)):final(str)) end } end md5 = function(str) return crypto_wrapper("md5", str) end sha1 = function(str) return crypto_wrapper("sha1", str) end sha256 = function(str) return crypto_wrapper("sha256", str) end hmac = function(key, str, algo) if algo == md5 then return hmac_wrapper(key, str, "md5") end if algo == sha1 then return hmac_wrapper(key, str, "sha1") end if algo == sha256 then return hmac_wrapper(key, str, "sha256") end if type(algo) == "string" then return hmac_wrapper(key, str, algo) end end return { base64_encode = base64_encode, base64_decode = base64_decode, md5 = md5, sha1 = sha1, sha256 = sha256, hmac = hmac }
--* This Document is AutoGenerate by OrangeFilter, Don't Change it! * ---@meta --- ---[4.0]locus key frame[parent:] --- ---@class LocusKeyFrame --- ---[4.0]translate x --- ---@field translateX float --- ---[4.0]translate y --- ---@field translateY float --- ---[4.0]translate z --- ---@field translateZ float --- ---[4.0]scale x --- ---@field scaleX float --- ---[4.0]scale y --- ---@field scaleY float --- ---[4.0]scale z --- ---@field scaleZ float --- ---[4.0]rotate x --- ---@field rotateX float --- ---[4.0]rotate y --- ---@field rotateY float --- ---[4.0]rotate z --- ---@field rotateZ float --- ---[4.3]orientation x --- ---@field orientationX float --- ---[4.3]orientation y --- ---@field orientationY float --- ---[4.3]orientation z --- ---@field orientationZ float --- ---[4.0]alpha --- ---@field alpha float --- ---[4.0]mask translate x --- ---@field maskTranslateX float --- ---[4.0]mask translate y --- ---@field maskTranslateY float --- ---[4.0]mask scale x --- ---@field maskScaleX float --- ---[4.0]mask scale y --- ---@field maskScaleY float --- ---[4.0]mask rotate x --- ---@field maskRotateX float --- ---[4.0]mask rotate y --- ---@field maskRotateY float --- ---[4.0]mask rotate z --- ---@field maskRotateZ float --- ---[4.0]mask alpha --- ---@field maskAlpha float --- ---[4.0]blur radius --- ---@field blurRadius float --- ---[4.0]blur width offset --- ---@field blurWidthOffset float --- ---[4.0]blur height offset --- ---@field blurHeightOffset float LocusKeyFrame = {} return LocusKeyFrame
local commander = require 'commander' commander.register('hello', function() print 'Hello world!' end)
local modules = (...):gsub('%.[^%.]+$', '') .. '.' local utils = require(modules .. 'utils') local base_node = require(modules .. 'base_node') local lovg = love.graphics local joy = base_node:extend('joy') function joy:constructor() joy.super.constructor(self) self.joyX = 0 self.joyY = 0 end function joy:limitMovement() if self.joyX >= self:stickRadius() then self.joyX = self:stickRadius() end if self.joyX <= -self:stickRadius() then self.joyX = -self:stickRadius() end if self.joyY >= self:stickRadius() then self.joyY = self:stickRadius() end if self.joyY <= -self:stickRadius() then self.joyY = -self:stickRadius() end end function joy:getX() return self.joyX / self:stickRadius() end function joy:getY() return self.joyY / self:stickRadius() end function joy:draw() local _, fgc = self:getLayerColors() lovg.setColor(fgc) utils.circ('fill', self:centerX() + self.joyX, self:centerY() + self.joyY, self:stickRadius()) end function joy:stickRadius() return math.min(self.w, self.h) * 0.25 end return joy
local c = 2.1; c = c * 10; return c+ 9;
--[=[ Holds utility math functions not available on Roblox's math library. @class Math ]=] local Math = {} --[=[ Maps a number from one range to another. :::note Note the mapped value can be outside of the initial range, which is very useful for linear interpolation. ::: ```lua print(Math.Map(0.1, 0, 1, 1, 0)) --> 0.9 ``` @param Number number @param Min0 number @param Max0 number @param Min1 number @param Max1 number @return number ]=] function Math.Map(Number: number, Min0: number, Max0: number, Min1: number, Max1: number): number if Max0 == Min0 then error("Range of zero") end return (Number - Min0) * (Max1 - Min1) / (Max0 - Min0) + Min1 end --[=[ Interpolates between two numbers, given an percent. The percent is a number in the range that will be used to define how interpolated it is between num0 and num1. ```lua print(Math.Lerp(-1000, 1000, 0.75)) --> 500 ``` @param Start number -- Number @param Finish number -- Second number @param Alpha number -- The percent @return number -- The interpolated ]=] function Math.Lerp(Start: number, Finish: number, Alpha: number): number return (1 - Alpha) * Start + Alpha * Finish end --[=[ Solving for angle across from c @param A number @param B number @param C number @return number? -- Returns nil if this cannot be solved for ]=] function Math.LawOfCosines(A: number, B: number, C: number): number? local Angle = math.acos((A * A + B * B - C * C) / (2 * A * B)) if Angle ~= Angle then return nil end return Angle end --[=[ Round the given number to given precision ```lua print(Math.Round(72.1, 5)) --> 75 ``` @param Number number @param Precision number? -- Defaults to 1 @return number ]=] function Math.Round(Number: number, Precision: number?): number if Precision then return math.floor((Number / Precision :: number) + 0.5) * Precision :: number else return math.floor(Number + 0.5) end end --[=[ Rounds up to the given precision @param Number number @param Precision number @return number ]=] function Math.RoundUp(Number: number, Precision: number): number return math.ceil(Number / Precision) * Precision end --[=[ Rounds down to the given precision @param Number number @param Precision number @return number ]=] function Math.RoundDown(Number: number, Precision: number): number return math.floor(Number / Precision) * Precision end table.freeze(Math) return Math
--this = SceneNode() Tool = {} local camera = nil local mapEditor = nil local copyBufferBillboard = nil function Tool.create() camera = this:getRootNode():findNodeByType(NodeId.camera) --camera = Camera() mapEditor = Core.getBillboard("MapEditor") buildAreaPanel = mapEditor:getPanel("BuildAreaPanel") -- oldMousePos = Vec2() mouseDownPos = Vec2() selectedAreaSprite = mapEditor:getScene2DNode("selectedArea") --Overide the deActivated event and add a a local function superDeActivated = deActivated deActivated = Tool.deactivated Tool.enableChangeOfSelectedScene = true copyBufferBillboard = Core.getGlobalBillboard("copyBuffer") selectState = 0 end function Tool.deactivated() superDeActivated() print("Overide deactivation\n") if selectedAreaSprite then selectedAreaSprite:setVisible(false) selectState = 0 end end local function setMoveTool() print("setMoveTool 1\n") toolManager = this:getRootNode():findNodeByTypeTowardsLeafe(NodeId.toolManager) print("setMoveTool 2\n") if toolManager then print("setMoveTool 3\n") toolManager:setToolScript("MapEditor/Tools/SceneMoveTool.lua") print("setMoveTool 4\n") end print("setMoveTool Done\n") end local function selectNode(sceneNode) if sceneNode then local result = sceneNode:findAllNodeByTypeTowardsLeaf({NodeId.islandMesh, NodeId.mesh, NodeId.animatedMesh, NodeId.nodeMesh}) for i=1, #result do local node = result[i] print("Node Type: "..node:getNodeType().."\n") local shader = node:getShader() if shader then local newShader = Core.getShader(shader:getName(),"SELECTED") print("New shader fullName: "..newShader:getFullName().."\n") if newShader then node:setShader(newShader) end end end end end local function deSelectSceneNode(sceneNode) if sceneNode then local result = sceneNode:findAllNodeByTypeTowardsLeaf({NodeId.islandMesh, NodeId.mesh, NodeId.nodeMesh}) for i=1, #result do --print("Node Type: "..result[i]:getNodeType().."\n") local shader = result[i]:getShader() if shader then local newShader = Core.getShader(shader:getName()) print("New shader fullName: "..newShader:getFullName().."\n") if newShader then result[i]:setShader(newShader) end end end end end --Clear all selected nodes function Tool.clearSelectedNodes() local selectedNodes = Tool.getSelectedSceneNodes() for i=1, #selectedNodes do deSelectSceneNode(selectedNodes[i]) end Tool.saveSelectedScene({}) end function Tool.saveSelectedScene(selectedNodes) local previousNumScene = mapEditor:getInt("numSelectedScene") mapEditor:setInt("numSelectedScene", #selectedNodes) for i=1, #selectedNodes do mapEditor:setSceneNode("selectedScene"..tostring(i), selectedNodes[i]) end for i=#selectedNodes+1, previousNumScene do mapEditor:setSceneNode("selectedScene"..tostring(i), nil) end end --try to add a sceneNode or deselect the node if its allready added function Tool.addSelectedScene(sceneNode) local selectedScenes = Tool.getSelectedSceneNodes() --Try to deselect the sceneNode for i=1, #selectedScenes do if selectedScenes[i] == sceneNode then --deselect node deSelectSceneNode(sceneNode) selectedScenes[i] = selectedScenes[#selectedScenes] table.remove(selectedScenes,#selectedScenes) Tool.saveSelectedScene(selectedScenes) return end end --Check if the node is allready selected local tmpSceneNode = sceneNode while tmpSceneNode do for i=1, #selectedScenes do if selectedScenes[i] == tmpSceneNode then --The node is allready added in a sub node return end end tmpSceneNode = tmpSceneNode:getParent() end --Deselect nodes that has the new added node as a parent for i=1, #selectedScenes do local tmpSceneNode = selectedScenes[i] while tmpSceneNode do if sceneNode == tmpSceneNode then --this node will be selected by the newly added node deSelectSceneNode(sceneNode) selectedScenes[i] = selectedScenes[#selectedScenes] table.remove(selectedScenes,#selectedScenes) i = i - 1 tmpSceneNode = nil else tmpSceneNode = tmpSceneNode:getParent() end end end --The node needs to be added selectNode(sceneNode) selectedScenes[#selectedScenes+1] = sceneNode Tool.saveSelectedScene(selectedScenes) end function Tool.getCollision(collisionAgainsObject, collisionAgainsSpace) local selectedScene = mapEditor:getSceneNode("editScene") if selectedScene and buildAreaPanel == Form.getPanelFromGlobalPos( Core.getInput():getMousePos() ) then local mouseLine = camera:getWorldLineFromScreen(Core.getInput():getMousePos()) local outNormal = Vec3() local collisionNode = nil local collisionPos = Vec3() if collisionAgainsObject then collisionNode = selectedScene:collisionTree( mouseLine, outNormal) else collisionNode = selectedScene:collisionTree( mouseLine, outNormal, {NodeId.islandMesh} ) end if collisionNode then if collisionNode:getNodeType() == NodeId.islandMesh then collisionNode = collisionNode:findNodeByTypeTowardsRoot(NodeId.island) elseif collisionNode:getNodeType() == NodeId.mesh or collisionNode:getNodeType() == NodeId.animatedMesh then collisionNode = collisionNode:findNodeByTypeTowardsRoot(NodeId.model) end end if collisionNode then --Core.addDebugSphere(Sphere(mouseLine.endPos, 0.1), 0.01, Vec3(1)) --Core.addDebugLine(mouseLine.endPos, mouseLine.endPos + outNormal, 0.01, Vec3(0,1,0)) return collisionNode, mouseLine.endPos, outNormal:normalizeV() elseif collisionAgainsSpace and Collision.lineSegmentPlaneIntersection(collisionPos, mouseLine, Vec3(0,1,0), Vec3(0))then local closestIsland = nil local closestDist = nil --Core.addDebugSphere(Sphere(collisionPos, 1.0),0, Vec3(1,0,0)) ilands = selectedScene:getRootNode():findAllNodeByTypeTowardsLeaf(NodeId.island) for i=1, #ilands do local island = ilands[i] --island = Island() local point = Vec3(collisionPos) local dist = island:getDistanceToIsland(point) if not closestIsland or dist < closestDist then --print("collision found\n") closestIsland = island closestDist = dist end end --Core.addDebugSphere(Sphere(collisionPos, 0.9),0, Vec3(0,1,0)) return closestIsland, collisionPos, Vec3(0,1,0) else return nil, Vec3(), Vec3() end end return nil, Vec3(), Vec3() end function Tool.trySelectNewScene(changeTool) if Core.getInput():getMouseDown( MouseKey.left ) and buildAreaPanel == Form.getPanelFromGlobalPos( Core.getInput():getMousePos() ) then print("mouseDown\n") mouseDownPos = Core.getInput():getMousePos() selectState = 1 elseif Core.getInput():getMouseHeld(MouseKey.left) and ( selectState == 1 or selectState == 2) then --Render select area, blue sprite selectState = 2 local mousePos = Core.getInput():getMousePos() if (mousePos-mouseDownPos):length() > 8 then if not selectedAreaSprite then selectedAreaSprite = Sprite(Vec4(0.2,0.2,1,0.5)) camera:add2DScene(selectedAreaSprite) mapEditor:setScene2DNode("selectedArea", selectedAreaSprite) -- print("Selected area visible") else selectedAreaSprite:setVisible(true) -- print("Selected area visible") end local minPos = Vec2(mouseDownPos) minPos:minimize( mousePos ) local maxPos = Vec2(mouseDownPos) maxPos:maximize( mousePos ) minPos = Vec2(math.round(minPos.x), math.round(minPos.y)) maxPos = Vec2(math.round(maxPos.x), math.round(maxPos.y)) selectedAreaSprite:setPosition(minPos) selectedAreaSprite:setSize(maxPos-minPos) -- if (oldMousePos-mouseDownPos):length() > 2 then -- oldMousePos = mouseDownPos -- print("position: "..minPos.x..", "..minPos.y) -- print("size: "..(maxPos-minPos).x..", "..(maxPos-minPos).y) -- end end elseif Core.getInput():getMousePressed(MouseKey.left) and selectState == 2 then selectState = 0 if selectedAreaSprite then selectedAreaSprite:setVisible(false) -- print("Selected area hidden") end local mousePos = Core.getInput():getMousePos() if (mousePos-mouseDownPos):length() > 8 then print("Select area\n") local corner1 = camera:getWorldLineFromScreen(mouseDownPos).endPos local corner2 = camera:getWorldLineFromScreen(Vec2(mousePos.x,mouseDownPos.y)).endPos local corner3 = camera:getWorldLineFromScreen(mousePos).endPos local corner4 = camera:getWorldLineFromScreen(Vec2(mouseDownPos.x, mousePos.y)).endPos local frustrum = Frustrum( camera:getGlobalPosition(), corner1, corner2, corner3, corner4) local playerNode = this:getRootNode():findNodeByType(NodeId.playerNode) local nodeList = playerNode:collisionTree(frustrum, {NodeId.mesh}) if #nodeList ~= 0 then if not Core.getInput():getKeyHeld(Key.lctrl) then Tool.clearSelectedNodes() end local selectedModels = {} for i=1, #nodeList do local modelNode = nodeList[i]:findNodeByTypeTowardsRoot(NodeId.model) local added = false for n=1, #selectedModels do if selectedModels[n] == modelNode then added = true end end if not added then selectedModels[#selectedModels + 1] = modelNode Tool.addSelectedScene(modelNode) end end if ( changeTool == nil or changeTool == true ) then setMoveTool() end end else local sceneNode = Tool.getCollision(true,false) if sceneNode and sceneNode:getNodeType() == NodeId.mesh then sceneNode = sceneNode:findNodeByTypeTowardsRoot(NodeId.model) --disclaimer this will not work when we have the mesh parent model as edit node end if not Core.getInput():getKeyHeld(Key.lctrl) then Tool.clearSelectedNodes() end Tool.addSelectedScene( sceneNode ) if sceneNode and ( changeTool == nil or changeTool == true ) then setMoveTool() end end local selectedNodes = Tool.getSelectedSceneNodes() end end function Tool.tryChangeTool() if buildAreaPanel == Form.getPanelFromGlobalPos( Core.getInput():getMousePos() ) and mapEditor:getInt("numSelectedScene") > 0 then toolManager = this:getRootNode():findNodeByTypeTowardsLeafe(NodeId.toolManager) if toolManager then if Core.getInput():getKeyDown( Key.t ) then toolManager:setToolScript("MapEditor/Tools/SceneScaleTool.lua") elseif Core.getInput():getKeyDown( Key.r ) then toolManager:setToolScript("MapEditor/Tools/SceneRotateTool.lua") elseif Core.getInput():getKeyDown( Key.g ) or Core.getInput():getKeyDown( Key.m ) then toolManager:setToolScript("MapEditor/Tools/SceneMoveTool.lua") end end end end function Tool.getSelectedSceneNodes() local out = {} local numSelectedNodes = mapEditor:getInt("numSelectedScene") for i=1, numSelectedNodes do out[i] = mapEditor:getSceneNode("selectedScene"..tostring(i)) end return out end function Tool.getSelectedNodesMatrix(selectedScenesNodes) if #selectedScenesNodes == 0 then return Matrix() elseif #selectedScenesNodes == 1 then return selectedScenesNodes[1]:getGlobalMatrix() else local centerPos = Vec3() for i=1, #selectedScenesNodes do centerPos = centerPos + selectedScenesNodes[i]:getGlobalPosition() end centerPos = centerPos / #selectedScenesNodes return Matrix(centerPos) end end function renderAllChildBoundVolumes(node) if node then if node:getBoundType() == BoundType.Sphere then Core.addDebugSphere(node:getGlobalBoundingSphere(), 60, Vec3(1) ) elseif node:getBoundType() == BoundType.Box then Core.addDebugBox(node:getGlobalBoundingBox(), 60, Vec3(1) ) end for i=1, node:getChildSize() do renderAllChildBoundVolumes( node:getChildNode(i) ) end end end function Tool.update() -- if Core.getInput():getKeyPressed( Key.t ) then -- -- local islands = this:getRootNode():findAllNodeByTypeTowardsLeaf(NodeId.island) -- -- for i=1, #islands do -- renderAllChildBoundVolumes(islands[i]) -- end -- end if Core.getInput():getMouseDown( MouseKey.right ) then toolManager = this:getRootNode():findNodeByTypeTowardsLeafe(NodeId.toolManager) if toolManager then toolManager:setToolScript("MapEditor/Tools/SceneSelectTool.lua") end print("Deselect nodes\n") local selectedNodes = Tool.getSelectedSceneNodes() for i=1, #selectedNodes do deSelectSceneNode(selectedNodes[i]) end mapEditor:setInt("numSelectedScene",0) end if Core.getInput():getKeyHeld(Key.lctrl) and Core.getInput():getKeyDown(Key.h) then if showDebugModels==nil then showDebugModels = false else showDebugModels = not showDebugModels end local nodeList = this:getRootNode():findAllNodeByNameTowardsLeaf("*debug*") for i=1, #nodeList, 1 do nodeList[i]:setVisible(showDebugModels) end end if Tool.enableChangeOfSelectedScene then if Core.getInput():getKeyDown(Key.delete) then local selectedScene = Tool.getSelectedSceneNodes() Tool.clearSelectedNodes() for i=1, #selectedScene do selectedScene[i]:destroy() end end if Core.getInput():getKeyHeld(Key.lctrl) then local selectedScene = Tool.getSelectedSceneNodes() if selectedScene and Core.getInput():getKeyDown(Key.c)then copyBufferBillboard:setInt("numBuffers", #selectedScene) local globalCenterPos = Vec3() for i=1, #selectedScene do globalCenterPos = globalCenterPos + selectedScene[i]:getGlobalPosition() end local globalMatrixOffset = Matrix(globalCenterPos / #selectedScene) globalMatrixOffset:inverse() for i=1, #selectedScene do selectedScene[i]:saveScene("Data/Dynamic/tmpbuffer/scenes/sceneCopyBuffer"..i) copyBufferBillboard:setBool("isBufferAIsland"..i, selectedScene[i]:findNodeByTypeTowardsLeafe(NodeId.island) ~= nil ) copyBufferBillboard:setMatrix("LocalMatrix"..i, globalMatrixOffset * selectedScene[i]:getGlobalMatrix()); end elseif selectedScene and Core.getInput():getKeyDown(Key.v) then local node, globalPosition = Tool.getCollision(false, true) if node == nil then node = this:findNodeByType(NodeId.playerNode) end local parentNode = node:findNodeByTypeTowardsRoot(NodeId.island) and node:findNodeByTypeTowardsRoot(NodeId.island) or node:findNodeByTypeTowardsRoot(NodeId.playerNode) local offsetLocalPos = parentNode:getGlobalMatrix():inverseM() * globalPosition if parentNode then Tool.clearSelectedNodes() local numBuffers = copyBufferBillboard:getInt("numBuffers") for i=1, numBuffers do if copyBufferBillboard:getBool("isBufferAIsland"..i) and parentNode:getNodeType() ~= NodeId.playerNode then local playerNode = parentNode:findNodeByType(NodeId.playerNode) if playerNode then local node = parentNode:loadScene("Data/Dynamic/tmpbuffer/scenes/sceneCopyBuffer"..i) node:setLocalMatrix( copyBufferBillboard:getMatrix("LocalMatrix"..i)) node:setLocalPosition( node:getLocalPosition() + globalPosition ) Tool.addSelectedScene( node ) else print("player node was not found the copy buffer is ignored") end else local node = parentNode:loadScene("Data/Dynamic/tmpbuffer/scenes/sceneCopyBuffer"..i) node:setLocalMatrix( copyBufferBillboard:getMatrix("LocalMatrix"..i)) node:setLocalPosition( node:getLocalPosition() + offsetLocalPos ) Tool.addSelectedScene( node ) end end end end if #selectedScene and #selectedScene > 0 then if Core.getInput():getKeyDown(Key.d) then Tool.clearSelectedNodes() copyBufferBillboard:setInt("numBuffers", 0) for i=1, #selectedScene do selectedScene[i]:saveScene("Data/Dynamic/tmpbuffer/scenes/sceneCopyBuffer") Tool.addSelectedScene( selectedScene[i]:getParent():loadScene("Data/Dynamic/tmpbuffer/scenes/sceneCopyBuffer") ) end end if Core.getInput():getKeyHeld(Key.lshift) and Core.getInput():getKeyDown(Key.j) then Tool.clearSelectedNodes() if #selectedScene == 1 then local meshes = selectedScene[1]:findAllNodeByTypeTowardsLeaf({NodeId.mesh, NodeId.animatedMesh}) local parentNode = selectedScene[1]:getParent() local invParentMatrix = parentNode:getGlobalMatrix():inverseM() for i=1, #meshes do local model = Model() parentNode:addChild(model) model:setLocalMatrix(invParentMatrix * meshes[i]:getGlobalMatrix()) meshes[i]:setLocalMatrix(Matrix()) model:addChild(meshes[i]) Tool.addSelectedScene(model) end --destroy remaining nodes selectedScene[1]:destroy() end elseif Core.getInput():getKeyDown(Key.j) then local model = Model() selectedScene[1]:getParent():addChild(model) local globalCenterPos = selectedScene[1]:getGlobalPosition() for i=2, #selectedScene do globalCenterPos = globalCenterPos + selectedScene[i]:getGlobalPosition() end globalCenterPos = globalCenterPos / #selectedScene model:setLocalPosition( model:getGlobalMatrix():inverseM() * globalCenterPos ) local inverseModelMatrix = model:getGlobalMatrix():inverseM() for i=1, #selectedScene do local nodes = selectedScene[i]:getChildNodes() for n=1, #nodes do local matix = nodes[n]:getGlobalMatrix() nodes[n]:setLocalMatrix(inverseModelMatrix * matix) model:addChild(nodes[n]) end selectedScene[i]:destroy() end Tool.clearSelectedNodes() Tool.addSelectedScene(model) end end end --Render the selected scene -- local selectedScene = mapEditor:getSceneNode("selectedScene1") -- if selectedScene then -- Core.addDebugBox(selectedScene:getGlobalBoundingBox(), 0.0, Vec3(0.8)) -- end end end
--- -- @author wesen -- @copyright 2020 wesen <wesen-ac@web.de> -- @release 0.1 -- @license MIT -- local BaseIncludeCommandParser = require "src.IncludeFileResolver.IncludeCommandParser.Base" --- -- IncludeCommandParser for the "exec" command. -- The "exec" command includes single cubescript files. -- -- @type ExecIncludeCommandParser -- local ExecIncludeCommandParser = BaseIncludeCommandParser:extend() --- -- ExecIncludeCommandParser. -- -- @tparam FileFinder _fileFinder The FileFinder to use to find included File's -- function ExecIncludeCommandParser:new(_fileFinder) BaseIncludeCommandParser.new(self, _fileFinder, "exec +\"scripts/([^\"]+)\";?") end -- Public Methods --- -- Parses a line that contains a "exec" command and returns the File's that are included by the command. -- -- @tparam string _line The line with the include command -- -- @treturn File[] The list of File's that are included by the command -- function ExecIncludeCommandParser:getFilesIncludedByIncludeCommand(_line) local includeFilePath = _line:match(self.commandPattern) local includeFile = self.fileFinder:getFile(includeFilePath) return { includeFile } end return ExecIncludeCommandParser
-- Creative Item Barrel Block storage_barrels.base_ndef.groups = storage_barrels.item_groups storage_barrels.base_ndef.max_count = -1 local ndef = table.copy(storage_barrels.base_ndef) ndef.description = "Creative Item Barrel" storage_barrels.configure_item_barrel_ndef(ndef, "storage_barrels_top_item_creative.png", false, true) storage_barrels.configure_locked_barrel_ndef(ndef) minetest.register_node("storage_barrels:item_creative", ndef) -- Creative Liquid Barrel Block if storage_barrels.enable_liquid_barrels then storage_barrels.base_ndef.groups = storage_barrels.liquid_groups storage_barrels.base_ndef.max_count = -1 local ndef = table.copy(storage_barrels.base_ndef) ndef.description = "Creative Liquid Barrel" storage_barrels.configure_liquid_barrel_ndef(ndef, "storage_barrels_top_liquid_creative.png", false, true) storage_barrels.configure_locked_barrel_ndef(ndef) minetest.register_node("storage_barrels:liquid_creative", ndef) end
/* - TO DO LIST - 3D Health Bars for apothecaries - Squad system - Stamina, Health, Armor - */ nut.bar = nut.bar or {} nut.bar.list = {} nut.bar.delta = nut.bar.delta or {} nut.bar.actionText = "" nut.bar.actionStart = 0 nut.bar.actionEnd = 0 local width = ScrW() local height = ScrH() local maxWidth = (width * 0.05) * 4 local startWidth = width/2 - ((width * 0.05)*2) local aimDirs = {} aimDirs[360] = "N" aimDirs[0] = "N" aimDirs[45] = "NE" aimDirs[90] = "E" aimDirs[135] = "SE" aimDirs[180] = "S" aimDirs[225] = "SW" aimDirs[270] = "W" aimDirs[315] = "NW" local numsDir = {} numsDir[0] = -3 numsDir[1] = -2 numsDir[2] = -1 numsDir[3] = 0 numsDir[4] = 1 numsDir[5] = 2 numsDir[6] = 3 function nut.bar.get(identifier) for i = 1, #nut.bar.list do local bar = nut.bar.list[i] if (bar and bar.identifier == identifier) then return bar end end end function nut.bar.add(getValue, color, priority, identifier) if (identifier) then local oldBar = nut.bar.get(identifier) if (oldBar) then table.remove(nut.bar.list, oldBar.priority) end end priority = priority or table.Count(nut.bar.list) + 1 local info = nut.bar.list[priority] nut.bar.list[priority] = { getValue = getValue, color = color or info.color or Color(math.random(150, 255), math.random(150, 255), math.random(150, 255)), priority = priority, lifeTime = 0, identifier = identifier } return priority end local color_dark = Color(0, 0, 0, 225) local gradient = nut.util.getMaterial("vgui/gradient-u") local gradient2 = nut.util.getMaterial("vgui/gradient-d") local surface = surface local text1 = false function nut.bar.draw(x, y, w, h, value, color) nut.util.drawBlurAt(x, y, w, h) surface.SetDrawColor(255, 255, 255, 15) surface.DrawRect(x, y, w, h) surface.DrawOutlinedRect(x, y, w, h) x, y, w, h = x + 2, y + 2, (w - 4) * math.min(value, 1), h - 4 surface.SetDrawColor(color.r, color.g, color.b, 250) surface.DrawRect(x, y, w, h) surface.SetDrawColor(255, 255, 255, 8) surface.SetMaterial(gradient) surface.DrawTexturedRect(x, y, w, h) --draw.SimpleText((math.Round( (value * 100), 1 )), "CenturyGothic", x + w*.03, y + h/2 - 2, color_white, 3, 1) end function nut.bar.drawSquadHP(x, y, w, h, client) nut.util.drawBlurAt(x, y, w, h) surface.SetDrawColor(255, 255, 255, 15) surface.DrawRect(x, y, w, h) surface.DrawOutlinedRect(x, y, w, h) x, y, w, h = x + 2, y + 2, (w - 4) * (client:Health() / client:GetMaxHealth()), (h - 4) surface.SetDrawColor(150, 30, 20, 250) surface.DrawRect(x, y, w, h) surface.SetDrawColor(255, 255, 255, 8) surface.SetMaterial(gradient) surface.DrawTexturedRect(x, y, w, h) end function nut.bar.drawSquadArmor(x, y, w, h, client) nut.util.drawBlurAt(x, y, w, h) surface.SetDrawColor(255, 255, 255, 15) surface.DrawRect(x, y, w, h) surface.DrawOutlinedRect(x, y, w, h) x, y, w, h = x + 2, y + 2, (w - 4) * (client:Armor() / 500), (h - 4) surface.SetDrawColor(255, 215, 0, 250) surface.DrawRect(x, y, w, h) surface.SetDrawColor(255, 255, 255, 8) surface.SetMaterial(gradient) surface.DrawTexturedRect(x, y, w, h) draw.SimpleText(client:Nick(), "CenturyGothicSmall", x + w*.03, y + h + 15, color_white, 3, 1) end local TEXT_COLOR = Color(240, 240, 240) local SHADOW_COLOR = Color(20, 20, 20) local Approach = math.Approach local hp = nut.util.getMaterial("vgui/redbar.png") local armor = nut.util.getMaterial("vgui/Armor.png") local stm = nut.util.getMaterial("vgui/marine.png") local psy = nut.util.getMaterial("vgui/psyker.png") local hpborder1 = nut.util.getMaterial("vgui/border_1.png") local hpborder2 = nut.util.getMaterial("vgui/border_2.png") local hpborder3 = nut.util.getMaterial("vgui/border_3.png") local hpbar1 = nut.util.getMaterial("vgui/border_icon_1.png") local hpbar2 = nut.util.getMaterial("vgui/border_icon_2.vmt") local hpbar3 = nut.util.getMaterial("vgui/border_icon_3.png") local hpbar4 = nut.util.getMaterial("vgui/border_icon_4.png") BAR_HEIGHT = 10 function DrawBorder( client ) local len = ( math.min(client:Health(),client:GetMaxHealth() ) / 5) local len2 = 35 + ( client:GetMaxHealth() / 5) if client:GetMaxHealth() < 500 then len2 = 35 + ( client:GetMaxHealth() / 2) end surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( hpborder2 ) surface.DrawTexturedRect( ScrW() * 0.05, 80, len2 - 100, 38) surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( hpborder1 ) surface.DrawTexturedRect( ScrW() * 0.040, 80, 48, 38) render.SetScissorRect( ScrW() * 0.05 + len2 - 100, 80, ScrW() * 0.05 + len2 - 00, 120, true ) surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial( hpborder3 ) surface.DrawTexturedRect( ScrW() * 0.05 + len2 - 135, 80, 139, 38) render.SetScissorRect( 0, 0, 0, 0, false ) -- Disable after you are done end function DrawHealth( client ) local len = ( math.min(client:Health(),client:GetMaxHealth() ) / 5) local len2 = 110 + ( client:GetMaxHealth() / 5) if client:GetMaxHealth() < 500 then len = ( math.min(client:Health(),client:GetMaxHealth() ) / 2) end if LocalPlayer():Alive() then surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( hpbar1 ) surface.DrawTexturedRect( ScrW() * 0.023, 80, 38, 38) end DrawStm( LocalPlayer() ) DrawArmor( LocalPlayer() ) DrawBorder( LocalPlayer() ) if LocalPlayer():Alive() then surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial( hpbar2 ) surface.DrawTexturedRectUV( ScrW() * 0.043 + 7, 90, len, 20, 0, 0, 1, 1 ) render.SetScissorRect( ScrW() * 0.043, 90, ScrW() * 0.043 + 7, 110, true ) surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial( hpbar3 ) surface.DrawTexturedRectUV( ScrW() * 0.043, 90, 26, 20, 0, 0, 1, 1 ) render.SetScissorRect( 0, 0, 0, 0, false ) -- Disable after you are done end end function DrawArmor( client ) local len = ScrW() * 0.04 + client:Armor() local len2 = 45 + 5000 local col = Color(255, 255, 0) local armor = { { x = ScrW() * 0.04, y = 83 }, { x = math.max ( ScrW() * 0.04 ,len ), y = 83 }, { x = math.max ( ScrW() * 0.04, len), y = 90 }, { x = ScrW() * 0.043, y = 90 }, } local armor2 = { { x = ScrW() * 0.043, y = 105 }, { x = math.max ( ScrW() * 0.04 ,len ), y = 105 }, { x = math.max ( ScrW() * 0.04, len), y = 117 }, { x = ScrW() * 0.04, y = 117 }, } surface.SetDrawColor( col ) draw.NoTexture() surface.DrawPoly( armor ) surface.SetDrawColor( col ) draw.NoTexture() surface.DrawPoly( armor2 ) end function DrawStm( client ) local len = ScrW() * 0.04 + LocalPlayer():getLocalVar("stm", 0) * 2 local len2 = 90 local col = Color(0, 115, 0) local stm = { { x = ScrW() * 0.04, y = 130 }, { x = math.max ( ScrW() * 0.04 ,len ), y = 130 }, { x = math.max ( ScrW() * 0.04, len), y = 150 }, { x = ScrW() * 0.04, y = 150 }, } DrawPsy( LocalPlayer() ) surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( hpborder2 ) surface.DrawTexturedRect( ScrW() * 0.05, 120, len2, 38) surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( hpborder1 ) surface.DrawTexturedRect( ScrW() * 0.040, 120, 48, 38) surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial( hpborder3 ) surface.DrawTexturedRect( ScrW() * 0.05 + len2, 120, 139, 38) surface.SetDrawColor( col ) draw.NoTexture() surface.DrawPoly( stm ) end function DrawPsy( client ) local len = ScrW() * 0.04 + LocalPlayer():getLocalVar("psy", 0) * 2 local col = Color(150, 20, 150) local psy1 = { { x = ScrW() * 0.04, y = 123 }, { x = math.max ( ScrW() * 0.04 ,len ), y = 123 }, { x = math.max ( ScrW() * 0.04, len), y = 128 }, { x = ScrW() * 0.043, y = 128 }, } local psy2 = { { x = ScrW() * 0.043, y = 145 }, { x = math.max ( ScrW() * 0.04 ,len ), y = 145 }, { x = math.max ( ScrW() * 0.04, len), y = 158 }, { x = ScrW() * 0.04, y = 158 }, } surface.SetDrawColor( col ) draw.NoTexture() surface.DrawPoly( psy1 ) surface.SetDrawColor( col ) draw.NoTexture() surface.DrawPoly( psy2 ) end function nut.bar.drawAll() if (hook.Run("ShouldHideBars")) then return end local players = (team.NumPlayers(LocalPlayer():Team())) if !IsValid(iconmodel) then iconmodel = vgui.Create("nutSquad") iconmodel:SetPos(ScrW() * 0.02, ScrH() / 3) iconmodel:SetSize(64,(64 * (players - 1))) iconmodel:ParentToHUD() timer.Create("SquadRefresh", 120, 0, function() iconmodel:Remove() end) end DrawHealth( LocalPlayer() ) local w, h = surface.ScreenWidth() * 0.10, BAR_HEIGHT local x, y = ScrW() * 0.02 + 70, ScrH() / 3 local deltas = nut.bar.delta local frameTime = FrameTime() local curTime = CurTime() for k, v in ipairs(team.GetPlayers(LocalPlayer():Team())) do --print(v) --print(LocalPlayer()) if v == LocalPlayer() then else nut.bar.drawSquadHP(x, y, w, h, v) y = y + h nut.bar.drawSquadArmor(x, y, w, h, v) y = y - h + 65 end end /* for i = 1, #nut.bar.list do local bar = nut.bar.list[i] if (bar) then local realValue = bar.getValue() nut.bar.draw(x, y, w, h + 10, realValue, bar.color, bar) y = y + h + 20 end end surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( hp ) surface.DrawTexturedRect( 60, 105, 30, 30) surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( armor ) surface.DrawTexturedRect( 60, 135, 30, 30)*/ surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( stm ) surface.DrawTexturedRect( 40, 125, 35, 35) nut.bar.drawAction() local dirWidth = (width / 20) local dirStartWidth = (dirWidth* 10) + (dirWidth * 3) local aimDir = 359 - math.floor(math.NormalizeAngle( LocalPlayer():EyeAngles().yaw) + 180) draw.SimpleText( aimDir,"CenturyGothic",width/2, 16,Color(255, 255, 255),TEXT_ALIGN_CENTER,TEXT_ALIGN_TOP) local offset = 0 for i=0,6 do local dived = (math.floor((aimDir )/45)) local tempDir = 45 * ((dived - numsDir[(i )] + offset) % 9) if aimDir <= 134 && tempDir >= 270 then offset = -45 else if aimDir <= 90 then offset = 0 end end if aimDir >= 270 && tempDir < 135 then offset = 45 else if aimDir >= 270 then offset = 0 end end tempDir = tempDir + offset draw.SimpleText( aimDirs[tempDir] or tempDir ,"CenturyGothic",dirStartWidth - (i* dirWidth) - (((aimDir % 45)/45) * dirWidth) , 16 + 25,Color(255, 255, 255),TEXT_ALIGN_CENTER,TEXT_ALIGN_TOP) end end
return { corerad = { acceleration = 0, airsightdistance = 1045, brakerate = 0, buildangle = 65536, buildcostenergy = 10275, buildcostmetal = 787, builder = false, buildinggrounddecaldecayspeed = 30, buildinggrounddecalsizex = 6, buildinggrounddecalsizey = 6, buildinggrounddecaltype = "corerad_aoplane.dds", buildpic = "corerad.dds", buildtime = 12000, canattack = true, canstop = 1, category = "ALL SURFACE", collisionvolumeoffsets = "0 -3 0", collisionvolumescales = "56 56 56", collisionvolumetype = "CylY", corpse = "corerad_dead", defaultmissiontype = "GUARD_NOMOVE", description = "Heavy Missile Battery", explodeas = "LARGE_BUILDINGEX", firestandorders = 1, footprintx = 4, footprintz = 4, icontype = "building", idleautoheal = 5, idletime = 1800, losemitheight = 50, mass = 787, maxdamage = 3210, maxslope = 10, maxvelocity = 0, maxwaterdepth = 0, name = "Eradicator", noautofire = false, objectname = "corerad", radaremitheight = 49, seismicsignature = 0, selfdestructas = "LARGE_BUILDING", sightdistance = 300, standingfireorder = 2, turninplaceanglelimit = 140, turninplacespeedlimit = 0, turnrate = 0, unitname = "corerad", usebuildinggrounddecal = true, yardmap = "oooooooooooooooo", customparams = { buildpic = "corerad.dds", faction = "CORE", prioritytarget = "air", }, featuredefs = { corerad_dead = { blocking = true, damage = 3757, description = "Rapid Eradicator Wreckage", energy = 0, featuredead = "corerad_heap", footprintx = 4, footprintz = 4, metal = 1431, object = "CORERAD_DEAD", reclaimable = true, customparams = { fromunit = 1, }, }, corerad_heap = { blocking = false, damage = 4696, description = "Rapid Eradicator Debris", energy = 0, footprintx = 3, footprintz = 3, metal = 763, object = "3X3B", reclaimable = true, customparams = { fromunit = 1, }, }, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { canceldestruct = "cancel2", cloak = "kloak1", uncloak = "kloak1un", underattack = "warning1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "twrturn3", }, select = { [1] = "twrturn3", }, }, weapondefs = { cor_erad2 = { areaofeffect = 64, avoidfeature = false, burnblow = true, canattackground = false, cegtag = "Core_Def_AA_Rocket", craterareaofeffect = 0, craterboost = 0, cratermult = 0, explosiongenerator = "custom:CORE_FIRE_SMALL", firestarter = 20, flighttime = 2.75, impulseboost = 0, impulsefactor = 0, model = "weapon_missile", name = "ExplosiveRockets", noselfdamage = true, proximitypriority = -4, range = 1045, reloadtime = 0.125, smoketrail = true, soundhitdry = "xplosml2", soundhitwet = "splsmed", soundhitwetvolume = 0.6, soundstart = "rocklit1", soundtrigger = true, startvelocity = 750, texture1 = "null", texture2 = "coresmoketrail", texture3 = "null", texture4 = "null", tolerance = 10000, tracks = true, turnrate = 25000, turret = true, weaponacceleration = 200, weapontimer = 3, weapontype = "MissileLauncher", weaponvelocity = 1500, damage = { areoship = 20, default = 5, priority_air = 80, unclassed_air = 80, }, }, }, weapons = { [1] = { badtargetcategory = "SCOUT SUPERSHIP", --Ground AA def = "COR_ERAD2", onlytargetcategory = "VTOL", }, }, }, }
local M, decompress, bin = {}, require("casc.platform").decompress, require("casc.bin") local CONCAT_CHUNK_SIZE, CONCAT_STOP_LENGTH = 512, 16384 function M.patch(old, patch) local ssub, int64ish_le, sadd = string.sub, bin.int64ish_le, bin.sadd if ssub(patch, 1, 8) ~= "ZBSDIFF1" then return nil, "corrupt patch: signature mismatch" end local csz, dsz, nsz = int64ish_le(patch, 8), int64ish_le(patch, 16), int64ish_le(patch, 24) if #patch < 32 + csz + dsz then return nil, "corrupt patch: header size mismatch" end local control = decompress(ssub(patch, 33, 32+csz)) local data = decompress(ssub(patch, 33+csz, 32+csz+dsz)) local extra = decompress(ssub(patch, 33+csz+dsz)) local o, on, oh, op, dp, ep, np = {}, 1, 1, 1,1,1, 0 for p=0,#control-1,24 do local x, y = int64ish_le(control, p), int64ish_le(control, p+8) if x < 0 or y < 0 then return nil, "corrupt patch: negative block length" elseif np + x + y > nsz then return nil, "corrupt patch: overflows declared size" elseif #data < dp + x - 1 then return nil, "corrupt patch: overread data" elseif #extra < ep + y - 1 then return nil, "corrupt patch: overread extra" end if x > 0 then dp, op, on = dp + x, op + x, sadd(data, dp, old, op, x, o, on) end if y > 0 then o[on], on, ep = ssub(extra, ep, ep + y - 1), on+1, ep + y end if oh + CONCAT_CHUNK_SIZE < on then o[oh], on = table.concat(o, "", oh, on-1), oh + 1 if #o[oh] > CONCAT_STOP_LENGTH then oh = oh + 1 end end op, np = op + int64ish_le(control, p+16), np + x + y end if np ~= nsz then return nil, "corrupt patch: underflows declared size" end return table.concat(o, "", 1, on-1) end return M
ITEM.name = "Mama's beads" ITEM.model ="models/nasca/etherealsrp_artifacts/mamas_beads.mdl" ITEM.description = "Helix-shaped, pulsating artifact." ITEM.longdesc = "Effectively heals minor wounds, and can heal large wounds over a long period of time. Emits insignificant radiation. Initial skin discoloration upon healing, effect reduces over time. [ +2 WH | +1 RAD]" ITEM.width = 1 ITEM.height = 1 ITEM.price = 33250 ITEM.flag = "A" ITEM.buff = "woundheal" ITEM.buffval = 2 ITEM.debuff = "rads" ITEM.debuffval = 1 ITEM.isArtefact = true ITEM.weight = 1.3;
local CorePackages = game:GetService("CorePackages") local Roact = require(CorePackages.Roact) local Components = script.Parent.Parent.Parent.Components local DataConsumer = require(Components.DataConsumer) local HeaderButton = require(Components.HeaderButton) local CellLabel = require(Components.CellLabel) local Constants = require(script.Parent.Parent.Parent.Constants) local GeneralFormatting = Constants.GeneralFormatting local LINE_WIDTH = GeneralFormatting.LineWidth local LINE_COLOR = GeneralFormatting.LineColor local ActionBindingsFormatting = Constants.ActionBindingsFormatting local HEADER_NAMES = ActionBindingsFormatting.ChartHeaderNames local CELL_WIDTHS = ActionBindingsFormatting.ChartCellWidths local HEADER_HEIGHT = ActionBindingsFormatting.HeaderFrameHeight local ENTRY_HEIGHT = ActionBindingsFormatting.EntryFrameHeight local CELL_PADDING = ActionBindingsFormatting.CellPadding local MIN_FRAME_WIDTH = ActionBindingsFormatting.MinFrameWidth local IS_CORE_STR = "Core" local IS_DEVELOPER_STR = "Developer" local NON_FOUND_ENTRIES_STR = "No ActionBindings Found" -- create table of offsets and sizes for each cell local totalCellWidth = 0 for _, cellWidth in ipairs(CELL_WIDTHS) do totalCellWidth = totalCellWidth + cellWidth end local currOffset = -totalCellWidth local cellOffset = {} local headerCellSize = {} local entryCellSize = {} currOffset = currOffset / 2 table.insert(cellOffset, UDim2.new(0, CELL_PADDING, 0, 0)) table.insert(headerCellSize, UDim2.new(.5, currOffset - CELL_PADDING, 0, HEADER_HEIGHT)) table.insert(entryCellSize, UDim2.new(.5, currOffset - CELL_PADDING, 0, ENTRY_HEIGHT)) for _, cellWidth in ipairs(CELL_WIDTHS) do table.insert(cellOffset,UDim2.new(.5, currOffset + CELL_PADDING, 0, 0)) table.insert(headerCellSize, UDim2.new(0, cellWidth - CELL_PADDING, 0, HEADER_HEIGHT)) table.insert(entryCellSize, UDim2.new(0, cellWidth - CELL_PADDING, 0, ENTRY_HEIGHT)) currOffset = currOffset + cellWidth end table.insert(cellOffset,UDim2.new(.5, currOffset + CELL_PADDING, 0, 0)) table.insert(headerCellSize, UDim2.new(.5, (-totalCellWidth / 2) - CELL_PADDING, 0, HEADER_HEIGHT)) table.insert(entryCellSize, UDim2.new(.5, (-totalCellWidth / 2) - CELL_PADDING, 0, ENTRY_HEIGHT)) local verticalOffsets = {} for i, offset in ipairs(cellOffset) do verticalOffsets[i] = UDim2.new( offset.X.Scale, offset.X.Offset - CELL_PADDING, offset.Y.Scale, offset.Y.Offset) end local ActionBindingsChart = Roact.Component:extend("ActionBindingsChart") local function constructHeader(onSortChanged, width) local header = {} for ind, name in ipairs(HEADER_NAMES) do header[name] = Roact.createElement(HeaderButton, { text = name, size = headerCellSize[ind], pos = cellOffset[ind], sortfunction = onSortChanged, }) end header["upperHorizontalLine"] = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, LINE_WIDTH), Position = UDim2.new(0, 0, 0, 0), BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }) header["lowerHorizontalLine"] = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, LINE_WIDTH), Position = UDim2.new(0, 0, 1, -LINE_WIDTH), BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }) for ind = 2, #verticalOffsets do local key = string.format("VerticalLine_%d",ind) header[key] = Roact.createElement("Frame", { Size = UDim2.new(0, LINE_WIDTH, 1, 0), Position = verticalOffsets[ind], BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }) end return Roact.createElement("Frame", { Size = UDim2.new(0, width, 0, HEADER_HEIGHT), BackgroundTransparency = 1, }, header) end local function constructEntry(entry, width, layoutOrder) local name = entry.name local actionInfo = entry.actionInfo -- the last element is special cased because the data in the -- string is passed in as value in the table -- use tostring to convert the enum into an actual string also because it's used twice local enumStr = tostring(actionInfo["inputTypes"][1]) local isCoreString = IS_CORE_STR if actionInfo["isCore"] then isCoreString = IS_DEVELOPER_STR end local row = {} for i = 2,#verticalOffsets do local key = string.format("line_%d",i) row[key] = Roact.createElement("Frame", { Size = UDim2.new(0,LINE_WIDTH,1,0), Position = verticalOffsets[i], BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }) end row[name] = Roact.createElement(CellLabel, { text = enumStr, size = entryCellSize[1], pos = cellOffset[1], }) row.priorityLevel = Roact.createElement(CellLabel, { text = actionInfo["priorityLevel"], size = entryCellSize[2], pos = cellOffset[2], }) row.isCore = Roact.createElement(CellLabel, { text = isCoreString, size = entryCellSize[3], pos = cellOffset[3], }) row.actionName = Roact.createElement(CellLabel, { text = name, size = entryCellSize[4], pos = cellOffset[4], }) row.inputTypes = Roact.createElement(CellLabel, { text = enumStr, size = entryCellSize[5], pos = cellOffset[5], }) row.lowerHorizontalLine = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, LINE_WIDTH), Position = UDim2.new(0, 0, 1, 0), BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }) return Roact.createElement("Frame", { Size = UDim2.new(0, width, 0, ENTRY_HEIGHT), BackgroundTransparency = 1, LayoutOrder = layoutOrder, },row) end function ActionBindingsChart:init(props) local initBindings = props.ActionBindingsData:getCurrentData() self.onSortChanged = function(sortType) local currSortType = props.ActionBindingsData:getSortType() if sortType == currSortType then self:setState({ reverseSort = not self.state.reverseSort }) else props.ActionBindingsData:setSortType(sortType) self:setState({ reverseSort = false, }) end end self.onCanvasPosChanged = function() local canvasPos = self.scrollingRef.current.CanvasPosition if self.state.canvasPos ~= canvasPos then self:setState({ canvasPos = canvasPos, }) end end self.scrollingRef = Roact.createRef() self.state = { actionBindingEntries = initBindings, reverseSort = false, } end function ActionBindingsChart:willUpdate() if self.canvasPosConnector then self.canvasPosConnector:Disconnect() end end function ActionBindingsChart:didUpdate() if self.scrollingRef.current then local signal = self.scrollingRef.current:GetPropertyChangedSignal("CanvasPosition") self.canvasPosConnector = signal:Connect(self.onCanvasPosChanged) local absSize = self.scrollingRef.current.AbsoluteSize local currAbsSize = self.state.absScrollSize if absSize.X ~= currAbsSize.X or absSize.Y ~= currAbsSize.Y then self:setState({ absScrollSize = absSize, }) end end end function ActionBindingsChart:didMount() self.bindingsUpdated = self.props.ActionBindingsData:Signal():Connect(function(bindingsData) self:setState({ actionBindingEntries = bindingsData }) end) if self.scrollingRef.current then local signal = self.scrollingRef.current:GetPropertyChangedSignal("CanvasPosition") self.canvasPosConnector = signal:Connect(self.onCanvasPosChanged) self:setState({ absScrollSize = self.scrollingRef.current.AbsoluteSize, canvasPos = self.scrollingRef.current.CanvasPosition, }) end end function ActionBindingsChart:willUnmount() self.bindingsUpdated:Disconnect() self.bindingsUpdated = nil self.canvasPosConnector:Disconnect() self.canvasPosConnector = nil end function ActionBindingsChart:render() local entries = {} local searchTerm = self.props.searchTerm local size = self.props.size local layoutOrder = self.props.layoutOrder local entryList = self.state.actionBindingEntries local reverseSort = self.state.reverseSort local canvasPos = self.state.canvasPos local absScrollSize = self.state.absScrollSize local frameWidth = absScrollSize and math.max(absScrollSize.X, MIN_FRAME_WIDTH) or MIN_FRAME_WIDTH entries["UIListLayout"] = Roact.createElement("UIListLayout", { HorizontalAlignment = Enum.HorizontalAlignment.Left, VerticalAlignment = Enum.VerticalAlignment.Top, SortOrder = Enum.SortOrder.LayoutOrder, }) local totalEntries = #entryList local canvasHeight = 0 if absScrollSize and canvasPos then local paddingHeight = -1 local usedFrameSpace = 0 local count = 0 for ind, entry in ipairs(entryList) do local foundTerm = false if searchTerm then local enumStr = tostring(entry.actionInfo["inputTypes"][1]) foundTerm = string.find(enumStr:lower(), searchTerm:lower()) ~= nil foundTerm = foundTerm or string.find(entry.name:lower(), searchTerm:lower()) ~= nil end if not searchTerm or foundTerm then if canvasHeight + ENTRY_HEIGHT >= canvasPos.Y then if usedFrameSpace < absScrollSize.Y then local entryLayoutOrder = reverseSort and (totalEntries - ind) or ind entries[ind] = constructEntry(entry, frameWidth, entryLayoutOrder + 1) end if paddingHeight < 0 then paddingHeight = canvasHeight else usedFrameSpace = usedFrameSpace + ENTRY_HEIGHT end count = count + 1 end canvasHeight = canvasHeight + ENTRY_HEIGHT end end if count == 0 then entries["NoneFound"] = Roact.createElement("TextLabel", { Size = UDim2.new(1, 0, 1, 0), Text = NON_FOUND_ENTRIES_STR, TextColor3 = LINE_COLOR, BackgroundTransparency = 1, LayoutOrder = 1, }) else entries["WindowingPadding"] = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, paddingHeight), BackgroundTransparency = 1, LayoutOrder = 1, }) end end return Roact.createElement("Frame", { Size = size, BackgroundTransparency = 1, ClipsDescendants = true, LayoutOrder = layoutOrder, }, { Header = constructHeader(self.onSortChanged, frameWidth), MainChart = Roact.createElement("ScrollingFrame", { Position = UDim2.new(0, 0, 0, HEADER_HEIGHT), Size = UDim2.new(1, 0, 1, - HEADER_HEIGHT), CanvasSize = UDim2.new(0, frameWidth, 0, canvasHeight), ScrollBarThickness = 6, BackgroundColor3 = Constants.Color.BaseGray, BackgroundTransparency = 1, [Roact.Ref] = self.scrollingRef }, entries), }) end return DataConsumer(ActionBindingsChart, "ActionBindingsData")
require("nvim-autopairs").setup( { disable_filetype = {"TelescopePrompt"}, ignored_next_char = string.gsub([[ [%w%%%'%[%"%.] ]], "%s+", ""), enable_moveright = true, enable_afterquote = true, -- add bracket pairs after quote enable_check_bracket_line = true, --- check bracket in same line check_ts = false } ) require("nvim-autopairs.completion.compe").setup( { map_cr = true, -- map <CR> on insert mode map_complete = true -- it will auto insert `(` after select function or method item } )
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local pairs = _G.pairs; local string = _G.string; --[[ STRING METHODS ]]-- local format = string.format; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## QUARTZ ########################################################## ]]-- local function StyleQuartz() local AceAddon = LibStub("AceAddon-3.0") if(not AceAddon) then return end local Quartz3 = AceAddon:GetAddon("Quartz3", true) assert(Quartz3, "AddOn Not Loaded") local GCD = Quartz3:GetModule("GCD") local CastBar = Quartz3.CastBarTemplate.template local function StyleQuartzBar(self) if not self.isStyled then self.IconBorder = CreateFrame("Frame", nil, self) SV.API:Set("Frame", self.IconBorder,"Transparent") self.IconBorder:SetFrameLevel(0) self.IconBorder:WrapPoints(self.Icon) SV.API:Set("Frame", self.Bar,"Transparent",true) self.isStyled = true end if self.config.hideicon then self.IconBorder:Hide() else self.IconBorder:Show() end end hooksecurefunc(CastBar, 'ApplySettings', StyleQuartzBar) hooksecurefunc(CastBar, 'UNIT_SPELLCAST_START', StyleQuartzBar) hooksecurefunc(CastBar, 'UNIT_SPELLCAST_CHANNEL_START', StyleQuartzBar) if GCD then hooksecurefunc(GCD, 'CheckGCD', function() if not Quartz3GCDBar.backdrop then SV.API:Set("Frame", Quartz3GCDBar,"Transparent",true) end end) end end MOD:SaveAddonStyle("Quartz", StyleQuartz)
local _, ns = ... local B, C, L, DB, P = unpack(ns) local S = P:GetModule("Skins") local _G = getfenv(0) local select, pairs, type = select, pairs, type local function reskinChildButton(frame) if not frame then return end for i = 1, frame:GetNumChildren() do local child = select(i, frame:GetChildren()) if child:GetObjectType() == 'Button' and child.Text then B.Reskin(child) end end end local function RemoveBorder(frame) for _, region in pairs {frame:GetRegions()} do local texture = region.GetTexture and region:GetTexture() if texture and texture ~= "" and type(texture) == "string" and texture:find("Quickslot2") then region:SetTexture("") end end end local function ReskinWAOptions() local frame = _G.WeakAurasOptions if not frame or frame.styled then return end B.StripTextures(frame) B.SetBD(frame) B.ReskinInput(frame.filterInput, 18) B.Reskin(_G.WASettingsButton) -- Minimize, Close Button for i = 1, frame:GetNumChildren() do local child = select(i, frame:GetChildren()) local numRegions = child:GetNumRegions() local numChildren = child:GetNumChildren() if numRegions == 3 and numChildren == 1 and child.PixelSnapDisabled then B.StripTextures(child) local button = child:GetChildren() local texturePath = button.GetNormalTexture and button:GetNormalTexture():GetTexture() if texturePath and type(texturePath) == "string" and texturePath:find("CollapseButton") then B.Reskin(button) button.SetNormalTexture = B.Dummy button.SetPushedTexture = B.Dummy button:SetSize(18, 18) button:ClearAllPoints() button:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -30, -6) local tex = button:CreateTexture(nil, "ARTWORK") tex:SetAllPoints() B.SetupArrow(tex, "up") button.__texture = tex button:SetScript("OnEnter", B.Texture_OnEnter) button:SetScript("OnLeave", B.Texture_OnLeave) button:HookScript("OnClick",function(self) if frame.minimized then B.SetupArrow(self.__texture, "down") else B.SetupArrow(self.__texture, "up") end end) else B.ReskinClose(button, frame) button:SetSize(18, 18) end end end -- Child Groups local childGroups = { "texturePicker", "iconPicker", "modelPicker", "importexport", "texteditor", "codereview", } for _, key in pairs(childGroups) do local group = frame[key] if group then reskinChildButton(group.frame) end end -- IconPicker local iconPicker = frame.iconPicker.frame if iconPicker then for i = 1, iconPicker:GetNumChildren() do local child = select(i, iconPicker:GetChildren()) if child:GetObjectType() == 'EditBox' then B.ReskinInput(child, 20) end end end -- Right Side Container local container = frame.container.content:GetParent() if container and container.bg then container.bg:Hide() end -- WeakAurasSnippets local snippets = _G.WeakAurasSnippets B.StripTextures(snippets) B.SetBD(snippets) reskinChildButton(snippets) -- MoverSizer local moversizer = frame.moversizer B.CreateBD(moversizer, 0) local index = 1 for i = 1, moversizer:GetNumChildren() do local child = select(i, moversizer:GetChildren()) local numChildren = child:GetNumChildren() if numChildren == 2 and child:IsClampedToScreen() then local button1, button2 = child:GetChildren() if index == 1 then B.ReskinArrow(button1, "up") B.ReskinArrow(button2, "down") else B.ReskinArrow(button1, "left") B.ReskinArrow(button2, "right") end index = index + 1 end end -- TipPopup for i = 1, frame:GetNumChildren() do local child = select(i, frame:GetChildren()) if child:GetFrameStrata() == "FULLSCREEN" and child.PixelSnapDisabled and child.backdropInfo then B.StripTextures(child) B.SetBD(child) for j = 1, child:GetNumChildren() do local child2 = select(j, child:GetChildren()) if child2:GetObjectType() == "EditBox" then B.ReskinInput(child2, 18) end end break end end frame.styled = true end function S:WeakAuras() if not IsAddOnLoaded("WeakAuras") then return end local WeakAuras = _G.WeakAuras if not WeakAuras then return end -- WeakAurasTooltip reskinChildButton(_G.WeakAurasTooltipImportButton:GetParent()) B.ReskinRadio(_G.WeakAurasTooltipRadioButtonCopy) B.ReskinRadio(_G.WeakAurasTooltipRadioButtonUpdate) local index = 1 local check = _G["WeakAurasTooltipCheckButton"..index] while check do B.ReskinCheck(check) index = index + 1 check = _G["WeakAurasTooltipCheckButton"..index] end -- Remove Aura Border (Credit: ElvUI_WindTools) if WeakAuras.RegisterRegionOptions then local origRegisterRegionOptions = WeakAuras.RegisterRegionOptions WeakAuras.RegisterRegionOptions = function(name, createFunction, icon, displayName, createThumbnail, ...) if type(icon) == "function" then local OldIcon = icon icon = function() local f = OldIcon() RemoveBorder(f) return f end end if type(createThumbnail) == "function" then local OldCreateThumbnail = createThumbnail createThumbnail = function() local f = OldCreateThumbnail() RemoveBorder(f) return f end end return origRegisterRegionOptions(name, createFunction, icon, displayName, createThumbnail, ...) end end -- WeakAurasOptions local count = 0 local function loadFunc(event, addon) if addon == "WeakAurasOptions" then hooksecurefunc(WeakAuras, "ShowOptions", ReskinWAOptions) count = count + 1 end if addon == "WeakAurasTemplates" then if WeakAuras.CreateTemplateView then local origCreateTemplateView = WeakAuras.CreateTemplateView WeakAuras.CreateTemplateView = function(...) local group = origCreateTemplateView(...) reskinChildButton(group.frame) return group end end count = count + 1 end if count >= 2 then B:UnregisterEvent(event, loadFunc) end end B:RegisterEvent("ADDON_LOADED", loadFunc) end S:RegisterSkin("WeakAuras", S.WeakAuras)
local storeKey = KEYS[1] local nodeKey = KEYS[2] local pathCount = tonumber(ARGV[1]) local hasStore = redis.call('exists', storeKey) if (hasStore == 0) then return -1 end -- 1. remove resource from path set local resources = {} for i = pathCount + 2, #ARGV do resources[#resources + 1] = ARGV[i] end local affected = redis.call('srem', nodeKey, unpack(resources)) if (affected == 0) then return 0 end -- 2. get path set count (resource count) local resourceCount = redis.call('scard', nodeKey) -- 3. update new count to store redis.call('hset', storeKey, ARGV[2], tostring(resourceCount)) -- 4. maintain ancestor nodes count local hmget = {} hmget[1] = 'hmget' hmget[2] = storeKey for i = 3, pathCount + 1 do hmget[#hmget + 1] = ARGV[i] end local hmgetResult = redis.call(unpack(hmget)) local hmset = {} hmset[1] = 'hmset' hmset[2] = storeKey for i = 3, pathCount + 1 do hmset[#hmset + 1] = ARGV[i] if (hmgetResult[i - 2] == nil or (type(hmgetResult[i - 2]) == 'boolean' and not hmgetResult[i - 2])) then hmset[#hmset + 1] = '0' else hmset[#hmset + 1] = tostring(tonumber(hmgetResult[i - 2]) - affected) end end redis.call(unpack(hmset)) return 1
SILE.registerCommand("thisframeLTR", function(options, content) SILE.typesetter.frame.direction = "LTR" SILE.typesetter:leaveHmode() SILE.typesetter.frame:newLine() end); SILE.registerCommand("thisframeRTL", function(options, content) SILE.typesetter.frame.direction = "RTL" SILE.typesetter:leaveHmode() SILE.typesetter.frame:newLine() end); local bidi = require("unicode-bidi-algorithm") local bidiBoxupNodes = function (self) local nl = self.state.nodes local newNl = {} for i=1,#nl do if nl[i]:isUnshaped() then local chunks = SU.splitUtf8(nl[i].text) for j = 1,#chunks do newNl[#newNl+1] = SILE.nodefactory.newUnshaped({text = chunks[j], options = nl[i].options }) end else newNl[#newNl+1] = nl[i] end end nl = bidi.process(newNl, self.frame) -- Reconstitute. This code is a bit dodgy. Currently we have a bunch of nodes -- each with one Unicode character in them. Sending that to the shaper one-at-a-time -- will cause, e.g. Arabic letters to all come out as isolated forms. But equally, -- we can't send the whole lot to the shaper at once because Harfbuzz doesn't itemize -- them for us, spaces have already been converted to glue, and so on. So we combine -- characters with equivalent options/character sets into a single node. newNL = {nl[1]} local ncount = 1 -- small optimization, save indexing newNL every time for i=2,#nl do local this = nl[i] local prev = newNL[ncount] if not this:isUnshaped() or not prev:isUnshaped() then ncount = ncount + 1 newNL[ncount] = this -- now both are unshaped, compare them elseif SILE.font._key(this.options) == SILE.font._key(prev.options) then -- same font prev.text = prev.text .. this.text else ncount = ncount + 1 newNL[ncount] = this end end self.state.nodes = newNL return SILE.defaultTypesetter.boxUpNodes(self) end SILE.typesetter.boxUpNodes = bidiBoxupNodes SILE.registerCommand("bidi-on", function(options, content) SILE.typesetter.boxUpNodes = bidiBoxupNodes end) SILE.registerCommand("bidi-off", function(options, content) SILE.typesetter.boxUpNodes = SILE.defaultTypesetter.boxUpNodes end) return { documentation = [[\begin{document} Scripts like the Latin alphabet you are currently reading are normally written left to right; however, some scripts, such as Arabic and Hebrew, are written right to left. The \code{bidi} package, which is loaded by default, provides SILE with the ability to correctly typeset right-to-left text and also documents which mix right-to-left and left-to-right typesetting. Because it is loaded by default, you can use both LTR and RTL text within a paragraph and SILE will ensure that the output characters appear in the correct order. The \code{bidi} package provides two commands, \command{\\thisframeLTR} and \command{\\thisframeRTL}, which set the default text direction for the current frame. That is, if you tell SILE that a frame is RTL, the text will start in the right margin and proceed leftward. It also provides the commands \command{\\bidi-off} and \command{\\bidi-on}, which allow you to trade off bidirectional support for a dubious increase in speed. \end{document}]] }
SWEP.PrintName = "Antidote gun" -- 'Nice' Weapon name (Shown on HUD) SWEP.Author = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.ViewModelFOV = 62 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/weapons/v_pistol.mdl" SWEP.WorldModel = "models/weapons/w_357.mdl" SWEP.Spawnable = false SWEP.AdminOnly = false SWEP.Primary.ClipSize = 8 -- Size of a clip SWEP.Primary.DefaultClip = 32 -- Default number of bullets in a clip SWEP.Primary.Automatic = false -- Automatic/Semi Auto SWEP.Primary.Ammo = "Pistol" SWEP.Secondary.ClipSize = -1 -- Size of a clip SWEP.Secondary.DefaultClip = -1 -- Default number of bullets in a clip SWEP.Secondary.Automatic = false -- Automatic/Semi Auto SWEP.Secondary.Ammo = "Pistol" --[[--------------------------------------------------------- Name: SWEP:Initialize( ) Desc: Called when the weapon is first loaded -----------------------------------------------------------]] function SWEP:Initialize() self:SetHoldType( "pistol" ) end function SWEP:PrimaryAttack() if ( IsFirstTimePredicted() ) then local bullet = {} bullet.Num = 1 bullet.Src = self.Owner:GetShootPos() bullet.Dir = self.Owner:GetAimVector() bullet.Spread = Vector( 0.01, 0.01, 0 ) bullet.Tracer = 1 bullet.Force = 5 bullet.Damage = 0 function bullet:Callback(attacker, tr, dmginfo) end self.Owner:FireBullets( bullet ) self:SendWeaponAnim( ACT_VM_PRIMARYATTACK ) self.Owner:SetAnimation( PLAYER_ATTACK1 ) end end function SWEP:SecondaryAttack() end
SettingMap = mondelefant.new_class() SettingMap.table = 'setting_map' SettingMap.primary_key = { "key", "subkey" }
--[[ Write a function that receives an array and prints all combinations of the elements in the array. (Hint: you can use the recursive formula for combination: C(n,m) = C(n-1,m-1) + C(n-1,m). To generate all C(n,m) combinations of n elements in groups of size m, you first add the first element to the result and then generate all C(n-1, m-1) combinations of the remaining elements in the remaining slots; then you remove the first element from the result and then generate all C(n-1, m) combinations of the remaining elements in the free slots. When n is smaller than m, there are no combinations. When m is zero, there is only one combination, which uses no elements. ]]-- function comb(n,m) if n==m then return 1; elseif m==0 then return 1; else return comb(n-1, m-1) + comb(n-1, m) end end print(comb(1,1)) print(comb(4,1)) print(comb(5,2)) print(comb(10,3))
local wool_colors = { {"wool:white", "excolor_white"}, {"wool:grey", "excolor_grey"}, {"wool:black", "excolor_black"}, {"wool:red", "excolor_red"}, {"wool:yellow", "excolor_yellow"}, {"wool:green", "excolor_green"}, {"wool:cyan", "excolor_cyan"}, {"wool:blue", "excolor_blue"}, {"wool:magenta", "excolor_red_violet"}, {"wool:orange", "excolor_orange"}, {"wool:violet", "excolor_violet"}, {"wool:brown", "unicolor_dark_orange"}, {"wool:pink", "unicolor_light_red"}, {"wool:dark_grey", "unicolor_darkgrey"}, {"wool:dark_green", "unicolor_dark_green"}, } paint_roller.register_table(wool_colors, "Default Wool")
local blank = { filename = "__computer_core__/graphics/blank.png", priority = "high", width = 1, height = 1, frame_count = 1, axially_symmetrical = false, direction_count = 1, shift = { 0.0, 0.0 }, } data:extend({{ type = "lamp", name = "computer-lamp", flags = { "placeable-neutral", "placeable-player", "player-creation" }, icon = "__computer_core__/graphics/icons/computer-icon.png", icon_size = 32, subgroup = "grass", order = "b[decorative]-k[stone-rock]-a[big]", collision_box = { { -1.2, -0.65 }, { 1.2, 0.65 } }, collision_mask = {"doodad-layer"}, selection_priority = 0, selection_box = {{-0.0, -0}, {0, 0}}, energy_source = { type = "electric", usage_priority = "secondary-input" }, energy_usage_per_tick = "2KW", light = { intensity = 0.4, size = 5 }, enable_gui = false, max_health = 10000, healing_per_tick = 10000, corpse = "medium-remnants", resistances = { }, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, picture_off = blank, picture_on = blank }, { type = "electric-energy-interface", name = "computer-interface-entity", flags = { "placeable-neutral", "placeable-player", "player-creation" }, icon = "__computer_core__/graphics/icons/computer-icon.png", icon_size = 32, subgroup = "grass", order = "b[decorative]-k[stone-rock]-a[big]", collision_box = { { -1.2, -0.65 }, { 1.2, 0.65 } }, selection_box = { { -1.5, -1 }, { 1.5, 1 } }, drawing_box = { { -1.5, -2.5 }, { 1.5, 1 } }, energy_source = { type = "electric", usage_priority = "primary-input", buffer_capacity = "5MJ", input_flow_limit = "300kW", output_flow_limit = "0kW" }, energy_production = "0kW", energy_usage = "50kW", light = { intensity = 0.4, size = 5 }, minable = { mining_time = 2, result = "computer-item", count = 1 }, enable_gui = false, mined_sound = { filename = "__base__/sound/deconstruct-bricks.ogg" }, max_health = 250, corpse = "medium-remnants", resistances = { { type = "physical", decrease = 3, percent = 60 }, { type = "impact", decrease = 45, percent = 60 }, { type = "explosion", decrease = 10, percent = 30 }, { type = "fire", percent = 0 }, { type = "laser", percent = 0 } }, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, picture = { filename = "__computer_core__/graphics/entities/computer.png", priority = "high", width = 250, height = 200, frame_count = 1, axially_symmetrical = false, direction_count = 1, shift = { 2.1, -1.1 }, scale = 1, hr_version = { filename = "__computer_core__/graphics/entities/computer_hr.png", priority = "high", width = 1000, height = 800, frame_count = 1, axially_symmetrical = false, direction_count = 1, shift = { 2.1, -1.1 }, scale = 0.25, } } }, { type = "constant-combinator", name = "computer-combinator", icon = "__base__/graphics/icons/constant-combinator.png", icon_size = 32, flags = {"placeable-player", "player-creation", "placeable-off-grid", "not-deconstructable"}, order = "y", max_health = 10000, healing_per_tick = 10000, corpse = "small-remnants", collision_box = {{-0.0, -0.0}, {0.0, 0.0}}, collision_mask = {"doodad-layer"}, selection_priority = 100, selection_box = {{-0.5, -0.5}, {0.5, 0.5}}, item_slot_count = 18, sprites = { north = blank, east = blank, south = blank, west = blank }, activity_led_sprites = { north = blank, east = blank, south = blank, west = blank }, activity_led_light = { intensity = 0, size = 1, }, activity_led_light_offsets = { {0, 0}, {0, 0}, {0, 0}, {0, 0} }, circuit_wire_connection_points = { { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.0, 0.0}, } }, { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.0, 0.0}, } }, { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.0, 0.0}, } }, { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.0, 0.0}, } } }, circuit_wire_max_distance = 10 }, { type = "constant-combinator", name = "computer-speaker-combinator", icon = "__base__/graphics/icons/constant-combinator.png", icon_size = 32, flags = {"placeable-player", "player-creation", "placeable-off-grid", "not-deconstructable"}, order = "y", max_health = 10000, healing_per_tick = 10000, corpse = "small-remnants", collision_box = {{-0.0, -0.0}, {0.0, 0.0}}, collision_mask = {"doodad-layer"}, selection_priority = 100, selection_box = {{-0.0, -0}, {0, 0}}, item_slot_count = 1, sprites = { north = blank, east = blank, south = blank, west = blank }, activity_led_sprites = { north = blank, east = blank, south = blank, west = blank }, activity_led_light = { intensity = 0, size = 1, }, activity_led_light_offsets = { {0, 0}, {0, 0}, {0, 0}, {0, 0} }, circuit_wire_connection_points = { { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.2, -0.7}, } }, { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.2, -0.7}, } }, { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.2, -0.7}, } }, { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {-0.0, -0.0}, red = {0.2, -0.7}, } } }, circuit_wire_max_distance = 10 }, { type = "programmable-speaker", name = "computer-speaker", icon = "__base__/graphics/icons/programmable-speaker.png", icon_size = 32, flags = {"placeable-player", "player-creation", "placeable-off-grid", "not-deconstructable"}, order = "y", max_health = 10000, healing_per_tick = 10000, corpse = "small-remnants", collision_box = { { -1.2, -0.65 }, { 1.2, 0.65 } }, collision_mask = {"doodad-layer"}, selection_priority = 0, selection_box = {{-0.0, -0}, {0, 0}}, energy_source = { type = "electric", usage_priority = "secondary-input" }, energy_usage_per_tick = "2KW", sprite = { layers = { blank, blank } }, audible_distance_modifier = 2, --multiplies the default 40 tiles of audible distance by this number maximum_polyphony = 10, --maximum number of samples that can play at the same time instruments = data.raw["programmable-speaker"]["programmable-speaker"].instruments, circuit_wire_connection_point = { shadow = { green = {-0.0, -0.0}, red = {0.0, 0.0}, }, wire = { green = {0.0, 0.0}, red = {0.2, -0.7}, } }, circuit_wire_max_distance = 10 }, { type = "item-subgroup", name = "virtual-music-signal", group = "signals", order = "1", }, { type = "virtual-signal", name = "signal-music-note", icon = "__computer_core__/graphics/icons/note-icon.png", icon_size = 32, subgroup = "virtual-music-signal", order = "a-a" }})
-- dap local dap = require('dap') local jdtls_util = require('jdtls.util') local launchjs = require('dap.ext.vscode') local utils = require('thijssesc.utils') local variables = require('dap.ui.variables') local nnoremap = utils.keymap.nnoremap launchjs.load_launchjs() dap.adapters.node2 = { type = 'executable', command = 'node', args = { vim.fn.getenv('HOME')..'/Software/vscode-node-debug2/out/src/nodeDebug.js' }, } dap.adapters.java = function(callback) jdtls_util.execute_command({ command = 'vscode.java.startDebugSession' } , function(err, port) assert(not err, vim.inspect(err)) callback({ type = 'server', host = '127.0.0.1', port = port, }) end) end dap.configurations.java = { { type = 'java', request = 'attach', name = 'Debug (Attach) - Remote', hostName = '127.0.0.1', port = 8000, }, } dap.configurations.javascript = { { type = 'node2', request = 'launch', program = '${workspaceFolder}/${file}', cwd = vim.fn.getcwd(), sourceMaps = true, protocol = 'inspector', console = 'integratedTerminal', skipFiles = { '<node_internals>/**' }, }, } dap.configurations.typescript = vim.tbl_extend('force', { outFiles = { '${workspaceFolder}/build/**/*.js' }, }, dap.configurations.javascript) dap.configurations.typescript = dap.configurations.typescript nnoremap { '<leader>dc', dap.continue } nnoremap { '<leader>dd', dap.down } nnoremap { '<leader>dg', dap.goto_ } nnoremap { '<leader>dh', variables.hover } nnoremap { '<leader>di', dap.step_into } nnoremap { '<leader>do', dap.step_over } nnoremap { '<leader>dO', dap.step_out } nnoremap { '<leader>dr', function() dap.repl.toggle({}, 'vsplit') end } nnoremap { '<leader>ds', variables.scopes } nnoremap { '<leader>dt', dap.toggle_breakpoint } nnoremap { '<leader>du', dap.up }
--[[ MIT License Copyright (c) 2020 DekuJuice Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local class = require("enginelib.middleclass") local CircularBuffer = class("CircularBuffer") function CircularBuffer:initialize(length) self.items = {} self.oldest = 1 self.length = length or 500 end function CircularBuffer:get_length() return self.length end function CircularBuffer:get_count() return #self.items end function CircularBuffer:is_full() return #self.items == self.length end function CircularBuffer:push(v) if self:is_full() then self.items[self.oldest] = v self.oldest = (self.oldest % self.length) + 1 else table.insert(self.items, v) end end -- negative indices are oldest items -- positive indices are newest items function CircularBuffer:at(i) local n = #self.items if i == 0 or math.abs(i) > n then return nil end if i >= 1 then return self.items[ (self.oldest - i - 1) % n + 1 ] elseif i <= -1 then return self.items[ (self.oldest - i - 2) % n + 1 ] end end return CircularBuffer
--[[ -- 作者:Steven -- 日期:2017-02-26 -- 文件名:err_redirect.lua -- 版权说明:南京正溯网络科技有限公司.版权所有©copy right. -- 错误重定向的简单封装,用于系统的重定向错误处理, -- 重定向过来时,如果存在url 则直接跳向该连接; 如果不存在url根据编码约定返回; 如果都没有,则跳转到默认文件 --]] -- 本文件进行重定向的管理 local cjson = require "cjson" local _M={ file_access_error = "/401.html", } --[[ -- _M.redirect( _url ) 系统重定向的 -- 如果不存在指定文件,将结果加入返回的数据表中 -- example -- @param err_code 系统错误编号 参考init.error_ex.lua 文件的预定义,用户可以自定义自己的参数,起始数字为444 -- @param _data 返回消息的主体 -- @param _desc 描述信息 --]] function _M.redirect_by_code( _redirect_code , _params) -- body if _redirect_code then local url = _M[_redirect_code]; if not url then ngx.exit(400) end; if _params then local jsonStr=cjson.encode(_params); if jsonStr then url = url.."?url="..ngx.decode_base64(jsonStr) end end return ngx.redirect(url) else return ngx.exit(400) end; end --[[废弃 但勿删除 function _M.redirect( _url ) -- body if url then return ngx.redirect(url) else return ngx.exit(400) end; end --]] return _M
local _, XB = ... -- Locals local GetTime = GetTime local UnitGUID = UnitGUID local GetSpellInfo = GetSpellInfo local InCombatLockdown = InCombatLockdown local UnitHealth = UnitHealth local wipe = wipe XB.CombatTracker = {} local Data = {} local L = XB.Locale -- Thse are Mixed Damage types (magic and pysichal) local Doubles = { [3] = 'Holy + Physical', [5] = 'Fire + Physical', [9] = 'Nature + Physical', [17] = 'Frost + Physical', [33] = 'Shadow + Physical', [65] = 'Arcane + Physical', [127] = 'Arcane + Shadow + Frost + Nature + Fire + Holy + Physical', } local function addToData(GUID) if not Data[GUID] then Data[GUID] = { dmgTaken = 0, dmgTaken_P = 0, dmgTaken_M = 0, Hits = 0, firstHit = GetTime(), lastHit = 0 } end end --[[ This Logs the damage done for every unit ]] local logDamage = function(...) local _,_,_,_,_,_,_, GUID, _,_,_,_,_, school, Amount = ... -- Mixed if Doubles[school] then Data[GUID].dmgTaken_P = Data[GUID].dmgTaken_P + Amount Data[GUID].dmgTaken_M = Data[GUID].dmgTaken_M + Amount -- Pysichal elseif school == 1 then Data[GUID].dmgTaken_P = Data[GUID].dmgTaken_P + Amount -- Magic else Data[GUID].dmgTaken_M = Data[GUID].dmgTaken_M + Amount end -- Totals Data[GUID].dmgTaken = Data[GUID].dmgTaken + Amount Data[GUID].Hits = Data[GUID].Hits + 1 end --[[ This Logs the swings (damage) done for every unit ]] local logSwing = function(...) local _,_,_,_,_,_,_, GUID, _,_,_, Amount = ... Data[GUID].dmgTaken_P = Data[GUID].dmgTaken_P + Amount Data[GUID].dmgTaken = Data[GUID].dmgTaken + Amount Data[GUID].Hits = Data[GUID].Hits + 1 end --[[ This Logs the healing done for every unit !!~counting selfhealing only for now~!!]] local logHealing = function(...) local _,_,_, sourceGUID, _,_,_, GUID, _,_,_,_,_,_, Amount = ... local playerGUID = UnitGUID('player') if sourceGUID == playerGUID then Data[GUID].dmgTaken_P = Data[GUID].dmgTaken_P - Amount Data[GUID].dmgTaken_M = Data[GUID].dmgTaken_M - Amount Data[GUID].dmgTaken = Data[GUID].dmgTaken - Amount end end --[[ This Logs the last action done for every unit ]] local addAction = function(...) local _,_,_, sourceGUID, _,_,_,_, destName, _,_,_, spellName = ... if not spellName then return end addToData(sourceGUID) -- Add to action Log, only for self for now if sourceGUID == UnitGUID('player') then local icon = select(3, GetSpellInfo(spellName)) XB.ActionLog:Add(L:TA('AL','SpellCastSucceed'), spellName, icon, destName) end Data[sourceGUID].lastcast = spellName end --[[ These are the events we're looking for and its respective action ]] local EVENTS = { ['SPELL_DAMAGE'] = function(...) logDamage(...) end, ['DAMAGE_SHIELD'] = function(...) logDamage(...) end, ['SPELL_PERIODIC_DAMAGE'] = function(...) logDamage(...) end, ['SPELL_BUILDING_DAMAGE'] = function(...) logDamage(...) end, ['RANGE_DAMAGE'] = function(...) logDamage(...) end, ['SWING_DAMAGE'] = function(...) logSwing(...) end, ['SPELL_HEAL'] = function(...) logHealing(...) end, ['SPELL_PERIODIC_HEAL'] = function(...) logHealing(...) end, ['UNIT_DIED'] = function(...) Data[select(8, ...)] = nil end, ['SPELL_CAST_SUCCESS'] = function(...) addAction(...) end, } --[[ Returns the total ammount of time a unit is in-combat for ]] function XB.CombatTracker:CombatTime(UNIT) local GUID = UnitGUID(UNIT) if Data[GUID] and InCombatLockdown() then local combatTime = (GetTime()-Data[GUID].firstHit) return combatTime end return 0 end function XB.CombatTracker:getDMG(UNIT) local total, Hits, phys, magic = 0, 0, 0, 0 local GUID = UnitGUID(UNIT) if Data[GUID] then local time = GetTime() -- Remove a unit if it hasnt recived dmg for more then 5 sec if (time-Data[GUID].lastHit) > 5 then Data[GUID] = nil else local combatTime = self:CombatTime(UNIT) total = Data[GUID].dmgTaken / combatTime phys = Data[GUID].dmgTaken_P / combatTime magic = Data[GUID].dmgTaken_M / combatTime Hits = Data[GUID].Hits end end return total, Hits, phys, magic end function XB.CombatTracker:TimeToDie(unit) if XB.Checker:IsDummy(unit) then return 999 end local ttd = 0 local DMG, Hits = self:getDMG(unit) if DMG >= 1 and Hits > 1 then ttd = UnitHealth(unit) / DMG end return ttd or 0 end function XB.CombatTracker:LastCast(unit) local GUID = UnitGUID(unit) if Data[GUID] then return Data[GUID].lastcast end end XB.Listener:Add('XB_CombatTracker', 'COMBAT_LOG_EVENT_UNFILTERED', function(...) local _, EVENT, _,_,_,_,_, GUID = ... -- Add the unit to our data if we dont have it addToData(GUID) -- Update last hit time Data[GUID].lastHit = GetTime() -- Add the amount of dmg/heak if EVENTS[EVENT] then EVENTS[EVENT](...) end end) XB.Listener:Add('XB_CombatTracker', 'PLAYER_REGEN_ENABLED', function() wipe(Data) end) XB.Listener:Add('XB_CombatTracker', 'PLAYER_REGEN_DISABLED', function() wipe(Data) end)
local nord = (function() local nord_colors = { nord0 = '#2E3440', nord1 = '#3B4252', nord2 = '#434C5E', nord3 = '#4C566A', nord4 = '#D8DEE9', nord5 = '#E5E9F0', nord6 = '#ECEFF4', nord7 = '#8FBCBB', nord8 = '#88C0D0', nord9 = '#81A1C1', nord10 = '#5E81AC', nord11 = '#BF616A', nord12 = '#D08770', nord13 = '#EBCB8B', nord14 = '#A3BE8C', nord15 = '#B48EAD' } return nord_colors end)() return nord
----------------------------------- -- Area: Chamber of Oracles -- Mob: Princeps V-XI -- Zilart 6 Fight ----------------------------------- mixins = {require("scripts/mixins/job_special")} ----------------------------------- function onMobDeath(mob, player, isKiller) end
--[[Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as is not negative; if a negative argument is passed as initialAge, the constructor should set initialAge to 0 and print Age is not valid, setting age to 0.. In addition, you must write the following instance methods: yearPasses() should increase the age instance variable by 1. amIOld() should perform the following conditional actions: If age < 13, print You are young.. If age >= 13 and age <= 18, print You are a teenager.. Otherwise, print You are old..--]] local Person = { }; Person.__index = Person function Person.new (initialAge) local self = setmetatable({ },Person); if (initialAge > 0) then self.age = initialAge else self.age = 0 print "Age is not valid, setting age to 0." end return self; end function Person:amIOld() if (self.age < 13) then print "You are young." elseif (self.age >= 13 and self.age <= 18) then print "You are a teenager." else print "You are old." end end function Person:yearPasses () self.age = self.age + 1 end local read = io.read; local T = read'*n'; for i = 1,T do local age = read'*n'; local p = Person.new(age); p:amIOld(); for j = 1,3 do p:yearPasses(); end p:amIOld(); print""; end
local typeof = typeof toluaSystem = System local isInstanceOfType = typeof(toluaSystem.Object).IsInstanceOfType local Timer = Timer.New -- tolua.Timer local function isFromCSharp(T) return T[".name"] ~= nil end local function isUserdataType(obj, T) if isFromCSharp(T) then return isInstanceOfType(typeof(T), obj) end return true end local config = { time = tolua.gettime, setTimeout = function (f, milliseconds) local t = Timer(f, milliseconds / 1000, 1, true) t:Start() return t end, clearTimeout = function (t) t:Stop() end, customTypeCheck = function (T) if isFromCSharp(T) then return isUserdataType end end } UnityEngine.isFromCSharp = isFromCSharp -- luajit table.move may causes a crash if jit then table.move = function(a1, f, e, t, a2) if a2 == nil then a2 = a1 end t = e - f + t while e >= f do a2[t] = a1[e] t = t - 1 e = e - 1 end end end require("CoreSystemLua.All")("CoreSystemLua", config) require("UnityAdapter") require("Compiled.manifest")("Compiled")
local _ = require('bit') local a = {} a.__index = function(e, f) return rawget(e, f) or e.bits[f] or 0 end a.__newindex = function(e, f, g) if tonumber(f) then e:set(f, g) else rawset(e, f, g) end end local function b(e) local f = {} f.bits = e or {} f.isSet = function(g, h) return g.bits[h] == 1 end f.set = function(g, h, i) g.bits[h] = i return g end f.toNumber = function(g) return tonumber(table.concat(g.bits, ""), 2) end f.areSet = function(g, ...) for h, i in pairs {...} do if not g.bits[i] then return false end end return true end f.areNotSet = function(g, ...) for h, i in pairs {...} do if g.bits[i] then return false end end return true end f.copy = function(g) return b(g.bits) end setmetatable(f, a) return f end local function c(e) local f = {} while e > 0 do local g = math.fmod(e, 2) f[#f + 1] = g e = (e - g) / 2 end return b(f) end local function d(e, f) f = f or 1 return _.band(_.rshift(e, f - 1), 1) end return {['new'] = b, ['fromNumber'] = c, ['isBitSet'] = d}
-- control.lua -- Apr 2017 function CreateTagGui(event) local player = game.players[event.player_index] if player.gui.top.tag == nil then player.gui.top.add{name="tag", type="button", caption="Tag"} end end -- Tag list local roles = { {display_name = "[Solo]"}, {display_name = "[Mining]"}, {display_name = "[Power]"}, {display_name = "[Oil]"}, {display_name = "[Smelt]"}, {display_name = "[Rail]"}, {display_name = "[Defense]"}, {display_name = "[Circuits]"}, {display_name = "[Science!]"}, {display_name = "[Logistics]"}, {display_name = "[Misc]"}, {display_name = "[Aliens]"}, {display_name = "[Rocket]"}, {display_name = "[AFK]"}, {display_name = "Clear"}} local function ExpandTagGui(player) local frame = player.gui.left["tag-panel"] if (frame) then frame.destroy() else local frame = player.gui.left.add{type="frame", name="tag-panel", caption="What are you doing:"} for _, role in pairs(roles) do frame.add{type="button", caption=role.display_name, name=role.display_name} end end end function TagGuiClick(event) if not (event and event.element and event.element.valid) then return end local player = game.players[event.element.player_index] local name = event.element.name if (name == "tag") then ExpandTagGui(player) end if (name == "Clear") then player.tag = "" return end for _, role in pairs(roles) do if (name == role.display_name) then player.tag = role.display_name end end end
id = 'V-38608' severity = 'low' weight = 10.0 title = 'The SSH daemon must set a timeout interval on idle sessions.' description = 'Causing idle users to be automatically logged out guards against compromises one system leading trivially to compromises on another.' fixtext = [=[SSH allows administrators to set an idle timeout interval. After this interval has passed, the idle user will be automatically logged out. To set an idle timeout interval, edit the following line in "/etc/ssh/sshd_config" as follows: ClientAliveInterval [interval] The timeout [interval] is given in seconds. To have a timeout of 15 minutes, set [interval] to 900. If a shorter timeout has already been set for the login shell, that value will preempt any SSH setting made here. Keep in mind that some processes may stop SSH from correctly detecting that the user is idle.]=] checktext = [=[Run the following command to see what the timeout interval is: # grep ClientAliveInterval /etc/ssh/sshd_config If properly configured, the output should be: ClientAliveInterval 900 If it is not, this is a finding.]=] function test() end function fix() end
print('core.utils.commonUtil') _commonUtil = { -- }; function _commonUtil.getTableLen(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end function _commonUtil.prtTable(T) print('_commonUtil:prtTabble'); for k, v in pairs(T) do print('k : ', k, 'v : ', v); end end function _commonUtil.splitStr (inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "([^"..sep.."]+)") do table.insert(t, str) end return t end function _commonUtil.hexStrToBytes(hexStr) return (hexStr:gsub('..', function (cc) return string.char(tonumber(cc, 16)) end)) end function _commonUtil.bytesToHexStr(str) return (str:gsub('.', function (c) return string.format('%02x', string.byte(c)) end)) end -- function _commonUtil.bytesToHexStr (str) -- local len = string.len( str ) -- local hex = "" -- for i = 1, len do -- local ord = string.byte( str, i ) -- hex = hex .. string.format( "%02X", ord ) -- end -- return hex -- end function _commonUtil.readBinaryFile(filePath) local file = assert(io.open(filePath, "rb")); local fData = file:read("*all"); assert(file:close()); -- local hexD = _debug.hex_dump(fData); -- print('hexD : '); -- print(hexD); return fData; end function _commonUtil.writeBinaryFile(filePath, fData) local file = assert(io.open(filePath, "wb")); file:write(fData); assert(file:close()); -- local hexD = _debug.hex_dump(fData); -- print('hexD : '); -- print(hexD); end function _commonUtil.readFile(filePath) local file = assert(io.open(filePath, "r")); local fData = file:read("*all"); assert(file:close()); return fData; end function _commonUtil.writeFile(filePath, fData) local file = assert(io.open(filePath, "w")); file:write(fData); assert(file:close()); end -- function _commonUtil.unescape(text) for uchar in string.gmatch(text, "\\u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])") do print('uchar : ', uchar); -- text = text:gsub("\\u"..uchar, utf8.char("0x"..uchar)); text = text:gsub("\\u"..uchar, string.format( "%02x", uchar )); end return text; end -- function _commonUtil.insertStr(str1, str2, pos) return str1:sub(0,pos)..str2..str1:sub(pos+0); end local clock = os.clock function _commonUtil.sleep(n) -- seconds local t0 = clock() while clock() - t0 <= n do end end -- Refer to : -- https://stackoverflow.com/questions/25403979/lua-only-call-a-function-if-it-exists/25557991 -- https://www.geeks3d.com/hacklab/20171129/how-to-check-if-a-lua-function-exists/ function _commonUtil.luaExeFunc(mainFunc, subFunc) if (mainFunc ~= nil) and (subFunc ~= nil) then if (_G[mainFunc] ~= nil) then -- print("%s lib is exposed.", mainFunc); if _G[mainFunc][subFunc] ~= nil then -- print("%s.%s() is exposed.", mainFunc, subFunc); _G[mainFunc][subFunc](); else -- print("%s.%s() is NOT exposed.", mainFunc, subFunc); end else -- print("%s lib is NOT exposed.", mainFunc); end elseif (mainFunc ~= nil) then if (_G[mainFunc] ~= nil) then -- print("%s lib is exposed.", mainFunc); _G[mainFunc](); else -- print("%s lib is NOT exposed.", mainFunc); end else -- print("Any lib is NOT exposed."); end end
local mock = require("luassert.mock") local stub = require("luassert.stub") local options = require("nvim-lsp-ts-utils.options") local u = require("nvim-lsp-ts-utils.utils") local o = mock(options, true) describe("client", function() stub(vim.lsp.util, "apply_workspace_edit") stub(vim.lsp.handlers, "textDocument/publishDiagnostics") after_each(function() o.get:clear() vim.lsp.util.apply_workspace_edit:clear() vim.lsp.handlers["textDocument/publishDiagnostics"]:clear() end) local client = require("nvim-lsp-ts-utils.client") describe("setup", function() local handler = stub.new() local mock_client before_each(function() mock_client = { handlers = { ["workspace/applyEdit"] = handler } } end) it("should override client handler", function() client.setup(mock_client) assert.is.Not.equals(mock_client.handlers["workspace/applyEdit"], handler) assert.equals(mock_client._ts_utils_setup_complete, true) end) it("should not override client handler if setup is complete", function() mock_client._ts_utils_setup_complete = true client.setup(mock_client) assert.equals(mock_client.handlers["workspace/applyEdit"], handler) end) end) describe("handlers", function() local edit_handler local diagnostics_handler before_each(function() local mock_client = { handlers = {} } client.setup(mock_client) edit_handler = mock_client.handlers["workspace/applyEdit"] diagnostics_handler = mock_client.handlers["textDocument/publishDiagnostics"] end) describe("edit_handler", function() it("should fix range and apply edit", function() local workspace_edit = { edit = { changes = { { { range = { start = { character = -1, line = -1 }, ["end"] = { character = -1, line = -1 }, }, }, }, }, }, } edit_handler(nil, nil, workspace_edit) assert.stub(vim.lsp.util.apply_workspace_edit).was_called_with({ changes = { { { range = { start = { character = 0, line = 0 }, ["end"] = { character = 0, line = 0 } }, }, }, }, }) end) it("should return apply_workspace_edit status and result", function() vim.lsp.util.apply_workspace_edit.invokes(function() error("something went wrong") end) local res = edit_handler(nil, nil, {}) assert.equals(res.applied, false) assert.truthy(string.find(res.failureReason, "something went wrong")) end) end) describe("diagnostics_handler", function() local diagnostics_result before_each(function() diagnostics_result = { diagnostics = { { source = "eslint", severity = u.severities.hint, code = 80001 }, { source = "typescript", severity = u.severities.error, code = 80001 }, { source = "typescript", severity = u.severities.information, code = 80001 }, { source = "typescript", severity = u.severities.hint, code = 80000 }, }, } end) it("should filter out hints and informations", function() o.get.returns({ filter_out_diagnostics_by_severity = { "information", u.severities.hint }, filter_out_diagnostics_by_code = {}, }) local expected_diagnostics_result = { diagnostics = { { source = "eslint", severity = u.severities.hint, code = 80001 }, { source = "typescript", severity = u.severities.error, code = 80001 }, }, } diagnostics_handler(nil, nil, diagnostics_result, nil, nil, nil) assert.stub(vim.lsp.handlers["textDocument/publishDiagnostics"]).was_called_with( nil, nil, expected_diagnostics_result, nil, nil, nil ) end) it("should filter out diagnostics by code", function() o.get.returns({ filter_out_diagnostics_by_severity = {}, filter_out_diagnostics_by_code = { 80001 }, }) local expected_diagnostics_result = { diagnostics = { { source = "eslint", severity = u.severities.hint, code = 80001 }, { source = "typescript", severity = u.severities.hint, code = 80000 }, }, } diagnostics_handler(nil, nil, diagnostics_result, nil, nil, nil) assert.stub(vim.lsp.handlers["textDocument/publishDiagnostics"]).was_called_with( nil, nil, expected_diagnostics_result, nil, nil, nil ) end) end) end) end)
package.path = package.path..";../?.lua" local bit = require("bit") local bor, band, lshift, rshift = bit.bor, bit.band, bit.lshift, bit.rshift local xf86drmMode = require("xf86drmMode_ffi") local libc = require("libc") local DRMFrameBuffer = require("DRMFrameBuffer") local DRMCard = require("DRMCard") local function draw(fb) -- draw something */ for i = 0, fb.Height-1 do for j = 0, fb.Width-1 do local color = ((i * j) / (fb.Height * fb.Width)) * 0xFF; fb.DataPtr[i * fb.Width + j] = band(0xFFFFFF, bor(lshift(0x00, 16), lshift(color, 8), color)); end end end local width = 1440 local height = 900 local bpp = 32 local card, err = DRMCard(); local fb = DRMFrameBuffer:newScanoutBuffer(card, width, height, bpp) print("==== FRAME BUFFER PRINT ====") print(fb) -- Save the current mode of the card and connector we are interested in --local savedCrtc = xf86drmMode.drmModeGetCrtc(card.Handle, dev.crtc_id); -- must store crtc data -- switch modes to a mode using our new framebuffer --local res = xf86drmMode.drmModeSetCrtc(card.Handle, dev.crtc_id, fb.Id, 0, 0, ffi.cast("unsigned int *",dev.conn_id), 1, dev.mode.ModeInfo) --if res ~= 0 then -- fatal("drmModeSetCrtc() failed"); --end -- Draw some stuff on our new framebuffer draw(fb) -- sleep for a little bit of time libc.sleep(3); -- restore saved crtc mode
require "Client.Scripts.Modulus.Cmd.MainCmd" require "Client.Scripts.Modulus.Cmd.BottomMidCmd" require "Client.Scripts.Modulus.Cmd.JoyStickCmd" require "Client.Scripts.Modulus.Cmd.BottomSkillCmd" require "Client.Scripts.Modulus.Cmd.FaceBookCmd" require "Client.Scripts.Modulus.Cmd.GuildCmd"
local key = ModPath .. ' ' .. RequiredScript if _G[key] then return else _G[key] = true end local REACT_AIM = AIAttentionObject.REACT_AIM local REACT_SCARED = AIAttentionObject.REACT_SCARED function CopLogicSniper._upd_enemy_detection(data) managers.groupai:state():on_unit_detection_updated(data.unit) data.t = TimerManager:game():time() local my_data = data.internal_data local min_reaction = REACT_AIM local delay = CopLogicBase._upd_attention_obj_detection(data, min_reaction, nil) local new_attention, new_prio_slot, new_reaction = CopLogicIdle._get_priority_attention(data, data.detected_attention_objects, CopLogicSniper._chk_reaction_to_attention_object) local old_att_obj = data.attention_obj CopLogicBase._set_attention_obj(data, new_attention, new_reaction) if new_reaction and new_reaction >= REACT_SCARED then local objective = data.objective local wanted_state local allow_trans, obj_failed = CopLogicBase.is_obstructed(data, objective, nil, new_attention) if allow_trans and obj_failed then wanted_state = CopLogicBase._get_logic_state_from_reaction(data) end if wanted_state and wanted_state ~= data.name then if obj_failed then data.objective_failed_clbk(data.unit, data.objective) end if my_data == data.internal_data then CopLogicBase._exit(data.unit, wanted_state) end CopLogicBase._report_detections(data.detected_attention_objects) return end end CopLogicSniper._upd_aim(data, my_data) delay = data.important and 0.1 or 0.5 + delay * 1.5 CopLogicBase.queue_task(my_data, my_data.detection_task_key, CopLogicSniper._upd_enemy_detection, data, data.t + delay) CopLogicBase._report_detections(data.detected_attention_objects) end
local U = {} local maxGetRange = 1600; local maxAddedRange = 200; local maxLevel = 25; function U.InitiateAbilities(hUnit, tSlots) local abilities = {}; for _,i in pairs(tSlots) do table.insert(abilities, hUnit:GetAbilityInSlot(i)); end return abilities; end function U.CantUseAbility(bot) return bot:NumQueuedActions() > 0 or not bot:IsAlive() or bot:IsInvulnerable() or bot:IsCastingAbility() or bot:IsUsingAbility() or bot:IsChanneling() or bot:IsSilenced() or bot:IsStunned() or bot:IsHexed() or bot:IsHexed() or bot:HasModifier("modifier_doom_bringer_doom") end function U.CanBeCast(ability) return ability:IsTrained() and ability:IsFullyCastable() and not ability:IsHidden(); end function U.GetProperCastRange(bIgnore, hUnit, ability) local abilityCR = ability:GetCastRange(); local attackRng = hUnit:GetAttackRange(); if bIgnore then return abilityCR; elseif abilityCR <= attackRng then return attackRng + maxAddedRange; elseif abilityCR + maxAddedRange <= maxGetRange then return abilityCR + maxAddedRange; elseif abilityCR > maxGetRange then return maxAddedRange; end end function U.IsRetreating(bot) return bot:GetActiveMode() == BOT_MODE_RETREAT and bot:GetActiveModeDesire() >= BOT_MODE_DESIRE_MODERATE end function U.GetLowestHPUnit(tUnits, bIgnoreImmune) local lowestHP = 100000; local lowestUnit = nil; for _,unit in pairs(tUnits) do local hp = unit:GetHealth() if hp < lowestHP and ( bIgnoreImmune or ( not bNotMagicImmune and not unit:IsMagicImmune() ) ) then lowestHP = hp; lowestUnit = unit; end end return lowestUnit; end function U.GetProperLocation(hUnit, nDelay) if hUnit:GetMovementDirectionStability() >= 0 then return hUnit:GetExtrapolatedLocation(nDelay); end return hUnit:GetLocation(); end function U.IsDefending(bot) local mode = bot:GetActiveMode(); return mode == BOT_MODE_DEFEND_TOWER_TOP or mode == BOT_MODE_DEFEND_TOWER_MID or mode == BOT_MODE_DEFEND_TOWER_BOT end function U.IsPushing(bot) local mode = bot:GetActiveMode(); return mode == BOT_MODE_PUSH_TOWER_TOP or mode == BOT_MODE_PUSH_TOWER_MID or mode == BOT_MODE_PUSH_TOWER_BOT end function U.IsInTeamFight(bot, range) local attackingAllies = bot:GetNearbyHeroes( range, false, BOT_MODE_ATTACK ); return attackingAllies ~= nil and #attackingAllies >= 2; end function U.IsGoingOnSomeone(bot) local mode = bot:GetActiveMode(); return mode == BOT_MODE_ROAM or mode == BOT_MODE_TEAM_ROAM or mode == BOT_MODE_GANK or mode == BOT_MODE_ATTACK or mode == BOT_MODE_DEFEND_ALLY end function U.IsValidTarget(target) return target ~= nil and target:IsAlive() and target:IsHero(); end function U.IsInRange(target, bot, nCastRange) return GetUnitToUnitDistance( target, bot ) <= nCastRange; end function U.IsSuspiciousIllusion(target) --TO DO Need to detect enemy hero's illusions better local bot = GetBot(); --Detect allies's illusions if target:IsIllusion() or target:HasModifier('modifier_illusion') or target:HasModifier('modifier_phantom_lancer_doppelwalk_illusion') or target:HasModifier('modifier_phantom_lancer_juxtapose_illusion') or target:HasModifier('modifier_darkseer_wallofreplica_illusion') or target:HasModifier('modifier_terrorblade_conjureimage') then return true; else --Detect replicate and wall of replica illusions if target:GetTeam() ~= bot:GetTeam() then local TeamMember = GetTeamPlayers(GetTeam()); for i = 1, #TeamMember do local ally = GetTeamMember(i); if ally ~= nil and ally:GetUnitName() == target:GetUnitName() then return true; end end end return false; end end function U.IsDisabled(enemy, target) if enemy then return target:IsRooted( ) or target:IsStunned( ) or target:IsHexed( ) or target:IsNightmared() or U.IsTaunted(target); else return target:IsRooted( ) or target:IsStunned( ) or target:IsHexed( ) or target:IsNightmared() or target:IsSilenced( ) or U.IsTaunted(target); end end function U.IsTaunted(target) return target:HasModifier("modifier_axe_berserkers_call") or target:HasModifier("modifier_legion_commander_duel") or target:HasModifier("modifier_winter_wyvern_winters_curse"); end function U.CanCastOnMagicImmune(target) return target:CanBeSeen() and not target:IsInvulnerable() and not U.IsSuspiciousIllusion(target); end function U.CanCastOnNonMagicImmune(target) return target:CanBeSeen() and not target:IsMagicImmune() and not target:IsInvulnerable() and not U.IsSuspiciousIllusion(target); end function U.CountVulnerableUnit(tUnits, locAOE, nRadius, nUnits) local count = 0; if locAOE.count >= nUnits then for _,unit in pairs(tUnits) do if GetUnitToLocationDistance(unit, locAOE.targetloc) <= nRadius and not unit:IsInvulnerable() then count = count + 1; end end end return count; end function U.CountNotStunnedUnits(tUnits, locAOE, nRadius, nUnits) local count = 0; if locAOE.count >= nUnits then for _,unit in pairs(tUnits) do if GetUnitToLocationDistance(unit, locAOE.targetloc) <= nRadius and not unit:IsInvulnerable() and not U.IsDisabled(true, unit) then count = count + 1; end end end return count; end function U.AllowedToSpam(bot, manaCost) return ( bot:GetMana() - manaCost ) / bot:GetMaxMana() >= ( 1.0 - bot:GetLevel()/(2*maxLevel) ); end return U;
--- This class handles the listeners for processing events. This -- class currently acts like a singleton but uses colon references -- in case it needs to be upgraded to a true class. -- @classmod ListenerProcessor -- region imports local class = require('classes/class') local listeners = require('classes/listeners/all') local events = require('classes/events/all') -- endregion local global_pre_listeners = {} local global_post_listeners = {} local listeners_by_event = {} -- region parsing listeners by event for _, list in ipairs(listeners) do local listens_to = list:get_events() local includes_pre = list:is_prelistener() local includes_post = list:is_postlistener() if listens_to == '*' then if includes_pre then global_pre_listeners[#global_pre_listeners + 1] = list end if includes_post then global_post_listeners[#global_post_listeners + 1] = list end else for _, evn in pairs(events) do if listens_to[evn.class_name] then local arr = listeners_by_event[evn.class_name] if not arr then arr = { pre = {}, post = {} } listeners_by_event[evn.class_name] = arr end if includes_pre then arr.pre[#arr.pre + 1] = list end if includes_post then arr.post[#arr.post + 1] = list end end end end end -- endregion -- region ordering listeners local function table_remove_by_value(tabl, val) local index = 0 for ind, v in ipairs(tabl) do if val == v then index = ind break end end if index ~= 0 then table.remove(tabl, index) end end local function get_order(list1, list2, pre) local order1 = list1:compare(list2.class_name, pre) local order2 = list2:compare(list1.class_name, pre) if order1 == 0 then return -order2 end if order2 ~= 0 and order2 ~= -order1 then error('Bad order! list1.class_name = ' .. list1.class_name .. ', list2.class_name = ' .. list2.class_name .. ', pre = ' .. tostring(pre) .. ', list1:compare(list2) = ' .. tostring(order1) .. ', list2:compare(list1) = ' .. tostring(order2)) end return order1 end local function get_sorted_listeners(lists, pre) local nodes = { -- { before = {indexes}, after = {indexes} } } local len_lists = #lists for i=1, len_lists do nodes[i] = { before = {}, after = {} } end for i=1, len_lists do for j=i+1, len_lists do local order = get_order(lists[i], lists[j], pre) if order == -1 then table.insert(nodes[i].after, j) table.insert(nodes[j].before, i) elseif order == 1 then table.insert(nodes[i].before, j) table.insert(nodes[j].after, i) end end end local without_incoming = {} for i=1, len_lists do if #nodes[i].before == 0 then table.insert(without_incoming, i) end end local sorted = {} -- Kahn's algorithm while #without_incoming > 0 do local index = without_incoming[#without_incoming] without_incoming[#without_incoming] = nil local node = nodes[index] table.insert(sorted, lists[index]) for _, after_ind in ipairs(node.after) do local after_node = nodes[after_ind] table_remove_by_value(after_node.before, index) if #after_node.before == 0 then table.insert(without_incoming, after_ind) end end end -- verify success for i, node in ipairs(nodes) do if #node.before > 0 then local msg = 'Detected cycle in listeners! Involved listeners: ' .. lists[i].class_name for j = 1, #node.before do msg = msg .. ', ' .. lists[node.before[j]].class_name end error(msg) end end return sorted end global_pre_listeners = get_sorted_listeners(global_pre_listeners, true) global_post_listeners = get_sorted_listeners(global_post_listeners, false) local new_listeners_by_event = {} for evn_name, lists in pairs(listeners_by_event) do new_listeners_by_event[evn_name] = { pre = get_sorted_listeners(lists.pre, true), post = get_sorted_listeners(lists.post, false) } end listeners_by_event = new_listeners_by_event -- endregion local ListenerProcessor = {} --- Invokes all prelisteners for the given event -- This should be called immediately prior to processing the given event -- @tparam GameContext game_ctx the game context -- @tparam LocalContext local_ctx the local context -- @tparam Networking networking the networking -- @tparam Event event the event that is about to be processed function ListenerProcessor:invoke_pre_listeners(game_ctx, local_ctx, networking, event) local lists = listeners_by_event[event.class_name] if lists then for _, list in ipairs(lists.pre) do list:process(game_ctx, local_ctx, networking, event, true) end end for _, list in ipairs(global_pre_listeners) do list:process(game_ctx, local_ctx, networking, event, true) end end --- Invokes all postlisteners for the given event -- This should be called immediately after processing the event -- @tparam GameContext game_ctx the game context -- @tparam LocalContext local_ctx the local context -- @tparam Networking networking the networking -- @tparam Event event the event that was just processed function ListenerProcessor:invoke_post_listeners(game_ctx, local_ctx, networking, event) local lists = listeners_by_event[event.class_name] if lists then for _, list in ipairs(lists.post) do list:process(game_ctx, local_ctx, networking, event, false) end end for _, list in ipairs(global_post_listeners) do list:process(game_ctx, local_ctx, networking, event, false) end end -- region add listener local function add_listener_to_table_sorted(tbl, listener, pre) if #tbl == 0 then table.insert(tbl, listener) return end local earliest_index = 1 local latest_index = #tbl + 1 for i=1, #tbl do local listener_comp_to_tbli = get_order(listener, tbl[i], pre) if listener_comp_to_tbli < 0 then earliest_index = i + 1 elseif listener_comp_to_tbli > 0 then latest_index = i end end if earliest_index < latest_index then local msg = 'Cannot add listener to table (pre=' .. tostring(pre) .. ')!\n' msg = msg .. string.format(' Listener: %s (pre=%s, post=%s)\n', listener.class_name, tostring(listener:is_prelistener()), tostring(listener:is_postlistener())) msg = msg .. 'Table:\n' for i=1, #tbl do local cls_nm = tbl[i].class_name local tbli_to_listener = tbl[i]:compare(listener.class_name, pre) local listener_to_tbli = listener:compare(tbl[i].class_name, pre) msg = msg .. string.format(' %s: to list: %d, to tbl[i]: %d\n', cls_nm, tbli_to_listener, listener_to_tbli) end msg = msg .. 'earliest_index: ' .. tostring(earliest_index) msg = msg .. 'latest_index: ' .. tostring(latest_index) end if latest_index == #tbl + 1 then table.insert(tbl, listener) else table.insert(tbl, latest_index, listener) end end --- Adds a listener to the listener processor. This is slower than -- having the listener be in the listener table in the first place, -- however it's better than resorting every time. It's not particularly -- optimized right now. -- -- This is the only way to get a listener to be instance-specific right now. -- @tparam Listener listener the listener to add function ListenerProcessor:add_listener(listener) local listens_to = listener:get_events() local is_pre = listener:is_prelistener() local is_post = listener:is_postlistener() if listens_to == '*' then if is_pre then add_listener_to_table_sorted(global_pre_listeners, listener, true) end if is_post then add_listener_to_table_sorted(global_post_listeners, listener, false) end else for evn_nm, _ in pairs(listens_to) do local lists = listeners_by_event[evn_nm] if not lists then lists = { pre = {}, post = {} } listeners_by_event[evn_nm] = lists end if is_pre then add_listener_to_table_sorted(lists.pre, listener, true) end if is_post then add_listener_to_table_sorted(lists.post, listener, false) end end end end --- Remove the specified listener by reference equality -- @tparam listener the listener to remvoe function ListenerProcessor:remove_listener(listener) local listens_to = listener:get_events() local is_pre = listener:is_prelistener() local is_post = listener:is_postlistener() if listens_to == '*' then if is_pre then table_remove_by_value(global_pre_listeners, listener) end if is_post then table_remove_by_value(global_post_listeners, listener) end else for _, evn_nm in ipairs(listens_to) do local lists = listeners_by_event[evn_nm] if is_pre then table_remove_by_value(lists.pre, listener) end if is_post then table_remove_by_value(lists.post, listener) end end end end -- endregion return class.create('ListenerProcessor', ListenerProcessor)
function On_Gossip(unit, event, player) unit:GossipCreateMenu(3544, player, 0) unit:GossipMenuAddItem(2, "Walmart", 1, 0) unit:GossipMenuAddItem(2, "Horde Cities", 3, 0) unit:GossipMenuAddItem(2, "Alliance Cities", 4, 0) unit:GossipMenuAddItem(2, "Global Locations", 5, 0) unit:GossipMenuAddItem(2, "Outland Locations", 6, 0) unit:GossipMenuAddItem(2, "Northrend Locations", 7, 0) unit:GossipMenuAddItem(2, "War Zones", 8, 0) unit:GossipMenuAddItem(2, "I'll Take A Little Boost, Thanks!", 9, 0) unit:GossipMenuAddItem(2, "Cure Me", 10, 0) unit:GossipSendMenu(player) end function Gossip_Submenus(unit, event, player, id, intid, code) if(intid == 999) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(2, "Walmart", 1, 0) unit:GossipMenuAddItem(2, "Horde Cities", 3, 0) unit:GossipMenuAddItem(2, "Alliance Cities", 4, 0) unit:GossipMenuAddItem(2, "Global Locations", 5, 0) unit:GossipMenuAddItem(2, "Outland Locations", 6, 0) unit:GossipMenuAddItem(2, "Northrend Locations", 7, 0) unit:GossipMenuAddItem(2, "War Zones", 8, 0) unit:GossipMenuAddItem(2, "I'll Take A Little Boost, Thanks!", 9, 0) unit:GossipMenuAddItem(2, "Cure Me", 10, 0) unit:GossipSendMenu(player) end if(intid == 1) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Horde Mall", 300, 0) unit:GossipMenuAddItem(1, "Alliance Mall", 301, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 3) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Orgrimmar", 15, 0) unit:GossipMenuAddItem(1, "Undercity", 16, 0) unit:GossipMenuAddItem(1, "Thunder Bluff", 17, 0) unit:GossipMenuAddItem(1, "Silvermoon City", 18, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 4) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Stormwind", 19, 0) unit:GossipMenuAddItem(1, "Ironforge", 20, 0) unit:GossipMenuAddItem(1, "Darnassus", 21, 0) unit:GossipMenuAddItem(1, "Exodar", 22, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 5) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(0, "Eastern Kingdoms", 500, 0) unit:GossipMenuAddItem(0, "Kalimdor", 501, 0) unit:GossipMenuAddItem(0, "Old School Raids", 502, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 500) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Alterac Mountains", 23, 0) unit:GossipMenuAddItem(1, "Arathi Highlands", 24, 0) unit:GossipMenuAddItem(1, "Badlands", 25, 0) unit:GossipMenuAddItem(1, "Blasted Lands", 26, 0) unit:GossipMenuAddItem(1, "Burning Steppes", 27, 0) unit:GossipMenuAddItem(1, "Deadwind Pass", 28, 0) unit:GossipMenuAddItem(1, "Dun Morogh", 29, 0) unit:GossipMenuAddItem(1, "Duskwood", 30, 0) unit:GossipMenuAddItem(1, "Eastern Plaguelands", 31, 0) unit:GossipMenuAddItem(1, "Elwynn Forest", 32, 0) unit:GossipMenuAddItem(1, "Eversong Woods", 33, 0) unit:GossipMenuAddItem(1, "Ghostlands", 34, 0) unit:GossipMenuAddItem(1, "Hillsbrad Foothills", 35, 0) unit:GossipMenuAddItem(0, "--->Second Page--->", 36, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 36) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Loch Modan",37, 0) unit:GossipMenuAddItem(1, "Redridge Mountains", 38, 0) unit:GossipMenuAddItem(1, "Searing Gorge", 39, 0) unit:GossipMenuAddItem(1, "Silverpine Forest", 40, 0) unit:GossipMenuAddItem(1, "Stranglethorn Vale", 41, 0) unit:GossipMenuAddItem(1, "Swamp Of Sorrows", 42, 0) unit:GossipMenuAddItem(1, "The Hinterlands", 43, 0) unit:GossipMenuAddItem(1, "Tirisfal Glades", 44, 0) unit:GossipMenuAddItem(1, "Western Plaguelands",45, 0) unit:GossipMenuAddItem(1, "Westfall",46, 0) unit:GossipMenuAddItem(1, "Wetlands", 47, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 501) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Ashenvale", 48, 0) unit:GossipMenuAddItem(1, "Azshara", 49, 0) unit:GossipMenuAddItem(1, "Azuremyst Isle", 50, 0) unit:GossipMenuAddItem(1, "Bloodmyst Isle", 51, 0) unit:GossipMenuAddItem(1, "Darkshore", 52, 0) unit:GossipMenuAddItem(1, "Desolace", 53, 0) unit:GossipMenuAddItem(1, "Durotar", 54, 0) unit:GossipMenuAddItem(1, "Dustwallow Marsh", 55, 0) unit:GossipMenuAddItem(1, "Felwood", 56, 0) unit:GossipMenuAddItem(1, "Feralas", 57, 0) unit:GossipMenuAddItem(1, "Moonglade", 58, 0) unit:GossipMenuAddItem(1, "Mulgore", 59, 0) unit:GossipMenuAddItem(1, "Silithus", 60, 0) unit:GossipMenuAddItem(0, "--->Second Page--->", 61, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 61) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Stonetalon Mountains", 62, 0) unit:GossipMenuAddItem(1, "Tanaris", 63, 0) unit:GossipMenuAddItem(1, "Teldrassil", 64, 0) unit:GossipMenuAddItem(1, "The Barrens", 65, 0) unit:GossipMenuAddItem(1, "Thousand Needles", 66, 0) unit:GossipMenuAddItem(1, "Un'Goro Crater", 67, 0) unit:GossipMenuAddItem(1, "Winterspring", 68, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 502) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Ahn'Qiraj", 69, 0) unit:GossipMenuAddItem(1, "Blackwing Lair", 70, 0) unit:GossipMenuAddItem(1, "Molten Core", 71, 0) unit:GossipMenuAddItem(1, "Onyxia's Lair", 72, 0) unit:GossipMenuAddItem(1, "Zul'Gurub", 73, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 6) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Blade's Edge Mountains", 74, 0) unit:GossipMenuAddItem(1, "Hellfire Peninsula", 75, 0) unit:GossipMenuAddItem(1, "Nagrand", 76, 0) unit:GossipMenuAddItem(1, "Netherstorm", 77, 0) unit:GossipMenuAddItem(1, "Shadowmoon Valley", 78, 0) unit:GossipMenuAddItem(1, "Terokkar Forest", 79, 0) unit:GossipMenuAddItem(1, "Zangarmarsh", 80, 0) unit:GossipMenuAddItem(1, "Shattrath", 81, 0) unit:GossipMenuAddItem(0, "Outland Raids", 82, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 82) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Black Temple", 83, 0) unit:GossipMenuAddItem(1, "Gruul's Lair", 84, 0) unit:GossipMenuAddItem(1, "Karazhan", 85, 0) unit:GossipMenuAddItem(1, "Magtheridon's Lair", 86, 0) unit:GossipMenuAddItem(1, "Mount Hyjal", 87, 0) unit:GossipMenuAddItem(1, "Serpentshrine Cavern", 88, 0) unit:GossipMenuAddItem(1, "Sunwell", 89, 0) unit:GossipMenuAddItem(1, "The Eye", 90, 0) unit:GossipMenuAddItem(1, "Zul'Aman", 91, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 7) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Borean Tundra", 92, 0) unit:GossipMenuAddItem(1, "Crystalsong Forest", 93, 0) unit:GossipMenuAddItem(1, "Dragonblight", 94, 0) unit:GossipMenuAddItem(1, "Grizzly Hills", 95, 0) unit:GossipMenuAddItem(1, "Howling Fjords", 96, 0) unit:GossipMenuAddItem(1, "Icecrown Glaicer", 97, 0) unit:GossipMenuAddItem(1, "Sholazar Basin", 98, 0) unit:GossipMenuAddItem(1, "Storm Peaks", 99, 0) unit:GossipMenuAddItem(1, "Wintergrasp", 100, 0) unit:GossipMenuAddItem(1, "Zul'Drak", 101, 0) unit:GossipMenuAddItem(1, "Dalaran", 102, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 8) then unit:GossipCreateMenu(3543, player, 0) unit:GossipMenuAddItem(1, "Blade's Edge Arena", 103, 0) unit:GossipMenuAddItem(1, "Gurubashi Arena", 104, 0) unit:GossipMenuAddItem(1, "Nagrand Arena", 105, 0) unit:GossipMenuAddItem(1, "Ring Of Valor (Alliance vs Horde)", 106, 0) unit:GossipMenuAddItem(0, "[Back]", 999, 0) unit:GossipSendMenu(player) end if(intid == 300) then player:Teleport(560, 2536.162354, 2456.324951, 61.985809) unit:GossipComplete(player) end if(intid == 301) then player:Teleport(560, 3604.475586, 2287.418213, 59.282700) unit:GossipComplete(player) end if(intid == 15) then player:Teleport(1, 1502.709961, -4415.419922, 21.552706) unit:GossipComplete(player) end if(intid == 16) then player:Teleport(0, 1560.453857, 244.334030, -43.102592) unit:GossipComplete(player) end if(intid == 17) then player:Teleport(1, -1195.436523, 34.784081, 132.40137) unit:GossipComplete(player) end if(intid == 18) then player:Teleport(530, 9496.041016, -7282.289551, 14.318037) unit:GossipComplete(player) end if(intid == 19) then player:Teleport(0, -8832.935547, 625.797485, 93.914894) unit:GossipComplete(player) end if(intid == 20) then player:Teleport(0, -4924.375488, -950.865112, 501.547333) unit:GossipComplete(player) end if(intid == 21) then player:Teleport(1, 9945.676758, 2482.677979, 1316.198853) unit:GossipComplete(player) end if(intid == 22) then player:Teleport(530, -3946.064941, -11727.777344, -138.922562) unit:GossipComplete(player) end if(intid == 23) then player:Teleport(0, 58.714684, -570.825317, 145.711151) unit:GossipComplete(player) end if(intid == 24) then player:Teleport(0, -1550.519409, -2496.936791, 54.452209) unit:GossipComplete(player) end if(intid == 25) then player:Teleport(0, -6819.416992, -3422.346680, 242.543167) unit:GossipComplete(player) end if(intid == 26) then player:Teleport(0, -11270.514648, -3061.004395, -0.152069) unit:GossipComplete(player) end if(intid == 27) then player:Teleport(0, -8057.234375, -1997.046143, 133.364822) unit:GossipComplete(player) end if(intid == 28) then player:Teleport(0, -10437.863281, -1866.211182, 104.634972) unit:GossipComplete(player) end if(intid == 29) then player:Teleport(0, -5271.595703, 43.802460, 386.111420) unit:GossipComplete(player) end if(intid == 30) then player:Teleport(0, -10893.999023, -349.645538, 39.141331) unit:GossipComplete(player) end if(intid == 31) then player:Teleport(0, 2263.505859, -4627.462891, 73.623268) unit:GossipComplete(player) end if(intid == 32) then player:Teleport(0, -9547.107422, 82.203911, 59.357063) unit:GossipComplete(player) end if(intid == 33) then player:Teleport(530, 8822.261719, -7098.651855, 35.365276) unit:GossipComplete(player) end if(intid == 34) then player:Teleport(530, 7230.481934, -6586.369629, 25.941483) unit:GossipComplete(player) end if(intid == 35) then player:Teleport(0, -414.885590, -662.270203, 54.499748) unit:GossipComplete(player) end if(intid == 37) then player:Teleport(0, -5544.246582, -2851.535645, 361.768768) unit:GossipComplete(player) end if(intid == 38) then player:Teleport(0, -9472.294922, -2266.869873, 74.356583) unit:GossipComplete(player) end if(intid == 39) then player:Teleport(0, -6667.144043, -1194.482300, 242.106873) unit:GossipComplete(player) end if(intid == 40) then player:Teleport(0, 581.543396, 1249.138062, 86.588158) unit:GossipComplete(player) end if(intid == 41) then player:Teleport(0, -12323.756836, -584.573059, 24.864433) unit:GossipComplete(player) end if(intid == 42) then player:Teleport(0, -10371.346680, -2723.086426, 21.678825) unit:GossipComplete(player) end if(intid == 43) then player:Teleport(0, 118.710144, -1948.693237, 148.925842) unit:GossipComplete(player) end if(intid == 44) then player:Teleport(0, 2024.515137, 168.655807, 33.867512) unit:GossipComplete(player) end if(intid == 45) then player:Teleport(0, 1678.447876, -1364.333862, 69.890274) unit:GossipComplete(player) end if(intid == 46) then player:Teleport(0, -10726.467773, 1030.061523, 33.054764) unit:GossipComplete(player) end if(intid == 47) then player:Teleport(0, -3192.923340, -2452.208496, 9.292380) unit:GossipComplete(player) end if(intid == 48) then player:Teleport(1, 2461.417725, -504.268280, 114.812622) unit:GossipComplete(player) end if(intid == 49) then player:Teleport(1, 3383.945313, -4665.848145, 94.969765) unit:GossipComplete(player) end if(intid == 50) then player:Teleport(530, -4251.174316, -12869.387695, 13.412463) unit:GossipComplete(player) end if(intid == 51) then player:Teleport(530, -2244.586670, -11910.894531, 24.423874) unit:GossipComplete(player) end if(intid == 52) then player:Teleport(1, 6145.536133, 282.024109, 23.928629) unit:GossipComplete(player) end if(intid == 53) then player:Teleport(1, -1127.806885, 1793.706909, 62.220467) unit:GossipComplete(player) end if(intid == 54) then player:Teleport(1, 601.661621, -4733.739258, -8.558049) unit:GossipComplete(player) end if(intid == 55) then player:Teleport(1, -3647.304199, -2721.955566, 33.222332) unit:GossipComplete(player) end if(intid == 56) then player:Teleport(1, 5378.582031, -752.227243, 344.328766) unit:GossipComplete(player) end if(intid == 57) then player:Teleport(1, -4805.526855, 1038.506226, 104.156227) unit:GossipComplete(player) end if(intid == 58) then player:Teleport(1, 8001.228027, -2672.624268, 512.099792) unit:GossipComplete(player) end if(intid == 59) then player:Teleport(1, -2362.893311, -826.267517, -9.369063) unit:GossipComplete(player) end if(intid == 60) then player:Teleport(1, -7015.238770, 968.619934, 5.474441) unit:GossipComplete(player) end if(intid == 62) then player:Teleport(1, 1299.952491, 728.316223, 177.870941) unit:GossipComplete(player) end if(intid == 63) then player:Teleport(1, -7184.853027, -3983.132324, 10.982137) unit:GossipComplete(player) end if(intid == 64) then player:Teleport(1, 10119.146484, 1549.032837, 1321.552002) unit:GossipComplete(player) end if(intid == 65) then player:Teleport(1, -642.360962, -2654.214844, 95.787682) unit:GossipComplete(player) end if(intid == 66) then player:Teleport(1, -5375.651367, -2509.229736, -40.432945) unit:GossipComplete(player) end if(intid == 67) then player:Teleport(1, -6178.627441, -1100.540283, -214.140274) unit:GossipComplete(player) end if(intid == 68) then player:Teleport(1, 6661.349121, -4560.519043, 717.435547) unit:GossipComplete(player) end if(intid == 69) then player:Teleport(1, -8189.559570, 1532.920898, 4.194667) unit:GossipComplete(player) end if(intid == 70) then player:Teleport(0, -7660.572266, -1221.226318, 287.787964) unit:GossipComplete(player) end if(intid == 71) then player:Teleport(230, 1120.799927, -467.276886, -104.741043) unit:GossipComplete(player) end if(intid == 72) then player:Teleport(1, -4693.167969, -3719.408936, 49.774086) unit:GossipComplete(player) end if(intid == 73) then player:Teleport(0, -11913.967773, -1115.898560, 77.279816) unit:GossipComplete(player) end if(intid == 74) then player:Teleport(530, 3034.863281, 5952.613281, 130.774368) unit:GossipComplete(player) end if(intid == 75) then player:Teleport(530, -215.563675, 2153.101074, 79.554207) unit:GossipComplete(player) end if(intid == 76) then player:Teleport(530, -1648.201416, 7686.244141, -14.353410) unit:GossipComplete(player) end if(intid == 77) then player:Teleport(530, 3037.424561, 3576.538818, 143.218384) unit:GossipComplete(player) end if(intid == 78) then player:Teleport(530, -3072.626709, 2879.110840, 82.300873) unit:GossipComplete(player) end if(intid == 79) then player:Teleport(530, -2812.025146, 5085.235352, -13.033023) unit:GossipComplete(player) end if(intid == 80) then player:Teleport(530, -203.677704, 5513.926758, 21.679346) unit:GossipComplete(player) end if(intid == 81) then player:Teleport(530, -1721.940063, 5382.318359, 1.537373) unit:GossipComplete(player) end if(intid == 83) then player:Teleport(530, -3637.713623, 315.175232, 35.551952) unit:GossipComplete(player) end if(intid == 84) then player:Teleport(530, 3530.903320, 5117.925293, 4.349529) unit:GossipComplete(player) end if(intid == 85) then player:Teleport(0, -11121.737305, -2015.547119, 47.084202) unit:GossipComplete(player) end if(intid == 86) then player:Teleport(530, -315.928223, 3090.644775, -116.455063) unit:GossipComplete(player) end if(intid == 87) then player:Teleport(1, -8173.633789, -4176.341797, -166.151794) unit:GossipComplete(player) end if(intid == 88) then player:Teleport(530, 796.048401, 6864.074219, -64.992691) unit:GossipComplete(player) end if(intid == 89) then player:Teleport(530, 12564.260742, -6775.855469, 15.090900) unit:GossipComplete(player) end if(intid == 90) then player:Teleport(530, 3086.903564, 1406.003540, 189.548431) unit:GossipComplete(player) end if(intid == 91) then player:Teleport(530, 6849.811035, -7953.119141, 170.099884) unit:GossipComplete(player) end if(intid == 92) then player:Teleport(571, 3760.002197, 5413.608398, 40.775795) unit:GossipComplete(player) end if(intid == 93) then player:Teleport(571, 5298.182129, -724.851501, 162.903442) unit:GossipComplete(player) end if(intid == 94) then player:Teleport(571, 3539.470215, 263.158417, 45.625706) unit:GossipComplete(player) end if(intid == 95) then player:Teleport(571, 3736.716553, -3862.061035, 183.021378) unit:GossipComplete(player) end if(intid == 96) then player:Teleport(571, 2029.114624, -4520.532715, 207.844940) unit:GossipComplete(player) end if(intid == 97) then player:Teleport(571, 6330.499023, 2310.453369, 477.265106) unit:GossipComplete(player) end if(intid == 98) then player:Teleport(571, 5484.500000, 4750.392578, -196.924042) unit:GossipComplete(player) end if(intid == 99) then player:Teleport(571, 8232.848633, -1483.130615, 1072.386108) unit:GossipComplete(player) end if(intid == 100) then player:Teleport(571, 4608.031738, 2846.253418, 396.896698) unit:GossipComplete(player) end if(intid == 101) then player:Teleport(571, 5449.899902, -2629.230713, 306.253143) unit:GossipComplete(player) end if(intid == 102) then player:Teleport(571, 5809.805664, 651.377075, 647.504602) unit:GossipComplete(player) end if(intid == 103) then player:Teleport(530, 2908.942383, 5973.306152, 2.096412) unit:GossipComplete(player) end if(intid == 104) then player:Teleport(0, -13258.738281, 168.794815, 34.707809) unit:GossipComplete(player) end if(intid == 105) then player:Teleport(530, -2073.057861, 6708.157227, 11.765224) unit:GossipComplete(player) end if(intid == 106) then player:Teleport(1, 2178.247070, -4766.309570, 54.911034) unit:GossipComplete(player) end if(intid == 9) then unit:FullCastSpellOnTarget(58451, player) unit:FullCastSpellOnTarget(48100, player) unit:FullCastSpellOnTarget(58453, player) unit:FullCastSpellOnTarget(48104, player) unit:FullCastSpellOnTarget(48102, player) unit:FullCastSpellOnTarget(58449, player) end if(intid == 10) then player:LearnSpell(15007) player:UnlearnSpell(15007) end end RegisterUnitGossipEvent(333333, 1, "On_Gossip") RegisterUnitGossipEvent(333333, 2, "Gossip_Submenus")
-- Dumb effect for tests { vertex = { uniformBuffers = { matrices = { wvp = "mat4" }, variables = { f = "float", v2 = "vec2", v3 = "vec3", v4 = "vec4" } }, inputs = { sl_Position = "vec4" }, code = [[ void main() { gl_Position = #matrices:wvp# * sl_Position; gl_Position.x = #variables:f# * #variables:v2#.x * #variables:v3#.x * #variables:v4#.x; SL_FIX_Y#gl_Position#; } ]] }, fragment = { uniformBuffers = { variables = { color = "vec4", tex = "sampler2D" } }, outputs = { fragColor = { type = "vec4", target = 0 } }, code = [[ void main() { fragColor = #variables:color# * texture(#variables:tex#, vec2(0, 0)); } ]] } }
sec = 14 day = 8 mon = 10 year = 2016 Text = "Neptune!"
local playsession = { {"tanneman", {248756}}, {"Augustona", {249991}}, {"Menander", {249328}}, {"Reyand", {94201}}, {"Gorlos", {237293}}, {"Qwa7", {1355}}, {"baterusoya", {56944}}, {"everLord", {206689}}, {"bbc26rus", {808}}, {"AurelienG", {197811}}, {"gearmach1ne", {137806}}, {"perrykain", {176387}}, {"mzore", {133049}}, {"keysersoyze", {48262}}, {"JohnGamer123", {31657}}, {"johnluke93", {117090}}, {"Jhumekes", {97829}}, {"Perlita109", {26543}}, {"soporis", {1535}}, {"lemarkiz", {3028}}, {"offenwagen", {56641}}, {"ugg8", {45702}}, {"redmoonrus", {1864}}, {"joe32", {46406}}, {"Mann_mit_Kimono", {39212}}, {"Jimmy50", {23989}}, {"Gerkiz", {2750}} } return playsession
local act = require "/modules/actor" local Label = {} Label.__index = Label function Label:new(x,y, color, w) local act = act.new(x, y) setmetatable(act, Label) act.w = w or 200 act.text = text or '' act.fsize = 12 act.font = nil act.color = color or {255, 255, 255} return act end function Label:setFont(font) self.font = font end function Label:draw(text, format) local text = text or self.text love.graphics.setFont(self.font) love.graphics.setColor(unpack(self.color)) love.graphics.printf(text , self.y -- x , self.x -- y , self.w , format ) end function Label:setPos(x, y) self.x, self.y = x, y end function Label:setText(text) self.text = text end return Label
data:extend { { type = 'bool-setting', name = 'picker-tool-tape-measure', setting_type = 'startup', default_value = true, order = 'tool-tape-measure' }, { type = 'bool-setting', name = 'picker-tool-ore-eraser', setting_type = 'startup', default_value = true, order = 'tool-ore-eraser' }, { type = 'bool-setting', name = 'picker-tool-camera', setting_type = 'startup', default_value = true, order = 'tool-camera' } }
-- This file is subject to copyright - contact swampservers@gmail.com for more information. local Entity = FindMetaTable("Entity") --[[ To use web materials, just call in your draw hook: mat = WebMaterial(args) Then set/override material to mat args is a table with the following potential keys: id: from SanitizeImgurId owner: player/steamid pos: rendering position, used for distance loading stretch: bool = false (stretch to fill frame, or contain to maintain aspect) shader: str = "VertexLitGeneric" params: str = "{}" (NOT A TABLE, A STRING THAT CAN BE PARSED AS A TABLE) pointsample: bool = false nsfw: bool = false (can be false, true, or "?") ]] --returns nil if invalid function SanitizeImgurId(id) if not isstring(id) or id:len() < 5 or id:len() > 100 then return end id = table.remove(string.Explode("/", id, false)) id = id:sub(1, -4) .. id:sub(-3):lower() id = id:gsub("%.jpeg", ".jpg") local id2 = " " .. id .. " " if id2:gsub("jp", "pn"):gsub(" %w+%.png ", "", 1) ~= "" then return end return id end function AsyncSanitizeImgurId(id, callback) nid = SanitizeImgurId(id) if nid then timer.Simple(0, function() callback(nid) end) return end -- expect at least 1 slash: we need gallery/id or a/id if not isstring(id) or id:len() < 5 or id:len() > 100 or not string.find(id, "/") then timer.Simple(0, function() callback(nil) end) return end local split = string.Explode("/", id, false) HTTP({ method = "GET", url = "https://imgur.com/" .. split[#split - 1] .. "/" .. split[#split], success = function(code, body, headers) if (code == 200) then callback(SanitizeImgurId(string.match(body, "og:image:height.+content=\"(.+)%?fb"))) else callback(nil) end end, failed = function(err) callback(nil) end }) end local inflight, q, qcb local function donext() if inflight then return end local nq, nqcb = q, qcb q, qcb = nil, nil inflight = true local already = false local callback = function(id) if already then return end already = true nqcb(id) inflight = false if q then donext() end end timer.Simple(30, function() if not already then callback(nil) error("Imgur timeout") end end) AsyncSanitizeImgurId(nq, callback) end function SingleAsyncSanitizeImgurId(url, callback) if qcb then qcb(nil) end q, qcb = url, callback donext() end function Entity:GetImgur() local url = self:GetNWString("imgur_url") if url ~= "" then return url, self:GetNWString("imgur_own") end end if SERVER then function Entity:SetImgur(url, own, auto) url = SanitizeImgurId(url) if url then self:SetNWString("imgur_url", url) self:SetNWString("imgur_own", own or "") self:SetNWBool("imgur_auto", auto or false) else self:SetNWString("imgur_url", "") self:SetNWString("imgur_own", "") self:SetNWBool("imgur_auto", false) end end hook.Add("OnSteamIDBanned", "ImgurEntityCleaner", function(id) for k, v in pairs(ents.GetAll()) do local url, own = v:GetImgur() if own == id then v:SetImgur() end end end) end
-- (Lot's taken from https://github.com/wbthomason/dotfiles/blob/linux/neovim/.config/nvim/init.lua) local g = vim.g local cmd = vim.cmd local o, wo, bo = vim.o, vim.wo, vim.bo local utils = require 'config.utils' local opt = utils.opt local autocmd = utils.autocmd local map = utils.map -- Leader / local leader g.mapleader = ' ' g.maplocalleader = ',' -- Skip some remote provider loading g.loaded_python_provider = 0 g.python_host_prog = '/usr/bin/python2' g.python3_host_prog = '/usr/bin/python' g.node_host_prog = '/usr/bin/neovim-node-host' -- Disable some built-in plugins we don't want local disabled_built_ins = { 'gzip', 'man', 'matchit', 'matchparen', 'shada_plugin', 'tarPlugin', 'tar', 'zipPlugin', 'zip', 'netrwPlugin', } for i = 1, 10 do g['loaded_' .. disabled_built_ins[i]] = 1 end -- Settings local buffer = { o, bo } local window = { o, wo } opt('textwidth', 100, buffer) opt('scrolloff', 7) opt('wildignore', '*.o,*~,*.pyc') opt('wildmode', 'longest,full') opt('whichwrap', vim.o.whichwrap .. '<,>,h,l') opt('inccommand', 'nosplit') opt('lazyredraw', true) opt('showmatch', true) opt('ignorecase', true) opt('smartcase', true) opt('tabstop', 2, buffer) opt('softtabstop', 0, buffer) opt('expandtab', true, buffer) opt('shiftwidth', 2, buffer) opt('number', true, window) opt('relativenumber', true, window) opt('smartindent', true, buffer) opt('laststatus', 2) opt('showmode', false) opt('shada', [['20,<50,s10,h,/100]]) opt('hidden', true) opt('shortmess', o.shortmess .. 'c') opt('completeopt', 'menuone,noselect') opt('joinspaces', false) opt('guicursor', [[n-v-c:block,i-ci-ve:ver25,r-cr:hor20,o:hor50]]) opt('updatetime', 500) opt('conceallevel', 2, window) opt('concealcursor', 'nc', window) opt('previewheight', 5) opt('undofile', true, buffer) opt('synmaxcol', 500, buffer) opt('display', 'msgsep') --opt('cursorline', true, window) opt('modeline', false, buffer) opt('mouse', 'nivh') opt('signcolumn', 'yes:1', window) -- Colorscheme -- opt('termguicolors', true) -- opt('background', 'dark') -- cmd [[colorscheme gruvbox-material]] -- cmd [[colorscheme nazgul]] -- Autocommands --autocmd('start_screen', [[VimEnter * ++once lua require('start').start()]], true) --autocmd( -- 'syntax_aucmds', -- [[Syntax * syn match extTodo "\<\(NOTE\|HACK\|BAD\|TODO\):\?" containedin=.*Comment.* | hi! link extTodo Todo]], -- true --) --autocmd('misc_aucmds', { [[BufWinEnter * checktime]], [[TextYankPost * silent! lua vim.highlight.on_yank()]] }, true) -- Commands cmd [[command! WhatHighlight :call util#syntax_stack()]] cmd [[command! PackerInstall packadd packer.nvim | lua require('plugins').install()]] cmd [[command! PackerUpdate packadd packer.nvim | lua require('plugins').update()]] cmd [[command! PackerSync packadd packer.nvim | lua require('plugins').sync()]] cmd [[command! PackerClean packadd packer.nvim | lua require('plugins').clean()]] cmd [[command! PackerCompile packadd packer.nvim | lua require('plugins').compile()]] -- Keybindings local silent = { silent = true } -- Disable annoying F1 binding map('', '<f1>', '<cmd>FloatermToggle<cr>') -- Run a build map('n', '<localleader><localleader>', '<cmd>Make<cr>', silent) -- Quit, close buffers, etc. map('n', '<leader>q', '<cmd>qa<cr>', silent) map('n', '<leader>x', '<cmd>x!<cr>', silent) map('n', '<leader>d', '<cmd>Sayonara<cr>', { silent = true, nowait = true }) -- A little Emacs in my Neovim map('n', '<c-x><c-s>', '<cmd>w<cr>', silent) map('i', '<c-x><c-s>', '<esc><cmd>w<cr>a', silent) -- Save buffer map('n', '<leader>w', '<cmd>w<cr>', { silent = true }) -- Version control map('n', 'gs', '<cmd>Neogit<cr>', silent) -- Esc in the terminal map('t', 'jj', [[<C-\><C-n>]]) -- Yank to clipboard map({ 'n', 'v' }, 'y+', '<cmd>set opfunc=util#clipboard_yank<cr>g@', silent) -- Window movement map('n', '<c-h>', '<c-w>h') map('n', '<c-j>', '<c-w>j') map('n', '<c-k>', '<c-w>k') map('n', '<c-l>', '<c-w>l')
local m_reactions={} local m_configForm = nil local m_colorForm = nil local m_template = nil local m_highlightObjID = nil local m_needRestoreHighlightByCursor = false local m_needRestoreHighlightByTarget = false local m_higlightNow = true local m_selectionColor1 = { r = 1, g = 1, b = 0, a = 0.9 } local m_selectionColor2 = { r = 1, g = 0, b = 0, a = 0.85 } local m_useMode1 = true local m_useMode2 = true local m_disableSystemHighlight = true local m_colorMode1 = nil local m_colorMode2 = nil local m_modeCheckBox1 = nil local m_modeCheckBox2 = nil local m_disableSystemHighlightCheckBox = nil local m_preview1 = nil local m_preview2 = nil local m_currMountHP = nil function AddReaction(name, func) if not m_reactions then m_reactions={} end m_reactions[name]=func end function RunReaction(widget) local name=getName(widget) if name == "GetModeBtn" then name=getName(getParent(widget)) end if not name or not m_reactions or not m_reactions[name] then return end m_reactions[name](widget) end function ButtonPressed(aParams) RunReaction(aParams.widget) changeCheckBox(aParams.widget) end function RightClick(params) end function ChangeMainWndVisible() LoadSettings() if isVisible(m_configForm) then hide(m_configForm) else show(m_configForm) end end local function GetTimestamp() return common.GetMsFromDateTime( common.GetLocalDateTime() ) end function ClearAllHighlight(anObjID) if anObjID and object.IsExist(anObjID) then unit.Select( anObjID, false, nil, nil, nil ) object.Highlight( anObjID, "SELECTION", nil, nil, 0 ) end end function ClearHighlight(anObjID) if anObjID and object.IsExist(anObjID) then if m_useMode1 then unit.Select( anObjID, false, nil, nil, nil ) end if m_useMode2 then object.Highlight( anObjID, "SELECTION", nil, nil, 0 ) end end end function Higlight(anObjID) if not anObjID or not object.IsExist(anObjID) then return end if not m_higlightNow then ClearHighlight(m_highlightObjID) else if m_useMode1 then unit.Select( anObjID, true, nil, m_selectionColor1, 1.6 ) end if m_useMode2 then object.Highlight( anObjID, "SELECTION", m_selectionColor2, nil, 0 ) end end end function OnEventIngameUnderCursorChanged( params ) if params.state == "main_view_3d_unit" then if params.unitId == m_highlightObjID then m_needRestoreHighlightByCursor = true end end if m_needRestoreHighlightByCursor and params.unitId ~= m_highlightObjID then ClearHighlight(m_highlightObjID) Higlight(m_highlightObjID) m_needRestoreHighlightByCursor = false end end function OnTargetChaged() local targetID = avatar.GetTarget() --[[if m_highlightObjID == targetID then m_needRestoreHighlightByTarget = true end if m_needRestoreHighlightByTarget and m_highlightObjID ~= targetID then ClearHighlight(m_highlightObjID) Higlight(m_highlightObjID) m_needRestoreHighlightByTarget = false end]] ClearHighlight(m_highlightObjID) Higlight(targetID) m_highlightObjID = targetID m_currMountHP = GetMountHP(targetID) end function OnCombatChaged(aParams) if aParams.objectId == m_highlightObjID then OnTargetChaged() end end --заливка при посадке на маунта не закрашивает маунта надо закрасить по новой function OnEventSecondTimer() local targetID = avatar.GetTarget() if m_highlightObjID ~= targetID then return end local mountMaxHealth = GetMountHP(targetID) if m_currMountHP ~= mountMaxHealth then ClearHighlight(targetID) Higlight(targetID) end m_currMountHP = mountMaxHealth end function GetMountHP(anObjID) if not anObjID or not object.IsExist(anObjID) or not unit.IsPlayer(anObjID) then return 0 end local mountInfo = mount.GetUnitMountHealth( anObjID ) if mountInfo then return mountInfo.healthLimit end return 0 end function SavePressed() m_needRestoreHighlightByCursor = false m_needRestoreHighlightByTarget = false m_useMode1 = getCheckBoxState(m_modeCheckBox1) m_useMode2 = getCheckBoxState(m_modeCheckBox2) m_disableSystemHighlight = getCheckBoxState(m_disableSystemHighlightCheckBox) local saveObj = {} saveObj.color = m_selectionColor1 saveObj.color2 = m_selectionColor2 saveObj.useMode1 = m_useMode1 saveObj.useMode2 = m_useMode2 saveObj.disableSystemHighlight = m_disableSystemHighlight userMods.SetGlobalConfigSection("TH_settings", saveObj) ClearAllHighlight(m_highlightObjID) common.StateUnloadManagedAddon( "UserAddon/TargetHighlighter" ) common.StateLoadManagedAddon( "UserAddon/TargetHighlighter" ) end function LoadSettings() local settings = userMods.GetGlobalConfigSection("TH_settings") if settings then m_selectionColor1 = settings.color m_selectionColor2 = settings.color2 m_useMode1 = settings.useMode1 m_useMode2 = settings.useMode2 m_disableSystemHighlight = settings.disableSystemHighlight end setLocaleText(m_modeCheckBox1, m_useMode1) setLocaleText(m_modeCheckBox2, m_useMode2) setLocaleText(m_disableSystemHighlightCheckBox, m_disableSystemHighlight) m_preview1:SetBackgroundColor(m_selectionColor1) m_preview2:SetBackgroundColor(m_selectionColor2) OnTargetChaged() end function InitConfigForm() setTemplateWidget(m_template) local formWidth = 300 local form=createWidget(mainForm, "ConfigForm", "Panel", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, formWidth, 250, 100, 120) priority(form, 2500) hide(form) local btnWidth = 100 setLocaleText(createWidget(form, "saveBtn", "Button", WIDGET_ALIGN_HIGH, WIDGET_ALIGN_HIGH, btnWidth, 25, formWidth/2-btnWidth/2, 20)) setLocaleText(createWidget(form, "header", "TextView", nil, nil, 140, 25, 20, 20)) setLocaleText(createWidget(form, "colorMode1Btn", "Button", nil, nil, 80, 25, 10, 112)) setLocaleText(createWidget(form, "colorMode2Btn", "Button", nil, nil, 80, 25, 10, 164)) m_disableSystemHighlightCheckBox = createWidget(form, "disableSystemHighlight", "CheckBox", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 280, 25, 10, 60) m_modeCheckBox1 = createWidget(form, "useMode1", "CheckBox", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 280, 25, 10, 86) m_modeCheckBox2 = createWidget(form, "useMode2", "CheckBox", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 280, 25, 10, 138) m_preview1 = createWidget(form, "preview1", "ImageBox", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 24, 24, 266, 112) m_preview2 = createWidget(form, "preview2", "ImageBox", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 24, 24, 266, 164) m_preview1:SetBackgroundTexture(nil) m_preview2:SetBackgroundTexture(nil) setText(createWidget(form, "closeMainButton", "Button", WIDGET_ALIGN_HIGH, WIDGET_ALIGN_LOW, 20, 20, 20, 20), "x") DnD:Init(form, form, true) return form end function ShowColorMode1Pressed() AddReaction("setColorButton", ColorMode1Changed) ShowColorPressed(m_selectionColor1) end function ShowColorMode2Pressed() AddReaction("setColorButton", ColorMode2Changed) ShowColorPressed(m_selectionColor2) end function ShowColorPressed(aColor) if m_colorForm then DnD.Remove(m_colorForm) destroy(m_colorForm) end m_colorForm = CreateColorSettingsForm(aColor) show(m_colorForm) end function ColorMode1Changed(aWdg) swap(getParent(aWdg)) m_selectionColor1 = GetColorFromColorSettingsForm() m_preview1:SetBackgroundColor(m_selectionColor1) OnTargetChaged() end function ColorMode2Changed(aWdg) swap(getParent(aWdg)) m_selectionColor2 = GetColorFromColorSettingsForm() m_preview2:SetBackgroundColor(m_selectionColor2) OnTargetChaged() end function ChangeClientSettings() options.Update() local pageIds = options.GetPageIds() for pageIndex = 0, GetTableSize( pageIds ) - 1 do local pageId = pageIds[pageIndex] if pageIndex == 3 then local groupIds = options.GetGroupIds(pageId) if groupIds then for groupIndex = 0, GetTableSize( groupIds ) - 1 do local groupId = groupIds[groupIndex] local blockIds = options.GetBlockIds( groupId ) for blockIndex = 0, GetTableSize( blockIds ) - 1 do local blockId = blockIds[blockIndex] local optionIds = options.GetOptionIds( blockId ) for optionIndex = 0, GetTableSize( optionIds ) - 1 do local optionId = optionIds[optionIndex] if pageIndex == 3 and groupIndex == 0 and blockIndex == 1 then if optionIndex == 0 then -- толщина обводки options.SetOptionCurrentIndex( optionId, 10 ) elseif optionIndex == 1 then -- прозрачность обводки options.SetOptionCurrentIndex( optionId, 10 ) end end end end end end options.Apply( pageId ) end end end function Init() ChangeClientSettings() m_template = createWidget(nil, "Template", "Template") setTemplateWidget(m_template) local button=createWidget(mainForm, "THButton", "Button", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 25, 25, 300, 120) setText(button, "TH") DnD:Init(button, button, true) common.RegisterReactionHandler( RightClick, "RIGHT_CLICK" ) common.RegisterReactionHandler(ButtonPressed, "execute") common.RegisterEventHandler( OnTargetChaged, "EVENT_AVATAR_TARGET_CHANGED") common.RegisterEventHandler( OnCombatChaged, "EVENT_OBJECT_COMBAT_STATUS_CHANGED") common.RegisterEventHandler(OnEventSecondTimer, "EVENT_SECOND_TIMER") m_configForm = InitConfigForm() LoadSettings() AddReaction("THButton", function () ChangeMainWndVisible() end) AddReaction("closeMainButton", function (aWdg) ChangeMainWndVisible() end) AddReaction("closeButton", function (aWdg) swap(getParent(aWdg)) end) AddReaction("colorMode1Btn", ShowColorMode1Pressed) AddReaction("colorMode2Btn", ShowColorMode2Pressed) AddReaction("saveBtn", SavePressed) local systemAddonStateChanged = false local targetSelectionLoaded = false local addons = common.GetStateManagedAddons() for i = 0, GetTableSize( addons ) - 1 do local info = addons[i] if info.name == "TargetSelection" then if info.isLoaded then targetSelectionLoaded = true end end end if m_disableSystemHighlight then common.StateUnloadManagedAddon( "TargetSelection" ) systemAddonStateChanged = targetSelectionLoaded else common.StateLoadManagedAddon( "TargetSelection" ) common.RegisterEventHandler( OnEventIngameUnderCursorChanged, "EVENT_INGAME_UNDER_CURSOR_CHANGED") systemAddonStateChanged = not targetSelectionLoaded end if systemAddonStateChanged then for i = 0, GetTableSize( addons ) - 1 do local info = addons[i] if string.find(info.name, "AOPanelMod") then if info.isLoaded then common.StateUnloadManagedAddon( info.name ) common.StateLoadManagedAddon( info.name ) end end end end AoPanelSupportInit() end if (avatar.IsExist()) then Init() else common.RegisterEventHandler(Init, "EVENT_AVATAR_CREATED") end
local function raw_table(state, arguments) local tbl = arguments[1] if not pcall(assert.falsy, getmetatable(tbl)) then return false end for _, v in ipairs({"ROWS", "VOID"}) do if tbl.type == v then return false end end if tbl.meta ~= nil then return false end return true end local say = require "say" say:set("assertion.raw_table.positive", "Expected %s\nto be a raw table") say:set("assertion.raw_table.negative", "Expected %s\nto not be a raw_table") assert:register("assertion", "raw_table", raw_table, "assertion.raw_table.positive", "assertion.raw_table.negative") local helpers = require "spec.02-integration.03-dao.helpers" local Factory = require "kong.dao.factory" local api_tbl = { name = "example", hosts = { "example.org" }, uris = { "/example" }, strip_uri = true, upstream_url = "https://example.org" } helpers.for_each_dao(function(kong_config) describe("Model (CRUD) with DB: #" .. kong_config.database, function() local factory, apis, oauth2_credentials setup(function() factory = assert(Factory.new(kong_config)) apis = factory.apis -- DAO used for testing arrays oauth2_credentials = factory.oauth2_credentials oauth2_credentials.constraints.unique.client_id.schema.fields.consumer_id.required = false assert(factory:run_migrations()) end) teardown(function() factory:truncate_tables() ngx.shared.kong_cassandra:flush_expired() end) describe("insert()", function() after_each(function() factory:truncate_tables() end) it("insert a valid API", function() local api, err = apis:insert(api_tbl) assert.falsy(err) assert.is_table(api) for k in pairs(api_tbl) do assert.truthy(api[k]) end -- Check that the timestamp is properly deserialized assert.truthy(type(api.created_at) == "number") end) it("insert a valid API bis", function() local api, err = apis:insert { name = "example", hosts = { "example.org" }, upstream_url = "http://example.org", } assert.falsy(err) assert.is_table(api) assert.equal("example", api.name) assert.raw_table(api) end) it("insert a valid array field and return it properly", function() local res, err = oauth2_credentials:insert { name = "test_app", redirect_uri = "https://example.org" } assert.falsy(err) assert.is_table(res) assert.equal("test_app", res.name) assert.is_table(res.redirect_uri) assert.equal(1, #res.redirect_uri) assert.same({"https://example.org"}, res.redirect_uri) assert.raw_table(res) end) it("insert a valid array field and return it properly bis", function() local res, err = oauth2_credentials:insert { name = "test_app", redirect_uri = "https://example.org, https://example.com" } assert.falsy(err) assert.is_table(res) assert.equal("test_app", res.name) assert.is_table(res.redirect_uri) assert.equal(2, #res.redirect_uri) assert.same({"https://example.org", "https://example.com"}, res.redirect_uri) assert.raw_table(res) end) it("add DAO-inserted values", function() local api, err = apis:insert(api_tbl) assert.falsy(err) assert.is_table(api) assert.truthy(api.id) assert.False(api.preserve_host) assert.is_number(api.created_at) assert.equal(13, #tostring(api.created_at)) -- Make sure the timestamp has millisecond precision when returned end) it("respect UNIQUE fields", function() local api, err = apis:insert(api_tbl) assert.falsy(err) assert.is_table(api) api, err = apis:insert(api_tbl) assert.falsy(api) assert.truthy(err) assert.True(err.unique) assert.equal("already exists with value 'example'", err.tbl.name) end) it("ignores ngx.null fields", function() local api, err = apis:insert { name = "example", hosts = { "example.org" }, upstream_url = "http://example.org", uris = ngx.null, methods = ngx.null, } assert.falsy(err) assert.is_table(api) assert.equal("example", api.name) assert.is_nil(api.uris) assert.is_nil(api.methods) assert.raw_table(api) end) describe("errors", function() it("refuse if invalid schema", function() local api, err = apis:insert { name = "example" } assert.falsy(api) assert.truthy(err) assert.True(err.schema) api, err = apis:insert { name = "example", hosts = { "example" } } assert.falsy(api) assert.truthy(err) assert.True(err.schema) api, err = apis:insert {} assert.falsy(api) assert.truthy(err) assert.True(err.schema) end) it("handle nil arg", function() assert.has_error(function() apis:insert() end, "bad argument #1 to 'insert' (table expected, got nil)") end) it("handle invalid arg", function() assert.has_error(function() apis:insert "" end, "bad argument #1 to 'insert' (table expected, got string)") end) end) end) describe("find()", function() local api_fixture before_each(function() local api, err = apis:insert(api_tbl) assert.falsy(err) assert.truthy(api) api_fixture = api end) after_each(function() factory:truncate_tables() end) it("select by primary key", function() local api, err = apis:find(api_fixture) assert.falsy(err) assert.same(api_fixture, api) assert.raw_table(api) end) it("handle invalid field", function() local api, err = apis:find { id = "abcd", foo = "bar" } assert.falsy(api) assert.truthy(err) assert.True(err.schema) end) describe("errors", function() it("error if no primary key", function() assert.has_error(function() apis:find {name = "example"} end, "Missing PRIMARY KEY field") end) it("handle nil arg", function() assert.has_error(function() apis:find() end, "bad argument #1 to 'find' (table expected, got nil)") end) it("handle invalid arg", function() assert.has_error(function() apis:find "" end, "bad argument #1 to 'find' (table expected, got string)") end) end) end) describe("find_all()", function() setup(function() factory:truncate_tables() for i = 1, 100 do local api, err = apis:insert { name = "fixture_" .. i, hosts = { "fixture" .. i .. ".com" }, upstream_url = "http://fixture.org" } assert.falsy(err) assert.truthy(api) end local res, err = oauth2_credentials:insert { name = "test_app", redirect_uri = "https://example.org, https://example.com" } assert.falsy(err) assert.truthy(res) end) teardown(function() factory:truncate_tables() end) it("retrieve all rows", function() local rows, err = apis:find_all() assert.falsy(err) assert.is_table(rows) assert.equal(100, #rows) assert.raw_table(rows) end) pending("retrieve all matching rows", function() local rows, err = apis:find_all { hosts = { "fixture1.com" } } assert.falsy(err) assert.is_table(rows) assert.equal(1, #rows) assert.same({ "fixture1.com" }, rows[1].hosts) assert.unique(rows) end) pending("return matching rows bis", function() local rows, err = apis:find_all { hosts = { "fixture100.com" }, name = "fixture_100" } assert.falsy(err) assert.is_table(rows) assert.equal(1, #rows) assert.equal("fixture_100", rows[1].name) end) it("return rows with arrays", function() local rows, err = oauth2_credentials:find_all() assert.falsy(err) assert.is_table(rows) assert.equal(1, #rows) assert.equal("test_app", rows[1].name) assert.is_table(rows[1].redirect_uri) assert.equal(2, #rows[1].redirect_uri) assert.same({ "https://example.org", "https://example.com" }, rows[1].redirect_uri) end) pending("return empty table if no row match", function() local rows, err = apis:find_all { hosts = { "inexistent.com" } } assert.falsy(err) assert.same({}, rows) end) pending("handles non-string values", function() local rows, err = apis:find_all { hosts = { string.char(105, 213, 205, 149) } } assert.falsy(err) assert.same({}, rows) end) describe("errors", function() it("handle invalid arg", function() assert.has_error(function() apis:find_all "" end, "bad argument #1 to 'find_all' (table expected, got string)") assert.has_error(function() apis:find_all {} end, "bad argument #1 to 'find_all' (expected table to not be empty)") end) it("handle invalid filter field", function() local rows, err = apis:find_all { foo = "bar", name = "fixture_100" } assert.truthy(err) assert.falsy(rows) assert.equal("unknown field", err.tbl.foo) end) it("handles invalid schema subset", function() assert.has_no_errors(function() apis:find_all { id = ngx.null } end) end) end) end) describe("find_page()", function() setup(function() factory:truncate_tables() for i = 1, 100 do local api, err = apis:insert { name = "fixture_" .. i, hosts = { "fixture" .. i .. ".com" }, upstream_url = "http://fixture.org" } assert.falsy(err) assert.truthy(api) end end) teardown(function() factory:truncate_tables() end) it("has a default_page size (100)", function() local rows, err = apis:find_page() assert.falsy(err) assert.is_table(rows) assert.equal(100, #rows) assert.raw_table(rows) end) it("support page_size", function() local rows, err = apis:find_page(nil, nil, 25) assert.falsy(err) assert.is_table(rows) assert.equal(25, #rows) end) it("support page_offset", function() local all_rows = {} local rows, err, offset for i = 1, 3 do rows, err, offset = apis:find_page(nil, offset, 30) assert.falsy(err) assert.equal(30, #rows) assert.truthy(offset) for _, row in ipairs(rows) do table.insert(all_rows, row) end end rows, err, offset = apis:find_page(nil, offset, 30) assert.falsy(err) assert.equal(10, #rows) assert.falsy(offset) for _, row in ipairs(rows) do table.insert(all_rows, row) end assert.unique(all_rows) end) it("support a filter", function() local rows, err, offset = apis:find_page { name = "fixture_2" } assert.falsy(err) assert.is_table(rows) assert.falsy(offset) assert.equal(1, #rows) assert.equal("fixture_2", rows[1].name) end) it("filter supports primary keys", function() local rows, err = apis:find_page { name = "fixture_2" } assert.falsy(err) local first_api = rows[1] local rows, err, offset = apis:find_page { id = first_api.id } assert.falsy(err) assert.is_table(rows) assert.falsy(offset) assert.equal(1, #rows) assert.same(first_api, rows[1]) end) it("filter supports a boolean value", function() local rows, err, _ = apis:find_page { name = "fixture_2", https_only = "false" } assert.falsy(err) assert.is_table(rows) end) describe("errors", function() it("handle invalid arg", function() assert.has_error(function() apis:find_page(nil, nil, "") end, "bad argument #3 to 'find_page' (number expected, got string)") assert.has_error(function() apis:find_page "" end, "bad argument #1 to 'find_page' (table expected, got string)") assert.has_error(function() apis:find_page {} end, "bad argument #1 to 'find_page' (expected table to not be empty)") end) it("handle invalid filter field", function() local rows, err = apis:find_page { foo = "bar", name = "fixture_100" } assert.truthy(err) assert.falsy(rows) assert.equal("unknown field", err.tbl.foo) end) it("handles invalid schema subset", function() assert.has_no_errors(function() apis:find_all { id = ngx.null } end) end) end) end) describe("count()", function() setup(function() factory:truncate_tables() for i = 1, 100 do local api, err = apis:insert { name = "fixture_" .. i, hosts = { "fixture" .. i .. ".com" }, upstream_url = "http://fixture.org" } assert.falsy(err) assert.truthy(api) end end) teardown(function() factory:truncate_tables() end) it("return the count of rows", function() local count, err = apis:count() assert.falsy(err) assert.equal(100, count) end) it("return the count of rows with filtering", function() local count, err = apis:count {name = "fixture_1"} assert.falsy(err) assert.equal(1, count) end) it("return 0 if filter doesn't match", function() local count, err = apis:count {name = "inexistent"} assert.falsy(err) assert.equal(0, count) end) describe("errors", function() it("handle invalid arg", function() assert.has_error(function() apis:count "" end, "bad argument #1 to 'count' (table expected, got string)") assert.has_error(function() apis:count {} end, "bad argument #1 to 'count' (expected table to not be empty)") end) it("handle invalid filter field", function() local rows, err = apis:count { foo = "bar", name = "fixture_100" } assert.truthy(err) assert.falsy(rows) assert.equal("unknown field", err.tbl.foo) end) it("handles invalid schema subset", function() assert.has_no_errors(function() apis:find_all { id = ngx.null } end) end) end) end) describe("update()", function() local api_fixture before_each(function() factory:truncate_tables() local api, err = apis:insert(api_tbl) assert.falsy(err) api_fixture = api end) after_each(function() factory:truncate_tables() end) it("update by primary key", function() api_fixture.name = "updated" local api, err = apis:update(api_fixture, {id = api_fixture.id}) assert.falsy(err) assert.same(api_fixture, api) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.same(api_fixture, api) assert.is_number(api.created_at) assert.equal(13, #tostring(api.created_at)) -- Make sure the timestamp has millisecond precision when returned end) it("update with arbitrary filtering keys", function() api_fixture.name = "updated" local api, err = apis:update(api_fixture, { name = "example" }) assert.falsy(err) assert.same(api_fixture, api) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.same(api_fixture, api) end) it("update multiple fields", function() api_fixture.name = "updated" api_fixture.hosts = { "updated.com" } api_fixture.upstream_url = "http://updated.com" local api, err = apis:update(api_fixture, {id = api_fixture.id}) assert.falsy(err) assert.same(api_fixture, api) api, err = apis:find(api_fixture) assert.falsy(err) assert.same(api_fixture, api) end) it("update partial entity (pass schema validation)", function() local api, err = apis:update({name = "updated"}, {id = api_fixture.id}) assert.falsy(err) assert.equal("updated", api.name) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.equal("updated", api.name) end) it("return nil if no rows were affected", function() local api, err = apis:update({ name = "inexistent", hosts = { "inexistent.com" }, upstream_url = "http://inexistent.com" }, {id = "6f204116-d052-11e5-bec8-5bc780ae6c56",}) assert.falsy(err) assert.falsy(api) end) it("check constraints", function() local api, err = apis:insert { name = "i_am_unique", hosts = { "unique.com" }, upstream_url = "http://unique.com" } assert.falsy(err) assert.truthy(api) api_fixture.name = "i_am_unique" api, err = apis:update(api_fixture, {id = api_fixture.id}) assert.truthy(err) assert.falsy(api) assert.equal("already exists with value 'i_am_unique'", err.tbl.name) end) it("check schema", function() api_fixture.name = 1 local api, err = apis:update(api_fixture, {id = api_fixture.id}) assert.truthy(err) assert.falsy(api) assert.True(err.schema) assert.equal("name is not a string", err.tbl.name) end) it("does not unset nil fields", function() api_fixture.uris = nil local api, err = apis:update(api_fixture, {id = api_fixture.id}) assert.falsy(err) assert.truthy(api) assert.not_same(api_fixture, api) assert.truthy(api.uris) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.not_same(api_fixture, api) assert.truthy(api.uris) end) it("does unset ngx.null fields", function() api_fixture.uris = ngx.null local api, err = apis:update(api_fixture, {id = api_fixture.id}) assert.falsy(err) assert.truthy(api) assert.not_same(api_fixture, api) assert.falsy(api.uris) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.not_same(api_fixture, api) assert.falsy(api.uris) end) describe("full", function() it("update with nil fetch_keys", function() -- primary key is contained in entity body api_fixture.name = "updated-full" local api, err = apis:update(api_fixture, api_fixture, {full = true}) assert.falsy(err) assert.truthy(api) assert.same(api_fixture, api) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.same(api_fixture, api) end) it("unset nil fields", function() api_fixture.uris = nil local api, err = apis:update(api_fixture, api_fixture, {full = true}) assert.falsy(err) assert.truthy(api) assert.same(api_fixture, api) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.same(api_fixture, api) end) it("unset ngx.null fields", function() api_fixture.uris = ngx.null local api, err = apis:update(api_fixture, api_fixture, {full = true}) api_fixture.uris = nil assert.falsy(err) assert.truthy(api) assert.same(api_fixture, api) assert.raw_table(api) api, err = apis:find(api_fixture) assert.falsy(err) assert.same(api_fixture, api) end) it("check schema", function() api_fixture.name = nil local api, err = apis:update(api_fixture, api_fixture, {full = true}) assert.truthy(err) assert.falsy(api) assert.True(err.schema) api, err = apis:find(api_fixture) assert.falsy(err) assert.is_table(api.hosts) assert.is_table(api.uris) end) end) describe("errors", function() it("handle invalid arg", function() assert.has_error(function() apis:update "foo" end, "bad argument #1 to 'update' (table expected, got string)") assert.has_error(function() apis:update {} end, "bad argument #1 to 'update' (expected table to not be empty)") assert.has_error(function() apis:update({a = ""}, "") end, "bad argument #2 to 'update' (table expected, got string)") end) it("handle nil arg", function() assert.has_error(function() apis:update() end, "bad argument #1 to 'update' (table expected, got nil)") end) end) end) describe("delete()", function() local api_fixture before_each(function() factory:truncate_tables() local api, err = apis:insert(api_tbl) assert.falsy(err) api_fixture = api end) after_each(function() factory:truncate_tables() end) it("delete a row", function() local res, err = apis:delete(api_fixture) assert.falsy(err) assert.same(res, api_fixture) local api, err = apis:find(api_fixture) assert.falsy(err) assert.falsy(api) end) it("return false if no rows were deleted", function() local res, err = apis:delete { id = "6f204116-d052-11e5-bec8-5bc780ae6c56", name = "inexistent", hosts = { "inexistent.com" }, upstream_url = "http://inexistent.com" } assert.falsy(err) assert.falsy(res) local api, err = apis:find(api_fixture) assert.falsy(err) assert.truthy(api) end) describe("errors", function() it("handle invalid arg", function() assert.has_error(function() apis:delete "foo" end, "bad argument #1 to 'delete' (table expected, got string)") end) it("handle nil arg", function() assert.has_error(function() apis:delete() end, "bad argument #1 to 'delete' (table expected, got nil)") end) end) end) describe("errors", function() it("returns errors prefixed by the DB type in __tostring()", function() local pg_port = kong_config.pg_port local cassandra_port = kong_config.cassandra_port local cassandra_timeout = kong_config.cassandra_timeout finally(function() kong_config.pg_port = pg_port kong_config.cassandra_port = cassandra_port kong_config.cassandra_timeout = cassandra_timeout ngx.shared.kong_cassandra:flush_all() ngx.shared.kong_cassandra:flush_expired() end) kong_config.pg_port = 3333 kong_config.cassandra_port = 3333 kong_config.cassandra_timeout = 1000 assert.error_matches(function() local fact = assert(Factory.new(kong_config)) assert(fact.apis:find_all()) end, "[" .. kong_config.database .. " error]", nil, true) end) end) end) -- describe end) -- for each
return { summary = 'Destroy the Shape.', description = 'Destroy the Shape, removing it from Colliders it\'s attached to.', arguments = {}, returns = {}, notes = 'Calling functions on the Shape after destroying it is a bad idea.', related = { 'Collider:destroy', 'Joint:destroy', 'World:destroy' } }
local Player, super = Class(Character) function Player:init(chara, x, y) super:init(self, chara, x, y) local hx, hy, hw, hh = self.collider.x, self.collider.y, self.collider.width, self.collider.height self.interact_collider = { ["left"] = Hitbox(self, hx - hw/2, hy, hw, hh), ["right"] = Hitbox(self, hx + hw/2, hy, hw, hh), ["up"] = Hitbox(self, hx, hy - hh/2, hw, hh), ["down"] = Hitbox(self, hx, hy + hh/2, hw, hh) } self.history_time = 0 self.history = {} self.battle_canvas = love.graphics.newCanvas(320, 240) self.battle_alpha = 0 self.persistent = true end function Player:onAdd(parent) super:onAdd(self, parent) if parent:includes(World) and not parent.player then parent.player = self end end function Player:onRemove(parent) super:onRemove(self, parent) if parent:includes(World) and parent.player == self then parent.player = nil end end function Player:interact() local col = self.interact_collider[self.facing] for _,obj in ipairs(self.world.children) do if obj.onInteract and obj:collidesWith(col) and obj:onInteract(self, self.facing) then return true end end return false end function Player:alignFollowers(facing, x, y) local ex, ey = self:getExactPosition() facing = facing or self.facing x, y = x or ex, y or ey local offset_x, offset_y = 0, 0 if facing == "left" then offset_x = 1 elseif facing == "right" then offset_x = -1 elseif facing == "up" then offset_y = 1 elseif facing == "down" then offset_y = -1 end self.history = {{x = ex, y = ey, time = self.history_time}} for i = 1, Game.max_followers do local dist = ((i * FOLLOW_DELAY) / (1/30)) * 4 table.insert(self.history, {x = x + (offset_x * dist), y = y + (offset_y * dist), time = self.history_time - (i * FOLLOW_DELAY)}) end end function Player:keepFollowerPositions() local ex, ey = self:getExactPosition() self.history = {{x = ex, y = ey, time = self.history_time}} for i,follower in ipairs(Game.world.followers) do local fex, fey = follower:getExactPosition() table.insert(self.history, {x = fex, y = fey, time = self.history_time - (i * FOLLOW_DELAY)}) end end function Player:update(dt) if #self.history == 0 then local ex, ey = self:getExactPosition() table.insert(self.history, {x = ex, y = ey, time = 0}) end if self.moved > 0 then self.history_time = self.history_time + dt local ex, ey = self:getExactPosition() if self.last_collided_x then ex = self.x end if self.last_collided_y then ey = self.y end table.insert(self.history, 1, {x = ex, y = ey, time = self.history_time}) while (self.history_time - self.history[#self.history].time) > (Game.max_followers * FOLLOW_DELAY) do table.remove(self.history, #self.history) end for _,follower in ipairs(Game.followers) do if follower.target == self and follower.following then follower:interprolate() end end end self.world.in_battle = false for _,area in ipairs(self.world.battle_areas) do if area:collidesWith(self.collider) then self.world.in_battle = true break end end if self.world.in_battle then self.battle_alpha = math.min(self.battle_alpha + (0.04 * DTMULT), 0.8) else self.battle_alpha = math.max(self.battle_alpha - (0.08 * DTMULT), 0) end self.world.soul.alpha = self.battle_alpha * 2 super:update(self, dt) end function Player:draw() -- Draw the player super:draw(self) -- Now we need to draw their battle mode overlay if self.battle_alpha > 0 then Draw.pushCanvas(self.battle_canvas) -- Let's draw in the middle of the canvas so the left doesnt get cut off -- There's more elegant ways to do this but whatever -- TODO: make the canvas size fit to the player instead of forcing 320x240 love.graphics.translate(320 / 2, 240 / 2) love.graphics.clear() love.graphics.setShader(Kristal.Shaders["AddColor"]) -- Left love.graphics.translate(-1, 0) Kristal.Shaders["AddColor"]:send("inputcolor", {1, 0, 0}) Kristal.Shaders["AddColor"]:send("amount", 1) super:draw(self) -- Right love.graphics.translate(2, 0) Kristal.Shaders["AddColor"]:send("inputcolor", {1, 0, 0}) Kristal.Shaders["AddColor"]:send("amount", 1) super:draw(self) -- Up love.graphics.translate(-1, -1) Kristal.Shaders["AddColor"]:send("inputcolor", {1, 0, 0}) Kristal.Shaders["AddColor"]:send("amount", 1) super:draw(self) -- Down love.graphics.translate(0, 2) Kristal.Shaders["AddColor"]:send("inputcolor", {1, 0, 0}) Kristal.Shaders["AddColor"]:send("amount", 1) super:draw(self) -- Center love.graphics.translate(0, -1) Kristal.Shaders["AddColor"]:send("inputcolor", {32/255, 32/255, 32/255}) Kristal.Shaders["AddColor"]:send("amount", 1) super:draw(self) love.graphics.setShader() Draw.popCanvas() love.graphics.setColor(1, 1, 1, self.battle_alpha) love.graphics.draw(self.battle_canvas, -320 / 2, -240 / 2) love.graphics.setColor(1, 1, 1, 1) end local col = self.interact_collider[self.facing] if DEBUG_RENDER then col:draw(1, 0, 0, 0.5) end end return Player
--setting up neovim globle settings --All explaned {nothing to do here} vim.o.backup = false -- creates a backup file vim.o.clipboard = "unnamedplus" -- allows neovim to access the system clipboard vim.o.cmdheight = 2 -- more space in the neovim command line for displaying messages vim.o.colorcolumn = "99999" -- fixes indentline for now vim.o.completeopt = "menuone,noselect" vim.o.conceallevel = 0 -- so that `` is visible in markdown files vim.o.cursorline = true -- highlight the current line vim.o.expandtab = true -- convert tabs to spaces vim.o.fileencoding = "utf-8" -- the encoding written to a file vim.o.foldexpr = "" -- set to "nvim_treesitter#foldexpr()" for treesitter based folding vim.o.foldmethod = "manual" -- folding set to "expr" for treesitter based folding vim.o.guifont = "monospace:h17" -- the font used in graphical neovim applications vim.o.hidden = true -- required to keep multiple buffers and open multiple buffers vim.o.hlsearch = true -- highlight all matches on previous search pattern vim.o.ignorecase = true -- ignore case in search patterns vim.o.mouse = "a" -- allow the mouse to be used in neovim vim.o.numberwidth = 4 -- set number column width to 2 {default 4} vim.o.pumheight = 10 -- pop up menu height vim.o.relativenumber = false -- set relative numbered lines vim.o.scrolloff = 8 -- is one of my fav vim.o.shiftwidth = 2 -- the number of spaces inserted for each indentation vim.o.showmode = false -- we don't need to see things like -- INSERT -- anymore vim.o.showtabline = 2 -- always show tabs vim.o.sidescrolloff = 8 vim.o.signcolumn = "yes" -- always show the sign column otherwise it would shift the text each time vim.o.smartcase = true -- smart case vim.o.smartindent = true -- make indenting smarter again vim.o.spell = false vim.o.spelllang = "en" vim.o.splitbelow = true -- force all horizontal splits to go below current window vim.o.splitright = true -- force all vertical splits to go to the right of current window vim.o.swapfile = false -- creates a swapfile vim.o.tabstop = 2 -- insert 2 spaces for a tab vim.o.termguicolors = true -- set term gui colors (most terminals support this) vim.o.title = true -- set the title of window to the value of the titlestring vim.o.undofile = true -- enable persistent undo vim.o.updatetime = 300 -- faster completion vim.o.wrap = false -- display lines as one long line vim.o.writebackup = false -- if a file is being edited by another program (or was written to file while editing with another program) it is not allowed to be edited vim.wo.number = true -- set numbered lines
-- -- function mat4_getInversed(mat) end ---@overload fun(mat,x,y,z,w):vec4_table function mat4_transformVector(mat, vec4) end function mat4_decompose(mat, scale, rotation, translation) return { scale = cc.vec3(), rotation = cc.quaternion(), translation = cc.vec3() } end function mat4_multiply(mat1, mat2) end function mat4_translate(mat, vec3) end function mat4_createRotationZ(mat, angle) end function mat4_setIdentity(mat) end ---@overload fun(x,y,z):mat4_table function mat4_createTranslation(vec3) end ---@overload fun(axis,angle):mat4_table function mat4_createRotation(quat) end function vec3_cross(v1, v2) end
return { id = 4001201, bgm = "story-french2", stages = { { { triggerType = 8, key = true, waveIndex = 900, preWaves = { 201 }, triggerParams = {} }, stageIndex = 1, failCondition = 1, timeCount = 300, passCondition = 1, backGroundStageID = 1, totalArea = { -75, 20, 90, 70 }, playerArea = { -75, 20, 42, 68 }, enemyArea = {}, fleetCorrdinate = { -80, 0, 75 }, waves = { { triggerType = 0, waveIndex = 201, conditionType = 1, preWaves = {}, triggerParams = {}, spawn = { { monsterTemplateID = 10116401, moveCast = true, delay = 0, corrdinate = { 0, 0, 55 }, bossData = { hpBarNum = 100, icon = "dunkeerke" }, phase = { { index = 0, switchType = 1, switchTo = 1, switchParam = 20, addWeapon = { 593501 } }, { index = 1, switchType = 1, switchTo = 2, switchParam = 1, removeWeapon = { 593501 } }, { index = 2, switchType = 1, switchTo = 3, switchParam = 10, addWeapon = { 593502 } }, { switchType = 1, switchTo = 4, index = 3, switchParam = 2, setAI = 70068, removeWeapon = { 593502 } }, { index = 4, switchType = 1, switchTo = 5, switchParam = 15, addWeapon = { 593503 } }, { index = 5, switchType = 1, switchTo = 6, switchParam = 3, removeWeapon = { 593503 } }, { index = 6, switchType = 1, switchTo = 7, switchParam = 10, addWeapon = { 593504, 593507 } }, { index = 7, switchType = 1, switchTo = 8, switchParam = 2, removeWeapon = { 593507 } }, { index = 8, switchType = 1, switchTo = 9, switchParam = 15, addWeapon = { 593507 } }, { index = 9, switchType = 1, switchTo = 10, switchParam = 1, removeWeapon = { 593504, 593507 } }, { switchParam = 5, switchTo = 11, index = 10, switchType = 1, setAI = 70072 }, { switchParam = 8, switchTo = 12, index = 11, switchType = 1, setAI = 70070 }, { switchParam = 5, switchTo = 0, index = 12, switchType = 1, setAI = 70069 } } }, { monsterTemplateID = 10116402, moveCast = true, delay = 0, corrdinate = { -15, 0, 55 }, bossData = { hpBarNum = 100, icon = "rangbaer" }, phase = { { index = 0, switchType = 1, switchTo = 1, switchParam = 30, addWeapon = { 593508 } }, { switchType = 1, switchTo = 2, index = 1, switchParam = 2, setAI = 70069, removeWeapon = { 593508 } }, { index = 2, switchType = 1, switchTo = 3, switchParam = 15, addWeapon = { 593509 } }, { index = 3, switchType = 1, switchTo = 4, switchParam = 3, removeWeapon = { 593509 } }, { switchParam = 30, switchTo = 5, index = 4, switchType = 1, setAI = 70070 }, { switchParam = 3, switchTo = 6, index = 5, switchType = 1, setAI = 70071 }, { index = 6, switchType = 1, switchTo = 7, switchParam = 10, addWeapon = { 593510, 593512 } }, { index = 7, switchType = 1, switchTo = 8, switchParam = 1, removeWeapon = { 593510, 593512 } }, { switchParam = 1, switchTo = 0, index = 8, switchType = 1, setAI = 70071 } } } } } } } }, fleet_prefab = {} }
local scriptPath = getScriptPath() package.path = scriptPath .. '/?.lua;' .. package.path local string = string local zmq = require("lzmq") local zmq_poller = require("lzmq.poller") local zap = require("auth.zap") local config_parser = require("utils.config_parser") local event_data_converter = require("impl.event_data_converter") local procedure_wrappers = require("impl.procedure_wrappers") local utils = require("utils.utils") local json = require("utils.json") local uuid = require("utils.uuid") local service = {} service._VERSION = "v2.0-alpha" service.QUIK_VERSION = "7.16.1.36" service.event_callbacks = {} local zmq_ctx = nil local rpc_sockets = {} local pub_sockets = {} local poller = nil local is_running = false local initialized = false local request_response_serde = { -- initialized on demand json = nil, protobuf = nil } local publishers = { json = nil, protobuf = nil } local protobuf_context = { is_initialized = false } function protobuf_context:init (context_path) require("qlua.qlua_pb_init")(context_path) self.is_initialized = true end local function pub_poll_out_callback () -- TODO: add reading from a message queue -- Polling out is not implemented at the moment: messages are being sent regardless of the POLLOUT event. end local function send_data (data, socket) local ok, err = pcall(function () local msg = zmq.msg_init_data(data) msg:send(socket) msg:close() end) -- if not ok then (log the error somehow, maybe to a file...) end end local function gen_error_obj (code, msg) local err = {code = code} if msg then err.message = msg end return err end local function create_rpc_poll_in_callback (socket, serde_protocol) local sd_proto = string.lower(serde_protocol) local handler if "json" == sd_proto then -- TODO: remove this message message("DEBUG: JSON message protocol detected") if not request_response_serde.json then request_response_serde.json = require("impl.json_request_response_serde"):new() end handler = request_response_serde.json elseif "protobuf" == sd_proto then -- TODO: make explicit check on protobuf -- TODO: remove this message message("DEBUG: PROTOBUF message protocol detected") if not request_response_serde.protobuf then if not protobuf_context.is_initialized then protobuf_context:init(scriptPath) end request_response_serde.protobuf = require("impl.protobuf_request_response_serde"):new() end handler = request_response_serde.protobuf else error( string.format("Неподдерживаемый протокол сериализации/десериализации: %s. Поддерживаемые протоколы: json, protobuf.", serde_protocol) ) end local callback = function () local ok, res = pcall(function() local recv = zmq.msg_init():recv(socket) local result if recv and recv ~= -1 then -- request deserialization local method, args = handler:deserialize_request( recv:data() ) recv:close() local response = { method = method } local proc_wrapper = procedure_wrappers[method] if not proc_wrapper then response.error = gen_error_obj(404, string.format("QLua-функция с именем '%s' не найдена.", method)) else -- procedure call local ok, proc_result = pcall(function() return proc_wrapper(args) end) if ok then response.proc_result = proc_result else response.error = gen_error_obj(1, res) -- the err code 1 is for errors inside the QLua functions' wrappers end end result = response end return result end) local response if ok then if res then response = res end else response = {} response.error = gen_error_obj(500, string.format("Ошибка при обработке входящего запроса: '%s'.", res)) end if response then -- response serialization local serialized_response = handler:serialize_response(response) -- response sending send_data(serialized_response, socket) end end return callback end local function publish (event_type, event_data) if not is_running then return end local converted_event_data = event_data_converter.convert(event_type, event_data) for _, publisher in pairs(publishers) do publisher:publish(event_type, converted_event_data) end end -- TODO: make the publishing depending on the serde protocol being used local function create_event_callbacks() return { OnClose = function () publish("OnClose") service.terminate() end, OnStop = function (signal) publish("OnStop", {signal = signal}) service.terminate() end, OnFirm = function (firm) publish("OnFirm", firm) end, OnAllTrade = function (alltrade) publish("OnAllTrade", alltrade) end, OnTrade = function (trade) publish("OnTrade", trade) end, OnOrder = function (order) publish("OnOrder", order) end, OnAccountBalance = function (acc_bal) publish("OnAccountBalance", acc_bal) end, OnFuturesLimitChange = function (fut_limit) publish("OnFuturesLimitChange", fut_limit) end, OnFuturesLimitDelete = function (lim_del) publish("OnFuturesLimitDelete", lim_del) end, OnFuturesClientHolding = function (fut_pos) publish("OnFuturesClientHolding", fut_pos) end, OnMoneyLimit = function (mlimit) publish("OnMoneyLimit", mlimit) end, OnMoneyLimitDelete = function (mlimit_del) publish("OnMoneyLimitDelete", mlimit_del) end, OnDepoLimit = function (dlimit) publish("OnDepoLimit", dlimit) end, OnDepoLimitDelete = function (dlimit_del) publish("OnDepoLimitDelete", dlimit_del) end, OnAccountPosition = function (acc_pos) publish("OnAccountPosition", acc_pos) end, OnNegDeal = function (neg_deal) publish("OnNegDeal", neg_deal) end, OnNegTrade = function (neg_trade) publish("OnNegTrade", neg_trade) end, OnStopOrder = function (stop_order) publish("OnStopOrder", stop_order) end, OnTransReply = function (trans_reply) publish("OnTransReply", trans_reply) end, OnParam = function (class_code, sec_code) publish("OnParam", {class_code = class_code, sec_code = sec_code}) end, OnQuote = function (class_code, sec_code) publish("OnQuote", {class_code = class_code, sec_code = sec_code}) end, OnDisconnected = function () publish("OnDisconnected") end, OnConnected = function (flag) publish("OnConnected", {flag = flag}) end, OnCleanUp = function () publish("OnCleanUp") end, OnDataSourceUpdate = function (update_info) publish("OnDataSourceUpdate", update_info) end } end local function create_socket (endpoint) local socket local sockets if endpoint.type == "RPC" then socket = zmq_ctx:socket(zmq.REP) poller:add(socket, zmq.POLLIN, create_rpc_poll_in_callback(socket, endpoint.serde_protocol)) sockets = rpc_sockets elseif endpoint.type == "PUB" then socket = zmq_ctx:socket(zmq.PUB) poller:add(socket, zmq.POLLIN, pub_poll_out_callback) sockets = pub_sockets else error( string.format("Указан неподдерживаемый тип '%s' для точки подключения. Поддерживаемые типы: RPC и PUB.", endpoint.type) ) end if zap.has_auth(endpoint) then if not zap.is_initialized() then zap.init(zmq_ctx, poller) end zap.setup_auth(socket, endpoint) end socket:bind( string.format("tcp://%s:%d", endpoint.address.host, endpoint.address.port) ) if endpoint.type == "PUB" then local serde_protocol = string.lower(endpoint.serde_protocol) local publisher if "protobuf" == serde_protocol then if not publishers.protobuf then publishers.protobuf = require("impl.protobuf_event_publisher"):new() end publisher = publishers.protobuf elseif "json" == serde_protocol then if not publishers.json then publishers.json = require("impl.json_event_publisher"):new() end publisher = publishers.json end publisher:add_pub_socket(socket) -- Как координировать PUB и SUB правильно (сложно): http://zguide.zeromq.org/lua:all#Node-Coordination -- Как не совсем правильно (просто): использовать sleep utils.sleep(0.25) -- in seconds local next = next if not next(service.event_callbacks) then service.event_callbacks = create_event_callbacks() end end table.sinsert(sockets, socket) return socket end local function reg_endpoint (endpoint) create_socket(endpoint) end local function check_if_initialized () if not initialized then error("The service is not initialized.") end end function service.init () if initialized then return end local config = config_parser.parse(scriptPath.."/config.json") zmq_ctx = zmq.context() poller = zmq_poller.new() for i, endpoint in ipairs(config.endpoints) do if endpoint.active then endpoint.id = i reg_endpoint(endpoint) end end uuid.seed() initialized = true end function service.start () check_if_initialized() if is_running then return else is_running = true end -- Does nothing useful at the moment, because the polling has not yet been started at the time it executes. -- Issue #13. publish("PublisherOnline") xpcall( function() return poller:start() end, function() message("Ошибка в poller:start. Стек вызовов:\n"..debug.traceback()) end ) end function service.stop () check_if_initialized() if is_running then poller:stop() is_running = false end end function service.terminate () check_if_initialized() if is_running then service.stop() end poller = nil -- Set non-negative linger to prevent termination hanging in case if there's a message pending for a disconnected subscriber for _i, socket in ipairs(rpc_sockets) do socket:close(0) end rpc_sockets = {} for _i, socket in ipairs(pub_sockets) do socket:close(0) end pub_sockets = {} zap.destroy() zmq_ctx:term(1) zmq_ctx = nil initialized = false end return service
local L = require "lpeg" local Node = require "espalier/node" local u = {} function u.inherit(meta) local MT = meta or {} local M = setmetatable({}, MT) M.__index = M local m = setmetatable({}, M) m.__index = m return M, m end function u.export(mod, constructor) mod.__call = constructor return setmetatable({}, mod) end local m = require "orb:Orbit/morphemes" local H, h = u.inherit(Node) function h.matchHandle(line) local handlen = L.match(L.C(m.handle), line) if handlen then return handlen else return "" --u.freeze("h.matchHandle fails to match a handle") end end local function new(Handle, line) local handle = setmetatable({}, H) handle.id = "handle" handle.val = h.matchHandle(line):sub(2, -1) return handle end return u.export(h, new)
-- taken from https://github.com/harvardnlp/seq2seq-attn/blob/master/s2sa/memory.lua -- module for memory management -- reuseMem is used for reusing output tensor for storing gradInput and optimizing memory allocation -- use :reuseMem() on the module to allow the feature -- then apply setReuse after initialization -- only applies if output and gradinput are of the same type require 'utils' if logging ~= nil then log = function(msg) logging:info(msg) end else log = print end function nn.Module:reuseMem(name) self.reuse = true return self end function nn.Module:setReuse() if self.reuse then assert(type(self.output) == type(self.gradInput), "invalid use of reuseMem:") self.gradInput = self.output end return self end -- usePrealloc is based on the same principle but use pre-allocated memory at the beginning of the process that can be shared -- between different objects -- use to prellocate gradInput, or output - useful for intermediate calculations working on large input preallocTable = nil function preallocateMemory(switch) if switch then preallocTable = {} log('Switching on memory preallocation') end end function preallocateTensor(name,D) if #D > 1 then local T={} for i=1,#D do table.insert(T,preallocateTensor(name,{D[i]})) end return T else D = D[1] end local t=localize(torch.zeros(torch.LongStorage(D))) return t end -- enable reuseMemory - if preallocation disable, then switched back to reuseMem checking for 'reuse' in name function nn.Module:usePrealloc(preallocName, inputDim, outputDim) if preallocTable == nil then if string.find(preallocName, "reuse") then self:reuseMem() end return self end self.prealloc = preallocName self.name = preallocName self.preallocInputDim = inputDim self.preallocOutputDim = outputDim return self end function nn.Module:setPrealloc() if self.prealloc and (self.preallocInputDim ~= nil or self.preallocOutputDim ~= nil) then if preallocTable[self.prealloc] == nil then preallocTable[self.prealloc] = { } if self.preallocInputDim ~= nil then preallocTable[self.prealloc].GI = preallocateTensor(self.prealloc, self.preallocInputDim) end if self.preallocOutputDim ~= nil then preallocTable[self.prealloc].O = preallocateTensor(self.prealloc, self.preallocOutputDim) end end local memmap = preallocTable[self.prealloc] if memmap["GI"] ~= nil then assert(type(self.gradInput) == type(memmap.GI), "invalid use of usePrealloc ["..self.prealloc.."]/GI: "..type(self.gradInput).."/"..type(memmap.GI)) self.gradInput = memmap["GI"] end if memmap["O"] ~= nil then assert(type(self.output) == type(memmap.O), "invalid use of usePrealloc ["..self.prealloc.."]/O:"..type(self.output).."/"..type(memmap.O)) self.output = memmap["O"] end end return self end
--monsterframes.lua local hooks = {} local settings = { showRaceType = false, showAttribute = false, showArmorMaterial = true, showMoveType = true, showEffectiveAtkType = false, showTargetSize = true, showMaxHp = true, showHpPercent = true, showKillCount = true} local posTable = { normal = {x = 303, y = 17, killx = 180, killy = 0, width = 35}, elite = {x = 200, y = 13, killx = 55, killy = 0, width = 35}, special = {x = 260, y = 17, killx = 180, killy = 0, width = 35}, boss = {x = 100, y = 25, killx = 35, killy = 5, width = 35}} function MONSTERFRAMES_ON_INIT(addon, frame) if next(hooks) == nil then local function setupHook(newFunc, oldFuncStr) hooks[oldFuncStr] = _G[oldFuncStr] _G[oldFuncStr] = newFunc end setupHook(TGTINFO_TARGET_SET_HOOKED, "TGTINFO_TARGET_SET") setupHook(TARGETINFOTOBOSS_TARGET_SET_HOOKED, "TARGETINFOTOBOSS_TARGET_SET") setupHook(TARGETINFO_TRANS_HP_VALUE_HOOKED, "TARGETINFO_TRANS_HP_VALUE") local acutil = require('acutil') local t, err = acutil.loadJSON("../addons/monsterframes/settings.json") if err then acutil.saveJSON("../addons/monsterframes/settings.json", settings) else settings = t end end end local function SHOW_PROPERTY_PIC(frame, monCls, targetInfoProperty, monsterPropertyIcon, x, y, spacingX, spacingY) local propertyType = frame:CreateOrGetControl("picture", monsterPropertyIcon .. "_icon", x + spacingX, y - spacingY, 100, 40) tolua.cast(propertyType, "ui::CPicture") if targetInfoProperty ~= nil then propertyType:SetImage(GET_MON_PROPICON_BY_PROPNAME(monsterPropertyIcon, monCls)) propertyType:ShowWindow(1) return 1 else propertyType:ShowWindow(0) return 0 end end local function SHOW_PROPERTY_TEXT(frame, propertyName, text, x, y, check) local propertyType = frame:CreateOrGetControl("richtext", propertyName .. "Text", x, y, 100, 40) tolua.cast(propertyType, "ui::CRichText") if check then propertyType:SetText(text) propertyType:ShowWindow(1) return 1 else propertyType:ShowWindow(0) return 0 end end local function SHOW_CUSTOM_ICONS(frame, targetHandle, targetinfo) local montype = world.GetActor(targetHandle):GetType() local monCls = GetClassByType("Monster", montype) if monCls == nil then return end local pos = posTable.normal if targetinfo.isBoss == 1 then pos = posTable.boss elseif targetinfo.isElite == 1 then pos = posTable.elite elseif info.GetMonRankbyHandle(targetHandle) == 'Special' then pos = posTable.special end local positionIndex = 0 if settings.showRaceType then positionIndex = positionIndex + SHOW_PROPERTY_PIC(frame, monCls, targetinfo.raceType, "RaceType", pos.x + (positionIndex * pos.width), pos.y, 10, 10) end if settings.showAttribute then positionIndex = positionIndex + SHOW_PROPERTY_PIC(frame, monCls, targetinfo.attribute, "Attribute", pos.x + (positionIndex * pos.width), pos.y, 10, 10) end if settings.showArmorMaterial then positionIndex = positionIndex + SHOW_PROPERTY_PIC(frame, monCls, targetinfo.armorType, "ArmorMaterial", pos.x + (positionIndex * pos.width), pos.y, 10, 10) end if settings.showMoveType then positionIndex = positionIndex + SHOW_PROPERTY_PIC(frame, monCls, monCls["MoveType"], "MoveType", pos.x + (positionIndex * pos.width), pos.y, 10, 10) end if settings.showEffectiveAtkType then positionIndex = positionIndex + SHOW_PROPERTY_PIC(frame, monCls, 1, "EffectiveAtkType", pos.x + (positionIndex * pos.width), pos.y, 10, 10) end if settings.showTargetSize then positionIndex = positionIndex + SHOW_PROPERTY_TEXT(frame, "TargetSize", "{@st41}{s28}" .. targetinfo.size, pos.x + (positionIndex * pos.width) + 10, pos.y - 8, targetinfo.size ~= nil) end if settings.showKillCount then local curLv, curPoint, curMaxPoint = GET_ADVENTURE_BOOK_MONSTER_KILL_COUNT_INFO(monCls.MonRank == 'Boss', GetMonKillCount(pc, montype)) SHOW_PROPERTY_TEXT(frame, "KillCount", string.format("{@st42}{s16}%d: %d/%d", curLv, curPoint, curMaxPoint), pos.killx, pos.killy, curMaxPoint ~= 0) end frame:Invalidate() end function TGTINFO_TARGET_SET_HOOKED(frame, msg, argStr, argNum, ...) if argStr == "None" then return; end if IS_IN_EVENT_MAP() == true then return; end local targetHandle = session.GetTargetHandle(); local targetinfo = info.GetTargetInfo( targetHandle ); if nil == targetinfo then return; end if targetinfo.TargetWindow == 0 then return; end if targetinfo.isBoss == 1 then return; end local ret = {hooks.TGTINFO_TARGET_SET(frame, msg, argStr, argNum, ...)} SHOW_CUSTOM_ICONS(frame, targetHandle, targetinfo) return unpack(ret) end function TARGETINFOTOBOSS_TARGET_SET_HOOKED(frame, msg, argStr, argNum, ...) if argStr == "None" or argNum == nil then return; end local targetinfo = info.GetTargetInfo(argNum); if targetinfo == nil then session.ResetTargetBossHandle(); frame:ShowWindow(0); return; end if 0 == targetinfo.TargetWindow or targetinfo.isBoss == 0 then session.ResetTargetBossHandle(); frame:ShowWindow(0); return; end local ret = {hooks.TARGETINFOTOBOSS_TARGET_SET(frame, msg, argStr, argNum, ...)} SHOW_CUSTOM_ICONS(frame, argNum, targetinfo) return unpack(ret) end function TARGETINFO_TRANS_HP_VALUE_HOOKED(handle, hp, fontStyle, ...) local ret = hooks.TARGETINFO_TRANS_HP_VALUE(handle, hp, fontStyle, ...) if info.IsPercentageHP(handle) ~= true then local stat = info.GetTargetInfo(handle).stat if settings.showMaxHp then ret = ret .. "/" .. tostring(math.floor(stat.maxHP)):reverse():gsub("(%d%d%d)","%1,"):gsub(",(%-?)$","%1"):reverse() end if settings.showHpPercent then ret = ret .. "(" .. (math.floor(stat.HP/stat.maxHP*100)) .. "%)" end end return ret end
print(0.0/1.0) print(-0.0/1.0) print(0.0/0.0)
return PlaceObj("ModDef", { "title", "Fix Buildings Broken And No Repair", "version", 3, "version_major", 0, "version_minor", 3, "image", "Preview.png", "id", "ChoGGi_FixBuildingsBrokenDownAndNoRepair", "steam_id", "1599190080", "pops_any_uuid", "56012643-cfef-4dd2-b358-a80d651b542f", "author", "ChoGGi", "lua_revision", 1001569, "code", { "Code/Script.lua", }, "has_options", true, "TagOther", true, "description", [[If you have broken down buildings the drones won't repair. This will check for them on load game. The affected buildings will say something about exceptional circumstances. Any buildings affected by this issue will need to be repaired with 000.1 resource after the fix happens. This also has a fix for buildings hit with lightning during a cold wave. Includes mod option to disable fix. A proper fix made by SkiRich (solves the underlying issue): https://steamcommunity.com/sharedfiles/filedetails/?id=2433157820 ]], })
--TRIGGERS THE CLOAKING CLIENT FUNCTIONS addEvent ("cloaktheplayer", true ) function cloakstart(thisplayer) setElementData ( thisplayer, "stealthmode", "on" ) playSoundFrontEnd ( thisplayer, 34 ) setElementAlpha ( thisplayer, 10 ) end addEventHandler("cloaktheplayer",getRootElement(),cloakstart) --TRIGGERS THE UNCLOAKING CLIENT FUNCTIONS addEvent ("uncloaktheplayer", true ) function cloakstop(thisplayer) if (cloakoff) then killTimer (cloakoff) cloakoff= nil end setElementData ( thisplayer, "stealthmode", "off" ) playSoundFrontEnd ( thisplayer, 35 ) setElementAlpha ( thisplayer, 255 ) end addEventHandler("uncloaktheplayer",getRootElement(),cloakstop) --GOGGLES addEvent ("goggleswap", true ) function changegoggles(player) local currentgoggles = getPedWeapon ( player, 11 ) if currentgoggles == 44 then giveWeapon ( player, 45, 1 ) outputChatBox("Infrared.",player, 255, 69, 0) elseif currentgoggles == 45 then giveWeapon ( player, 44, 1 ) outputChatBox("Nightvision.",player, 255, 69, 0) end end addEventHandler("goggleswap",getRootElement(),changegoggles) --PROXY MINES --LAYS THE MINE AND SETS THE COL addEvent ("poopoutthemine", true ) function laymine(player) local posx, posy, posz = getElementPosition ( player ) local landmine = createObject ( 1510, posx, posy, posz - .999, 0, 0, 3.18 ) local landminecol = createColSphere ( posx, posy, posz, 3 ) setElementData ( landminecol, "type", "alandmine" ) setElementData ( landminecol, "owner", player ) setElementData ( landmine, "type", "proximity" ) setElementParent ( landmine, landminecol ) end addEventHandler("poopoutthemine",getRootElement(),laymine) --DETECTS THE HIT function landminehit ( player, matchingDimension ) if ( getElementData ( source, "type" ) == "alandmine" ) then if ( getElementData ( player, "stealthmode" ) ~= "on" ) then local mineowner = getElementData ( source, "owner" ) local ownersteam = getPlayerTeam ( mineowner ) local victimteam = getPlayerTeam ( player ) if ownersteam ~= victimteam then --IS THIS PLAYER ON THE SAME TEAM AS THE GUY WHO PUT IT THERE? local posx, posy, posz = getElementPosition ( source ) createExplosion (posx, posy, posz, 8, mineowner ) setElementData ( source, "type", nil ) destroyElement ( source ) end end end end addEventHandler ( "onColShapeHit", getRootElement(), landminehit ) --KILLS THE MINE WHEN SHOT addEvent ("destroylandmine", true ) function destroymine(hitElement) if (hitElement) then local damagedmine = getElementParent ( hitElement ) destroyElement ( damagedmine ) end end addEventHandler("destroylandmine",getRootElement(),destroymine) --SPYCAMERA addEvent ("placethecam", true ) function dropcamera(player) local playerrot = getPedRotation ( player ) local rot = playerrot-180 triggerClientEvent(player,"findcamerapos",getRootElement(),rot ) end addEventHandler("placethecam",getRootElement(),dropcamera) addEvent ("cameraobject", true ) function placecamball(x, y, z, player) local camball = createObject ( 3106, x, y, z ) local camcol = createColSphere ( x, y, z, 1 ) setElementData ( camcol, "camowner", player ) setElementData ( camcol, "type", "acamera" ) setElementParent ( camball, camcol ) end addEventHandler("cameraobject",getRootElement(),placecamball) addEvent ("killcameraobject", true ) function removecamball(player) coltable = getElementsByType ( "colshape" ) for theKey,thecol in ipairs(coltable) do if getElementData ( thecol, "camowner" ) == player then setElementData ( thecol, "type", nil ) destroyElement ( thecol ) end end end addEventHandler("killcameraobject",getRootElement(),removecamball) --SHIELD addEvent ("shieldup", true ) function maketheshield (player) local x, y, z = getElementPosition( player ) shield = createObject ( 1631, x, y, z, 0, 0, 0 ) setElementData ( shield, "type", "ashield" ) if isPedDucked ( player ) then attachElements( shield, player, .2, .5, -.6, 0, 90, 0 ) else giveWeapon ( player, 0, 0, true ) attachElements( shield, player, .2, .5, .2 ) end end addEventHandler("shieldup", getRootElement() , maketheshield) addEvent ("shielddown", true ) function killtheshield (player, currentweapon ) stuckstuff = getAttachedElements ( player ) for ElementKey, ElementValue in ipairs(stuckstuff) do if ( getElementData ( ElementValue, "type" ) == "ashield" ) then theshield = ElementValue end end destroyElement ( theshield ) giveWeapon ( player, currentweapon, 0, true ) end addEventHandler("shielddown", getRootElement() , killtheshield)
-------------------------------------- ---- Made by Roids#9757 for TWPRP ---- -------------------------------------- ------- VORP Stuff don't touch ------- -------------------------------------- local VorpCore = {} TriggerEvent("getCore",function(core) VorpCore = core end) VORP = exports.vorp_core:vorpAPI() -------------------------------------- -- Don't touch this shit either lol -- -------------------------------------- RegisterServerEvent("twprp:fine") AddEventHandler("twprp:fine", function(criminal, fine) local _source = source local _criminal = criminal local _fine = fine local Character = VorpCore.getUser(_source).getUsedCharacter local Receiver = VorpCore.getUser(_criminal).getUsedCharacter local job = Character.job if job == 'police' then TriggerClientEvent("vorp:TipBottom", _criminal, 'You have been Fined $'.._fine, 5000) TriggerClientEvent("vorp:TipBottom", _source , Receiver.firstname..' '..Receiver.lastname..' has been Fined $'.._fine, 5000) Receiver.removeCurrency(0, _fine) Citizen.Wait(2000) end if job ~= 'police' then TriggerClientEvent("vorp:TipBottom", _source, "Only lawmen can do that. You are not a lawman!", 5000) end end) -------------------------------------- ----- Now was that so hard? LOL ------ --------------------------------------
return { name = "rphillips/options", version = "0.0.4", description = "easy to use getopt library", author = "pancake <pancake@nopcode.org>", dependencies = { }, files = { "*.lua", "!test*", } }
require("config") require("cocos.init") require("framework.init") -- require("framework.utilitys") local MyApp = class("MyApp", cc.mvc.AppBase) function MyApp:ctor() MyApp.super.ctor(self) self.scenes_ = { "MenuScene", "CCSSample1Scene", "CCSSample2Scene", "CCSSample3Scene", "CCSSample4Scene", "CCSSample5Scene", "CCSSample6Scene", "CCSReader1Scene", "CCSReader2Scene", "CCSReader3Scene", "CCSReader4Scene", "CCSReader5Scene", "CCSReader6Scene" } end function MyApp:run() cc.FileUtils:getInstance():addSearchPath("res/") self:enterNextScene() end function MyApp:enterScene(sceneName, ...) self.currentSceneName_ = sceneName MyApp.super.enterScene(self, sceneName, ...) end function MyApp:enterNextScene(bReader) if not bReader then if "CCSSample6Scene" == self.currentSceneName_ then self.currentSceneName_ = "CCSReader6Scene" end end local index = 1 while index <= #self.scenes_ do if self.scenes_[index] == self.currentSceneName_ then break end index = index + 1 end index = index + 1 if index > #self.scenes_ then index = 1 end self:enterScene(self.scenes_[index]) end function MyApp:createTitle(scene, title) cc.ui.UILabel.new({text = "-- " .. title .. " --", size = 24, color = display.COLOR_WHITE}) :align(display.CENTER, display.cx, display.top - 20) :addTo(scene, 10) end function MyApp:createNextButton(scene) cc.ui.UIPushButton.new("NextButton.png") :onButtonPressed(function(event) event.target:setScale(1.2) end) :onButtonRelease(function(event) event.target:setScale(1.0) end) :onButtonClicked(function(event) self:enterNextScene() end) :align(display.RIGHT_BOTTOM, display.right - 20, display.bottom + 20) :addTo(scene, 10) end function MyApp:loadCCSJsonFile(scene, jsonFile) local node, width, height = cc.uiloader:load(jsonFile) width = width or display.width height = height or display.height if node then node:setPosition((display.width - width)/2, (display.height - height)/2) node:setTag(101) scene:addChild(node) -- clone test code -- local cloneNode = node:clone() -- cloneNode:setPosition((display.width - width)/2, (display.height - height)/2) -- cloneNode:setTag(101) -- scene:addChild(cloneNode) -- node:removeSelf() end end return MyApp
require 'nn' require 'nngraph' local san = {} function san.n_attention_layer(opt) local inputs, outputs = {}, {} table.insert(inputs, nn.Identity()()) table.insert(inputs, nn.Identity()()) local img_feat = inputs[1] local ques_feat = inputs[2] local u = ques_feat local img_tr = nn.Dropout(0.5)(nn.Tanh()(nn.View(-1, 196, opt.im_tr_size)(nn.Linear(512, opt.im_tr_size)(nn.View(512):setNumInputDims(2)(img_feat))))) for i = 1, opt.num_attention_layers do -- linear layer: 14x14x1024 -> 14x14x512 local img_common = nn.View(-1, 196, opt.common_embedding_size)(nn.Linear(opt.im_tr_size, opt.common_embedding_size)(nn.View(-1, opt.im_tr_size)(img_tr))) -- replicate lstm state 196 times local ques_common = nn.Linear(opt.rnn_size, opt.common_embedding_size)(u) local ques_repl = nn.Replicate(196, 2)(ques_common) -- add image and question features (both 196x512) local img_ques_common = nn.Dropout(0.5)(nn.Tanh()(nn.CAddTable()({img_common, ques_repl}))) local h = nn.Linear(opt.common_embedding_size, 1)(nn.View(-1, opt.common_embedding_size)(img_ques_common)) local p = nn.SoftMax()(nn.View(-1, 196)(h)) -- weighted sum of image features local p_att = nn.View(1, -1):setNumInputDims(1)(p) local img_tr_att = nn.MM(false, false)({p_att, img_tr}) local img_tr_att_feat = nn.View(-1, opt.im_tr_size)(img_tr_att) -- add image feature vector and question vector u = nn.CAddTable()({img_tr_att_feat, u}) end -- MLP to answers local o = nn.LogSoftMax()(nn.Linear(opt.rnn_size, opt.num_output)(nn.Dropout(0.5)(u))) table.insert(outputs, o) return nn.gModule(inputs, outputs) end return san