code hangs up after some period while comparing datetime - datetime
I have the following code which hangs after some period while comparing datetime. Following is my code.
def worker():
flag = True
while True:
s1 = '101:35:00'
e1 = '101:36:00'
s2 = '101:37:00'
e2 = '101:38:00'
s3 = '101:39:00'
e3 = '101:40:00'
if int(s1[0]) == 1:
start1 = str(datetime.datetime.now().date()) + ' ' + s1[1:9]
else:
start1 = str(datetime.datetime.now().date() + datetime.timedelta(days=1)) + ' ' + s1[1:9]
if int(s2[0]) == 1:
start2 = str(datetime.datetime.now().date()) + ' ' + s2[1:9]
else:
start2 = str(datetime.datetime.now().date() + datetime.timedelta(days=1)) + ' ' + s2[1:9]
if int(s3[0]) == 1:
start3 = str(datetime.datetime.now().date()) + ' ' + s3[1:9]
else:
start3 = str(datetime.datetime.now().date() + datetime.timedelta(days=1)) + ' ' + s3[1:9]
if int(e1[0]) == 1:
end1 = str(datetime.datetime.now().date()) + ' ' + e1[1:9]
else:
end1 = str(datetime.datetime.now().date() + datetime.timedelta(days=1)) + ' ' + e1[1:9]
if int(e2[0]) == 1:
end2 = str(datetime.datetime.now().date()) + ' ' + e2[1:9]
else:
end2 = str(datetime.datetime.now().date() + datetime.timedelta(days=1)) + ' ' + e2[1:9]
if int(e3[0]) == 1:
end3 = str(datetime.datetime.now().date()) + ' ' + e3[1:9]
else:
end3 = str(datetime.datetime.now().date() + datetime.timedelta(days=1)) + ' ' + e3[1:9]
s1t = datetime.datetime.strptime(start1, '%Y-%m-%d %H:%M:%S')
s2t = datetime.datetime.strptime(start2, '%Y-%m-%d %H:%M:%S')
s3t = datetime.datetime.strptime(start3, '%Y-%m-%d %H:%M:%S')
e1t = datetime.datetime.strptime(end1, '%Y-%m-%d %H:%M:%S')
e2t = datetime.datetime.strptime(end2, '%Y-%m-%d %H:%M:%S')
e3t = datetime.datetime.strptime(end3, '%Y-%m-%d %H:%M:%S')
cur = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
curr = datetime.datetime.strptime(cur, '%Y-%m-%d %H:%M:%S')
if e1t < curr <= s2t or e2t < curr <= s3t:
flag = False
else: pass
while not flag:
print 'iwashereghgj'
print str(curr) #line1
if s2t <= curr < e2t or s3t <= curr < e3t:
q1.put(True)
flag = True
else:
flag = True
For example in this case the code just hangs up after curr reaches '2014-01-06 01:37:00' at line1. Anyone can help me out why it is happening like this?
All of that duplication makes your code very difficult to debug. Start with some encapsulation:
def process_time(timestring):
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)
h, m, s = map(int, timestring[1:9].split(':'))
time = datetime.time(hour=h, minute=m, second=s)
if timestring[0] == '1':
return datetime.datetime.combine(today, time)
return datetime.datetime.combine(tomorrow, time)
Now it is clear what the function is actually doing and you can skip straight to
s1t = process_time(s1) # and so on
Plus it feels like you could shorten
cur = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
curr = datetime.datetime.strptime(cur, '%Y-%m-%d %H:%M:%S')
to
curr = datetime.datetime.now()
As for your problem, it's that you don't update curr in your loop, so it remains the time at which you started doing your task. You need to keep checking the current time.
To implement:
# process time strings once, outside loop
timeslots = [(s1t, e1t), ...]
while True:
## starting = True
while any(s <= datetime.datetime.now() < e for s, e in timeslots):
## if starting:
## print("Starting:", datetime.datetime.now())
## starting = False
q1.put(True) # do task in timeslots
if all(datetime.datetime.now() >= e for s, e in timeslots):
## print("All timeslots done:", datetime.datetime.now())
break
# whatever happens afterwards
Note: lines starting ## are for demo purposes, leave commented out for "production" use.
Related
Script Math's not correct lua minecraft
idk what is wrong but it writes this into the file when it saves the value. If u need more information or have a question please ask me! Thanks for your time and hopefully u your solution! SebyGHG My discord: S̸̽̚e̵̓̓b̸̿̕y̴͆͐#4638 Here is a screenshot of the time and the value in the file: Value in file Time in game Code: 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() 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 - 86400 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
One error I spot is this part while (time > 3599) do hours = hours + 1 time = time - 86400 end this is most likely supposed to be while (time > 3599) do hours = hours + 1 time = time - 3600 end
How can I use last-of in a QUERY-PREPARE()?
I made a huge code and it was taking a very long time to process. Following suggestions here, I made it shorter and better and now it's running much faster. However, I noticed I should be getting a sum of the values whereas I'm just getting the values. I tried using ACCUMULATE TOTAL, but it didn't work because the LAST-OF can only be used with a BREAK BY and my break by is inside the QUERY-PREPARE(). How can I get the sum of the following values? doc-fiscal.vl-cont-doc doc-fiscal.vl-bicms doc-fiscal.vl-icms doc-fiscal.vl-icmsou doc-fiscal.vl-ipiou doc-fiscal.vl-ipi Bellow is the code I'm using, which is working almost perfectly. //Query cQuery = "FOR EACH doc-fiscal WHERE doc-fiscal.dt-docto >= " + QUOTER(pd-data-1) + " AND doc-fiscal.dt-docto <= " + QUOTER(pd-data-2) + " AND (doc-fiscal.cod-observa <> 4 OR doc-fiscal.tipo-nat <> 3) AND doc-fiscal.cd-situacao <> 06 AND doc-fiscal.cd-situacao <> 22". cQuery = cQuery + semCodEmitente + comCodEmitente + CheckBoxindSitDoc. cQuery = cQuery + ", EACH natur-oper USE-INDEX natureza WHERE doc-fiscal.nat-operacao = natur-oper.nat-operacao" + modeloEletronico + tipoEntrada + natOper. cQuery = cQuery + " BREAK BY doc-fiscal.dt-docto BY doc-fiscal.nr-doc-fis ". QUERY qRelatorio:QUERY-PREPARE(cQuery). QUERY qRelatorio:QUERY-OPEN(). GET FIRST qRelatorio. DEF VAR soma-vl-cont-doc AS DECIMAL. DO WHILE AVAILABLE doc-fiscal: soma-vl-cont-doc = soma-vl-cont-doc + doc-fiscal.vl-cont-doc. IF LAST-OF(doc-fiscal.nr-doc-fis) THEN DO: CREATE tt-relatorio. ASSIGN tt-relatorio.nr-doc-fis = doc-fiscal.nr-doc-fis tt-relatorio.serie = doc-fiscal.serie tt-relatorio.char-2 = SUBSTRING(doc-fiscal.char-2,155,44, "CHAR") tt-relatorio.cod-model-nf-eletro = natur-oper.cod-model-nf-eletro tt-relatorio.tipo = natur-oper.tipo tt-relatorio.cod-estabel = doc-fiscal.cod-estabel tt-relatorio.cod-emitente = doc-fiscal.cod-emitente tt-relatorio.nome-ab-emi = doc-fiscal.nome-ab-emi tt-relatorio.cgc = doc-fiscal.cgc tt-relatorio.dt-emis-doc = doc-fiscal.dt-emis-doc tt-relatorio.dt-docto = doc-fiscal.dt-docto tt-relatorio.ind-sit-doc = doc-fiscal.ind-sit-doc tt-relatorio.vl-cont-doc = doc-fiscal.vl-cont-doc tt-relatorio.vl-bicms = doc-fiscal.vl-bicms tt-relatorio.vl-icms = doc-fiscal.vl-icms tt-relatorio.vl-icmsou = doc-fiscal.vl-icmsou tt-relatorio.vl-ipiou = doc-fiscal.vl-ipiou tt-relatorio.vl-ipi = doc-fiscal.vl-ipi tt-relatorio.imp-nota = natur-oper.imp-nota. GET NEXT qRelatorio. END. END. QUERY qRelatorio:QUERY-CLOSE(). Thanks for the help and sorry for being such a newbie. I hope my question can help other people.
I managed to do it. I used LAST-OF() METHOD. My code became the following. DEF VAR soma-vl-cont-doc AS DECIMAL. //INICIO DAS SOMAS DEF VAR soma-vl-bicms AS DECIMAL. DEF VAR soma-vl-icms AS DECIMAL. DEF VAR soma-vl-icmsou AS DECIMAL. DEF VAR soma-vl-ipiou AS DECIMAL. DEF VAR soma-vl-ipi AS DECIMAL. DO WHILE AVAILABLE doc-fiscal: soma-vl-cont-doc = soma-vl-cont-doc + doc-fiscal.vl-cont-doc. soma-vl-bicms = soma-vl-bicms + doc-fiscal.vl-bicms. soma-vl-icms = soma-vl-icms + doc-fiscal.vl-icms. soma-vl-icmsou = soma-vl-icmsou + doc-fiscal.vl-icmsou. soma-vl-ipiou = soma-vl-ipiou + doc-fiscal.vl-ipiou. soma-vl-ipi = soma-vl-ipi + doc-fiscal.vl-ipi. IF QUERY qRelatorio:LAST-OF(2) THEN DO: CREATE tt-relatorio. ASSIGN tt-relatorio.nr-doc-fis = doc-fiscal.nr-doc-fis tt-relatorio.serie = doc-fiscal.serie tt-relatorio.char-2 = SUBSTRING(doc-fiscal.char-2,155,44, "CHAR") tt-relatorio.cod-model-nf-eletro = natur-oper.cod-model-nf-eletro tt-relatorio.tipo = natur-oper.tipo tt-relatorio.cod-estabel = doc-fiscal.cod-estabel tt-relatorio.cod-emitente = doc-fiscal.cod-emitente tt-relatorio.nome-ab-emi = doc-fiscal.nome-ab-emi tt-relatorio.cgc = doc-fiscal.cgc tt-relatorio.dt-emis-doc = doc-fiscal.dt-emis-doc tt-relatorio.dt-docto = doc-fiscal.dt-docto tt-relatorio.ind-sit-doc = doc-fiscal.ind-sit-doc tt-relatorio.vl-cont-doc = soma-vl-cont-doc tt-relatorio.vl-bicms = soma-vl-bicms tt-relatorio.vl-icms = soma-vl-icms tt-relatorio.vl-icmsou = soma-vl-icmsou tt-relatorio.vl-ipiou = soma-vl-ipiou tt-relatorio.vl-ipi = soma-vl-ipi //tt-relatorio.idi-sit-nf-eletro = nota-fiscal.idi-sit-nf-eletro tt-relatorio.imp-nota = natur-oper.imp-nota. soma-vl-cont-doc = 0. soma-vl-bicms = 0. soma-vl-icms = 0. soma-vl-icmsou = 0. soma-vl-ipiou = 0. soma-vl-ipi = 0. END. GET NEXT qRelatorio. END. With this, I managed to get the answers I wanted andthe query is quite fast. If there's any suggestions as to how make it faster, I'm open for them. Thanks.
How to validate Google Recaptcha 2.0 server side in ASP Classic?
I need help to implement the answer Google Recaptcha 2.0. I've tried a few ways to recover the response after sending the form but not consigui get the answer True. Follows the example I'm trying: <%#LANGUAGE=VBSCRIPT%> <% Option Explicit %> <html> <head> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </head> <body> <% If Request.ServerVariables("REQUEST_METHOD") = "POST" Then Dim recaptcha_secret, sendstring, objXML ' Secret key recaptcha_secret = "xxxxxxxxxxsec" sendstring = "https://www.google.com/recaptcha/api/siteverify?secret=" & recaptcha_secret & "&response=" & Request.form("g-recaptcha-response") Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP") objXML.Open "GET", sendstring, False objXML.Send Response.write "<br><h3>Response: " & objXML.responseText & "</h3><br>" Set objXML = Nothing END If %> <form method="post" action=""> <!-- Site key --> <div class="g-recaptcha" data-sitekey="xxxxxxxxxx"></div> <br /> <input type="submit" value="Try"> </form> </body> </html> How do I implement a way to check that Recaptcha were marked?
finally found it after so many search i found it first i use this asp class https://github.com/zhennanzhuce/js/blob/master/js/ueditor/1.4.3/asp/ASPJson.class.asp then to validate the response i use this result = (objXML.responseText) Set oJSON = New aspJSON oJSON.loadJSON(result) Set objXML = Nothing success = oJSON.data("success") if success = "True" then action = "go to next page" else action = "" end if now the used code is : <%#LANGUAGE=VBSCRIPT%> <% Option Explicit %> <html> <head> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </head> <body> <!-- #include file="aspJSON.asp"--> <% If Request.ServerVariables("REQUEST_METHOD") = "POST" Then Dim recaptcha_secret, sendstring, objXML ' Secret key recaptcha_secret = "XXXCCCXXXX" sendstring = "https://www.google.com/recaptcha/api/siteverify?onload=onloadCallback&render=explicit&secret=" & recaptcha_secret & "&response=" & Request.form("g-recaptcha-response") Set objXML = Server.CreateObject("MSXML2.ServerXMLHTTP") objXML.Open "GET", sendstring, False objXML.Send dim result, oJSON, success, action, errorCapatcha, errorMsg result = (objXML.responseText) Set oJSON = New aspJSON oJSON.loadJSON(result) Set objXML = Nothing success = oJSON.data("success") if success = "True" then action = "go to next page" else action = "do nothing" end if END If %> <form method="post" action=""> <!-- Site key --> <div class="g-recaptcha" data-sitekey="XXXXXXXXX"></div> <br /> <input type="submit" value="Try"> </form> </body> Many Thanks to Lankymart, Leonardo Duarte
First download json.asp https://github.com/tugrul/aspjson insert in page <script language="javascript" runat="server" src="json2.asp"></script> in return do so If success(objXML.responseText) = True Then Response.write "success" Elseif success(objXML.responseText) = False Then Response.write "failure" End If call the function to get the json Function success(result) Set motor = JSON.parse(result) success = motor.success Set motor = Nothing End Function
There is a better way and stand alone captcha for ASP instead google captcha. You don't need to add JSON function. Here is the code: On your submit page, add: Type the number bellow:<br> <input type=text name="captchacode" value="" size=5 maxlength=5><br/> <img id="imgCaptcha" src="captcha.asp" /><br /> Refresh<br/> <script language="Javascript"> function RefreshImage(valImageId) { var objImage = document.images[valImageId]; if (objImage == undefined) { return; } var now = new Date(); objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString(); } </script> Insert the function bellow to your asp file: '******************************************************* function TestCaptcha(byval valSession, byval valCaptcha) '******************************************************* dim tmpSession valSession = Trim(valSession) valCaptcha = Trim(valCaptcha) if (valSession = vbNullString) or (valCaptcha = vbNullString) then TestCaptcha = false else tmpSession = valSession valSession = Trim(Session(valSession)) Session(tmpSession) = vbNullString if valSession = vbNullString then TestCaptcha = false else valCaptcha = Replace(valCaptcha,"i","I") if StrComp(valSession,valCaptcha,1) = 0 then TestCaptcha = true else TestCaptcha = false end if end if end if end function Save the code bellow to captcha.asp: <%#LANGUAGE="VBSCRIPT"%> <% 'ASP Security Image Generator v4.0 - 13/July/2008 'Generate images to make a CAPTCHA test '© 2006-2007 Emir Tüzül. All rights reserved. 'http://www.tipstricks.org 'This program is free software; you can redistribute it and/or 'modify it under the terms of the Common Public License 'as published by the Open Source Initiative OSI; either version 1.0 'of the License, or any later version. 'This program is distributed in the hope that it will be useful, 'but WITHOUT ANY WARRANTY; without even the implied warranty of 'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 'Common Public License for more details. '*[null pixel]Numbers[repeat count], #[text]Numbers[repeat count], &[row reference]number[referenced row index] 'First row [font height, chars...] 'Following rows [char width, pixel maps...] FontMap = Array(_ split("13,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9",",") ,_ split("14,*5#4*5,*4#6*4,&2,&2,*3#3*2#3*3,&5,*2#4*2#4*2,*2#3*4#3*2,*2#10*2,*1#12*1,*1#3*6#3*1,&11,#3*8#3",",") ,_ split("11,#8*3,#10*1,#3*4#3*1,&3,&3,&1,&2,#3*4#4,#3*5#3,&9,&8,&2,#9*2",",") ,_ split("11,*4#6*1,*2#9,*1#4*4#2,*1#3*6#1,#3*8,&5,&5,&5,&5,&4,&3,&2,&1",",") ,_ split("12,#8*4,#10*2,#3*4#4*1,#3*5#3*1,#3*6#3,&5,&5,&5,&5,&4,&3,&2,&1",",") ,_ split("9,#9,&1,#3*6,&3,&3,#8*1,&6,&3,&3,&3,&3,&1,&1",",") ,_ split("9,#9,&1,#3*6,&3,&3,&1,&1,&3,&3,&3,&3,&3,&3",",") ,_ split("13,*4#7,*2#11,*1#4*5#3,*1#3*8#1,#3,#3,#3*4#6,&7,#3*7#3,*1#3*6#3,*1#5*4#3,&2,&1",",") ,_ split("11,#3*5#3,&1,&1,&1,&1,#11,&6,&1,&1,&1,&1,&1,&1",",") ,_ split("7,#7,#7,*2#3,&3,&3,&3,&3,&3,&3,&3,&3,&1,&1",",") ,_ split("8,*2#6,&1,*5#3,&3,&3,&3,&3,&3,&3,&3,*4#4,#7,#6",",") ,_ split("12,#3*5#4,#3*4#4,#3*3#4,#3*2#4,#3*2#3,#3*1#3,#7,#8,&5,#3*3#3,#3*4#3,#3*5#3,&1",",") ,_ split("9,#3,#3,#3,#3,#3,#3,#3,#3,#3,#3,#3,#9,#9",",") ,_ split("13,#3*7#3,#4*5#4,&2,#5*3#5,&4,#6*1#6,#3*1#2*1#2*1#3,#3*1#5*1#3,#3*2#3*2#3,&9,#3*7#3,&11,&11",",") ,_ split("11,#4*4#3,#5*3#3,&2,#6*2#3,&4,#3*1#3*1#3,&6,#3*2#6,&8,#3*3#5,&10,#3*4#4,#3*5#3",",") ,_ split("13,*4#5,*2#9,*1#4*3#4,*1#3*5#3,#3*7#3,&5,&5,&5,&5,&4,&3,&2,&1",",") ,_ split("10,#8,#9,#3*3#4,#3*4#3,&4,&4,&3,&2,#7,#3,#3,#3,#3",",") ,_ split("13,*3#6,*2#8,*1#3*4#3,*1#2*6#2,#2*8#2,&5,&5,#2*4#1*3#2,#2*4#2*2#2,*1#2*4#4,&3,*2#10,*3#6*2#2",",") ,_ split("12,#8,#9,#3*4#3,&3,&3,#3*3#4,&2,&1,#3*2#4,#3*3#3,&3,#3*4#4,#3*5#4",",") ,_ split("11,*3#6,*1#9,#4*4#2,#3*6#1,#4,#8,&2,*3#8,*7#4,#1*7#3,#3*4#4,#10,*1#7",",") ,_ split("11,#11,&1,*4#3,&3,&3,&3,&3,&3,&3,&3,&3,&3,&3,&3",",") ,_ split("11,#3*5#3,&1,&1,&1,&1,&1,&1,&1,&1,&1,#4*3#4,*1#9,*3#5",",") ,_ split("14,#3*8#3,*1#3*6#3,&2,*1#3*5#4,*2#3*4#3,&5,*3#3*2#3,&7,&7,*4#6,&10,&10,*5#4",",") ,_ split("17,#3*4#3*4#3,&1,#3*3#5*3#3,*1#3*2#2*1#2*2#3,&4,*1#3*1#3*1#3*1#3,&6,*1#3*1#2*3#2*1#3,&8,*2#5*3#5,&10,*2#4*5#4,&12",",") ,_ split("14,#4*6#4,*1#4*4#4,*2#4*2#4,*3#3*2#3,*3#8,*4#6,*5#4,&6,&5,&4,&3,&2,&1",",") ,_ split("13,#4*5#4,*1#3*5#3,*2#3*3#3,*2#4*1#4,*3#3*1#3,*3#7,*4#5,*5#3,&8,&8,&8,&8,&8",",") ,_ split("10,#10,&1,*6#4,*5#4,*5#3,*4#3,*3#4,*3#3,*2#3,*1#4,#4,&1,&1",",") ,_ split("10,*3#4*3,*1#8*1,*1#3*2#3*1,#3*4#3,&4,&4,&4,&4,&4,&4,&3,&2,&1",",") ,_ split("9,*3#3*3,&1,#6*3,&3,*3#3*3,&5,&5,&5,&5,&5,&5,#9,&12",",") ,_ split("10,*1#6*3,#8*2,#2*3#4*1,#1*5#3*1,*6#3*1,&5,*5#3*2,*4#4*2,*3#4*3,*2#4*4,*1#4*5,#10,&12",",") ,_ split("11,*1#8*2,#10*1,#3*5#3,#1*7#3,*7#3*1,*3#6*2,*3#7*1,*7#4,*8#3,&4,#3*4#4,&2,*1#7*3",",") ,_ split("12,*6#4*2,*5#5*2,&2,*4#2*1#3*2,*3#3*1#3*2,*2#3*2#3*2,*1#3*3#3*2,#3*4#3*2,#12,&9,*7#3*2,&11,&11",",") ,_ split("11,*1#10,&1,*1#3*7,&3,*1#8*2,*1#9*1,*7#4,*8#3,&8,#1*7#3,#3*4#3*1,#10*1,*1#7*3",",") ,_ split("11,*4#6*1,*2#8*1,*1#4*6,*1#3*7,#3*1#5*2,#10*1,#3*4#4,#3*5#3,&8,&8,*1#3*3#3*1,*1#9*1,*3#5*3",",") ,_ split("11,#11,&1,*7#4,*7#3*1,*6#4*1,*6#3*2,*5#3*3,*4#4*3,*4#3*4,*3#4*4,*3#3*5,*2#3*6,*1#4*6",",") ,_ split("11,*2#7*2,*1#9*1,#3*4#4,#3*5#3,#4*3#3*1,*1#8*2,&1,*1#3*1#5*1,&4,&4,#4*3#4,&2,*2#6*3",",") ,_ split("11,*3#5*3,*1#9*1,*1#3*3#3*1,#3*5#3,&4,&4,#4*4#3,*1#10,*2#5*1#3,*7#3*1,*6#4*1,*1#8*2,*1#6*4",",") _ )'Previous row must end with _ '#Begin ColorMap const BmpColorMap = "dffeff000c851700eceeee006c363600da644a00" ColorMap = Array(_ split("00,01,01,03",",") ,_ split("02,03,03,01",",") ,_ split("00,04,04,02",",") _ )'End ColorMap '#Auto calculated variables dim ImageWidth, ImageHeight, arrTextWidth(), TextHeight, LeftMargin, arrTopMargin(), CursorPos dim BmpEndLine, BColor, TColor, NColor dim i, j, k, x, y '#Editable consts and variables dim Bitmap(40,200) '[Height,Width] const CodeLength = 5 'Secure code length (Max:8) const CodeType = 0 '0[Random numbers], 1[Random chars and numbers], 2[Fake word] const CharTracking = 35 'Set the tracking between two characters const RndTopMargin = true 'Randomize top margin every character const NoiseEffect = 0 '0[none], 1[sketch], 2[random foreground lines], 3[random background lines], 4[1 and 3 (Recommed maximum NoiseLine=4)] const NoiseLine = 3 'Low values make easy OCR, high values decrease readability const MinLineLength = 6 'Minimum noise line length const SessionName = "ASPCAPTCHA" 'Where store your secure code '#Subroutines and functions '***************************** function CreateGUID(valLength) '***************************** if CodeType = 1 then strValid = "A0B1C2D3E4F5G6H7I8J9K8L7M6N5O4P3Q2R1S0T1U2V3W4X5Y6Z7" else strValid = "0516273849" end if tmpGUID = vbNullString tmpChr = vbNullString Randomize(Timer) for cGUID=1 to valLength do tmpChr = Mid(strValid, Int(Rnd(1) * Len(strValid)) + 1, 1) loop while CStr(tmpChr) = CStr(Right(tmpGUID,1)) tmpGUID = tmpGUID & tmpChr Next CreateGUID = tmpGUID end function '*************************** function FakeWord(valLength) '*************************** arrChars = Array("AEIOU", "BCDFGHJKLMNPQRSTVWXYZ") cVowel = 0 cConsonant = 0 tmpWord = vbNullString Randomize(Timer) for cWord=1 to valLength if (cWord=2) or ((valLength > 1) and (cWord = valLength)) then ixChars = 1-ixChars elseif (cVowel < 2) and (cConsonant < 2) then ixChars = Int(Rnd(1) * 2) elseif (cVowel < 2) then ixChars = 0 elseif (cConsonant < 2) then ixChars = 1 end if Pattern = arrChars(ixChars) tmpWord = tmpWord & Mid(Pattern, Int(Rnd(1) * Len(Pattern)) + 1, 1) if ixChars = 0 then cVowel = cVowel + 1 cConsonant = 0 else cVowel = 0 cConsonant = cConsonant + 1 end if next FakeWord = tmpWord end function '********************************** function RndInterval(valMin,valMax) '********************************** Randomize(Timer) RndInterval = Int(((valMax - valMin + 1) * Rnd()) + valMin) end function '************************** function GetCharMap(valChr) '************************** dim i, j j = 0 for i=1 to UBound(FontMap(0)) if CStr(FontMap(0)(i)) = CStr(valChr) then j = i exit for end if next if j > 0 then GetCharMap = FontMap(j) else GetCharMap = Array(0) end if end function '************************************************ sub WriteCanvas(byval valChr, byval valTopMargin) '************************************************ dim i, j, k, curPos, tmpChr, arrChrMap, strPixMap, drawPixel, pixRepeat 'find char map arrChrMap = GetCharMap(valChr) if UBound(arrChrMap) < 1 then exit sub end if for i=1 to UBound(arrChrMap) 'get pixel map active line strPixMap = arrChrMap(i) if Left(strPixMap,1) = "&" then j = Mid(strPixMap,2) if (IsNumeric(j) = true) then strPixMap = arrChrMap(CInt(j)) else strPixMap = vbNullString end if end if strPixMap = Trim(strPixMap) 'drawing pixel curPos = CursorPos drawPixel = false pixRepeat = vbNullString for j=1 to Len(strPixMap) tmpChr = Mid(strPixMap,j,1) if (IsNumeric(tmpChr) = true) and (j < Len(strPixMap)) then pixRepeat = pixRepeat & tmpChr else 'end pixel map? if IsNumeric(tmpChr) = true then pixRepeat = pixRepeat & tmpChr end if 'draw pixel if (drawPixel = true) and (IsNumeric(pixRepeat) = true) then for k=1 to CInt(pixRepeat) curPos = curPos + 1 Bitmap((valTopMargin + i),curPos) = TColor next elseif IsNumeric(pixRepeat) = true then curPos = curPos + CInt(pixRepeat) end if 'what is new command? if tmpChr = "#" then drawPixel = true else drawPixel = false end if pixRepeat = vbNullString end if next next end sub '******************************* sub PrepareBitmap(valSecureCode) '******************************* dim i, j 'image dimensions ImageWidth = UBound(Bitmap,2) ImageHeight = UBound(Bitmap,1) 'char and text width redim arrTextWidth(CodeLength) arrTextWidth(0) = 0 for i=1 to CodeLength arrTextWidth(i) = CInt(GetCharMap(Mid(secureCode,i,1))(0)) arrTextWidth(0) = arrTextWidth(0) + arrTextWidth(i) next arrTextWidth(0) = arrTextWidth(0) + ((CodeLength - 1) * CharTracking) 'text height TextHeight = CInt(FontMap(0)(0)) 'left margin LeftMargin = Round((ImageWidth - arrTextWidth(0)) / 2) 'top margin redim arrTopMargin(CodeLength) arrTopMargin(0) = Round((ImageHeight - TextHeight) / 2) if RndTopMargin = true then for i=1 to CodeLength arrTopMargin(i) = RndInterval(Int(arrTopMargin(0) / 2),(arrTopMargin(0) + Round(arrTopMargin(0) / 2))) next else for i=1 to CodeLength arrTopMargin(i) = arrTopMargin(0) next end if 'color selection i = RndInterval(0,UBound(ColorMap)) BColor = ColorMap(i)(0) NColor = ColorMap(i)(1) TColor = ColorMap(i)(2) 'Apply background effect if NoiseEffect = 3 then AddNoise() end if 'write text for i=1 to CodeLength 'calculate cursor pos CursorPos = 0 for j=(i-1) to 1 step -1 CursorPos = CursorPos + arrTextWidth(j) + CharTracking next CursorPos = LeftMargin + CursorPos 'write active char WriteCanvas Mid(secureCode,i,1),arrTopMargin(i) next end sub '*********************************** sub DrawLine(x0, y0, x1, y1, valClr) '*********************************** 'Reference from Donald Hearn and M. Pauline Baker, Computer Graphics C Version dim m, b, dx, dy if (NoiseEffect = 4) and (Bitmap(y0,x0) = TColor) then clrNoise = vbNullString else clrNoise = valClr end if Bitmap(y0,x0) = clrNoise dx = x1 - x0 dy = y1 - y0 if Abs(dx) > Abs(dy) then m = (dy / dx) b = y0 - (m * x0) if dx < 0 then dx = -1 else dx = 1 end if do while x0 <> x1 x0 = x0 + dx if (NoiseEffect = 4) and (Bitmap(Round((m * x0) + b),x0) = TColor) then clrNoise = vbNullString else clrNoise = valClr end if Bitmap(Round((m * x0) + b),x0) = clrNoise loop elseif dy <> 0 then m = (dx / dy) b = x0 - (m * y0) if dy < 0 then dy = -1 else dy = 1 end if do while y0 <> y1 y0 = y0 + dy if (NoiseEffect = 4) and (Bitmap(y0,Round((m * y0) + b)) = TColor) then clrNoise = vbNullString else clrNoise = valClr end if Bitmap(y0,Round((m * y0) + b)) = clrNoise loop end if end sub '************* sub AddNoise() '************* dim median, i, j, x0, y0, x1, y1, dx, dy, dxy if NoiseEffect = 1 then clrNoise = vbNullString else clrNoise = NColor end if for i=1 to NoiseLine x0 = RndInterval(1,ImageWidth) y0 = RndInterval(1,ImageHeight) x1 = RndInterval(1,ImageWidth) y1 = RndInterval(1,ImageHeight) 'Check minimum line length dx = Abs(x1 - x0) dy = Abs(y1 - y0) median = Round(Sqr((dx * dx) + (dy * dy))/2) if median < MinLineLength then dxy = MinLineLength - median if x1 < x0 then dx = -1 else dx = 1 end if if y1 < y0 then dy = -1 else dy = 1 end if for j=1 to dxy if ((x1 + dx) < 1) or ((x1 + dx) > ImageWidth) or ((y1 + dy) < 1) or ((y1 + dy) > ImageHeight) then exit for end if x1 = x1 + dx y1 = y1 + dy next end if 'Draw noise line DrawLine x0,y0,x1,y1,clrNoise next end sub '***************************************************************** function FormatHex(byval valHex,byval fixByte,fixDrctn,valReverse) '***************************************************************** fixByte = fixByte * 2 tmpLen = Len(valHex) if fixByte > tmpLen then tmpFixHex = String((fixByte - tmpLen),"0") if fixDrctn = 1 then valHex = valHex & tmpFixHex else valHex = tmpFixHex & valHex end if end if if valReverse = true then tmpHex = vbNullString for cFrmtHex=1 to Len(valHex) step 2 tmpHex = Mid(valHex,cFrmtHex,2) & tmpHex next FormatHex = tmpHex else FormatHex = CStr(valHex) end if end function '****************** sub SendHex(valHex) '****************** for cHex = 1 to Len(valHex) step 2 Response.BinaryWrite ChrB(CByte("&H" & Mid(valHex,cHex,2))) next end sub '*************** sub SendBitmap() '*************** if (ImageWidth mod 4) <> 0 then BmpEndLine = String((4-(ImageWidth mod 4))*2,"0") else BmpEndLine = vbNullString end if BmpInfoHeader = Array("28000000","00000000","00000000","0100","0800","00000000","00000000","120B0000","120B0000","00000000","00000000") BmpInfoHeader(1) = FormatHex(Hex(ImageWidth),4,0,true) BmpInfoHeader(2) = FormatHex(Hex(ImageHeight),4,0,true) BmpInfoHeader(6) = FormatHex(Hex((ImageHeight * ImageWidth) + (ImageHeight * (Len(BmpEndLine) / 2))),4,0,true) BmpInfoHeader(9) = FormatHex(Hex(Len(BmpColorMap)/8),4,0,true) BmpInfoHeader(10) = BmpInfoHeader(9) BmpHeader = Array("424D","00000000","0000","0000","00000000") BmpHeader(1) = FormatHex(Hex((Len(Join(BmpHeader,"")) / 2) + (Len(Join(BmpInfoHeader,"")) / 2) + (Len(BmpColorMap) / 2) + (ImageHeight * ImageWidth) + (ImageHeight * (Len(BmpEndLine) / 2))),4,0,true) BmpHeader(4) = FormatHex(Hex((Len(Join(BmpHeader,"")) / 2) + (Len(Join(BmpInfoHeader,"")) / 2) + (Len(BmpColorMap) / 2)),4,0,true) Response.Clear Response.Buffer = True Response.ContentType = "image/bmp" Response.AddHeader "Content-Disposition", "inline; filename=captcha.bmp" Response.CacheControl = "no-cache" Response.AddHeader "Pragma", "no-cache" Response.Expires = -1 SendHex(Join(BmpHeader,"")) SendHex(Join(BmpInfoHeader,"")) SendHex(BmpColorMap) for y=ImageHeight to 1 step -1 for x=1 to ImageWidth tmpHex = Bitmap(y,x) if tmpHex = vbNullString then SendHex(BColor) else SendHex(tmpHex) end if next SendHex(BmpEndLine) next Response.Flush end sub '#Generate captcha if CodeType < 2 then secureCode = CreateGUID(CodeLength) else secureCode = FakeWord(CodeLength) end if Session(SessionName) = secureCode PrepareBitmap(secureCode) if (NoiseEffect > 0) and (NoiseEffect <> 3) then AddNoise() end if SendBitmap() %> Before process, validate the captcha: <% if not TestCaptcha("ASPCAPTCHA", request("captchacode")) then response.write "Captcha error!" response.end end if response.write "Captcha OK" '... process... %>
moment js bug : unexpected behavior when I select new timezone
Unexpected behavior I first select the timezone in drop-down when I press another timezone in select, the previous selected timezone are save. function run(){ var timeZone = document.getElementById("selectTimezone"); var i = timeZone.selectedIndex; var removeParenthesis = timeZone.options[i].text.replace(/[()]/g, '') var splitString = removeParenthesis.split(' ') var d = new Date('Nov 1, 2017 ' + ' ' + splitString[0]) var $clock = $('#clock'), eventTime = moment(d.getTime()).unix(), currentTime = moment(new Date().getTime()).unix(), diffTime = eventTime - currentTime, duration = moment.duration(diffTime * 1000, 'milliseconds'), interval = 1000; // if time to countdown if(diffTime > 0) { // Show clock // $clock.show(); setInterval(function(){ duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds'); var d = moment.duration(duration).days(), h = moment.duration(duration).hours(), m = moment.duration(duration).minutes(), s = moment.duration(duration).seconds(); d = $.trim(d).length === 1 ? '0' + d : d; h = $.trim(h).length === 1 ? '0' + h : h; m = $.trim(m).length === 1 ? '0' + m : m; s = $.trim(s).length === 1 ? '0' + s : s; // show how many hours, minutes and seconds are left $('.days').text(d + 'days'); $('.hours').text(h + 'hours'); $('.minutes').text(m + 'minutes'); $('.seconds').text(s + 'seconds'); }, interval); } } https://codepen.io/edward1995/pen/oGpMOq
Clear the interval before starting a new one var myInterval;// Used to save previous interval if one has been started function run(){ var timeZone = document.getElementById("selectTimezone"); var i = timeZone.selectedIndex; var removeParenthesis = timeZone.options[i].text.replace(/[()]/g, '') var splitString = removeParenthesis.split(' ') var d = new Date('Nov 1, 2017 ' + ' ' + splitString[0]) var $clock = $('#clock'), eventTime = moment(d.getTime()).unix(), currentTime = moment(new Date().getTime()).unix(), diffTime = eventTime - currentTime, duration = moment.duration(diffTime * 1000, 'milliseconds'), interval = 1000; // if time to countdown if(diffTime > 0) { // Show clock // $clock.show(); clearInterval(myInterval); myInterval = setInterval(function(){ duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds'); var d = moment.duration(duration).days(), h = moment.duration(duration).hours(), m = moment.duration(duration).minutes(), s = moment.duration(duration).seconds(); d = $.trim(d).length === 1 ? '0' + d : d; h = $.trim(h).length === 1 ? '0' + h : h; m = $.trim(m).length === 1 ? '0' + m : m; s = $.trim(s).length === 1 ? '0' + s : s; // show how many hours, minutes and seconds are left $('.days').text(d + 'days'); $('.hours').text(h + 'hours'); $('.minutes').text(m + 'minutes'); $('.seconds').text(s + 'seconds'); }, interval); } }
run-time error '5' maps.googleapis.com/maps/api/distancematrix
Yesterday, I ran the following script in excel and it worked, but now it throws an error: (run-time error '5' ) in the line: Distance = Mid(Distance, InStr(1, Distance, ">") + 1, InStr(1, Distance, " ") - InStr(1, Distance, ">") - 1) Sub Поиск_ближайшего_СБС() Set Points = Worksheets("Точки") Set SBS = Worksheets("СБС") Dim Cordinate11, Cordinate12, Cordinate21, Cordinate22 As String i = 2 Do While SBS.Cells(i, 1) <> Empty Rows_of_SBS = i i = i + 1 Loop i = 2 Do While Cells(i, 1) <> Empty Dist = 1000 Cordinate21 = Points.Cells(i + 1, 3) Cordinate22 = Points.Cells(i + 1, 4) For j = 2 To Rows_of_SBS Cordinate11 = SBS.Cells(j, 2) Cordinate12 = SBS.Cells(j, 3) Set IE = CreateObject("InternetExplorer.Application") IE.Visible = False With IE .Navigate "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" _ & Cordinate11 & ",+" & Cordinate12 _ & "&destinations=" _ & Cordinate21 & ",+" & Cordinate22 _ & "&mode=driving&language=ru&sensor=false" Do While .Busy DoEvents Loop For Each MyTable In .Document.getElementsByTagName("text") Distance = MyTable.innertext Next Distance = Mid(Distance, InStr(1, Distance, ">") + 1, InStr(1, Distance, " ") - InStr(1, Distance, ">") - 1) If CDbl(Distance) < Dist Then Dist = CDbl(Distance) s = j End If End With IE.Quit Set EI = Nothing Next j Points.Cells(i + 1, 5) = Dist Points.Cells(i + 1, 6) = SBS.Cells(s, 1) i = i + 1 Loop End Sub '