AS3 timer is faster than php - actionscript-3

Im trying too load new messages every second, but new messages are doubled everytime they are loaded, I suppose because the timer is completed before the php is executed?
so I tried to add
if (checker != "" + idstored + "done") {
checker = "" + idstored + "done";
so that once the timer completes, it changes the checker so that when the timer restarts and finishes again it would not execute again... but it stopped checking for all new messages... any tips??
var count:Timer = new Timer(1000, 1);
count.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
count.start();
var checker;
function onTimerComplete(event:TimerEvent):void{
if (checker != "" + idstored + "done") {
checker = "" + idstored + "done";
var variables_cc:URLVariables = new URLVariables();
var varSend_cc:URLRequest = new URLRequest("chat.php");
varSend_cc.method = URLRequestMethod.POST;
varSend_cc.data = variables_cc;
var varLoader_cc:URLLoader = new URLLoader;
varLoader_cc.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader_cc.addEventListener(Event.COMPLETE, completeHandler_cc);
function completeHandler_cc(event:Event):void{
if (event.target.data.statusline == "is_new") {
stored_id_txt.text = "" + event.target.data.stored_id;
status_txt.text = "" + event.target.data.statusline;
returnline.text = "" + event.target.data.returnBody;
checker.text = checker;
splitByDelimiter(event.target.data.returnBody);
idstored = event.target.data.stored_id;
checker = "refresh";
}
}}
// ready the last_refresh_time variable for sending to PHP
variables_cc.requester = "chat_check";
variables_cc.stored_id = idstored;
varLoader_cc.load(varSend_cc);
count.reset();
count.start();
}

You get errors becouse you sometimes try to start new download when the previous is not finished. It's not wise to do something latency dependent every 1 second real time. You need to start something, wait for it to finish, and then start it again.
removeEventListener of the timer after it launches (inside onTimerComplete function) and stop the timer and reset it. qddEventListener to the timer and start it after the data is downloaded (inside completeHangler_cc function).

Related

Google Apps Script (seemingly) hangs (circle icon runs indefinitely) randomly in a loop

I didn't do a great job of explaining the problem. The hanging behavior seems to be related to the use of console logging (with either Logger.log or console.log statements). If I comment out the logging statements, the hanging behavior does not occur. So, if I put in a breakpoint, the looping code will stop at the breakpoint one or a few times after clicking Resume and then just hang without getting back to the breakpoint. The number of successful times hitting the breakpoint before the hanging behavior occurs seems to be random. So, it seems that the problem is related to there being console logging in the loop. If I remove the logging statements, the hanging behavior does not occur. Thanks for any suggestions, here.
I have a loop that hangs in the debugger when a breakpoint{s) are set (but seemingly not when there are no breakpoints set). I've tried putting breakpoints in at various locations and then step over the breakpointed statement and then continue execution. Sometimes (randomly) it just never returns to the breakpoint and just runs forever (until timeout). Here's my code. Can anybody see what's going on. Thanks.
function getHikesDataByMonth() {
var firstHikeMonth = events[1][0].getMonth();
var thisHikeMonth = firstHikeMonth;
//var hikesColumn = firstHikeMonth;
var hikeDate, hikeDay,hikeName, hikeLevel, hikeNameShort;
var hikeMonth, newHikeMonth;
var eventRow = 1;
var hikeRow = 0;
var participantNumber = 0;
var numParticipants;
var hikeData = [];
var hikesColumn = [];
var hikeDate, hikeName, hikeNameShort, hikeLevel;
Logger.log("events.length " + events.length)
while (eventRow < events.length) {
//if (events[eventRow][4].isBlank) { break;}
if ((!events[eventRow][4].includes("hike") && !events[eventRow][4].includes("Hike") && !events[eventRow][4].includes("HIKE")) || events[eventRow][4].includes("CANCEL")) {
eventRow += 1;
continue;
}
// found a hike
console.log("Found Hike: " + events[eventRow][4]);
hikeName = events[eventRow][4];
hikeMonth = events[eventRow][0].getMonth() - firstHikeMonth;
if (hikeMonth > thisHikeMonth - firstHikeMonth) {
newHikeMonth = true;
thisHikeMonth = hikeMonth;
} else {
newHikeMonth = false;
}
hikeLevel = getHikeLevel(hikeName);
hikeNameShort = getHikeNameShort(hikeName);
hikeDate = events[eventRow][0];
hikeDay = weekDayNames[hikeDate.getDay()];
hikeData.push(hikeDay);
hikeData.push(hikeDate.toLocaleDateString('en-US'));
hikeData.push(hikeName)
hikeData.push(hikeNameShort);
hikeData.push(hikeLevel);
hikeData.push("");
hikeData.push("");
//hikeRowArray[0] = hikeRow;
//hikeData[hikeRow] = hikeRow;
console.log("Getting Participants: " + hikeName)
while (events[eventRow][4] == hikeName){
if (events[eventRow][9] != "Paid") {
eventRow += 1;
continue;
}
hikeData.push(events[eventRow][6] + " " + events[eventRow][5]);
eventRow += 1;
participantNumber += 1;
}
numParticipants = participantNumber
for (var i = participantNumber+1; i < 30; i++){
hikeData.push("");
}
//Logger.log(hikeParticipants[participantNumber]);
hikeData.push(numParticipants < 15 ? "Yes" : "No");
hikeData.push(15 - numParticipants);
// That's all for that hike - go to next hike
participantNumber = 0;
eventRow += 1;
hikeData.push(hikeData);
hikesColumn.push(hikeData);
console.log("Going to next hike at eventRow:" + eventRow)
if (newHikeMonth) {
hikesDataByMonth.push(hikesColumn);
}
}
}

How to make a user on my website ping a specific ip address?

I'm wondering how website like this one : https://ping.eu/ping/ manage to make our ip ping an other ip and get the result.
Someone have an idea ?
Thanks
It Doesn't. A PHP script(on the server) will most likely do it with "PHP Sockets". Have a look at
this: https://www.php.net/manual/en/sockets.examples.php
Else it could use exec() function, but that would be a security flaw.
So to answer your question: The website will ping the IP address not the 'client'
If you want to ping a server, i.e. an actual web address/URL like www.google.com, you can look at this JSFiddle http://jsfiddle.net/GSSCD/203/ or GitHub repository https://github.com/jdfreder/pingjs.
Here's some code from the JSFiddle:
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
Another way to ping a server/web address is to use JavaScript and the XMLHttpRequest() function it supports:
HTML:
<div id="result"></div>
JavaScript:
function http_ping(fqdn) {
var NB_ITERATIONS = 4; // number of loop iterations
var MAX_ITERATIONS = 5; // beware: the number of simultaneous XMLHttpRequest is limited by the browser!
var TIME_PERIOD = 1000; // 1000 ms between each ping
var i = 0;
var over_flag = 0;
var time_cumul = 0;
var REQUEST_TIMEOUT = 9000;
var TIMEOUT_ERROR = 0;
document.getElementById('result').innerHTML = "HTTP ping for " + fqdn + "</br>";
var ping_loop = setInterval(function() {
// let's change non-existent URL each time to avoid possible side effect with web proxy-cache software on the line
url = "http://" + fqdn + "/a30Fkezt_77" + Math.random().toString(36).substring(7);
if (i < MAX_ITERATIONS) {
var ping = new XMLHttpRequest();
i++;
ping.seq = i;
over_flag++;
ping.date1 = Date.now();
ping.timeout = REQUEST_TIMEOUT; // it could happen that the request takes a very long time
ping.onreadystatechange = function() { // the request has returned something, let's log it (starting after the first one)
if (ping.readyState == 4 && TIMEOUT_ERROR == 0) {
over_flag--;
if (ping.seq > 1) {
delta_time = Date.now() - ping.date1;
time_cumul += delta_time;
document.getElementById('result').innerHTML += "</br>http_seq=" + (ping.seq-1) + " time=" + delta_time + " ms</br>";
}
}
}
ping.ontimeout = function() {
TIMEOUT_ERROR = 1;
}
ping.open("GET", url, true);
ping.send();
}
if ((i > NB_ITERATIONS) && (over_flag < 1)) { // all requests are passed and have returned
clearInterval(ping_loop);
var avg_time = Math.round(time_cumul / (i - 1));
document.getElementById('result').innerHTML += "</br> Average ping latency on " + (i-1) + " iterations: " + avg_time + "ms </br>";
}
if (TIMEOUT_ERROR == 1) { // timeout: data cannot be accurate
clearInterval(ping_loop);
document.getElementById('result').innerHTML += "<br/> THERE WAS A TIMEOUT ERROR <br/>";
return;
}
}, TIME_PERIOD);
}
But, of course, these are web addresses, not IP addresses, so I'm not sure if that's what you're aiming for. I'm also not sure if you're looking for the amount of time spent to get the connection and the number of packets and bytes sent and received, or if you just want to validate the connection. The above code does all of those things. For IP addresses, you can try an AJAX request to ping a server, which only sees if there is a connection using YOUR SERVER'S IP address, NOT THE USER'S CLIENT, like this:
client --AJAX-- yourserver --ICMP ping-- targetservers
You could also try:
Using a Java applet with isReachable
Writing a server-side script which pings, and using AJAX to communicate to your server-side script
You might also be able to ping in Flash (using ActionScript)
One last hypothetical and unorthodox way to get an IP address is to inspect and view the source of the website you mentioned and copy some code, mostly JavaScript, and test it on your end and try to implement it.

Type Error #1009 in flash cs6 using AS3

I am actually trying to check whether a game's score is a high score. And then if it is, the score will be added to the leaderboard.
However I got this error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at FlashGame_fla::MainTimeline/checkBananaHS()
In my game, in that particular frame, this is the code that would link to the checkBananaHS():
function rpslsWon():void
{
gameOverBananaMC.visible = true;
bananaWinLose.visible = true;
bananaWinLose.text = "Kampai " + cPlayerData.pName + "! You are totally bananas!! \nYour Score: " + pBananaScore;
toMenuBtn.visible = true;
rollAgainBtn.visible = true;
toMenuBtn.addEventListener(MouseEvent.CLICK, Click_backtoMain);
rollAgainBtn.addEventListener(MouseEvent.CLICK, backtoBanana);
saveItBtn.addEventListener(MouseEvent.CLICK, checkBananaHS);
cPlayerData.pBananaScore = pBananaScore;
saveData();
tracePlayerData();
}
And this is the piece of code in the high score's frame:
var rpslsHighScore:int;
var rpslsHSName:String;
rpslsHighScore = 0;
rpslsHSName = "";
//rpslsHighScore = 0;
bananaWinnerDisplay.text = " ";
bananaScoreDisplay.text = "0";
function checkBananaHS(event:MouseEvent):void
{
if ((cPlayerData.pBananaScore > rpslsHighScore ||
rpslsHighScore == 0) && cPlayerData.pBananaScore > 0)
{
trace("There's a new high score for Banana");
rpslsHighScore = cPlayerData.pBananaScore;
rpslsHSName = cPlayerData.pName;
bananaScoreDisplay.text = "" + rpslsHighScore;
bananaWinnerDisplay.text = rpslsHSName;
saveData();
}
}
I just can't manage to fix the error. Can anyone help me out? Thanks alot!
One of your variables within checkBananaHS() are not set when it is called. So when you try to access a property of that object, it errors out because nothing exists.
Wit that in mind, that means one of the following objects are not yet set in your function:
cPlayerData
bananaScoreDisplay
bananaWinnerDisplay
Run a trace on each of those, one at a time at the beginning of your function, and see which one doesn't return [Object object]

Intermittant DriveWriteVolume rateMax exception

I have been struggling with this error since about a week before DriveApp was released. I have a section of code that fails intermittantly with the error:
Service invoked too many times in a short time: driveWriteVolume rateMax. Try Utilities.sleep(1000) between calls.
Here is the code in question:
for(var a = 0; a<attachments.length; a++){
if(a > 0){
child = "." + (a + 1) + " ";
}
else{
child = ".1 ";
}
var parent = (m + 1);
Utilities.sleep(5000);
var file = attachmentFolder.createFile(attachments[a]);//This is the line that causes the error.
Utilities.sleep(1000);
file.rename(parent + child + attachments[a].getName());
}
I started with 1000ms, then gradually worked up to 5000 and it still throws the error every ~200 iterations. This is using DocsList.
I have had a similar problem in a script I'm working on.
The problem arises when I loop through the attachments to the message and attempt to save them too. If I skip the attachments, I don't have a problem, even with the same number of total file creations and the same sleep time between them. This is the code I'm using. newFolder.createFile(pdfBlob) does not cause a problem. newFolder.createFile(attachmentBlob) does.
// Create the message PDF inside the new folder
var htmlBodyFile = newFolder.createFile('body.html', messageBody, "text/html");
var pdfBlob = htmlBodyFile.getAs('application/pdf');
pdfBlob.setName(newFolderName + ".pdf");
newFolder.createFile(pdfBlob);
Utilities.sleep(sleepTime); // wait after creating something on the drive.
htmlBodyFile.setTrashed(true);
// Save attachments
Logger.log("Saving Attachments");
for(var i = 0; i < messageAttachments.length; i++) {
Logger.log("Saving Attachment " + i);
var attachmentBlob = messageAttachments[i].copyBlob();
newFolder.createFile(attachmentBlob);
Utilities.sleep(sleepTime); // wait after creating something on the drive.
} // each attachment

AS3 AIR - black screen when packaged

When I run the application from Flash Develop everything is fine, both in Debug and Release.
After the application is packaged and installed, I just get a black screen when run.
However if I add a 'debug' file to applicationDirecty\META-INF\AIR\debug the application runs normally.
What could be causing this? and how can it be solved?
A debugging utility seemed to be causing the problem in the release build... removing calls to this solved the issue.
/** Gets the name of the function which is calling */
public function Log(prefix:String = "", suffix:String = "", params:* = null):void
{
var error:Error = new Error();
var stackTrace:String = error.getStackTrace(); // entire stack trace
var startIndex:int = stackTrace.indexOf("at ", stackTrace.indexOf("at ") + 1); //start of second line
var endIndex:int = stackTrace.indexOf("()", startIndex); // end of function name
var lastLine:String = stackTrace.substring(startIndex + 3, endIndex);
var functionSeperatorIndex:int = lastLine.indexOf('/');
var ClassSeperatorIndex:int = lastLine.indexOf(':');
var objectName:String = lastLine.substring(ClassSeperatorIndex+2, functionSeperatorIndex);
var functionName:String = lastLine.substring(functionSeperatorIndex + 1, lastLine.length);
trace(prefix +" " + "[" + objectName + "]" + " > " + functionName + " " + suffix);
}
Open Run.bat and replace
set OPTIONS=-connect %DEBUG_IP%
with
set DEBUG_IP=%DEBUG_IP%