Lua timer script producing all-numeric value instead of proper time - math

My timer script writes this into the file when it saves the value.
Example Time in file: 1638185640
Example of time displayed in game:
name = "Timer"
description = "Just a normal Timer."
positionX = 0
positionY = 0
sizeX = 24
sizeY = 10
scale = 1
START_STOP_KEY = 0x55 --or 'U'
RESET_KEY = 0x4A --or 'J'
--
--[[
Timer Module Script by SebyGHG original script by Onix64(Stopwatch)
if you wish to change the key you can take the key code from here
https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
]] -------------script-code-------------
state = 1
stopTime = 0
startTime = 0
f = io.input("timesave.txt")
result = f :read()
f :close()
stopTime = result
state = 2
function keyboard(key, isDown)
if (isDown == true) then
if (key == RESET_KEY) then
state = 0
elseif (key == START_STOP_KEY) then
if (state == 0) then
state = 1
startTime = os.time()
elseif (state == 1) then
state = 2
io.output("timesave.txt")
timesave= (io.open("timesave.txt","w"))
io.write(stopTime)
io.close(timesave)
stopTime = os.time() -stopTime
elseif (state == 2) then
state = 1
startTime =startTime + os.time() - stopTime
end
end
end
end
TimerText = "00:00"
TextColor = {r = 30, g = 255, b = 30, a = 255}
function doubleDigit(number)
if (number < 10) then
return "0" .. math.floor(number)
else
return math.floor(number)
end
end
function timeText(time)
local result = ""
local days = 0
while (time > 86399) do
days = days + 1
time = time - 86400
end
local hours = 0
while (time > 3599) do
hours = hours + 1
time = time - 3600
end
local minutes = 0
while (time > 59) do
minutes = minutes + 1
time = time - 60
end
if (days == 0) then
if (hours == 0) then
return doubleDigit(minutes) .. ":" .. doubleDigit(time)
else
return math.floor(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
else
return math.floor(days) ..
" : " .. doubleDigit(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
end
function update()
if (state == 0) then
TextColor = {r = 255, g = 0, b = 0, a = 255}
TimerText = "00:00"
elseif (state == 1) then
TimerText = timeText(os.time() - startTime)
TextColor = {r = 0, g = 255, b = 255, a = 255}
elseif (state == 2) then
TimerText = timeText(stopTime - startTime)
TextColor = {r = 255, g = 255, b = 0, a = 255}
end
end
function render()
local font = gui.font()
local tw = font.width(TimerText)
gfx.color(0, 0, 0, 0)
gfx.rect(0, 0, tw + 4, 10)
gfx.color(TextColor.r, TextColor.g, TextColor.b, TextColor.a)
gfx.text(2, 1, TimerText)
end

It looks like you are saving the Unix Timestamp to your file, you can try and make it human readable using an online time converter (https://time.is/Unix_time_converter)
Besides this, take some time to read the os.time() implementation details on this lua page: https://www.lua.org/pil/22.1.html
The time function, when called without arguments, returns the current date and time, coded as a number. (In most systems, that number is the number of seconds since some epoch.)
If you want the time in between certain action, save the initial timestamp and diff it at the end of the action. This is natively supported in lua using os.difftime(). (http://www.lua.org/manual/5.3/manual.html#pdf-os.difftime)

Related

Object Shell.Application Open Folder In Same Explorer Window

I want to ask you a question regarding Shell.Application COM Object. The programming language I work in is AutoIT. I would like to know, how can I open a folder in the exact same Window a previous folder has been opened.
For instance, if I open the C:\Folder in a Window and it has a subfolder, then how can I make the Script open that subfolder in the same window the "parent folder" has been opened, without creating a new window for that. The only way I can open a Folder is like this:
global $ShellApplication = ObjCreate("Shell.Application")
$ShellApplication.Explore("C:\Folder")
Sleep(100)
$ShellApplication.Explore("C:\Folder\Subfolder")
but this way is the wrong way. I hope someone has got any idea about how this could be achieved.
I don't know whether this is what you want, but you can automate the current window like this:
#include <Array.au3>
Opt("SendKeyDelay", 1) ;5 milliseconds
Opt("SendKeyDownDelay", 1) ;1 millisecond
$pid = ShellExecute("explorer.exe ", #DesktopDir)
Sleep(300)
;~ $aWinList=WinList("[REGEXPCLASS:(Explore|Cabinet)WClass]")
;~ _ArrayDisplay($aWinList)
ConsoleWrite($pid & #CRLF)
$handle = _WinGetHandleByPID($pid)
Sleep(2000)
SendKeepActive($handle)
Send('{F4}')
Send('^a')
Send(#AppDataCommonDir & "{ENTER}")
Func _WinGetHandleByPID($vProcess, $nShow = 1)
; Get Window Handle by PID
; Author Hubertus
; derived from Smoke_N's script with the same name,
; but to handle more than one process with the same name
; and to return handle of newest window ($nShow = 2).
;
; $vProcess = Processname(e.g. "Notepad.exe") or Processnumber(e.g. 4711 )
; $nShow = -1 "All (Visble or not)", $nShow = 0 "Not Visible Only", $nShow = 1 "Visible Only", $nShow = 2 "return handle of newest window "
; #error = 0 Returns array of matches. Array[0][0] and #extended shows number of matches.
; #error = 0 and $nShow = 2 return handle of newest window
; Array[n][0] shows windows title. Array[n][1] shows windows handle. n = 1 to #extended
; #error = 1 Process not found.
; #error = 2 Window not found.
If Not ProcessExists($vProcess) Then Return SetError(1, 0, 0) ; no matching process
Local $iWinList, $aWinList = WinList()
Local $iResult, $aResult[UBound($aWinList)][2]
Local $iProcessList, $aProcessList = ProcessList($vProcess)
If $aProcessList[0][0] = 0 Then Local $aProcessList[2][2] = [[1, 0], ["", $vProcess]]
For $iWinList = 1 To $aWinList[0][0]
For $iProcessList = 1 To $aProcessList[0][0]
If WinGetProcess($aWinList[$iWinList][1]) = $aProcessList[$iProcessList][1] Then
If $nShow > -1 And Not $nShow = (2 = BitAND(WinGetState($aWinList[$iWinList][1]), 2)) Then ContinueLoop
$iResult += 1
$aResult[$iResult][0] = $aWinList[$iWinList][0]
$aResult[$iResult][1] = $aWinList[$iWinList][1]
EndIf
Next
Next
If $iResult = 0 Then Return SetError(2, 0, 0) ; no window found
ReDim $aResult[$iResult + 1][2]
$aResult[0][0] = $iResult
If $nShow = 2 Then Return SetError(0, $iResult, $aResult[1][1])
Return SetError(0, $iResult, $aResult)
EndFunc ;==>_WinGetHandleByPID

Loss function in chainer remains zero

Im using chainer and im try to do topic modeling. The code for the training phase contains the following:
optimizer = O.Adam()
optimizer.setup(self.train_model)
clip = chainer.optimizer.GradientClipping(5.0)
optimizer.add_hook(clip)
j = 0
msgs = defaultdict(list)
for epoch in range(epochs):
print "epoch : ",epoch
data = prepare_topics(cuda.to_cpu(self.train_model.mixture.weights.W.data).copy(),
cuda.to_cpu(self.train_model.mixture.factors.W.data).copy(),
cuda.to_cpu(self.train_model.sampler.W.data).copy(),
self.words)
top_words = print_top_words_per_topic(data)
if j % 100 == 0 and j > 100:
coherence = topic_coherence(top_words)
for j in range(self.n_topics):
print j, coherence[(j, 'cv')]
kw = dict(top_words=top_words, coherence=coherence, epoch=epoch)
data['doc_lengths'] = self.doc_lengths
data['term_frequency'] = self.term_frequency
for d, f in utils.chunks(self.batchsize, self.doc_ids, self.flattened):
t0 = time.time()
self.train_model.cleargrads()
l = self.train_model.fit_partial(d.copy(), f.copy(), update_words = update_words, update_topics = update_topics)
prior = self.train_model.prior()
loss = prior * self.fraction
loss.backward()
optimizer.update()
msg = ("J:{j:05d} E:{epoch:05d} L:{loss:1.3e} "
"P:{prior:1.3e} R:{rate:1.3e}")
prior.to_cpu()
loss.to_cpu()
t1 = time.time()
dt = t1 - t0
rate = self.batchsize / dt
msgs["E"].append(epoch)
msgs["L"].append(float(l))
j += 1
logs = dict(loss=float(l), epoch=epoch, j=j, prior=float(prior.data), rate=rate)
print msg.format(**logs)
print "\n ================================= \n"
#serializers.save_hdf5("lda2vec.hdf5", self.model)
msgs["loss_per_epoch"].append(float(l))
whn i execute the code i get for example:
J:00200 E:00380 L:0.000e+00 P:-2.997e+04 R:2.421e+04
only the L(loss) dont change, can someone please help to know why this value remain zero?

NameError: global name 'key_str' is not defined

in below script i am getting the error
if not any(d['KEY'] == key_str for d in records):
NameError: global name 'key_str' is not defined
I am transposing a input file set of columns to rows and rows to columns.
please help:
if "Sales-Target" in fdmContext["LOCNAME"]:
filename = fdmContext["FILENAME"]
dim_cols = 7
period_dim_index = 0
input_filename = (os.path.abspath("E:/FDMEE/")+"\%s" % filename)
months = ['M%s' % x for x in range(1,13)]
first_row = True
headers = []
records = []
output_filename = "%s_out.%s" % (input_filename.split(".")[0],input_filename.split(".")[1])
input_f = open(input_filename)
for line in input_f:
if first_row:
headers = line.split(",")
headers = [x.rstrip() for x in headers]
else:
data = line.split(",")
for i in range(dim_cols,len(headers)):
key = data[:dim_cols]
del key[period_dim_index]
key.append(headers[i])
key_str = "_".join(key)
if not any(d['KEY'] == key_str for d in records):
record = {}
record["ACCOUNT"] = headers[i]
record["KEY"] = key_str
record["PERIODS"] = {}
for j in range(0,dim_cols):
if j == period_dim_index:
record["PERIODS"][data[j]] = data[i].rstrip()
else:
record[headers[j]] = data[j]
records.append(record)
else:
record = (d for d in records if d["KEY"] == key_str).next()
record["PERIODS"][data[period_dim_index]] = data[i].rstrip()
first_row = False
input_f.close()
output_f = open(output_filename,"w")
row=[]
[row.append(x) for x in headers[:dim_cols] if headers.index(x) != period_dim_index]
row.append("ACCOUNT")
[row.append(x) for x in months]
output_f.write("%s\n" % ",".join(row))
for record in records:
row = [record[x] for x in headers[:dim_cols] if headers.index(x) != period_dim_index]
row.append(record["ACCOUNT"])
for month in months:
if month in record["PERIODS"].keys():
row.append(record["PERIODS"][month])
else:
row.append("0")
output_f.write("%s\n" % ",".join(row))
output_f.close()

winhttp.winhttprequest.5.1 with progress bar

It is possible, in AU3, use WinHttp.WinHttpRequest.5.1 with a progress bar? Actually what I need is to know how many MB have already been downloaded.
I need to use "WinHttp.WinHttpRequest.5.1" because I have to use the parameter "Referer" in the header.
Of course it is
#include "WinHttp.au3"
; Download some gif
;~ http://33.media.tumblr.com/dd3ffab90cc338666f192fd86f6a4f8f/tumblr_n0pefhIpss1swyb6ao1_500.gif
; Initialize and get session handle
$hOpen = _WinHttpOpen()
; Get connection handle
$hConnect = _WinHttpConnect($hOpen, "http://33.media.tumblr.com")
; Specify the reguest
$hRequest = _WinHttpOpenRequest($hConnect, Default, "dd3ffab90cc338666f192fd86f6a4f8f/tumblr_n0pefhIpss1swyb6ao1_500.gif")
; Send request
_WinHttpSendRequest($hRequest)
; Wait for the response
_WinHttpReceiveResponse($hRequest)
;~ ConsoleWrite(_WinHttpQueryHeaders($hRequest) & #CRLF)
ProgressOn("Downloading", "In Progress...")
Progress(_WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_LENGTH))
Local $sData
; Check if there is data available...
If _WinHttpQueryDataAvailable($hRequest) Then
While 1
$sChunk = _WinHttpReadData_Ex($hRequest, Default, Default, Default, Progress)
If #error Then ExitLoop
$sData &= $sChunk
Sleep(20)
WEnd
Else
MsgBox(48, "Error", "Site is experiencing problems (or you).")
EndIf
Sleep(1000)
ProgressOff()
; Close handles
_WinHttpCloseHandle($hRequest)
_WinHttpCloseHandle($hConnect)
_WinHttpCloseHandle($hOpen)
; Do whatever with data, write to some file or whatnot. I'll just print it to console here:
ConsoleWrite($sData & #CRLF)
Local $hFile = FileOpen(#DesktopDir & "\test.gif", 26)
FileWrite($hFile, $sData)
FileClose($hFile)
Func Progress($iSizeAll, $iSizeChunk = 0)
Local Static $iMax, $iCurrentSize
If $iSizeAll Then $iMax = $iSizeAll
$iCurrentSize += $iSizeChunk
Local $iPercent = Round($iCurrentSize / $iMax * 100, 0)
ProgressSet($iPercent, $iPercent & " %")
EndFunc
Func _WinHttpReadData_Ex($hRequest, $iMode = Default, $iNumberOfBytesToRead = Default, $pBuffer = Default, $vFunc = Default)
__WinHttpDefault($iMode, 0)
__WinHttpDefault($iNumberOfBytesToRead, 8192)
__WinHttpDefault($vFunc, 0)
Local $tBuffer, $vOutOnError = ""
If $iMode = 2 Then $vOutOnError = Binary($vOutOnError)
Switch $iMode
Case 1, 2
If $pBuffer And $pBuffer <> Default Then
$tBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]", $pBuffer)
Else
$tBuffer = DllStructCreate("byte[" & $iNumberOfBytesToRead & "]")
EndIf
Case Else
$iMode = 0
If $pBuffer And $pBuffer <> Default Then
$tBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]", $pBuffer)
Else
$tBuffer = DllStructCreate("char[" & $iNumberOfBytesToRead & "]")
EndIf
EndSwitch
Local $sReadType = "dword*"
If BitAND(_WinHttpQueryOption(_WinHttpQueryOption(_WinHttpQueryOption($hRequest, $WINHTTP_OPTION_PARENT_HANDLE), $WINHTTP_OPTION_PARENT_HANDLE), $WINHTTP_OPTION_CONTEXT_VALUE), $WINHTTP_FLAG_ASYNC) Then $sReadType = "ptr"
Local $aCall = DllCall($hWINHTTPDLL__WINHTTP, "bool", "WinHttpReadData", _
"handle", $hRequest, _
"struct*", $tBuffer, _
"dword", $iNumberOfBytesToRead, _
$sReadType, 0)
If #error Or Not $aCall[0] Then Return SetError(1, 0, "")
If Not $aCall[4] Then Return SetError(-1, 0, $vOutOnError)
If IsFunc($vFunc) Then $vFunc(0, $aCall[4])
If $aCall[4] < $iNumberOfBytesToRead Then
Switch $iMode
Case 0
Return SetExtended($aCall[4], StringLeft(DllStructGetData($tBuffer, 1), $aCall[4]))
Case 1
Return SetExtended($aCall[4], BinaryToString(BinaryMid(DllStructGetData($tBuffer, 1), 1, $aCall[4]), 4))
Case 2
Return SetExtended($aCall[4], BinaryMid(DllStructGetData($tBuffer, 1), 1, $aCall[4]))
EndSwitch
Else
Switch $iMode
Case 0, 2
Return SetExtended($aCall[4], DllStructGetData($tBuffer, 1))
Case 1
Return SetExtended($aCall[4], BinaryToString(DllStructGetData($tBuffer, 1), 4))
EndSwitch
EndIf
EndFunc
You here find the WinHTTP.au3 here: https://github.com/dragana-r/autoit-winhttp/releases.
It is my favorite UDF!
I have comments all around the code to explain you the process.

Relative date/time for classic ASP

Does anyone have a relative date/time from now to a natural/human for classic ASP function in VBScript? This is like Twitter.
Examples:
Less than 1 minute ago
About 5 minutes ago
About an hour ago
About 3 hours ago
Yesterday
Wednesday
etc.
This is the one I use. Pretty certain I just ripped it from Jeff's example that he used for this site.
Yes, yes I did: How can I calculate relative time in C#?
Function RelativeTime(dt)
Dim t_SECOND : t_SECOND = 1
Dim t_MINUTE : t_MINUTE = 60 * t_SECOND
Dim t_HOUR : t_HOUR = 60 * t_MINUTE
Dim t_DAY : t_DAY = 24 * t_HOUR
Dim t_MONTH : t_MONTH = 30 * t_DAY
Dim delta : delta = DateDiff("s", dt, Now)
Dim strTime : strTime = ""
If (delta < 1 * t_MINUTE) Then
If delta = 0 Then
strTime = "just now"
ElseIf delta = 1 Then
strTime = "one second ago"
Else
strTime = delta & " seconds ago"
End If
ElseIf (delta < 2 * t_MINUTE) Then
strTime = "a minute ago"
ElseIf (delta < 50 * t_MINUTE) Then
strTime = Max(Round(delta / t_MINUTE), 2) & " minutes ago"
ElseIf (delta < 90 * t_MINUTE) Then
strTime = "an hour ago"
ElseIf (delta < 24 * t_HOUR) Then
strTime = Round(delta / t_HOUR) & " hours ago"
ElseIf (delta < 48 * t_HOUR) Then
strTime = "yesterday"
ElseIf (delta < 30 * t_DAY) Then
strTime = Round(delta / t_DAY) & " days ago"
ElseIf (delta < 12 * t_MONTH) Then
Dim months
months = Round(delta / t_MONTH)
If months <= 1 Then
strTime = "one month ago"
Else
strTime = months & " months ago"
End If
Else
Dim years : years = Round((delta / t_DAY) / 365)
If years <= 1 Then
strTime = "one year ago"
Else
strTime = years & " years ago"
End If
End If
RelativeTime = strTime
End Function
taken from ajaxed
'here comes some global helpers...
public function sayDate(dat, mode, relativNotation)
if not isDate(dat) then
sayDate = "unknown"
exit function
end if
if relativNotation then
diff = dateDiff("s", dat, now())
if diff <= 10 and diff >= 0 then
sayDate = "Just now" : exit function
elseif diff < 60 and diff >= 0 then
sayDate = diff & " seconds ago" : exit function
elseif diff = 60 and diff >= 0 then
sayDate = diff & " minute ago" : exit function
elseif diff <= 1800 and diff >= 0 then
sayDate = int(diff / 60) & " minutes ago" : exit function
elseif diff < 86400 and diff >= 0 then
sayDate = plural(int(diff / 60 / 60), "hour", empty) & " ago"
else
if datevalue(dat) = date() then
sayDate = "Today"
elseif dateValue(dat) = dateAdd("d", 1, date()) then
sayDate = "Tomorrow"
elseif dateValue(dat) = dateAdd("d", -1, date()) then
sayDate = "Yesterday"
end if
end if
end if
if relativNotation and lCase(mode) = "datetime" and isEmpty(sayDate) then
diff = dateDiff("d", dat, now())
sayDate = plural(diff, "day", empty) & " ago"
exit function
end if
if isEmpty(sayDate) then
sayDate = day(dat) & ". " & monthname(month(dat), true)
if year(dat) <> year(now()) then sayDate = sayDate & " " & year(dat)
end if
if lCase(mode) <> "datetime" then exit function
if uBound(split(dat, " ")) <= 0 then exit function
'sayDate = sayDate & ", " & str.padLeft(hour(dat), 2, "0") & ":" & str.padLeft(minute(dat), 2, "0")
end function
public function plural(val, singularform, pluralform)
plural = singularform
if val <> 1 then plural = pluralform
if isEmpty(plural) then plural = singularform & "s"
plural = val & " " & plural
end function
I write my own function like this, could be found at http://asp.web.id/asp-classic-relative-date-function.html
it is used conversion asp date to unixtimestamp format and calculate the time margin. it is customizable you could also create relative date for upcoming date using this function.
DateAdd("n", -1, Now)
DateAdd("n", -5, Now)
DateAdd("h", -1, Now)
DateAdd("h", -3, Now)
DateAdd("d", -1, Date)
DateAdd("d", -1, Date)
Not sure about what you mean by Wednesday part.
Can you elaborate?

Resources