content
stringlengths
5
1.05M
actualtree={ branchname="Zinsrechner", --tree['title0'] { branchname="1. Allgemeiner Rechner", --tree['title1'] state="COLLAPSED", "Geben Sie eine Rechenaufgabe ein, z.B. 5+7:", --tree['title2'] "10000*0.03", --tree['title3'] { branchname="Berechnen", --tree['title4'] "", --tree['title5'] }, }, { branchname="2. Schaltjahrberechnung", --tree['title6'] state="COLLAPSED", "Geben Sie ein Jahr zwischen 1900 und 2999 ein:", --tree['title7'] "2021", --tree['title8'] { branchname="Ausgabe", --tree['title9'] "", --tree['title10'] }, }, { branchname="3. Zinsberechnung", --tree['title11'] { branchname="Geben Sie Kapital und Zinssatz ein:", --tree['title12'] state="COLLAPSED", "10000", --tree['title13'] "0.3", --tree['title14'] }, { branchname="Startdatum:", --tree['title15'] state="COLLAPSED", "01.02.2012", --tree['title16'] { branchname="Startdatum ist Last of day February", --tree['title17'] "nein", --tree['title18'] }, }, { branchname="Endedatum:", --tree['title19'] state="COLLAPSED", "31.05.2013", --tree['title20'] { branchname="Endedatum ist Last day of February", --tree['title21'] "nein", --tree['title22'] }, }, { branchname="Schalttage im Zins-Intervall bestimmen", --tree['title23'] "", --tree['title24'] }, { branchname="Anzahl Tage im Zähler bestimmen und soweit schon möglich im Nenner, sonst weitere Knoten verwenden", --tree['title25'] { branchname="Tageskonventionen für 360 Tage mit der Formel", --tree['title26'] state="COLLAPSED", { branchname="Tage = 360 * ( Y2 - Y1 ) + 30 * ( M2 - M1 ) + (D2 - D1)", --tree['title27'] { branchname="30/360 Bond Basis, 30A/360:", --tree['title28'] state="COLLAPSED", "This convention is exactly as 30U/360 below, except for the first two rules. Note that the order of calculations is important:", --tree['title29'] "D1 = MIN (D1, 30).If D1 = 30 Then D2 = MIN (D2,30)", --tree['title30'] "Sources: ISDA 2006 Section 4.16(f), though the first two rules are not included. \'ISDA Definitions, Section 4.16\'. 2006. Retrieved2014-09-18.", --tree['title31'] }, { branchname="Anzahl Tage Zähler 30 und Nenner 360", --tree['title32'] "", --tree['title33'] }, { branchname="30/360 ISDA:", --tree['title34'] state="COLLAPSED", "Regel 1: If D1 is 31, then change D1 to 30.", --tree['title35'] "Regel 2 If D1 = 30 after applying Regel 1 and D2 =31 then change D2 to 30.", --tree['title36'] "Sources: alternate names of day conventions.", --tree['title37'] }, { branchname="Anzahl Tage Zähler 30ISDA und Nenner 360", --tree['title38'] "", --tree['title39'] }, { branchname="30E/360, 30/360 ICMA, 30S/360, Eurobond basis (ISDA 2006), Special German (spezielle deutsche Zinsmethode):", --tree['title40'] state="COLLAPSED", "Regel 1: If D1 is 31, then change D1 to 30.", --tree['title41'] "Regel 2 If D2 is 31, then change D2 to 30.", --tree['title42'] "Sources: \'ICMA Rule Book, Rule 251\'. Retrieved 2014-09-18. ICMA Rule 251.1(ii), 251.2. \'ISDA Definitions, Section 4.16\'. 2006. Retrieved 2014-09-18. ISDA 2006 Section 4.16(g).", --tree['title43'] }, { branchname="Anzahl Tage Zähler 30E und Nenner 360", --tree['title44'] "", --tree['title45'] }, { branchname="30E+/360:", --tree['title46'] state="COLLAPSED", "Regel 1: If D1 is 31, then change D1 to 30.", --tree['title47'] "Regel 2 If D2 is 31, set D2.M2.Y2 to 1st day of the next month.", --tree['title48'] "Sources: alternate names of day conventions.", --tree['title49'] }, { branchname="Zum Endedatum 1. des Folgemonats für Regel 30E+:", --tree['title50'] "2013", --tree['title51'] "6", --tree['title52'] "1", --tree['title53'] }, { branchname="Anzahl Tage Zähler 30E+ und Nenner 360", --tree['title54'] "", --tree['title55'] }, { branchname="30/360 German (spezielle deutsche Zinsmethode siehe oben):", --tree['title56'] state="COLLAPSED", "Regel 1: If D1 and/or D2 is 31, then change D1 to 30 and/or D2 to 30.", --tree['title57'] "Regel 2 If D1.M1.Y1 and/or D2.M2.Y2 = last day of february =1.3.-1 Tag then change D1 to 30 and/or D2 to 30.", --tree['title58'] "Sources: alternate names of day conventions.", --tree['title59'] }, { branchname="Anzahl Tage Zähler 30German und Nenner 360", --tree['title60'] "", --tree['title61'] }, { branchname="30/360 US:", --tree['title62'] state="COLLAPSED", "Regel 1: If D2.M2.Y2 ist the last day of February (28 ohne Schaltjahr und 29 im Schaltjahr) and D1.M1.Y1 ist the last day of February then D2 = 30", --tree['title63'] "Regel 2: If D1.M1.Y1 ist the last day of February (28 ohne Schaltjahr und 29 im Schaltjahr) then D1 = 30", --tree['title64'] "Regel 3: If D2 is 31 and D1=30 or D1=31, then change D2 to 30.", --tree['title65'] "Regel 4: If D1 is 31, then change D1 to 30.", --tree['title66'] "Sources: alternate names of day conventions.", --tree['title67'] }, { branchname="Anzahl Tage Zähler 30US und Nenner 360", --tree['title68'] "", --tree['title69'] }, }, }, { branchname="Tageskonventionen actual mit der exakten Anzahl Tage im Zähler und Nenner für actual im Weiteren Knoten bestimmen", --tree['title70'] state="COLLAPSED", { branchname="Anzahl Tage Zähler actual und Nenner für actual im Weiteren Knoten bestimmen", --tree['title71'] "", --tree['title72'] { branchname="Für die no leap year abgezogene Tage im Zähler bei der Methode NL/365", --tree['title73'] "0", --tree['title74'] }, }, }, { branchname="Für die Rechnung benutzte Tage im Zähler", --tree['title75'] "", --tree['title76'] { branchname="Nenner für Tageskonventionen actual mit der exakten Anzahl Tage bestimmen", --tree['title77'] state="COLLAPSED", { branchname="actual 365.25 1/1:", --tree['title78'] state="COLLAPSED", "This is used for inflation instruments and divides the overall 4 year period distributing the additional day across all 4 years i.e. giving 365.25 days to each year.", --tree['title79'] "Sources: \'ISDA Definitions, Section 4.16\'. 2006. Retrieved2014-09-18. ISDA 2006 Section 4.16(a). \'FBF Master Agreement for Financial Transactions, Supplement to the Derivatives Annex, Edition 2004\'. 2004. Retrieved 2014-09-18. FBF Master Agreement for Financi", --tree['title80'] }, { branchname="Nenner actual 365.25 1/1", --tree['title81'] "", --tree['title82'] }, { branchname="actual 366:", --tree['title83'] state="COLLAPSED", "Für Schaltjahre oder Act/365A für gesamte Periode, falls Schalttag vorhanden oder Act/365L falls Endedatum im Schaltjahr", --tree['title84'] }, { branchname="Nenner actual 366", --tree['title85'] "", --tree['title86'] }, { branchname="actual 365, Act/365, FixedAct/365, FixedAct/365FEnglish:", --tree['title87'] state="COLLAPSED", "Each month is treated normally and the year is assumed to be 365 days. For example, in a period from February 1, 2005 to April 1, 2005, the Factor is considered to be 59 days divided by 365.", --tree['title88'] "The CouponFactor uses the same formula, replacing Date2 by Date3. In general, coupon payments will vary from period to period, due to the differing number of days in the periods. The formula applies to both regular and irregular coupon periods.", --tree['title89'] "Sources: \'ISDA Definitions, Section 4.16\'. 2006. Retrieved2014-09-18. ISDA 2006 Section 4.16(d).", --tree['title90'] }, { branchname="Nenner actual 365", --tree['title91'] "", --tree['title92'] }, { branchname="actual 364:", --tree['title93'] state="COLLAPSED", "Each month is treated normally and the year is assumed to be 364 days. For example, in a period from February 1, 2005 to April 1, 2005, the Factor is considered to be 59 days divided by 364.", --tree['title94'] "The CouponFactor uses the same formula, replacing Date2 by Date3. In general, coupon payments will vary from period to period, due to the differing number of days in the periods. The formula applies to both regular and irregular coupon periods.", --tree['title95'] }, { branchname="Nenner actual 364", --tree['title96'] "", --tree['title97'] }, { branchname="Actual 360, Act/360, A/360, French (französische Methode):", --tree['title98'] state="COLLAPSED", "This convention is used in money markets for short-term lending of currencies, including the US dollar and Euro, and is applied in ESCBmonetary policy operations. It is the convention used withRepurchase agreements. Each month is treated normally and the year", --tree['title99'] "The CouponFactor uses the same formula, replacing Date2 by Date3. In general, coupon payments will vary from period to period, due to the differing number of days in the periods. The formula applies to both regular and irregular coupon periods.", --tree['title100'] "Sources: \'ICMA Rule Book, Rule 251\'. Retrieved 2014-09-18. ICMA Rule 251.1(i) (not sterling). \'ISDA Definitions, Section 4.16\'. 2006. Retrieved2014-09-18. ISDA 2006 Section 4.16(e). (Mayle 1993)", --tree['title101'] }, { branchname="Nenner actual 360", --tree['title102'] "", --tree['title103'] }, }, { branchname="Für die Rechnung benutzte Tage im Nenner", --tree['title104'] "", --tree['title105'] }, { branchname="Geben Sie die Anzahl Jahre mit Nachkommastellen manuell ein:", --tree['title106'] state="COLLAPSED", "1", --tree['title107'] { branchname="Jahre manuell setzen", --tree['title108'] state="COLLAPSED", }, }, { branchname="Für die Rechnung benutzte Jahre mit Nachkommastellen", --tree['title109'] "", --tree['title110'] }, { branchname="Für die Rechnung benutzte Zinsberechnungsmethode:", --tree['title111'] "", --tree['title112'] }, { branchname="Zinsberechnung", --tree['title113'] { branchname="Kapital und Zinssatz eintragen", --tree['title114'] { branchname="Alle Zinsen mit Titel ausgeben", --tree['title115'] { branchname="Titel", --tree['title116'] "", --tree['title117'] }, { branchname="Zinsen linear = Kapital * Zinssatz * Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner", --tree['title118'] "", --tree['title119'] }, { branchname="Zinsen mit Zinseszinsen = Kapital * ((1+Zinssatz)^(Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner)-1)", --tree['title120'] "", --tree['title121'] }, { branchname="Zinsen stetig verzinst = Kapital * (e^(Zinssatz * Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner) -1)", --tree['title122'] "", --tree['title123'] }, { branchname="Alle Zinsen mit Titel in eine Datei ausgeben", --tree['title124'] "C:\\Tree\\LuatoLua\\reflexive_Tree_calculator_with_interests.txt", --tree['title125'] }, }, }, { branchname="Zurücksetzen", --tree['title126'] state="COLLAPSED", }}}}}, {branchname="Quellen", --tree['title127'] state="COLLAPSED", "https://en.m.wikipedia.org/wiki/Day_count_convention", --tree['title128'] "https://m.zinsen-berechnen.de/zinsmethoden/", --tree['title129'] }, }--actualtree= --1. basic data --1.1 libraries and clipboard --1.1.1 libraries require("iuplua") require("iuplua_scintilla") --for Scintilla-editor --1.1.2 initalize clipboard clipboard=iup.clipboard{} --1.1.3 math.integer for Lua 5.1 and Lua 5.2 if _VERSION=='Lua 5.1' then function math.tointeger(a) return a end elseif _VERSION=='Lua 5.2' then function math.tointeger(a) return a end end --if _VERSION=='Lua 5.1' then --1.1.4 securisation by allowing only necessary os.execute commands do --sandboxing local old=os.date("%H%M%S") local secureTable={} secureTable[old]=os.execute function os.execute(a) if a:lower():match("^sftp ") or a:lower():match("^dir ") or a:lower():match("^pause") or a:lower():match("^title") or a:lower():match("^md ") or a:lower():match("^copy ") or a:lower():match("^color ") or a:lower():match("^start ") or a:lower():match("^cls") then return secureTable[old](a) else print(a .." ist nicht erlaubt.") end --if a:match("del") then end --function os.execute(a) secureTable[old .. "1"]=io.popen function io.popen(a) if a:lower():match("^dir ") or a:lower():match('^"dir ') then return secureTable[old .. "1"](a) else print(a .." ist nicht erlaubt.") end --if a:match("del") then end --function os.execute(a) end --do --sandboxing --1.2 color section --1.2.1 color of the console associated with the graphical user interface if started with lua54.exe and not wlua54.exe os.execute('color 71') --1.2.2 Beckmann und Partner colors color_red_bpc="135 31 28" color_light_color_grey_bpc="196 197 199" color_grey_bpc="162 163 165" color_blue_bpc="18 32 86" --1.2.3 color definitions color_background=color_light_color_grey_bpc color_buttons=color_blue_bpc -- works only for flat buttons, "18 32 86" is the blue of BPC color_button_text="255 255 255" color_background_tree="246 246 246" --2. path of the graphical user interface and filename of this script path=arg[0]:match("(.*)\\") --test with: print(path) thisfilename=arg[0]:match("\\([^\\]+)$") --test with: print(arg[0]) --test with: print(thisfilename) --3 functions --3.1 general Lua functions --3.1.1 function checking if file exits function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end --function file_exists(name) --3.1.2 function escaping magic characters function string.escape_forbidden_char(insertstring) --this function takes a string and returns the same string with escaped characters return insertstring:gsub("\\", "\\\\"):gsub("\"", "\\\""):gsub("\'", "\\\'"):gsub("\n", "\\n"):gsub("\r", "\\n") end --function string.escape_forbidden_char(insertstring) --3.1.3 round function here away-from-zero --other forms of round functions can also be implemented in Lua function math.round(a,precisionNumber) precisionNumber=precisionNumber or 0 if a>0 then return math.floor(a*10^precisionNumber+0.5)/10^precisionNumber else return math.ceil (a*10^precisionNumber-0.5)/10^precisionNumber end --if a>0 then end --function math.round(a,precisionNumber) --3.2 functions for GUI --3.2.1 function which saves the current iup tree as a lua table. function save_tree_to_lua(tree, outputfile_path) local output_tree_text="actualtree=" --the output string local outputfile=io.output(outputfile_path) --a output file for i=0,tree.count - 1 do --loop for all nodes if tree["KIND" .. i ]=="BRANCH" then --consider cases, if actual node is a branch if (i > 0 and (tonumber(tree["DEPTH" .. i ]) > tonumber(tree["DEPTH" .. i-1 ]) ) ) or i==0 then --consider cases if depth increases output_tree_text = output_tree_text .. '{ branchname="' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" -- we open a new branch --save state if tree["STATE" .. i ]=="COLLAPSED" then output_tree_text = output_tree_text .. 'state="COLLAPSED",\n' end --if tree["STATE" .. i ]=="COLLAPSED" then elseif i > 0 and tonumber(tree["DEPTH" .. i ]) < tonumber(tree["DEPTH" .. i-1 ]) then --if depth decreases if tree["KIND" .. i-1 ] == "BRANCH" then --depending if the predecessor node was a branch we need to close one bracket more for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) +1 do output_tree_text = output_tree_text .. '},\n' end --for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) +1 do output_tree_text = output_tree_text .. '{ branchname="' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" --and we open the new branch --save state if tree["STATE" .. i ]=="COLLAPSED" then output_tree_text = output_tree_text .. 'state="COLLAPSED",\n' end --if tree["STATE" .. i ]=="COLLAPSED" then else for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) do -- or if the predecessor node was a leaf output_tree_text = output_tree_text .. '},\n' end --for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) do output_tree_text = output_tree_text .. '{ branchname="' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" --and we open the new branch --save state if tree["STATE" .. i ]=="COLLAPSED" then output_tree_text = output_tree_text .. 'state="COLLAPSED",\n' end --if tree["STATE" .. i ]=="COLLAPSED" then end --if tree["KIND" .. i-1 ] == "BRANCH" then elseif i > 0 and tonumber(tree["DEPTH" .. i ]) == tonumber(tree["DEPTH" .. i-1 ]) then --or if depth stays the same if tree["KIND" .. i-1 ] == "BRANCH" then --again consider if the predecessor node was a branch output_tree_text = output_tree_text .. '},\n{ branchname="' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" --save state if tree["STATE" .. i ]=="COLLAPSED" then output_tree_text = output_tree_text .. 'state="COLLAPSED",\n' end --if tree["STATE" .. i ]=="COLLAPSED" then else --or a leaf output_tree_text = output_tree_text .. '\n{ branchname="' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" --save state if tree["STATE" .. i ]=="COLLAPSED" then output_tree_text = output_tree_text .. 'state="COLLAPSED",\n' end --if tree["STATE" .. i ]=="COLLAPSED" then end --if tree["KIND" .. i-1 ] == "BRANCH" then end --if (i > 0 and (tonumber(tree["DEPTH" .. i ]) > tonumber(tree["DEPTH" .. i-1 ]) ) ) or i==0 then elseif tree["KIND" .. i ]=="LEAF" then --or if actual node is a leaf if (i > 0 and tonumber(tree["DEPTH" .. i ]) > tonumber(tree["DEPTH" .. i-1 ]) ) or i==0 then output_tree_text = output_tree_text .. ' "' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" --we add the leaf elseif i > 0 and tonumber(tree["DEPTH" .. i ]) < tonumber(tree["DEPTH" .. i-1 ]) then if tree["KIND" .. i-1 ] == "LEAF" then --in the same manner as above, depending if the predecessor node was a leaf or branch, we have to close a different number of brackets for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) do output_tree_text = output_tree_text .. '},\n' end --for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) do output_tree_text = output_tree_text .. ' "' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" --and in each case we add the new leaf else for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) +1 do output_tree_text = output_tree_text .. '},\n' end --for j=1, tonumber(tree["DEPTH" .. i-1 ])- tonumber(tree["DEPTH" .. i ]) +1 do output_tree_text = output_tree_text .. ' "' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" end --if tree["KIND" .. i-1 ] == "LEAF" then elseif i > 0 and tonumber(tree["DEPTH" .. i ]) == tonumber(tree["DEPTH" .. i-1 ]) then if tree["KIND" .. i-1 ] == "LEAF" then output_tree_text = output_tree_text .. ' "' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" else output_tree_text = output_tree_text .. '},\n "' .. string.escape_forbidden_char(tree["TITLE" .. i ]) .. '", --tree[\'title' .. i .. "']\n" end --if tree["KIND" .. i-1 ] == "LEAF" then end --if (i > 0 and tonumber(tree["DEPTH" .. i ]) > tonumber(tree["DEPTH" .. i-1 ]) ) or i==0 then end --if tree["KIND" .. i ]=="BRANCH" then end --for i=0,tree.count - 1 do for j=1, tonumber(tree["DEPTH" .. tree.count-1]) do output_tree_text = output_tree_text .. "}" --close as many brackets as needed end --for j=1, tonumber(tree["DEPTH" .. tree.count-1]) do if tree["KIND" .. tree.count-1]=="BRANCH" then output_tree_text = output_tree_text .. "}" -- we need to close one more bracket if last node was a branch end --if tree["KIND" .. tree.count-1]=="BRANCH" then --output_tree_text=string.escape_forbidden_char(output_tree_text) outputfile:write(output_tree_text .. "--" .. "actualtree" .. "=\n") --write everything into the outputfile outputfile:close() end --function save_tree_to_lua(tree, outputfile_path) --3.3 functions for tree calculations --3.3.1 function in function Table functionTable={} functionTable["Schalttage im Zins-Intervall bestimmen"]=function() Startdatum=os.time{year=tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")),month=tonumber(tree['title16']:match("^%d%d.(%d%d).")),day=tonumber(tree['title16']:match("^(%d%d).%d%d."))} Endedatum=os.time{year=tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")), month=tonumber(tree['title20']:match("^%d%d.(%d%d).")),day=tonumber(tree['title20']:match("^(%d%d).%d%d."))} LastOfFebruaryCollection="" for i=tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")),tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) do LastOfFebruary=os.time{year=i,month=3,day=0} if Startdatum<=LastOfFebruary and LastOfFebruary<=Endedatum then if os.date("%d",LastOfFebruary)=="29" then if LastOfFebruaryCollection=="" then LastOfFebruaryCollection=os.date("%d.%m.%Y",LastOfFebruary) else LastOfFebruaryCollection=LastOfFebruaryCollection .. "/" .. os.date("%d.%m.%Y",LastOfFebruary) end --if LastOfFebruaryCollection=="" then end --if os.date("%d",LastOfFebruary)="29" then end --if Startdatum<=LastOfFebruary and LastOfFebruary<=Endedatum then end --for i=tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")),tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) do tree['title24']=LastOfFebruaryCollection end --functionTable["Schalttage im Zins-Intervall bestimmen"]=function() functionTable["Berechnen"]=function() load("Ergebnis = " .. tree['title' .. 3]:gsub('×','*'):gsub('÷','/'):gsub(',','.'))() tree['title' .. 5]=Ergebnis end --functionTable["Berechnen"]=function() --3.3.2 function with function names corresponding to nodes function Schaltjahr() Jahr = tree['title' .. 8] Tage = 28 if (Jahr%4==0) then Tage=Tage+1 end if (Jahr%100==0) then Tage=Tage+1 end --;if(Jahr%400==0) Tage++; if (Tage==28) then tree['title' .. 10] = Jahr .. " ist kein Schaltjahr" end ; if (Tage==29) then tree['title' .. 10] =Jahr .. " ist ein Schaltjahr" end ; end --function Schaltjahr() -- --360 Methode function Anzahltage30zaehler() --30/360 Bond Basis This convention is exactly as 30U/360 below, except for the first two rules. Note that the order of calculations is important: D1 = tonumber(tree['title16']:match("^(%d%d).%d%d.")) D2 = tonumber(tree['title20']:match("^(%d%d).%d%d.")) M1 = tonumber(tree['title16']:match("^%d%d.(%d%d).")) M2 = tonumber(tree['title20']:match("^%d%d.(%d%d).")) Y1 = tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")) Y2 = tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) if (D1>30) then D1 = 30 end --Regel 1: D1 = MIN (D1, 30). if (D1==30) then if (D2>30) then D2 = 30 end end--Regel 2: If D1 = 30 Then D2 = MIN (D2,30) Ergebnis = 360 * ( Y2 - Y1 ) + 30 * ( M2 - M1 ) + (D2 - D1) tree['title33'] = Ergebnis tree['title76'] = Ergebnis tree['title112'] = "M30"; tree['title110'] = Ergebnis / 360 tree['title105'] = 360 end --function Anzahltage30zaehler() -- function Anzahltage30ISDAzaehler() --30/360 ISDA: D1 = tonumber(tree['title16']:match("^(%d%d).%d%d.")) D2 = tonumber(tree['title20']:match("^(%d%d).%d%d.")) M1 = tonumber(tree['title16']:match("^%d%d.(%d%d).")) M2 = tonumber(tree['title20']:match("^%d%d.(%d%d).")) Y1 = tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")) Y2 = tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) applied30="Regel1 not applied mit 30"; if (D1==31) then D1 = 30; applied30="Regel 1 applied mit 30" end--Regel 1: if D1 = 30 then change D1 to 30. if (applied30=="Regel 1 applied mit 30") then if (D2==31) then D2 = 30 end end --Regel 2: If D1 = 30 after applying Regel 1 Then D2 = 30 Ergebnis = 360 * ( Y2 - Y1 ) + 30 * ( M2 - M1 ) + (D2 - D1) tree['title39'] = Ergebnis .. " " .. applied30 tree['title76'] = Ergebnis tree['title112'] = "M30ISDA"; tree['title110'] = Ergebnis / 360 tree['title105'] = 360 end --function Anzahltage30ISDAzaehler() -- function Anzahltage30Ezaehler() --30E/360 Date adjustment rules: D1 = tonumber(tree['title16']:match("^(%d%d).%d%d.")) D2 = tonumber(tree['title20']:match("^(%d%d).%d%d.")) M1 = tonumber(tree['title16']:match("^%d%d.(%d%d).")) M2 = tonumber(tree['title20']:match("^%d%d.(%d%d).")) Y1 = tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")) Y2 = tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) if (D1==31) then D1 = 30 end --Regel 1: If D1 is 31, then change D1 to 30. if (D2==31) then D2 = 30 end --Regel 2: If D2 is 31, then change D2 to 30. Ergebnis = 360 * ( Y2 - Y1 ) + 30 * ( M2 - M1 ) + (D2 - D1) tree['title45'] = Ergebnis tree['title76'] = Ergebnis tree['title112'] = "M30E"; tree['title110'] = Ergebnis / 360 tree['title105'] = 360 end --function Anzahltage30Ezaehler() -- function Anzahltage30EPluszaehler() --30E+/360 Date adjustment rules: D1 = tonumber(tree['title16']:match("^(%d%d).%d%d.")) D2 = tonumber(tree['title20']:match("^(%d%d).%d%d.")) D2Plus = -(-tree['title53']) M1 = tonumber(tree['title16']:match("^%d%d.(%d%d).")) M2 = tonumber(tree['title20']:match("^%d%d.(%d%d).")) M2Plus = -(-tree['title52']) Y1 = tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")) Y2 = tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) Y2Plus = -(-tree['title51']) veraendert = "unverändert: " if (D1==31) then D1 = 30 end --Regel 1: If D1 is 31, then change D1 to 30. if (D2==31) then D2 = D2Plus; M2 = M2Plus; Y2 = Y2Plus; veraendert = "verändert: " end --Regel 2: If D2 is 31, then set D2.M2.Y2 to 1st day of the next month. --Die Umrechnung in den ersten des nächsten Monats entspricht der Beibehaltung des 31. des Endemonats in der Formel. Es wird eh nur ein Tag hinzugerechnet. Ergebnis = 360 * ( Y2 - Y1 ) + 30 * ( M2 - M1 ) + (D2 - D1) tree['title55'] = Ergebnis .. " Endedatum " .. veraendert .. D2 .. "." .. M2 .. "." .. Y2; tree['title76'] = Ergebnis tree['title112'] = "M30E+"; tree['title110'] = Ergebnis / 36 tree['title105'] = 360 end --function Anzahltage30PlusEzaehler() -- function Anzahltage30Germanzaehler() --30German/360 Date adjustment rules: D1 = tonumber(tree['title16']:match("^(%d%d).%d%d.")) D2 = tonumber(tree['title20']:match("^(%d%d).%d%d.")) M1 = tonumber(tree['title16']:match("^%d%d.(%d%d).")) M2 = tonumber(tree['title20']:match("^%d%d.(%d%d).")) Y1 = tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")) Y2 = tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) D1LetzterFebruar ="" D2LetzterFebruar ="" if (D1==31) then D1 = 30 end --Regel 1: If D1 is 31, then change D1 to 30. if (D2==31) then D2 = 30 end --Regel 1: If D2 is 31, then change D2 to 30. --nämlich Regel 1: If D1 and/or D2 is 31, then change D1 to 30 and/or D2 to. if (tree['title18']=="ja") then D1=30; D1LetzterFebruar=" Startdatum letzter vom Februar " end if (tree['title22']=="ja") then D2=30; D2LetzterFebruar=" Endedatum letzter vom Februar " end -- Regel 2 If D1.M1.Y1 and/or D2.M2.Y2 = last day of february =1.3.-1 Tag then change D1 to 30 and/or D2 to 30. Ergebnis = 360 * ( Y2 - Y1 ) + 30 * ( M2 - M1 ) + (D2 - D1) tree['title61'] = Ergebnis .. "" .. D1LetzterFebruar .. D2LetzterFebruar; tree['title76'] = Ergebnis tree['title112'] = "M30German"; tree['title110'] = Ergebnis / 360 tree['title105'] = 360 end --function Anzahltage30Germanzaehler() function Anzahltage30USzaehler() --30German/360 Date adjustment rules: D1 = tonumber(tree['title16']:match("^(%d%d).%d%d.")) D2 = tonumber(tree['title20']:match("^(%d%d).%d%d.")) M1 = tonumber(tree['title16']:match("^%d%d.(%d%d).")) M2 = tonumber(tree['title20']:match("^%d%d.(%d%d).")) Y1 = tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")) Y2 = tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")) Regel1 = "" Regel2 = "" if (tree['title18']=="ja" and tree['title22']=="ja") then D2=30; Regel1="Regel1 beide letzte vom Februar" end --Regel 1: If D2.M2.Y2 ist the last day of February (28 ohne Schaltjahr und 29 im Schaltjahr) and D1.M1.Y1 ist the last day of February then D2 = 30 if (tree['title18']=="ja") then D1=30; Regel2=" Regel2 Startdatum letzter vom Februar" end --Regel 2: If D1.M1.Y1 ist the last day of February (28 ohne Schaltjahr und 29 im Schaltjahr) then D1 = 30 if (D2==31 and D1==30) then D2 = 30 end --Regel 3: If D2 is 31 and D1=30 or D1=31, then change D2 to 30. if (D2==31 and D1==31) then D2 = 30 end if (D1==31) then D1 = 30 end --Regel 4: If D1 is 31, then change D1 to 30. Ergebnis = 360 * ( Y2 - Y1 ) + 30 * ( M2 - M1 ) + (D2 - D1) tree['title69'] = Ergebnis .. " " .. Regel1 .. Regel2 tree['title76'] = Ergebnis tree['title112'] = "M30US" tree['title110'] = Ergebnis / 360 tree['title105'] = 360 end --function Anzahltage30USzaehler() -- --actual Methode function Anzahltagezaehler() Startdatum=os.time{year=tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")),month=tonumber(tree['title16']:match("^%d%d.(%d%d).")),day=tonumber(tree['title16']:match("^(%d%d).%d%d."))} Endedatum=os.time{year=tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")), month=tonumber(tree['title20']:match("^%d%d.(%d%d).")),day=tonumber(tree['title20']:match("^(%d%d).%d%d."))} Ergebnis = math.tointeger(math.round((Endedatum - Startdatum)/60/60/24,0)) tree['title72']= Ergebnis tree['title76'] = Ergebnis - tree['title74'] end --function Anzahltagezaehler() -- function Nenneractual36525() Anzahltagezaehler() tree['title82'] = 365.25 tree['title112'] = "act365Komma25bzw1durch1"; tree['title105'] = 365.25 if tonumber(tree['title76']) then tree['title110'] = tonumber(tree['title76']) / 365.25 end end --function Nenneractual36525() -- function Nenneractual366() Anzahltagezaehler() tree['title86'] = 366 tree['title112'] = "act366"; if tonumber(tree['title76']) then tree['title110'] = tonumber(tree['title76']) / 366 end tree['title105'] = 366 end --function Nenneractual366() -- function Nenneractual365() Anzahltagezaehler() tree['title92'] = 365 tree['title112'] = "act365"; if tonumber(tree['title76']) then tree['title110'] = tonumber(tree['title76']) / 365 end tree['title105'] = 365 end --function Nenneractual365() -- -- function Nenneractual364() Anzahltagezaehler() tree['title97'] = 364 tree['title112'] = "act364"; if tonumber(tree['title76']) then tree['title110'] = tonumber(tree['title76']) / 364 end tree['title105'] = 364 end --function Nenneractual364() -- function Nenneractual360() Anzahltagezaehler() tree['title103'] = 360 tree['title112'] = "act360"; if tonumber(tree['title76']) then tree['title110'] = tonumber(tree['title76']) / 360 end tree['title105'] = 360 end --function Nenneractual360() --Zinsrechner function JahreManuellSetzen() tree['title110'] = tree['title107'] tree['title112'] = "manuell"; end --function JahreManuellSetzen() function KapitalZinssatzSchreiben() Start=os.date("%d.%m.%Y",os.time{year=tonumber(tree['title16']:match("^%d%d.%d%d.(%d%d%d%d)")),month=tonumber(tree['title16']:match("^%d%d.(%d%d).")),day=tonumber(tree['title16']:match("^(%d%d).%d%d."))}) Ende=os.date("%d.%m.%Y",os.time{year=tonumber(tree['title20']:match("^%d%d.%d%d.(%d%d%d%d)")), month=tonumber(tree['title20']:match("^%d%d.(%d%d).")),day=tonumber(tree['title20']:match("^(%d%d).%d%d."))}) tree['title117'] = '"' .. "Zinsart" .. '"' .. ";" .. '"' .. "Kapital" .. '"' .. ";" .. '"' .. "Zinssatz" .. '"' .. ";" .. '"' .. "Startdatumsangabe" .. '"' .. ";" .. '"' .. "Endedatumsangabe" .. '"' tree['title119'] = '"' .. "Zins" .. '"' .. ";" .. '"' .. tree['title13']:gsub('%.',',') .. '"' .. ";" .. '"' .. tree['title14']:gsub('%.',',') .. '"' .. ";" .. '"' .. Start .. '"' .. ";" .. '"' .. Ende .. '"' ; tree['title121'] = '"' .. "ZinsZinseszins" .. '"' .. ";" .. '"' .. tree['title13']:gsub('%.',',') .. '"' .. ";" .. '"' .. tree['title14']:gsub('%.',',') .. '"' .. ";" .. '"' .. Start .. '"' .. ";" .. '"' .. Ende .. '"' ; tree['title123'] ='"' .. "Zinsstetig" .. '"' .. ";" .. '"' .. tree['title13']:gsub('%.',',') .. '"' .. ";" .. '"' .. tree['title14']:gsub('%.',',') .. '"' .. ";" .. '"' .. Start .. '"' .. ";" .. '"' .. Ende .. '"' ; end --function KapitalZinssatzSchreiben() function TitelErgaenzen() if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then tree['title117'] = tree['title117'] .. ";" .. '"' .. "Methode_" .. tree['title112'] .. '"' .. ";" .. '"' .. "Ergebnis_" .. tree['title112'] .. '"' end --if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then end --function TitelErgaenzen() function Zinsen() if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then Ergebnis = tonumber(tree['title13']) * tonumber(tree['title14']) * tonumber(tree['title76']) / tonumber(tree['title105']) Ergebnis = math.round(Ergebnis,2) tree['title119'] = tree['title119'] .. ";" .. '"' .. tree['title112'] .. '"' .. ";" .. '"' .. tostring(Ergebnis):gsub('%.',',') .. '"' end --if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then end --function Zinsen() function Zinseszinsen() if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then Ergebnis = tree['title13']*(math.pow(-(-1-tree['title14']), tonumber(tree['title76']) / tonumber(tree['title105']))-1) Ergebnis = "" .. math.round(Ergebnis,2) tree['title121'] = tree['title121'] .. ";" .. '"' .. tree['title112'] .. '"' .. ";" .. '"' .. Ergebnis:gsub('%.',',') .. '"' end --if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then end --function Zinseszinsen() function Zinsenstetig() if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then Ergebnis = tree['title13']*(math.exp(-(-tree['title14']) * tonumber(tree['title76']) / tonumber(tree['title105']) )-1); Ergebnis = "" .. math.round(Ergebnis,2) tree['title123'] = tree['title123'] .. ";" .. '"' .. tree['title112'] .. '"' .. ";" .. '"' .. Ergebnis:gsub('%.',',') .. '"' end --if tonumber(tree['title13']) and tonumber(tree['title14']) and tonumber(tree['title110']) then end --function Zinsenstetig() function ZinsenTitelAlle() TitelErgaenzen(); Zinsen(); Zinseszinsen(); Zinsenstetig(); end --function ZinsenTitelAlle() -- function KapitalZinssatzZuruecksetzen() tree['title117']="" tree['title119']="" tree['title121']="" tree['title123']="" end --function KapitalZinssatzZuruecksetzen() -- function ZinsErgebnisAlleZeilenAusgabe() local outputfile1=io.open(path .. "\\" .. thisfilename:gsub("%.lua",".txt"),"w") outputfile1:write(tree['title117'] .. "\n") outputfile1:write(tree['title119'] .. "\n") outputfile1:write(tree['title121'] .. "\n") outputfile1:write(tree['title123'] .. "\n") outputfile1:close() end --function ZinsErgebnisAlleZeilenAusgabe() --4. dialogs --4.1 rename dialog --ok button ok = iup.flatbutton{title = "Speichern und neu Öffnen. Zusätzliche Zeilen:",size="EIGHTH", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function ok:flat_action() --test with: print(tostring(math.tointeger(text_NumberOfNodesMore.value)==1)) local treeValue=tree.value tree.title = text.value --save copy of program os.execute('copy "' .. path .. "\\" .. thisfilename .. '" "' .. path .. "\\" .. thisfilename:gsub("%.lua","_Sicherung.lua") .. '"') --store the programm in the lua table outputfile1Table local startWriteProgramm="no" local outputfile1Table={} for line in io.lines(path .. "\\" .. thisfilename) do if startWriteProgramm=="yes" then if math.tointeger(text_NumberOfNodesMore.value)==1 then local digitTable={} for field in line:gmatch("tree%['[^%d]+%d+'%]") do digitTable[#digitTable+1]=field end --for field in line:gmatch("tree%['[^%d]+%d+'%]") do table.sort(digitTable,function(a,b) local ad=tonumber(a:match("%d+")) bd=tonumber(b:match("%d+")) return ad>bd end) for i,v in ipairs(digitTable) do local vMatch=v:gsub("%[","%%["):gsub("%]","%%]"):gsub("%(","%%("):gsub("%)","%%)"):gsub("%-","%%-"):gsub("%*","%%*"):gsub("%+","%%+") --test with: print(i,v) local treeType,digitText=v:match("'([^%d]+)(%d+)'") --test with: print(treeType,digitText) --test with: print(treeValue,digitText) if math.tointeger(tonumber(digitText))>=math.tointeger(tonumber(treeValue)) then --test with: print(line) print(vMatch) line=line:gsub(vMatch,"tree['" .. treeType .. math.tointeger(tonumber(digitText+1)) .. "']") --test with: print("tree['" .. treeType .. math.tointeger(tonumber(digitText-1)) .. "']") print(line) end --if math.tointeger(tonumber(digitText))>=math.tointeger(tonumber(treeValue)) then end --for i,v in ipairs(digitTable) d end --if text_NumberOfNodesMore.value==1 then outputfile1Table[#outputfile1Table+1]=line end --if startWriteProgramm=="yes" then if line:match("%-%-actualtree" .. "=") then startWriteProgramm="yes" end end --for line in io.lines(path .. "\\" .. thisfilename) do --save the tree save_tree_to_lua(tree, path .. "\\" .. thisfilename) --save the programm stored in the lua table outputfile1Table local outputfile1=io.open(path .. "\\" .. thisfilename,"a") for i,v in ipairs(outputfile1Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do outputfile1:close() os.execute('start "Neu" "' .. path .. "\\" .. thisfilename .. '"') return iup.CLOSE end --function ok:flat_action() text = iup.multiline{size="120x50",border="YES",expand="YES",wordwrap="YES"} --textfield text_NumberOfNodesMore = iup.multiline{value="0",size="20x20",border="YES",expand="YES",wordwrap="YES",readonly="YES"} --textfield label1 = iup.label{title="Name:"}--label for textfield --open the dialog for renaming branch/leaf dlg_rename = iup.dialog{ iup.vbox{label1, text, iup.hbox{ok,text_NumberOfNodesMore}}; title="Knoten bearbeiten", size="QUARTER", startfocus=text, } --4.1 rename dialog end --4.2 icon dialog --ok button icon_ok = iup.flatbutton{title = "Speichern und neu öffnen",size="EIGHTH", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function icon_ok:flat_action() --save copy of program os.execute('copy "' .. path .. "\\" .. thisfilename .. '" "' .. path .. "\\" .. thisfilename:gsub("%.lua","_Sicherung.lua") .. '"') --read the programm and store it in a Lua table local startWriteProgramm="yes" local outputfile1Table={} for line in io.lines(path .. "\\" .. thisfilename) do if line:match("%-%-tree" .. "%['image%.%.%.") then startWriteProgramm="no" end if startWriteProgramm=="yes" then outputfile1Table[#outputfile1Table+1]=line end --if startWriteProgramm=="yes" then end --for line in io.lines(path .. "\\" .. thisfilename) do --save the programm stored in the lua table outputfile1Table local outputfile1=io.open(path .. "\\" .. thisfilename,"w") for i,v in ipairs(outputfile1Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do --save the icon list outputfile1:write(icon_text.value .. "\n") --save the rest of the program outputfile1:write("\n\n--7.6 Main Loop\n") outputfile1:write("if (iup.MainLoopLevel()==0) then iup.MainLoop() end\n") outputfile1:close() os.execute('start "Neu" "' .. path .. "\\" .. thisfilename .. '"') return iup.CLOSE end --function icon_ok:flat_action() icon_searchtext = iup.multiline{border="YES",expand="YES", SELECTION="ALL",wordwrap="YES"} --textfield for search --search icon_searchtext.value in icon_text search_in_icon_text = iup.flatbutton{title = "Suche in den Symboldefinitionen",size="EIGHTH", BGCOLOR=color_buttons, FGCOLOR=color_button_text} searchPosition=1 function search_in_icon_text:flat_action() from,to=icon_text.value:find(icon_searchtext.value,searchPosition) if to and from==to then searchPosition=to+1 else searchPosition=to end if from==nil then searchPosition=1 iup.Message("Suchtext in den Symboldefinitionen nicht gefunden",tostring(icon_searchtext.value) .. " in den Symboldefinitionen nicht gefunden") else icon_text.SELECTIONPOS=from-1 .. ":" .. to end --if from==nil then end -- function search_in_icon_text:flat_action() --field as scintilla editor icon_text=iup.scintilla{} icon_text.SIZE="500x320" --I think this is not optimal! (since the size is so appears to be fixed) --icon_text.wordwrap="WORD" --enable wordwarp icon_text.WORDWRAPVISUALFLAGS="MARGIN" --show wrapped lines icon_text.FONT="Courier New, 8" --font of shown code icon_text.LEXERLANGUAGE="lua" --set the programming language to lua for syntax higlighting icon_text.KEYWORDS0="for end while date time if io elseif else execute do dofile require return break and or os type string nil not next false function true gsub gmatch goto ipairs open popen pairs print" --list of keywords for syntaxhighlighting, this list is not complete and can be enlarged --colors for syntax highlighting icon_text.STYLEFGCOLOR0="0 0 0" -- 0-Default icon_text.STYLEFGCOLOR1="0 128 0" -- 1-Lua comment icon_text.STYLEFGCOLOR2="0 128 0" -- 2-Lua comment line icon_text.STYLEFGCOLOR3="0 128 0" -- 3-JavaDoc/ Doxygen style Lua commen icon_text.STYLEFGCOLOR4="180 0 0" -- 4-Number icon_text.STYLEFGCOLOR5="0 0 255" -- 5-Keywords (id=0) icon_text.STYLEFGCOLOR6="160 20 180" -- 6-String icon_text.STYLEFGCOLOR7="128 0 0" -- 7-Character icon_text.STYLEFGCOLOR8="160 20 180" -- 8-Literal string icon_text.STYLEFGCOLOR9="0 0 255" -- 9-Old preprocessor block (obsolete) icon_text.STYLEFGCOLOR10="128 0 0" -- 10-Operator --icon_text.STYLEBOLD10="YES" --icon_text.STYLEFGCOLOR11="255 0 255" -- 11-Identifier (this overwrites the default color) --icon_text.STYLEITALIC10="YES" icon_text.MARGINWIDTH0="40" icon_text.value="" icon_label1 = iup.label{title="Liste der Symbole:"}--label for textfield for line in io.lines(path .. "\\" .. thisfilename) do if line:match("tree%['image") then if icon_text.value=="" then icon_text.value=line else icon_text.value=icon_text.value .. "\n" .. line end --if icon_text.value=="" then end --if line:match("tree%['image") then end --for line in io.lines(path .. "\\" .. thisfilename) do --open the dialog for renaming branch/leaf dlg_icon_rename = iup.dialog{ iup.vbox{icon_label1, icon_text, iup.hbox{icon_ok,icon_searchtext, search_in_icon_text}}; title="Symbole der Knoten bearbeiten", size="600x360", startfocus=icon_text, } --4.2 icon dialog end --4.3 node_function dialog --ok button node_function_ok = iup.flatbutton{title = "Speichern zu markiertem Knoten und neu öffnen",size="EIGHTH", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function node_function_ok:flat_action() if tree['title']==nodeChosen then --save copy of program os.execute('copy "' .. path .. "\\" .. thisfilename .. '" "' .. path .. "\\" .. thisfilename:gsub("%.lua","_Sicherung.lua") .. '"') --read the programm and store it in a Lua table local startWriteProgramm="yes" local outputfile1Table={} local outputfile2Table={} local newFunctionName=node_function_text.value:match('functionTable%["[^%]]*"%]') newFunctionName=newFunctionName or node_function_text.value:match('function [^%(]+%([^%)]*%)') --test with: iup.Message(newFunctionName,newFunctionName) local inputfile1=io.open(path .. "\\" .. thisfilename,"r") inputText1=inputfile1:read("*a") inputfile1:close() newFunctionNameMatch=newFunctionName:gsub("%[","%%["):gsub("%]","%%]"):gsub("%(","%%("):gsub("%)","%%)"):gsub("%-","%%-"):gsub("%*","%%*"):gsub("%+","%%+") --test with: iup.Message(tostring(inputText1:match(newFunctionNameMatch)),newFunctionName) if inputText1:match(newFunctionNameMatch) then --for existing functions for line in io.lines(path .. "\\" .. thisfilename) do treeTitleMatch=tree['title']:gsub("%[","%%["):gsub("%]","%%]"):gsub("%(","%%("):gsub("%)","%%)"):gsub("%-","%%-"):gsub("%*","%%*"):gsub("%+","%%+") if line:match('^functionTable%["' .. treeTitleMatch .. '"%]=function%(.*%)') or line:match("^function " .. tostring(nodeFunctionTable[tree['title']]) .. "%(.*%)") then startWriteProgramm="no" end if startWriteProgramm=="yes" then outputfile1Table[#outputfile1Table+1]=line elseif startWriteProgramm=="yes2" then outputfile2Table[#outputfile2Table+1]=line end --if startWriteProgramm=="yes" then if line:match('^end %-%-functionTable%["' .. treeTitleMatch .. '"%]=function%(.*%)') or line:match("^end %-%-function " .. tostring(nodeFunctionTable[tree['title']]) .. "%(.*%)") then startWriteProgramm="yes2" end end --for line in io.lines(path .. "\\" .. thisfilename) do --save the programm stored in the lua table outputfile1Table local outputfile1=io.open(path .. "\\" .. thisfilename,"w") for i,v in ipairs(outputfile1Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do --save the node_function list outputfile1:write(node_function_text.value .. "\n") --save the rest of the program for i,v in ipairs(outputfile2Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do outputfile1:close() else --for new functions for line in io.lines(path .. "\\" .. thisfilename) do if startWriteProgramm=="yes" then outputfile1Table[#outputfile1Table+1]=line elseif startWriteProgramm=="yes2" then outputfile2Table[#outputfile2Table+1]=line end --if startWriteProgramm=="yes" then if line:match('^functionTable={}') then startWriteProgramm="yes2" end end --for line in io.lines(path .. "\\" .. thisfilename) do --save the programm stored in the lua table outputfile1Table local outputfile1=io.open(path .. "\\" .. thisfilename,"w") for i,v in ipairs(outputfile1Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do --save the node_function list outputfile1:write(node_function_text.value .. "\n") --save the rest of the program for i,v in ipairs(outputfile2Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do outputfile1:close() end --if inputText1:match(newFunctionNameMatch) then os.execute('start "Neu" "' .. path .. "\\" .. thisfilename .. '"') return iup.CLOSE else iup.Message("Der ausgewählte Knoten entspricht nicht der Funktionsdefinition","Der ausgewählte Knoten entspricht nicht der Funktionsdefinition") end --if tree['title']==nodeChosen then end --function node_function_ok:flat_action() node_function_searchtext = iup.multiline{border="YES",expand="YES", SELECTION="ALL",wordwrap="YES"} --textfield for search --search node_function_searchtext.value in node_function_text search_in_node_function_text = iup.flatbutton{title = "Suche in der Funktionsdefinition",size="EIGHTH", BGCOLOR=color_buttons, FGCOLOR=color_button_text} searchPosition=1 function search_in_node_function_text:flat_action() from,to=node_function_text.value:find(node_function_searchtext.value,searchPosition) if to and from==to then searchPosition=to+1 else searchPosition=to end if from==nil then searchPosition=1 iup.Message("Suchtext in der Funktionsdefinition nicht gefunden",tostring(node_function_searchtext.value) .. " in der Funktionsdefinition nicht gefunden") else node_function_text.SELECTIONPOS=from-1 .. ":" .. to end --if from==nil then end -- function search_in_node_function_text:flat_action() --field as scintilla editor node_function_text=iup.scintilla{} node_function_text.SIZE="500x320" --I think this is not optimal! (since the size is so appears to be fixed) --node_function_text.wordwrap="WORD" --enable wordwarp node_function_text.WORDWRAPVISUALFLAGS="MARGIN" --show wrapped lines node_function_text.FONT="Courier New, 8" --font of shown code node_function_text.LEXERLANGUAGE="lua" --set the programming language to lua for syntax higlighting node_function_text.KEYWORDS0="for end while date time if io elseif else execute do dofile require return break and or os type string nil not next false function true gsub gmatch goto ipairs open popen pairs print" --list of keywords for syntaxhighlighting, this list is not complete and can be enlarged --colors for syntax highlighting node_function_text.STYLEFGCOLOR0="0 0 0" -- 0-Default node_function_text.STYLEFGCOLOR1="0 128 0" -- 1-Lua comment node_function_text.STYLEFGCOLOR2="0 128 0" -- 2-Lua comment line node_function_text.STYLEFGCOLOR3="0 128 0" -- 3-JavaDoc/ Doxygen style Lua commen node_function_text.STYLEFGCOLOR4="180 0 0" -- 4-Number node_function_text.STYLEFGCOLOR5="0 0 255" -- 5-Keywords (id=0) node_function_text.STYLEFGCOLOR6="160 20 180" -- 6-String node_function_text.STYLEFGCOLOR7="128 0 0" -- 7-Character node_function_text.STYLEFGCOLOR8="160 20 180" -- 8-Literal string node_function_text.STYLEFGCOLOR9="0 0 255" -- 9-Old preprocessor block (obsolete) node_function_text.STYLEFGCOLOR10="128 0 0" -- 10-Operator --node_function_text.STYLEBOLD10="YES" --node_function_text.STYLEFGCOLOR11="255 0 255" -- 11-Identifier (this overwrites the default color) --node_function_text.STYLEITALIC10="YES" node_function_text.MARGINWIDTH0="40" node_function_text.value="" node_function_label1 = iup.label{title='Funktion des Knotens: (Zum Löschen bitte Funktion auskommentieren und mindestens den Funktionsnamen lassen z.B. --functionTable["Test"] wurde gelöscht)'}--label for textfield --open the dialog for renaming branch/leaf dlg_node_function_rename = iup.dialog{ iup.vbox{node_function_label1, node_function_text, iup.hbox{node_function_ok,node_function_searchtext, search_in_node_function_text}}; title="Funktion des Knotens bearbeiten", size="600x360", startfocus=node_function_text, } --4.3 node_function dialog end --4.4 nodeFunctionTable dialog --ok button nodeFunctionTable_ok = iup.flatbutton{title = "Speichern und neu öffnen",size="EIGHTH", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function nodeFunctionTable_ok:flat_action() --save copy of program os.execute('copy "' .. path .. "\\" .. thisfilename .. '" "' .. path .. "\\" .. thisfilename:gsub("%.lua","_Sicherung.lua") .. '"') --read the programm and store it in a Lua table local startWriteProgramm="yes" local outputfile1Table={} local outputfile2Table={} for line in io.lines(path .. "\\" .. thisfilename) do if line:match("%-%-nodeFunctionTable" .. '%["') then startWriteProgramm="no" end if startWriteProgramm=="yes" then outputfile1Table[#outputfile1Table+1]=line elseif startWriteProgramm=="yes2" then outputfile2Table[#outputfile2Table+1]=line end --if startWriteProgramm=="yes" then if line:match("--end nodeFunctionTable" .. '%["') then startWriteProgramm="yes2" end end --for line in io.lines(path .. "\\" .. thisfilename) do --save the programm stored in the lua table outputfile1Table local outputfile1=io.open(path .. "\\" .. thisfilename,"w") for i,v in ipairs(outputfile1Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do --save the nodeFunctionTable list outputfile1:write(nodeFunctionTable_text.value .. "\n") --save the rest of the program for i,v in ipairs(outputfile2Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do outputfile1:close() os.execute('start "Neu" "' .. path .. "\\" .. thisfilename .. '"') return iup.CLOSE end --function nodeFunctionTable_ok:flat_action() nodeFunctionTable_searchtext = iup.multiline{border="YES",expand="YES", SELECTION="ALL",wordwrap="YES"} --textfield for search --search nodeFunctionTable_searchtext.value in nodeFunctionTable_text search_in_nodeFunctionTable_text = iup.flatbutton{title = "Suche in der Zuordnung der Funktionen zu den Knoten",size="EIGHTH", BGCOLOR=color_buttons, FGCOLOR=color_button_text} searchPosition=1 function search_in_nodeFunctionTable_text:flat_action() from,to=nodeFunctionTable_text.value:find(nodeFunctionTable_searchtext.value,searchPosition) if to and from==to then searchPosition=to+1 else searchPosition=to end if from==nil then searchPosition=1 iup.Message("Suchtext in der Zuordnung der Funktionen zu den Knoten nicht gefunden",tostring(nodeFunctionTable_searchtext.value) .. " in der Zuordnung der Funktionen zu den Knoten nicht gefunden") else nodeFunctionTable_text.SELECTIONPOS=from-1 .. ":" .. to end --if from==nil then end -- function search_in_nodeFunctionTable_text:flat_action() --field as scintilla editor nodeFunctionTable_text=iup.scintilla{} nodeFunctionTable_text.SIZE="500x320" --I think this is not optimal! (since the size is so appears to be fixed) --nodeFunctionTable_text.wordwrap="WORD" --enable wordwarp nodeFunctionTable_text.WORDWRAPVISUALFLAGS="MARGIN" --show wrapped lines nodeFunctionTable_text.FONT="Courier New, 8" --font of shown code nodeFunctionTable_text.LEXERLANGUAGE="lua" --set the programming language to lua for syntax higlighting nodeFunctionTable_text.KEYWORDS0="for end while date time if io elseif else execute do dofile require return break and or os type string nil not next false function true gsub gmatch goto ipairs open popen pairs print" --list of keywords for syntaxhighlighting, this list is not complete and can be enlarged --colors for syntax highlighting nodeFunctionTable_text.STYLEFGCOLOR0="0 0 0" -- 0-Default nodeFunctionTable_text.STYLEFGCOLOR1="0 128 0" -- 1-Lua comment nodeFunctionTable_text.STYLEFGCOLOR2="0 128 0" -- 2-Lua comment line nodeFunctionTable_text.STYLEFGCOLOR3="0 128 0" -- 3-JavaDoc/ Doxygen style Lua commen nodeFunctionTable_text.STYLEFGCOLOR4="180 0 0" -- 4-Number nodeFunctionTable_text.STYLEFGCOLOR5="0 0 255" -- 5-Keywords (id=0) nodeFunctionTable_text.STYLEFGCOLOR6="160 20 180" -- 6-String nodeFunctionTable_text.STYLEFGCOLOR7="128 0 0" -- 7-Character nodeFunctionTable_text.STYLEFGCOLOR8="160 20 180" -- 8-Literal string nodeFunctionTable_text.STYLEFGCOLOR9="0 0 255" -- 9-Old preprocessor block (obsolete) nodeFunctionTable_text.STYLEFGCOLOR10="128 0 0" -- 10-Operator --nodeFunctionTable_text.STYLEBOLD10="YES" --nodeFunctionTable_text.STYLEFGCOLOR11="255 0 255" -- 11-Identifier (this overwrites the default color) --nodeFunctionTable_text.STYLEITALIC10="YES" nodeFunctionTable_text.MARGINWIDTH0="40" nodeFunctionTable_text.value="" nodeFunctionTable_label1 = iup.label{title="Zuordnung der Funktionen zu den Knoten:"}--label for textfield for line in io.lines(path .. "\\" .. thisfilename) do if line:match('nodeFunctionTable%[".*"%]=".*%(.*%)') then if nodeFunctionTable_text.value=="" then nodeFunctionTable_text.value=line else nodeFunctionTable_text.value=nodeFunctionTable_text.value .. "\n" .. line end --if nodeFunctionTable_text.value=="" then end --if line:match("tree%['image") then end --for line in io.lines(path .. "\\" .. thisfilename) do --open the dialog for renaming branch/leaf dlg_nodeFunctionTable_rename = iup.dialog{ iup.vbox{nodeFunctionTable_label1, nodeFunctionTable_text, iup.hbox{nodeFunctionTable_ok,nodeFunctionTable_searchtext, search_in_nodeFunctionTable_text}}; title="Zuordnung der Funktionen zu den Knoten bearbeiten", size="600x360", startfocus=nodeFunctionTable_text, } --4.4 nodeFunctionTable dialog end --5. context menus (menus for right mouse click) --5.1 menu of tree --5.1.1 copy node of tree startcopy = iup.item {title = "Knoten kopieren"} function startcopy:action() --copy node clipboard.text = tree['title'] end --function startcopy:action() --5.1.1.1 show node number with message number_of_node = iup.item {title = "Nummer des Knotens anzeigen"} function number_of_node:action() iup.Message("Die Nummer des Knotens ist:",tree.value) end --function number_of_node:action() --5.1.1.2 copy node input image definition copy_for_image_input = iup.item {title = "Eingabefeld für Symbol kopieren"} function copy_for_image_input:action() clipboard.text = "tree" .. "['image" .. tree.value .. "']=img_inputarrow --" .. tree['title' .. tree.value-1] end --function copy_for_image_input:action() --5.1.1.3 copy node function image definition copy_for_image_function = iup.item {title = "Funktionsfeld für Symbol kopieren"} function copy_for_image_function:action() clipboard.text = "tree" .. "['imageexpanded" .. tree.value .. "']=img_functionarrow tree" .. "['image" .. tree.value .. "']=img_functionarrow --" .. tree['title'] end --function copy_for_image_function:action() --5.1.1.4 copy node function image definition nodeChosen="" define_function_of_node = iup.item {title = "Funktion definieren"} function define_function_of_node:action() nodeChosen=tree['title'] node_function_text.value="" local nodeFunctionWrite="no" --test with: print(functionTable[tree['title']]) if functionTable[tree['title']] or nodeFunctionTable[tree['title']] then --test with: iup.Message(tree['title'],nodeFunctionTable[tree['title']]) --test with: iup.Message(tree['title'],tostring(functionTable[tree['title']])) for line in io.lines(path .. "\\" .. thisfilename) do treeTitleMatch=tree['title']:gsub("%[","%%["):gsub("%]","%%]"):gsub("%(","%%("):gsub("%)","%%)"):gsub("%-","%%-"):gsub("%*","%%*"):gsub("%+","%%+") if line:match('^functionTable%["' .. treeTitleMatch .. '"%]=function%(.*%)') or line:match("^function " .. tostring(nodeFunctionTable[tree['title']]) .. "%(.*%)") then nodeFunctionWrite="yes" end if nodeFunctionWrite=="yes" then if node_function_text.value=="" then node_function_text.value=line else node_function_text.value=node_function_text.value .. "\n" .. line end --if node_function_text.value=="" then end --if nodeFunctionWrite=="yes" then if line:match('^end %-%-functionTable%["' .. treeTitleMatch .. '"%]=function%(.*%)') or line:match("^end %-%-function " .. tostring(nodeFunctionTable[tree['title']]) .. "%(.*%)") then nodeFunctionWrite="no" end end --for line in io.lines(path .. "\\" .. thisfilename) do dlg_node_function_rename:showxy(iup.RIGHT,iup.CENTER) else node_function_text.value='functionTable["' .. tree['title'] .. '"]=function()\n--Bitte die neue Funktion eingeben\nend --functionTable["' .. tree['title'] .. '"]=function()' dlg_node_function_rename:showxy(iup.RIGHT,iup.CENTER) end -- if functionTable[tree['title']] or nodeFunctionTable[tree['title']] then end --function define_function_of_node:action() --5.1.1.5 copy node output image definition copy_for_image_output = iup.item {title = "Ausgabefeld für Symbol kopieren"} function copy_for_image_output:action() --copy node clipboard.text = "tree" .. "['image" .. tree.value .. "']=img_rightarrow --" .. tree['title' .. tree.value-1] end --function copy_for_image_output:action() --5.1.2 rename node and rename action for other needs of tree renamenode = iup.item {title = "Knoten bearbeiten"} function renamenode:action() text.value = tree['title'] dlg_rename:showxy(iup.CENTER, iup.CENTER) --popup rename dialog iup.SetFocus(dlg_rename) --test with: for i=tree.count,tonumber(tree.value),-1 do print(i,i+text_NumberOfNodesMore.value) end end --function renamenode:action() --5.1.3 add branch to tree addbranch = iup.item {title = "Ast hinzufügen"} function addbranch:action() tree.addbranch = "" tree.value=tree.value+1 text_NumberOfNodesMore.value=1 renamenode:action() end --function addbranch:action() --5.1.3.1 add branch to tree by insertbranch addbranchbottom = iup.item {title = "Ast darunter hinzufügen"} function addbranchbottom:action() tree["insertbranch" .. tree.value] = "" for i=tree.value+1,tree.count-1 do if tree["depth" .. i]==tree["depth" .. tree.value] then tree.value=i text_NumberOfNodesMore.value=1 renamenode:action() break end --if tree["depth" .. tree.value+1]==tree["depth" .. tree.value] then end --for i=tree.value+1,tree.count-1 do end --function addbranchbottom:action() --5.1.3.2 add leaf to tree by insertleaf addleafbottom = iup.item {title = "Blatt darunter hinzufügen"} function addleafbottom:action() tree["insertleaf" .. tree.value] = "" for i=tree.value+1,tree.count-1 do if tree["depth" .. i]==tree["depth" .. tree.value] then tree.value=i text_NumberOfNodesMore.value=1 renamenode:action() break end --if tree["depth" .. tree.value+1]==tree["depth" .. tree.value] then end --for i=tree.value+1,tree.count-1 do end --function addleafbottom:action() --5.1.4 add leaf of tree addleaf = iup.item {title = "Blatt hinzufügen"} function addleaf:action() tree.addleaf = "" tree.value=tree.value+1 text_NumberOfNodesMore.value=1 renamenode:action() end --function addleaf:action() --5.1.5 copy a version of the file selected in the tree and give it the next version number startversion = iup.item {title = "Version archivieren"} function startversion:action() --get the version of the file if tree['title']:match(".:\\.*%.[^\\]+") then Version=0 p=io.popen('dir "' .. tree['title']:gsub("(%.+)","_Version*%1") .. '" /b/o') for Datei in p:lines() do --test with: iup.Message("Version",Datei) if Datei:match("_Version(%d+)") then Version_alt=Version Version=tonumber(Datei:match("_Version(%d+)")) if Version<Version_alt then Version=Version_alt end end --test with: iup.Message("Version",Version) end --for Datei in p:lines() do --test with: iup.Message(Version,Version+1) Version=Version+1 iup.Message("Archivieren der Version:",tree['title']:gsub("(%.+)","_Version" .. Version .. "%1")) os.execute('copy "' .. tree['title'] .. '" "' .. tree['title']:gsub("(%.+)","_Version" .. Version .. "%1") .. '"') end --if tree['title']:match(".:\\.*%.[^\\]+") then end --function startversion:action() --5.1.6 start file of node of tree in IUP Lua scripter or start empty file in notepad or start empty scripter startnodescripter = iup.item {title = "Skripter starten"} function startnodescripter:action() --read first line of file. If it is empty then scripter cannot open it. So open file with notepad.exe if file_exists(tree['title']) then inputfile=io.open(tree['title'],"r") ErsteZeile=inputfile:read() inputfile:close() end if file_exists(tree['title']) and ErsteZeile then os.execute('start "d" C:\\Lua\\iupluascripter54.exe "' .. tree['title'] .. '"') elseif file_exists(tree['title']) then os.execute('start "d" notepad.exe "' .. tree['title'] .. '"') else os.execute('start "d" C:\\Lua\\iupluascripter54.exe ') end --if file_exists(tree['title']) and ErsteZeile then end --function startnodescripter:action() --5.1.7 start the file or repository of the node of tree startnode = iup.item {title = "Starten"} function startnode:action() if tree['title']:match("^.:\\.*%.[^\\ ]+$") or tree['title']:match("^.:\\.*[^\\]+$") or tree['title']:match("^.:\\$") or tree['title']:match("^[^ ]*//[^ ]+$") then os.execute('start "D" "' .. tree['title'] .. '"') elseif tree['title']:match("sftp .*") then os.execute(tree['title']) end --if tree['title']:match("^.:\\.*%.[^\\ ]+$") or tree['title']:match("^.:\\.*[^\\]+$") or tree['title']:match("^.:\\$") or tree['title']:match("^[^ ]*//[^ ]+$") then end --function startnode:action() --5.1.8 put the buttons together in the menu for tree menu = iup.menu{ startcopy, --to be deactivated number_of_node, --to be deactivated copy_for_image_input, --to be deactivated copy_for_image_function, --to be deactivated define_function_of_node, --to be deactivated copy_for_image_output, --to be deactivated renamenode, --to be deactivated addbranch, --to be deactivated addbranchbottom, --to be deactivated addleaf, --to be deactivated addleafbottom, --to be deactivated startversion, startnodescripter, startnode, } --5.1 menu of tree end --6 buttons --6.1 logo image definition and button wiht logo img_logo = iup.image{ { 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,3,3,1,1,3,3,3,1,1,1,1,1,3,1,1,1,3,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,3,3,1,1,3,1,1,3,1,1,1,1,3,1,1,3,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,3,3,3,3,1,1,1,1,1,3,1,1,3,1,1,1,1,3,1,3,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,3,3,3,4,4,3,1,1,1,1,3,3,3,3,1,1,1,1,3,3,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,3,3,3,3,4,4,3,3,1,1,1,3,1,1,1,3,1,1,1,3,1,3,1,1,1,1,1,1,4,4,4 }, { 4,1,1,3,3,3,3,3,3,3,3,1,1,1,3,1,1,1,3,1,1,1,3,1,1,3,1,1,1,1,1,4,4,4 }, { 4,1,1,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,1,1,3,1,3,1,1,1,3,1,3,1,1,4,4,4 }, { 4,1,1,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,1,3,1,3,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,1,1,1,1,4,1,1,1,1,1,3,1,3,3,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,1,1,1,4,4,4,4,1,1,3,3,1,3,1,3,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,1,1,4,4,4,4,4,4,4,1,1,3,3,1,3,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,1,1,1,4,4,4,4,4,3,3,4,4,4,4,1,3,3,1,1,1,1,1,1,1,4,4,4,4 }, { 4,1,1,1,1,1,1,1,4,4,4,4,3,3,3,3,3,3,4,4,4,3,1,1,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,1,4,4,4,4,4,3,3,3,3,3,3,3,3,3,4,3,4,1,1,1,1,1,1,1,1,4,4,4 }, { 4,1,1,1,1,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,1,1,1,1,1,1,4,4,4 }, { 4,1,1,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,1,1,1,1,1,4,4,4 }, { 4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,1,1,1,4,4,4 }, { 4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,1,1,4,4,4 }, { 4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,4,4,4 }, { 4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4 }, { 4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4 }, { 4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4 }, { 4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3 }, { 4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4 }, { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4 }, { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4 }, { 3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4 }, { 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4 } ; colors = { color_grey_bpc, color_light_color_grey_bpc, color_blue_bpc, "255 255 255" } } button_logo=iup.button{image=img_logo,title="", size="23x20"} function button_logo:action() iup.Message("Beckmann & Partner CONSULT","BERATUNGSMANUFAKTUR\nMeisenstraße 79\n33607 Bielefeld\nDr. Bruno Kaiser\nLizenz Open Source") end --function button_logo:flat_action() --6.2 button to edit in IUP Lua scripter the script for tree2 button_edit_treescript=iup.flatbutton{title="Programmieren des \ngesamten Programms", size="85x20", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function button_edit_treescript:flat_action() os.execute('start "d" C:\\Lua\\iupluascripter54.exe "' .. path .. '\\' .. thisfilename .. '"') end --function button_edit_treescript:flat_action() --6.3 button to edit the icon definition list button_edit_icon_list=iup.flatbutton{title="Programmieren der \nSymbole", size="75x20", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function button_edit_icon_list:flat_action() dlg_icon_rename:showxy(iup.RIGHT, iup.CENTER) --show rename dialog end --function button_edit_icon_list:flat_action() --6.4 button to edit the relation table for node to function button_edit_nodeFunctionTable=iup.flatbutton{title="Programmieren der \nFunktionszuordnung zu den Knoten", size="135x20", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function button_edit_nodeFunctionTable:flat_action() dlg_nodeFunctionTable_rename:showxy(iup.RIGHT, iup.CENTER) --show rename dialog end --function button_edit_nodeFunctionTable:flat_action() --6.5 button to save version without buttons and menus to be fixed calculation button_save_fixed_calculation=iup.flatbutton{title="Speichern einer\nfixierten Version", size="85x20", BGCOLOR=color_buttons, FGCOLOR=color_button_text} function button_save_fixed_calculation:flat_action() --open a filedialog filedlg1=iup.filedlg{dialogtype="SAVE",title="Ziel auswählen",filter="*.lua",filterinfo="Lua Files", directory=path} filedlg1:popup(iup.ANYWHERE,iup.ANYWHERE) if filedlg1.status=="1" or filedlg1.status=="0" then local outputfile=io.output(filedlg1.value) --setting the outputfile for line in io.lines(path .. "\\" .. thisfilename) do if line:match("%-%-to be deactivated") then outputfile:write("--deactivated: " .. line .. "\n") elseif line:match("%-%-%[%[to be deactivated%]%]") then outputfile:write("--[====[deactivated: " .. line .. "\n") elseif line:match("%-%-%[%[to be deactivated end%]%]") then outputfile:write(line .. "\n--deactivated end]====]\n") else outputfile:write(line .. "\n") end --if line:match("%-%-to be deactivated") then end --for line in io.lines(path .. "\\" .. thisfilename) do outputfile:close() --close the outputfile else --no outputfile was choosen iup.Message("Schließen","Keine Datei ausgewählt") iup.NextField(maindlg) end --if filedlg1.status=="1" or filedlg1.status=="0" then end --function button_save_fixed_calculation:flat_action() --7 Main Dialog --7.1 icon definitions img_functionarrow= iup.image{ { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,2,2,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,1,1,2,1,1,1,1,1,1 }, { 1,1,1,1,1,2,2,1,1,2,2,1,1,1,1,1 }, { 1,1,1,1,2,2,1,1,1,1,2,2,1,1,1,1 }, { 1,1,1,1,2,2,1,1,1,1,2,2,1,1,1,1 }, { 1,1,1,1,2,2,1,1,1,1,2,2,1,1,1,1 }, { 1,1,1,1,2,2,1,1,1,1,2,2,1,1,1,1 }, { 1,1,1,1,2,2,1,1,1,1,2,2,1,1,1,1 }, { 1,1,1,1,2,2,1,1,1,1,2,2,1,1,1,1 }, { 1,1,1,1,1,2,2,1,1,2,2,1,1,1,1,1 }, { 1,1,1,1,1,1,2,1,1,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,2,2,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 } -- Sets "X" image colors ; colors = { color_background_tree, color_red_bpc} } img_inputarrow= iup.image{ { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,2,2,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,2,2,2,2,2,2,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,2,2,2,2,2,2,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,2,2,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 } -- Sets "X" image colors ; colors = { color_background_tree, color_red_bpc} } img_rightarrow= iup.image{ { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,2,2,2,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,2,2,2,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,2,2,2,1,1,1 }, { 1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,1 }, { 1,1,2,2,2,2,2,2,2,2,2,2,2,2,1,1 }, { 1,1,1,1,1,1,1,1,1,1,2,2,2,1,1,1 }, { 1,1,1,1,1,1,1,1,1,2,2,2,1,1,1,1 }, { 1,1,1,1,1,1,1,1,2,2,2,1,1,1,1,1 }, { 1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1 }, { 1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 }, { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 } -- Sets "X" image colors ; colors = { color_background_tree, color_red_bpc} } --7.2 build tree tree=iup.tree{ map_cb=function(self) self:AddNodes(actualtree) end, --function(self) SIZE="10x200", showrename="YES",--F2 key active markmode="SINGLE",--for Drag & Drop SINGLE not MULTIPLE --showdragdrop="YES", } -- Callback for pressed keys function tree:k_any(c) if c == iup.K_DEL then --[[to be deactivated]] if tree.childcount=="0" then local treeValue=tree.value --test with: print(tree.value) --save copy of program os.execute('copy "' .. path .. "\\" .. thisfilename .. '" "' .. path .. "\\" .. thisfilename:gsub("%.lua","_Sicherung.lua") .. '"') --test with: iup.Message(tree.childcount,tree.childcount) tree.delnode = "SELECTED" --test with: iup.Message(tree.count,tree.value) --store the programm in the lua table outputfile1Table local startWriteProgramm="no" local outputfile1Table={} for line in io.lines(path .. "\\" .. thisfilename) do --test with: print(tree.value) if startWriteProgramm=="yes" then local digitTable={} for field in line:gmatch("tree%['[^%d]+%d+'%]") do digitTable[#digitTable+1]=field end --for field in line:gmatch("tree%['[^%d]+%d+'%]") do table.sort(digitTable,function(a,b) local ad=tonumber(a:match("%d+")) bd=tonumber(b:match("%d+")) return ad<bd end) for i,v in ipairs(digitTable) do local vMatch=v:gsub("%[","%%["):gsub("%]","%%]"):gsub("%(","%%("):gsub("%)","%%)"):gsub("%-","%%-"):gsub("%*","%%*"):gsub("%+","%%+") --test with: print(i,v) local treeType,digitText=v:match("'([^%d]+)(%d+)'") --test with: print(treeType,digitText) --test with: print(treeValue,digitText) if tonumber(digitText)>tonumber(treeValue) then --test with: print(line) print(vMatch) line=line:gsub(vMatch,"tree['" .. treeType .. math.tointeger(tonumber(digitText-1)) .. "']") --test with: print("tree['" .. treeType .. math.tointeger(tonumber(digitText-1)) .. "']") print(line) elseif digitText==treeValue then --test with: print(line) print(vMatch) line=line:gsub(vMatch,"tree['" .. treeType .. digitText .. "xxx']") --test with: print("tree['" .. treeType .. math.tointeger(tonumber(digitText-1)) .. "']") print(line) end --if tonumber(digitText)>=tonumber(treeValue) then end --for i,v in ipairs(digitTable) d outputfile1Table[#outputfile1Table+1]=line end --if startWriteProgramm=="yes" then if line:match("%-%-actualtree" .. "=") then startWriteProgramm="yes" end end --for line in io.lines(path .. "\\" .. thisfilename) do --save the tree save_tree_to_lua(tree, path .. "\\" .. thisfilename) --save the programm stored in the lua table outputfile1Table local outputfile1=io.open(path .. "\\" .. thisfilename,"a") for i,v in ipairs(outputfile1Table) do outputfile1:write(v .. "\n") end --for i,v in ipairs(outputfile1Table) do outputfile1:close() end --if tree.childcount=="0" then os.execute('start "Neu" "' .. path .. "\\" .. thisfilename .. '"') return iup.CLOSE --[[to be deactivated end]] elseif c == iup.K_cC then --copy node of tree clipboard.text = tree['title'] elseif c == iup.K_Menu then menu:popup(iup.MOUSEPOS,iup.MOUSEPOS) --popup the defined menue end --if c == iup.K_DEL then end --function tree:k_any(c) -- Callback for right click preparing by node function table --nodeFunctionTablefunction table --nodeFunctionTable["node name"]="name_of_the_function()" nodeFunctionTable={} --nodeFunctionTable["Knotentext eingeben"]="Name_der_Funktion()" nodeFunctionTable["Ausgabe"]="Schaltjahr()" nodeFunctionTable["Anzahl Tage Zähler 30 und Nenner 360"]="Anzahltage30zaehler()" nodeFunctionTable["Anzahl Tage Zähler 30ISDA und Nenner 360"]="Anzahltage30ISDAzaehler()" nodeFunctionTable["Anzahl Tage Zähler 30E und Nenner 360"]="Anzahltage30Ezaehler()" nodeFunctionTable["Anzahl Tage Zähler 30E+ und Nenner 360"]="Anzahltage30EPluszaehler()" nodeFunctionTable["Anzahl Tage Zähler 30German und Nenner 360"]="Anzahltage30Germanzaehler()" nodeFunctionTable["Anzahl Tage Zähler 30US und Nenner 360"]="Anzahltage30USzaehler()" nodeFunctionTable["Anzahl Tage Zähler actual und Nenner für actual im Weiteren Knoten bestimmen"]="Anzahltagezaehler()" nodeFunctionTable["Nenner actual 365.25 1/1"]="Nenneractual36525()" nodeFunctionTable["Nenner actual 366"]="Nenneractual366()" nodeFunctionTable["Nenner actual 365"]="Nenneractual365()" nodeFunctionTable["Nenner actual 364"]="Nenneractual364()" nodeFunctionTable["Nenner actual 360"]="Nenneractual360()" nodeFunctionTable["Jahre manuell setzen"]="JahreManuellSetzen()" nodeFunctionTable["Kapital und Zinssatz eintragen"]="KapitalZinssatzSchreiben()" nodeFunctionTable["Alle Zinsen mit Titel ausgeben"]="ZinsenTitelAlle()" nodeFunctionTable["Titel"]="TitelErgaenzen()" nodeFunctionTable["Zinsen linear = Kapital * Zinssatz * Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner"]="Zinsen()" nodeFunctionTable["Zinsen mit Zinseszinsen = Kapital * ((1+Zinssatz)^(Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner)-1)"]="Zinseszinsen()" nodeFunctionTable["Zinsen stetig verzinst = Kapital * (e^(Zinssatz * Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner) -1)"]="Zinsenstetig()" nodeFunctionTable["Alle Zinsen mit Titel in eine Datei ausgeben"]="ZinsErgebnisAlleZeilenAusgabe()" nodeFunctionTable["Zurücksetzen"]="KapitalZinssatzZuruecksetzen()" --end nodeFunctionTable["node name"]="name_of_the_function()" --Callback for right click function tree:rightclick_cb(id) if nodeFunctionTable[tree['title']] then load(nodeFunctionTable[tree['title']])() elseif functionTable[tree['title']] then functionTable[tree['title']]() --test with: print(tree['title']) else menu:popup(iup.MOUSEPOS,iup.MOUSEPOS) --popup the defined menue end --if tree['title']=="Berechnen" then end --function tree:rightclick_cb(id) --7.3 building the dialog and put buttons, trees and preview together maindlg = iup.dialog { iup.scrollbox{iup.vbox{ iup.hbox{ button_logo, button_edit_treescript, --to be deactivated button_edit_icon_list, --to be deactivated button_edit_nodeFunctionTable, --to be deactivated button_save_fixed_calculation, --to be deactivated }, iup.frame{title="Zinsrechner", tree, size="FULLxFULL"}, },}, --iup.scrollbox{iup.vbox{ icon = img_logo, size="HALFxFULL", --"FULLxFULL", --gap="3", --alignment="ARIGHT", --margin="5x5" }--maindlg = iup.dialog { --7.4 show the dialog maindlg:showxy(iup.LEFT,iup.CENTER) --7.5 icons adopted in tree --default image for branch collapsed can be defined by: tree.imagebranchcollapsed=img_rightarrow --tree['image... default image for branch expanded --tree['image... image for branches with functions tree['imageexpanded4']=img_functionarrow --Berechnen Rechner() tree['imageexpanded9']=img_functionarrow --Ausgabe Schaltjahr() tree['imageexpanded23']=img_functionarrow tree['image23']=img_functionarrow --Schalttage im Zins-Intervall bestimmen tree['imageexpanded32']=img_functionarrow --Anzahl Tage Zähler 30 und Nenner 360 Anzahltage30zaehler() tree['imageexpanded38']=img_functionarrow --Anzahl Tage Zähler 30ISDA und Nenner 360 Anzahltage30ISDAzaehler() tree['imageexpanded44']=img_functionarrow --Anzahl Tage Zähler 30E und Nenner 360 Anzahltage30Ezaehler() tree['imageexpanded54']=img_functionarrow --Anzahl Tage Zähler 30E+ und Nenner 360 Anzahltage30EPluszaehler() tree['imageexpanded60']=img_functionarrow --Anzahl Tage Zähler 30German und Nenner 360 Anzahltage30Germanzaehler() tree['imageexpanded68']=img_functionarrow --Anzahl Tage Zähler 30US und Nenner 360 Anzahltage30USzaehler() tree['imageexpanded71']=img_functionarrow --Anzahl Tage Zähler actual und Nenner für actual im Weiteren Knoten bestimmen Anzahltagezaehler() tree['imageexpanded81']=img_functionarrow --Nenner actual 365.25 1/1 Nenneractual36525() tree['imageexpanded85']=img_functionarrow --Nenner actual 366 Nenneractual366() tree['imageexpanded91']=img_functionarrow --Nenner actual 365 Nenneractual365() tree['imageexpanded96']=img_functionarrow --Nenner actual 364 Nenneractual364() tree['imageexpanded102']=img_functionarrow --Nenner actual 360 Nenneractual360() tree['imageexpanded108']=img_functionarrow --Jahre manuell setzen JahreManuellSetzen() tree['image108']=img_functionarrow --Jahre manuell setzen JahreManuellSetzen() tree['imageexpanded114']=img_functionarrow --Kapital und Zinssatz eintragen KapitalZinssatzSchreiben() tree['imageexpanded115']=img_functionarrow --Alle Zinsen mit Titel ausgeben ZinsenTitelAlle() tree['imageexpanded116']=img_functionarrow --Titel TitelErgaenzen() tree['imageexpanded118']=img_functionarrow --Zinsen linear = Kapital * Zinssatz * Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner Zinsen() tree['imageexpanded120']=img_functionarrow --Zinsen mit Zinseszinsen = Kapital * ((1+Zinssatz)^(Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner)-1) Zinseszinsen() tree['imageexpanded122']=img_functionarrow --Zinsen stetig verzinst = Kapital * (e^(Zinssatz * Anzahl_Tage_Zaehler / Anzahl_Tage_Nenner) -1) Zinsenstetig() tree['imageexpanded124']=img_functionarrow --Alle Zinsen mit Titel in eine Datei ausgeben ZinsErgebnisAlleZeilenAusgabe() tree['imageexpanded126']=img_functionarrow --Zurücksetzen KapitalZinssatzZuruecksetzen() tree['image126']=img_functionarrow --Zurücksetzen KapitalZinssatzZuruecksetzen() --tree['image... input and output nodes tree['image3']=img_inputarrow --document.Formular.Eingabe.value tree['image5']=img_rightarrow --document.Formular.Ergebnis.value tree['image8']=img_inputarrow --document.Formular1.Eingabe3.value tree['image10']=img_rightarrow --document.Formular1.ErgebnisSchaltjahr.value tree['image13']=img_inputarrow --document.FormularZins.Kapital.value tree['image14']=img_inputarrow --document.FormularZins.Zinssatz.value tree['image16']=img_inputarrow --document.FormularZins.Startmonat.value tree['image18']=img_inputarrow --document.FormularZins.ManuellLastDayFebruary1.value tree['image20']=img_inputarrow --document.FormularZins.Endemonat.value tree['image22']=img_inputarrow --document.FormularZins.ManuellLastDayFebruary2.value tree['image24']=img_rightarrow --Schalttage im Zins-Intervall bestimmen tree['image33']=img_rightarrow --document.FormularZins.Anzahltage30.value tree['image39']=img_rightarrow --document.FormularZins.Anzahltage30ISDA.value tree['image45']=img_rightarrow --document.FormularZins.Anzahltage30E.value tree['image51']=img_inputarrow --document.FormularZins.EndejahrPlus.value tree['image52']=img_inputarrow --document.FormularZins.EndemonatPlus.value tree['image53']=img_inputarrow --document.FormularZins.EndetagPlus.value tree['image55']=img_rightarrow --document.FormularZins.Anzahltage30EPlus.value tree['image61']=img_rightarrow --document.FormularZins.Anzahltage30German.value tree['image69']=img_rightarrow --document.FormularZins.Anzahltage30US.value tree['image72']=img_rightarrow --document.FormularZins.Anzahltageactual.value tree['image74']=img_inputarrow --document.FormularZins.AnzahltageNoLeap.value tree['image76']=img_rightarrow --document.FormularZins.AnzahlTageZaehler.value tree['image82']=img_rightarrow --document.FormularZins.Nenner36525.value tree['image86']=img_rightarrow --document.FormularZins.Nenner366.value tree['image92']=img_rightarrow --document.FormularZins.Nenner365.value tree['image97']=img_rightarrow --document.FormularZins.Nenner364.value tree['image103']=img_rightarrow --document.FormularZins.Nenner360.value tree['image105']=img_rightarrow --document.FormularZins.AnzahlTageNenner.value tree['image107']=img_inputarrow --document.FormularZins.JahreManuelleEingabe.value tree['image110']=img_rightarrow --document.FormularZins.Jahre.value tree['image112']=img_rightarrow --document.FormularZins.Methode.value tree['image117']=img_rightarrow --document.FormularZins.Titel.value tree['image119']=img_rightarrow --document.FormularZins.Zins.value tree['image121']=img_rightarrow --document.FormularZins.Zinszins.value tree['image123']=img_rightarrow --document.FormularZins.Zinsstetig.value --7.6 Main Loop if (iup.MainLoopLevel()==0) then iup.MainLoop() end
slot2 = "CheckGameSilenceDownloadBean" CheckGameSilenceDownloadBean = class(slot1) CheckGameSilenceDownloadBean.ctor = function (slot0) slot4 = AbstractBean ClassUtil.extends(slot2, slot0) end CheckGameSilenceDownloadBean.start = function (slot0) if IS_TEST_PACKAGE_DOWNLOAD then slot3 = slot0 slot0.finish(slot2) else slot3 = gameMgr gameMgr.checkPackageSilenceQueue(slot2) end slot3 = slot0 slot0.finish(slot2) end return
--[[ File name: forge.lua Description: weapon system, this SHOULD NOT be used for items. For items look at "pine" Author: oldmilk --]] local forge = {} -- defaults local forgeDefaults = { defaultDamage = { min = 10, max = 30 } } local playerStats = require(game.ReplicatedStorage:WaitForChild("modules").playerStat) -- core functions -- loadAnimation: loads an animation onto the players humanoid, and returns the animation track function loadAnimation(player, id) -- check for animator local animator = nil if player.Character.Humanoid:FindFirstChildOfClass("Animator") == nil then animator = Instance.new("Animator") else animator = player.Character.Humanoid:FindFirstChildOfClass("Animator") end -- build animation local animationBuild = Instance.new("Animation") animationBuild.AnimationId = "rbxassetid://"..id -- load the animation local animationTrack = animator:LoadAnimation(animationBuild) return animationTrack end local forgeClass = {} forgeClass.__index = forgeClass forgeClass.config = {} forgeClass.tool = nil -- getValue: get a value from inside the config function forgeClass:getValue(key) local config = self.config if config[key] == nil then warn("key not found in config table.") return nil else return config[key] end end -- setValue: set a value inside of the config function forgeClass:setValue(key, value) if self.config[key] ~= nil then warn("data overwrited.") end -- Write damage config into tool if key == "damage" then if value.min ~= nil then self.tool:SetAttribute("damageMax", value.max) end if value.min ~= nil then self.tool:SetAttribute("damageMin", value.min) end end self.config[key] = value end -- swing: swing the tool function forgeClass:swing() -- prep everything before we do any tool animations/damage -- check for the player if self:getValue("owner") == nil then error("Failed to swing: owner of tool is nil!") end local player = self:getValue("owner") -- look for the swing animation local config = self.config local animations = self:getValue("animations") if animations == nil then warn("no tool animations found in config.") end -- check for damage config local damageConfig = self:getValue("damage") if damageConfig == nil then warn("damageConfig is nil, using default value") damageConfig = forgeDefaults.defaultDamage end -- look for the handle in the tool local tool = self.tool if tool:FindFirstChild("Handle") == nil then error("The weapon must have a handle, for items please use pine.") end -- play animations if tool:GetAttribute("coolDownEnabled") == nil then tool:SetAttribute("coolDownEnabled", true) else return end if animations ~= nil then local track = loadAnimation(player, animations[forge.enums.animationTypes.ItemUse]) track:Play() end local currentStats = playerStats.getStatPoints(player) local strPoints = currentStats.str local damagePerPoint = 6 local damageAdd = strPoints * damagePerPoint -- do da math -- NOTE: Only boost the min damage, cause if we boost the max then any weapon can become OP local minDamage = damageConfig.min + damageAdd -- Prevent bug if (damageConfig.min + damageAdd) > damageConfig.max then minDamage = damageConfig.max - 1 end local maxDamage = damageConfig.max -- check if server pvp is enabled. local serverPvpEnabled = game.ServerStorage:FindFirstChild("pvpEnabled") -- calculate the damage in the range of maxDamage, and minDamage local damageCalc = math.random(minDamage, maxDamage) local toolConnect = tool.Handle.Touched:Connect(function (hit) -- check if the thing we hit has a humanoid if hit.Parent:FindFirstChildOfClass("Humanoid") ~= nil then -- pvp checks local hitPlayer = game.Players:GetPlayerFromCharacter(hit.Parent) if hitPlayer ~= nil then if serverPvpEnabled ~= nil then hitPlayer.Character.Humanoid:TakeDamage(damageCalc) else warn("global pvp is disabled, to enable it create a item inside of ServerStorage named 'pvpEnabled'") end else tool:SetAttribute("coolDownEnabled", true) local killers = hit.Parent:FindFirstChild("killers") if killers == nil then killers = Instance.new("Folder") killers.Name = "killers" killers.Parent = hit.Parent end if killers:FindFirstChild(player.Name) == nil then local killerTag = Instance.new("StringValue") killerTag.Name = player.Name killerTag.Value = player.Name killerTag.Parent = killers end hit.Parent.Humanoid:TakeDamage(damageCalc) end end end) task.wait(0.1) -- give some time for the player to hit the target tool:SetAttribute("coolDownEnabled", nil) -- remove the event from memory toolConnect:Disconnect() end forge.enums = {} forge.enums.animationTypes = { ["Idle"] = "AnimationIdle", ["ItemUse"] = "AnimationUse" } -- register: returns a new instance of the forge class forge.register = function(tool) local self = { tool = tool } tool:SetAttribute("isForgeWeapon", true) setmetatable(self, forgeClass) return self end return forge
-- Project: OiL - ORB in Lua -- Release: 0.6 -- Title : Factory of outgoing (client-side) channels -- Authors: Renato Maia <maia@inf.puc-rio.br> local _G = require "_G" --[[VERBOSE]] local verbose = require "oil.verbose" local pairs = _G.pairs local coroutine = require "coroutine" local running = coroutine.running local yield = coroutine.yield local oo = require "oil.oo" local class = oo.class local Connector = require "oil.kernel.base.Connector" local connectto = Connector.connectto local CoConnector = class({}, Connector) function CoConnector:__init() self.pending = {} end function CoConnector:connectto(connid, ...) if connid == nil then return nil, (...) end local pending = self.pending local threads = pending[connid] if threads ~= nil then --[[VERBOSE]] verbose:channels("connection to channel in progress, wait completion") threads[running()] = true return yield("suspend") end threads = {} pending[connid] = threads local socket, except = connectto(self, connid, ...) pending[connid] = nil for thread in pairs(threads) do yield("next", thread, socket, except) end return socket, except end return CoConnector
-- default mcl_beacon colors mcl_beacon.register_color("White", "#ffffffff", "mcl_dye:white") mcl_beacon.register_color("Black", "#0f0f0fff", "mcl_dye:black") mcl_beacon.register_color("Blue", "#0000ffff", "mcl_dye:blue") mcl_beacon.register_color("Cyan", "#00ffffff", "mcl_dye:cyan") mcl_beacon.register_color("Green", "#00ff00ff", "mcl_dye:green") mcl_beacon.register_color("Magenta", "#ff00ffff", "mcl_dye:magenta") mcl_beacon.register_color("Orange", "#ff8000ff", "mcl_dye:orange") mcl_beacon.register_color("Red", "#ff0000ff", "mcl_dye:red") mcl_beacon.register_color("Violet", "#8f00ffff", "mcl_dye:violet") mcl_beacon.register_color("Yellow", "#ffff00ff", "mcl_dye:yellow") -- base mcl_beacon recipe minetest.register_craft({ output = "mcl_beacon:white", recipe = { {"mcl_core:glass", "mcl_core:glass", "mcl_core:glass"}, {"mcl_core:glass", "mcl_mobitems:nether_star", "mcl_core:glass"}, {"mcl_core:obsidian", "mcl_core:obsidian", "mcl_core:obsidian"}, } }) -- floating beam cleanup minetest.register_lbm({ label = "Floating mcl_beacon beam cleanup", name = "mcl_beacon:beam_cleanup", nodenames = {"group:mcl_beacon_beam"}, run_at_every_load = true, action = function(pos, node) local under_pos = vector.add(pos, mcl_beacon.param2_to_under[node.param2]) if mcl_beacon.is_airlike_node(under_pos) then minetest.set_node(pos, { name = "air" }) end end, }) -- purple is named violet now minetest.register_alias("mcl_beacon:purplebeam", "mcl_beacon:violetbeam") minetest.register_alias("mcl_beacon:purplebase", "mcl_beacon:violetbase") minetest.register_alias("mcl_beacon:purple", "mcl_beacon:violet") -- no empty/unactivated mcl_beacon minetest.register_alias("mcl_beacon:empty", "mcl_beacon:white")
-- test_get_font_list.lua package.path = package.path..";../?.lua" local ffi = require("ffi") local caca_ffi = require("caca_ffi")() local Lib_caca = caca_ffi.Lib_caca; local function printFontInfo(name, font) print("==== printFontInfo ====") print(name); local width = caca_get_font_width(font); local height = caca_get_font_height(font); print(string.format("Size: %dx%d", width, height)); end local function fontNameList() local fonts = caca_get_font_list(); local idx = -1; local function closure() idx = idx + 1; if fonts[idx] == nil then return nil; end return ffi.string(fonts[idx]); end return closure; end local function fontList() local fontNames = caca_get_font_list(); local idx = -1; local function closure() idx = idx + 1; if fontNames[idx] == nil then return nil; end local font = caca_load_font(fontNames[idx], 0); ffi.gc(font, caca_free_font); return font, ffi.string(fontNames[idx]); end return closure; end local function test_list_font_info() for font, fontName in fontList() do printFontInfo(fontName, font); end end local function test_list_font_names() for fontName in fontNameList() do print(fontName); end end test_list_font_names(); test_list_font_info();
-- optimised param2 rotation functions. -- please note, these were machine generated. local rotation_functions = {} rotation_functions[0] = function(v) return { x = v.x, y = v.y, z = v.z, } end rotation_functions[1] = function(v) return { x = v.z, y = v.y, z = ( -v.x ), } end rotation_functions[2] = function(v) return { x = ( -v.x ), y = v.y, z = ( -v.z ), } end rotation_functions[3] = function(v) return { x = ( -v.z ), y = v.y, z = v.x, } end rotation_functions[4] = function(v) return { x = v.x, y = ( -v.z ), z = v.y, } end rotation_functions[5] = function(v) return { x = v.z, y = v.x, z = v.y, } end rotation_functions[6] = function(v) return { x = ( -v.x ), y = v.z, z = v.y, } end rotation_functions[7] = function(v) return { x = ( -v.z ), y = ( -v.x ), z = v.y, } end rotation_functions[8] = function(v) return { x = v.x, y = v.z, z = ( -v.y ), } end rotation_functions[9] = function(v) return { x = v.z, y = ( -v.x ), z = ( -v.y ), } end rotation_functions[10] = function(v) return { x = ( -v.x ), y = ( -v.z ), z = ( -v.y ), } end rotation_functions[11] = function(v) return { x = ( -v.z ), y = v.x, z = ( -v.y ), } end rotation_functions[12] = function(v) return { x = v.y, y = ( -v.x ), z = v.z, } end rotation_functions[13] = function(v) return { x = v.y, y = ( -v.z ), z = ( -v.x ), } end rotation_functions[14] = function(v) return { x = v.y, y = v.x, z = ( -v.z ), } end rotation_functions[15] = function(v) return { x = v.y, y = v.z, z = v.x, } end rotation_functions[16] = function(v) return { x = ( -v.y ), y = v.x, z = v.z, } end rotation_functions[17] = function(v) return { x = ( -v.y ), y = v.z, z = ( -v.x ), } end rotation_functions[18] = function(v) return { x = ( -v.y ), y = ( -v.x ), z = ( -v.z ), } end rotation_functions[19] = function(v) return { x = ( -v.y ), y = ( -v.z ), z = v.x, } end rotation_functions[20] = function(v) return { x = ( -v.x ), y = ( -v.y ), z = v.z, } end rotation_functions[21] = function(v) return { x = ( -v.z ), y = ( -v.y ), z = ( -v.x ), } end rotation_functions[22] = function(v) return { x = v.x, y = ( -v.y ), z = ( -v.z ), } end rotation_functions[23] = function(v) return { x = v.z, y = ( -v.y ), z = v.x, } end return { funcs = rotation_functions, }
require("user.options") require("user.keymaps") require("user.plugins") require("user.colorscheme") require("user.cmp") require("user.lsp") require("user.telescope") require("user.treesitter") require("user.autopairs") require("user.comment") require("user.gitsigns") require("user.nvim-tree") require("user.bufferline") require("user.lualine") require("user.toggleterm") require("user.project") require("user.impatient") require("user.indentline") require("user.alpha") require("user.whichkey") require("user.autocommands") --require("user.wilder") require("user.autosave") require("user.languagetool") --require("user.prosesitter") require("grammar-guard").init() require("user.bullets") require("user.notify") require("user.trouble") require("user.twilight") require("user.zen-mode") require("user.zk-nvim") require("user.pywal") --vim.g.tq_enabled_backends = { "openoffice_en", "mthesaur_txt" } --vim.g.tq_mthesaur_file = { "~/.config/nvim/thesaurus/mthesaur.txt" } ---vim.g.tq_language = { "en" } --
-- Lua require('lsp.servers.sunmeko') -- Python require('lsp.servers.pyright') -- JavaScript require('lsp.servers.tsserver') --require('lsp.servers.eslint_d') -- General Lenguage Server require('lsp.servers.efm') -- Vimscript require("lsp.servers.vim")
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by Administrator. --- DateTime: 2018/6/23 20:17 --- local windowsBase = require("Core.WindowBase") local fgui = require("FGUI.FairyGUI") local yk = require("Core.YK") ---@class TestWind :WindowBase local this= yk.wind_class(windowsBase) function this:ctor(ins) self.resName = "LoginWindow" self.packName = "LoadingScenePack" self.isNeedHideAnimation = false self.isNeedShowAnimation = false print(self.resName) ---@type FairyGUI.GComponent local url = fgui.UIPackage.GetItemURL(self.packName,"TestLogin") fgui.register_extension(url,require("Game.ext.Test")) end function this:OnInit() --local test = self.Objs.TestLogin ---@type test --test:test() end function this:OnShown(param) end function this:OnBtnClick(btn) print(btn.sender.name) end return this
local Suite = CreateTestSuite("fritomod.Ordering"); function Suite:TestOrdering() local o = Ordering:New(); o:Order("A", "B", "D", "C", "E", "F", "G"); o:Order("C", "D", "G"); Assert.Equals( {"A", "B", "C", "D", "E", "F", "G"}, o:Get()); end; function Suite:TestOrderingWithEqualHead() local o = Ordering:New(); o:Order("A", "B", "C", "D", "E", "F", "G"); o:Order("A", "B", "C"); Assert.Equals( {"A", "B", "C", "D", "E", "F", "G"}, o:Get()); end; function Suite:TestOrderingWithEqualTail() local o = Ordering:New(); o:Order("A", "B", "C", "D", "E", "F", "G"); o:Order("E", "F", "G"); Assert.Equals( {"A", "B", "C", "D", "E", "F", "G"}, o:Get()); end; function Suite:TestOrderingWithTail() local o = Ordering:New(); o:Order("A", "B", "C", "D"); o:Order("E", "F", "G"); Assert.Equals( {"A", "B", "C", "D", "E", "F", "G"}, o:Get()); end;
local TRAIL_EFFECT = Idstring("effects/particles/weapons/sniper_trail") local idstr_trail = Idstring("trail") local idstr_simulator_length = Idstring("simulator_length") local idstr_size = Idstring("size") local trail_length function SniperGrazeDamage:on_wunderwaffe_fired(weapon_unit, result) if not alive(weapon_unit) then return end local player_unit = managers.player:player_unit() if not player_unit then return end if weapon_unit ~= managers.player:equipped_weapon_unit() then return end if weapon_unit:base():get_name_id() ~= "wunderwaffe_primary" and weapon_unit:base():get_name_id() ~= "wunderwaffe_secondary" and weapon_unit:base():get_name_id() ~= "wunderwaffe_dg3_primary" and weapon_unit:base():get_name_id() ~= "wunderwaffe_dg3_secondary" then return end local bumps = 10 local timer_between = 0.5 if weapon_unit:base():get_name_id() == "wunderwaffe_dg3_primary" or weapon_unit:base():get_name_id() == "wunderwaffe_dg3_secondary" then bumps = 15 timer_between = 0.25 end local upgrade_value = managers.player:upgrade_value("snp", "graze_damage") local sentry_mask = managers.slot:get_mask("sentry_gun") local ally_mask = managers.slot:get_mask("all_criminals") local enemy_mask = managers.slot:get_mask("enemies") local geometry_mask = managers.slot:get_mask("world_geometry") local hit_enemies = {} local ignored_enemies = {} for _, hit in ipairs(result.rays) do local is_turret = hit.unit:in_slot(sentry_mask) local is_ally = hit.unit:in_slot(ally_mask) local result = hit.damage_result local attack_data = result and result.attack_data if attack_data and not is_turret and not is_ally then local multiplier = 1 local key = hit.unit:key() hit_enemies[key] = { position = hit.position, damage = 125000 } ignored_enemies[key] = true end end local radius = 800 for _, hit in pairs(hit_enemies) do self:find_wunderwaffe_closest_hit(hit, ignored_enemies, upgrade_value, enemy_mask, geometry_mask, player_unit, bumps, timer_between) end end function SniperGrazeDamage:find_wunderwaffe_closest_hit(hit, ignored_enemies, upgrade_value, enemy_mask, geometry_mask, player_unit, times, timer_between) if times <= 0 then return end if times == 7 or times == 12 then local tbl_spree_soundbank = { "wunderwaffe_spree", "wunderwaffe_spree2" } local sound_wunderspree = SoundDevice:create_source("WunderwaffeSpree") sound_wunderspree:set_position(managers.player:player_unit():position()) sound_wunderspree:post_event(tbl_spree_soundbank [ math.random( #tbl_spree_soundbank ) ]) end local hit_units = World:find_units_quick("sphere", hit.position, 800, enemy_mask) local closest local closest_d_sq for _, unit in ipairs(hit_units) do if not ignored_enemies[unit:key()] then local d_s = mvector3.distance_sq(hit.position, unit:movement():m_head_pos()) if not closest_d_sq or d_s < closest_d_sq then if not World:raycast("ray", hit.position, unit:movement():m_head_pos(), "slot_mask", geometry_mask) then closest = unit closest_d_sq = d_s end end end end if closest then ignored_enemies[closest:key()] = true local hit_pos = Vector3() mvector3.set(hit_pos, closest:movement():m_head_pos()) if not trail_length then trail_length = World:effect_manager():get_initial_simulator_var_vector2(TRAIL_EFFECT, idstr_trail, idstr_simulator_length, idstr_size) end local trail = World:effect_manager():spawn({ effect = Idstring("effects/payday2/particles/character/taser_stop"), position = hit.position, normal = hit_pos - hit.position }) local sound_wunderhit = SoundDevice:create_source("WunderwaffeHit") sound_wunderhit:set_position(hit.position) sound_wunderhit:post_event("wunderwaffe_hit") mvector3.set_y(trail_length, math.sqrt(closest_d_sq)) World:effect_manager():set_simulator_var_vector2(trail, idstr_trail, idstr_simulator_length, idstr_size, trail_length) DelayedCalls:Add("grazehit" .. tostring(closest), timer_between, function () if not alive(closest) or not alive(player_unit) then return end local result = closest:character_damage():damage_simple({ variant = "graze", damage = hit.damage, attacker_unit = player_unit, pos = hit_pos, attack_dir = hit_pos - hit.position }) hit = { position = hit_pos, damage = result and result.damage or hit.damage } self:find_wunderwaffe_closest_hit(hit, ignored_enemies, upgrade_value, enemy_mask, geometry_mask, player_unit, times - 1, timer_between) end) end end
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- F I N A L C U T P R O A P I -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === cp.apple.finalcutpro.main.ColorBoard === --- --- Color Board Module. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local log = require("hs.logger").new("timline") local inspect = require("hs.inspect") local geometry = require("hs.geometry") local prop = require("cp.prop") local just = require("cp.just") local axutils = require("cp.ui.axutils") local tools = require("cp.tools") local Pucker = require("cp.apple.finalcutpro.main.ColorPucker") local id = require("cp.apple.finalcutpro.ids") "ColorBoard" -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local ColorBoard = {} --- cp.apple.finalcutpro.main.ColorBoard.aspect -> table --- Constant --- A table containing tables of all the aspect panel settings ColorBoard.aspect = {} --- cp.apple.finalcutpro.main.ColorBoard.aspect.color -> table --- Constant --- A table containing the Color Board Color panel settings ColorBoard.aspect.color = { id = 1, reset = id "ColorReset", global = { puck = id "ColorGlobalPuck", pct = id "ColorGlobalPct", angle = id "ColorGlobalAngle"}, shadows = { puck = id "ColorShadowsPuck", pct = id "ColorShadowsPct", angle = id "ColorShadowsAngle"}, midtones = { puck = id "ColorMidtonesPuck", pct = id "ColorMidtonesPct", angle = id "ColorMidtonesAngle"}, highlights = { puck = id "ColorHighlightsPuck", pct = id "ColorHighlightsPct", angle = id "ColorHighlightsAngle"} } --- cp.apple.finalcutpro.main.ColorBoard.aspect.saturation -> table --- Constant --- A table containing the Color Board Saturation panel settings ColorBoard.aspect.saturation = { id = 2, reset = id "SatReset", global = { puck = id "SatGlobalPuck", pct = id "SatGlobalPct"}, shadows = { puck = id "SatShadowsPuck", pct = id "SatShadowsPct"}, midtones = { puck = id "SatMidtonesPuck", pct = id "SatMidtonesPct"}, highlights = { puck = id "SatHighlightsPuck", pct = id "SatHighlightsPct"} } --- cp.apple.finalcutpro.main.ColorBoard.aspect.exposure -> table --- Constant --- A table containing the Color Board Exposure panel settings ColorBoard.aspect.exposure = { id = 3, reset = id "ExpReset", global = { puck = id "ExpGlobalPuck", pct = id "ExpGlobalPct"}, shadows = { puck = id "ExpShadowsPuck", pct = id "ExpShadowsPct"}, midtones = { puck = id "ExpMidtonesPuck", pct = id "ExpMidtonesPct"}, highlights = { puck = id "ExpHighlightsPuck", pct = id "ExpHighlightsPct"} } --- cp.apple.finalcutpro.main.ColorBoard.currentAspect -> string --- Variable --- The current aspect as a string. ColorBoard.currentAspect = "*" --- cp.apple.finalcutpro.main.ColorBoard.isColorBoard(element) -> boolean --- Function --- Checks to see if a GUI element is the Color Board or not --- --- Parameters: --- * `element` - The element you want to check --- --- Returns: --- * `true` if the `element` is a Color Board otherwise `false` function ColorBoard.isColorBoard(element) for _, child in ipairs(element) do ----------------------------------------------------------------------- -- Final Cut Pro 10.3: ---------------------------------------------------------------------- if axutils.childWith(child, "AXIdentifier", id "BackButton") then return true end ----------------------------------------------------------------------- -- Final Cut Pro 10.4: ----------------------------------------------------------------------- local splitGroup = axutils.childWith(child, "AXRole", "AXSplitGroup") if splitGroup then local colorBoardGroup = axutils.childWith(splitGroup, "AXIdentifier", id "ColorBoardGroup") if colorBoardGroup and colorBoardGroup[1] and colorBoardGroup[1][1] and #colorBoardGroup[1][1]:attributeValue("AXChildren") >= 19 then return true end end end return false end --- cp.apple.finalcutpro.main.ColorBoard:new(parent) -> ColorBoard object --- Method --- Creates a new ColorBoard object --- --- Parameters: --- * `parent` - The parent --- --- Returns: --- * A ColorBoard object function ColorBoard:new(parent) local o = { _parent = parent, _child = {} } return prop.extend(o, ColorBoard) end --- cp.apple.finalcutpro.main.ColorBoard:parent() -> table --- Method --- Returns the ColorBoard's parent table --- --- Parameters: --- * None --- --- Returns: --- * The parent object as a table function ColorBoard:parent() return self._parent end --- cp.apple.finalcutpro.main.ColorBoard:app() -> table --- Method --- Returns the `cp.apple.finalcutpro` app table --- --- Parameters: --- * None --- --- Returns: --- * The application object as a table function ColorBoard:app() return self:parent():app() end ----------------------------------------------------------------------- -- -- COLORBOARD UI: -- ----------------------------------------------------------------------- --- cp.apple.finalcutpro.main.ColorBoard:UI() -> hs._asm.axuielement object --- Method --- Returns the `hs._asm.axuielement` object for the Color Board --- --- Parameters: --- * None --- --- Returns: --- * A `hs._asm.axuielement` object function ColorBoard:UI() -- TODO: David should review this code, as there's repeated code. return axutils.cache(self, "_ui", function() local parent = self:parent() local ui = parent:rightGroupUI() if ui then ----------------------------------------------------------------------- -- It's in the right panel (full-height): ----------------------------------------------------------------------- if ColorBoard.isColorBoard(ui) then if self:app():isColorInspectorSupported() then ----------------------------------------------------------------------- -- Final Cut Pro 10.4: ---------------------------------------------------------------------- local groupChildren = ui:attributeValue("AXChildren") if groupChildren then for _, child in ipairs(groupChildren) do local splitGroup = axutils.childWith(child, "AXRole", "AXSplitGroup") if splitGroup then return splitGroup and splitGroup[1] and splitGroup[1][1] and splitGroup[1][1][1] end end end else ----------------------------------------------------------------------- -- Final Cut Pro 10.3: ----------------------------------------------------------------------- return ui end end else ----------------------------------------------------------------------- -- It's in the top-left panel (half-height): ----------------------------------------------------------------------- local top = parent:topGroupUI() if not top then return nil end for i,child in ipairs(top) do if ColorBoard.isColorBoard(child) then if self:app():isColorInspectorSupported() then ----------------------------------------------------------------------- -- Final Cut Pro 10.4: ---------------------------------------------------------------------- local groupChildren = child:attributeValue("AXChildren") if groupChildren then for _, grandChild in ipairs(groupChildren) do local splitGroup = axutils.childWith(grandChild, "AXRole", "AXSplitGroup") if splitGroup then return splitGroup and splitGroup[1] and splitGroup[1][1] and splitGroup[1][1][1] end end end else ----------------------------------------------------------------------- -- Final Cut Pro 10.3: ----------------------------------------------------------------------- return child end end end end return nil end, function(element) return ColorBoard:isColorBoard(element) end) end --- cp.apple.finalcutpro.main.ColorBoard:colorInspectorBarUI() -> hs._asm.axuielement object --- Method --- Returns the `hs._asm.axuielement` object for the Final Cut Pro 10.4 Color Board Inspector Bar (i.e. where you can add new Color Corrections from the dropdown) --- --- Parameters: --- * None --- --- Returns: --- * A `hs._asm.axuielement` object function ColorBoard:colorInspectorBarUI() return self:app():inspector():colorInspector():colorInspectorBarUI() end --- cp.apple.finalcutpro.main.ColorBoard:isShowing() -> boolean --- Method --- Returns whether or not the Color Board is visible --- --- Parameters: --- * None --- --- Returns: --- * `true` if the Color Board is showing, otherwise `false` ColorBoard.isShowing = prop.new(function(self) if self:app():isColorInspectorSupported() then ----------------------------------------------------------------------- -- Final Cut Pro 10.4: ----------------------------------------------------------------------- return self:app():inspector():colorInspector():colorBoard():isShowing() else ----------------------------------------------------------------------- -- Final Cut Pro 10.3: ----------------------------------------------------------------------- local ui = self:UI() return ui ~= nil and ui:attributeValue("AXSize").w > 0 end end):bind(ColorBoard) --- cp.apple.finalcutpro.main.ColorBoard:isActive() -> boolean --- Method --- Returns whether or not the Color Board is active --- --- Parameters: --- * None --- --- Returns: --- * `true` if the Color Board is active, otherwise `false` ColorBoard.isActive = prop.new(function(self) local ui = self:colorSatExpUI() return ui ~= nil and axutils.childWith(ui:parent(), "AXIdentifier", id "ColorSatExp") end):bind(ColorBoard) --- cp.apple.finalcutpro.main.ColorBoard:show() -> ColorBoard object --- Method --- Shows the Color Board --- --- Parameters: --- * None --- --- Returns: --- * ColorBoard object function ColorBoard:show() if not self:isShowing() then if self:app():isColorInspectorSupported() then ----------------------------------------------------------------------- -- Final Cut Pro 10.4: ----------------------------------------------------------------------- self:app():inspector():colorInspector():colorBoard():show() else ----------------------------------------------------------------------- -- Final Cut Pro 10.3: ----------------------------------------------------------------------- self:app():menuBar():selectMenu({"Window", "Go To", id "ColorBoard"}) end end return self end --- cp.apple.finalcutpro.main.ColorBoard:hide() -> ColorBoard object --- Method --- Hides the Color Board --- --- Parameters: --- * None --- --- Returns: --- * ColorBoard object function ColorBoard:hide() local ui = self:showInspectorUI() if ui then ui:doPress() end return self end --- cp.apple.finalcutpro.main.ColorBoard:childUI(id) -> hs._asm.axuielement object --- Method --- Gets the `hs._asm.axuielement` object for a child with the specified ID. --- --- Parameters: --- * id - `AXIdentifier` of the child --- --- Returns: --- * An `hs._asm.axuielement` object function ColorBoard:childUI(id) return axutils.cache(self._child, id, function() local ui = self:UI() return ui and axutils.childWith(ui, "AXIdentifier", id) end) end --- cp.apple.finalcutpro.main.ColorBoard:topToolbarUI() -> hs._asm.axuielement object --- Method --- Gets the `hs._asm.axuielement` object for the top toolbar (i.e. where the Back Button is located in Final Cut Pro 10.3) --- --- Parameters: --- * None --- --- Returns: --- * An `hs._asm.axuielement` object --- --- Notes: --- * This object doesn't exist in Final Cut Pro 10.4 as the Color Board is now contained within the Color Inspector function ColorBoard:topToolbarUI() return axutils.cache(self, "_topToolbar", function() local ui = self:UI() if ui then for i,child in ipairs(ui) do if axutils.childWith(child, "AXIdentifier", id "BackButton") then return child end end end return nil end) end --- cp.apple.finalcutpro.main.ColorBoard:showInspectorUI() -> hs._asm.axuielement object --- Method --- Gets the `hs._asm.axuielement` object for the inspector --- --- Parameters: --- * None --- --- Returns: --- * An `hs._asm.axuielement` object function ColorBoard:showInspectorUI() return axutils.cache(self, "_showInspector", function() local ui = self:topToolbarUI() if ui then return axutils.childWith(ui, "AXIdentifier", id "BackButton") end return nil end) end ----------------------------------------------------------------------- -- -- COLOR CORRECTION PANELS: -- ----------------------------------------------------------------------- --- cp.apple.finalcutpro.main.ColorBoard:colorSatExpUI() -> hs._asm.axuielement object --- Method --- Gets the `hs._asm.axuielement` object for the `AXRadioGroup` which houses the "Color", "Saturation" and "Exposure" button --- --- Parameters: --- * None --- --- Returns: --- * An `hs._asm.axuielement` object function ColorBoard:colorSatExpUI() return axutils.cache(self, "_colorSatExp", function() local ui = self:UI() return ui and axutils.childWith(ui, "AXIdentifier", id "ColorSatExp") end) end --- cp.apple.finalcutpro.main.ColorBoard:getAspect(aspect, property) -> table --- Method --- Gets a table containing the ID information for a specific `aspect` and `property` --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- --- Returns: --- * A table or `nil` if an error occurs function ColorBoard:getAspect(aspect, property) local panel = nil if type(aspect) == "string" then if aspect == ColorBoard.currentAspect then ----------------------------------------------------------------------- -- Return the currently-visible aspect: ----------------------------------------------------------------------- local ui = self:colorSatExpUI() if ui then for k,value in pairs(ColorBoard.aspect) do if ui[value.id] and ui[value.id]:value() == 1 then panel = value end end end else panel = ColorBoard.aspect[aspect] end else panel = name end if panel and property then return panel[property] end return panel end ----------------------------------------------------------------------- -- -- PANEL CONTROLS: -- ----------------------------------------------------------------------- --- cp.apple.finalcutpro.main.ColorBoard:togglePanel() -> ColorBoard object --- Method --- Toggles the Color Board Panels between "Color", "Saturation" and "Exposure" --- --- Parameters: --- * None --- --- Returns: --- * ColorBoard object function ColorBoard:togglePanel() self:show() local colorAspect = self:getAspect("color") local saturationAspect = self:getAspect("saturation") local exposureAspect = self:getAspect("exposure") local ui = self:colorSatExpUI() if colorAspect and ui and ui[colorAspect.id]:value() == 1 then ui[saturationAspect.id]:doPress() elseif saturationAspect and ui and ui[saturationAspect.id]:value() == 1 then ui[exposureAspect.id]:doPress() elseif exposureAspect and ui and ui[exposureAspect.id]:value() == 1 then ui[colorAspect.id]:doPress() end return self end --- cp.apple.finalcutpro.main.ColorBoard:selectedPanel() -> string | nil --- Method --- Returns the currently selected Color Board panel --- --- Parameters: --- * None --- --- Returns: --- * "Color", "Saturation", "Exposure" or `nil` if an error occurs function ColorBoard:selectedPanel() local colorAspect = self:getAspect("color") local saturationAspect = self:getAspect("saturation") local exposureAspect = self:getAspect("exposure") local ui = self:colorSatExpUI() if colorAspect and ui and ui[colorAspect.id] and ui[colorAspect.id]:value() == 1 then return "color" elseif saturationAspect and ui and ui[saturationAspect.id] and ui[saturationAspect.id]:value() == 1 then return "saturation" elseif exposureAspect and ui and ui[exposureAspect.id] and ui[exposureAspect.id]:value() == 1 then return "exposure" end return nil end --- cp.apple.finalcutpro.main.ColorBoard:showPanel(aspect) -> ColorBoard object --- Method --- Shows a specific panel based on the specified `aspect` --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- --- Returns: --- * ColorBoard object function ColorBoard:showPanel(aspect) self:show() aspect = self:getAspect(aspect) local ui = self:colorSatExpUI() if aspect and ui and ui[aspect.id]:value() == 0 then ui[aspect.id]:doPress() end return self end --- cp.apple.finalcutpro.main.ColorBoard:reset(aspect) -> ColorBoard object --- Method --- Resets a specified `aspect` --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- --- Returns: --- * ColorBoard object function ColorBoard:reset(aspect) aspect = self:getAspect(aspect) self:showPanel(aspect) local ui = self:UI() if ui then local reset = axutils.childWith(ui, "AXIdentifier", aspect.reset) if reset then reset:doPress() end end return self end --- cp.apple.finalcutpro.main.ColorBoard:puckUI(aspect, property) -> hs._asm.axuielement object --- Method --- Gets the `hs._asm.axuielement` object of a specific Color Board puck --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- --- Returns: --- * An `hs._asm.axuielement` object function ColorBoard:puckUI(aspect, property) local details = self:getAspect(aspect, property) return self:childUI(details.puck) end --- cp.apple.finalcutpro.main.ColorBoard:selectPuck(aspect, property) -> ColorBoard object --- Method --- Selects a specific Color Board puck --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- --- Returns: --- * ColorBoard object function ColorBoard:selectPuck(aspect, property) self:showPanel(aspect) local puckUI = self:puckUI(aspect, property) if puckUI then local f = puckUI:frame() local centre = geometry(f.x + f.w/2, f.y + f.h/2) tools.ninjaMouseClick(centre) end return self end --- cp.apple.finalcutpro.main.ColorBoard:aspectPropertyPanelUI(aspect, property, type) -> hs._asm.axuielement object --- Method --- Ensures that the specified aspect/property panel is visible and returns the specified value type `hs._asm.axuielement` object --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- * type - "pct" or "angle" --- --- Returns: --- * An `hs._asm.axuielement` object or `nil` if an error occurs function ColorBoard:aspectPropertyPanelUI(aspect, property, type) if not self:isShowing() then return nil end self:showPanel(aspect) local details = self:getAspect(aspect, property) if not details or not details[type] then return nil end local ui = self:childUI(details[type]) if not ui then ----------------------------------------------------------------------- -- Short inspector panels can hide some details panels: ----------------------------------------------------------------------- self:selectPuck(aspect, property) ----------------------------------------------------------------------- -- Try again: ----------------------------------------------------------------------- ui = self:childUI(details[type]) end return ui end --- cp.apple.finalcutpro.main.ColorBoard:applyPercentage(aspect, property, value) -> ColorBoard object --- Method --- Applies a Color Board Percentage value to the specified aspect/property --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- * value - value as string --- --- Returns: --- * ColorBoard object function ColorBoard:applyPercentage(aspect, property, value) local pctUI = self:aspectPropertyPanelUI(aspect, property, 'pct') if pctUI then pctUI:setAttributeValue("AXValue", tostring(value)) pctUI:doConfirm() end return self end --- cp.apple.finalcutpro.main.ColorBoard:shiftPercentage(aspect, property, shift) -> ColorBoard object --- Method --- Shifts a Color Board Percentage value of the specified aspect/property --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- * shift - number you want to increase/decrease the percentage by --- --- Returns: --- * ColorBoard object function ColorBoard:shiftPercentage(aspect, property, shift) local ui = self:aspectPropertyPanelUI(aspect, property, 'pct') if ui then local value = tonumber(ui:attributeValue("AXValue") or "0") ui:setAttributeValue("AXValue", tostring(value + tonumber(shift))) ui:doConfirm() end return self end --- cp.apple.finalcutpro.main.ColorBoard:getPercentage(aspect, property) -> number | nil --- Method --- Gets a percentage value of the specified `aspect` and `property` --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- --- Returns: --- * Number or `nil` if an error occurred function ColorBoard:getPercentage(aspect, property) local pctUI = self:aspectPropertyPanelUI(aspect, property, 'pct') if pctUI then return tonumber(pctUI:attributeValue("AXValue")) end return nil end --- cp.apple.finalcutpro.main.ColorBoard:applyAngle(aspect, property, value) -> ColorBoard object --- Method --- Applies a Color Board Angle value to the specified aspect/property --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- * value - value as string --- --- Returns: --- * ColorBoard object function ColorBoard:applyAngle(aspect, property, value) local angleUI = self:aspectPropertyPanelUI(aspect, property, 'angle') if angleUI then angleUI:setAttributeValue("AXValue", tostring(value)) angleUI:doConfirm() end return self end --- cp.apple.finalcutpro.main.ColorBoard:shiftAngle(aspect, property, shift) -> ColorBoard object --- Method --- Shifts a Color Board Angle value of the specified aspect/property --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- * shift - number you want to increase/decrease the angle by --- --- Returns: --- * ColorBoard object function ColorBoard:shiftAngle(aspect, property, shift) local ui = self:aspectPropertyPanelUI(aspect, property, 'angle') if ui then local value = tonumber(ui:attributeValue("AXValue") or "0") ----------------------------------------------------------------------- -- Loop around between 0 and 360 degrees: ----------------------------------------------------------------------- value = (value + shift + 360) % 360 ui:setAttributeValue("AXValue", tostring(value)) ui:doConfirm() end return self end --- cp.apple.finalcutpro.main.ColorBoard:getAngle(aspect, property) -> number | nil --- Method --- Gets an angle value of the specified `aspect` and `property` --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- --- Returns: --- * Number or `nil` if an error occurred function ColorBoard:getAngle(aspect, property, value) local angleUI = self:aspectPropertyPanelUI(aspect, property, 'angle') if angleUI then local value = angleUI:attributeValue("AXValue") if value ~= nil then return tonumber(value) end end return nil end --- cp.apple.finalcutpro.main.ColorBoard:startPucker(aspect, property) -> Pucker object --- Method --- Creates a Pucker object for the specified `aspect` and `property` --- --- Parameters: --- * aspect - "color", "saturation" or "exposure" --- * property - "global", "shadows", "midtones" or "highlights" --- --- Returns: --- * Pucker object function ColorBoard:startPucker(aspect, property) if self.pucker then self.pucker:cleanup() self.pucker = nil end self.pucker = Pucker:new(self, aspect, property):start() return self.pucker end return ColorBoard
--- Library for creating and manipulating physics-less models AKA "Holograms". -- @shared local holograms_library = SF.RegisterLibrary("holograms") --- Hologram type local hologram_methods, hologram_metamethods = SF.RegisterType("Hologram") local checktype = SF.CheckType local checkluatype = SF.CheckLuaType local checkpermission = SF.Permissions.check SF.Holograms = {} SF.Permissions.registerPrivilege("hologram.modify", "Modify holograms", "Allows the user to modify holograms", { entities = {} }) SF.Holograms.Methods = hologram_methods SF.Holograms.Metatable = hologram_metamethods local ang_meta, vec_meta, ent_meta local wrap, unwrap, vwrap, vunwrap, aunwrap, ewrap, eunwrap local hologramSENT SF.AddHook("postload", function() ang_meta = SF.Angles.Metatable vec_meta = SF.Vectors.Metatable ent_meta = SF.Entities.Metatable vwrap = SF.Vectors.Wrap vunwrap = SF.Vectors.Unwrap aunwrap = SF.Angles.Unwrap ewrap = SF.Entities.Wrap eunwrap = SF.Entities.Unwrap SF.ApplyTypeDependencies(hologram_methods, hologram_metamethods, ent_meta) wrap, unwrap = SF.CreateWrapper(hologram_metamethods, true, false, nil, ent_meta) SF.Holograms.Wrap = wrap SF.Holograms.Unwrap = unwrap if CLIENT then hologramSENT = scripted_ents.GetStored( "starfall_hologram" ) if not hologramSENT then hook.Add("Initialize","SF_GetHologramRenderFunc",function() hologramSENT = scripted_ents.GetStored( "starfall_hologram" ) end) end end end) SF.Permissions.registerPrivilege("hologram.create", "Create hologram", "Allows the user to create holograms", CLIENT and { client = {} } or nil) SF.Permissions.registerPrivilege("hologram.setRenderProperty", "RenderProperty", "Allows the user to change the rendering of an entity", { entities = {} }) local plyCount = SF.LimitObject("holograms", "holograms", 200, "The number of holograms allowed to spawn via Starfall scripts for a single player") SF.AddHook("initialize", function(inst) inst.data.holograms = {holos = {}} end) local function hologramOnDestroy(holo, holodata, ply) holodata[holo] = nil plyCount:free(ply, 1) end SF.AddHook("deinitialize", function(inst) local holos = inst.data.holograms.holos local holo = next(holos) while holo do if (holo and holo:IsValid()) then holo:RemoveCallOnRemove("starfall_hologram_delete") hologramOnDestroy(holo, holos, inst.player) holo:Remove() end holo = next(holos, holo) end end) local entmeta = FindMetaTable("Entity") local cl_hologram_meta = { __index = function(t,k,v) if k=="CPPIGetOwner" then return function(ent) return ent.SFHoloOwner end elseif k=="CPPICanTool" then return function(ent, pl) return ent.SFHoloOwner==pl end elseif k=="CPPICanPhysgun" then return function(ent, pl) return ent.SFHoloOwner==pl end else return entmeta.__index(t,k,v) end end, __newindex = entmeta.__newindex, __concat = entmeta.__concat, __tostring = entmeta.__tostring, __eq = entmeta.__eq, } --- Creates a hologram. -- @return The hologram object function holograms_library.create(pos, ang, model, scale) local instance = SF.instance checkpermission(instance, nil, "hologram.create") checktype(pos, vec_meta) checktype(ang, ang_meta) checkluatype(model, TYPE_STRING) local pos = vunwrap(pos) local ang = aunwrap(ang) local ply = instance.player local holodata = instance.data.holograms.holos plyCount:checkuse(ply, 1) local holoent if SERVER then holoent = ents.Create("starfall_hologram") if holoent and holoent:IsValid() then holoent:SetPos(SF.clampPos(pos)) holoent:SetAngles(ang) holoent:SetModel(model) holoent:CallOnRemove("starfall_hologram_delete", hologramOnDestroy, holodata, ply) holoent:Spawn() hook.Run("PlayerSpawnedSENT", ply, holoent) holodata[holoent] = true if scale~=nil then checktype(scale, vec_meta) holoent:SetScale(vunwrap(scale)) end plyCount:free(ply, -1) return wrap(holoent) end else holoent = ClientsideModel(model, RENDERGROUP_TRANSLUCENT) if holoent and holoent:IsValid() then holoent.IsSFHologram = true holoent.SFHoloOwner = ply holoent:SetPos(SF.clampPos(pos)) holoent:SetAngles(ang) holoent:CallOnRemove("starfall_hologram_delete", hologramOnDestroy, holodata, ply) table.Inherit(holoent:GetTable(), hologramSENT.t) holoent:Initialize() holoent.RenderOverride = holoent.Draw holoent.DrawHologram = holoent.DrawCLHologram debug.setmetatable(holoent, cl_hologram_meta) holodata[holoent] = true if scale~=nil then checktype(scale, vec_meta) SF.Holograms.SetScale(holoent, vunwrap(scale)) end plyCount:free(ply, -1) return wrap(holoent) end end end --- Checks if a user can spawn anymore holograms. -- @return True if user can spawn holograms, False if not. function holograms_library.canSpawn() if not SF.Permissions.hasAccess(SF.instance, nil, "hologram.create") then return false end return plyCount:check(SF.instance.player) > 0 end --- Checks how many holograms can be spawned -- @return number of holograms able to be spawned function holograms_library.hologramsLeft () if not SF.Permissions.hasAccess(SF.instance, nil, "hologram.create") then return 0 end return plyCount:check(SF.instance.player) end if SERVER then --- Sets the hologram scale. Basically the same as setRenderMatrix() with a scaled matrix -- @shared -- @param scale Vector new scale function hologram_methods:setScale(scale) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checktype(scale, vec_meta) local scale = vunwrap(scale) checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo:SetScale(scale) end --- Suppress Engine Lighting of a hologram. Disabled by default. -- @shared -- @param suppress Boolean to represent if shading should be set or not. function hologram_methods:suppressEngineLighting (suppress) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkluatype(suppress, TYPE_BOOL) checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo:SetSuppressEngineLighting(suppress) end --- Sets the hologram linear velocity -- @server -- @param vel New velocity function hologram_methods:setVel (vel) checktype(self, hologram_metamethods) checktype(vel, vec_meta) local vel = vunwrap(vel) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo:SetLocalVelocity(vel) end --- Sets the hologram's angular velocity. -- @server -- @param angvel *Vector* angular velocity. function hologram_methods:setAngVel (angvel) checktype(self, hologram_metamethods) checktype(angvel, ang_meta) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo:SetLocalAngularVelocity(aunwrap(angvel)) end --- Animates a hologram -- @server -- @param animation number or string name -- @param frame The starting frame number -- @param rate Frame speed. (1 is normal) function hologram_methods:setAnimation(animation, frame, rate) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") if isstring(animation) then animation = holo:LookupSequence(animation) end frame = frame or 0 rate = rate or 1 holo.AutomaticFrameAdvance = animation~=-1 holo:ResetSequence(animation) holo:SetCycle(frame) holo:SetPlaybackRate(rate) end else SF.Holograms.maxclips = CreateClientConVar("sf_holograms_maxclips_cl", "8", true, false, "The max number of clips per hologram entity") SF.Permissions.registerPrivilege("hologram.setParent", "Set Parent", "Allows the user to parent a hologram", { entities = {} }) function SF.Holograms.SetScale(holo, scale) holo.scale = scale if scale == Vector(1, 1, 1) then holo.HoloMatrix = nil holo:DisableMatrix("RenderMultiply") else local scalematrix = Matrix() scalematrix:Scale(scale) holo.HoloMatrix = scalematrix holo:EnableMatrix("RenderMultiply", scalematrix) end end --- Sets the hologram's position. -- @shared -- @param vec New position function hologram_methods:setPos(vec) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checktype(vec, vec_meta) local vec = vunwrap(vec) checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo:SetPos(SF.clampPos(vec)) end --- Sets the hologram's angles. -- @shared -- @param ang New angles function hologram_methods:setAngles(ang) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checktype(ang, ang_meta) local ang = aunwrap(ang) checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo:SetAngles(ang) end --- Removes a hologram function hologram_methods:remove() checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.create") holo:Remove() end --- Sets the texture filtering function when viewing a close texture -- @client -- @param val The filter function to use http://wiki.garrysmod.com/page/Enums/TEXFILTER function hologram_methods:setFilterMag(val) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") if val then checkluatype(val, TYPE_NUMBER) holo.filter_mag = val else holo.filter_mag = nil end end --- Sets the texture filtering function when viewing a far texture -- @client -- @param val The filter function to use http://wiki.garrysmod.com/page/Enums/TEXFILTER function hologram_methods:setFilterMin(val) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") if val then checkluatype(val, TYPE_NUMBER) holo.filter_min = val else holo.filter_min = nil end end --- Sets a hologram entity's rendermatrix -- @client -- @param mat Starfall matrix to use function hologram_methods:setRenderMatrix(mat) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") if mat ~= nil then checktype(mat, SF.VMatrix.Metatable) local matrix = SF.VMatrix.Unwrap(mat) if matrix:IsIdentity() then holo.HoloMatrix = nil holo:DisableMatrix("RenderMultiply") else holo.HoloMatrix = matrix holo:EnableMatrix("RenderMultiply", matrix) end else holo:DisableMatrix("RenderMultiply") end end function hologram_methods:setScale(scale) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checktype(scale, vec_meta) local scale = vunwrap(scale) checkpermission(SF.instance, holo, "hologram.setRenderProperty") SF.Holograms.SetScale(holo, scale) end --- Updates a clip plane -- @client -- @param index Whatever number you want the clip to be -- @param enabled Whether the clip is enabled -- @param origin The center of the clip plane in world coordinates, or local to entity if it is specified -- @param normal The the direction of the clip plane in world coordinates, or local to entity if it is specified -- @param entity (Optional) The entity to make coordinates local to, otherwise the world is used function hologram_methods:setClip(index, enabled, origin, normal, entity) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkluatype(index, TYPE_NUMBER) checkluatype(enabled, TYPE_BOOL) checktype(origin, vec_meta) checktype(normal, vec_meta) if entity ~= nil then checktype(entity, ent_meta) entity = eunwrap(entity) end local origin, normal = vunwrap(origin), vunwrap(normal) checkpermission(SF.instance, holo, "hologram.setRenderProperty") local clips = holo.clips if enabled then local clip = clips[index] if not clip then local max = SF.Holograms.maxclips:GetInt() if table.Count(holo.clips)==max then SF.Throw("The maximum hologram clips is " .. max, 2) end clip = {} clips[index] = clip end clip.normal = normal clip.origin = origin clip.entity = entity else clips[index] = nil end end function hologram_methods:suppressEngineLighting (suppress) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkluatype(suppress, TYPE_BOOL) checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo.suppressEngineLighting = suppress end local function parentChildren(ent) for child, attachment in pairs(ent.sf_children) do if child and child:IsValid() then child:SetParent(ent, attachment) if child.sf_children then return parentChildren(child) end end end end hook.Add("NotifyShouldTransmit", "starfall_hologram_parents", function(ent, transmit) if ent and ent:IsValid() and ent.sf_children then parentChildren(ent) end end) local holoChildrenMeta = { __mode = "k" } --- Parents a hologram -- @param ent Entity parent (nil to unparent) -- @param attachment Optional attachment ID function hologram_methods:setParent (ent, attachment) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The hologram is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setParent") if ent ~= nil then checktype(ent, ent_meta) local parent = eunwrap(ent) if not (parent and parent:IsValid()) then SF.Throw("The parent is invalid", 2) end if attachment == nil then attachment = -1 end checkluatype(attachment, TYPE_NUMBER) if not parent.sf_children then parent.sf_children = setmetatable({}, holoChildrenMeta) end if holo.sf_parent then holo.sf_parent.sf_children[holo] = nil end parent.sf_children[holo] = attachment holo.sf_parent = parent holo:SetParent(parent, attachment) else if holo.sf_parent then holo.sf_parent.sf_children[holo] = nil end holo.sf_parent = nil holo:SetParent() end end end --- Gets the hologram scale. -- @shared -- @return Vector scale function hologram_methods:getScale() checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") return vwrap(holo.scale) end --- Sets the model of a hologram -- @param model string model path function hologram_methods:setModel(model) checktype(self, hologram_metamethods) local holo = unwrap(self) if not (holo and holo:IsValid()) then SF.Throw("The entity is invalid", 2) end checkluatype(model, TYPE_STRING) if not util.IsValidModel(model) then SF.Throw("Model is invalid", 2) end checkpermission(SF.instance, holo, "hologram.setRenderProperty") holo:SetModel(model) end
sherkarTeleportScreenPlay = ScreenPlay:new { numberOfActs = 1, } registerScreenPlay("sherkarTeleportScreenPlay", true) function sherkarTeleportScreenPlay:start() if (isZoneEnabled("mustafar")) then self:spawnMobiles() self:spawnSceneObjects() end end function sherkarTeleportScreenPlay:spawnSceneObjects() end function sherkarTeleportScreenPlay:spawnMobiles() local pCollector1 = spawnMobile("mustafar", "teleporter", 120, -2528.2, 225, 1645.8, 7, 0) local collector1 = LuaCreatureObject(pCollector1) collector1:setOptionsBitmask(264) collector1:setCustomObjectName("\\#FF0000Travel to Sher Kar's Lair") createObserver(OBJECTRADIALUSED, "sherkarTeleportScreenPlay", "teleportSherKar", pCollector1) if (pCollecter1~= nil) then return end end function sherkarTeleportScreenPlay:teleportSherKar(pCollector, pPlayer)--current local player = LuaSceneObject(pPlayer) player:switchZone("dungeon2", -6.7, -0.8, 3.6, 14201161) return 0 end
pfUI:RegisterModule("firstrun", 20400, function () pfUI.firstrun = CreateFrame("Frame", "pfFirstRunWizard", UIParent) pfUI.firstrun.steps = {} pfUI.firstrun:RegisterEvent("PLAYER_ENTERING_WORLD") pfUI.firstrun:SetScript("OnEvent", function() pfUI.firstrun:NextStep() end) local autoconfig = false function pfUI.firstrun:AddStep(name, func) if not name then return end table.insert(pfUI.firstrun.steps, { name = name, func = func}) end local cur, max = 0, 0 function pfUI.firstrun:NextStep() local windowcount = 0 for i, step in pairs(pfUI.firstrun.steps) do if not pfUI_init[step.name] then windowcount = windowcount + 1 end end max = windowcount > max and windowcount or max for _, step in pairs(pfUI.firstrun.steps) do local name = step.name if not pfUI_init[name] then cur = cur + 1 local f = step.func() f.progress:SetMinMaxValues(0, max) f.progress:SetValue(cur) f.ptext:SetText(cur .. " / " .. max) f.name = name f:Show() if autoconfig == true then f.next:Click() end if cur == max then f.next:SetText(T["Finish"]) autoconfig = false cur = 0 max = 0 end return end end end -- main function to create wizard windows local function CreateFirstRunPage() local f = CreateFrame("Frame", nil, UIParent) f:SetPoint("CENTER", 0, 0) f:SetFrameStrata("TOOLTIP") f:SetMovable(true) f:EnableMouse(true) f:SetWidth(380) f:SetHeight(180) f:SetScript("OnMouseDown",function() this:StartMoving() end) f:SetScript("OnMouseUp",function() this:StopMovingOrSizing() end) CreateBackdrop(f, nil, nil, .85) -- text f.text = f:CreateFontString("Status", "OVERLAY", "GameFontNormal") f.text:SetFontObject(GameFontWhite) f.text:SetJustifyV("TOP") f.text:SetJustifyH("CENTER") f.text:SetPoint("TOPLEFT", f, "TOPLEFT", 10, -10) f.text:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", -10, 10) f.progress = CreateFrame("StatusBar", nil, f) f.progress:SetPoint("BOTTOMLEFT", 100, 10) f.progress:SetPoint("BOTTOMRIGHT", -100, 10) f.progress:SetHeight(12) f.progress:SetStatusBarTexture("Interface\\AddOns\\pfUI\\img\\bar") f.progress:SetStatusBarColor(.2,1,.8,1) f.progress:SetMinMaxValues(1,9) f.progress:SetValue(3) CreateBackdrop(f.progress) f.ptext = f.progress:CreateFontString("Status", "LOW", "GameFontNormal") f.ptext:SetFontObject(GameFontWhite) f.ptext:SetAllPoints() f.ptext:SetText("0/0") f.next = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") f.next:SetWidth(80) f.next:SetHeight(20) f.next:SetPoint("BOTTOMLEFT", f.progress.backdrop, "BOTTOMRIGHT", 8, 0) f.next:SetText(T["Next"]) f.next:SetScript("OnClick", function() if f.NextScript then f.NextScript() end pfUI_init[f.name] = true f:Hide() pfUI.firstrun:NextStep() end) SkinButton(f.next) f.abort = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") f.abort:SetWidth(80) f.abort:SetHeight(20) f.abort:SetPoint("BOTTOMRIGHT", f.progress.backdrop, "BOTTOMLEFT", -8, 0) f.abort:SetText(T["Defaults"]) f.abort:SetScript("OnClick", function() autoconfig = true f.next:Click() end) SkinButton(f.abort) f:Hide() return f end -- welcome dialog pfUI.firstrun:AddStep("init", function() local f = CreateFirstRunPage() f.text:SetText(T["Welcome to |cff33ffccpf|cffffffffUI|r!\n\nI'm the first run wizard that will guide you through some basic configuration. If you're lazy, feel free to hit the \"Defaults\" button. If you wish to run this dialog again, go to the settings and hit the \"Reset Firstrun\" button.\n\nVisit |cff33ffcchttp://shagu.org|r to check for the latest version."]) return f end) -- choose profile pfUI.firstrun:AddStep("profile", function() local f = CreateFirstRunPage() f.text:SetText(T["A new installation of |cff33ffccpf|rUI ships with 4 prebuilt design profiles. Click below if you wish to load one of these profiles."]) f.pfUI = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") f.pfUI:SetWidth(120) f.pfUI:SetHeight(20) f.pfUI:SetPoint("BOTTOM", -65, 80) f.pfUI:SetTextColor(1,1,1) f.pfUI:SetText("pfUI") f.pfUI:SetScript("OnClick", function() _G["pfUI_config"] = CopyTable(pfUI_profiles["pfUI"]) pfUI:LoadConfig() ReloadUI() end) SkinButton(f.pfUI) f.pfUIDark = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") f.pfUIDark:SetWidth(120) f.pfUIDark:SetHeight(20) f.pfUIDark:SetPoint("BOTTOM", -65, 55) f.pfUIDark:SetTextColor(1,1,1) f.pfUIDark:SetText("Dark") f.pfUIDark:SetScript("OnClick", function() _G["pfUI_config"] = CopyTable(pfUI_profiles["pfUI Dark"]) pfUI:LoadConfig() ReloadUI() end) SkinButton(f.pfUIDark) f.Slim = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") f.Slim:SetWidth(120) f.Slim:SetHeight(20) f.Slim:SetPoint("BOTTOM", 65, 80) f.Slim:SetTextColor(1,1,1) f.Slim:SetText("Slim") f.Slim:SetScript("OnClick", function() _G["pfUI_config"] = CopyTable(pfUI_profiles["Slim"]) pfUI:LoadConfig() ReloadUI() end) SkinButton(f.Slim) f.Adapta = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") f.Adapta:SetWidth(120) f.Adapta:SetHeight(20) f.Adapta:SetPoint("BOTTOM", 65, 55) f.Adapta:SetTextColor(1,1,1) f.Adapta:SetText("Adapta") f.Adapta:SetScript("OnClick", function() _G["pfUI_config"] = CopyTable(pfUI_profiles["Adapta"]) pfUI:LoadConfig() ReloadUI() end) SkinButton(f.Adapta) return f end) -- optimized cvars dialog pfUI.firstrun:AddStep("cvars", function() local f = CreateFirstRunPage() f.text:SetText(T["|cff33ffccBlizzard: \"Interface Options\"|r\n\nDo you want me to set up the recommended Blizzard UI settings? This will enable settings that can be found in the Interface section of your client. Options like Buff Durations, Instant Quest Text, Auto Selfcast and others will be set."]) f.checkbox = CreateFrame("CheckButton", "pfCheckBoxCVAR", f, "UICheckButtonTemplate") f.checkbox:SetChecked(true) f.checkbox.text = f:CreateFontString("Status", "LOW", "GameFontNormal") f.checkbox.text:SetPoint("LEFT", f.checkbox, "RIGHT", 5, 0) f.checkbox.text:SetText(" " .. T["Setup Optimized Game Settings"]) f.checkbox:SetPoint("BOTTOMLEFT", (f:GetWidth() - f.checkbox.text:GetStringWidth() - 20) / 2, 50) SkinCheckbox(f.checkbox, 18) f.NextScript = function() if f.checkbox:GetChecked() then pfUI.SetupCVars() end end return f end) -- right chat dialog pfUI.firstrun:AddStep("chat_right", function() local f = CreateFirstRunPage() f.text:SetText(T["|cff33ffccChat: \"Loot & Spam\"|r\n\nDo you want me to create and manage a specific Chatframe called \"Loot & Spam\"? This chat will display world channels, loot information and miscellaneous messages, that would otherwise clutter your main chatframe."]) f.checkbox = CreateFrame("CheckButton", "pfCheckBoxChatRight", f, "UICheckButtonTemplate") f.checkbox:SetChecked(true) f.checkbox.text = f:CreateFontString("Status", "LOW", "GameFontNormal") f.checkbox.text:SetPoint("LEFT", f.checkbox, "RIGHT", 5, 0) f.checkbox.text:SetText(" " .. T["Enable \"Loot & Spam\" Window"]) f.checkbox:SetPoint("BOTTOMLEFT", (f:GetWidth() - f.checkbox.text:GetStringWidth() - 20) / 2, 50) SkinCheckbox(f.checkbox, 18) f.NextScript = function() if not pfUI.chat then message("Couldn't apply settings. Chat module is disabled.") end pfUI.chat.SetupRightChat(f.checkbox:GetChecked()) end return f end) -- chat position dialog pfUI.firstrun:AddStep("chat_position", function() local f = CreateFirstRunPage() f.text:SetText(T["|cff33ffccChat: \"Layout\"|r\n\nDo you want me to adjust the layout of your chatframes? This would make sure, that every window is placed on its dedicated position."]) f.checkbox = CreateFrame("CheckButton", "pfCheckBoxChatPosition", f, "UICheckButtonTemplate") f.checkbox:SetChecked(true) f.checkbox.text = f:CreateFontString("Status", "LOW", "GameFontNormal") f.checkbox.text:SetPoint("LEFT", f.checkbox, "RIGHT", 5, 0) f.checkbox.text:SetText(" " .. T["Align Chat Windows"]) f.checkbox:SetPoint("BOTTOMLEFT", (f:GetWidth() - f.checkbox.text:GetStringWidth() - 20) / 2, 50) SkinCheckbox(f.checkbox, 18) f.NextScript = function() if not pfUI.chat then message("Couldn't apply settings. Chat module is disabled.") end if f.checkbox:GetChecked() then pfUI.chat.SetupPositions() end end return f end) -- chat channels dialog pfUI.firstrun:AddStep("chat_channels", function() local f = CreateFirstRunPage() f.text:SetText(T["|cff33ffccChat: \"Channels\"|r\n\nDo you want me to setup the chat channels of your chatframes? This would set important or personal messages to the left chat and world channels and lootinformation to the right chat."]) f.checkbox = CreateFrame("CheckButton", "pfCheckBoxChatChannels", f, "UICheckButtonTemplate") f.checkbox:SetChecked(true) f.checkbox.text = f:CreateFontString("Status", "LOW", "GameFontNormal") f.checkbox.text:SetPoint("LEFT", f.checkbox, "RIGHT", 5, 0) f.checkbox.text:SetText(" " .. T["Setup All Chat Channels"]) f.checkbox:SetPoint("BOTTOMLEFT", (f:GetWidth() - f.checkbox.text:GetStringWidth() - 20) / 2, 50) SkinCheckbox(f.checkbox, 18) f.NextScript = function() if not pfUI.chat then message("Couldn't apply settings. Chat module is disabled.") end if f.checkbox:GetChecked() then pfUI.chat.SetupChannels() end end return f end) -- finalize dialog pfUI.firstrun:AddStep("finalize", function() local f = CreateFirstRunPage() f.text:SetText(T["Your interface is now set up.\n\nFor advanced configuration, just open the |cff33ffccpf|rUI settings via the escape menu or type \"|cffffffaa/pfui|r\" into the chat.\n\n Have a nice trip!\n\n|cffaaaaaa- Shagu"]) return f end) end)
return { meta = require("apioak.sys.meta"), admin = require("apioak.sys.admin"), router = require("apioak.sys.router"), plugin = require('apioak.sys.plugin'), balancer = require("apioak.sys.balancer"), }
local Object = require('core').Object local Http = require("./http").Http local router = require("./router") local app = Object:extend() function app:initialize() self._server = Http:new() self._router = router.new() end function app:get(path, cb) self._router:get(path, function(params) return cb(params) end) end function app:post(path, cb) self._router:post(path, function(params) return cb(params) end) end function app:any(path, cb) self._router:any(path, function(params) return cb(params) end) end local function prepareHeader(req, body) body = body or '' local header = { code = 200, { "Server", "Luz" }, { "Content-Type", "text/plain" }, { "Content-Length", #body }, } if req.keepAlive then header[#header + 1] = { "Connection", "Keep-Alive" } end return header end function app:listen(options) self._server:listen(options, function(client, req) local _, body = self._router:execute(req.method, req.path) local header = prepareHeader(req, body) client:respond(header, body) end) end return { app = app, }
mapFields = require "lib/mapFields" mapQuests = require "lib/mapQuests" quest = target.get_quest(mapQuests.getID("FreeMarketQuest")) quest.record = tostring(target.field) target.play_portal_sound_effect() target.transfer_field(mapFields.getID("FreeMarketEtrance"), "st00")
--[[ Netherstorm -- Captain Zovax.lua This script was written and is protected by the GPL v2. This script was released by BlackHer0 of the BLUA Scripting Project. Please give proper accredidations when re-releasing or sharing this script with others in the emulation community. ~~End of License Agreement -- BlackHer0, July, 23th, 2008. ]] function Captain_OnEnterCombat(Unit,Event) Unit:RegisterEvent("Captain_Cleave",1000,0) Unit:RegisterEvent("Captain_Toughen",1000,0) end function Captain_Cleave(Unit,Event) Unit:FullCastSpellOnTarget(15576,Unit:GetClosestPlayer()) end function Captain_Thougen(Unit,Event) Unit:CastSpell(33962) end function Captain_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function Captain_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent (20727, 1, "Captain_OnEnterCombat") RegisterUnitEvent (20727, 2, "Captain_OnLeaveCombat") RegisterUnitEvent (20727, 4, "Captain_OnDied")
local K, C, L = unpack(select(2, ...)) if C.Automation.Resurrection ~= true then return end -- Wow API local CanUseSoulstone = CanUseSoulstone local GetBattlefieldStatus = GetBattlefieldStatus local GetCurrentMapAreaID = GetCurrentMapAreaID local GetMaxBattlefieldID = GetMaxBattlefieldID local HasSoulstone = HasSoulstone -- Global variables that we don't cache, list them here for mikk"s FindGlobals script -- GLOBALS: SetMapToCurrentZone, RepopMe -- Auto release the spirit in battlegrounds local AutoRelease = CreateFrame("Frame") AutoRelease:RegisterEvent("PLAYER_DEAD") AutoRelease:SetScript("OnEvent", function(self, event) local inBattlefield = false for i = 1, GetMaxBattlefieldID() do local status = GetBattlefieldStatus(i) if status == "active" then inBattlefield = true end end if not (HasSoulstone() and CanUseSoulstone()) then SetMapToCurrentZone() local areaID = GetCurrentMapAreaID() or 0 if areaID == 501 or areaID == 708 or areaID == 978 or areaID == 1009 or areaID == 1011 or inBattlefield == true then RepopMe() end end end)
--!A cross-platform build utility based on Lua -- -- 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 tool governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file tool.lua -- -- define module local tool = tool or {} local _instance = _instance or {} -- load modules local os = require("base/os") local path = require("base/path") local utils = require("base/utils") local table = require("base/table") local string = require("base/string") local config = require("project/config") local sandbox = require("sandbox/sandbox") local platform = require("platform/platform") local import = require("sandbox/modules/import") -- new an instance function _instance.new(kind, name, program) -- import "core.tools.xxx" local toolclass = nil if os.isfile(path.join(os.programdir(), "modules", "core", "tools", name .. ".lua")) then toolclass = import("core.tools." .. name) end -- not found? if not toolclass then return nil, string.format("cannot import \"core.tool.%s\" module!", name) end -- new an instance local instance = table.inherit(_instance, toolclass) -- save name, kind and program instance._NAME = name instance._KIND = kind instance._PROGRAM = program instance._INFO = {} -- init instance if instance.init then local ok, errors = sandbox.load(instance.init, instance) if not ok then return nil, errors end end -- ok return instance end -- get the tool name function _instance:name() return self._NAME end -- get the tool kind function _instance:kind() return self._KIND end -- get the tool program function _instance:program() return self._PROGRAM end -- set the value to the platform info function _instance:set(name, ...) self._INFO[name] = table.unwrap({...}) end -- add the value to the platform info function _instance:add(name, ...) local info = table.wrap(self._INFO[name]) self._INFO[name] = table.unwrap(table.join(info, ...)) end -- get the platform configure function _instance:get(name) if self._super_get then local value = self:_super_get(name) if value ~= nil then return value end end return self._INFO[name] end -- has the given flag? function _instance:has_flags(flags, flagkind, opt) -- init options opt = opt or {} opt.program = opt.program or self:program() opt.toolkind = opt.toolkind or self:kind() opt.flagkind = opt.flagkind or flagkind -- get system flags opt.sysflags = opt.sysflags or self:get(self:kind() .. 'flags') if not opt.sysflags and flagkind then opt.sysflags = self:get(flagkind) end -- import has_flags() self._has_flags = self._has_flags or import("lib.detect.has_flags", {anonymous = true}) -- has flags? return self._has_flags(self:name(), flags, opt) end -- load the given tool from the given kind -- -- @param kind the tool kind e.g. cc, cxx, mm, mxx, as, ar, ld, sh, .. -- @param program the tool program, e.g. /xxx/arm-linux-gcc, gcc@mipscc.exe -- function tool.load(kind, program) -- init key local key = kind .. (program or "") .. (config.get("arch") or os.arch()) -- get it directly from cache dirst tool._TOOLS = tool._TOOLS or {} if tool._TOOLS[key] then return tool._TOOLS[key] end -- contain toolname? parse it, e.g. 'gcc@xxxx.exe' local toolname = nil if program then local pos = program:find('@', 1, true) if pos then toolname = program:sub(1, pos - 1) program = program:sub(pos + 1) end end -- get the tool program and name if not program then program, toolname = platform.tool(kind) end if not program then return nil, string.format("cannot get program for %s", kind) end -- import find_toolname() tool._find_toolname = tool._find_toolname or import("lib.detect.find_toolname") -- get the tool name from the program local ok, name_or_errors = sandbox.load(tool._find_toolname, toolname or program, {program = program}) if not ok then return nil, name_or_errors end -- get name local name = name_or_errors if not name then return nil, string.format("cannot find known tool script for %s", toolname or program) end -- new an instance local instance, errors = _instance.new(kind, name, program) if not instance then return nil, errors end -- save instance to the cache tool._TOOLS[key] = instance -- ok return instance end -- return module return tool
ServerModSetup("1207269058") ServerModCollectionSetup("1207269058")
-- This file is subject to copyright - contact swampservers@gmail.com for more information. -- INSTALL: CINEMA AF_CITYMAT = AF_CITYMAT or Material("swamponions/af/city") local c0 = Vector(-2385, 96, 763) --left edge of window local c1 = Vector(-2096, -193, 646) --right edge of window local w_center = (c0 + c1) * 0.5 local w_width = math.sqrt(math.pow(c0.x - c1.x, 2) + math.pow(c0.y - c1.y, 2)) local w_height = c0.z - c1.z local v_width = 16000 local v_height = 9000 local v_dist = 5000 hook.Add("PostDrawOpaqueRenderables", "AFCityParallaxEffect", function(depth, sky) if sky or depth then return end local to_c0 = c0 - EyePos() local to_c1 = c1 - EyePos() local adjacent = to_c0:Dot(Vector(1, 1, 0):GetNormalized()) if adjacent <= 0 then return end local function calc_parallax(opposite, w_sz, v_sz) local real_hit = (((opposite / adjacent) * v_dist) + (w_sz / 2)) local virtual_hit = real_hit / (v_sz / 2) return (virtual_hit / 2) + 0.5 end vofs = -0.01 local v0 = calc_parallax(-to_c0.z, -w_height, v_height) + vofs local v1 = calc_parallax(-to_c1.z, w_height, v_height) + vofs local u0 = calc_parallax(to_c0:Dot(Vector(1, -1, 0):GetNormalized()), -w_width, v_width) local u1 = calc_parallax(to_c1:Dot(Vector(1, -1, 0):GetNormalized()), w_width, v_width) cam.Start3D2D(w_center, Angle(0, -45, 90), 1) -- Already backface culled by checks above surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial(AF_CITYMAT) surface.DrawTexturedRectUV(-w_width / 2, -w_height / 2, w_width, w_height, u0, v0, u1, v1) cam.End3D2D() end)
local outfit = {lookType = 267, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookTypeEx = 0, lookAddons = 0} function onStepIn(creature, item, position, fromPosition) local player = creature:getPlayer() if not player then return true end doSetCreatureOutfit(player, outfit, -1) end function onStepOut(creature, item, position, fromPosition) local player = creature:getPlayer() if not player then return true end player:removeCondition(CONDITION_OUTFIT) end
return Def.ActorFrame{ LoadActor(THEME:GetPathG("","_gameover"))..{ InitCommand=function(self) self:Center():diffusealpha(0) end, OnCommand=function(self) self:accelerate(0.75):diffusealpha(0.75):glow(color("1,1,1,1")):decelerate(1):glow(color("1,1,1,0")) end, }, }
local typedefs = require "kong.db.schema.typedefs" local Schema = require "kong.db.schema" local PROTECTED_TAGS = { "error", "http.method", "http.path", "http.status_code", "kong.balancer.state", "kong.balancer.try", "kong.consumer", "kong.credential", "kong.node.id", "kong.route", "kong.service", "lc", "peer.hostname", } local static_tag = Schema.define { type = "record", fields = { { name = { type = "string", required = true, not_one_of = PROTECTED_TAGS } }, { value = { type = "string", required = true } }, }, } local validate_static_tags = function(tags) if type(tags) ~= "table" then return true end local found = {} for i = 1, #tags do local name = tags[i].name if found[name] then return nil, "repeated tags are not allowed: " .. name end found[name] = true end return true end return { name = "zipkin", fields = { { config = { type = "record", fields = { { http_endpoint = typedefs.url }, { sample_ratio = { type = "number", default = 0.001, between = { 0, 1 } } }, { default_service_name = { type = "string", default = nil } }, { include_credential = { type = "boolean", required = true, default = true } }, { traceid_byte_count = { type = "integer", required = true, default = 16, one_of = { 8, 16 } } }, { header_type = { type = "string", required = true, default = "preserve", one_of = { "preserve", "b3", "b3-single", "w3c" } } }, { default_header_type = { type = "string", required = true, default = "b3", one_of = { "b3", "b3-single", "w3c" } } }, { static_tags = { type = "array", elements = static_tag, custom_validator = validate_static_tags } } }, }, }, }, }
Markers = {} Markers.showMarkers = false Markers.showHospital = false Markers.markerPositions = {} Markers.hospitalMarkerPosition = nil Markers.markerSize = Config.Markers.Size / 2.0 function Markers.StartMarkers(hospitalMarker) Markers.showMarkers = true Markers.hospitalMarkerPosition = hospitalMarker Citizen.CreateThread(function() while Markers.showMarkers do Citizen.Wait(10) Stream.of(Markers.markerPositions).forEach(Markers.drawPedMarker) if Markers.showHospital then Markers.drawHospitalMarker(Markers.hospitalMarkerPosition) end end end) end function Markers.StopMarkers() Markers.markerPositions = {} Markers.showMarkers = false Markers.showHospital = false end function Markers.UpdateMarkers(markersTable) Markers.markerPositions = markersTable end function Markers.SetShowHospital(showHospital) Markers.showHospital = showHospital end function Markers.drawPedMarker(coords) Markers.drawMarker(coords, 22, -- MarkerTypeChevronUpx3 180.0, 2.0, 10.0, true ) end function Markers.drawHospitalMarker(coords) Markers.drawMarker(coords, 1, -- MarkerTypeVerticalCylinder 0.0, Markers.markerSize, -1.0, false ) end function Markers.drawMarker(coords, type, yRot, scaleY, zOffset, bobUpAndDown) Wrapper.DrawMarker(type,-- type coords.x, -- posX coords.y, -- posY coords.z + zOffset, -- posZ 0, -- dirX 0, -- dirY 0, -- dirZ 0.0, -- rotX yRot, -- rotY 0.0, -- rotZ Markers.markerSize, -- scaleX scaleY, -- scaleY 10.0, -- scaleZ 0, -- red 0, -- green 150, -- blue 100, -- alpha bobUpAndDown, -- bobUpAndDown true, -- faceCamera 2, -- p19 "Typically set to 2. Does not seem to matter directly." 1, -- rotate 0, -- textureDict 0, -- textureName 0 -- drawOnEnts ) end
function Inventories:OnContextMenuOpen() if IsValid(PLAYER.hotbar) then PLAYER.hotbar:safe_remove() end timer.destroy('fl_hotbar_popup') PLAYER.hotbar = Inventories:create_hotbar() PLAYER.hotbar:SetAlpha(255) PLAYER.hotbar:MakePopup() PLAYER.hotbar:MoveToFront() PLAYER.hotbar:SetMouseInputEnabled(true) PLAYER.hotbar:rebuild() end function Inventories:OnContextMenuClose() if IsValid(PLAYER.hotbar) then PLAYER.hotbar:safe_remove() end end function Inventories:AddTabMenuItems(menu) menu:add_menu_item('inventory', { title = 'Inventory', panel = 'fl_inventory_menu', icon = 'fa-briefcase', default = true, callback = function(menu_panel, button) local inv = menu_panel.active_panel inv:SetTitle('Inventory') end }) end function Inventories:OnInventoryRebuild(panel) if panel:get_inventory_type() == 'pockets' then local parent = panel:GetParent() panel:SizeToContents() panel:SetWide(math.min(panel:GetWide(), parent.main_inventory:GetWide())) end end function Inventories:create_hotbar() local hotbar = PLAYER:get_inventory('hotbar'):create_panel() hotbar:set_slot_size(math.scale(80)) hotbar:set_slot_padding(math.scale(8)) hotbar:draw_inventory_slots(true) hotbar:set_title() hotbar:SizeToContents() hotbar:SetPos(ScrW() * 0.5 - hotbar:GetWide() * 0.5, ScrH() - hotbar:GetTall() - math.scale(16)) return hotbar end function Inventories:popup_hotbar() if !IsValid(PLAYER.hotbar) then PLAYER.hotbar = Inventories:create_hotbar() PLAYER.hotbar:rebuild() timer.create('fl_hotbar_popup', 0.05, 0, function() if IsValid(PLAYER.hotbar) then local alpha = PLAYER.hotbar:GetAlpha() PLAYER.hotbar:SetAlpha(alpha - 5) if alpha <= 50 then PLAYER.hotbar:safe_remove() end else timer.destroy('fl_hotbar_popup') end end) else PLAYER.hotbar:SetAlpha(255) end end function Inventories:OnMenuPanelOpen(menu_panel, active_panel) if PLAYER.opened_containers then for k, v in pairs(PLAYER.opened_containers) do if IsValid(v) then v:safe_remove() end end PLAYER.opened_containers = {} end end function Inventories:CanItemMenuOpen(item_obj) local inventory = Inventories.find(item_obj.inventory_id) if inventory and inventory.instance_id then return false end end Cable.receive('fl_inventory_sync', function(data) local inventory = Inventories.stored[data.id] or Inventory.new(data.id) inventory.id = data.id inventory.title = data.title inventory.icon = data.icon inventory.type = data.inv_type inventory.width = data.width inventory.height = data.height inventory.slots = data.slots inventory.multislot = data.multislot inventory.disabled = data.disabled inventory.owner = data.owner inventory.instance_id = data.instance_id if data.owner and data.owner == PLAYER then PLAYER.inventories = PLAYER.inventories or {} PLAYER.inventories[inventory.type] = inventory end if IsValid(inventory.panel) then inventory.panel:rebuild() end hook.run('OnInventorySync', inventory) end) Cable.receive('fl_rebuild_player_panel', function() if IsValid(Flux.tab_menu) and Flux.tab_menu:IsVisible() then local active_panel = Flux.tab_menu.active_panel if IsValid(active_panel) and active_panel.id == 'inventory' then local player_model = active_panel.player_model if IsValid(player_model) then player_model:rebuild() end end end end) Cable.receive('fl_open_player_inventory', function(player, inventory_ids) local inventory = vgui.create('fl_inventory_container') inventory:open_player_inventories(player, inventory_ids) Flux.container_panel = inventory end) Cable.receive('fl_inventory_open', function(inventory_id) if !IsValid(Flux.tab_menu) and !IsValid(Flux.container_panel) then local inventory = vgui.create('fl_inventory_container') inventory:open_inventory(inventory_id) Flux.container_panel = inventory else local inventory = Inventories.find(inventory_id) local item_obj = Item.find_instance_by_id(inventory.instance_id) local parent = IsValid(Flux.tab_menu) and Flux.tab_menu or IsValid(Flux.container_panel) and Flux.container_panel or nil local frame = vgui.create('fl_frame', parent) local inventory_panel = inventory:create_panel(frame) inventory_panel:set_title() inventory_panel:SizeToContents() inventory_panel:rebuild() inventory_panel:Dock(FILL) local left, top, right, bottom = frame:GetDockPadding() frame:set_title(t(item_obj:get_name())) frame:set_draggable(true) frame:SetSize(inventory_panel:GetWide() + left + right, inventory_panel:GetTall() + top + bottom) frame:SetPos(input.GetCursorPos()) frame:MoveToFront() frame.inventory = inventory frame.OnRemove = function() local inventory_id = frame.inventory.id Cable.send('fl_inventory_close', inventory_id) PLAYER.opened_containers[inventory_id] = nil end PLAYER.opened_containers = PLAYER.opened_containers or {} PLAYER.opened_containers[inventory_id] = frame end end) Cable.receive('fl_inventory_close', function(inventory_id) if inventory_id then local inventory_panel = PLAYER.opened_containers[inventory_id] if IsValid(inventory_panel) then inventory_panel:safe_remove() end else if IsValid(Flux.container_panel) then Flux.container_panel:safe_remove() end end end) local function create_item_icon(item_obj, parent) local icon = spawnmenu.CreateContentIcon('model', parent, { model = item_obj:get_model(), skin = item_obj:get_skin(), wide = math.scale(128), tall = math.scale(128) }) local padding = math.scale(4) icon:DockPadding(padding, padding, padding, padding) local name_label = vgui.create('DLabel', icon) name_label:SetText(t(item_obj:get_real_name())) name_label:Dock(BOTTOM) name_label:SetTextColor(color_white) name_label:SetFont(Theme.get_font('text_bar')) name_label:SetWrap(true) name_label:SetAutoStretchVertical(true) padding = math.scale(2) name_label.Paint = function(pnl, w, h) DisableClipping(true) draw.RoundedBox(math.scale(4), -padding, -padding, w + padding * 2, h + padding * 2, Color(0, 0, 0, 150)) DisableClipping(false) end icon:SetToolTip(t(item_obj:get_real_name())..'\n'..t(item_obj:get_description())) icon.DoRightClick = function(pnl) local derma_menu = DermaMenu() local give_self = derma_menu:AddSubMenu(t'ui.spawnmenu.give.self') if item_obj.stackable then give_self:AddOption(t'ui.spawnmenu.give.stack', function() MVC.push('SpawnMenu::GiveItem', PLAYER, item_obj.id, item_obj.max_stack) end) end give_self:AddOption(t'ui.spawnmenu.give.one', function() MVC.push('SpawnMenu::GiveItem', PLAYER, item_obj.id, 1) end) local players = player.all() if #players > 1 then local give_player = derma_menu:AddSubMenu(t'ui.spawnmenu.give.player') for k, v in ipairs(players) do if PLAYER == v then continue end local player_line = give_player:AddSubMenu(v:Name()) if item_obj.stackable then player_line:AddOption(t'ui.spawnmenu.give.stack', function() MVC.push('SpawnMenu::GiveItem', v, item_obj.id, item_obj.max_stack) end) end player_line:AddOption(t'ui.spawnmenu.give.one', function() MVC.push('SpawnMenu::GiveItem', v, item_obj.id, 1) end) end end derma_menu:Open() end return icon end function Inventories:spawnmenu_populate_items(content_panel, tree, node) local categories = {} for id, item_obj in pairs(Item.all()) do if !categories[item_obj.category] then categories[item_obj.category] = {} end table.insert(categories[item_obj.category], item_obj) end for name, category in pairs(categories) do local node = tree:AddNode(t(name), Item.get_category_icon(name)) node.DoPopulate = function(pnl) if IsValid(pnl.list) then return end pnl.list = vgui.create('ContentContainer', content_panel) pnl.list:SetVisible(false) pnl.list:SetTriggerSpawnlistChange(false) for k, item_obj in SortedPairsByMemberValue(category, 'name') do local icon = create_item_icon(item_obj, pnl.list) icon.DoClick = function(pnl) MVC.push('SpawnMenu::SpawnItem', item_obj.id) end end end node.DoClick = function(pnl) pnl:DoPopulate() content_panel:SwitchPanel(pnl.list) end end end function Inventories:PopulateSpawnMenu() spawnmenu.AddCreationTab(t'ui.spawnmenu.items', function() local panel = vgui.Create('SpawnmenuContentPanel') panel:EnableSearch('items', 'spawnmenu_populate_items') panel:CallPopulateHook('spawnmenu_populate_items') return panel end, 'icon16/briefcase.png', 40) end search.AddProvider(function(query) query = query:utf8lower() local results = {} for k, item_obj in pairs(Item.all()) do if t(item_obj:get_name()):utf8lower():find(query) then table.insert(results, { text = item_obj.id, func = function() MVC.push('SpawnMenu::SpawnItem', item_obj.id) end, icon = create_item_icon(item_obj), words = { item_obj } }) end end return results end, 'items') concommand.Add('fl_icon_editor', function() if IsValid(Flux.icon_editor) then Flux.icon_editor:safe_remove() end Flux.icon_editor = vgui.create('fl_icon_editor') end)
AuctionatorFullScanFrameMixin = {} local FULL_SCAN_EVENTS = { "REPLICATE_ITEM_LIST_UPDATE", "AUCTION_HOUSE_CLOSED" } function AuctionatorFullScanFrameMixin:OnLoad() Auctionator.Debug.Message("AuctionatorFullScanFrameMixin:OnLoad") Auctionator.EventBus:RegisterSource(self, "AuctionatorFullScanFrameMixin") -- Updates to self.state should store in the SAVED_VARIABLE self.state = Auctionator.SavedState end function AuctionatorFullScanFrameMixin:ResetData() self.scanData = {} end function AuctionatorFullScanFrameMixin:InitiateScan() if self:CanInitiate() then Auctionator.EventBus:Fire(self, Auctionator.FullScan.Events.ScanStart) self.state.TimeOfLastScan = time() self.inProgress = true self:RegisterForEvents() Auctionator.Utilities.Message(Auctionator.Locales.Apply("STARTING_FULL_SCAN")) Auctionator.AH.ReplicateItems() -- 10% complete after making the replicate request Auctionator.EventBus:Fire(self, Auctionator.FullScan.Events.ScanProgress, 0.1) else Auctionator.Utilities.Message(self:NextScanMessage()) end end function AuctionatorFullScanFrameMixin:CanInitiate() return ( self.state.TimeOfLastScan ~= nil and time() - self.state.TimeOfLastScan > 60 * 15 and not self.inProgress ) or self.state.TimeOfLastScan == nil end function AuctionatorFullScanFrameMixin:NextScanMessage() local timeSinceLastScan = time() - self.state.TimeOfLastScan local minutesUntilNextScan = 15 - math.floor(timeSinceLastScan / 60) - 1 local secondsUntilNextScan = (15 * 60 - timeSinceLastScan) % 60 return Auctionator.Locales.Apply( "NEXT_SCAN_MESSAGE", minutesUntilNextScan, secondsUntilNextScan ) end function AuctionatorFullScanFrameMixin:RegisterForEvents() Auctionator.Debug.Message("AuctionatorFullScanFrameMixin:RegisterForEvents()") FrameUtil.RegisterFrameForEvents(self, FULL_SCAN_EVENTS) end function AuctionatorFullScanFrameMixin:UnregisterForEvents() Auctionator.Debug.Message("AuctionatorFullScanFrameMixin:UnregisterForEvents()") FrameUtil.UnregisterFrameForEvents(self, FULL_SCAN_EVENTS) end function AuctionatorFullScanFrameMixin:CacheScanData() -- 20% complete after server response Auctionator.EventBus:Fire(self, Auctionator.FullScan.Events.ScanProgress, 0.2) self:ResetData() self.waitingForData = C_AuctionHouse.GetNumReplicateItems() self:ProcessBatch( 0, Auctionator.Config.Get(Auctionator.Config.Options.FULL_SCAN_STEP), self.waitingForData ) end function AuctionatorFullScanFrameMixin:ProcessBatch(startIndex, stepSize, limit) if startIndex >= limit then return end -- 20-100% complete when 0-100% through caching the scan Auctionator.EventBus:Fire(self, Auctionator.FullScan.Events.ScanProgress, 0.2 + startIndex/limit*0.8 ) Auctionator.Debug.Message("AuctionatorFullScanFrameMixin:ProcessBatch (links)", startIndex, stepSize, limit) local i = startIndex while i < startIndex+stepSize and i < limit do local info = { C_AuctionHouse.GetReplicateItemInfo(i) } local link = C_AuctionHouse.GetReplicateItemLink(i) local timeLeft = C_AuctionHouse.GetReplicateItemTimeLeft(i) if not info[18] then local item = Item:CreateFromItemID(info[17]) item:ContinueOnItemLoad((function(index) return function() self.waitingForData = self.waitingForData - 1 table.insert(self.scanData, { replicateInfo = { C_AuctionHouse.GetReplicateItemInfo(index) }, itemLink = C_AuctionHouse.GetReplicateItemLink(index), timeLeft = C_AuctionHouse.GetReplicateItemTimeLeft(index) }) if self.waitingForData == 0 then self:EndProcessing() end end end)(i)) else self.waitingForData = self.waitingForData - 1 table.insert(self.scanData, { replicateInfo = info, itemLink = link, timeLeft = timeLeft }) end i = i + 1 end C_Timer.After(0.01, function() self:ProcessBatch(startIndex + stepSize, stepSize, limit) end) if self.waitingForData == 0 then self:EndProcessing() end end function AuctionatorFullScanFrameMixin:OnEvent(event, ...) if event == "REPLICATE_ITEM_LIST_UPDATE" then Auctionator.Debug.Message("REPLICATE_ITEM_LIST_UPDATE") FrameUtil.UnregisterFrameForEvents(self, { "REPLICATE_ITEM_LIST_UPDATE" }) self:CacheScanData() elseif event =="AUCTION_HOUSE_CLOSED" then self:UnregisterForEvents() if self.inProgress then self.inProgress = false self:ResetData() Auctionator.Utilities.Message( Auctionator.Locales.Apply("FULL_SCAN_FAILED") .. " " .. self:NextScanMessage() ) Auctionator.EventBus:Fire(self, Auctionator.FullScan.Events.ScanFailed) end end end local function GetInfo(replicateInfo, itemLink) local count = replicateInfo[3] local buyoutPrice = replicateInfo[10] local effectivePrice = buyoutPrice / count local itemKey = Auctionator.Utilities.ItemKeyFromLink(itemLink) return itemKey, effectivePrice end function AuctionatorFullScanFrameMixin:EndProcessing() local rawFullScan = self.scanData local count = Auctionator.Database.ProcessScan(self:MergePrices()) Auctionator.Utilities.Message(Auctionator.Locales.Apply("FINISHED_PROCESSING", count)) self.inProgress = false self:ResetData() self:UnregisterForEvents() Auctionator.EventBus:Fire(self, Auctionator.FullScan.Events.ScanComplete, rawFullScan) end function AuctionatorFullScanFrameMixin:MergePrices() local prices = {} local index = 0 for index = 1, #self.scanData do local itemKey, effectivePrice = GetInfo(self.scanData[index].replicateInfo, self.scanData[index].itemLink) if prices[itemKey] == nil then prices[itemKey] = { effectivePrice } else table.insert(prices[itemKey], effectivePrice) end index = index + 1 end return prices end
return { include = function() includedirs { "../vendor/tinygltf/" } defines { "TINYGLTF_USE_CPP14", "TINYGLTF_NO_INCLUDE_JSON" } end, run = function() language 'C++' kind 'StaticLib' files { 'vendor/tinygltf.cpp' } end }
local re = require 'parser.relabel' local m = require 'lpeglabel' local ast = require 'parser.ast' local scriptBuf = '' local compiled = {} local parser local defs = ast.defs -- goto 可以作为名字,合法性之后处理 local RESERVED = { ['and'] = true, ['continue'] = true, ['break'] = true, ['do'] = true, ['else'] = true, ['elseif'] = true, ['end'] = true, ['false'] = true, ['for'] = true, ['function'] = true, ['if'] = true, ['in'] = true, ['local'] = true, ['nil'] = true, ['not'] = true, ['or'] = true, ['repeat'] = true, ['return'] = true, ['then'] = true, ['true'] = true, ['until'] = true, ['while'] = true, } defs.nl = (m.P'\r\n' + m.S'\r\n') defs.s = m.S' \t' defs.S = - defs.s defs.ea = '\a' defs.eb = '\b' defs.ef = '\f' defs.en = '\n' defs.er = '\r' defs.et = '\t' defs.ev = '\v' defs['nil'] = m.Cp() / function () return nil end defs['false'] = m.Cp() / function () return false end defs.NotReserved = function (_, _, str) if RESERVED[str] then return false end return true end defs.Reserved = function (_, _, str) if RESERVED[str] then return true end return false end defs.None = function () end defs.np = m.Cp() / function (n) return n+1 end m.setmaxstack(1000) local eof = re.compile '!. / %{SYNTAX_ERROR}' local function grammar(tag) return function (script) scriptBuf = script .. '\r\n' .. scriptBuf compiled[tag] = re.compile(scriptBuf, defs) * eof end end local function errorpos(pos, err) return { type = 'UNKNOWN', start = pos or 0, finish = pos or 0, err = err, } end grammar 'Comment' [[ Comment <- LongComment / '--' ShortComment / '//' ShortComment LongComment <- ('--[' {} {:eq: '='* :} {} '[' {(!CommentClose .)*} (CommentClose {} / {} {})) -> LongComment / ( {} '/*' {} (!'*/' .)* {} '*/' {} ) -> CLongComment CommentClose <- (']' =eq ']') CCommentClose <- (!'*/' .)* ShortComment <- (!%nl .)* ]] grammar 'Sp' [[ Sp <- (Comment / %nl / %s)* Sps <- (Comment / %nl / %s)+ ]] grammar 'Common' [[ Word <- [a-zA-Z0-9_] Cut <- !Word X16 <- [a-fA-F0-9] Rest <- (!%nl .)* AND <- Sp {} {'and'} Cut CAND <- Sp {} {'&&'} BREAK <- Sp 'break' Cut CONTINUE <- Sp 'continue' Cut DO <- Sp 'do' Cut / Sp ({} 'then' Cut {}) -> ErrDo ELSE <- Sp 'else' Cut ELSEIF <- Sp 'elseif' Cut END <- Sp 'end' Cut FALSE <- Sp 'false' Cut FOR <- Sp 'for' Cut FUNCTION <- Sp 'function' Cut GOTO <- Sp 'goto' Cut IF <- Sp 'if' Cut IN <- Sp 'in' Cut LOCAL <- Sp 'local' Cut NIL <- Sp 'nil' Cut NOT <- Sp 'not' Cut OR <- Sp {'or'} Cut COR <- Sp {'||'} REPEAT <- Sp 'repeat' Cut RETURN <- Sp 'return' Cut THEN <- Sp 'then' Cut / Sp ({} 'do' Cut {}) -> ErrThen TRUE <- Sp 'true' Cut UNTIL <- Sp 'until' Cut WHILE <- Sp 'while' Cut Esc <- '\' -> '' EChar EChar <- 'a' -> ea / 'b' -> eb / 'f' -> ef / 'n' -> en / 'r' -> er / 't' -> et / 'v' -> ev / '\' / '"' / "'" / %nl / ('z' (%nl / %s)*) -> '' / ({} 'x' {X16 X16}) -> Char16 / ([0-9] [0-9]? [0-9]?) -> Char10 / ('u{' {} {Word*} '}') -> CharUtf8 -- 错误处理 / 'x' {} -> MissEscX / 'u' !'{' {} -> MissTL / 'u{' Word* !'}' {} -> MissTR / {} -> ErrEsc BOR <- Sp {'|'} BXOR <- Sp {'~'} !'=' BAND <- Sp {'&'} Bshift <- Sp {BshiftList} BshiftList <- '<<' / '>>' Concat <- Sp {'..'} Adds <- Sp {AddsList} AddsList <- '+' / '-' Muls <- Sp {MulsList} MulsList <- '*' / '//' / '/' / '%' Unary <- Sp {} {UnaryList} UnaryList <- NOT / '!' !'=' / '#' / '-' / '~' !'=' POWER <- Sp {'^'} BinaryOp <- Sp {} {'or'} Cut / Sp {} {'and'} Cut / Sp {} {'<=' / '>=' / '<'!'<' / '>'!'>' / '~=' / '!=' / '=='} / Sp {} ({} '=' {}) -> ErrEQ / Sp {} {'||'} / Sp {} {'|'} / Sp {} {'!'} / Sp {} {'&&'} / Sp {} {'~'} / Sp {} {'&'} / Sp {} {'<<' / '>>'} / Sp {} {'..'} !'.' / Sp {} {'+' / '-'} / Sp {} {'*' / '//' / '/' / '%'} / Sp {} {'^'} UnaryOp <- Sp {} {'not' Cut / '#' / '!' !'=' / '~' !'=' / '-' !'-'} PL <- Sp '(' PR <- Sp ')' BL <- Sp '[' !'[' !'=' BR <- Sp ']' TL <- Sp '{' TR <- Sp '}' COMMA <- Sp ',' SEMICOLON <- Sp ';' DOTS <- Sp ({} '...') -> DOTS DOT <- Sp ({} '.' !'.') -> DOT COLON <- Sp ({} ':' !':') -> COLON LABEL <- Sp '::' ASSIGN <- Sp '=' !'=' AssignOrEQ <- Sp ({} '==' {}) -> ErrAssign / Sp '=' Nothing <- {} -> Nothing DirtyBR <- BR {} / {} -> MissBR DirtyTR <- TR {} / {} -> MissTR DirtyPR <- PR {} / {} -> DirtyPR DirtyLabel <- LABEL / {} -> MissLabel NeedPR <- PR / {} -> MissPR NeedEnd <- END / {} -> MissEnd NeedDo <- DO / {} -> MissDo NeedAssign <- ASSIGN / {} -> MissAssign NeedComma <- COMMA / {} -> MissComma NeedIn <- IN / {} -> MissIn NeedUntil <- UNTIL / {} -> MissUntil ]] grammar 'Nil' [[ Nil <- Sp ({} -> Nil) NIL ]] grammar 'Boolean' [[ Boolean <- Sp ({} -> True) TRUE / Sp ({} -> False) FALSE ]] grammar 'String' [[ String <- Sp ({} StringDef {}) -> String StringDef <- {'"'} {~(Esc / !%nl !'"' .)*~} -> 1 ('"' / {} -> MissQuote1) / {"'"} {~(Esc / !%nl !"'" .)*~} -> 1 ("'" / {} -> MissQuote2) / ('[' {} {:eq: '='* :} {} '[' %nl? {(!StringClose .)*} -> 1 (StringClose / {})) -> LongString StringClose <- ']' =eq ']' ]] grammar 'Number' [[ Number <- Sp ({} {NumberDef} {}) -> Number NumberSuffix? ErrNumber? NumberDef <- Number16 / Number10 NumberSuffix<- ({} {[uU]? [lL] [lL]}) -> FFINumber / ({} {[iI]}) -> ImaginaryNumber ErrNumber <- ({} {([0-9a-zA-Z] / '.')+}) -> UnknownSymbol Number10 <- Float10 Float10Exp? / Integer10 Float10? Float10Exp? Integer10 <- [0-9]+ ('.' [0-9]*)? Float10 <- '.' [0-9]+ Float10Exp <- [eE] [+-]? [0-9]+ / ({} [eE] [+-]? {}) -> MissExponent Number16 <- '0' [xX] Float16 Float16Exp? / '0' [xX] Integer16 Float16? Float16Exp? Integer16 <- X16+ ('.' X16*)? / ({} {Word*}) -> MustX16 Float16 <- '.' X16+ / '.' ({} {Word*}) -> MustX16 Float16Exp <- [pP] [+-]? [0-9]+ / ({} [pP] [+-]? {}) -> MissExponent ]] grammar 'Name' [[ Name <- Sp ({} NameBody {}) -> Name NameBody <- {[a-zA-Z_] [a-zA-Z0-9_]*} FreeName <- Sp ({} {NameBody=>NotReserved} {}) -> Name MustName <- Name / DirtyName DirtyName <- {} -> DirtyName ]] grammar 'Exp' [[ Exp <- (UnUnit (BinaryOp (UnUnit / {} -> DirtyExp))*) -> Exp UnUnit <- ExpUnit / UnaryOp+ (ExpUnit / {} -> DirtyExp) ExpUnit <- Nil / Boolean / String / Number / DOTS -> DotsAsExp / Table / Function / Simple Simple <- (Prefix (Sp Suffix)*) -> Simple Prefix <- Sp ({} PL DirtyExp DirtyPR) -> Prefix / FreeName Index <- ({} BL DirtyExp DirtyBR) -> Index Suffix <- DOT Name / DOT {} -> MissField / Method (!(Sp CallStart) {} -> MissPL)? / ({} Table {}) -> Call / ({} String {}) -> Call / Index / ({} PL CallArgList DirtyPR) -> Call Method <- COLON Name / COLON {} -> MissMethod CallStart <- PL / TL / '"' / "'" / '/*' / '[' '='* '[' DirtyExp <- Exp / {} -> DirtyExp MaybeExp <- Exp / MissExp MissExp <- {} -> MissExp ExpList <- Sp (MaybeExp (COMMA (MaybeExp))*) -> List MustExpList <- Sp (Exp (COMMA (MaybeExp))*) -> List CallArgList <- Sp ({} (COMMA {} / Exp)+ {}) -> CallArgList / %nil NameList <- (MustName (COMMA MustName)*) -> List ArgList <- (DOTS -> DotsAsArg / Name / Sp {} COMMA)* -> ArgList Table <- Sp ({} TL TableFields? DirtyTR) -> Table TableFields <- (Emmy / TableSep {} / TableField)+ TableSep <- COMMA / SEMICOLON TableField <- NewIndex / NewField / Exp NewIndex <- Sp (Index NeedAssign DirtyExp) -> NewIndex NewField <- (MustName ASSIGN DirtyExp) -> NewField Function <- Sp ({} FunctionBody {}) -> Function FuncArg <- PL {} ArgList {} NeedPR / {} {} -> MissPL Nothing {} FunctionBody<- FUNCTION BlockStart FuncArg (Emmy / !END Action)* BlockEnd NeedEnd BlockStart <- {} -> BlockStart BlockEnd <- {} -> BlockEnd -- 纯占位,修改了 `relabel.lua` 使重复定义不抛错 Action <- !END . Set <- END Emmy <- '---@' ]] grammar 'Action' [[ Action <- Sp (CrtAction / UnkAction) CrtAction <- Semicolon / Do / Break / Continue / Return / Label / GoTo / If / For / While / Repeat / NamedFunction / LocalFunction / Local / Set / Call / ExpInAction UnkAction <- ({} {Word+}) -> UnknownAction / ({} {. (!Sps !CrtAction .)*}) -> UnknownAction ExpInAction <- Sp ({} Exp {}) -> ExpInAction Semicolon <- SEMICOLON -> Skip SimpleList <- (Simple (COMMA Simple)*) -> List Do <- Sp ({} 'do' Cut DoBody NeedEnd {}) -> Do DoBody <- (Emmy / !END Action)* -> DoBody Break <- BREAK ({} Semicolon* AfterBreak?) -> Break AfterBreak <- Sp !END !UNTIL !ELSEIF !ELSE Action BreakStart <- {} -> BreakStart BreakEnd <- {} -> BreakEnd Continue <- CONTINUE ({} Semicolon* AfterContinue?) -> Continue AfterContinue <- Sp !END !UNTIL !ELSEIF !ELSE Action ContinueStart <- {} -> ContinueStart ContinueEnd <- {} -> ContinueEnd Return <- (ReturnBody Semicolon* AfterReturn?) -> AfterReturn ReturnBody <- Sp ({} RETURN MustExpList? {}) -> Return AfterReturn <- Sp !END !UNTIL !ELSEIF !ELSE Action Label <- Sp ({} LABEL MustName DirtyLabel {}) -> Label GoTo <- Sp ({} GOTO MustName {}) -> GoTo If <- Sp ({} IfBody {}) -> If IfHead <- (IfPart -> IfBlock) / ({} ElseIfPart -> ElseIfBlock) -> MissIf / ({} ElsePart -> ElseBlock) -> MissIf IfBody <- IfHead (ElseIfPart -> ElseIfBlock)* (ElsePart -> ElseBlock)? NeedEnd IfPart <- IF DirtyExp THEN {} (Emmy / !ELSEIF !ELSE !END Action)* {} / IF DirtyExp {}->MissThen {} {} ElseIfPart <- ELSEIF DirtyExp THEN {} (Emmy / !ELSE !ELSEIF !END Action)* {} / ELSEIF DirtyExp {}->MissThen {} {} ElsePart <- ELSE {} (Emmy / !END Action)* {} For <- Loop / In / FOR Loop <- Sp ({} LoopBody {}) -> Loop LoopBody <- FOR LoopStart LoopFinish LoopStep NeedDo BreakStart ContinueStart (Emmy / !END Action)* ContinueEnd BreakEnd NeedEnd LoopStart <- MustName AssignOrEQ DirtyExp LoopFinish <- NeedComma DirtyExp LoopStep <- COMMA DirtyExp / NeedComma Exp / Nothing In <- Sp ({} InBody {}) -> In InBody <- FOR InNameList NeedIn ExpList NeedDo BreakStart ContinueStart (Emmy / !END Action)* ContinueEnd BreakEnd NeedEnd InNameList <- &IN DirtyName / NameList While <- Sp ({} WhileBody {}) -> While WhileBody <- WHILE DirtyExp NeedDo BreakStart ContinueStart (Emmy / !END Action)* ContinueEnd BreakEnd NeedEnd Repeat <- Sp ({} RepeatBody {}) -> Repeat RepeatBody <- REPEAT BreakStart ContinueStart (Emmy / !UNTIL Action)* ContinueEnd BreakEnd NeedUntil DirtyExp LocalTag <- (Sp '<' Sp MustName Sp LocalTagEnd)* -> LocalTag LocalTagEnd <- '>' / {} -> MissGT Local <- (LOCAL LocalNameList (AssignOrEQ ExpList)?) -> Local Set <- (SimpleList AssignOrEQ ExpList?) -> Set LocalNameList <- (LocalName (COMMA LocalName)*) -> List LocalName <- (MustName LocalTag) -> LocalName Call <- Simple -> SimpleCall LocalFunction <- Sp ({} LOCAL FunctionNamedBody {}) -> LocalFunction NamedFunction <- Sp ({} FunctionNamedBody {}) -> NamedFunction FunctionNamedBody <- FUNCTION FuncName BlockStart FuncArg (Emmy / !END Action)* BlockEnd NeedEnd FuncName <- (MustName (DOT MustName)* FuncMethod?) -> Simple FuncMethod <- COLON Name / COLON {} -> MissMethod -- 占位 Emmy <- '---@' ]] grammar 'Emmy' [[ Emmy <- EmmyAction / EmmyComments EmmyAction <- EmmySp '---' %s* '@' EmmyBody ShortComment EmmySp <- (!'---' Comment / %s / %nl)* EmmyComments <- EmmyComment+ -> EmmyComment EmmyComment <- EmmySp '---' %s* !'@' {(!%nl .)*} EmmyBody <- 'class' %s+ EmmyClass -> EmmyClass / 'type' %s+ EmmyType -> EmmyType / 'alias' %s+ EmmyAlias -> EmmyAlias / 'param' %s+ EmmyParam -> EmmyParam / 'return' %s+ EmmyReturn -> EmmyReturn / 'field' %s+ EmmyField -> EmmyField / 'generic' %s+ EmmyGeneric -> EmmyGeneric / 'vararg' %s+ EmmyVararg -> EmmyVararg / 'language' %s+ EmmyLanguage -> EmmyLanguage / 'see' %s+ EmmySee -> EmmySee / 'overload' %s+ EmmyOverLoad -> EmmyOverLoad / EmmyIncomplete EmmyName <- ({} {[a-zA-Z_] [a-zA-Z0-9_.]*}) -> EmmyName MustEmmyName <- EmmyName / DirtyEmmyName DirtyEmmyName <- {} -> DirtyEmmyName EmmyLongName <- ({} {(!%nl .)+}) -> EmmyName EmmyIncomplete <- MustEmmyName -> EmmyIncomplete EmmyClass <- (MustEmmyName EmmyParentClass?) EmmyParentClass <- %s* {} ':' %s* MustEmmyName EmmyType <- EmmyFunctionType / EmmyTableType / EmmyArrayType / EmmyCommonType EmmyCommonType <- EmmyTypeNames -> EmmyCommonType EmmyTypeNames <- EmmyTypeName (%s* {} '|' %s* !String EmmyTypeName)* EmmyTypeName <- EmmyFunctionType / EmmyTableType / EmmyArrayType / MustEmmyName EmmyTypeEnum <- %s* (%nl %s* '---')? '|' EmmyEnum -> EmmyTypeEnum EmmyEnum <- %s* {'>'?} %s* String (EmmyEnumComment / (!%nl !'|' .)*) EmmyEnumComment <- %s* '#' %s* {(!%nl .)*} EmmyAlias <- MustEmmyName %s* EmmyType EmmyTypeEnum* EmmyParam <- MustEmmyName %s* EmmyType %s* EmmyOption %s* EmmyTypeEnum* EmmyOption <- Table? -> EmmyOption EmmyReturn <- {} %nil %nil {} Table -> EmmyOption / {} EmmyType (%s* EmmyName/%nil) {} EmmyOption EmmyField <- (EmmyFieldAccess MustEmmyName %s* EmmyType) EmmyFieldAccess <- ({'public'} Cut %s*) / ({'protected'} Cut %s*) / ({'private'} Cut %s*) / {} -> 'public' EmmyGeneric <- EmmyGenericBlock (%s* ',' %s* EmmyGenericBlock)* EmmyGenericBlock<- (MustEmmyName %s* (':' %s* EmmyType)?) -> EmmyGenericBlock EmmyVararg <- EmmyType EmmyLanguage <- MustEmmyName EmmyArrayType <- ({} MustEmmyName -> EmmyCommonType {} '[' DirtyBR) -> EmmyArrayType / ({} PL EmmyCommonType DirtyPR '[' DirtyBR) -> EmmyArrayType EmmyTableType <- ({} 'table' Cut '<' %s* EmmyType %s* ',' %s* EmmyType %s* '>' {}) -> EmmyTableType EmmyFunctionType<- ({} 'fun' Cut %s* EmmyFunctionArgs %s* EmmyFunctionRtns {}) -> EmmyFunctionType EmmyFunctionArgs<- ('(' %s* EmmyFunctionArg %s* (',' %s* EmmyFunctionArg %s*)* DirtyPR) -> EmmyFunctionArgs / '(' %nil DirtyPR -> None / %nil EmmyFunctionRtns<- (':' %s* EmmyType (%s* ',' %s* EmmyType)*) -> EmmyFunctionRtns / %nil EmmyFunctionArg <- MustEmmyName %s* ':' %s* EmmyType EmmySee <- {} MustEmmyName %s* '#' %s* MustEmmyName {} EmmyOverLoad <- EmmyFunctionType ]] grammar 'Lua' [[ Lua <- Head? (Emmy / Action)* -> Lua BlockEnd Sp Head <- '#' (!%nl .)* ]] return function (self, lua, mode) local gram = compiled[mode] or compiled['Lua'] local r, _, pos = gram:match(lua) if not r then local err = errorpos(pos) return nil, err end return r end
-- Name: drawing.lua currentColor = { r = 255, g = 255, b = 255, a = 255 } function setColorGL(r,g,b,a) currentColor = { r = r, g = g, b = b, a = a } colorGL(currentColor.r, currentColor.g, currentColor.b, currentColor.a) end function shade(f) currentColor.r = currentColor.r * f currentColor.g = currentColor.g * f currentColor.b = currentColor.b * f if currentColor.r < 0 then currentColor.r = 0 end if currentColor.g < 0 then currentColor.g = 0 end if currentColor.b < 0 then currentColor.b = 0 end if currentColor.r > 255 then currentColor.r = 255 end if currentColor.g > 255 then currentColor.g = 255 end if currentColor.b > 255 then currentColor.b = 255 end colorGL(currentColor.r, currentColor.g, currentColor.b, currentColor.a) end function drawTriangleGL(p1,p2,p3) local norm = Vector3D.cross(p2-p1, p3-p1) norm = Vector3D.normalize(norm) normalGL(norm.x, norm.y, norm.z) vectorGL(p1.x, p1.y, p1.z) normalGL(norm.x, norm.y, norm.z) vectorGL(p2.x, p2.y, p2.z) normalGL(norm.x, norm.y, norm.z) vectorGL(p3.x, p3.y, p3.z) end function drawPolygon(pos,r,n,s,h) beginTriGL() angstep = (math.pi * 2) / n for i=s,math.pi * 2+s,angstep do shade(0.95) local p1 = vec2d(r*math.cos(i ), r*math.sin(i )) local p2 = vec2d(r*math.cos(i+angstep), r*math.sin(i+angstep)) local pos2 = pos + vec3d(0,h,0) drawTriangleGL(pos, pos+p1, pos+p2) drawTriangleGL(pos2, pos2+p2, pos2+p1) -- now draw the connecting quad drawTriangleGL(pos+p2, pos+p1, pos2+p1) drawTriangleGL(pos2+p1, pos2+p2, pos+p2) end endGL() end function drawCurve(p1, p2) --disableLighting() colorGL(0,255,0,255) beginLinGL() for t=0,0.801,0.01 do local pos1 = calcCurve(p1,p2,t) local pos2 = calcCurve(p1,p2,t+0.2) --local pos2 = calcCurve(p1,p2,t+0.01) normalGL(0,1,0) vectorGL(pos1.x, pos1.y, pos1.z) normalGL(0,1,0) vectorGL(pos2.x, pos2.y, pos2.z) --drawLine(pos1.x, pos1.y, pos1.z, -- pos2.x, pos2.y, pos2.z) end endGL() --enableLighting() end function drawTexQuad(pos,s) enableTexturing() beginQuadGL() texGL(0,0) normalGL(0,1,0) vectorGL(pos.x, pos.y, pos.z) texGL(1,0) normalGL(0,1,0) vectorGL(pos.x, pos.y, pos.z+s) texGL(1,1) normalGL(0,1,0) vectorGL(pos.x+s, pos.y, pos.z+s) texGL(0,1) normalGL(0,1,0) vectorGL(pos.x+s, pos.y, pos.z) endGL() disableTexturing() end function drawEmptyPolygon(pos,r,n,s) angstep = (math.pi * 2) / n for i=s,math.pi * 2+s,angstep do drawLine( pos.x+r*math.cos(i), pos.y, pos.z+r*math.sin(i), pos.x+r*math.cos(i+angstep), pos.y, pos.z+r*math.sin(i+angstep)) end end function drawCircle(pos,r,h) drawPolygon(pos,r,20,0,h) end function drawEmptyCircle(pos,r) drawEmptyPolygon(pos,r,20,0) end function drawSquare(pos,r,h) drawPolygon(pos,r,4,math.pi/4,h) end function drawTriangle(pos,r,h) drawPolygon(pos,r,3,0,h) end function drawArrow(p1, p2, h) p1 = p1 + vec3d(0,h,0) p2 = p2 + vec3d(0,h,0) drawLine(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z) local direction = Vector3D.normalize(p2 - p1) * 2 local perp_direction = Vector3D.normalize(Vector3D.ortho2D(direction)) * 2 local arrow_base = p2 - direction local arrow_left = arrow_base - perp_direction local arrow_right = arrow_base + perp_direction drawLine(p2.x, p2.y, p2.z, arrow_left.x, arrow_left.y, arrow_left.z) drawLine(p2.x, p2.y, p2.z, arrow_right.x, arrow_right.y, arrow_right.z) end function drawBond(p1, p2, h) end
-- network-server 数据处理部分 local DataConverter = require("./dataConverter.lua") local utiles = require("../../utiles/utiles.lua") local logger = require("../log.lua") function process(data) if data == nil then logger.error("data is nil") return nil end logger.info("server data handler start...") if data.type == nil or type(data.type) ~= "string" then logger.error("data.type is nil", data) return nil end if data.data == nil then logger.error("data.data is nil", data) return nil end local ret = nil local retIndex = data.type local retData = data.data while true do retIndex, retData = utiles.switch(retIndex) { ["ConnectorPubToServer"] = function() return DataConverter.uplinkDataHandler(retData) -- Network Connector --> Network Server end, ["ControllerPubToServer"] = function() -- Control Server --> Network Server end, ["JoinPubToServer"] = function() return DataConverter.joinAcceptHandler(retData) -- Join Server --> Network Server end, ["AppPubToServer"] = function() -- if retData.DevAddr == nil or retData.FRMPayload == nil then -- p("Invalid message from kafka, Message ${JSON.stringify(message)}") -- return nil -- end return DataConverter.applicationAcceptHandler(retData) -- Application Server ---> Network Server end, [utiles.Default] = function() logger.error({"data.type is error", retData}) end } logger.info({"retIndex:", retIndex}) if retData == nil or retIndex == "other" then break end end ret = retData logger.info("server module _> connector module, send message") return ret end return { process = process }
-- ############################### -- ## Project: MTA:Speedrace ## -- ## Name: World Class ## -- ## Author: Noneatme ## -- ## Version: 1.0 ## -- ## License: See top Folder ## -- ############################### -- FUNCTIONS / METHODS -- local cFunc = {}; -- Local Functions local cSetting = {}; -- Local Settings World = {}; World.__index = World; -- /////////////////////////////// -- ///// New ////// -- /////////////////////////////// function World:New(...) local obj = setmetatable({}, {__index = self}); if obj.Constructor then obj:Constructor(...); end return obj; end -- /////////////////////////////// -- ///// Start ////// -- /////////////////////////////// function World:Start() -- Wird aufgerufen bei verlassen der Garage loadingScreen:EnableRandom(); vehicleSelector:Stop(); vehicleSelector = nil; cameraMover:StopCam(); vehicleControls = VehicleControls:New(); renderHUD = RenderHUD:New(); localPlayer:JoinWorld(); gameSettings = GameSettings:New(); renderGarage:Destructor(); renderGarage = nil; local ssm = SoundSettingsManager:New(true); ssm.vol1 = ssm.vol1 or 100 ssm.vol2 = ssm.vol2 or 100 soundManager:SetCategoryVolume("sounds", (ssm.vol1/100 or 1)) soundManager:SetCategoryVolume("music", (ssm.vol2/100 or 1)) rtm = RenderTrackPlayer:New(); rtm:GiveTable(ssm.songstable) --rtm:PlayRandom(); ssm:Destructor(); ssm = nil; setTimer(function() loadingScreen:Disable(); showPlayerHudComponent("all", false); rtm:PlayRandom(); rtm:Show(); end, 1000, 1) end -- /////////////////////////////// -- ///// Stop ////// -- /////////////////////////////// function World:Stop() -- Wird aufgerufen bei betreten der Garage loadingScreen:EnableRandom(); vehicleControls:Destructor(); gameSettings:Destructor(); renderHUD:Destructor(); destroyElement(localPlayer:GetVehicle()); localPlayer:JoinGarage(); renderGarage = RenderGarage:New(); garage = nil; garage = Garage:New(); setTimer(function() loadingScreen:Disable(); garage:Start(true); end, 2000, 1) rtm:Destructor(); end -- /////////////////////////////// -- ///// Constructor ////// -- /////////////////////////////// function World:Constructor(...) logger:OutputInfo("[CALLING] World: Constructor"); end -- EVENT HANDLER --
cflags{ '-D HAVE_CONFIG_H', -- it is important that the arch-specific directory is searched first '-I $srcdir/linux/x86_64', '-I $srcdir/linux', '-I $srcdir', '-I $outdir', '-isystem $builddir/pkg/linux-headers/include', } build('cat', '$outdir/config.h', { '$builddir/probe/HAVE___BUILTIN_POPCOUNT', '$dir/config.h', }) build('cpp', '$outdir/ioctl_iocdef.i', '$srcdir/ioctl_iocdef.c') build('sed', '$outdir/ioctl_iocdef.h', '$outdir/ioctl_iocdef.i', { expr=[[-n 's/^DEFINE HOST/#define /p']], }) sub('tools.ninja', function() toolchain(config.host) cflags{ '-D X86_64=1', '-I $srcdir/linux/x86_64', '-I $srcdir/linux', '-I $outdir', } for i = 0, 2 do build('cat', '$outdir/ioctls_all'..i..'.h', { '$srcdir/linux/x86_64/ioctls_inc'..i..'.h', '$srcdir/linux/x86_64/ioctls_arch'..i..'.h', }) build('cc', '$outdir/ioctlsort'..i..'.c.o', { '$srcdir/ioctlsort.c', '|', '$outdir/ioctl_iocdef.h', '$outdir/ioctls_all'..i..'.h', }, {cflags=string.format([[$cflags -D 'IOCTLSORT_INC="ioctls_all%d.h"']], i)}) exe('ioctlsort'..i, {'ioctlsort'..i..'.c.o'}) rule('ioctlsort'..i, '$outdir/ioctlsort'..i..' >$out') build('ioctlsort'..i, '$outdir/ioctlent'..i..'.h', {'|', '$outdir/ioctlsort'..i}) end end) local mpers = lines('mpers.txt') for _, f in ipairs(mpers) do build('cpp', '$outdir/'..f..'.mpers.i', {'$srcdir/'..f, '|', '$outdir/config.h'}, { cflags='$cflags -DIN_MPERS_BOOTSTRAP', }) end local function makempers(name, script) build('awk', '$outdir/'..name, {expand{'$outdir/', mpers, '.mpers.i'}, '|', '$dir/'..script}, { expr='-f $dir/'..script, }) end makempers('printers.h', 'printers.awk') makempers('native_printer_decls.h', 'printerdecls.awk') makempers('native_printer_defs.h', 'printerdefs.awk') build('cpp', '$outdir/syscallent.i', '$srcdir/linux/x86_64/syscallent.h') build('awk', '$outdir/scno-syscallent.h', {'$outdir/syscallent.i', '|', '$dir/scno.awk'}, { expr='-f $dir/scno.awk', }) build('cat', '$outdir/scno.h', {'$srcdir/scno.head', '$outdir/scno-syscallent.h'}) -- this seems to be enough syscall headers to build local syscalls = expand{'$srcdir/linux/', { '32/syscallent.h', '64/syscallent.h', 'arm/syscallent.h', 'i386/syscallent.h', 'sparc/syscallent.h', 'sparc64/syscallent.h', 'subcall.h', 'syscallent-common.h', 'x86_64/syscallent.h', }} build('awk', '$outdir/sen.h', {syscalls, '|', '$dir/sen.awk'}, { expr='-f $dir/sen.awk', }) local srcs = { 'access.c', 'affinity.c', 'aio.c', 'alpha.c', 'basic_filters.c', 'bind.c', 'bjm.c', 'block.c', 'bpf.c', 'bpf_filter.c', 'bpf_seccomp_filter.c', 'bpf_sock_filter.c', 'btrfs.c', 'cacheflush.c', 'capability.c', 'chdir.c', 'chmod.c', 'clone.c', 'close_range.c', 'copy_file_range.c', 'count.c', 'delay.c', 'desc.c', 'dirent.c', 'dirent64.c', 'dirent_types.c', 'dm.c', 'dup.c', 'dyxlat.c', 'epoll.c', 'error_prints.c', 'evdev.c', 'evdev_mpers.c', 'eventfd.c', 'execve.c', 'fadvise.c', 'fallocate.c', 'fanotify.c', 'fchownat.c', 'fcntl.c', 'fetch_bpf_fprog.c', 'fetch_indirect_syscall_args.c', 'fetch_struct_flock.c', 'fetch_struct_keyctl_kdf_params.c', 'fetch_struct_mmsghdr.c', 'fetch_struct_msghdr.c', 'fetch_struct_stat.c', 'fetch_struct_stat64.c', 'fetch_struct_statfs.c', 'fetch_struct_xfs_quotastat.c', 'file_handle.c', 'file_ioctl.c', 'filter_qualify.c', 'filter_seccomp.c', 'flock.c', 'fs_x_ioctl.c', 'fsconfig.c', 'fsmount.c', 'fsopen.c', 'fspick.c', 'fstatfs.c', 'fstatfs64.c', 'futex.c', 'get_personality.c', 'get_robust_list.c', 'getcpu.c', 'getcwd.c', 'getpagesize.c', 'getpid.c', 'getrandom.c', 'hdio.c', 'hostname.c', 'inotify.c', 'inotify_ioctl.c', 'io.c', 'io_uring.c', 'ioctl.c', 'ioperm.c', 'iopl.c', 'ioprio.c', 'ipc.c', 'ipc_msg.c', 'ipc_msgctl.c', 'ipc_sem.c', 'ipc_semctl.c', 'ipc_shm.c', 'ipc_shmctl.c', 'kcmp.c', 'kexec.c', 'keyctl.c', 'kvm.c', 'ldt.c', 'link.c', 'listen.c', 'lookup_dcookie.c', 'loop.c', 'lseek.c', 'mem.c', 'membarrier.c', 'memfd_create.c', 'mknod.c', 'mmap_cache.c', 'mmap_notify.c', 'mmsghdr.c', 'mount.c', 'move_mount.c', 'mq.c', 'msghdr.c', 'mtd.c', 'nbd_ioctl.c', 'net.c', 'netlink.c', 'netlink_crypto.c', 'netlink_inet_diag.c', 'netlink_kobject_uevent.c', 'netlink_netfilter.c', 'netlink_netlink_diag.c', 'netlink_packet_diag.c', 'netlink_route.c', 'netlink_selinux.c', 'netlink_smc_diag.c', 'netlink_sock_diag.c', 'netlink_unix_diag.c', 'nlattr.c', 'nsfs.c', 'numa.c', 'number_set.c', 'oldstat.c', 'open.c', 'open_tree.c', 'or1k_atomic.c', 'pathtrace.c', 'perf.c', 'perf_ioctl.c', 'personality.c', 'pidfd_getfd.c', 'pidfd_open.c', 'pidns.c', 'pkeys.c', 'poll.c', 'prctl.c', 'print_aio_sigset.c', 'print_dev_t.c', 'print_group_req.c', 'print_ifindex.c', 'print_instruction_pointer.c', 'print_kernel_version.c', 'print_mac.c', 'print_mq_attr.c', 'print_msgbuf.c', 'print_sg_req_info.c', 'print_sigevent.c', 'print_statfs.c', 'print_struct_stat.c', 'print_syscall_number.c', 'print_time.c', 'print_timespec32.c', 'print_timespec64.c', 'print_timeval.c', 'print_timeval64.c', 'print_timex.c', 'printmode.c', 'printrusage.c', 'printsiginfo.c', 'process.c', 'process_vm.c', 'ptp.c', 'ptrace_syscall_info.c', 'quota.c', 'random_ioctl.c', 'readahead.c', 'readlink.c', 'reboot.c', 'renameat.c', 'resource.c', 'retval.c', 'riscv.c', 'rt_sigframe.c', 'rt_sigreturn.c', 'rtc.c', 'rtnl_addr.c', 'rtnl_addrlabel.c', 'rtnl_dcb.c', 'rtnl_link.c', 'rtnl_mdb.c', 'rtnl_neigh.c', 'rtnl_neightbl.c', 'rtnl_netconf.c', 'rtnl_nsid.c', 'rtnl_route.c', 'rtnl_rule.c', 'rtnl_tc.c', 'rtnl_tc_action.c', 's390.c', 'sched.c', 'scsi.c', 'seccomp.c', 'sendfile.c', 'sg_io_v3.c', 'sg_io_v4.c', 'shutdown.c', 'sigaltstack.c', 'signal.c', 'signalfd.c', 'sigreturn.c', 'sock.c', 'sockaddr.c', 'socketcall.c', 'socketutils.c', 'sparc.c', 'sram_alloc.c', 'stage_output.c', 'stat.c', 'stat64.c', 'statfs.c', 'statfs64.c', 'statx.c', 'string_to_uint.c', 'swapon.c', 'sync_file_range.c', 'sync_file_range2.c', 'syscall.c', 'sysctl.c', 'sysinfo.c', 'syslog.c', 'sysmips.c', 'tee.c', 'term.c', 'time.c', 'times.c', 'trie.c', 'truncate.c', 'ubi.c', 'ucopy.c', 'uid.c', 'uid16.c', 'umask.c', 'umount.c', 'uname.c', 'upeek.c', 'upoke.c', 'userfaultfd.c', 'ustat.c', 'util.c', 'utime.c', 'utimes.c', 'v4l2.c', 'wait.c', 'watchdog_ioctl.c', 'xattr.c', 'xgetdents.c', 'xlat.c', 'xmalloc.c', } build('sed', '$outdir/sys_func.h', expand{'$srcdir/', srcs}, { expr=[[-n 's/^SYS_FUNC(.*/extern &;/p']], }) pkg.deps = { '$outdir/config.h', '$outdir/ioctlent0.h', '$outdir/ioctlent1.h', '$outdir/ioctlent2.h', '$outdir/native_printer_decls.h', '$outdir/native_printer_defs.h', '$outdir/printers.h', '$outdir/scno.h', '$outdir/sen.h', '$outdir/sys_func.h', 'pkg/linux-headers/headers', } lib('libstrace.a', srcs) exe('strace', {'strace.c', 'libstrace.a'}) file('bin/strace', '755', '$outdir/strace') man{'strace.1'} fetch 'curl'
local _M = { _VERSION = '0.1' } local function _keys(tbl) local ks = {} for k, _ in pairs(tbl) do table.insert( ks, k ) end return ks end local function _repr_opt(opt) opt = opt or {} opt.indent = opt.indent or '' opt.sep = opt.sep or '' return opt end local function _normkey(k, opt) if opt.mode == 'str' then return tostring(k) end local key if type(k) == 'string' and string.match( k, '^[%a_][%w_]*$' ) ~= nil then key = k else key = '['.._M.repr(k)..']' end return key end local function _extend(lst, sublines, opt) for _, sl in ipairs(sublines) do table.insert( lst, opt.indent .. sl ) end lst[ #lst ] = lst[ #lst ] .. ',' end local function _repr_lines(t, opt) local tp = type( t ) if tp == 'string' then local s = string.format('%q', t) if opt.mode == 'str' then -- strip quotes s = s:sub( 2, -2 ) end return { s } elseif tp ~= 'table' then return { tostring(t) } end -- table local keys = _keys(t) if #keys == 0 then return { '{}' } end table.sort( keys, function( a, b ) return tostring(a)<tostring(b) end ) local lst = {'{'} local i = 1 while t[i] ~= nil do local sublines = _repr_lines(t[i], opt) _extend(lst, sublines, opt) i = i+1 end for _, k in ipairs(keys) do if type(k) ~= 'number' or k > i then local sublines = _repr_lines(t[k], opt) sublines[ 1 ] = _normkey(k, opt) ..'='.. sublines[ 1 ] _extend(lst, sublines, opt) end end -- remove the last ',' lst[ #lst ] = lst[ #lst ]:sub( 1, -2 ) table.insert( lst, '}' ) return lst end local function _repr(t, opt) local lst = _repr_lines(t, opt) local sep = opt.sep if opt.indent ~= "" then sep = "\n" end return table.concat( lst, sep ) end function _M.str(t, opt) opt = _repr_opt(opt) opt.mode = 'str' return _repr(t, opt) end function _M.repr(t, opt) opt = _repr_opt(opt) return _repr(t, opt) end return _M
local ContextFuncCompleted local oo = require "loop.base" local Component = oo.class() function Component:context(context) assert(context.__component == self, "invalid component implementation") assert(context.__factory == self.factory, "invalid factory") for _, context in ipairs{ context, context.__reference } do assert(context.facet.name == "facet") assert(context.recep.name == "recep") assert(context.list[1].name == "list") assert(context.hash.key.name == "hash") for _ in context.set:__all() do error("set receptacle is not empty") end end ContextFuncCompleted = true end function Component:check() Component.context(self, self.context) end return function(cpack, ppack) local template = cpack.Template{ facet = ppack.Facet, recep = ppack.Receptacle, list = ppack.ListReceptacle, hash = ppack.HashReceptacle, set = ppack.SetReceptacle, } local factory = template{ Component, facet = function() return {name="facet"} end, recep = function() return {name="recep"} end, list = function() return {{name="list"}} end, hash = function() return {key={name="hash"}} end, } Component.factory = factory factory() -- context is set using method 'context' assert(ContextFuncCompleted == true) ContextFuncCompleted = nil factory{context=false}:check() -- context is placed in field 'context' assert(ContextFuncCompleted == true) end
local function round(num, n) local mult = 10^(n or 0) return math.floor(num * mult + 0.5) / mult end commandArray = {} if (devicechanged['Temperature balcon']) then if ((tonumber(otherdevices_temperature['Temperature balcon']) > tonumber(otherdevices_temperature['Temperature Salon'])) and uservariables['notifsalon'] == '0') then commandArray['SendEmail']='Temperature Balcon#La temperature du Balcon '..round(otherdevices_temperature['Temperature balcon'],2)..'°c est plus elevee que la temperature du Salon '..round(otherdevices_temperature['Temperature Salon'],2)..'°c.#adresse@mail.com' commandArray['Variable:notifsalon']='1' elseif ((tonumber(otherdevices_temperature['Temperature balcon']) < tonumber(otherdevices_temperature['Temperature Salon'])) and uservariables['notifsalon'] == '1') then commandArray['SendEmail']='Temperature Balcon#La temperature du Balcon '..round(otherdevices_temperature['Temperature balcon'],2)..'°c est plus basse que la temperature du Salon '..round(otherdevices_temperature['Temperature Salon'],2)..'°c.#adresse@mail.com' commandArray['Variable:notifsalon']='0' end end return commandArray
function Test() local originalFiles = { "file1.tga", "file2.tga", "Jamfile.jam", } local originalDirs = { } ospath.remove('cache/') ospath.remove('.depcache') RunJam{ 'clean' } TestDirectories(originalDirs) TestFiles(originalFiles) local pattern = [[ *** found 5 target(s)... *** updating 2 target(s)... @ ConvertImageHelper file1.image !NEXT!Caching file1.image @ ConvertImageHelper file2.image !NEXT!Caching file2.image *** updated 2 target(s)... ]] TestPattern(pattern, RunJam()) local pass1Files = { '.depcache', 'Jamfile.jam', 'file1.image', 'file1.tga', 'file2.image', 'file2.tga', 'cache/c51/c518ad13579d451d4c0b2b69178a5095-ead1e43de665f2a38d9f939274cf079c.link', 'cache/e80/e803da4ab5571e583e755f963d4b37fd-faa1fdb2548701eb77fc77cfa18d8e47.link', 'cache/ead/ead1e43de665f2a38d9f939274cf079c.blob', 'cache/faa/faa1fdb2548701eb77fc77cfa18d8e47.blob', } local newDirectories = { 'cache/', 'cache/c51/', 'cache/e80/', 'cache/ead/', 'cache/faa/', } TestFiles(pass1Files) TestDirectories(newDirectories) RunJam{ 'clean' } local pass2Files = { '.depcache', 'Jamfile.jam', 'file1.tga', 'file2.tga', 'cache/c51/c518ad13579d451d4c0b2b69178a5095-ead1e43de665f2a38d9f939274cf079c.link', 'cache/e80/e803da4ab5571e583e755f963d4b37fd-faa1fdb2548701eb77fc77cfa18d8e47.link', 'cache/ead/ead1e43de665f2a38d9f939274cf079c.blob', 'cache/faa/faa1fdb2548701eb77fc77cfa18d8e47.blob', } TestFiles(pass2Files) TestDirectories(newDirectories) local pattern2 = [[ *** found 5 target(s)... *** updating 2 target(s)... Using cached file1.image Using cached file2.image *** updated 2 target(s)... ]] TestPattern(pattern2, RunJam()) TestFiles(pass1Files) TestDirectories(newDirectories) osprocess.sleep(1.0) ospath.touch('file1.tga') local pattern3 = [[ *** found 5 target(s)... *** updating 1 target(s)... file1.image is already the proper cached target. *** updated 1 target(s)... ]] TestPattern(pattern3, RunJam()) ospath.remove('cache/') ospath.remove('.depcache') RunJam{ 'clean' } TestDirectories(originalDirs) TestFiles(originalFiles) end
local ig = require "imgui.love" local instance love.load = function(args) instance = ig.love_load{use_imgui_docking = true, use_imgui_viewport = false} end love.textinput = function(text) instance.textinput(text) end love.keypressed = function(key,scancode,isrepeat) instance.update_key(scancode, true) end love.keyreleased = function(key,scancode) instance.update_key(scancode, false) end love.wheelmoved = function(x,y) instance.wheelmoved(x,y) end local ffi = require"ffi" local val = ffi.new("float[1]") local padval = ffi.new("float[2]") local curve = ig.Curve("mycurve",12,100) local Quat = ffi.new("quat",{1,0,0,0}) local v3 = ffi.new("G3Dvec3",{1,0,0}) local mat4 = ig.mat4_cast(Quat) love.draw = function() instance:NewFrame() instance.MainDockSpace() if ig.Begin("widgets",nil, ig.lib.ImGuiWindowFlags_AlwaysAutoResize) then if ig.TreeNode"dial" then ig.dial("turns",val,nil,0.5/math.pi) ig.SameLine() ig.dial("radians",val) ig.TreePop(); ig.Separator(); end if ig.TreeNode"pad" then ig.pad("mypad", padval) ig.InputFloat2("vals",padval) ig.TreePop(); ig.Separator(); end if ig.TreeNode"curve" then if curve:draw(ig.ImVec2(400,300)) then --do something with curve.LUT array of 100 floats end ig.InputFloat2("first two",curve.LUT, nil, ig.lib.ImGuiInputTextFlags_ReadOnly) ig.TreePop(); ig.Separator(); end if ig.TreeNode"gizmoquat" then if ig.gizmo3D("###guizmo0",v3,Quat,150) then mat4 = ig.mat4_pos_cast(Quat,v3) end ig.SameLine() ig.BeginGroup() ig.InputFloat4("##1",mat4.f, nil, ig.lib.ImGuiInputTextFlags_ReadOnly) ig.InputFloat4("##2",mat4.f+4, nil, ig.lib.ImGuiInputTextFlags_ReadOnly) ig.InputFloat4("##3",mat4.f+8, nil, ig.lib.ImGuiInputTextFlags_ReadOnly) ig.InputFloat4("##4",mat4.f+12, nil, ig.lib.ImGuiInputTextFlags_ReadOnly) ig.EndGroup() ig.imguiGizmo_setDirectionColor(ig.ImVec4(1,0,0,1)) ig.gizmo3D("guizmo3",v3,150) ig.imguiGizmo_restoreDirectionColor() ig.InputFloat3("dir",ffi.new("float[3]",{v3.x,v3.y,v3.z}), nil, ig.lib.ImGuiInputTextFlags_ReadOnly) ig.TreePop(); ig.Separator(); end end ig.End() ig.ShowDemoWindow() instance:Render() end
local metadata = { plugin = { format = 'jar', -- Valid values are 'jar' manifest = { permissions = {}, usesPermissions = { "android.permission.INTERNET", "android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_NETWORK_STATE", }, usesFeatures = {}, applicationChildElements = { [[<activity android:name="com.facebook.ads.InterstitialAdActivity" android:configChanges="keyboardHidden|orientation|screenSize"/> <activity android:name="com.mobfox.sdk.interstitialads.InterstitialActivity"></activity>]] } }, }, coronaManifest = { dependencies = { ["shared.google.play.services.ads"] = "com.coronalabs" } } } return metadata;
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -- -- This file is compatible with Lua 5.3 local class = require("class") require("kaitaistruct") local stringstream = require("string_stream") local utils = require("utils") TypeTernary = class.class(KaitaiStruct) function TypeTernary:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function TypeTernary:_read() if not(self.is_hack) then self._raw_dif_wo_hack = self._io:read_bytes(1) local _io = KaitaiStream(stringstream(self._raw_dif_wo_hack)) self.dif_wo_hack = TypeTernary.Dummy(_io, self, self._root) end self._raw__raw_dif_with_hack = self._io:read_bytes(1) self._raw_dif_with_hack = KaitaiStream.process_xor_one(self._raw__raw_dif_with_hack, 3) local _io = KaitaiStream(stringstream(self._raw_dif_with_hack)) self.dif_with_hack = TypeTernary.Dummy(_io, self, self._root) end TypeTernary.property.is_hack = {} function TypeTernary.property.is_hack:get() if self._m_is_hack ~= nil then return self._m_is_hack end self._m_is_hack = true return self._m_is_hack end TypeTernary.property.dif = {} function TypeTernary.property.dif:get() if self._m_dif ~= nil then return self._m_dif end self._m_dif = utils.box_unwrap((not(self.is_hack)) and utils.box_wrap(self.dif_wo_hack) or (self.dif_with_hack)) return self._m_dif end TypeTernary.property.dif_value = {} function TypeTernary.property.dif_value:get() if self._m_dif_value ~= nil then return self._m_dif_value end self._m_dif_value = self.dif.value return self._m_dif_value end TypeTernary.Dummy = class.class(KaitaiStruct) function TypeTernary.Dummy:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function TypeTernary.Dummy:_read() self.value = self._io:read_u1() end
local function mounts(path) local tbl = {} for str in io.lines(path) do table.insert(tbl, str) end return tbl end return { decoder = mounts; }
-- Importing modules local Explain = require "elasticsearch.endpoints.Explain" local parser = require "elasticsearch.parser" local MockTransport = require "lib.MockTransport" local getmetatable = getmetatable -- Setting up environment local _ENV = lunit.TEST_CASE "tests.endpoints.ExplainTest" -- Declaring local variables local endpoint local mockTransport = MockTransport:new() -- Testing the constructor function constructorTest() assert_function(Explain.new) local o = Explain:new() assert_not_nil(o) local mt = getmetatable(o) assert_table(mt) assert_equal(mt, mt.__index) end -- The setup function function setup() endpoint = Explain:new{ transport = mockTransport } end -- Testing request function request1Test() mockTransport.method = "GET" mockTransport.uri = "/twitter/tweet/1/_explain" mockTransport.params = {} mockTransport.body = parser.jsonEncode{ query = { term = { message = "search" } } } endpoint:setParams{ index = "twitter", type = "tweet", id = "1", body = { query = { term = { message = "search" } } } } local _, err = endpoint:request() assert_nil(err) end -- Testing request function request2test() mockTransport.method = "GET" mockTransport.uri = "/twitter/tweet/1/_explain" mockTransport.params = { q = "message:search" } mockTransport.body = nil endpoint:setParams{ index = "twitter", type = "tweet", id = "1", q = "message:search" } local _, err = endpoint:request() assert_nil(err) end
OpenNefia.Entities.Elona = { ItemComputer = { MetaData = { Name = "コンピューター" } } }
local Input = {} local Bridge = require "util.bridge" local Memory = require "util.memory" local Utils = require "util.utils" local lastSend local currentButton, remainingFrames, setForFrame local debug local bCancel = true local function bridgeButton(btn) if btn ~= lastSend then lastSend = btn Bridge.input(btn) end end local function sendButton(button, ab) local inputTable = {[button] = true} joypad.set(inputTable) if debug then Utils.drawText(0, 14, button.." "..remainingFrames) end if ab then button = "A,B" end bridgeButton(button) setForFrame = button end function Input.press(button, frames, walk) if setForFrame then Utils.printFilter("error", "ERR: Reassigning "..setForFrame.." to "..button) return end if frames == nil or frames > 0 then if button == currentButton then return end if not frames then frames = 1 end currentButton = button remainingFrames = frames else remainingFrames = 0 end bCancel = button ~= "B" sendButton(button) if walk then local cancel if bCancel then cancel = "B" else cancel = "A" end local inputTable = {[button]=true, [cancel]=true} joypad.set(inputTable) end end function Input.cancel(accept) if accept and Memory.value("menu", "option_dialogue") == 20 then Input.press(accept) return true end local button if bCancel then button = "B" else button = "A" end remainingFrames = 0 sendButton(button, true) bCancel = not bCancel end function Input.escape() local inputTable = {Right=true, Down=true} joypad.set(inputTable) bridgeButton("D,R") end function Input.clear() currentButton = nil remainingFrames = -1 end function Input.update() if currentButton then remainingFrames = remainingFrames - 1 if remainingFrames >= 0 then if remainingFrames > 0 then sendButton(currentButton) return true end else currentButton = nil end end setForFrame = nil end function Input.advance() if not setForFrame then bridgeButton("e") end end function Input.setDebug(enabled) debug = enabled end function Input.test(fn, completes) while true do if not Input.update() then if fn() and completes then break end end emu.frameadvance() end if completes then print(completes.." complete!") end end return Input
list.Set( "XDBot_Personas", "_default_persona", XDBOT_GLOBALS.DefaulPersona ) list.Set( "XDBot_Personas", "laszlo", { Name = "Laszlo", Model = "male05" --, -- Playercolor = "0.24 0.34 0.41", -- Weaponcolor = "0.30 1.80 2.10", -- Bodygroups = "0", -- Skin = "0" } ) list.Set( "XDBot_Personas", "emptytable", { } ) list.Set( "XDBot_Personas", "gman", { Name = "Gman", Model = "gman" } ) list.Set( "XDBot_Personas", "alyx", { Name = "Alyx", Model = "alyx", Playercolor = "0.329412 0.349020 0.360784", Weaponcolor = "1.000000 0.513726 0.000000" } ) list.Set( "XDBot_Personas", "barney", { Name = "Barney", Model = "barney", Playercolor = "0.035294 0.113725 0.188235" } )
Tunnel = module("vrp","lib/Tunnel") Proxy = module("vrp","lib/Proxy") Tools = module("vrp","lib/Tools") vRP = Proxy.getInterface("vRP") vRPclient = Tunnel.getInterface("vRP") vrpServer = {} Tunnel.bindInterface("pd-inventory",vrpServer) idgens = Tools.newIDGenerator() vCLIENT = Tunnel.getInterface("pd-inventory") vGARAGE = Tunnel.getInterface("vrp_garages") vDIAGNOSTIC = Tunnel.getInterface("vrp_diagnostic") ----------------------------------------------------------------------------------------------------------------------------------------- -- WEBHOOK ----------------------------------------------------------------------------------------------------------------------------------------- webhookdrop = "https://discordapp.com/api/webhooks/588051843163095186/PIohjIJEkbhKC3pwpsRkYVIsCXcyIKdXyy1Tx2uo7h2SBQDu6e0hmEqwgle58-_ybxfO" webhooksenditem = "https://discordapp.com/api/webhooks/584808824981159936/EJpDs2OWbG_MWlfzbJgQdf1lH_0e6Mro-D-RR_BAlXFlRbkIU--bZFVE1GnfY7CreYEv" webhookchestcar = "https://discordapp.com/api/webhooks/625240724392116234/XlMCDd87ozvP7r1eW5joBDBjQ-eFUNABwals8FN5Bh1SGPNY_PmoIgEgd_9qzpQ6i4Qo" webhookchesthomes = "https://discordapp.com/api/webhooks/595667589837881346/Eg6b-cri7HI2NkrhJ2v0DiTK-veTcSyMXWlf9eBU-jjymJokJEvajEvn4Tjerzq_hYJy" webhookchestpolice = "https://discordapp.com/api/webhooks/616171780217765888/VBkr8-d-NodLpagHOkcI1PP3_pK86lzXKbJD3tdgasUE17O3bM7nWXyb_yjiTHY7-kZb" webhookchestgang = "https://discordapp.com/api/webhooks/615151216283877377/E7OAhXDZNCU82F87MRiEXLLDvX7vvDwJ-wAASqm-OE-S_5GIiiXIb5p1U3pAvA9sE7up" webhookre = "https://discordapp.com/api/webhooks/666180766434197534/gqrQ0jWUqAXnU8I4VtWMBrL93m5JpmZgLr5jA-TqQT4RBTfbBMPCxmi795_5xUCaLrm1" webhookporte = "https://discordapp.com/api/webhooks/666330662768214028/UACP641JObFnC8GMFP-0XOU1kk0yQhhssUG6YcJgVfP04Vov0p6J_ZgWwOQpKG_wSi-a" function SendWebhookMessage(webhook,message) if webhook ~= nil and webhook ~= "" then PerformHttpRequest(webhook,function(err,text,headers) end,'POST',json.encode({ content = message }),{['Content-Type'] = 'application/json' }) end end ------------------------------------------------------------------------------------------------------------------------------------------------------ -- Shared Functions ------------------------------------------------------------------------------------------------------------------------------------------------------ function vrpServer.giveMax(user_id,var) local max = vRP.query("pd-getMax", { user_id = user_id })[1].max if var then vRP.execute("pd-giveMax", { max = var, user_id = user_id }) end end function vrpServer.getWeight() local source = source local user_id = vRP.getUserId(source) local weight = 0.0 if user_id then local query = vRP.query("pd-getInv", { user_id = user_id }) local data = json.decode(query[1].itemlist) for k, v in pairs(data) do weight = weight + ( itemlist[v.item].weight * v.amount ) end return weight end end function vrpServer.getInv(zone) local source = source local user_id = vRP.getUserId(source) local weight = 0.0 if user_id then local query = vRP.query("pd-getInv", { user_id = user_id }) if not query[1] then -- New User vRP.execute("pd-newInv", { user_id = user_id, itemlist = "{}", max = 6 }) query = { [1] = { itemlist = "{}" } } end local max = vRP.query("pd-getMax", { user_id = user_id })[1].max local data = json.decode(query[1].itemlist) local res = {} for k, v in pairs(data) do v.item = k v.weight = itemlist[v.item].weight * v.amount v.name = itemlist[v.item].name v.icon = itemlist[v.item].icon v.desc = itemlist[v.item].desc table.insert(res, v) weight = weight + ( itemlist[v.item].weight * v.amount ) end local x, y, z = vRPclient.getPosition(source) local drop = getDropList(zone, x, y, z) local resDrop = {} for k,v in pairs(drop) do v.item = k v.weight = itemlist[v.item].weight * v.amount v.name = itemlist[v.item].name v.icon = itemlist[v.item].icon v.desc = itemlist[v.item].desc table.insert(resDrop, v) end return weight,json.encode(res),json.encode(resDrop),max end end function vrpServer.getIdentity() local source = source local user_id = vRP.getUserId(source) if user_id then local identity = vRP.getUserIdentity(user_id) local job = vRP.getUserGroupByType(user_id,"job") local cash = vRP.getMoney(user_id) local bank = vRP.getBankMoney(user_id) local paypal = vRP.getPaypalMoney(user_id) local tax = json.decode(vRP.getUData(user_id,"vRP:multas")) or 0 local job = vRP.getUserGroupByType(user_id,"job") local vipName = vRP.getUserGroupByType(user_id,"vip") local vipTime = vRP.query("getVipTime",{ id = user_id }) local coins = vRP.getCoins(user_id) if identity or (#vipTime and vipTime[1].vip_time ~= 0) then return identity.name,identity.firstname,identity.user_id,identity.age,identity.registration,identity.phone,vRP.format(parseInt(cash)),vRP.format(parseInt(bank)),vRP.format(parseInt(paypal)),vRP.format(parseInt(tax)),job,vipName,getDayHours(parseInt(vipTime[1].vip_time-os.time())),vRP.format(parseInt(coins)) end end end function getDayHours(seconds) if seconds > 0 then local days = math.floor(seconds/86400) seconds = seconds - days * 86400 local hours = math.floor(seconds/3600) if days > 0 then return string.format("%d Dias e %d Horas",days,hours) else return string.format("%d Horas",hours) end else return string.format("Nenhum") end end ------------------------------------------------------------------------------------------------------------------------------------------------------ -- ------------------------------------------------------------------------------------------------------------------------------------------------------ RegisterCommand('item',function(source, args) local user_id = vRP.getUserId(source) if vRP.hasPermission(user_id,"admin.permissao") then if args[1] and args[2] then giveItem(user_id, args[1], parseInt(args[2]), true, "Recebeu", true) TriggerClientEvent("b03461cc:pd-inventory:updateInventory",source) end end end) -------------------------------------------------------------------------------------------------------------------------- -- Exports -------------------------------------------------------------------------------------------------------------------------- function getItemAmount(user_id, item) local amount = 0 local query = json.decode(vRP.query("pd-getInv", { user_id = user_id })[1].itemlist) for k, v in pairs(query) do if k == item then amount = parseInt(v.amount) break end end return amount end function getItemName(item) return itemlist[item].name end function consumeItem(user_id, item, amount, notify, var) amount = parseInt(amount) local source = vRP.getUserSource(user_id) local query = json.decode(vRP.query("pd-getInv", { user_id = user_id })[1].itemlist) for k, v in pairs(query) do if k == item then local newAmount = v.amount - amount if newAmount <= 0 then query[k] = nil else query[k].amount = newAmount end vRP.execute("pd-updateInv", { user_id = user_id, itemlist = json.encode(query) }) if notify then if var then TriggerClientEvent("ItemNotify", source, itemlist[item].name, itemlist[item].icon, ""..var.." x"..amount) else TriggerClientEvent("ItemNotify", source, itemlist[item].name, itemlist[item].icon, "Enviou x"..amount) end end return true end end TriggerClientEvent("Notify", source, "negado", "Não Possui <b>"..itemlist[item].name.." x"..amount.."</b>") return false end function checkWeightAmount(user_id, item, amount) local source = vRP.getUserSource(user_id) local max = vRP.query("pd-getMax", { user_id = user_id })[1].max local query = json.decode(vRP.query("pd-getInv", { user_id = user_id })[1].itemlist) local weight = 0.0 if query[item] then query[item].amount = query[item].amount + amount else query[item] = { amount = amount } end for k, v in pairs(query) do weight = weight + ( itemlist[k].weight * v.amount ) end if weight > max then TriggerClientEvent("Notify", source, "negado", "<b>Inventário cheio</b>") return false else return true end end function checkChestWeightAmount(user_id, item, amount, max_weight, name) local source = vRP.getUserSource(user_id) local query = json.decode(vRP.getSData(name)) or {} local weight = 0.0 if query[item] then query[item].amount = query[item].amount + amount else query[item] = { amount = amount } end for k, v in pairs(query) do weight = weight + ( itemlist[k].weight * v.amount ) end if weight > max_weight then TriggerClientEvent("Notify", source, "negado", "<b>Baú Cheio</b>") return false else return true end end function giveItem(user_id, item, amount, notify, var, police) amount = parseInt(amount) local source = vRP.getUserSource(user_id) if itemlist[item] then local weight = 0.0 local max = vRP.query("pd-getMax", { user_id = user_id })[1].max local query = json.decode(vRP.query("pd-getInv", { user_id = user_id })[1].itemlist) if query[item] then query[item].amount = query[item].amount + amount else query[item] = { amount = amount } end if not police then for k, v in pairs(query) do weight = weight + ( itemlist[k].weight * v.amount ) if weight > max then TriggerClientEvent("Notify", source, "aviso", "<b>Inventário cheio</b>") return end end end vRP.execute("pd-updateInv", { user_id = user_id, itemlist = json.encode(query) }) if notify then if var then TriggerClientEvent("ItemNotify", source, itemlist[item].name, itemlist[item].icon, ""..var.." x"..amount) else TriggerClientEvent("ItemNotify", source, itemlist[item].name, itemlist[item].icon, "Recebeu x"..amount) end end end end function tableTostring(tbl) local result, done = {}, {} local function val_to_str ( v ) if "string" == type( v ) then v = string.gsub( v, "\n", "\\n" ) if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then return "'" .. v .. "'" end return '"' .. string.gsub(v,'"', '\\"' ) .. '"' else return "table" == type( v ) and tableTostring( v ) or tostring( v ) end end local function key_to_str ( k ) if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then return k else return "[" .. val_to_str( k ) .. "]" end end for k, v in ipairs( tbl ) do table.insert( result, val_to_str( v ) ) done[ k ] = true end for k, v in pairs( tbl ) do if not done[ k ] then table.insert( result, key_to_str( k ) .. "=" .. val_to_str( v ) ) end end return "{" .. table.concat( result, "," ) .. "}" end --[[vRP.prepare("transinventory1", "SELECT dvalue FROM vrp_user_data WHERE dkey = \"vRP:datatable\" AND user_id = @user_id") vRP.prepare("transinventory2","INSERT INTO vrp_user_inventory(user_id,itemlist,max) VALUES(@user_id,@itemlist,@max)") vRP.prepare("transinventory3", "UPDATE vrp_user_inventory SET itemlist = @itemlist WHERE user_id = @user_id") vRP.prepare("transinventory4", "SELECT * FROM vrp_user_inventory WHERE user_id = @user_id") function caralho() for i=1,957 do vRP.execute("transinventory2",{ user_id = i, itemlist = "[]", max = 90 }) local rows = vRP.query("transinventory1", { user_id = i }) if rows[1] then local invNew = {} rows = json.decode(rows[1].dvalue) for k,v in pairs(rows.inventory) do invNew[k] = v if string.find(k,"wbody|WEAPON_") then invNew[k] = nil local name = string.lower(k) name = string.gsub(name, "wbody|weapon_","") print(name,v.amount) invNew[name] = v elseif string.find(k, "wammo") then invNew[k] = nil local name = string.lower(k) name = string.gsub(name, "wammo|weapon_","ammo_") print(name) invNew[name] = v elseif string.find(k,"wbody|GADGET_") then invNew[k] = nil local name = string.lower(k) name = string.gsub(name, "wbody|gadget_","") print(name,v.amount) invNew[name] = v end end vRP.execute("transinventory3", { user_id = i, itemlist = json.encode(invNew) }) end end print("END") end Citizen.CreateThread(function() caralho() end)]] exports("getItemAmount", getItemAmount) exports("getItemName", getItemName) exports("checkWeightAmount", checkWeightAmount) exports("tblTostring", tableTostring) exports("consumeItem", consumeItem) exports("giveItem", giveItem) --exports["pd-inventory"]:getItemName(
-- -- Created by IntelliJ IDEA. -- User: Kunkka Huang -- Date: 17/1/18 -- Time: 下午6:08 -- To change this template use File | Settings | File Templates. -- local panel = {} function panel.create(parent) local winSize = cc.Director:getInstance():getWinSize() local self = cc.LayerColor:create(gk.theme.config.backgroundColor, winSize.width - gk.display.leftWidth - gk.display.rightWidth, gk.display.bottomHeight) setmetatableindex(self, panel) self.parent = parent self:setPosition(gk.display.leftWidth, 0) local scale = 0.25 local fontSize = 40 local scale = 0.25 local topY = gk.display.bottomHeight - 35 local leftX = 12 local inputWidth1 = 140 local inputWidth2 = 400 local stepY = 25 local leftX2 = 100 + leftX local leftX3 = leftX2 + inputWidth1 + 20 local leftX4 = leftX3 + 100 -- size label local fontName = gk.theme.font_fnt local content = string.format("designSize(%.0fx%.0f) ScreenSize(%.0fx%.0f) accuWinSize(%.0fx%.0f) xScale(%.2f) yScale(%.2f) minScale(%.2f)", gk.display.width(), gk.display.height(), gk.display:winSize().width, gk.display:winSize().height, gk.display:accuWinSize().width, gk.display:accuWinSize().height, gk.display:xScale(), gk.display:yScale(), gk.display:minScale()) local label = gk.create_label(content, fontName, fontSize) label:setScale(scale) local height = 20 label:setDimensions(self:getContentSize().width / 0.2, height / 0.2) label:setOverflow(2) gk.set_label_color(label, gk.theme.config.fontColorNormal) self:addChild(label) label:setAnchorPoint(0, 0.5) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setPosition(leftX, gk.display.bottomHeight - height / 2) local createLabel = function(content, x, y) local label = gk.create_label(content, fontName, fontSize) label:setScale(scale) gk.set_label_color(label, gk.theme.config.fontColorNormal) self:addChild(label) label:setAnchorPoint(0, 0.5) label:setPosition(x, y) return label end local createInput = function(content, x, y, width, callback, defValue, lines) lines = lines or 1 local node = gk.EditBox:create(cc.size(width / scale, 16 / scale * lines)) node:setScale9SpriteBg(gk.create_scale9_sprite("gk/res/texture/edit_box_bg.png", cc.rect(20, 20, 20, 20))) local label = gk.create_label(content, gk.theme.font_ttf, fontSize) gk.set_label_color(label, cc.c3b(0, 0, 0)) node:setInputLabel(label) local contentSize = node:getContentSize() label:setPosition(cc.p(contentSize.width / 2, contentSize.height / 2 - 5)) label:setDimensions(contentSize.width - 15, contentSize.height) self:addChild(node) node:setScale(scale) node:onEditEnded(function(...) callback(...) end) node:setAnchorPoint(0, 1) node:setPosition(x, y + 16 / 2) node.enabled = not self.disabled return node end local createSelectBox = function(items, index, x, y, width, callback) local node = gk.SelectBox:create(cc.size(width / scale, 16 / scale), items, index) node:setScale9SpriteBg(gk.create_scale9_sprite("gk/res/texture/edit_box_bg.png", cc.rect(20, 20, 20, 20))) local label = gk.create_label("", fontName, fontSize) gk.set_label_color(label, cc.c3b(0, 0, 0)) node:setMarginLeft(5) node:setMarginRight(22) node:setMarginTop(4) node:setDisplayLabel(label) node:onCreatePopupLabel(function() local label = gk.create_label("", fontName, fontSize) gk.set_label_color(label, cc.c3b(0, 0, 0)) return label end) self:addChild(node) node:setScale(scale) node:setAnchorPoint(0, 0.5) node:setPosition(x, y) node:onSelectChanged(callback) return node end local yIndex = 0 createLabel("Android SDK Path", leftX, topY - stepY * yIndex) local sdk = cc.UserDefault:getInstance():getStringForKey("gk_android_sdk_location") local onValueChanged = function(editBox, input) if input == "" then return false end local adb = input .. "/platform-tools/adb" local handle = io.popen(adb .. " version") local ret = handle:read("*a") handle:close() -- local correct = os.execute(adb .. " version") == 0 local correct = ret and #ret > 0 if editBox then gk.set_label_color(editBox.label, correct and cc.c3b(45, 35, 255) or cc.c3b(0, 0, 0)) end return correct end local editBox = createInput(sdk, leftX2, topY - stepY * yIndex, inputWidth2, function(editBox, input) local correct = onValueChanged(editBox, input) if correct then cc.UserDefault:getInstance():setStringForKey("gk_android_sdk_location", input) cc.UserDefault:getInstance():flush() end end) editBox:onInputChanged(function(_, input) onValueChanged(editBox, input) end) onValueChanged(editBox, sdk) yIndex = yIndex + 1 createLabel("Default Activity", leftX, topY - stepY * yIndex) local var = cc.UserDefault:getInstance():getStringForKey("gk_android_default_activity", "org.cocos2dx.lua.AppActivity") createInput(var, leftX2, topY - stepY * yIndex, inputWidth1, function(editBox, input) cc.UserDefault:getInstance():setStringForKey("gk_android_default_activity", input) cc.UserDefault:getInstance():flush() end) -- devices createLabel("Android Devices", leftX3, topY - yIndex * stepY) local items = { "-" } local selectBox = createSelectBox(items, 1, leftX4, topY - yIndex * stepY, inputWidth1, function(index) end) selectBox:setCascadeOpacityEnabled(true) selectBox.enabled = #items == 1 selectBox:setOpacity(#items == 1 and 150 or 255) -- check devieces local checkDevices = function() local sdk = cc.UserDefault:getInstance():getStringForKey("gk_android_sdk_location") if onValueChanged(nil, sdk) then local devices = {} local adb = sdk .. "/platform-tools/adb" local handle = io.popen(adb .. " devices -l") local result = handle:read("*a") handle:close() if result and result:find("model:") then local id = result:sub(result:find("attached") + 9, result:find("attached") + 9 + 7) local name = result:sub(result:find("model:") + 6, result:find("device:") - 2) table.insert(devices, { id = id, name = name }) -- dump(devices) return devices end end return {} end self.hasDevices = false local scanDevices = function() if not selectBox.popup then local devices = checkDevices() local items = { "-" } for _, v in pairs(devices) do table.insert(items, v.name) end selectBox:setItems(items) if (selectBox.selectIndex == 0 or selectBox.selectIndex == 1) and #items > 1 then selectBox:setSelectIndex(2) else selectBox:setSelectIndex(1) end selectBox.enabled = #items == 1 selectBox:setOpacity(#items == 1 and 150 or 255) local hasDevices = #items > 1 if self.hasDevices and not hasDevices then print("no phone connected") elseif not self.hasDevices and hasDevices then print("new phone connected -> " .. items[2]) end self.hasDevices = hasDevices end end scanDevices() selectBox:runAction(cc.RepeatForever:create(cc.Sequence:create(cc.DelayTime:create(0.5), cc.CallFunc:create(function() scanDevices() end)))) yIndex = yIndex + 1 self.logOn = false createLabel("LogCat", leftX4 + inputWidth1 - 60, topY - stepY * yIndex) local icon = gk.create_sprite("gk/res/texture/icon_android.png") local button = gk.ZoomButton.new(icon) self:addChild(button) button:setScale(scale * 0.8) button:setPosition(leftX4 + inputWidth1, topY - yIndex * stepY) button:setAnchorPoint(1, 0.5) button:onClicked(function() self.logOn = not self.logOn local program = cc.GLProgramState:getOrCreateWithGLProgramName(self.logOn and "ShaderPositionTextureColor_noMVP" or "ShaderUIGrayScale") if program then icon:setGLProgramState(program) end if self.logOn then print("turn logcat on, tag = cocos2d") gk.util:stopActionByTagSafe(self, -991) local sdk = cc.UserDefault:getInstance():getStringForKey("gk_android_sdk_location") if not onValueChanged(nil, sdk) then gk.log("must set valid sdk location") return end local action = self:runAction(cc.RepeatForever:create(cc.Sequence:create(cc.DelayTime:create(0.5), cc.CallFunc:create(function() local devices = checkDevices() if #devices == 0 then return end local adb = sdk .. "/platform-tools/adb" local handle = io.popen(adb .. " logcat -d | grep cocos2d") local result = handle:read("*a"):trim() if result ~= "" then print(result) end handle:close() local handle = io.popen(adb .. " logcat -c") handle:close() end)))) action:setTag(-991) else print("turn logcat off") gk.util:stopActionByTagSafe(self, -991) end end) local program = cc.GLProgramState:getOrCreateWithGLProgramName(self.logOn and "ShaderPositionTextureColor_noMVP" or "ShaderUIGrayScale") if program then icon:setGLProgramState(program) end createLabel("Clean", leftX, topY - stepY * yIndex) local label = gk.create_label("↻", fontName, fontSize + 20) gk.set_label_color(label, cc.c3b(50, 255, 50)) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setDimensions(60 / scale, 20 / scale) local node = cc.Node:create() node:setContentSize(60 / scale, 16 / scale) node:addChild(label) label:enableBold() label:setPosition(node:getContentSize().width / 2, node:getContentSize().height / 2 - 4) local button = gk.ZoomButton.new(node) button:setScale(scale * 0.8, scale) button:setPosition(leftX2, topY - yIndex * stepY) self:addChild(button) gk.util:drawNodeBg(node, cc.c4f(0.5, 0.5, 0.5, 1), -2) button:setAnchorPoint(0, 0.5) button:onClicked(function() gk.set_label_color(label, cc.c3b(166, 166, 166)) self:runAction(cc.Sequence:create(cc.DelayTime:create(0.02), cc.CallFunc:create(function() gk.set_label_color(label, cc.c3b(50, 255, 50)) local instanceRun = require("gk.instanceRun") local MAC_ROOT = instanceRun.MAC_ROOT local ANDROID_ROOT = instanceRun.ANDROID_ROOT local ANDROID_PACKAGE_NAME = instanceRun.ANDROID_PACKAGE_NAME local defaultActivity = cc.UserDefault:getInstance():getStringForKey("gk_android_default_activity", "org.cocos2dx.lua.AppActivity") if ANDROID_PACKAGE_NAME == "" then gk.log("must set packageName") return end if not ANDROID_ROOT or ANDROID_ROOT == "/" then gk.log("must set ANDROID_ROOT") return end local sdk = cc.UserDefault:getInstance():getStringForKey("gk_android_sdk_location") if not onValueChanged(nil, sdk) then gk.log("must set valid sdk location") return end gk.log("----------------------------------") gk.log("Cleaning ......") -- local dir = MAC_ROOT .. "gen" -- gk.log("remove dir %s", dir) -- cc.FileUtils:getInstance():removeDirectory(dir) local adb = sdk .. "/platform-tools/adb" gk.log("remove dir %s", ANDROID_ROOT) local handle = io.popen(adb .. " shell rm -rf " .. ANDROID_ROOT) local result = handle:read("*a") handle:close() gk.log("Clean finished!") end))) end) createLabel("Deploy", leftX3, topY - stepY * yIndex) local label = gk.create_label("▶", fontName, fontSize + 10) gk.set_label_color(label, cc.c3b(50, 255, 50)) label:setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setVerticalAlignment(cc.TEXT_ALIGNMENT_CENTER) label:setDimensions(60 / scale, 20 / scale) local node = cc.Node:create() node:setContentSize(60 / scale, 16 / scale) node:addChild(label) label:setPosition(node:getContentSize().width / 2, node:getContentSize().height / 2 - 4) local button = gk.ZoomButton.new(node) button:setScale(scale * 0.8, scale) button:setPosition(leftX4, topY - yIndex * stepY) self:addChild(button) gk.util:drawNodeBg(node, cc.c4f(0.5, 0.5, 0.5, 1), -2) button:setAnchorPoint(0, 0.5) button:onClicked(function() local instanceRun = require("gk.instanceRun") local ANDROID_PACKAGE_NAME = instanceRun.ANDROID_PACKAGE_NAME if ANDROID_PACKAGE_NAME == "" then gk.log("must set packageName") return end local defaultActivity = cc.UserDefault:getInstance():getStringForKey("gk_android_default_activity", "org.cocos2dx.lua.AppActivity") if defaultActivity == "" then gk.log("must set defaultActivity") return end local sdk = cc.UserDefault:getInstance():getStringForKey("gk_android_sdk_location") if not onValueChanged(nil, sdk) then gk.log("must set valid sdk location") return end gk.log("----------------------------------") gk.log("Deploying to Android device ......") gk:increaseRuntimeVersion() local scene = gk.SceneManager:getRunningScene() if scene and scene.layer then local label = scene:getChildByTag(gk.util.tags.versionTag) if label then label:setString(gk:getRuntimeVersion()) end end gk.set_label_color(label, cc.c3b(166, 166, 166)) self:runAction(cc.Sequence:create(cc.DelayTime:create(0.02), cc.CallFunc:create(function() gk.set_label_color(label, cc.c3b(50, 255, 50)) local dir = gk.editorConfig.ANDROID_ROOT or "/" local adb = sdk .. "/platform-tools/adb" local handle = io.popen(gk.editorConfig.MAC_ROOT .. "src/gk/script/push.py " .. gk.editorConfig.MAC_ROOT .. " " .. adb .. " " .. packageName .. " " .. defaultActivity .. " " .. dir) local result = handle:read("*a") print(result) handle:close() gk.log("Finished!") gk.log("----------------------------------") end))) end) yIndex = yIndex + 1 self:handleEvent() return self end function panel:handleEvent() -- swallow touches local listener = cc.EventListenerTouchOneByOne:create() listener:setSwallowTouches(true) listener:registerScriptHandler(function(touch, event) if gk.util:hitTest(self, touch) then return true end end, cc.Handler.EVENT_TOUCH_BEGAN) cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, self) end return panel
local HeroChangedVelocity = class("HeroChangedVelocity") function HeroChangedVelocity:initialize(vx, vy) self.vx = vx self.vy = vy end return HeroChangedVelocity
local Piece = require 'tetris.components.piece' local Ruleset = require 'tetris.rulesets.ti_srs' local SRS = Ruleset:extend() SRS.name = "ACE-SRS" SRS.hash = "ACE Standard" SRS.MANIPULATIONS_MAX = 128 function SRS:onPieceRotate(piece, grid) piece.lock_delay = 0 -- rotate reset if piece:isDropBlocked(grid) then piece.manipulations = piece.manipulations + 1 if piece.manipulations >= self.MANIPULATIONS_MAX then piece.locked = true end end end return SRS
local exports = {} exports.parseType = function(s) -- s: String -- parse s type --[[ { list: boolean dict: boolean primitive: boolean # one and only one of these three conditionals must be true values?: table # if dict keys?: table # if list || dict } ]]-- end
local M = {} package.loaded["utils.hooks"] = nil ---Join path segments that were passed as input ---@return string function _G.join_paths(...) local uv = vim.loop local path_sep = "/" local result = table.concat({ ... }, path_sep) return result end ---Get the full path to runtime dir ---@return string function _G.get_runtime_dir() -- when nvim is used directly return vim.fn.stdpath "data" end ---Get the full path to config dir ---@return string function _G.get_config_dir() return vim.fn.stdpath "config" end ---Get the full path to cache dir ---@return string function _G.get_cache_dir() return vim.fn.stdpath "cache" end ---Get the full path to the currently installed repo ---@return string local function get_install_path() return vim.fn.stdpath "config" end ---Initialize the `&runtimepath` variables and prepare for startup ---@return table function M:init() self.runtime_dir = get_runtime_dir() self.config_dir = get_config_dir() self.cache_path = get_cache_dir() self.install_path = get_install_path() self.pack_dir = join_paths(self.runtime_dir, "site", "pack") self.packer_install_dir = join_paths(self.runtime_dir, "site", "pack", "packer", "start", "packer.nvim") self.packer_cache_path = join_paths(self.config_dir, "plugin", "packer_compiled.lua") vim.fn.mkdir(vim.fn.stdpath "cache", "p") local config = require "config" config:init { path = join_paths(self.config_dir, "config.lua"), } require("plugin-loader"):init { package_root = self.pack_dir, install_path = self.packer_install_dir, } return self end return M
print("starting up...") print("tmr.now()",tmr.now()) print("tmr.time()",tmr.time()) print("tmr.uptime()",tmr.uptime()) local tm = rtctime.epoch2cal(rtctime.get()) local tz = 'UTC' print("rtctime",string.format("%04d/%02d/%02d %02d:%02d:%02d %s",tm["year"],tm["mon"],tm["day"],tm["hour"],tm["min"],tm["sec"],tz)) print("node.chipid()",node.chipid(),string.format("0x%x",node.chipid())) print("node.flashid()",node.flashid()) print("node.heap()",node.heap(),string.format("%dKiB",node.heap()/1014)) local o = "" for f,s in pairs(file.list()) do o = o .. f .. "("..s..") " end print("file.list()",o) print("file.stat() with json",sjson.encode(file.stat("README.md"))) local remain, used, total = file.fsinfo() print("file.fsinfo()",string.format("remain %.3fMiB, used %.3fMiB, total %.3fMiB",remain/1024,used/1024,total/1024)) if true then -- brief tmr.* testing local n = 1 tmr.create():alarm(1*1000,tmr.ALARM_AUTO,function(t) print("tmr-test: ping",tmr.uptime(),n) if n==5 then tmr.suspend_all() tmr.create():alarm(3*1000,tmr.ALARM_SINGLE,function(t) print("tmr-test: once",tmr.uptime()) end) end n = n + 1 end) tmr.create():alarm(1.5*1000,tmr.ALARM_AUTO,function(t) print("tmr-test: pong",tmr.uptime()) t:unregister() end) end if not _sysinfo.architecture:match("^arm") then local ffi = require("ffi") -- testing ffi (disabled for ARM-based CPU, as luaffifb seems broken there) if ffi then ffi.cdef[[ int printf(const char *fmt, ...); ]] ffi.C.printf("ffi-test: Hello %s!\n", "world") end end if net and net.createConnection then local host = "httpbin.org" print("net-test: connecting to",host) local srv = net.createConnection(net.TCP, 0) srv:on("receive",function(sck,c) print("net-test: http-received:") c:gsub("([^\n]+)\n",function(s) print("|",s) end) end) srv:on("connection", function(sck, c) -- 'Connection: close' rather than 'Connection: keep-alive' to have server -- initiate a close of the connection after final response (frees memory -- earlier here), https://tools.ietf.org/html/rfc7230#section-6.6 sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n") end) srv:connect(80,host) end if net and net.createServer then local port = 10080 print("net-test: basic http server started on port",port) local sv = net.createServer(net.TCP, 30) if sv then sv:listen(port,function(conn) conn:on("receive",function(sck,data) print("net-test: web server received") data:gsub("([^\n]+)\n",function(s) print("|",s) end) end) conn:on("sent",function(sck) print("net-test: web-server 'sent'-event received, now closing",sck,conn) sck:close() end) conn:send("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello world! "..tmr.uptime()) end) end end if file.exists("cpu/main.lua") then -- NodeMCU Shell arround, if so run `cpu` command dofile("cpu/main.lua")("cpu") end
--[[ Окна ]] -- ORGMOD.windows = {}; ORGMOD.windows.OrganizationAdmin = include( "orgmod/cl/menu/clan_admin.lua" ); ORGMOD.windows.OrganizationControl = include( "orgmod/cl/menu/organization_control/main_menu.lua" ); --[[ Консольные команды ]] -- -- Открыть меню управления кланом concommand.Add( "open_clan_menu", function( ply, cmd, args ) if ( string.lower( args[1] ) == "clan_admin_menu" and ( LocalPlayer():IsAdmin() or LocalPlayer():IsSuperAdmin() ) ) then ORGMOD.windows.OrganizationAdmin.MainMenu(); end; if ( string.lower( args[1] ) == "my_organizations" ) then ORGMOD.windows.OrganizationControl.MainMenu(); end; end, function( cmd, stringargs ) stringargs = string.Trim( stringargs ); stringargs = string.lower( stringargs ); local windows = { ["clan_admin_menu"] = true, ["my_organizations"] = false, }; local data_result = {}; if ( string.len( stringargs ) == 0 ) then for window, adminOnly in pairs( windows ) do if ( adminOnly ) then if ( LocalPlayer():IsAdmin() or LocalPlayer():IsSuperAdmin() ) then table.insert( data_result, "open_clan_menu " .. window ); end; else table.insert( data_result, "open_clan_menu " .. window ); end; end; else for window, adminOnly in pairs( windows ) do if ( string.find( "open_clan_menu " .. window, stringargs .. "*" ) ) then if ( adminOnly ) then if ( LocalPlayer():IsAdmin() or LocalPlayer():IsSuperAdmin() ) then table.insert( data_result, "open_clan_menu " .. window ); end; else table.insert( data_result, "open_clan_menu " .. window ); end; end; end; end; return data_result; end, "Help text.", FCVAR_USERINFO );
require 'model_utils.MaskTime' require 'model_utils.MaskFuture' require 'model_utils.ReplaceZero' local encoderNet = {} function encoderNet.model(params) local dropout = params.dropout or 0.5 -- Use `nngraph` nn.FastLSTM.usenngraph = true; -- encoder network local enc = nn.Sequential(); -- create the two branches local concat = nn.ConcatTable(); -- word branch, along with embedding layer enc.wordEmbed = nn.LookupTableMaskZero(params.vocabSize, params.embedSize); local wordBranch = nn.Sequential():add(nn.SelectTable(1)):add(enc.wordEmbed); -- make clones for embed layer local qEmbedNet = enc.wordEmbed:clone('weight', 'bias', 'gradWeight', 'gradBias'); local hEmbedNet = enc.wordEmbed:clone('weight', 'bias', 'gradWeight', 'gradBias'); -- create two branches local histBranch = nn.Sequential() :add(nn.SelectTable(3)) :add(hEmbedNet); enc.histLayers = {}; -- number of layers to read the history for layer = 1, params.numLayers do local inputSize = (layer == 1) and params.embedSize or params.rnnHiddenSize; enc.histLayers[layer] = nn.SeqLSTM(inputSize, params.rnnHiddenSize); enc.histLayers[layer]:maskZero(); histBranch:add(enc.histLayers[layer]); end histBranch:add(nn.Select(1, -1)); -- image branch -- embedding for images local imgPar = nn.ParallelTable() :add(nn.Identity()) :add(nn.Sequential() :add(nn.Dropout(0.5)) :add(nn.Linear(params.imgFeatureSize, params.imgEmbedSize))); -- select words and image only local imageBranch = nn.Sequential() :add(nn.NarrowTable(1, 2)) :add(imgPar) :add(nn.MaskTime(params.imgEmbedSize)); -- add concatTable and join concat:add(wordBranch) concat:add(imageBranch) concat:add(histBranch) enc:add(concat); -- another concat table local concat2 = nn.ConcatTable(); -- select words + image, and history local wordImageBranch = nn.Sequential() :add(nn.NarrowTable(1, 2)) :add(nn.JoinTable(-1)) -- language model enc.rnnLayers = {}; for layer = 1, params.numLayers do local inputSize = (layer==1) and (params.imgEmbedSize+params.embedSize) or params.rnnHiddenSize; enc.rnnLayers[layer] = nn.SeqLSTM(inputSize, params.rnnHiddenSize); enc.rnnLayers[layer]:maskZero(); wordImageBranch:add(enc.rnnLayers[layer]); end wordImageBranch:add(nn.Select(1, -1)); -- add both the branches (wordImage, select history) to concat2 concat2:add(wordImageBranch):add(nn.SelectTable(3)); enc:add(concat2); -- single layer neural network -- create attention based history local prepare = nn.Sequential() :add(nn.Linear(params.rnnHiddenSize, 1)) :add(nn.View(-1, params.maxQuesCount)) local wordHistBranch = nn.Sequential() :add(nn.ParallelTable() :add(prepare:clone()) :add(prepare:clone())) :add(nn.ParallelTable() :add(nn.Replicate(10, 3)) :add(nn.Replicate(10, 2))) :add(nn.CAddTable()) --:add(nn.Tanh()) :add(nn.MaskFuture(params.maxQuesCount)) :add(nn.View(-1, params.maxQuesCount)) :add(nn.ReplaceZero(-1*math.huge)) :add(nn.SoftMax()) :add(nn.View(-1, params.maxQuesCount, params.maxQuesCount)) :add(nn.Replicate(params.rnnHiddenSize, 4)); local histOnlyBranch = nn.Sequential() :add(nn.SelectTable(2)) :add(nn.View(-1, params.maxQuesCount, params.rnnHiddenSize)) :add(nn.Replicate(params.maxQuesCount, 2)) -- add another concatTable to create attention over history local concat3 = nn.ConcatTable() :add(wordHistBranch) :add(histOnlyBranch) :add(nn.SelectTable(1)) -- append attended history with question enc:add(concat3); -- parallel table to multiply first two tables, and leave the third one untouched local multiplier = nn.Sequential() :add(nn.NarrowTable(1, 2)) :add(nn.CMulTable()) :add(nn.Sum(3)) :add(nn.View(-1, params.rnnHiddenSize)); local concat4 = nn.ConcatTable() :add(multiplier) :add(nn.SelectTable(3)); enc:add(concat4); -- join both the tensors (att over history and encoded question) enc:add(nn.JoinTable(-1)); enc:add(nn.View(-1, params.maxQuesCount, 2*params.rnnHiddenSize)) enc:add(nn.Transpose({1, 2})) enc:add(nn.SeqLSTM(2 * params.rnnHiddenSize, params.rnnHiddenSize)) enc:add(nn.Transpose({1, 2})) enc:add(nn.View(-1, params.rnnHiddenSize)) return enc; end return encoderNet
function Item.getType(self) return ItemType(self:getId()) end function Item.isContainer(self) return false end function Item.isCreature(self) return false end function Item.isMonster(self) return false end function Item.isNpc(self) return false end function Item.isPlayer(self) return false end function Item.isTeleport(self) return false end function Item.isTile(self) return false end
local Aye = Aye; if not Aye.load then return end; Aye.default.global.AutoReadyCheck = { enable = true, -- Enable Auto Ready Check AFKdisable = true, -- Disable Auto Ready Check if AFK DNDdisable = false, -- Disable Auto Ready Check if DND DeadDisable = true, -- Disable Auto Ready Check if Dead or Ghost CombatDisable = true, -- Disable Auto Ready Check if in Combat NotFullHealthDisable = true, -- Disable Auto Ready Check if Not at Full Health NotFullPowerDisable = true, -- Disable Auto Ready Check if Not at Full Power NoBiSFlaskDisable = true, -- Disable Auto Ready Check if player have No BiS Flask NoRuneDisable = false, -- Disable Auto Ready Check if player have No Rune NotWellFedDisable = true, -- Disable Auto Ready Check if no BiS Well Fed buff WellFedTier = 3, -- Minimum required Well Fed Tier (5 is BiS only) BuffTimeEnable = true, -- Enable Minimum Buff Time setting BuffTime = 10, -- Disable Auto Ready Check if players buff is close to expire (with remaining time left ≤ given minutes) GuildGroupDisable = true, -- Disable Auto Ready Check in Guild group LFGDisable = false, -- Disable Auto Ready Check in LFG group PvPDisable = false, -- Disable Auto Ready Check on PvP (arena, battleground) OutsideInstanceDisable = false, -- Disable Auto Ready Check outside Instance GuildGroupForceEnable = false, -- Force Enable Auto Ready Check in Guild group LFGForceEnable = true, -- Force Enable Auto Ready Check in LFG group PvPForceEnable = true, -- Force Enable Auto Ready Check on PvP (arena, battleground) OutsideInstanceForceEnable = false, -- Force Enable Auto Ready Check outside Instance ForceEnableIfBenched = true, -- Force Enable if Benched };
mt = {} function mt:a(arg) print('A from metatable') print(self) print(arg) end mt.__index = mt; mt.__gc = function() print('Death') end do local obj = {} setmetatable(obj, mt) obj:a(123) end collectgarbage('collect') print('Program end')
-- Description: GUI styles Textbox local default_gui = data.raw["gui-style"].default ------------------------------------------------------------------------------- -- Style slider -- -- @type Slider -- ------------------------------------------------------------------------------- -- Style of default -- -- @field [parent=#Slider] default default_gui[Constants.Names.Styles.Sliders.SELogisticsSlider] = { type = "slider_style", parent = "slider", width = 167, height = 19, top_padding = 5 }
----------------------------------------------------------------------------------------- -- -- main.lua -- ----------------------------------------------------------------------------------------- -- Your code here physics = require("physics") physics.start() local ground = display.newRect(display.contentCenterX, 470, display.contentWidth, 20) physics.addBody(ground, "static") local ball = display.newCircle( display.contentCenterX, 0, 20 ) physics.addBody( ball, "dynamic", {density=1, bounce=0.4, radius=20} )
local util = require 'lspconfig.util' local language_id_mapping = { bib = 'bibtex', plaintex = 'tex', rnoweb = 'sweave', rst = 'restructuredtext', tex = 'latex', xhtml = 'xhtml', } return { default_config = { cmd = { 'ltex-ls' }, filetypes = { 'bib', 'markdown', 'org', 'plaintex', 'rst', 'rnoweb', 'tex' }, root_dir = util.find_git_ancestor, single_file_support = true, get_language_id = function(_, filetype) local language_id = language_id_mapping[filetype] if language_id then return language_id else return filetype end end, }, docs = { package_json = 'https://raw.githubusercontent.com/valentjn/vscode-ltex/develop/package.json', description = [=[ https://github.com/valentjn/ltex-ls LTeX Language Server: LSP language server for LanguageTool 🔍✔️ with support for LaTeX 🎓, Markdown 📝, and others To install, download the latest [release](https://github.com/valentjn/ltex-ls/releases) and ensure `ltex-ls` is on your path. To support org files or R sweave, users can define a custom filetype autocommand (or use a plugin which defines these filetypes): ```lua vim.cmd [[ autocmd BufRead,BufNewFile *.org set filetype=org ]] ``` ]=], }, }
local rules = require "scripts.rules" local animations = require "character.animations" local Character = require "character.character" local ServantGirl = Character:new() function ServantGirl:new(o, control) o = o or Character:new(o, control) setmetatable(o, self) self.__index = self return o end function ServantGirl:create() Character.create(self) self:set_skin("french_maid") self.data.enemy = false local stats = self.data.stats stats.name = "Servant Girl" stats.hit_die = "d6", rules.set_ability_scores_map(stats, { str = 10, dex = 13, con = 10, int = 10, wis = 13, cha = 10, }) end return ServantGirl
-- Inofficial NEO Extension for MoneyMoney -- Fetches NEO quantity for address via neoscan.io -- Fetches NEO price in EUR via CoinGecko -- Returns cryptoassets as securities -- -- Provide multiple NEO addresses comma-seperated -- MIT License -- Copyright (c) 2020 Jacubeit, aaronk6 -- 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. WebBanking{ version = 1.00, description = "Fetches balances from neoscan.io and returns them as securities", services= { "NEO" } } local neoAddress local connection = Connection() local currency = "EUR" local currencyField = "eur" local marketName = "CoinGecko" local priceUrl = "https://api.coingecko.com/api/v3/simple/price?ids=neo&vs_currencies=eur" local balanceUrl = "https://api.neoscan.io/api/main_net/v1/get_balance/" local addresses local balances function SupportsBank (protocol, bankCode) return protocol == ProtocolWebBanking and bankCode == "NEO" end function InitializeSession (protocol, bankCode, username, username2, password, username3) addresses = strsplit(",%s*", username) end function ListAccounts (knownAccounts) local account = { name = "NEO", accountNumber = "Crypto Asset NEO", currency = currency, portfolio = true, type = "AccountTypePortfolio" } return {account} end function RefreshAccount (account, since) local s = {} price = queryPrices() balances = queryBalances(addresses) for i,v in ipairs(addresses) do s[i] = { name = v, currency = nil, market = marketName, quantity = balances[i], price = price, } end return {securities = s} end function EndSession () end function queryPrices() local connection = Connection() local res = JSON(connection:request("GET", priceUrl)) return res:dictionary()["neo"][currencyField] end function queryBalances(addresses) local connection = Connection() local balances = {} local res local postContent for key, address in pairs(addresses) do res = JSON(connection:request("GET", balanceUrl .. "/" .. address)) for i, asset in ipairs(res:dictionary()["balance"]) do if asset["asset_symbol"] == "NEO" then table.insert(balances, asset["amount"]) break end end end return balances end -- from http://lua-users.org/wiki/SplitJoin function strsplit(delimiter, text) local list = {} local pos = 1 if string.find("", delimiter, 1) then -- this would result in endless loops error("delimiter matches empty string!") end while 1 do local first, last = string.find(text, delimiter, pos) if first then -- found? table.insert(list, string.sub(text, pos, first-1)) pos = last+1 else table.insert(list, string.sub(text, pos)) break end end return list end
teraud_loyalist = Creature:new { objectName = "@mob/creature_names:warren_teraud_loyalist", randomNameType = NAME_GENERIC, randomNameTag = true, socialGroup = "warren_teraud", faction = "", level = 34, chanceHit = 0.41, damageMin = 315, damageMax = 340, baseXp = 3460, baseHAM = 8700, baseHAMmax = 10700, armor = 0, resists = {25,25,0,-1,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = { "object/mobile/warren_teraud_loyalist_s01.iff", "object/mobile/warren_teraud_loyalist_s02.iff", "object/mobile/warren_teraud_loyalist_s03.iff", "object/mobile/warren_teraud_loyalist_s04.iff"}, lootGroups = { { groups = { {group = "junk", chance = 4500000}, {group = "tailor_components", chance = 1000000}, {group = "loot_kit_parts", chance = 2000000}, {group = "armor_attachments", chance = 500000}, {group = "clothing_attachments", chance = 500000}, {group = "wearables_common", chance = 1500000} } } }, weapons = {"pirate_weapons_medium"}, conversationTemplate = "", attacks = merge(brawlermaster,marksmanmaster,carbineermaster) } CreatureTemplates:addCreatureTemplate(teraud_loyalist, "teraud_loyalist")
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local t_insert, t_sort, t_remove, t_concat = table.insert, table.sort, table.remove, table.concat; local setmetatable = setmetatable; local getmetatable = getmetatable; local math_random = math.random; local math_floor = math.floor; local pairs, ipairs = pairs, ipairs; local tostring = tostring; local type = type; local array = {}; local array_base = {}; local array_methods = {}; local array_mt = { __index = array_methods; __name = "array"; __tostring = function (self) return "{"..self:concat(", ").."}"; end; }; function array_mt:__freeze() return self; end local function new_array(self, t, _s, _var) if type(t) == "function" then -- Assume iterator t = self.collect(t, _s, _var); end return setmetatable(t or {}, array_mt); end function array_mt.__add(a1, a2) local res = new_array(); return res:append(a1):append(a2); end function array_mt.__eq(a, b) if getmetatable(a) ~= array_mt or getmetatable(b) ~= array_mt then -- Lua 5.3+ calls this if both operands are tables, even if metatables differ return false; end if #a == #b then for i = 1, #a do if a[i] ~= b[i] then return false; end end else return false; end return true; end function array_mt.__div(a1, func) local a2 = new_array(); local o = 0; for i = 1, #a1 do local new_value = func(a1[i]); if new_value ~= nil then o = o + 1; a2[o] = new_value; end end return a2; end setmetatable(array, { __call = new_array }); -- Read-only methods function array_methods:random() return self[math_random(1, #self)]; end -- Return a random value excluding the one at idx function array_methods:random_other(idx) local max = #self; return self[((math.random(1, max-1)+(idx-1))%max)+1]; end -- These methods can be called two ways: -- array.method(existing_array, [params [, ...]]) -- Create new array for result -- existing_array:method([params, ...]) -- Transform existing array into result -- function array_base.map(outa, ina, func) for k, v in ipairs(ina) do outa[k] = func(v); end return outa; end function array_base.filter(outa, ina, func) local inplace, start_length = ina == outa, #ina; local write = 1; for read = 1, start_length do local v = ina[read]; if func(v) then outa[write] = v; write = write + 1; end end if inplace and write <= start_length then for i = write, start_length do outa[i] = nil; end end return outa; end function array_base.sort(outa, ina, ...) if ina ~= outa then outa:append(ina); end t_sort(outa, ...); return outa; end function array_base.unique(outa, ina) local seen = {}; return array_base.filter(outa, ina, function (item) if seen[item] then return false; else seen[item] = true; return true; end end); end function array_base.pluck(outa, ina, key, default) for i = 1, #ina do local v = ina[i][key]; if v == nil then v = default; end outa[i] = v; end return outa; end function array_base.reverse(outa, ina) local len = #ina; if ina == outa then local middle = math_floor(len/2); len = len + 1; local o; -- opposite for i = 1, middle do o = len - i; outa[i], outa[o] = outa[o], outa[i]; end else local off = len + 1; for i = 1, len do outa[i] = ina[off - i]; end end return outa; end --- These methods only mutate the array function array_methods:shuffle() local len = #self; for i = 1, #self do local r = math_random(i, len); self[i], self[r] = self[r], self[i]; end return self; end function array_methods:append(ina) local len, len2 = #self, #ina; for i = 1, len2 do self[len+i] = ina[i]; end return self; end function array_methods:push(x) t_insert(self, x); return self; end array_methods.pop = t_remove; function array_methods:concat(sep) return t_concat(array.map(self, tostring), sep); end function array_methods:length() return #self; end --- These methods always create a new array function array.collect(f, s, var) local t = {}; while true do var = f(s, var); if var == nil then break; end t_insert(t, var); end return setmetatable(t, array_mt); end --- -- Setup methods from array_base for method, f in pairs(array_base) do local base_method = f; -- Setup global array method which makes new array array[method] = function (old_a, ...) local a = new_array(); return base_method(a, old_a, ...); end -- Setup per-array (mutating) method array_methods[method] = function (self, ...) return base_method(self, self, ...); end end return array;
vim.cmd("autocmd BufEnter * lua require'completion'.on_attach()")
TOOL.Category = "Metro" TOOL.Name = "Train Feature Editor" TOOL.Command = nil TOOL.ConfigName = "" if CLIENT then language.Add("Tool.switch.name", "Train Feature Editor") language.Add("Tool.switch.desc", "Change features of the target train") language.Add("Tool.switch.0", "Primary: Apply selected features to the train") end TOOL.ClientConVar["train"] = 0 TOOL.ClientConVar["passtexture"] = 0 TOOL.ClientConVar["texture"] = 0 TOOL.ClientConVar["adv"] = 1 TOOL.ClientConVar["led"] = 0 TOOL.ClientConVar["cran"] = 0 TOOL.ClientConVar["bpsn"] = 1 TOOL.ClientConVar["kvsnd"] = 1 TOOL.ClientConVar["oldkvpos"] = 0 TOOL.ClientConVar["horn"] = 0 TOOL.ClientConVar["ars"] = 1 TOOL.ClientConVar["lamp"] = 0 TOOL.ClientConVar["mask"] = 0 TOOL.ClientConVar["seat"] = 0 TOOL.ClientConVar["hand"] = 0 TOOL.ClientConVar["mvm"] = 0 TOOL.ClientConVar["bort"] = 0 TOOL.ClientConVar["horn"] = 0 TOOL.ClientConVar["breakers"] = 0 function TOOL:LeftClick(trace) if CLIENT then return true end local ply = self:GetOwner() if not trace then return false end if trace.Entity and trace.Entity:IsPlayer() then return false end if not Metrostroi.IsTrainClass[trace.Entity:GetClass()] then return false end local train = trace.Entity if train:GetClass():find("1-703") then return end --train:SetSkin(self:GetClientNumber("skin")) train.LED = self:GetClientNumber("led") > 0 train.ARSType = self:GetClientNumber("ars") train:SetNW2Int("ARSType",train.ARSType) train.LampType = self:GetClientNumber("lamp") train.MaskType = self:GetClientNumber("mask") train.SeatType = self:GetClientNumber("seat") train.HandRail = self:GetClientNumber("hand") train.MVM = self:GetClientNumber("mvm") > 0 train.BortLampType = self:GetClientNumber("bort") train.BPSNType= self:GetClientNumber("bpsn") train.Breakers= self:GetClientNumber("breakers") train:SetNW2Bool("Breakers",(train.Breakers or 1) > 0) train.OldKVPos = self:GetClientNumber("oldkvpos") > 0 train.Adverts = self:GetClientNumber("adv") --train:SetNW2Int("ARSType",train.ARSType) train:SetNW2Int("BPSNType",train.BPSNType+1) --if self:GetClientNumber("kvsnd") > 0 then for k,v in pairs(train.SoundNames) do if type(v) ~= "string" then continue end if not k:find("kv_") then continue end if k:find("ezh") then continue end train.KVSnd = self:GetClientNumber("kvsnd") train.SoundNames[k] = string.gsub(v,"kv%d","kv"..self:GetClientNumber("kvsnd")) train.NewKV = self:GetClientNumber("kvsnd") > 1 train:SetNW2Bool("NewKV",train.NewKV) end --else --for k,v in pairs(train.SoundNames) do -- if type(v) ~= "string" then continue end --if not v:find("kv_") then continue end --if v:find("ezh") then continue end --train.SoundNames[k] = string.Replace(v,"subway_trains/kv","subway_trains/new/kv") --end --end if train.Horn then train.Horn:TriggerInput("NewType",self:GetClientNumber("horn")) end if not train:GetClass():find("81") then local path = Metrostroi.Skins["ezh3"][self:GetClientNumber("texture")].path if path == "RND" then path = Metrostroi.Skins["ezh3"][math.random(1,#Metrostroi.Skins["ezh3"])].path end train.Texture = path --ent:SetSkin(self.tbl.Paint == 1 and math.random(0,2) or self.tbl.Paint-2) else train.Pneumatic.ValveType = self:GetClientNumber("cran") train.Texture = Metrostroi.Skins["717"][self:GetClientNumber("texture")] and Metrostroi.Skins["717"][self:GetClientNumber("texture")].path or nil local path = Metrostroi.Skins["717_pass"][self:GetClientNumber("passtexture")] and Metrostroi.Skins["717_pass"][self:GetClientNumber("passtexture")].path or nil if path == "RND" then path = Metrostroi.Skins["717_pass"][math.random(1,#Metrostroi.Skins["717_pass"])].path end train.PassTexture = path --ent:SetSkin(self.tbl.Paint-1) end --Entity:SetSkin( --[[local entlist = ents.FindInSphere(trace.HitPos,64) for k,v in pairs(entlist) do if v:GetClass() == "gmod_track_switch" then v:SetChannel(1) print("Set channel 1") end end]]-- return true end function TOOL:RightClick(trace) return true end local SettingTypes = { "Train,Texture,PassTexture,ARS,Cran,Mask,LED,BPSN,KVSnd,Horn,OldKVPos,Bort,MVM,Hand,Seat,Lamp,Breakers,Adv", "Train,Texture,PassTexture,ARS,Cran,Mask,LED,BPSN,KVSnd,Horn,OldKVPos,Bort,MVM,Hand,Seat,Lamp,Breakers,Adv", "Train", "Train", "Train,Texture,Horn", "Train", } function TOOL:UpdateConCMD() for k,v in pairs(self.Settings) do RunConsoleCommand("train_edit_"..k:lower(), v) end end function TOOL:LoadConCMD() self.Settings = { Train = 1, Texture = 1, PassTexture = 1, Adv = 1, ARS = 1, Cran = 1, Mask = 1, BPSN = 1, KVSnd = 1, OldKVPos = 0, Horn = 0, LED = 0, Horn = 0, Bort = 0, MVM = 0, Hand = 0, Seat = 0, Lamp = 0, Breakers = 0, } for k in pairs(self.Settings) do self.Settings[k] = GetConVarNumber("train_edit_"..k:lower()) end if self.Settings.Train > #SettingTypes then self.Settings.Train = #SettingTypes RunConsoleCommand("train_edit_train",self.Settings.Train) end if self.Settings.Train < 1 then self.Settings.Train = 1 RunConsoleCommand("train_edit_train",self.Settings.Train) end end function TOOL:CreateList(name,text,tbl,OnSelect) if not SettingTypes[self.Settings.Train]:find(name) then return end local frame = controlpanel.Get("train_edit") local List,ListLabel = frame:ComboBox(text) List:SizeToContents() tbl[0] = text for i=1,#tbl do List:AddChoice(tbl[i], i, self.Settings[name] == i) end local tool = self List.OnSelect = function(self,_, _, index) tool.Settings[name] = index tool:UpdateConCMD() if OnSelect then OnSelect(List,ListLabel) end tool.NotBuilt = true end end function TOOL:CreateCheckBox(name,text,OnSelect) if not SettingTypes[self.Settings.Train]:find(name) then return end local frame = controlpanel.Get("train_edit") local CB = frame:CheckBox(text) CB:SetValue(self.Settings[name]) CB:SizeToContents() local tool = self function CB:OnChange() --tool:BuildCPanelCustom() tool.Settings[name] = CB:GetChecked() and 1 or 0 tool:UpdateConCMD() if OnSelect then OnSelect(CB,CBLabel) end tool.NotBuilt = true end --frame:AddItem(CBLabel) -- frame:AddItem(CB) end function TOOL:UpdateTrainList() --self.VGUI = {} local frame = controlpanel.Get("train_edit") self.Pos = 0 if self.Settings.Train < 3 then if #Metrostroi.Skins[self.Settings.Train == 1 and "717" or "ezh3"] < self.Settings.Texture then self.Settings.Texture = 1 end --if IsValid(self.VGUI.Texture) then self.VGUI.Texture:Clear() end for k,v in pairs(Metrostroi.Skins[self.Settings.Train == 1 and "717" or "ezh3"]) do if not v.path:find("/16") or LocalPlayer():IsAdmin() then --if IsValid(self.VGUI.Texture) then self.VGUI.Texture:AddChoice(v.name, k, k == self.Settings.Texture) end --Texture[k] = v.name else if k == self.Settings.Texture then self.Settings.Texture = 1 end --if IsValid(self.VGUI.Texture) then self.VGUI.Texture:ChooseOptionID(1) end end end for i=1,#Metrostroi.Skins[self.Settings.Train == 1 and "717" or "ezh3"] do end end self.NotBuilt = true end function TOOL:BuildCPanelCustom() self:LoadConCMD() local panel = controlpanel.Get("train_edit") if not panel then return end panel:ClearControls() --panel:SetPadding(0) --panel:SetSpacing(0) panel:Dock( FILL ) local Texture = {} -- for k,v in pairs(Metrostroi.Skins[self.Settings.Train == 1 and "717" or "ezh3"]) do --if not v.path:find("/16") or LocalPlayer():IsAdmin() then -- Texture[k] = v.name --end --end local PassTexture = {} --for k,v in pairs(Metrostroi.Skins[self.Settings.Train == 1 and "717_pass" or "717_pass"]) do --print(v) -- PassTexture[k] = v.name -- end self:CreateList("Train","Train:",{"81-71x MVM","81-71x LVZ","E","Em","Ezh","81-703x"},function() self:UpdateTrainList() end) -- self:CreateSlider("WagNum",0,1, GetGlobalInt("metrostroi_maxwagons"),"Wagons") self:CreateList("Texture","Texture",Texture) self:CreateList("PassTexture","PassTexture",PassTexture) self:CreateList("Adv","Adverts",{"Type1","Type2","Type3","No adverts"}) self:CreateList("Cran","Cran type",{"334","013"}) self:CreateList("ARS","ARS Type",{"Standart(square lamps)","Standart(round lamps)","Kiev/St.Petersburg"}) self:CreateList("Mask","Mask",{"2-2","2-2-2","1-4-1 bumper 1","1-3-1","1-4-1 bumper2","1-1"}) self:CreateList("BPSN","BPSN type",{"Normal","Old high tone","Old medium tone","Normal2(from St.Petersburg)","Normal3(from wiki)","No sound"}) self:CreateList("Seat","Seat type",{"Old","New"}) self:CreateList("Hand","Hand rail type",{"Old","New"}) self:CreateList("Bort","Bort",{"Horisontal","Vertical"}) self:CreateList("Lamp","Lamp type",{"Type1","Type2","Type3"}) self:CreateCheckBox("Breakers","Right-syde breakers") self:CreateCheckBox("LED","LED") self:CreateList("KVSnd","KV snd",{"Dildo","Type2","Type3"}) self:CreateCheckBox("OldKVPos","Old KV pos") self:CreateCheckBox("Horn","Piter horn") self:CreateCheckBox("MVM","MVM icon") --self:UpdateTrainList() --[[ local Train = panel:AddControl("ComboBox", { Label = "ARS panel type", Options = { ["Moscow/default"] = { train_edit_ars = 0 }, ["Classic"] = { train_edit_ars = 1 }, ["Petersburg/Kyiv"] = { train_edit_ars = 2 }, } }) panel:AddControl("ComboBox", { Label = "ARS panel type", Options = { ["Moscow/default"] = { train_edit_ars = 0 }, ["Classic"] = { train_edit_ars = 1 }, ["Petersburg/Kyiv"] = { train_edit_ars = 2 }, } }) panel:AddControl("ComboBox", { Label = "ARS panel type", Options = { ["Moscow/default"] = { train_edit_ars = 0 }, ["Classic"] = { train_edit_ars = 1 }, ["Petersburg/Kyiv"] = { train_edit_ars = 2 }, } }) panel:AddControl("ComboBox", { Label = "Train skin", Options = { ["Default (Moscow)"] = { train_edit_skin = 0 }, ["Alternative 1"] = { train_edit_skin = 1 }, ["Alternative 2"] = { train_edit_skin = 2 }, } }) panel:AddControl("ComboBox", { Label = "Drivers valve type", Options = { ["334"] = { train_edit_valve = 0 }, ["013"] = { train_edit_valve = 1 }, } }) panel:AddControl("ComboBox", { Label = "81-717 front mask type", Options = { ["2-2"] = { train_edit_mask = 0 }, ["2-2-2"] = { train_edit_mask = 1}, ["1-4-1 adv1"] = { train_edit_mask = 2}, ["1-4-1 adv2"] = { train_edit_mask = 3}, ["1-4-1 adv3 bumper 2"] = { train_edit_mask = 4}, } }) panel:AddControl("ComboBox", { Label = "BPSN type", Options = { ["Normal"] = {train_edit_bpsn = 1}, ["Old high tone"] = {train_edit_bpsn = 2}, ["Old medium tone"] = {train_edit_bpsn = 3}, ["Normal2(from St.Petersburg)"] = {train_edit_bpsn = 4}, ["Normal3(from wiki)"] = {train_edit_bpsn = 5}, ["No sound"] = {train_edit_bpsn = 6}, } }) panel:AddControl("ComboBox", { Label = "Horn", Options = { ["Moscow"] = {train_edit_horn = 0}, ["St. Petersburg'"] = {train_edit_horn = 1}, } }) panel:AddControl("ComboBox", { Label = "KV Sounds", Options = { ["New"] = {train_edit_oldkv = 0}, ["Old'"] = {train_edit_oldkv = 1}, } }) ]] end TOOL.NotBuilt = true function TOOL:Think() if CLIENT and (self.NotBuilt or NeedUpdate) then --self:SendSettings() self:BuildCPanelCustom() self.NotBuilt = nil NeedUpdate = nil end end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool.switch.name", Description = "#Tool.switch.desc" }) end
msgpack = require('msgpack') env = require('test_run') test_run = env.new() s = box.schema.space.create('select', { temporary = true }) index1 = s:create_index('primary', { type = 'tree' }) index2 = s:create_index('second', { type = 'tree', unique = true, parts = {2, 'unsigned', 1, 'unsigned'}}) for i = 1, 20 do s:insert({ i, 1, 2, 3 }) end test_run:cmd("setopt delimiter ';'") local function test_op(op, idx, ...) local t1 = idx[op .. '_ffi'](idx, ...) local t2 = idx[op .. '_luac'](idx, ...) if msgpack.encode(t1) ~= msgpack.encode(t2) then return 'different result from '..op..'_ffi and '..op..'_luac', t1, t2 end return t1 end test = setmetatable({}, { __index = function(_, op) return function(...) return test_op(op, ...) end end }); test_run:cmd("setopt delimiter ''"); -------------------------------------------------------------------------------- -- get tests -------------------------------------------------------------------------------- s.index[0].get == s.index[0].get_ffi or s.index[0].get == s.index[0].get_luac test.get(s.index[0]) test.get(s.index[0], {}) test.get(s.index[0], nil) test.get(s.index[0], 1) test.get(s.index[0], {1}) test.get(s.index[0], {1, 2}) test.get(s.index[0], 0) test.get(s.index[0], {0}) test.get(s.index[0], "0") test.get(s.index[0], {"0"}) test.get(s.index[1], 1) test.get(s.index[1], {1}) test.get(s.index[1], {1, 2}) -------------------------------------------------------------------------------- -- select tests -------------------------------------------------------------------------------- s.index[0].select == s.index[0].select_ffi or s.index[0].select == s.index[0].select_luac test.select(s.index[0]) test.select(s.index[0], {}) test.select(s.index[0], nil) test.select(s.index[0], {}, {iterator = 'ALL'}) test.select(s.index[0], nil, {iterator = box.index.ALL }) test.select(s.index[0], {}, {iterator = box.index.ALL, limit = 10}) test.select(s.index[0], nil, {iterator = box.index.ALL, limit = 0}) test.select(s.index[0], {}, {iterator = 'ALL', limit = 1, offset = 15}) test.select(s.index[0], nil, {iterator = 'ALL', limit = 20, offset = 15}) test.select(s.index[0], nil, {iterator = box.index.EQ}) test.select(s.index[0], {}, {iterator = 'EQ'}) test.select(s.index[0], nil, {iterator = 'REQ'}) test.select(s.index[0], {}, {iterator = box.index.REQ}) test.select(s.index[0], nil, {iterator = 'EQ', limit = 2, offset = 1}) test.select(s.index[0], {}, {iterator = box.index.REQ, limit = 2, offset = 1}) test.select(s.index[0], 1) test.select(s.index[0], {1}) test.select(s.index[0], {1, 2}) test.select(s.index[0], 0) test.select(s.index[0], {0}) test.select(s.index[0], "0") test.select(s.index[0], {"0"}) test.select(s.index[1], 1) test.select(s.index[1], {1}) test.select(s.index[1], {1}, {limit = 2}) test.select(s.index[1], 1, {iterator = 'EQ'}) test.select(s.index[1], {1}, {iterator = box.index.EQ, offset = 16, limit = 2}) test.select(s.index[1], {1}, {iterator = box.index.REQ, offset = 16, limit = 2 }) test.select(s.index[1], {1, 2}, {iterator = 'EQ'}) test.select(s.index[1], {1, 2}, {iterator = box.index.REQ}) test.select(s.index[1], {1, 2}) test.select(s.index[0], nil, { iterator = 'ALL', offset = 0, limit = 4294967295 }) test.select(s.index[0], {}, { iterator = 'ALL', offset = 0, limit = 4294967295 }) test.select(s.index[0], 1) test.select(s.index[0], 1, { iterator = box.index.EQ }) test.select(s.index[0], 1, { iterator = 'EQ' }) test.select(s.index[0], 1, { iterator = 'GE' }) test.select(s.index[0], 1, { iterator = 'GE', limit = 2 }) test.select(s.index[0], 1, { iterator = 'LE', limit = 2 }) test.select(s.index[0], 1, { iterator = 'GE', offset = 10, limit = 2 }) s:select(2) -------------------------------------------------------------------------------- -- min/max tests -------------------------------------------------------------------------------- test.min(s.index[1]) test.max(s.index[1]) -------------------------------------------------------------------------------- -- count tests -------------------------------------------------------------------------------- test.count(s.index[1]) test.count(s.index[0], nil) test.count(s.index[0], {}) test.count(s.index[0], 10, { iterator = 'GT'}) -------------------------------------------------------------------------------- -- random tests -------------------------------------------------------------------------------- test.random(s.index[0], 48) s:drop() collectgarbage('collect') -- gh-3224 resurrect tuple bigrefs collectgarbage('stop') s = box.schema.space.create('select', { temporary = true }) index = s:create_index('primary', { type = 'tree' }) _ = s:insert{0} _ = s:insert{1} _ = s:insert{2} _ = s:insert{3} lots_of_links = setmetatable({}, {__mode = 'v'}) i = 0 while (i < 33000) do table.insert(lots_of_links, s:get{0}) i = i + 1 end while (i < 66000) do table.insert(lots_of_links, s:get{1}) i = i + 1 end while (i < 100000) do table.insert(lots_of_links, s:get{2}) i = i + 1 end ref_count = 0 for k, v in pairs(lots_of_links) do ref_count = ref_count + 1 end ref_count -- check that tuples are deleted after gc is activated collectgarbage('collect') lots_of_links s:drop()
--[[---------------------------------------------------------------------------- Copyright (c) 2010, Erik Raetz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of rBottomBarStyler nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------]] ------------------------------------------------------ -- / VARIABLES / -- ------------------------------------------------------ local default_scale = 0.82 local default_art = "roth" local default_bar = "bar2" local default_movable = 1 local default_locked = 1 local default_healthorb = 0 local default_manaorb = 3 local default_automana = 1 local usegalaxy = 1 local default_font = NAMEPLATE_FONT rBottomBarStyler = rBottomBarStyler or {} local frame_to_scale local bar_to_show local hfill, mfill local hgal1,hgal2,hgal3,mgal1,mgal2,mgal3 local frame_to_drag local player_class_color = RAID_CLASS_COLORS[select(2, UnitClass("player"))] local orbtab = { [0] = {r = player_class_color.r*0.8, g = player_class_color.g*0.8, b = player_class_color.b*0.8, scale = 0.9, z = -12, x = -0.5, y = -0.8, anim = "SPELLS\WhiteRadiationFog.m2"}, -- class color [1] = {r = 0.8, g = 0, b = 0, scale = 0.8, z = -12, x = 0.8, y = -1.7, anim = "SPELLS\\RedRadiationFog.m2"}, -- red [2] = {r = 0.2, g = 0.8, b = 0, scale = 0.75, z = -12, x = 0, y = -1.1, anim = "SPELLS\\GreenRadiationFog.m2"}, -- green [3] = {r = 0, g = 0.35, b = 0.9, scale = 0.75, z = -12, x = 1.2, y = -1, anim = "SPELLS\\BlueRadiationFog.m2"}, -- blue [4] = {r = 0.9, g = 0.7, b = 0.1, scale = 0.75, z = -12, x = -0.3, y = -1.2, anim = "SPELLS\\OrangeRadiationFog.m2"}, -- yellow [5] = {r = 0.1, g = 0.8, b = 0.7, scale = 0.9, z = -12, x = -0.5, y = -0.8, anim = "SPELLS\\WhiteRadiationFog.m2"}, -- runic } local galaxytab = { [0] = {r = player_class_color.r, g = player_class_color.g, b = player_class_color.b, }, -- class color [1] = {r = 0.90, g = 0.1, b = 0.1, }, -- red [2] = {r = 0.25, g = 0.9, b = 0.25, }, -- green [3] = {r = 0, g = 0.35, b = 0.9, }, -- blue [4] = {r = 0.9, g = 0.8, b = 0.35, }, -- yellow [5] = {r = 0.35, g = 0.9, b = 0.9, }, -- runic } local rBBS_PowerColor = {} rBBS_PowerColor["MANA"] = { r = 0, g = 0.4, b = 1 }; rBBS_PowerColor["RAGE"] = { r = 1.00, g = 0.00, b = 0.00 }; rBBS_PowerColor["FOCUS"] = { r = 1.00, g = 0.50, b = 0.25 }; rBBS_PowerColor["ENERGY"] = { r = 1.00, g = 0.75, b = 0.10 }; rBBS_PowerColor["HAPPINESS"] = { r = 0.00, g = 1.00, b = 1.00 }; rBBS_PowerColor["RUNES"] = { r = 0.50, g = 0.50, b = 0.50 }; rBBS_PowerColor["RUNIC_POWER"] = { r = 0.00, g = 0.82, b = 1.00 }; rBBS_PowerColor["AMMOSLOT"] = { r = 0.80, g = 0.60, b = 0.00 }; rBBS_PowerColor["FUEL"] = { r = 0.0, g = 0.55, b = 0.5 }; ------------------------------------------------------ -- / CHAT OUTPUT FUNC / -- ------------------------------------------------------ local function am(text) DEFAULT_CHAT_FRAME:AddMessage(text) end ------------------------------------------------------ -- / SET UP DEFAULT VALUES / -- ------------------------------------------------------ local function load_default() if(not rBottomBarStyler.scalevalue) then rBottomBarStyler.scalevalue = default_scale end if(not rBottomBarStyler.artvalue) then rBottomBarStyler.artvalue = default_art end if(not rBottomBarStyler.barvalue) then rBottomBarStyler.barvalue = default_bar end if(not rBottomBarStyler.movable) then rBottomBarStyler.movable = default_movable end if(not rBottomBarStyler.locked) then rBottomBarStyler.locked = default_locked end if(not rBottomBarStyler.healthorb) then rBottomBarStyler.healthorb = default_healthorb end if(not rBottomBarStyler.manaorb) then rBottomBarStyler.manaorb = default_manaorb end if(not rBottomBarStyler.automana) then rBottomBarStyler.automana = default_automana end end ------------------------------------------------------ -- / SAVE POSXY FUNC / -- ------------------------------------------------------ local function save_posxy() local point, relativeTo, relativePoint, x, y = frame_to_scale:GetPoint() rBottomBarStyler.point = point rBottomBarStyler.posx = x rBottomBarStyler.posy = y end ------------------------------------------------------ -- / MOVE ME FUNC / -- ------------------------------------------------------ local function move_my_frame() if frame_to_drag then frame_to_drag:Hide() end if rBottomBarStyler.movable == 1 then frame_to_scale:SetMovable(true) if rBottomBarStyler.locked == 0 then if frame_to_drag then frame_to_drag:Show() end frame_to_scale:EnableMouse(true) frame_to_scale:RegisterForDrag("LeftButton","RightButton") frame_to_scale:SetScript("OnDragStart", function(self) if IsShiftKeyDown() and IsAltKeyDown() then self:StartMoving() end end) frame_to_scale:SetScript("OnDragStop", function(self) if IsShiftKeyDown() and IsAltKeyDown() then self:StopMovingOrSizing() save_posxy() end end) end else rBottomBarStyler.point = nil rBottomBarStyler.posx = nil rBottomBarStyler.posy = nil frame_to_scale:ClearAllPoints() frame_to_scale:SetPoint("BOTTOM",0,0) end end ------------------------------------------------------ -- / SET ME GLOWS / -- ------------------------------------------------------ local function set_the_hglows() hfill:SetVertexColor(orbtab[rBottomBarStyler.healthorb].r,orbtab[rBottomBarStyler.healthorb].g,orbtab[rBottomBarStyler.healthorb].b) hgal1.t:SetVertexColor(galaxytab[rBottomBarStyler.healthorb].r,galaxytab[rBottomBarStyler.healthorb].g,galaxytab[rBottomBarStyler.healthorb].b) hgal2.t:SetVertexColor(galaxytab[rBottomBarStyler.healthorb].r,galaxytab[rBottomBarStyler.healthorb].g,galaxytab[rBottomBarStyler.healthorb].b) hgal3.t:SetVertexColor(galaxytab[rBottomBarStyler.healthorb].r,galaxytab[rBottomBarStyler.healthorb].g,galaxytab[rBottomBarStyler.healthorb].b) end local function set_the_mglows() local powertype = select(2, UnitPowerType("player")) local color = rBBS_PowerColor[powertype] if color and rBottomBarStyler.automana == 1 then mfill:SetVertexColor(color.r,color.g,color.b) mgal1.t:SetVertexColor(color.r,color.g,color.b) mgal2.t:SetVertexColor(color.r,color.g,color.b) mgal3.t:SetVertexColor(color.r,color.g,color.b) else mfill:SetVertexColor(orbtab[rBottomBarStyler.manaorb].r,orbtab[rBottomBarStyler.manaorb].g,orbtab[rBottomBarStyler.manaorb].b) mgal1.t:SetVertexColor(galaxytab[rBottomBarStyler.manaorb].r,galaxytab[rBottomBarStyler.manaorb].g,galaxytab[rBottomBarStyler.manaorb].b) mgal2.t:SetVertexColor(galaxytab[rBottomBarStyler.manaorb].r,galaxytab[rBottomBarStyler.manaorb].g,galaxytab[rBottomBarStyler.manaorb].b) mgal3.t:SetVertexColor(galaxytab[rBottomBarStyler.manaorb].r,galaxytab[rBottomBarStyler.manaorb].g,galaxytab[rBottomBarStyler.manaorb].b) end end ------------------------------------------------------ -- / CREATE ME A ORB GALAXY FUNC / -- ------------------------------------------------------ local function create_me_a_galaxy(f,x,y,size,alpha,dur,tex,useorb) local h = CreateFrame("Frame",nil,f) h:SetHeight(size) h:SetWidth(size) h:SetPoint("CENTER",x,y-10) h:SetAlpha(alpha) h:SetFrameLevel(5) local t = h:CreateTexture() t:SetAllPoints(h) t:SetTexture("Interface\\AddOns\\rBottomBarStyler\\orbtex\\"..tex) t:SetBlendMode("ADD") t:SetVertexColor(galaxytab[useorb].r,galaxytab[useorb].g,galaxytab[useorb].b) h.t = t local ag = h:CreateAnimationGroup() h.ag = ag local a1 = h.ag:CreateAnimation("Rotation") a1:SetDegrees(360) a1:SetDuration(dur) h.ag.a1 = a1 h.ag:SetLooping("REPEAT") h.ag:Play() return h end ------------------------------------------------------ -- / CREATE ME A FRAME FUNC / -- ------------------------------------------------------ local function create_me_a_frame(fart,fname,fparent,fstrata,flevel,fwidth,fheight,fanchor,fxpos,fypos,fscale,fdrag,finherit) -- PARENT, BACKGROUND, LOW, MEDIUM, HIGH, DIALOG, FULLSCREEN, FULLSCREEN_DIALOG, TOOLTIP local f = CreateFrame(fart,fname,fparent,finherit) f:SetFrameStrata(fstrata) f:SetFrameLevel(flevel) f:SetWidth(fwidth) f:SetHeight(fheight) if fname == "rBBS_Holder" then if rBottomBarStyler.point and rBottomBarStyler.posx and rBottomBarStyler.posy then f:SetPoint(rBottomBarStyler.point,rBottomBarStyler.posx,rBottomBarStyler.posy) else f:SetPoint(fanchor,fxpos,fypos) end else f:SetPoint(fanchor,fxpos,fypos) end f:SetScale(fscale) if fdrag == true then f:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background", edgeFile = "", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 0, right = 0, top = 0, bottom = 0 }}) end return f end ------------------------------------------------------ -- / CREATE ME A TEXTURE FUNC / -- ------------------------------------------------------ local function create_me_a_texture(fhooked,tstrata,tfile,tspecial) -- BACKGROUND, BORDER, ARTWORK, OVERLAY, HIGHLIGHT local t = fhooked:CreateTexture(nil,tstrata) t:SetTexture(tfile) if tspecial == "fill" then t:SetPoint("BOTTOM",fhooked,"BOTTOM",0,0) t:SetWidth(fhooked:GetWidth()) t:SetHeight(fhooked:GetHeight()) else t:SetAllPoints(fhooked) end return t end ------------------------------------------------------ -- / DO FORMAT / -- ------------------------------------------------------ local function do_format(v) local string = "" if v > 1000000 then string = (floor((v/1000000)*10)/10).."m" elseif v > 1000 then string = (floor((v/1000)*10)/10).."k" else string = v end return string end ------------------------------------------------------ -- / ORB HEALTH FUNC / -- ------------------------------------------------------ local function orbhealth(orb1,orb1_fill,orbtext1,orbtext2) orb1:SetScript("OnEvent", function(self, event, arg1, ...) if event == "PLAYER_LOGIN" or event == "PLAYER_ENTERING_WORLD" or arg1 == "player" then local uh, uhm = UnitHealth("player"), UnitHealthMax("player") local perc = floor(uh/uhm*100) local nuh = do_format(uh) local nuhm = do_format(uhm) orbtext1:SetText(perc) orbtext2:SetText(nuh) orb1_fill:SetHeight((uh/uhm) * orb1_fill:GetWidth()) orb1_fill:SetTexCoord(0,1, math.abs(uh/uhm - 1),1) set_the_hglows() hgal1:SetAlpha(uh / uhm) hgal2:SetAlpha(uh / uhm) hgal3:SetAlpha(uh / uhm) end end) orb1:RegisterEvent("UNIT_HEALTH") orb1:RegisterEvent("PLAYER_LOGIN") orb1:RegisterEvent("PLAYER_ENTERING_WORLD") end ------------------------------------------------------ -- / ORB MANA FUNC / -- ------------------------------------------------------ local function orbmana(orb2,orb2_fill,orbtext1,orbtext2) orb2:SetScript("OnEvent", function(self, event, arg1, ...) if event == "PLAYER_LOGIN" or event == "PLAYER_ENTERING_WORLD" or event == "UPDATE_SHAPESHIFT_FORM" or arg1 == "player" then local um, umm = UnitMana("player"), UnitManaMax("player") local perc = floor(um/umm*100) local nuh = do_format(um) local nuhm = do_format(umm) local powertype = select(2, UnitPowerType("player")) if powertype ~= "MANA" then orbtext1:SetText(nuh) orbtext2:SetText(perc) else orbtext1:SetText(perc) orbtext2:SetText(nuh) end orb2_fill:SetHeight((um/umm) * orb2_fill:GetWidth()) orb2_fill:SetTexCoord(0,1, math.abs(um/umm - 1),1) set_the_mglows() mgal1:SetAlpha(um / umm) mgal2:SetAlpha(um / umm) mgal3:SetAlpha(um / umm) end end) orb2:RegisterEvent("UNIT_POWER") orb2:RegisterEvent("UNIT_MAXPOWER") orb2:RegisterEvent("PLAYER_ENTERING_WORLD") orb2:RegisterEvent("PLAYER_LOGIN") orb2:RegisterEvent("UPDATE_SHAPESHIFT_FORM") end ------------------------------------------------------ -- / SET ME A FONT / -- ------------------------------------------------------ local function set_me_a_font(f, font, size, style) local fs = f:CreateFontString(nil, "OVERLAY") fs:SetFont(font, size, style) fs:SetShadowColor(0,0,0,1) return fs end ------------------------------------------------------ -- / CREATE ORB FUNC / -- ------------------------------------------------------ local function create_orb(orbtype,orbsize,orbanchorframe,orbpoint,orbposx,orbposy,orbscale,orbfilltex,useorb) --create the player frame local orbname = "rBBSManaOrb" if orbtype == "life" then orbname = "rBBSLifeOrb" end local orb1 = create_me_a_frame("Button",orbname,orbanchorframe,"BACKGROUND",4,orbsize,orbsize,orbpoint,orbposx,orbposy,orbscale,nil,"SecureUnitButtonTemplate") orb1:RegisterForClicks("AnyUp") orb1:SetAttribute("unit", "player") orb1:SetAttribute("*type1", "target") local showmenu = function() ToggleDropDownMenu(1, nil, PlayerFrameDropDown, "cursor", 0, 0) end orb1.showmenu = showmenu orb1.unit = "player" orb1:SetAttribute("*type2", "showmenu") orb1:SetScript("OnEnter", UnitFrame_OnEnter) orb1:SetScript("OnLeave", UnitFrame_OnLeave) ClickCastFrames = ClickCastFrames or {} ClickCastFrames[orb1] = true local orb1_back = create_me_a_texture(orb1,"BORDER","Interface\\AddOns\\rBottomBarStyler\\orbtex\\orb_back2") local orb1_fill = create_me_a_texture(orb1,"ARTWORK","Interface\\AddOns\\rBottomBarStyler\\orbtex\\"..orbfilltex,"fill") if orbtype == "life" then orb1_fill:SetVertexColor(orbtab[useorb].r,orbtab[useorb].g,orbtab[useorb].b) hfill = orb1_fill hgal1 = create_me_a_galaxy(orb1,0,15,110,1,35,"galaxy2",useorb) hgal2 = create_me_a_galaxy(orb1,0,-10,150,1,45,"galaxy",useorb) hgal3 = create_me_a_galaxy(orb1,-10,-10,130,1,18,"galaxy3",useorb) else orb1_fill:SetVertexColor(orbtab[useorb].r,orbtab[useorb].g,orbtab[useorb].b) mfill = orb1_fill mgal1 = create_me_a_galaxy(orb1,0,10,110,1,40,"galaxy2",useorb) mgal2 = create_me_a_galaxy(orb1,-10,-10,150,1,50,"galaxy",useorb) mgal3 = create_me_a_galaxy(orb1,10,-10,130,1,20,"galaxy3",useorb) end local orb1_glossholder = create_me_a_frame("Frame",nil,orb1,"BACKGROUND",6,orbsize,orbsize,"BOTTOM",0,0,1) local orb1_gloss = create_me_a_texture(orb1_glossholder,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\orbtex\\orb_gloss") local orbtext1 = set_me_a_font(orb1_glossholder, default_font, orbsize/5.5, "THINOUTLINE") orbtext1:SetPoint("CENTER", 0, (orbsize/12)) orbtext1:SetTextColor(1,1,1) local orbtext2 = set_me_a_font(orb1_glossholder, default_font, orbsize/9, "THINOUTLINE") orbtext2:SetPoint("CENTER", 0, -(orbsize/12)) orbtext2:SetTextColor(0.6,0.6,0.6) if orbtype == "life" then orbhealth(orb1,orb1_fill,orbtext1,orbtext2) else orbmana(orb1,orb1_fill,orbtext1,orbtext2) end end ------------------------------------------------------ -- / SET ME A SCALE / -- ------------------------------------------------------ local function set_me_a_scale() frame_to_scale:SetScale(rBottomBarStyler.scalevalue) end ------------------------------------------------------ -- / SET ME A BAR / -- ------------------------------------------------------ local function set_me_a_bar() if rBottomBarStyler.artvalue == "roth" then bar_to_show:SetTexture("Interface\\AddOns\\rBottomBarStyler\\rothtex\\"..rBottomBarStyler.barvalue) elseif rBottomBarStyler.artvalue == "d3" then bar_to_show:SetTexture("Interface\\AddOns\\rBottomBarStyler\\d3tex\\"..rBottomBarStyler.barvalue) elseif rBottomBarStyler.artvalue == "d3no" then bar_to_show:SetTexture("Interface\\AddOns\\rBottomBarStyler\\d3tex\\"..rBottomBarStyler.barvalue) else am("Does only work for roth or d3 layout") end end ------------------------------------------------------ -- / CREATE D1 STYLE / -- ------------------------------------------------------ local function create_d1_style(scale) --holder local holder = create_me_a_frame("Frame","rBBS_Holder",UIParent,"BACKGROUND",1,100,100,"BOTTOM",0,0,scale) frame_to_scale = holder --bar texture local bar = create_me_a_frame("Frame",nil,holder,"BACKGROUND",2,1024,256,"BOTTOM",0,0,1) local bar_tex = create_me_a_texture(bar,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d1tex\\bar") --orbs create_orb("life",160,holder,"BOTTOM",-290,120,1,"orb_filling8",rBottomBarStyler.healthorb) create_orb("mana",160,holder,"BOTTOM",285,120,1,"orb_filling8",rBottomBarStyler.manaorb) --left figure local lefty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,256,256,"BOTTOM",-320,35,0.9) local lefty_tex = create_me_a_texture(lefty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d1tex\\figure_left") --right figure local righty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,256,256,"BOTTOM",320,35,0.9) local righty_tex = create_me_a_texture(righty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d1tex\\figure_right") --dragframe local dragframe = create_me_a_frame("Frame",nil,holder,"TOOLTIP",1,100,100,"BOTTOM",0,0,scale,true) frame_to_drag = dragframe end ------------------------------------------------------ -- / CREATE D2 STYLE / -- ------------------------------------------------------ local function create_d2_style(scale) --holder local holder = create_me_a_frame("Frame","rBBS_Holder",UIParent,"BACKGROUND",1,100,100,"BOTTOM",0,0,scale) frame_to_scale = holder --bar texture local bar = create_me_a_frame("Frame",nil,holder,"BACKGROUND",8,1024,128,"BOTTOM",0,44,1) local bar_tex = create_me_a_texture(bar,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d2tex\\bar") --border local border_left = create_me_a_frame("Frame",nil,holder,"BACKGROUND",3,1024,512,"BOTTOMRIGHT",-40,0,1) local border_left_tex = create_me_a_texture(border_left,"BORDER","Interface\\AddOns\\rBottomBarStyler\\d2tex\\border_left") local border_right = create_me_a_frame("Frame",nil,holder,"BACKGROUND",3,1024,512,"BOTTOMLEFT",40,0,1) local border_right_tex = create_me_a_texture(border_right,"BORDER","Interface\\AddOns\\rBottomBarStyler\\d2tex\\border_right") --orbs create_orb("life",160,holder,"BOTTOM",-472,55,1,"orb_filling8",rBottomBarStyler.healthorb) create_orb("mana",160,holder,"BOTTOM",465,55,1,"orb_filling8",rBottomBarStyler.manaorb) --left figure local lefty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,256,256,"BOTTOM",-453,44,1) local lefty_tex = create_me_a_texture(lefty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d2tex\\figure_left") --right figure local righty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,256,256,"BOTTOM",453,44,1) local righty_tex = create_me_a_texture(righty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d2tex\\figure_right") --dragframe local dragframe = create_me_a_frame("Frame",nil,holder,"TOOLTIP",1,100,100,"BOTTOM",0,0,scale,true) frame_to_drag = dragframe end ------------------------------------------------------ -- / CREATE D3 STYLE (ADAPTED) / -- ------------------------------------------------------ local function create_d3_style(scale) --holder local holder = create_me_a_frame("Frame","rBBS_Holder",UIParent,"BACKGROUND",1,100,100,"BOTTOM",0,0,scale) frame_to_scale = holder --bar texture local bar = create_me_a_frame("Frame",nil,holder,"BACKGROUND",2,1024,512,"BOTTOM",0,0,1) local bar_tex = create_me_a_texture(bar,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\"..rBottomBarStyler.barvalue) bar_to_show = bar_tex --orbs create_orb("life",200,holder,"BOTTOM",-525,-6,1,"orb_filling8",rBottomBarStyler.healthorb) create_orb("mana",200,holder,"BOTTOM",525,-6,1,"orb_filling8",rBottomBarStyler.manaorb) --xp local xpholder = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,1178,32,"BOTTOM",0,104,1) local xpholder_tex = create_me_a_texture(xpholder,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\xpbar") --left figure local lefty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,512,256,"BOTTOM",-520,0,1) local lefty_tex = create_me_a_texture(lefty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\figure_left") --right figure local righty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,512,256,"BOTTOM",522,0,1) local righty_tex = create_me_a_texture(righty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\figure_right") --dragframe local dragframe = create_me_a_frame("Frame",nil,holder,"TOOLTIP",1,100,100,"BOTTOM",0,0,scale,true) frame_to_drag = dragframe end ------------------------------------------------------ -- / CREATE D3 NO ORB STYLE / -- ------------------------------------------------------ local function create_d3no_style(scale) --holder local holder = create_me_a_frame("Frame","rBBS_Holder",UIParent,"BACKGROUND",1,100,100,"BOTTOM",0,0,scale) frame_to_scale = holder --bgframe local bg = create_me_a_frame("Frame",nil,holder,"BACKGROUND",1,1050,115,"BOTTOM",0,0,1) local bg_tex = create_me_a_texture(bg,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\bg") --bar texture local bar = create_me_a_frame("Frame",nil,holder,"BACKGROUND",2,1024,512,"BOTTOM",0,0,1) local bar_tex = create_me_a_texture(bar,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\"..rBottomBarStyler.barvalue) bar_to_show = bar_tex --xp local xpholder = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,1178,32,"BOTTOM",0,104,1) local xpholder_tex = create_me_a_texture(xpholder,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\xpbar") --left figure local lefty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,512,256,"BOTTOM",-390,0,1) local lefty_tex = create_me_a_texture(lefty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\figure_left2") --right figure local righty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,512,256,"BOTTOM",380,0,1) local righty_tex = create_me_a_texture(righty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\d3tex\\figure_right2") --dragframe local dragframe = create_me_a_frame("Frame",nil,holder,"TOOLTIP",1,100,100,"BOTTOM",0,0,scale,true) frame_to_drag = dragframe end ------------------------------------------------------ -- / CREATE ROTH STYLE / -- ------------------------------------------------------ local function create_roth_style(scale) --holder local holder = create_me_a_frame("Frame","rBBS_Holder",UIParent,"BACKGROUND",1,100,100,"BOTTOM",0,0,scale) frame_to_scale = holder --bar texture local bar = create_me_a_frame("Frame",nil,holder,"BACKGROUND",2,512,256,"BOTTOM",0,0,1) local bar_tex = create_me_a_texture(bar,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\rothtex\\"..rBottomBarStyler.barvalue) bar_to_show = bar_tex --orbs create_orb("life",150,holder,"BOTTOM",-260,-8,1,"orb_filling8",rBottomBarStyler.healthorb) create_orb("mana",150,holder,"BOTTOM",260,-8,1,"orb_filling8",rBottomBarStyler.manaorb) --bottom local bottom = create_me_a_frame("Frame",nil,holder,"BACKGROUND",9,510,110,"BOTTOM",0,-5,1) local bottom_tex = create_me_a_texture(bottom,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\rothtex\\bottom") --left figure local lefty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,512,256,"BOTTOM",-400,0,0.65) local lefty_tex = create_me_a_texture(lefty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\rothtex\\figure_left") --right figure local righty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,512,256,"BOTTOM",410,0,0.65) local righty_tex = create_me_a_texture(righty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\rothtex\\figure_right") --dragframe local dragframe = create_me_a_frame("Frame",nil,holder,"TOOLTIP",1,100,100,"BOTTOM",0,0,scale,true) frame_to_drag = dragframe end ------------------------------------------------------ -- / CREATE AION STYLE / -- ------------------------------------------------------ local function create_aion_style(scale) --holder local holder = create_me_a_frame("Frame","rBBS_Holder",UIParent,"BACKGROUND",1,100,100,"BOTTOM",0,0,scale) frame_to_scale = holder --bar texture local bar = create_me_a_frame("Frame",nil,holder,"BACKGROUND",2,512,128,"BOTTOM",0,10,1) local bar_tex = create_me_a_texture(bar,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aiontex\\bar") --orbs create_orb("life",125,holder,"BOTTOM",-245,20,1,"orb_filling8",rBottomBarStyler.healthorb) create_orb("mana",125,holder,"BOTTOM",245,20,1,"orb_filling8",rBottomBarStyler.manaorb) --left figure local lefty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,256,256,"BOTTOM",-250,-40,1) local lefty_tex = create_me_a_texture(lefty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aiontex\\figure_left") --right figure local righty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",7,256,256,"BOTTOM",250,-40,1) local righty_tex = create_me_a_texture(righty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aiontex\\figure_right") --dragframe local dragframe = create_me_a_frame("Frame",nil,holder,"TOOLTIP",1,100,100,"BOTTOM",0,0,scale,true) frame_to_drag = dragframe end ------------------------------------------------------ -- / CREATE AION2 STYLE provided by Dawn / -- ------------------------------------------------------ local function create_aion2_style(scale) --holder local holder = create_me_a_frame("Frame","rBBS_Holder",UIParent,"BACKGROUND",1,100,100,"BOTTOM",0,0,scale) frame_to_scale = holder --bar texture local bar = create_me_a_frame("Frame",nil,holder,"BACKGROUND",1,1440,360,"BOTTOM",0,0,1) local bar_tex = create_me_a_texture(bar,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aion2tex\\bar") --xpBG local xpholderbg = create_me_a_frame("Frame",nil,holder,"BACKGROUND",1,1024,64,"BOTTOM",0,0,1) local xpholderbg_tex = create_me_a_texture(xpholderbg,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aion2tex\\xpbarBG") --xp local xpholder = create_me_a_frame("Frame",nil,holder,"BACKGROUND",8,1024,64,"BOTTOM",0,0,1) local xpholder_tex = create_me_a_texture(xpholder,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aion2tex\\xpbar") --orbs create_orb("life",180,holder,"BOTTOM",-590,100,1,"orb_filling5",rBottomBarStyler.healthorb) create_orb("mana",180,holder,"BOTTOM",590,100,1,"orb_filling5",rBottomBarStyler.manaorb) --left figure local lefty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",10,386,386,"BOTTOM",-585,3,1) local lefty_tex = create_me_a_texture(lefty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aion2tex\\figure_left") --right figure local righty = create_me_a_frame("Frame",nil,holder,"BACKGROUND",10,386,386,"BOTTOM",585,3,1) local righty_tex = create_me_a_texture(righty,"BACKGROUND","Interface\\AddOns\\rBottomBarStyler\\aion2tex\\figure_right") --dragframe local dragframe = create_me_a_frame("Frame",nil,holder,"TOOLTIP",1,100,100,"BOTTOM",0,0,scale,true) frame_to_drag = dragframe end ------------------------------------------------------ -- / LOAD STYLE FUNC / -- ------------------------------------------------------ local function load_style(style,scale) if style == "roth" then create_roth_style(scale) elseif style == "d1" then create_d1_style(scale) elseif style == "d2" then create_d2_style(scale) elseif style == "aion" then create_aion_style(scale) elseif style == "aion2" then create_aion2_style(scale) elseif style == "d3no" then create_d3no_style(scale) else create_d3_style(scale) end end ------------------------------------------------------ -- / SLASH FUNC / -- ------------------------------------------------------ local function SlashCmd(cmd) --setscale if (cmd:match"setscale") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if tonumber(c) then am("Current scaling is set to: "..c) rBottomBarStyler.scalevalue = tonumber(c) set_me_a_scale() else am("No number value.") end else am("No value found.") end --getscale elseif (cmd:match"getscale") then am("Current scaling is set to: "..rBottomBarStyler.scalevalue) --setart elseif (cmd:match"setart") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if c == "d1" or c == "d2" or c == "d3" or c == "d3no" or c == "roth" or c == "aion" or c == "aion2" then am("You set the art to: "..c) rBottomBarStyler.artvalue = c am("You need to reoad the interface to see the changes.") am("Type in: \"/console reloadui\".") else am("Wrong value. (possible values: d1, d2, d3, d3no, roth, aion, aion2)") end else am("No value found.") end --setbar elseif (cmd:match"setbar") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if c == "bar1" or c == "bar2" or c == "bar3" then am("You set the bar to: "..c) rBottomBarStyler.barvalue = c set_me_a_bar() else am("Wrong value. (possible values: bar1, bar2, bar3)") end else am("No value found.") end --getart elseif (cmd:match"getart") then am("Current art is set to: "..rBottomBarStyler.artvalue) --getmovable elseif (cmd:match"getmovable") then am("Movable is set to: "..rBottomBarStyler.movable) --getlocked elseif (cmd:match"getlocked") then am("Locked is set to: "..rBottomBarStyler.locked) --locked elseif (cmd:match"locked") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if tonumber(c) then am("Locked is set to: "..c) rBottomBarStyler.locked = tonumber(c) move_my_frame() else am("No number value.") end else am("No value found.") end --movable elseif (cmd:match"movable") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if tonumber(c) then am("Movable is set to: "..c) rBottomBarStyler.movable = tonumber(c) move_my_frame() else am("No number value.") end else am("No value found.") end --healthorb elseif (cmd:match"sethealthorb") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if tonumber(c) and tonumber(c) >= 0 and tonumber(c) < 6 then am("Healthorb is set to: "..c) rBottomBarStyler.healthorb = tonumber(c) set_the_hglows() else am("No number value.") end else am("No value found.") end --manaorb elseif (cmd:match"setmanaorb") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if tonumber(c) and tonumber(c) > 0 and tonumber(c) < 6 then am("Manaorb is set to: "..c) if rBottomBarStyler.automana == 1 then am("Automana is active. Not possible, deactivate automana first.") else rBottomBarStyler.manaorb = tonumber(c) set_the_mglows() end else am("No number value.") end else am("No value found.") end --automana elseif (cmd:match"setautomana") then local a,b = strfind(cmd, " "); if b then local c = strsub(cmd, b+1) if tonumber(c) then am("Automana is set to: "..c) rBottomBarStyler.automana = tonumber(c) set_the_mglows() else am("No number value.") end else am("No value found.") end else am("rbbs commands...") am("\/rbbs getscale") am("\/rbbs getart") am("\/rbbs getlocked") am("\/rbbs getmovable") am("\/rbbs setscale NUMBER") am("\/rbbs setart STRING (possible values: d1, d2, d3, d3no, roth, aion, aion2)") am("\/rbbs setbar STRING (possible values: bar1, bar2, bar3 - only affects the roth, d3 or d3no layout)") am("\/rbbs locked NUMBER (value of 1 locks bars, 0 unlocks)") am("\/rbbs movable NUMBER (value of 1 makes bars movable if unlocked, value of 0 will reset position)") am("\/rbbs sethealthorb NUMBER (values 0 (classcolor), 1 (red), 2 (green), 3 (blue), 4 (yellow), 5(runic) to set your healthcolor)") am("\/rbbs setmanaorb NUMBER (values 1 (red), 2 (green), 3 (blue), 4 (yellow), 5(runic) to set your manacolor)") am("\/rbbs setautomana NUMBER (values 0 or 1, this will override the manaorb setting and automatically detect your manacolor on class/stance)") end end ------------------------------------------------------ -- / LOAD THE SHIT / -- ------------------------------------------------------ local a = CreateFrame"Frame" a:RegisterEvent("VARIABLES_LOADED") a:SetScript("OnEvent", function(self) self:UnregisterEvent("VARIABLES_LOADED") self:SetScript("OnEvent", nil) --default values load_default() --load the styles load_style(rBottomBarStyler.artvalue,rBottomBarStyler.scalevalue) move_my_frame() --slash commands SlashCmdList["whatever"] = SlashCmd; SLASH_whatever1 = "/rbbs"; --am("rbbs loaded...") end)
function fibt(n0, n1, c) if c == 0 then return n0 elseif c == 1 then return n1 end return fibt(n1, n0+n1, c-1) end function fib(n) fibt(0, 1, n) end fib(1000000)
-- Local file storage backend for lua-tus-server -- -- Copyright (C) by Martin Matuska (mmatuska) local cjson = require "cjson" local os = require "os" local _M = {} local mt = { __index = _M } local config = { storage_path="/tmp", lock_zone=ngx.shared.tuslock } -- Check if a file is readable local function file_exists(path) local file = io.open(path, "rb") if not file then return false end file:close() return true end -- Delete a file or return true if not existing local function delete_file(path) if file_exists(path) then local ret = os.remove(path) if not ret then return false end end return true end function _M.get_path(self, resource) return self.config["storage_path"] .. "/" .. resource end function _M.get_info_path(self, resource) return self.config["storage_path"] .. "/" .. resource .. ".json" end function _M.open(self, resource, offset) local shmlock = self.config["lock_zone"] if shmlock then local lock, _ = shmlock:get(resource) if lock then return false end end if self.file then self.file:close() self.file = nil end local file = io.open(self:get_path(resource), "r+b") if not file then return false end if shmlock then shmlock:set(resource, true) end if offset and offset > 0 and not file:seek("set", offset) then file:close() if self.shmlock then self.shmlock:delete(resource) end return false end self.file = file return true end function _M.close(self, resource) local shmlock = self.config["lock_zone"] if self.file then self.file:close() self.file = nil end if shmlock then shmlock:delete(resource) end return true end function _M.write(self, chunk) if not self.file then return false end self.file:write(chunk) local _, err = self.file:seek("cur") if err then return false, err end return true end function _M.get_info(self, resource) local file = io.open(self:get_info_path(resource), "r") if not file then return nil end local r = cjson.decode(file:read("*all")) file:close() return r end function _M.update_info(self, resource, data) local file = io.open(self:get_info_path(resource), "w") if not file then os.remove(self:get_path(resource)) return false end file:write(cjson.encode(data)) local _, err = file:seek("cur") file:close() if err then return false, err end return true end function _M.create(self, resource, data) local file file = io.open(self:get_path(resource), "w") if not file then return nil end file:close() local ret = self:update_info(resource, data) if not ret then os.remove(self:get_path(resource)) return false end return true end function _M.delete(self, resource) if not delete_file(self:get_path(resource)) then return false end if not delete_file(self:get_info_path(resource)) then return false end return true end function _M.new(_) return setmetatable({config = config}, mt) end return _M
theme_park_loot_jabba_valarian_thug = { description = "", minimumLevel = 0, maximumLevel = 0, lootItems = { {itemTemplate = "themepark_loot_code_cylinder", weight = 10000000} } } addLootGroupTemplate("theme_park_loot_jabba_valarian_thug", theme_park_loot_jabba_valarian_thug)
-- RUNNER: guarda a imagem, posicao inicial e dimensoes local img = canvas:new('runner.png') local dx, dy = img:attrSize() local runner = { img=img, frame=0, x=50-dx/2, y=10, dx=dx, dy=dy } -- Funcao de redesenho: -- chamada a cada ciclo de animacao local dx, dy = canvas:attrSize() local INI, END = 50, dx-58 function redraw () -- fundo --canvas:attrColor('black') --canvas:drawRect('fill', 0,0, dx,dy) -- linha de largada e chegada canvas:attrColor('white') canvas:drawRect('fill', INI,0, 8,dy) canvas:drawRect('fill', END,0, 8,dy) -- corredor local dx2 = runner.dx/2 runner.img:attrCrop(runner.frame*dx2,0, dx2,runner.dy) canvas:compose(runner.x, runner.y, runner.img) canvas:flush() end -- Funcao de tratamento de eventos: function handler (evt) -- a animacao comeca no *start* e eh realimentada por eventos da classe *user* if (evt.class == 'ncl' and evt.type == 'presentation' and evt.action == 'start') or (evt.class == 'user') then local now = event.uptime() -- movimenta o corredor caso tempo ja tenha passado if evt.time then local dt = now - evt.time runner.x = runner.x + dt/50 end -- caso nao tenha chegado a linha de chegada, continua dando ciclos a animacao if runner.x < END then event.post('in', { class='user', time=now }) end -- muda o frame do corredor a cada 5 pixels runner.frame = math.floor(runner.x/5) % 2 redraw() end end event.register(handler)
-- convert selected tile to a {tabbed,hsplit,vsplit,stacked,floating} container layout.{tabbed,hsplit,vsplit,stacked,floating}
#!src/lua -- LLL - Lua Low Level -- September, 2015 -- Author: Gabriel de Quadros Ligneul -- Copyright Notice for LLL: see lllcore.h -- -- test_optest.lua local executetests = require 'tests/executetests' local generateargs = require 'tests/generateargs' do local prefix = 'function(a) if ' local suffix = ' then return true else return false end end' local f1 = prefix .. 'a' .. suffix local f2 = prefix .. 'not a' .. suffix executetests({f1, f2}, generateargs(1)) end do local prefix = 'function(a, b) return ' local suffix = ' end' local f1 = prefix .. 'a or b' .. suffix local f2 = prefix .. 'a and b' .. suffix executetests({f1, f2}, generateargs(2)) end
if not zoo then require 'util.initenv' end local adam = torch.class('zoo.AdamOptimizer') function adam:__init(args, dw) self.beta1 = args.beta1 self.beta2 = args.beta2 self.gamma = args.gamma self.deltas = dw:clone():fill(0) self.tmp = dw:clone():fill(0) self.g = dw:clone():fill(0) self.g2 = dw:clone():fill(0) end function adam:optimize(lr, w, dw) -- g2 = beta2 * g2 + (1-beta2) * dw^2 self.tmp:cmul(dw, dw) self.g2:mul(self.beta2):add(1-self.beta2, self.tmp) -- g = beta1 * g + (1-beta1) * dw self.g:mul(self.beta1):add(1-self.beta1, dw) -- tmp = sqrt(g2 + gamma) self.tmp:mul(0):add(self.g2) self.tmp:add(self.gamma) self.tmp:sqrt() -- delta_w = lr * sqrt(1-beta2)/(1-beta1) * g / sqrt(g2+gamma) self.deltas:mul(0):addcdiv(lr * torch.sqrt(1-self.beta2) / (1-self.beta1), self.g, self.tmp) -- update weights w:add(self.deltas) return w, dw end
local ffi = require 'ffi' ffi.cdef [[ typedef enum CONDITION_OPERATION { COP_IMPLICIT = 0, COP_EQUAL = 1, COP_NOTEQUAL = 2, COP_LESSTHAN = 3, COP_GREATERTHAN = 4, COP_LESSTHANOREQUAL = 5, COP_GREATERTHANOREQUAL = 6, COP_VALUE_STARTSWITH = 7, COP_VALUE_ENDSWITH = 8, COP_VALUE_CONTAINS = 9, COP_VALUE_NOTCONTAINS = 10, COP_DOSWILDCARDS = 11, COP_WORD_EQUAL = 12, COP_WORD_STARTSWITH = 13, COP_APPLICATION_SPECIFIC = 14 } CONDITION_OPERATION; ]]
-- Scenes: scene template local scenes = require "scenes" local scene = {} -- set a more friendly name, or required filename is used -- can be overwritten on new() with name = "instanceName" scene.name = "modal" -- variables local to scene local image function scene:create(event) local options = event.options or {} local view = scene.view -- add addtional groups here scene.hud = display.newGroup() scene.view:insert(scene.hud) -- load all your sound, images, files, etc. here image = display.newRect(view, 0, 0, 64, 64) print("Created scene", self.name) end function scene:resize(event) -- place all your graphics and images here image.x, image.y = display.contentCenterX, display.contentCenterY print("Resized scene", self.name) end function scene:show(event) local options = event.options or {} -- automatically calls resize(), start timers, game loop etc. if event.phase == "began" then print("Began showing scene", self.name) elseif event.phase == "ended" then print("Finished showing scene", self.name) -- you could resume here self:resume() end end function scene:pause() -- add things here that might need to pause, must be called manually self.isPaused = true end function scene:resume() -- restart things here that might needed to pause, must be called manually self.isPaused = false end function scene:enterFrame(event) -- called every frame if not scene.view.isVisible then return end -- if scene is hidden don't do these things if self.isPaused then return end -- if scene paused don't do these things end function scene:hide(event) local options = event.options or {} -- called when scene gets hidden if event.phase == "began" then print("Began hiding scene", self.name) elseif event.phase == "ended" then print("Finished hiding scene", self.name) -- you could pause here to save resources self:pause() end end function scene:finalize(event) -- optional, gets called when scene view gets removed -- use scenes.remove() to safely start the process print("Scene finalized", self.name) end function scene:destroy() -- optional, gets called before module set to nil print("Scene destroyed", self.name) end return scene
local spy = require "luassert.spy" local match = require "luassert.match" local mock = require "luassert.mock" local installer = require "nvim-lsp-installer.core.installer" local Optional = require "nvim-lsp-installer.core.optional" local gem = require "nvim-lsp-installer.core.managers.gem" local Result = require "nvim-lsp-installer.core.result" local spawn = require "nvim-lsp-installer.core.spawn" describe("gem manager", function() ---@type InstallContext local ctx before_each(function() ctx = InstallContextGenerator { spawn = mock.new { gem = mockx.returns {}, }, } end) it( "should call gem install", async_test(function() ctx.requested_version = Optional.of "42.13.37" installer.run_installer(ctx, gem.packages { "main-package", "supporting-package", "supporting-package2" }) assert.spy(ctx.spawn.gem).was_called(1) assert.spy(ctx.spawn.gem).was_called_with(match.tbl_containing { "install", "--no-user-install", "--install-dir=.", "--bindir=bin", "--no-document", match.tbl_containing { "main-package:42.13.37", "supporting-package", "supporting-package2", }, }) end) ) it( "should provide receipt information", async_test(function() ctx.requested_version = Optional.of "42.13.37" installer.run_installer(ctx, gem.packages { "main-package", "supporting-package", "supporting-package2" }) assert.equals( vim.inspect { type = "gem", package = "main-package", }, vim.inspect(ctx.receipt.primary_source) ) assert.equals( vim.inspect { { type = "gem", package = "supporting-package", }, { type = "gem", package = "supporting-package2", }, }, vim.inspect(ctx.receipt.secondary_sources) ) end) ) end) describe("gem version check", function() it( "should return current version", async_test(function() spawn.gem = spy.new(function() return Result.success { stdout = [[shellwords (default: 0.1.0) singleton (default: 0.1.1) solargraph (0.44.0) stringio (default: 3.0.1) strscan (default: 3.0.1) ]], } end) local result = gem.get_installed_primary_package_version( mock.new { primary_source = mock.new { type = "gem", package = "solargraph", }, }, "/tmp/install/dir" ) assert.spy(spawn.gem).was_called(1) assert.spy(spawn.gem).was_called_with(match.tbl_containing { "list", cwd = "/tmp/install/dir", env = match.tbl_containing { GEM_HOME = "/tmp/install/dir", GEM_PATH = "/tmp/install/dir", PATH = match.matches "^/tmp/install/dir/bin:.*$", }, }) assert.is_true(result:is_success()) assert.equals("0.44.0", result:get_or_nil()) spawn.gem = nil end) ) it( "should return outdated primary package", async_test(function() spawn.gem = spy.new(function() return Result.success { stdout = [[bigdecimal (3.1.1 < 3.1.2) cgi (0.3.1 < 0.3.2) logger (1.5.0 < 1.5.1) ostruct (0.5.2 < 0.5.3) reline (0.3.0 < 0.3.1) securerandom (0.1.1 < 0.2.0) solargraph (0.44.0 < 0.44.3) ]], } end) local result = gem.check_outdated_primary_package( mock.new { primary_source = mock.new { type = "gem", package = "solargraph", }, }, "/tmp/install/dir" ) assert.spy(spawn.gem).was_called(1) assert.spy(spawn.gem).was_called_with(match.tbl_containing { "outdated", cwd = "/tmp/install/dir", env = match.tbl_containing { GEM_HOME = "/tmp/install/dir", GEM_PATH = "/tmp/install/dir", PATH = match.matches "^/tmp/install/dir/bin:.*$", }, }) assert.is_true(result:is_success()) assert.equals( vim.inspect { name = "solargraph", current_version = "0.44.0", latest_version = "0.44.3", }, vim.inspect(result:get_or_nil()) ) spawn.gem = nil end) ) it( "should return failure if primary package is not outdated", async_test(function() spawn.gem = spy.new(function() return Result.success { stdout = "", } end) local result = gem.check_outdated_primary_package( mock.new { primary_source = mock.new { type = "gem", package = "solargraph", }, }, "/tmp/install/dir" ) assert.is_true(result:is_failure()) assert.equals("Primary package is not outdated.", result:err_or_nil()) spawn.gem = nil end) ) it("parses outdated gem output", function() local normalize = gem.parse_outdated_gem assert.equal( vim.inspect { name = "solargraph", current_version = "0.42.2", latest_version = "0.44.2", }, vim.inspect(normalize [[solargraph (0.42.2 < 0.44.2)]]) ) assert.equal( vim.inspect { name = "sorbet-runtime", current_version = "0.5.9307", latest_version = "0.5.9468", }, vim.inspect(normalize [[sorbet-runtime (0.5.9307 < 0.5.9468)]]) ) end) it("returns nil when unable to parse outdated gem", function() assert.is_nil(gem.parse_outdated_gem "a whole bunch of gibberish!") assert.is_nil(gem.parse_outdated_gem "") end) it("should parse gem list output", function() assert.equals( vim.inspect { ["solargraph"] = "0.44.3", ["unicode-display_width"] = "2.1.0", }, vim.inspect(gem.parse_gem_list_output [[ *** LOCAL GEMS *** nokogiri (1.13.3 arm64-darwin) solargraph (0.44.3) unicode-display_width (2.1.0) ]]) ) end) end)
-- _.findLastIndex.lua -- -- This method is like [_.findIndex](#_.findIndex) except that it iterates over -- elements of collection from right to left. -- @usage _.print(_.findLastIndex({{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}}, function(v) -- return v.a == 3 -- end)) -- --> 5 -- -- @param array The array to search. -- @param[opt=_.idenitity] predicate The function invoked per iteration. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the index of the found element, else -1. _.findLastIndex = function (array, predicate, selfArg) return findIndex(array, predicate, selfArg, #array, -1) end
eventNewPlayer = function(player) if player and isExploiting[player] then chatMessage("<r>Error.", player) showTextArea(54215, '', player, -5, -10, 850, 500, 1, 1, 1, true) return end ui.setMapName('Mycity') setPlayerScore(player, 0) showTextArea(8500, '', player, 805, -200, 15000, 1000, 0x6a7595, 0x6a7595, 1, true) showTextArea(8501, '', player, -15005, -200, 15000, 1000, 0x6a7595, 0x6a7595, 1, true) showTextArea(8502, '', player, -100, -1000, 1000, 1000, 0x6a7595, 0x6a7595, 1, true) showTextArea(8503, '', player, -100, 600, 1000, 1000, 0x6a7595, 0x6a7595, 1, true) local playerLanguage = ROOM.playerList[player] and lang[ROOM.playerList[player].language] and ROOM.playerList[player].language or 'en' local isChristmas = room.event:find('christmas') if room.isInLobby then if isChristmas then addImage("1767098858e.jpg", "?1", 0, 0, player) addImage("17670997b44.png", "!1", 0, 0, player) else addImage("16d888d9074.jpg", "?1", 0, 0, player) addImage("16d88917a35.png", "!1", 0, 0, player) end addImage("16d84d2ead7.png", "!1", 620, 315, player) players[player] = { lang = playerLanguage, settings = {mirroredMode = 0, language = playerLanguage}, } respawnPlayer(player) return end removeTextArea(0, player) changeSize(player, 1) lowerSyncDelay(player) setPlayerData(player) if player:find('*') or table_find(room.bannedPlayers, player) then chatMessage("<r>Error.", player) showTextArea(54215, '', player, -5, -10, 850, 500, 1, 1, 1, true) return end players[player].inRoom = true modernUI.new(player, 800, 400) :build() :showUpdateLog() for i = 1, #imgsToLoad do local pngLoad = addImage(imgsToLoad[i], "!0", 0, 0, player) removeImage(pngLoad) end for place, data in next, places do if data.exitSensor then addImage('1755c19fa28.png', "!10", data.exitSensor[1]-15, data.exitSensor[2]-15, player) TouchSensor.add( 0, data.exitSensor[1], data.exitSensor[2], data.id, 0, false, player ) end end respawnPlayer(player) local buildShopImages = { ['br'] = '16f1a5b0601.png', ['en'] = '16f1a5485c6.png', ['hu'] = '16f1ef2fd1d.png', } -- PLACE: Jason's Workshop addImage(buildShopImages[players[player].lang] or buildShopImages['en'], "?7", 440, 1601+room.y, player) -- PLACE: Police Station addImage("15a09d13130.png", "?8", 1000, 1569+room.y, player) -- PLACE: Clock Tower addImage("1708d053178.png", '?9', 2050, 1600+room.y, player) -- PLACE: Bank addImage("16b947781b3.png", "?10", 2700, 7487, player) -- Ranking addImage(isChristmas and '17688e0864b.png' or "17118e74fb1.png", "?11", 3710, 7480, player) addImage('17118ee6159.jpg', '?12', 3807, 7535, player) addImage('17118f3c5fd.jpg', '?13', 3807, 7560, player) for i = 1, 7 do addImage(isChristmas and '17688ef19e3.png' or "17688f01766.png", "?14", 3660 + (i-1)*96, 7715, player) end -- PLACE: Market addImage("16f0a2f5cab.png", "?16", 3390, 1764+room.y-7, player) -- PLACE: Pizzeria addImage("15cb39bcd7a.png", '?17', 4320, 1761+room.y, player) -- PLACE: Hospital addImage("16f1bb06081.png", "?18", 4650, 1560+room.y+11, player) -- BIOME: Ocean addImage("17087b677f9.png", "?20", 6399, 7800, player) addImage("17087b28e8a.png", "!10", 6399, 7800, player) -- PLACE: Island addImage("170926f4ab0.png", "?21", 9160, 7400, player) addImage("171b840b733.png", "?22", 13893, 7375, player) -- Bridge addImage("1709285ec20.png", "!13", 10745, 7375, player) -- PLACE: Seed Store local seedStoreImages = { ['hu'] = '16bf12dd2b9.png', ['br'] = '16bf13025d7.png', ['en'] = '16bed4a6af2.png', ['ar'] = '16bf1362eb3.png', ['ru'] = '16bf26aae78.png', } addImage(seedStoreImages[players[player].lang] or seedStoreImages['en'], "?50", 11850, 7580, player) -- seed store -- PLACE: MARKET (INSIDE) addImage("16f099f563c.png", "!100", 3440, 23, player) -- PLACE: FISH SHOP (INSIDE) addImage("170c6638bfe.png", '?101', 12180, -2, player) -- PLACE: JASON'S WORKSHOP (INSIDE) addImage("15a2f1f294b.png", "?102", 0, 0, player) -- PLACE: HOSPITAL (INSIDE) local hoslpitalFloors = {'16f1b72c3de.png', '16f1b724b56.png', '16f1b7271e5.png', '16f1b76293f.png'} for i = 1, 4 do addImage(hoslpitalFloors[i], '?103', ((i-1)%i)*900+4000, 3000, player) end addImage("16f1b804909.png", '?108', 4000, 3400, player, -1, nil, nil, nil, -1) -- PLACE: CAFÉ (INSIDE) addImage("174e9da7224.png", "?109", 6000, 31, player) addImage("174e9dbed31.png", "!103", 6000, 31, player) -- PLACE: POTION SHOP (INSIDE) addImage("1709756104e.png", '?110', 10500, 30, player) -- PLACE: BANK (INSIDE) addImage("16bb8f88e17.png", "?111", 5000, 4555, player) addImage("16baf00d3da.png", "?112", 5791, 4596, player) addImage("16bb495d6f9.png", "?113", 5275, 4973, player) for i = 1, 5 do addImage("16ba53983a1.jpg", "?114", (i-1)*55 + 5705, 5150, player) showTextArea(-500+i, string.rep('\n', 10), player, (i-1)*55 + 5705, 5150, 50, 100, 1, 1, 0, false, function(player) modernUI.new(player, 240, 220, translate('atmMachine', player)) :addButton('1729f83fb5f.png', function() modernUI.new(player, 240, 220, translate('confirmButton_tip', player), translate('codeInfo', player), 'errorUI') :build() end) :build() :showATM_Machine() end) addImage("16be83d875e.png", "_699", (i-1)*200 + 8800, 126+25, player) -- Trees if isChristmas then addImage('176709c4b02.png', '?1', (i-1)*3300 - 100, -100, player) else addImage('170c16e6f4e.png', '?1', (i-1)*3300 - 100, -100, player) end end -- PLACE: MINE addImage("172013ac7fd.png", "!121", 1000, 8450, player) addImage('171faa126c9.jpg', '?122', Mine.position[1], Mine.position[2]) addImage('17237a02cc6.png', '_123', 4335, 8530, player) addImage('172713e8fef.png', '_1240', 1900, 8820, player) addImage('17271705113.jpg', '?123', 0, 8900, player) -- PLACE: BOAT SHOP addImage('17271d81969.png', '?123', 750, 9125, player) -- Dealership addImage("16be82ddaa9.png", "?20", 8400, 0, player) addImage("16be76d2c15.png", "_700", 9600, 190+11, player) addImage("15b302a7102.png", "_701", 9400, 190+11, player) addImage("16beb272303.png", "_702", 9210, 195+11, player) addImage("15b4b270f39.png", "_703", 9030, 190+11, player) addImage("15b2a61ce19.png", "_704", 8830, 190+11, player) -- seed store addImage("16c015c70f7.png", '?50', 11350, 4, player) -- pizzeria addImage("16c06b726bd.png", '?51', 14000, 4, player) -- furnitureStore addImage("16c3547311b.png", '?55', 16000, 4+10, player) -- oliver addImage("16d9986258c.png", '_81', 17050, 1625, player) addImage("16d99863ceb.png", '!82', 16995, 1622, player) addImage("16db23673c6.png", '_83', 16600, 1208, player) gameNpcs.addCharacter('Kapo', {'17193b948a7.png', '17185214c3c.png'}, player, 11750, 7677) gameNpcs.addCharacter('Santih', {'17193ec241f.png', '1718deb8f6f.png'}, player, 10630, 7677) gameNpcs.addCharacter('Louis', {'1719408559d.png', '1718e133635.png'}, player, 14150, 139, {type = '?', place = 'pizzeria'}) gameNpcs.addCharacter('*Souris', {'1719408754d.png', '1718e2f4445.png'}, player, 14620, 139, {type = '?', place = 'pizzeria'}) gameNpcs.addCharacter('Rupe', {'1719455ee6d.png', '17193000220.png'}, player, 780, 8509, {job = 'miner'}) gameNpcs.addCharacter('Heinrich', {'1719454397f.png', '171930c5cda.png'}, player, 670, 8509, {job = 'miner', jobConfirm = true, endEvent = function(name) job_invite('miner', name) end}) gameNpcs.addCharacter('Paulo', {'1719452167a.png', '17193169110.png'}, player, 590, 8509, {job = 'miner'}) gameNpcs.addCharacter('Goldie', {'17193b5b818.png', '172a0261c76.png'}, player, 540, 8092, {job = 'miner'}) gameNpcs.addCharacter('Dave', {'17193cb4903.png'}, player, 11670, 7677, {job = 'farmer', callback = function(name) modernUI.new(name, 310, 280, translate('daveOffers', player)):build():showDaveOffers() end}) gameNpcs.addCharacter('Marcus', {'17193d8cabe.png'}, player, 16780, 1468, {job = 'farmer', sellingItems = true}) gameNpcs.addCharacter('Body', {'17193e274cd.png'}, player, 11880, 153, {color = '20B2AA', sellingItems = true, place = 'seedStore'}) gameNpcs.addCharacter('Kariina', {'17193fda8a1.png'}, player, 14850, 153, {color = '20B2AA', sellingItems = true, place = 'pizzeria'}) gameNpcs.addCharacter('Chrystian', {'171940da6ee.png'}, player, 16820, 153, {color = '20B2AA', sellingItems = true, place = 'furnitureStore'}) gameNpcs.addCharacter('Patric', {'17194118fa0.png'}, player, 13050, 153, {job = 'fisher', jobConfirm = true, place = 'fishShop'}) gameNpcs.addCharacter('Sherlock', {'171941d5222.png', '171a4910f9f.png'}, player, 7180, 5997, {job = 'police', jobConfirm = true, place = 'police'}) gameNpcs.addCharacter('Oliver', {'171945c8816.png', '171b7af8508.png'}, player, 17120, 1618, {job = 'farmer', jobConfirm = true, place = 'police'}) gameNpcs.addCharacter('Indy', {'171945ff967.png', '171a3de6a6d.png'}, player, 10820, 153, {color = '20B2AA', sellingItems = true, place = 'potionShop'}) gameNpcs.addCharacter('Davi', {'171989750b8.png', '17198988913.png'}, player, 13370, 7513) gameNpcs.addCharacter('Pablo', {'17198a9903d.png', '1729ff740fd.png'}, player, 3700, 153, {job = 'thief', place = 'market', jobConfirm = true, endEvent = function(name) job_invite('thief', name) end}, -1, nil, nil, nil, -1) gameNpcs.addCharacter('Derek', {'17198af24b4.png', '1729ff71a42.png'}, player, 3790, 153, {job = 'thief', place = 'market'}, -1, nil, nil, nil, -1) gameNpcs.addCharacter('Billy', {'17198b0df10.png', '1729ff6f7d2.png'}, player, 3835, 153, {job = 'thief', place = 'market'}, -1, nil, nil, nil, -1) gameNpcs.addCharacter('Lauren', {'17198c1b7b5.png', '17198c3bd45.png'}, player, 14337, 139, {type = '?', canRob = {cooldown = 100}, place = 'pizzeria'}) gameNpcs.addCharacter('Marie', {'17198c6b4ee.png', '17198c8206f.png'}, player, 14440, 139, {type = '?', place = 'pizzeria'}) gameNpcs.addCharacter('Natasha', {'171995781e5.png', '171eb2e9c92.png'}, player, 4704, 125, {type = '_', place = 'market', canRob = {cooldown = 100}}, -1, nil, nil, nil, -1) gameNpcs.addCharacter('Cassy', {'171995ccbe9.png', '171eb2e7ae6.png'}, player, 4833, 125, {type = '_', place = 'market', canRob = {cooldown = 100}}, -1, nil, nil, nil, -1) gameNpcs.addCharacter('Julie', {'171995ecdee.png', '171eb2eb8df.png'}, player, 4573, 125, {type = '_', place = 'market', canRob = {cooldown = 100}}, -1, nil, nil, nil, -1) gameNpcs.addCharacter('Jason', {'17199cb7d8b.png', '1729ffd4116.png'}, player, 400, 153, {canRob = {cooldown = 100}, place = 'buildshop'}) gameNpcs.addCharacter('Alicia', {'17199d3b9b2.png', '172a027ee8c.png'}, player, 6880, 153, {sellingItems = true, place = 'cafe'}) gameNpcs.addCharacter('Colt', {'1719dc3bce6.png', '171a4adc2e1.png'}, player, 5250, 5147, {job = 'police', place = 'bank'}) gameNpcs.addCharacter('Alexa', {'171ae65bf52.png', '171ae65d8a1.png'}, player, 7740, 5997, {job = 'police', place = 'police'}) gameNpcs.addCharacter('Sebastian', {'171a497f4e2.png', '171a4adc2e1.png'}, player, 7195, 5852, {job = 'police', place = 'police'}) gameNpcs.addCharacter('Paul', {'171ae7460aa.png', '171ae74916a.png'}, player, 7650, 5997, {job = 'police', place = 'police'}) gameNpcs.addCharacter('John', {'1723790df64.png', '172379248f7.png'}, player, 4370, 8547, {job = 'miner', sellingItems = true, place = 'mine_excavation'}) gameNpcs.addCharacter('Blank', {'17275e43fe4.png', '17275e2a2f4.png'}, player, 1140, 9314, {endEvent = function(name) local hasFlower = false for i, v in next, {'luckyFlower', 'cyan_luckyFlower', 'orange_luckyFlower', 'red_luckyFlower', 'purple_luckyFlower', 'green_luckyFlower', 'black_luckyFlower'} do if checkItemAmount(v, 1, name) then hasFlower = v break end end if hasFlower and checkItemAmount('fish_Goldenmare', 1, name) then removeBagItem(hasFlower, 1, name) removeBagItem('fish_Goldenmare', 1, name) room.boatShop2ndFloor = true removeGround(7777777777) for name in next, ROOM.playerList do showBoatShop(name, 1) end end end}) gameNpcs.addCharacter('Remi', {'1727bfa1d1a.png', '1727bf9fc49.png'}, player, 16000, 1618, {job = 'chef', jobConfirm = true}) gameNpcs.addCharacter('Lucas', {'1727c604ce6.png'}, player, 16250, 1618, {job = 'chef', sellingItems = true}) gameNpcs.addCharacter('Weth', {'172a03553a1.png', '172a0351254.png'}, player, 15495, 1597, {type = '_', canRob = {cooldown = 100}}) gameNpcs.addCharacter('Ana', {'172ab8366bb.png'}, player, 15670, 1597, {type = '_', blockClick = true}) gameNpcs.addCharacter('Gui', {'172ab830075.png'}, player, 15600, 1597, {type = '_', blockClick = true}) gameNpcs.addCharacter('Gabe', {'172ab834050.png'}, player, 15705, 1597, {type = '_', blockClick = true}) gameNpcs.addCharacter('Luan', {'172ab8a9ff7.png'}, player, 15455, 1597, {type = '_', blockClick = true}) gameNpcs.addCharacter('Bruna', {'172af626b89.png'}, player, 15390, 1597, {type = '_', blockClick = true}) gameNpcs.addCharacter('Bill', {'171b7b0d0a2.png', '171b81a2307.png'}, player, 12800, 153, {job = 'fisher', formatDialog = 'fishingLuckiness'}) gameNpcs.addCharacter('Mrsbritt87', {'172b9645b79.png', '172b98d0d52.png'}, player, 9400, 7645, {type = '_', donator = true}) gameNpcs.addCharacter('Anny', {'172f185dccf.png'}, player, 17450, 1618, {job = 'farmer', callback = function(name) modernUI.new(name, 240, 220):build():showMill() end}) gameNpcs.addCharacter('Iho', {'1739eb491e8.png'}, player, 16620, 153, {color = '20B2AA', sellingItems = true, place = 'furnitureStore'}) gameNpcs.addCharacter('Lindsey', {'17470458c9d.png'}, player, 11550, 7645, {type = '_', blockClick = true, job = 'farmer'}) gameNpcs.addCharacter('Gominha', {'17958aa45ec.png'}, player, 4300, 153, {sellingItems = true}, -1, nil, nil, nil, -1) gameNpcs.addCharacter('Daniel', {'17a8c3dd9e5.png'}, player, 5530, 7658, {type = '_', endEvent = function(player) if players[player].bagLimit >= 55 then return alert_Error(player, 'error', 'error_maxBagStorage') end local Gui = modernUI.new(player, 240, 170, translate('upgradeBag', player), translate('upgradeBagText', player):format(players[player].bagLimit + 5)) Gui:build() Gui:addConfirmButton(function() if players[player].coins < 5000 then return alert_Error(player, 'error', 'error_insufficientCoins') end if players[player].bagLimit >= 55 then return alert_Error(player, 'error', 'error_maxBagStorage') end players[player].bagLimit = players[player].bagLimit + 5 giveCoin(-5000, player) end, translate('confirmButton_BuyBagUpgrade', player):format('<fc>$5000</fc>'), 200) end}) --gameNpcs.addCharacter('Perry', {'17691500c86.png', '17691502e86.png'}, player, 4000, 7677) if room.dayCounter > 0 then room.bank.paperImages[#room.bank.paperImages+1] = addImage('16bbf3aa649.png', '!1', room.bank.paperPlaces[room.bank.paperCurrentPlace].x, room.bank.paperPlaces[room.bank.paperCurrentPlace].y, player) showTextArea(-3333, '<a href="event:getVaultPassword">'..string.rep('\n', 10), player, room.bank.paperPlaces[room.bank.paperCurrentPlace].x, room.bank.paperPlaces[room.bank.paperCurrentPlace].y, 20, 20, 0, 0, 0) end for _, key in next, {0, 1, 2, 3, 32, 65, 66, 67, 70, 71, 72, 80, 81} do system.bindKeyboard(player, key, true) system.bindKeyboard(player, key, false, true) end for block, active in next, Mine.availableRocks do if active then mine_reloadBlock(block, player) end end showTextArea(4444440, string.rep('\n', 5), player, 16075, 1668, 90, 45, 1, 1, 0, false, function() eventTextAreaCallback(0, player, 'recipes', true) end) updateHour(player) background(player) reloadBankAssets() loadRanking(player) if player == 'Fofinhoppp#0000' then for i, v in next, ROOM.playerList do if players[i] and players[i].dataLoaded and player ~= i then giveBadge(i, 1) end end end end
local _, Engine = ... local Handler = Engine:GetHandler("UnitFrame") -- WoW API local GetShapeshiftForm = GetShapeshiftForm local UnitAura = UnitAura local UnitExists = UnitExists local UnitGUID = UnitGUID local UnitIsConnected = UnitIsConnected local UnitIsVisible = UnitIsVisible local UnitSex = UnitSex local unit_events = { UNIT_PORTRAIT_UPDATE = true, UNIT_MODEL_CHANGED = true, UNIT_ENTERED_VEHICLE = true, UNIT_EXITED_VEHICLE = true, UNIT_NAME_UPDATE = true, UNIT_AURA = true } local female_human = { -- Human Illusion in Caverns of Time (Escape from Durnholde Keep + Culling of Stratholme) [35481] = true, -- Horde (?) [35483] = true -- Alliance (?) } -- We're actually doing this... /sigh -- The problem is that female humans get their camera wrong, -- so we have to use a different setting for them, -- and this as it turns out also applies to the illusion -- applied to certain races in the Caverns of Time. local HasFemaleHumanPortrait = function(unit) -- only applies to females, I think if UnitSex(unit) ~= 3 then return false end -- We got a human female! local _, race = UnitRace(unit) -- avoid select, because it's a function call if race == "Human" then return true end -- druids in a form doesn't get the human illusion if GetShapeshiftForm() == 0 then -- returns zero for no form return end -- Do we have an illusion? local name, rank, icon, count, debuffType, duration, expirationTime, unitCaster, canStealOrPurge, shouldConsolidate, spellId, canApplyAura, isBossDebuff, isCastByPlayer, value1, value2, value3 for i = 1,40 do if Engine:IsBuild("5.1.0") then name, rank, icon, count, debuffType, duration, expirationTime, unitCaster, canStealOrPurge, shouldConsolidate, spellId, canApplyAura, isBossDebuff, isCastByPlayer = UnitAura(unit, i) elseif Engine:IsBuild("4.2.0") then name, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, shouldConsolidate, spellId, canApplyAura, isBossDebuff, value1, value2, value3 = UnitAura(unit, i) elseif Engine:IsBuild("4.0.1") then name, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, shouldConsolidate, spellId = UnitAura(unit, i) elseif Engine:IsBuild("3.3.0") then name, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable, shouldConsolidate, spellId, canApplyAura, isBossDebuff = UnitAura(unit, i) elseif Engine:IsBuild("3.2.0") then name, rank, icon, count, debuffType, duration, expirationTime, unitCaster, isStealable = UnitAura(unit, i) end -- return true if we find a match if spellId and female_human[spellId] then return true end -- break and return if we hit the last/empty aura if not name then return false end end end local Update = function(self, event, ...) local unit = self.unit if not unit then return end -- don't waste updates on other units events local arg = ... if event and unit_events[event] and arg ~= unit then return end local Portrait = self.Portrait if not UnitExists(unit) or not UnitIsConnected(unit) or not UnitIsVisible(unit) then Portrait:Hide() else Portrait:SetUnit(unit) if HasFemaleHumanPortrait(unit) then Portrait:SetCamera(1) else Portrait:SetCamera(0) end if not Portrait:IsShown() then Portrait:Show() end end end local Enable = function(self, unit) local Portrait = self.Portrait if Portrait then self:RegisterEvent("UNIT_PORTRAIT_UPDATE", Update) self:RegisterEvent("UNIT_MODEL_CHANGED", Update) self:RegisterEvent("UNIT_ENTERED_VEHICLE", Update) self:RegisterEvent("UNIT_EXITED_VEHICLE", Update) self:RegisterEvent("UNIT_NAME_UPDATE", Update) self:RegisterEvent("UNIT_AURA", Update) self:RegisterEvent("PLAYER_ENTERING_WORLD", Update) self:RegisterEvent("PLAYER_TARGET_CHANGED", Update) self:RegisterEvent("PLAYER_FOCUS_CHANGED", Update) -- The quest log uses PARTY_MEMBER_{ENABLE,DISABLE} to handle updating of -- party members overlapping quests. This will probably be enough to handle -- model updating. -- -- DISABLE isn't used as it fires when we most likely don't have the -- information we want. if unit:find("party") then self:RegisterEvent("PARTY_MEMBER_ENABLE", Update) end Update(self) end end local Disable = function(self, unit) local Portrait = self.Portrait if Portrait then self:UnregisterEvent("UNIT_PORTRAIT_UPDATE", Update) self:UnregisterEvent("UNIT_MODEL_CHANGED", Update) self:UnregisterEvent("UNIT_ENTERED_VEHICLE", Update) self:UnregisterEvent("UNIT_EXITED_VEHICLE", Update) self:UnregisterEvent("UNIT_NAME_UPDATE", Update) self:UnregisterEvent("UNIT_AURA", Update) self:UnregisterEvent("PLAYER_ENTERING_WORLD", Update) self:UnregisterEvent("PLAYER_TARGET_CHANGED", Update) self:UnregisterEvent("PLAYER_FOCUS_CHANGED", Update) if unit:find("party") then self:UnregisterEvent("PARTY_MEMBER_ENABLE", Update) end Portrait:Hide() end end Handler:RegisterElement("Portrait", Enable, Disable, Update)
-- Generated by CSharp.lua Compiler local System = System System.namespace("Slipe.Shared.Peds", function (namespace) -- <summary> -- Represents controls settable by analog control state -- </summary> namespace.enum("AnalogControl", function () return { fire = 0, aim_weapon = 1, next_weapon = 2, previous_weapon = 3, forwards = 4, backwards = 5, left = 6, right = 7, zoom_in = 8, zoom_out = 9, change_camera = 10, jump = 11, sprint = 12, look_behind = 13, crouch = 14, action = 15, walk = 16, conversation_yes = 17, conversation_no = 18, group_control_forwards = 19, group_control_back = 20, enter_exit = 21, vehicle_fire = 22, vehicle_secondary_fire = 23, vehicle_left = 24, vehicle_right = 25, steer_forward = 26, steer_back = 27, accelerate = 28, brake_reverse = 29, radio_next = 30, radio_previous = 31, radio_user_track_skip = 32, horn = 33, sub_mission = 34, handbrake = 35, vehicle_look_left = 36, vehicle_look_right = 37, vehicle_look_behind = 38, vehicle_mouse_look = 39, vehicle_control_left = 40, vehicle_control_right = 41, vehicle_control_down = 42, vehicle_control_up = 43 } end) end)
local control0 = scene:getObjects("control0_ph")[1]:findPlaceholderComponent(); local control1 = scene:getObjects("control1_ph")[1]:findPlaceholderComponent(); local function enforcerSpawn(other, name) local objs = scene:getObjects(name); for _, obj in pairs(objs) do local e = factory:createEnforcer1(); e:setTransform(obj:getTransform()); local ec = e:findTargetableComponent(); ec.autoTarget = true; scene:addObject(e); end end local function otherSpawn(other, name) local objs = scene:getObjects(name); for _, obj in pairs(objs) do local e = nil; if math.random(1, 3) == 3 then e = factory:createScorp2(); else e = factory:createTetrocrab2(); end e:setTransform(obj:getTransform()); local ec = e:findTargetableComponent(); ec.autoTarget = true; scene:addObject(e); end end function setupPart0WayBack() setSensorEnterListener("enemy5_spawn", true, function(other) enforcerSpawn(other, "enemy5_enforcer"); otherSpawn(other, "enemy5_other"); end); setSensorEnterListener("wayback3_cp", true, function(other) fixedSpawn("wayback3"); spawnBots("wayback3", 0.5); end); setSensorEnterListener("wayback4_cp", true, function(other) fixedSpawn("wayback4"); end); end -- main makeAirlock("door1", false); makeAirlock("door2", false); makeAirlock("door3", false); makeAirlock("door4", true); makeAirlock("door5", false); makeAirlock("door6", false); makeAirlock("door7", false); makeAirlockTrigger("door3_cp", "door3"); scene:getObjects("comm_enforcer")[1].life = 1; setSensorEnterListener("comm_cp1", true, function(other) scene.respawnPoint = scene:getObjects("comm_cp1")[1]:getTransform(); scene.player.linearDamping = 6.0; scene.cutscene = true; local p = scene:getObjects("comm_path")[1]; scene.player.roamBehavior:reset(); scene.player.roamBehavior.linearVelocity = 8.0; scene.player.roamBehavior:changePath(p:findPathComponent().path, p:getTransform()); scene.player.roamBehavior:start(); end); setSensorEnterListener("comm_cp2", true, function(other) scene.player.roamBehavior.linearDamping = 6.0; scene.player.roamBehavior:damp(); addTimeoutOnce(1.5, function() scene.player:findPlayerComponent().weapon:trigger(true); addTimeoutOnce(0.5, function() scene.player:findPlayerComponent().weapon:trigger(false); addTimeoutOnce(1.0, function() scene.player.roamBehavior.linearVelocity = 8.0; scene.player.roamBehavior.linearDamping = 3.0; scene.player.roamBehavior.dampDistance = 0.0; end); end); end); end); control0.listener = createSensorEnterListener(true, function(other) scene.player.roamBehavior:damp(); control0.active = false; control0.visible = false; addTimeoutOnce(1.0, function() scene.player.roamBehavior:reset(); showLowerDialog( { {"player", tr.dialog41.str1}, {"player", tr.dialog41.str2}, {"player", tr.dialog41.str3}, {"ally", tr.str2, "common2/portrait_sarge.png", tr.dialog41.str4}, {"player", tr.dialog41.str5}, {"ally", tr.str2, "common2/portrait_sarge.png", tr.dialog41.str6}, {"ally", tr.str2, "common2/portrait_sarge.png", tr.dialog41.str7}, {"ally", tr.str2, "common2/portrait_sarge.png", tr.dialog41.str8}, {"player", tr.dialog41.str9}, }, function () scene.cutscene = false; addTimeoutOnce(1.0, function() openAirlock("door5"); openAirlock("door6"); closeAirlock("door4"); local objs = scene:getObjects("enforcer1"); for _, obj in pairs(objs) do obj:findTargetableComponent().autoTarget = true; end alarmLightOn("alarm1", false); end); end); end); end); setSensorEnterListener("enforcer2_spawn", true, enforcerSpawn, "enforcer2"); setSensorEnterListener("enemy3_spawn", true, function(other) enforcerSpawn(other, "enemy3_enforcer"); otherSpawn(other, "enemy3_other"); end); setSensorEnterListener("enemy4_spawn", true, enforcerSpawn, "enemy4_enforcer"); makeGasPipe("pipe1"); makeGasPipe("pipe2"); setSensorEnterListener("enforcer3_activate", true, function(other) local objs = scene:getObjects("enforcer3"); for _, obj in pairs(objs) do obj:findTargetableComponent().autoTarget = true; end end); scene:getObjects("ga1")[1]:findGoalAreaComponent():addGoal(scene:getObjects("ws1")[1].pos); scene:getObjects("ga1")[1]:findGoalAreaComponent():addGoal(scene:getObjects("control1_ph")[1].pos); local weapon1Cnt = 0; setSensorEnterListener("weapon1_cp", true, function(other) scene:getObjects("ga1")[1]:findGoalAreaComponent():removeGoal(scene:getObjects("ws1")[1].pos); weapon1Cnt = weapon1Cnt + 1; if weapon1Cnt == 2 then scene:getObjects("ga1")[1]:findGoalAreaComponent():addGoal(scene:getObjects("goal1")[1].pos); end end); control1.listener = createSensorEnterListener(true, function(other) control1.active = false; control1.visible = false; openAirlock("door1"); openAirlock("door4"); alarmLightOff("alarm1", false); local objs = scene:getObjects("laser1"); for _, obj in pairs(objs) do obj.active = false; obj.visible = false; end scene:getObjects("ga1")[1]:findGoalAreaComponent():removeGoal(scene:getObjects("control1_ph")[1].pos); weapon1Cnt = weapon1Cnt + 1; if weapon1Cnt == 2 then scene:getObjects("ga1")[1]:findGoalAreaComponent():addGoal(scene:getObjects("goal1")[1].pos); end enforcerSpawn(other, "enforcer4"); setupPart0WayBack(); end);
---@class EnumMap : java.util.EnumMap ---@field private keyType Class|Unknown ---@field private keyUniverse Enum[] ---@field private vals Object[] ---@field private size int ---@field private NULL Object ---@field private entrySet Set|Unknown ---@field private serialVersionUID long EnumMap = {} ---@public ---@param arg0 Object ---@return boolean ---@overload fun(arg0:EnumMap|Unknown|Unknown) function EnumMap:equals(arg0) end ---@private ---@param arg0 EnumMap|Unknown|Unknown ---@return boolean function EnumMap:equals(arg0) end ---@private ---@param arg0 Object ---@param arg1 Object ---@return boolean function EnumMap:containsMapping(arg0, arg1) end ---@public ---@return int function EnumMap:hashCode() end ---@private ---@param arg0 Object ---@return boolean function EnumMap:isValidKey(arg0) end ---@public ---@param arg0 Enum|Unknown ---@param arg1 Object ---@return Object function EnumMap:put(arg0, arg1) end ---@private ---@param arg0 Object ---@return Object function EnumMap:unmaskNull(arg0) end ---@public ---@return Collection|Unknown function EnumMap:values() end ---@private ---@param arg0 int ---@return int function EnumMap:entryHashCode(arg0) end ---@public ---@param arg0 Map|Unknown|Unknown ---@return void function EnumMap:putAll(arg0) end ---@private ---@param arg0 Class|Unknown ---@return Enum[] function EnumMap:getKeyUniverse(arg0) end ---@private ---@param arg0 ObjectInputStream ---@return void function EnumMap:readObject(arg0) end ---@public ---@return Set|Unknown function EnumMap:keySet() end ---@public ---@param arg0 Object ---@return boolean function EnumMap:containsKey(arg0) end ---@public ---@param arg0 Object ---@return Object function EnumMap:get(arg0) end ---@public ---@param arg0 Object ---@return Object function EnumMap:remove(arg0) end ---@private ---@param arg0 Object ---@param arg1 Object ---@return boolean function EnumMap:removeMapping(arg0, arg1) end ---@private ---@param arg0 Object ---@return Object function EnumMap:maskNull(arg0) end ---@public ---@return void function EnumMap:clear() end ---@public ---@return Set|Unknown function EnumMap:entrySet() end ---@private ---@param arg0 ObjectOutputStream ---@return void function EnumMap:writeObject(arg0) end ---@public ---@return EnumMap|Unknown|Unknown function EnumMap:clone() end ---@public ---@param arg0 Object ---@return boolean function EnumMap:containsValue(arg0) end ---@private ---@param arg0 Enum|Unknown ---@return void function EnumMap:typeCheck(arg0) end ---@public ---@return int function EnumMap:size() end
local PI = 3.141592653589793 local SOLAR_MASS = 4 * PI * PI local DAYS_PER_YEAR = 365.24 sun = body() sun.x= 0.0 sun.y= 0.0 sun.z= 0.0 sun.vx= 0.0 sun.vy= 0.0 sun.vz= 0.0 sun.mass= SOLAR_MASS jupiter = body() jupiter.x= 4.84143144246472090e+00 jupiter.y= -1.16032004402742839e+00 jupiter.z= -1.03622044471123109e-01 jupiter.vx= 1.66007664274403694e-03 * DAYS_PER_YEAR jupiter.vy= 7.69901118419740425e-03 * DAYS_PER_YEAR jupiter.vz= -6.90460016972063023e-05 * DAYS_PER_YEAR jupiter.mass= 9.54791938424326609e-04 * SOLAR_MASS saturn = body() saturn.x= 8.34336671824457987e+00 saturn.y= 4.12479856412430479e+00 saturn.z= -4.03523417114321381e-01 saturn.vx= -2.76742510726862411e-03 * DAYS_PER_YEAR saturn.vy= 4.99852801234917238e-03 * DAYS_PER_YEAR saturn.vz= 2.30417297573763929e-05 * DAYS_PER_YEAR saturn.mass= 2.85885980666130812e-04 * SOLAR_MASS uranus = body() uranus.x= 1.28943695621391310e+01 uranus.y= -1.51111514016986312e+01 uranus.z= -2.23307578892655734e-01 uranus.vx= 2.96460137564761618e-03 * DAYS_PER_YEAR uranus.vy= 2.37847173959480950e-03 * DAYS_PER_YEAR uranus.vz= -2.96589568540237556e-05 * DAYS_PER_YEAR uranus.mass= 4.36624404335156298e-05 * SOLAR_MASS neptune = body() neptune.x= 1.53796971148509165e+01 neptune.y= -2.59193146099879641e+01 neptune.z= 1.79258772950371181e-01 neptune.vx= 2.68067772490389322e-03 * DAYS_PER_YEAR neptune.vy= 1.62824170038242295e-03 * DAYS_PER_YEAR neptune.vz= -9.51592254519715870e-05 * DAYS_PER_YEAR neptune.mass= 5.15138902046611451e-05 * SOLAR_MASS function array(...) return ... end local ...bodies = array(sun,jupiter,saturn,uranus,neptune) local function advance(nbody, dt) for i=1,nbody do local bi = bodies[i] local bix, biy, biz, bimass = bi.x, bi.y, bi.z, bi.mass local bivx, bivy, bivz = bi.vx, bi.vy, bi.vz for j=i+1,nbody do local bj = bodies[j] local dx, dy, dz = bix-bj.x, biy-bj.y, biz-bj.z local dist2 = dx*dx + dy*dy + dz*dz local mag = sqrt(dist2) mag = dt / (mag * dist2) local bm = bj.mass*mag bivx = bivx - (dx * bm) bivy = bivy - (dy * bm) bivz = bivz - (dz * bm) bm = bimass*mag bj.vx = bj.vx + (dx * bm) bj.vy = bj.vy + (dy * bm) bj.vz = bj.vz + (dz * bm) end bi.vx = bivx bi.vy = bivy bi.vz = bivz bi.x = bix + dt * bivx bi.y = biy + dt * bivy bi.z = biz + dt * bivz end end local function energy(nbody) local e = 0 for i=1,nbody do local bi = bodies[i] local vx, vy, vz, bim = bi.vx, bi.vy, bi.vz, bi.mass e = e + (0.5 * bim * (vx*vx + vy*vy + vz*vz)) for j=i+1,nbody do local bj = bodies[j] local dx, dy, dz = bi.x-bj.x, bi.y-bj.y, bi.z-bj.z local distance = sqrt(dx*dx + dy*dy + dz*dz) e = e - ((bim * bj.mass) / distance) end end return e end local function offsetMomentum(nbody) local px, py, pz = 0, 0, 0 for i=1,nbody do local bi = bodies[i] local bim = bi.mass px = px + (bi.vx * bim) py = py + (bi.vy * bim) pz = pz + (bi.vz * bim) end bodies[1].vx = -px / SOLAR_MASS bodies[1].vy = -py / SOLAR_MASS bodies[1].vz = -pz / SOLAR_MASS end local N = 500000 -- tonumber(arg and arg[1]) or 1000 local nbody = #bodies offsetMomentum(nbody) start = clock() println(energy(nbody)) for i=1,N do advance(nbody, 0.01) end println(energy(nbody), clock() - start)
---@meta resty_sha256={} function resty_sha256.final(self) end function resty_sha256.new(self) end function resty_sha256.reset(self) end resty_sha256._VERSION="0.11" function resty_sha256.update(self, s) end return resty_sha256
Macro { area="Common"; key="CtrlR"; description="Use hotkey <Ctrl-R> to perform XLat function."; flags=""; action = function() Keys('xlat') end; }
------------------------------------------------------ -- options.lua -- -- ------------------------------------------------------ return function (vararg) ------------------------------------------------------ -- options {} -- -- Define a table of options using the following -- syntax rules: -- -- name = { short = ?, args = ? } -- short = , ( -1 is any number, -- any other number parses that may arguments ) -- -- Option syntax. -- --[[ [ option name ] .short = short flag .long = long flag .argc = argument count .argv = argument element(s) .run = [ true or false ] depending on if option thrown. .rules = functions to run on each argument [ .body ] = can optionally code with the function you want in the table thrown (if order matters, you don't want to use this) --]] ------------------------------------------------------ local args = { ------------------------------------------------------ -- backend -- -- Choose a different backend. ------------------------------------------------------ backend = { short = "b", argc = 1 }, ------------------------------------------------------ -- suspend -- -- Suspend certain libraries. ------------------------------------------------------ suspend = { short = "s", argc = -1 }, ------------------------------------------------------ -- suspend-group { a, b, c, ... } or "[a, b, c, ... ]" -- -- Suspend an entire group of libraries. ------------------------------------------------------ ["suspend-group"] = { short = "x", argc = -1 }, ------------------------------------------------------ -- dump-pg -- -- Dump everything in an instance's pg table. ------------------------------------------------------ ["dump-pg"] = { short = "d", argc = 0 }, ------------------------------------------------------ -- list-modules -- -- List all the modules in a particular place. ------------------------------------------------------ ["list-modules"] = { short = "l", argc = 0 }, ------------------------------------------------------ -- post [t] -- -- Submit table or string over POST. -- If ------------------------------------------------------ post = { short = "p", argc = -1 }, ------------------------------------------------------ -- get [t] -- -- Perform a GET request for [path] ------------------------------------------------------ get = { short = "g", argc = -1 }, } ------------------------------------------------------ -- Probably need to check args to make sure .short -- options don't repeat themselves. -- -- Compile both short and long options. ------------------------------------------------------ local opts = {} for ok, ov in pairs(args) do opts[ok] = ov.short or "nil" -- print( ok .. " = " .. tostring(ov.short or "nil") ) end ------------------------------------------------------ -- Parse each argument. ------------------------------------------------------ -- Hold each argument "categorizer" local flag, ns -- Run the looper. for __blankarg__, cli_value in ipairs( vararg ) do -- Is argv and argument or flag? local arg_flag -- Catch double-dash full option names. if is.value( string.sub(cli_value,3,-1), table.keys(opts) ) then flag = string.sub(cli_value,3,-1) arg_flag = true -- Catch single-dash short option names. elseif is.value( string.sub(cli_value,2,3), table.values(opts) ) then flag = table.index( opts, string.sub(cli_value,2,3)) arg_flag = true -- Unix Format end of options. elseif string.sub(cli_value, 0,2) == "--" and string.sub( cli_value, 2, -1) == "" then arg_flag = true -- Catch invalid arguments. elseif string.sub(cli_value, 0,1) == "-" or string.sub( cli_value, 0, 2) == "--" and string.sub( cli_value, 2, -1) ~= "" then print("Invalid argument received: " .. cli_value) os.exit() end -- What is the value of flag after every evaluation. -- print( "flag: " .. tostring(flag) ) -- print( "argv: " .. tostring(cli_value) ) -- Set the evaluation flag to true. ns = args[flag] ns.run = true -- Set the options. -- This can be within the else clause at the top of the loop. -- If this is true, then start just adding to the argument chain. if not arg_flag then if ns.argc == 0 then -- print( "argc is 0" ) elseif ns.argc == 1 then -- print("argc is exactly 1") ns.argv = cli_value elseif ns.argc > 1 then -- print("argc is greater than 0") if not ns.argv then ns.argv = {} end if ns.argv and table.maxn(ns.argv) > ns.argc then print("Too many arguments supplied to option: --" .. flag) end table.insert(ns.argv, cli_value) elseif ns.argc == -1 then -- print("argc can be of any length") if not ns.argv then ns.argv = {} end table.insert(ns.argv, cli_value) end end end -- Unset flag flag = nil ns = nil ------------------------------------------------------ -- Add each o ------------------------------------------------------ return args end
object_mobile_smuggler_fence_seth = object_mobile_shared_smuggler_fence_seth:new { } ObjectTemplates:addTemplate(object_mobile_smuggler_fence_seth, "object/mobile/smuggler_fence_seth.iff")
local names = {} EMVU = {} EMVU.Configurations = {} EMVU.Configurations.Supported = {} function EMVU:OverwriteIndex(n, t) table.insert(names, n) end Photon = {} Photon.VehicleLibrary = {} function Photon:OverwriteIndex() end list = {} function list.Set() end hook = {} function hook.Add() end concommand = {} function concommand.Add() end net = {} function net.Receive() end function table.Copy(i) local o = {} for k, v in pairs(i) do o[k] = v end return o end resource = {} function resource.AddWorkshop() end function resource.AddFile() end function resource.AddSingleFile() end function AddCSLuaFile() end function include() end function CreateClientConVar() end function Vector(x, y, z) return {x = x, y = y, z = z} end function Angle(r, p, y) return {r = r, p = p, y = y} end function Color(r, g, b, a) return {r = r, g = g, b = b, a = a or 255} end function CurTime() return 0 end dofile(arg[1]) local out = table.concat(names, '--##--') print(out)
-------------------------------------------------------------------------- -- category utilities -- -------------------------------------------------------------------------- function checkIfExists(table, name) for k,v in pairs(table) do if (v.name == name) or (v == name) then print("Conflict (i.e elements appearing twice) detected when loading Database. Skipping the item.") return true end end return false end function checkIfFormulaExists(table, formula) for k,v in pairs(table) do if (v.formula == formula) then -- lulz lua powa print("Conflict (i.e formula appearing twice) detected when loading Database. Skipping formula.") return true end end return false end Constants = {} Categories = {} Formulas = {} function addCat(id,name,info) if checkIfExists(Categories, name) then print("Warning ! This category appears to exist already ! Adding anyway....") end return table.insert(Categories, id, {id=id, name=name, info=info, sub={}, varlink={}}) end function addCatVar(cid, var, info, unit) Categories[cid].varlink[var] = {unit=unit, info=info } end function addSubCat(cid, id, name, info) if checkIfExists(Categories[cid].sub, name) then print("Warning ! This subcategory appears to exist already ! Adding anyway....") end return table.insert(Categories[cid].sub, id, {category=cid, id=id, name=name, info=info, formulas={}, variables={}}) end function addSubCatScreen(cid, id, name, info, screen) if checkIfExists(Categories[cid].sub, name) then print("Warning ! This subcategory appears to exist already ! Adding anyway....") end return table.insert(Categories[cid].sub, id, {category=cid, id=id, name=name, info=info, formulas={}, variables={}, screen=screen}) end function aF(cid, sid, formula, variables) --add Formula local fr = {category=cid, sub=sid, formula=formula, variables=variables} -- In times like this we are happy that inserting tables just inserts a reference -- commented out this check because only the subcategory duplicates should be avoided, and not on the whole db. --if not checkIfFormulaExists(Formulas, fr.formula) then table.insert(Formulas, fr) --end if not checkIfFormulaExists(Categories[cid].sub[sid].formulas, fr.formula) then table.insert(Categories[cid].sub[sid].formulas, fr) end -- This function might need to be merged with U(...) for variable,_ in pairs(variables) do Categories[cid].sub[sid].variables[variable] = true end end function U(...) local out = {} for i, p in ipairs({...}) do out[p] = true end return out end
-- Copyright (c) 2017 Andrejs Mivreņiks -- -- 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 mp = require 'mp' local msg = require 'mp.msg' local utils = require 'mp.utils' local http = require 'socket.http' ------------------------------------- ------------------------------------- function on_pause_change(name, value) if mp.get_property('filename') ~= nil then filename = mp.get_property('filename') end if filename == nil then return end local name, season, episode = extract_data_from_filename(filename) if name == nil or season == nil or episode == nil then msg.debug("Could not extract show and episode information from the file name") return end if time_pos == nil then return end if duration == nil then return end -- Scrobble if not value then start_scrobble(name, season, episode) else stop_scrobble(name, season, episode) end end ------------------------------------- ------------------------------------- function on_time_pos_change(name, value) time_pos = value end ------------------------------------- ------------------------------------- function on_duration_change(name, value) duration = value end ------------------------------------- ------------------------------------- function on_file_loaded() time_pos = mp.get_property('time-pos') duration = mp.get_property('duration') if time_pos == nil then time_pos = 0.0 end local paused = false if mp.get_property('pause') == "yes" then paused = true end on_pause_change('pause', paused) end ------------------------------------- ------------------------------------- function on_end() on_pause_change('pause', true) end ------------------------------------- ------------------------------------- function start_scrobble(name, season, episode) msg.info("Starting scrobbling to Trakt.tv") --mp.osd_message("Starting scrobbling to Trakt.tv", 1) data = { ['progress'] = time_pos / duration, ['episode'] = { ['season'] = tonumber(season), ['number'] = tonumber(episode) }, ['show'] = { ['title'] = name } } http_post('https://api.trakt.tv/scrobble/start', data) end ------------------------------------- ------------------------------------- function stop_scrobble(name, season, episode) msg.info("Stopping scrobbling to Trakt.tv") --mp.osd_message("Stopping scrobbling to Trakt.tv", 1) data = { ['progress'] = time_pos / duration, ['episode'] = { ['season'] = tonumber(season), ['number'] = tonumber(episode) }, ['show'] = { ['title'] = name } } http_post('https://api.trakt.tv/scrobble/stop', data) end ------------------------------------- -- Loads and returns trakt.tv credentials ------------------------------------- function load_credentials() local credentials_file = get_data_dir().."/mpv-trakt/credentials.json" if not file_exists(credentials_file) then msg.error("Credentials file not found: "..credentials_file) msg.error("Please launch `install.sh` script to authorize in trakt.tv before using this script") return end local credentials_json = read_file(credentials_file) return utils.parse_json(credentials_json) end ------------------------------------- -- Returns standard data home directory -- Defaluts to ~/.local/share ------------------------------------- function get_data_dir() local result = os.getenv("HOME").."/.local/share" if os.getenv("XDG_DATA_HOME") ~= nil then result = os.getenv("XDG_DATA_HOME") end return result end ------------------------------------- -- Check if the file exists -- @param file File path ------------------------------------- function file_exists(file) local f = io.open(file, "rb") if f then f:close() end return f ~= nil end ------------------------------------- -- Read and return contents from file -- @param file File path ------------------------------------- function read_file(file) local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end ------------------------------------- -- Extracts show name, season and episode number from file name -- Currently supports only "Show.name.s01e01" format -- @param filename File name ------------------------------------- function extract_data_from_filename(filename) -- TODO Add more patterns local pattern = "^(.*)[Ss]([0-9]+)[\\.\\- ]?[Ee]([0-9]+)" local name, season, episode = filename:match(pattern) if name ~= nil then name = name:gsub('[\\.-]', ' '):match("^%s*(.-)%s*$") end return name, season, episode end ------------------------------------- ------------------------------------- function http_post(url, data) msg.error(utils.to_string(data)) body = utils.format_json(data) msg.debug('POST '..url) msg.debug('Body: '..body) local response = {} local client, code, headers, status = http.request{ url = url, sink = ltn12.sink.table(response), method = "POST", headers = { ['Authorization'] = 'Bearer '..credentials['access_token'], ['Accept'] = 'application/json', ['Content-Type'] = 'application/json', ['trakt-api-key'] = trakt_api_key, ['trakt-api-version'] = '2', ["Content-Length"] = body:len() }, source = ltn12.source.string(body) } msg.debug('Response data: '..utils.to_string(client)..'; '..utils.to_string(code)..'; '..utils.to_string(status)) msg.debug('Response body: '..utils.to_string(response)) return code, response end -- Script entry point trakt_api_key = 'fc9742bb96e86fdfdd163086eb95712f7657a86f051f75e04e5334a5d2b40f64' credentials = load_credentials() if credentials ~= nil then mp.observe_property("pause", "bool", on_pause_change) mp.observe_property("time-pos", "number", on_time_pos_change) mp.observe_property("duration", "number", on_duration_change) mp.register_event("file-loaded", on_file_loaded) mp.register_event("end-file", on_end) end
--[[ Validate a login attempt to a mailbox. ]] uuid = storage("channel", "uuid") -- Mailbox info. mailbox = storage("login_settings", "mailbox_number") password = storage("mailbox_settings", "password") -- The user entered password. entered_password = storage("get_digits", "password") -- Have we set up this mailbox yet? mailbox_setup_complete = storage("mailbox_settings", "mailbox_setup_complete") return { -- Load the mailbox for the user. { action = "call_sequence", sequence = "sub:load_mailbox_settings " .. mailbox .. "," .. profile.domain .. ",mailbox_settings", }, -- Clear the DTMF queue before collecting the password, in case a stray -- terminator key was pressed when entering the mailbox number. { action = "api_command", command = "uuid_flush_dtmf " .. uuid, }, -- Get a password from the user. Use the correct password to set the -- max_digit parameter -- smoothes user experience. { action = "get_digits", audio_files = "phrase:get_password", bad_input = "", max_digits = ":" .. password, storage_key = "password", timeout = profile.user_input_timeout, }, -- No entered password is a fail. { action = "conditional", value = entered_password, compare_to = "", comparison = "equal", if_true = "exit", }, -- Check for password match, fail if incorrect. { action = "conditional", value = password, compare_to = entered_password, comparison = "equal", if_false = "mailbox_login_incorrect", }, -- Check for new user condition and redirect as appropriate. { action = "conditional", value = mailbox_setup_complete, compare_to = "yes", comparison = "equal", if_true = "load_new_old_messages", if_false = "new_user_walkthrough", }, }
local busted = require "busted" local dir = require "pl.dir" local etlua = require "etlua" local file = require "pl.file" local grp = require "posix.grp" local handler = require 'busted.outputHandlers.base'() local log_tail = require "spec.support.log_tail" local path = require "pl.path" local process = require "process" local pwd = require "posix.pwd" local redis = require "resty.redis" local shell_blocking = require "shell-games" local unistd = require "posix.unistd" local _M = {} _M.nginx_process = nil _M.nginx_error_log_tail = nil _M.ngrok_process = nil _M.ngrok_hostname = nil _M.redis_process = nil _M.root_dir = path.dirname(path.dirname(path.dirname(path.abspath(debug.getinfo(1, "S").short_src)))) _M.dehydrated_persist_accounts_dir = _M.root_dir .. "/spec/tmp/dehydrated-accounts" _M.test_dir = "/tmp/resty-auto-ssl-test" _M.ngrok_test_dir = _M.test_dir .. "/ngrok" _M.redis_test_dir = _M.test_dir .. "/redis" _M.tests_test_dir = _M.test_dir .. "/tests" _M.test_counter = 0 _M.nobody_user = "nobody" _M.nobody_group = assert(grp.getgrgid(assert(pwd.getpwnam(_M.nobody_user)).pw_gid)).gr_name local nginx_template = etlua.compile(assert(file.read(_M.root_dir .. "/spec/config/nginx.conf.etlua"))) local redis_template = etlua.compile(assert(file.read(_M.root_dir .. "/spec/config/redis.conf.etlua"))) local nginx_path = ngx.re.gsub(os.getenv("PATH"), [[[^:]+/resty-auto-ssl-test-luarocks/[^:]+:]], "") local nginx_lua_path = ngx.re.gsub(os.getenv("LUA_PATH"), [[[^;]+/resty-auto-ssl-test-luarocks/[^;]+;]], "") local nginx_lua_cpath = ngx.re.gsub(os.getenv("LUA_CPATH"), [[[^;]+/resty-auto-ssl-test-luarocks/[^;]+;]], "") local function kill(proc) local pid = proc:pid() proc:kill() process.waitpid(pid) proc:kill(6) proc:kill(9) end local function start_ngrok() if not _M.ngrok_hostname then assert(dir.makepath(_M.ngrok_test_dir)) local ngrok_process, exec_err = process.exec("ngrok", { "http", "9080", "--log", _M.ngrok_test_dir .. "/ngrok.log", "--log-format", "logfmt", "--log-level", "debug" }) assert(not exec_err, exec_err) _M.ngrok_process = ngrok_process local log = log_tail.new(_M.ngrok_test_dir .. "/ngrok.log") local ok, output = log:read_until("start tunnel listen.*Hostname:[a-z0-9]+.ngrok.io") if not ok then print(ngrok_process:stdout()) print(ngrok_process:stderr()) local log_content, log_content_err = file.read(_M.ngrok_test_dir .. "/ngrok.log") if log_content then print(log_content) elseif log_content_err then print(log_content_err) end error("ngrok did not startup as expected") end local matches, match_err = ngx.re.match(output, "Hostname:([a-z0-9]+.ngrok.io)", "jo") assert(not match_err, match_err) _M.ngrok_hostname = matches[1] end end local function start_redis() if not _M.redis_process then assert(dir.makepath(_M.redis_test_dir)) assert(file.write(_M.redis_test_dir .. "/redis.conf", redis_template({ redis_test_dir = _M.redis_test_dir, }))) local redis_process, err = process.exec("redis-server", { _M.redis_test_dir .. "/redis.conf" }) _M.redis_process = redis_process local log = log_tail.new(_M.redis_test_dir .. "/redis.log") local ok = log:read_until("(now ready|Ready to accept)") if not ok then print(redis_process:stdout()) print(redis_process:stderr()) local log_content, log_content_err = file.read(_M.redis_test_dir .. "/redis.log") if log_content then print(log_content) elseif err then print(log_content_err) end local conf, conf_err = file.read(_M.redis_test_dir .. "/redis.conf") if conf then print(conf) elseif conf_err then print(conf_err) end error("redis did not startup as expected") end end local r = redis:new() assert(r:connect("127.0.0.1", 9999)) assert(r:flushall()) end local function exit_handler() if _M.nginx_process then kill(_M.nginx_process) end if _M.ngrok_process then kill(_M.ngrok_process) end if _M.redis_process then kill(_M.redis_process) end end busted.subscribe({ "exit" }, exit_handler) busted.subscribe({ "test", "start" }, function(element) _M.current_test_name = handler.getFullName(element) end) busted.subscribe({ "test", "end" }, function() _M.current_test_name = nil end) function _M.start(options) if not _M.started_once then if path.exists(_M.test_dir) then assert(dir.rmtree(_M.test_dir)) end -- We persist the Let's Encrypt account configuration across individual -- test runs so that each test doesn't register it's own account and we -- don't hit the Let's Encrypt rate limits of 10 accounts per IP per 3 -- hours (https://letsencrypt.org/docs/rate-limits/). -- -- But we still want to ensure the normal account creation process works -- and creates files with the right permissions, so if the persisted -- account config is older than 4 hours, delete it, so the next test run -- perform a normal, fresh account registration. if path.exists(_M.dehydrated_persist_accounts_dir) then local persist_account_time = path.getmtime(_M.dehydrated_persist_accounts_dir) if persist_account_time < ngx.now() - 60 * 60 * 4 then assert(dir.rmtree(_M.dehydrated_persist_accounts_dir)) end end _M.started_once = true end start_ngrok() start_redis() _M.stop_sockproc() if not options then options = {} end _M.test_counter = _M.test_counter + 1 local test_name_dir = assert(ngx.re.gsub(_M.current_test_name or "", "[^0-9A-Za-z_-]+", "_")) test_name_dir = string.sub(test_name_dir, 1, 250) test_name_dir = test_name_dir .. "-" .. string.format("%04d", _M.test_counter) _M.current_test_dir = _M.tests_test_dir .. "/" .. test_name_dir _M.current_test_accounts_dir = _M.current_test_dir .. "/auto-ssl/letsencrypt/accounts" assert(dir.makepath(_M.current_test_dir .. "/auto-ssl/letsencrypt")) assert(unistd.chown(_M.current_test_dir .. "/auto-ssl", _M.nobody_user)) -- If there is persisted account configuration, copy it into place for this -- test run. This prevents us hitting account registration rate limits if we -- were to register a new account on every test. if path.exists(_M.dehydrated_persist_accounts_dir) then _M.dehydrated_cached_accounts = true local _, cp_err = shell_blocking.capture_combined({ "cp", "-pr", _M.dehydrated_persist_accounts_dir, _M.current_test_accounts_dir }) assert(not cp_err, cp_err) local _, chown_err = shell_blocking.capture_combined({ "chown", "-R", _M.nobody_user .. ":" .. _M.nobody_group, _M.current_test_accounts_dir }) assert(not chown_err, chown_err) end options["root_dir"] = _M.root_dir options["current_test_dir"] = _M.current_test_dir options["user"] = _M.nobody_user .. " " .. _M.nobody_group assert(file.write(_M.current_test_dir .. "/nginx.conf", nginx_template(options))) local nginx_process, err = process.exec("nginx", { "-p", _M.current_test_dir, "-c", _M.current_test_dir .. "/nginx.conf", }, { ["PATH"] = nginx_path, ["LUA_PATH"] = nginx_lua_path, ["LUA_CPATH"] = nginx_lua_cpath, }, options["pwd"]) _M.nginx_process = nginx_process _M.nginx_error_log_tail = log_tail.new(_M.current_test_dir .. "/error.log") local ok, output = _M.nginx_error_log_tail:read_until("init_by_lua_block") if not ok or (output and string.match(output, "emerg")) then print(nginx_process:stdout()) print(nginx_process:stderr()) local log_content, log_content_err = file.read(_M.current_test_dir .. "/error.log") if log_content then print(log_content) elseif err then print(log_content_err) end local conf, conf_err = file.read(_M.current_test_dir .. "/nginx.conf") if conf then print(conf) elseif conf_err then print(conf_err) end error("nginx did not startup as expected") end end function _M.stop() if _M.nginx_process then -- On shutdown, if we don't already have persisted account config, then -- copy the generated config into the persisted directory. if _M.current_test_accounts_dir and not path.exists(_M.dehydrated_persist_accounts_dir) and path.exists(_M.current_test_accounts_dir) then assert(dir.makepath(path.dirname(_M.dehydrated_persist_accounts_dir))) local _, cp_err = shell_blocking.capture_combined({ "cp", "-pr", _M.current_test_accounts_dir, _M.dehydrated_persist_accounts_dir }) assert(not cp_err, cp_err) end kill(_M.nginx_process) _M.nginx_process = nil _M.stop_sockproc() end end function _M.read_error_log() local log = log_tail.new(_M.current_test_dir .. "/error.log") return log:read() end function _M.stop_sockproc() shell_blocking.capture_combined({ "pkill", "sockproc" }) local _, err = shell_blocking.capture_combined({ "rm", "-f", "/tmp/shell.sock", "/tmp/auto-ssl-sockproc.pid" }) assert(not err, err) end return _M
local objects = { -- LauraV createObject(8532,2097.3095703125,467.5703125,0.57099723815918,0,0,0,32), createObject(14412,2111.009765625,486.0947265625,5.9121675491333,0,0,0,32), createObject(7022,2072.052734375,473.7294921875,-0.98354810476303,0,0,179.98901367188,32), createObject(10615,2109.669921875,414.630859375,-9.4058980941772,0,0,180.01098632813,32), createObject(10615,2030.8648681641,500.60235595703,-9.4048976898193,0,0,90.010986328125,32), createObject(10615,2114.3366699219,558.82250976563,-9.4068984985352,0,0,359.9990234375,32), createObject(10615,2187.1567382813,513.65087890625,-9.4018964767456,0,0,269.99591064453,32), createObject(3858,2087.9890136719,488.8307800293,3.754786491394,0,0,315,32), createObject(3859,2087.9697265625,479.13671875,3.7733204364777,0,0,16.54541015625,32), createObject(1523,2088.0317382813,472.80746459961,0.72010338306427,0,0,90,32), createObject(1523,2087.9699707031,475.85092163086,0.72010338306427,0,0,270,32), createObject(1537,2079.498046875,479.56884765625,0.75110298395157,0,0,90,32), createObject(1533,2079.4958496094,476.55621337891,0.74710273742676,0,0,90,32), createObject(14842,2081.2890625,473.49313354492,2.3344030380249,0,0,88.5,32), createObject(3601,2076.6496582031,467.13272094727,-6.8556604385376,0,0,0,32), createObject(3858,2076.2307128906,475.23498535156,3.6618196964264,0,0,44.988006591797,32), createObject(7022,2140.953125,430.50991821289,-1.3743098974228,0,0,270,32), createObject(3601,2125.5234375,474.6298828125,-8.6607189178467,0,0,0,32), createObject(2780,2121.7270507813,478.56848144531,-8.4339761734009,0,0,0,32), createObject(1255,2099.2749023438,498.8703918457,1.4179989099503,0,0,274.20202636719,32), createObject(1255,2101.0573730469,498.88790893555,1.4179989099503,0,0,267.44677734375,32), createObject(1255,2107.1608886719,498.79113769531,1.4169985055923,0,0,267.44567871094,32), createObject(1255,2105.33203125,499.005859375,1.4179989099503,0,0,278.69018554688,32), createObject(1255,2111.6364746094,498.99032592773,1.4169985055923,0,0,270.75,32), createObject(1255,2114.3845214844,499.09918212891,1.4169985055923,0,0,270.7470703125,32), createObject(1255,2126.9716796875,491.31939697266,1.4169985055923,0,0,179.7470703125,32), createObject(1255,2126.9423828125,488.8037109375,1.4169985055923,0,0,179.736328125,32), createObject(1255,2126.9208984375,483.6689453125,1.4169985055923,0,0,179.736328125,32), createObject(1255,2126.8061523438,481.50500488281,1.4169985055923,0,0,169.48706054688,32), createObject(1255,2111.4968261719,473.93536376953,1.4169985055923,0,0,94.7470703125,32), createObject(1255,2109.8271484375,473.86981201172,1.4169985055923,0,0,91.74609375,32), createObject(1255,2101.5751953125,473.95751953125,1.4169985055923,0,0,94.741333007813,32), createObject(1255,2100.369140625,473.86383056641,1.4169985055923,0,0,94.740600585938,32), createObject(14487,2114.994140625,486.1904296875,6.4303913116455,0,0,269.40124511719,32), createObject(14487,2093.2041015625,486.3447265625,6.4343910217285,0,0,269.40124511719,32), createObject(1640,2116.3354492188,473.80102539063,0.84410190582275,0,0,354,32), createObject(1641,2097.62890625,498.9404296875,0.84310150146484,0,0,0,32), createObject(633,2095.876953125,473.58203125,1.8420121669769,0,0,0,32), createObject(646,2107.3427734375,473.173828125,2.0916237831116,0,0,0,32), createObject(728,2126.6496582031,474.06661987305,0.39810359477997,0,0,0,32), createObject(800,2127.0954589844,499.23406982422,1.6419801712036,0,0,355.5,32), createObject(1428,2104.16015625,477.66909790039,-0.55725985765457,195.029296875,0,179.533203125,32), createObject(14782,2082.1166992188,485.27072143555,1.8611497879028,0,0,0,32), createObject(7022,2084.140625,508.05740356445,-45.365573883057,0,90,0,32), createObject(14401,2091.1682128906,469.46755981445,1.039598107338,0,0,0.75,32), createObject(7022,2081.5280761719,508.06491088867,-45.353580474854,0,90,0,32), createObject(14782,2081.9108886719,481.84555053711,1.8611497879028,0,0,180,32), createObject(7022,2084.1318359375,503.56625366211,-45.365573883057,0,90,0,32), createObject(7022,2081.5251464844,503.55404663086,-45.354579925537,0,90,0,32), createObject(2628,2080.6650390625,488.35284423828,0.83979034423828,0,0,90,32), createObject(2628,2080.6789550781,490.9856262207,0.83979034423828,0,0,90,32), createObject(2630,2084.7170410156,487.47280883789,0.83979034423828,0,0,90,32), createObject(2630,2084.810546875,489.23181152344,0.83979034423828,0,0,87.4951171875,32), createObject(2627,2084.8151855469,491.23806762695,0.83979034423828,0,0,270,32), createObject(2627,2084.8115234375,492.75189208984,0.83979034423828,0,0,270,32), createObject(2629,2081.9362792969,493.93359375,0.83979034423828,0,0,90,32), createObject(2631,2085.1511230469,496.60681152344,0.88611853122711,0,0,270,32), createObject(2631,2080.7348632813,497.63967895508,0.88611853122711,0,0,270,32), createObject(2915,2080.369140625,496.27328491211,1.0609529018402,0,0,288.75,32), createObject(2916,2080.3044433594,499.09124755859,1.0563286542892,0,0,67,32), createObject(2913,2081.3898925781,493.49328613281,1.8187875747681,0,90,90,32), createObject(728,2089.5988769531,498.93975830078,0.39810359477997,0,0,194.25,32), createObject(1533,2119.69140625,500.01904296875,0.84310150146484,0,0,0,32), createObject(1537,2122.7038574219,500.01715087891,0.84310150146484,0,0,0,32), createObject(646,2127.2822265625,486.03530883789,2.241623878479,0,0,0,32), createObject(14454,2118.6748046875,449.60424804688,13.518056869507,90,90,0,32), createObject(14454,2102.6149902344,482.60784912109,13.516056060791,90,90,270,32), createObject(14454,2107.3012695313,482.69561767578,13.516056060791,90,90,270,32), createObject(14454,2118.673828125,445.2839050293,13.518056869507,90,90,0,32), createObject(2780,2082.5617675781,472.79586791992,-6.6748657226563,0,0,0,32), createObject(8487,2105.9438476563,476.66485595703,0.012143272906542,0,0,0,32), createObject(8487,2106.2004394531,466.94180297852,0.012143272906542,0,0,0,32) } local col = createColSphere(2104.8046875, 489.287109375, 44.98458480835,80) local function watchChanges( ) if getElementDimension( getLocalPlayer( ) ) > 0 and getElementDimension( getLocalPlayer( ) ) ~= getElementDimension( objects[1] ) and getElementInterior( getLocalPlayer( ) ) == getElementInterior( objects[1] ) then for key, value in pairs( objects ) do setElementDimension( value, getElementDimension( getLocalPlayer( ) ) ) end elseif getElementDimension( getLocalPlayer( ) ) == 0 and getElementDimension( objects[1] ) ~= 65535 then for key, value in pairs( objects ) do setElementDimension( value, 65535 ) end end end addEventHandler( "onClientColShapeHit", col, function( element ) if element == getLocalPlayer( ) then addEventHandler( "onClientRender", root, watchChanges ) end end ) addEventHandler( "onClientColShapeLeave", col, function( element ) if element == getLocalPlayer( ) then removeEventHandler( "onClientRender", root, watchChanges ) end end ) -- Put them standby for now. for key, value in pairs( objects ) do local x, y, z = getElementPosition( value ) setElementPosition( value, x, y, z + 40 ) setElementDimension( value, 65535 ) end
require("games/common2/module/layerShowTypeData"); local headBaseLayout = require("view/kScreen_1280_800/games/common2/headBaseLayout"); require("games/common2/module/invite2/data/inviteConfig"); local viewBase = Import("games/common2/module/viewBase"); HeadViewBase = class(viewBase,false); local _getNickMaxWidth; local _getNickSubLen; HeadViewBase.s_defaultBoyFile = UserBaseInfoIsolater.getInstance():getMaleHead(); HeadViewBase.s_defaultGirlFile = UserBaseInfoIsolater.getInstance():getFemaleHead(); HeadViewBase.Delegate = { }; HeadViewBase.ctor = function ( self, seat, layoutConfig ) super(self,layoutConfig); self.m_seat = seat; self.m_isAi = false; if self.m_root then local width, height = self.m_root:getSize(); self:setSize(width,height); self.m_root:setVisible(false); end self:commonInitView(); end HeadViewBase.dtor = function ( self ) ImageCache.getInstance():cleanRef(self); delete(self.m_vipAnim); self.m_vipAnim = nil; if self.m_netTipsAnim then self.m_netTipsAnim:stop() self.m_netTipsAnim = nil end end HeadViewBase.commonInitView = function ( self ) self.m_commonHeadView = SceneLoader.load(headBaseLayout); self:addChild(self.m_commonHeadView); self.m_commonHeadView:setAlign(kAlignCenter); self.m_commonHeadView:setSize(92,92); self.m_commonHeadView:setLevel(-1); self.m_headView = self.m_commonHeadView:getChildByName("headView"); self.m_headRobot = self.m_headView:getChildByName("headRobot"); self.m_headDefault = self.m_headView:getChildByName("defaultHead"); self.m_headFrame = self.m_headView:getChildByName("headFrame"); self.m_vipFrame = self.m_headView:getChildByName("vipFrame"); self.m_bankruptView = self.m_headView:getChildByName("bankruptView"); self.m_netTips = self.m_commonHeadView:getChildByName("net_tips"); self.m_wifi = self.m_netTips:getChildByName("wifi"); self.m_headFrame:setLevel(2); self.m_vipFrame:setLevel(2); self.m_bankruptView:setLevel(2); self.m_headEmpty = self.m_commonHeadView:getChildByName("headEmpty"); self.m_inviteBtn = self.m_headEmpty:getChildByName("inviteBtn"); self.m_nameArea = self.m_commonHeadView:getChildByName("name_area"); self.m_nickText = self.m_nameArea:getChildByName("nick_text"); self.m_moneyArea = self.m_commonHeadView:getChildByName("money_area"); self.m_moneyIcon = self.m_moneyArea:getChildByName("money_icon"); self.m_moneyView = self.m_moneyArea:getChildByName("money_view"); self.m_scoreArea = self.m_commonHeadView:getChildByName("score_area"); self.m_score = self.m_scoreArea:getChildByName("score"); self.m_ownerView = self.m_commonHeadView:getChildByName("ownerView"); local file = RoomPropertyData.getInstance():getCurPropertyIcon(); self:resetMoneyIconFile(file); self.m_headFrame:setOnClick(self,self.onPlayerHeadClick); self.m_vipFrame:setOnClick(self,self.onPlayerHeadClick); self.m_inviteBtn:setOnClick(self,self.onInviteBtnClick); self:setInviteBtnStatus(PrivateRoomIsolater.getInstance():isInPrivateRoom()); if GameInfoIsolater.getInstance():isInMatchRoom() then self.m_nameArea:setVisible(false); self.m_moneyArea:setVisible(false); self.m_scoreArea:setVisible(true); else self.m_nameArea:setVisible(true); self.m_moneyArea:setVisible(true); self.m_scoreArea:setVisible(false); end self.m_scoreColor = {255,255,255}; end -----------------------------------private function------------------------------------------------------------------ _getNickMaxWidth = function(self,len) if not self.m_nickMaxWidth then local test = "宽"; local nickText = new(Text, test, 1, 1, kAlignLeft, nil,26); self.m_nickMaxWidth = nickText:getSize(); self.m_nickMaxWidth = self.m_nickMaxWidth*(len or 5); delete(nickText); end return self.m_nickMaxWidth; end _getNickSubLen = function(self,userName,maxLen) self.m_nickMaxlen = maxLen or (self.m_nickMaxlen or 5); if string.isEmpty(userName) then return self.m_nickMaxlen; end local maxWidth = _getNickMaxWidth(self,self.m_nickMaxlen); local len; for i = self.m_nickMaxlen,3,-1 do local nickName = string.subUtfStrByCn(userName,1,i,""); local nickText = new(Text, nickName, 1, 1, kAlignLeft, nil,26); local w = nickText:getSize(); delete(nickText); if w <= maxWidth then len = i; break; end end len = len or 2; return len; end -----------------------------------private function------------------------------------------------------------------ HeadViewBase.setInviteBtnStatus = function ( self, visible ) if self.m_inviteBtn then local curShowType = LayerShowTypeData.getInstance():getCurShowType(); if curShowType == LayerShowTypeData.getInstance():getOnlookerType() then visible = false; end self.m_inviteBtn:setVisible(visible); end end HeadViewBase.setBaseHeadPos = function ( self, x, y, align ) if self.m_commonHeadView then self.m_commonHeadView:setPos(x, y); self.m_commonHeadView:setAlign(align); end end HeadViewBase._getNameArea = function(self) self.m_commonHeadView:removeChild(self.m_nameArea); return self.m_nameArea; end HeadViewBase._getScoreArea = function(self) self.m_commonHeadView:removeChild(self.m_scoreArea); return self.m_scoreArea; end HeadViewBase._refreshScoreAreaSize = function(self) local w = self.m_score:getSize(); self.m_scoreArea:setSize(w,nil); end HeadViewBase._setScoreColor = function(self,r,g,b) self.m_scoreColor = {r,g,b}; end HeadViewBase._getMoneyArea = function(self) self.m_commonHeadView:removeChild(self.m_moneyArea); return self.m_moneyArea; end HeadViewBase._setMoneyIconFile = function ( self, file ) self:resetMoneyIconFile(file); self:resetMoneyIconSize(); if self.m_userData then local money = self.m_userData:getMoney(); self:setMoneyView(money); end end HeadViewBase.resetMoneyIconFile = function(self,file) if type(file) ~= "string" or file == "" then return; end self.m_moneyIcon:setFile(file); end HeadViewBase.resetMoneyIconSize = function(self) local res = self.m_moneyIcon.m_res; if res then local width = res:getWidth(); local height = res:getHeight(); self.m_moneyIcon:setSize(width,height); end end HeadViewBase.refreshNickName = function(self,userName) if not userName then return end local len = _getNickSubLen(self,userName); local nickName = string.subUtfStrByCn(userName,1,len,""); self.m_nickText:setText(nickName,nil,nil,self.m_nickText:getColor()); end -- 设置昵称长度 HeadViewBase.setNickNameMaxLen = function(self,maxLen) if not maxLen then return end self.m_nickMaxlen = maxLen; end -- 根据身份信息设置昵称颜色 HeadViewBase.refreshNickColor = function(self,identity) if not identity then return end if not GameInfoIsolater.getInstance():isInMatchRoom() then local color = {255,255,255}; self.m_nameArea:setVisible(true); if UserIdentityIsolater.getInstance():checkIsVip(identity) then color = {246,80,0}; if self:isDuringDefenseCheatTime() then -- 防作弊时,昵称颜色默认黑色 color = {255,255,255}; end end self.m_nickText:setColor(unpack(color)); end end HeadViewBase.refreshHeadIcon = function(self,url,sex) self.m_headView:setVisible(true); self.m_headEmpty:setVisible(false); local isFemale = UserBaseInfoIsolater.getInstance():checIsFemale(sex); local imagePath = isFemale and HeadViewBase.s_defaultGirlFile or HeadViewBase.s_defaultBoyFile; self:__setHeadDefault(imagePath); self.m_headDefault:setVisible(true); if self.m_headImage then self.m_headImage:setVisible(false); end if (not GameInfoIsolater.getInstance():isInMatchRoom()) then if url and (not self:isDuringDefenseCheatTime()) then -- 防作弊时,不显示自定义头像 ImageCache.getInstance():request(url,self,self.onUpdateHeadImage); end end end HeadViewBase.setUserData = function ( self, userData ) if not userData then return; end self.m_userData = userData; if self.m_root then self.m_root:setVisible(true); end self.m_uid = userData:getMid(); self:refreshNickName(userData:getNick()); self:refreshNickColor(userData:getIdentity()); self:refreshHeadIcon(userData:getAvatar(),userData:getSex()); self:refreshIdentity(userData); self:refreshProperty(userData); self:setUserAi(userData:isAi()); self:refreshPos(); if GameInfoIsolater.getInstance():isInMatchRoom() then self:refreshMatchScore(); end end HeadViewBase.__setHeadDefault = function (self, imagePath) if self.m_headDefaultImage then self.m_headDefault:removeChild(self.m_headDefaultImage); end delete(self.m_headDefaultImage); self.m_headDefaultImage = nil; self.m_headDefaultImage = self:createHeadImage(imagePath); self.m_headDefault:addChild(self.m_headDefaultImage); self.m_headDefaultImage:setAlign(kAlignCenter); self.m_headDefaultImage:setSize(self.m_headDefault:getSize()); self:updateHeadImagePath(imagePath); end HeadViewBase.refreshPos = function ( self ) InteractionInfo.getInstance():setHeadAbsolutePos(self.m_seat,self:getHeadAbsolutePos()); InteractionInfo.getInstance():setHeadPos(self.m_seat,self:getPos()); InteractionInfo.getInstance():setHeadSize(self.m_seat,self.m_commonHeadView:getSize()); end HeadViewBase.setUserAi = function ( self, isAi ) -- body self.m_headRobot:setVisible(isAi); if self.m_isAi ~= isAi then if self.m_clickListener then self.m_clickListener.onAiStateChanged(self, self.m_seat, isAi); end end self.m_isAi = isAi; if isAi then if self.m_headImage then self.m_headImage:setVisible(false); end self.m_headDefault:setVisible(false); else if self.m_isHasImage then self.m_headDefault:setVisible(false); if self.m_headImage then self.m_headImage:setVisible(true); end else self.m_headDefault:setVisible(true); if self.m_headImage then self.m_headImage:setVisible(false); end end end end HeadViewBase.isAiState = function ( self ) -- body return self.m_isAi; end HeadViewBase.setUserReady = function ( self, isReady ) -- body if self.m_isReady ~= isReady then if self.m_clickListener then self.m_clickListener.onReadyStateChanged(self, self.m_seat, isReady); end end self.m_isReady = isReady; end HeadViewBase.reset = function ( self ) self:setUserReady(false); self:setUserAi(false); end -- 清人 HeadViewBase.clear = function ( self ) self.m_headEmpty:setVisible(true); self.m_headView:setVisible(false); self.m_moneyArea:setVisible(false); self.m_nameArea:setVisible(false); self.m_headRobot:setVisible(false); if self.m_root then self.m_root:setVisible(false); end self.m_userData = nil; self.m_isHasImage = nil; self.m_isAi = false; self:stopBankruptAnim(); end HeadViewBase.refreshIdentity = function ( self, userData ) -- body if not userData then return; end local identity = userData:getIdentity(); local isVip = UserIdentityIsolater.getInstance():checkIsVip(identity); if isVip and not self:isDuringDefenseCheatTime() then -- 添加vip动画 delete(self.m_vipAnim); self.m_vipAnim = nil; self.m_vipFrame:setVisible(true); self.m_headFrame:setVisible(false); self.m_vipAnim = new(AnimHeadVipAnim2); self.m_vipAnim:init(); self.m_vipAnim:play(self.m_vipFrame); else self.m_vipFrame:setVisible(false); self.m_headFrame:setVisible(true); end end HeadViewBase.refreshProperty = function ( self, userData ) -- body if not userData then return; end local money = userData:getMoney(); self:setMoneyView(money); if self:isDuringDefenseCheatTime() then self.m_moneyArea:setVisible(false); elseif GameInfoIsolater.getInstance():isInMatchRoom() then self.m_moneyArea:setVisible(false); else self.m_moneyArea:setVisible(true); end local file = RoomPropertyData.getInstance():getCurPropertyIcon(); self:resetMoneyIconFile(file); end HeadViewBase.getHeadAbsolutePos = function ( self ) -- body local x, y = self.m_commonHeadView:getAbsolutePos(); return x, y; end HeadViewBase.setMoneyView = function ( self, money ) self.m_moneyView:removeAllChildren(true); local number_path = "games/common/head/head_base/money_num/money_%s.png" local moneyStr = MoneyTools.skipMoney(money); local moneyNode = MoneyTools.getNumberNode(number_path,moneyStr,-2); local moneyNode_w,moneyNode_h = moneyNode:getSize(); self.m_moneyView:addChild(moneyNode); moneyNode:setAlign(kAlignCenter); self.m_moneyView:setSize(moneyNode_w,moneyNode_h); local icon_w,icon_h = self.m_moneyIcon:getSize(); self.m_moneyArea:setSize(moneyNode_w+icon_w+4,30); end HeadViewBase.updateScore = function ( self, score ) self.m_score:setText(score,nil,nil,unpack(self.m_scoreColor)); local w = self.m_score:getSize(); self.m_scoreArea:setSize(w,nil); end HeadViewBase.onUpdateHeadImage = function ( self, url, imagePath ) -- body Log.v("HeadViewBase.onUpdateHeadImage",imagePath); if imagePath then self:updateHeadImagePath(imagePath); self.m_isHasImage = true; self.m_headDefault:setVisible(false); if self.m_headImage then self.m_headView:removeChild(self.m_headImage); end delete(self.m_headImage); self.m_headImage = nil; self.m_headImage = self:createHeadImage(imagePath); self.m_headView:addChild(self.m_headImage); self.m_headImage:setLevel(1); self.m_headImage:setAlign(kAlignCenter); self.m_headImage:setSize(self.m_headDefault:getSize()); else self.m_isHasImage = nil; end end HeadViewBase.createHeadImage = function ( self, imagePath ) -- body local headImage = new(Mask,imagePath,"games/common/head/head_base/ddz_head_mask.png"); return headImage; end HeadViewBase.updateHeadImagePath = function ( self,imagePath ) self.m_headImagePath = imagePath; InteractionInfo.getInstance():setHeadImagePath(self.m_seat,imagePath); end HeadViewBase.getHeadAreaSize = function ( self ) -- body return self.m_commonHeadView:getSize(); end HeadViewBase.isDuringDefenseCheatTime = function (self) return GameInfoIsolater.getInstance():checkIsDuringDefenseCheatTime() and self.m_seat ~= 1; end HeadViewBase.onPlayerHeadClick = function ( self ) ReportIsolater.getInstance():report(UBConfig.kGameDesktopPlayerInfo, true, true) if GameInfoIsolater.getInstance():isInMatchRoom() then local isShowPlayerInfo = false; local myUserId = UserBaseInfoIsolater.getInstance():getUserId(); local curShowType = LayerShowTypeData.getInstance():getCurShowType(); local onlookerType = LayerShowTypeData.getInstance():getOnlookerType(); if self.m_uid ~= myUserId and curShowType ~= onlookerType and MatchIsolater.getInstance():getCurMatchIsSupportReport() then isShowPlayerInfo = true; end if not isShowPlayerInfo then Toast.getInstance():showText("比赛场无法查看选手信息",50,30,kAlignLeft,"",24,200,175,110); return; end end local data = {seat = self.m_seat} local action = GameMechineConfig.ACTION_NS_HEADCLICK; MechineManage.getInstance():receiveAction(action,data,self.m_uid); end HeadViewBase.onInviteBtnClick = function ( self ) local action = GameMechineConfig.ACTION_NS_REQUESTINVITELIST; local inviteType = InviteConfig.TYPE_PRIVATE_ROOM; MechineManage.getInstance():receiveAction(action, inviteType); end HeadViewBase.joinGame = function ( self, seat, uid, info, isFast ) self:onUpdateUserInfo(seat, uid, info, isFast); self:refreshInviteBtnStatus(); end HeadViewBase.onUpdateUserInfo = function ( self, seat, uid, info, isFast ) local gameplayerInfo = GamePlayerManager2.getInstance():getPlayerBySeat(seat); if gameplayerInfo then self.m_seat = seat; self.m_uid = uid; self:setUserData(gameplayerInfo); -- self:setUserReady(false); end end HeadViewBase.gameReady = function ( self, seat, uid, info, isFast ) self:setUserReady(true); self:stopBankruptAnim(); end HeadViewBase.startGame = function ( self ) self:setUserReady(false); self:stopBankruptAnim(); end HeadViewBase.onLogout = function ( self, seat, uid, info, isFast ) self:setUserReady(false); end HeadViewBase.onGameOver = function ( self, seat, uid, info, isFast ) self:onUpdateUserInfo(seat, uid, info, isFast); self:reset(); end HeadViewBase.onAi = function ( self, seat, uid, info, isFast ) -- body if not info then return; end self:setUserAi(info.isAi == 1); end HeadViewBase.refreshMatchScore = function(self,seat,uid,info,isFast) local info = MatchIsolater.getInstance():getMatchScoreInfo(); info = table.verify(info); for k,v in pairs(info) do if v.mid == self.m_uid then self:updateScore(v.score); end end end HeadViewBase.refreshInviteBtnStatus = function (self) self:setInviteBtnStatus(PrivateRoomIsolater.getInstance():isInPrivateRoom()); end HeadViewBase.parseConfig = function ( self, config ) -- body if not config then return; end local headPos = config.headPos and config.headPos[self.m_seat] or nil; if headPos then self:setPos(headPos.x, headPos.y); self:setAlign(headPos.align); end local ownerPos = config.ownerPos and config.ownerPos[self.m_seat] or nil; if ownerPos and self.m_ownerView then self.m_ownerView:setPos(ownerPos.x, ownerPos.y); self.m_ownerView:setAlign(ownerPos.align); end end HeadViewBase.showBankruptAnim = function(self,seat) if GameInfoIsolater.getInstance():isInMatchRoom() then return; end local playerInfo = GamePlayerManager2.getInstance():getPlayerBySeat(seat); if playerInfo then if RoomPropertyData.getInstance():checkIsBankrupt(playerInfo:getMoney()) then self:stopBankruptAnim(); require("games/common2/animation/animBankrupt"); self.m_bankruptAnim = new(AnimBankrupt); self.m_bankruptAnim:play(); self.m_bankruptView:addChild(self.m_bankruptAnim); self.m_bankruptAnim:setAlign(kAlignCenter) end end end HeadViewBase.stopBankruptAnim = function(self) if self.m_bankruptAnim then delete(self.m_bankruptAnim); self.m_bankruptAnim = nil; self.m_bankruptView:removeAllChildren(true); end end HeadViewBase.refreshUserProperty = function ( self, seat, uid, info, isFast ) local gameplayerInfo = GamePlayerManager2.getInstance():getPlayerBySeat(seat); self:refreshProperty(gameplayerInfo); end HeadViewBase.refreshWifi = function (self, seat, uid, info, isFast) if self.m_netTips and self.m_wifi then self.m_netTips:setVisible(info) if info then if not self.m_netTipsAnim then local am = require 'animation' self.m_netTipsAnim = am.Animator(am.flash(), am.updator(self.m_wifi:getWidget()),kAnimLoop) end self.m_netTipsAnim:start() else if self.m_netTipsAnim then self.m_netTipsAnim:stop() self.m_netTipsAnim = nil end end end end HeadViewBase.refreshReadyStatus = function(self,seat,uid,info,isFast) info = table.verify(info); self:setUserReady(info.isShow); end HeadViewBase.resetHeadEmptyPos = function(self,x,y) self.m_headEmpty:setPos((x or 0), (y or 0)); end HeadViewBase.setUserOwner = function(self, isOwner) if self.m_ownerView then local isInJiFenRoom = PrivateRoomIsolater.getInstance():isInJiFenRoom(); self.m_ownerView:setVisible(isInJiFenRoom and isOwner) end end HeadViewBase.s_stateFuncMap = { [GameMechineConfig.STATUS_LOGIN] = "joinGame"; [GameMechineConfig.STATUS_READY] = "gameReady"; [GameMechineConfig.STATUS_PLAYING] = "startGame"; [GameMechineConfig.STATUS_LOGOUT] = "onLogout"; [GameMechineConfig.STATUS_GAMEOVER] = "onGameOver"; }; HeadViewBase.s_actionFuncMap = { [GameMechineConfig.ACTION_NS_ROBOT] = "onAi"; [GameMechineConfig.ACTION_NS_MATCH_SCORE] = "refreshMatchScore"; [GameMechineConfig.ACTION_NS_UPDATE_USERINFO] = "onUpdateUserInfo"; [GameMechineConfig.ACTION_NS_REFRESH_USERPROPERTY] = "refreshUserProperty"; [GameMechineConfig.ACTION_NS_REFRESH_WIFI] = "refreshWifi"; [GameMechineConfig.ACTION_NS_REFRESH_READY_STATUS] = "refreshReadyStatus"; } return HeadViewBase;
------------------------------------------------------------------------------------------- -- -- raylib [textures] example - Texture loading and drawing a part defined by a rectangle -- -- This example has been created using raylib 1.6 (www.raylib.com) -- raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -- -- Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) -- ------------------------------------------------------------------------------------------- local MAX_FRAME_SPEED = 14 local MIN_FRAME_SPEED = 1 -- Initialization ------------------------------------------------------------------------------------------- local screenWidth = 800 local screenHeight = 450 InitWindow(screenWidth, screenHeight, "raylib [texture] example - texture rectangle") -- NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) local scarfy = LoadTexture("resources/scarfy.png") -- Texture loading local position = Vector2(350.0, 280.0) local frameRec = Rectangle(0, 0, scarfy.width/6, scarfy.height) local currentFrame = 0 local framesCounter = 0 local framesSpeed = 8 -- Number of spritesheet frames shown by second SetTargetFPS(60); -- Set our game to run at 60 frames-per-second ------------------------------------------------------------------------------------------- -- Main game loop while not WindowShouldClose() do -- Detect window close button or ESC key -- Update --------------------------------------------------------------------------------------- framesCounter = framesCounter + 1 if (framesCounter >= (60/framesSpeed)) then framesCounter = 0 currentFrame = currentFrame + 1 if (currentFrame > 5) then currentFrame = 0 end frameRec.x = currentFrame*scarfy.width/6 end if (IsKeyPressed(KEY.RIGHT)) then framesSpeed = framesSpeed + 1 elseif (IsKeyPressed(KEY.LEFT)) then framesSpeed = framesSpeed - 1 end if (framesSpeed > MAX_FRAME_SPEED) then framesSpeed = MAX_FRAME_SPEED elseif (framesSpeed < MIN_FRAME_SPEED) then framesSpeed = MIN_FRAME_SPEED end --------------------------------------------------------------------------------------- -- Draw --------------------------------------------------------------------------------------- BeginDrawing() ClearBackground(RAYWHITE) DrawTexture(scarfy, 15, 40, WHITE) DrawRectangleLines(15, 40, scarfy.width, scarfy.height, LIME) DrawRectangleLines(15 + frameRec.x, 40 + frameRec.y, frameRec.width, frameRec.height, RED) DrawText("FRAME SPEED: ", 165, 210, 10, DARKGRAY) DrawText(string.format("%02i FPS", framesSpeed), 575, 210, 10, DARKGRAY) DrawText("PRESS RIGHT/LEFT KEYS to CHANGE SPEED!", 290, 240, 10, DARKGRAY) for i = 1, MAX_FRAME_SPEED do if (i <= framesSpeed) then DrawRectangle(250 + 21*i, 205, 20, 20, RED) end DrawRectangleLines(250 + 21*i, 205, 20, 20, MAROON) end DrawTextureRec(scarfy, frameRec, position, WHITE) -- Draw part of the texture DrawText("(c) Scarfy sprite by Eiden Marsal", screenWidth - 200, screenHeight - 20, 10, GRAY) EndDrawing() --------------------------------------------------------------------------------------- end -- De-Initialization ------------------------------------------------------------------------------------------- UnloadTexture(scarfy) -- Texture unloading CloseWindow() -- Close window and OpenGL context -------------------------------------------------------------------------------------------