How can I make my counter look less fake? - javascript

I'm using this bit of code to display the number of users on a site.
My customer is complaining it looks fake. Any suggestions?
var visitors = 187584;
var updateVisitors = function()
{
visitors++;
var vs = visitors.toString(),
i = Math.floor(vs.length / 3),
l = vs.length % 3;
while (i-->0) if (!(l==0&&i==0))
vs = vs.slice(0,i*3+l)
+ ','
+ vs.slice(i*3+l);
$('#count').text(vs);
setTimeout(updateVisitors, Math.random()*2000);
};
setTimeout(updateVisitors, Math.random()*2000);
Edited:
alt text http://img695.imageshack.us/img695/4268/reachdevs2.png
Screenshot-Advertise - Stack Overflow - Chromium http://img130.imageshack.us/img130/8083/screenshotadvertisestac.png
http://inedomedia.com/stackoverflow.aspx

Everyone knows JS counters are fake, don't bother trying to make it look "less fake", bother making a real one.
If you don't have enough visitors to show around, just don't use a counter, they're so 90's.

Warning: Attempted Humour
Did he ask for a giant splash page to go along with the fake real-time visitor counter? How about some nice "Netscape Now!" button logos and blinking text? Here are some really cool "under construction" animated gifs you can use too.
http://www.animatedgif.net/underconstruction/construction.shtml
-Oisin

I'm guessing it looks fake because every time you load the page it starts at the same number and counts upwards?
Take a look at the javascript that tells you how many megabytes of email storage you get with a Gmail account. I think it bases the starting number on the date/time, so that if you load a page, watch it count up, and then load it again, it won't reload with a smaller number.
Be honest though... it is fake right? You aren't showing precisely how many users there are and updating it live as new users create accounts. The goal then is to make sure it is somewhat close to reality. Hopefully the rate at which the number increases in your script is based on past new-user subscription rates.

make the interval parameter of the setInterval random as well ... it will look more real as it will randomly increment the random numbers :)

Related

Randomize numbers in a random order script

I have searched and although I see this addressed in Python and PHP, I don't see it using JS. This script randomizes order on refresh and I would like the numbers to be randomly generated as well as the order. The order part is already working, but I don't want it limited to numbers I input (150, 375 and 900 in this example). I'm going to have about 50 variables but I've just listed three to keep it short here.
I would also like to understand how to control the place values permitted, so I could have xx,xx,xx, etc./ xxx,xxx,xxx etc. and also how to state a range, so it could include xx,xxx,xxxx
Lastly I would be very keen to understand how to limit the generated numbers to meet certain profiles, like all tens (670,320,980,410,650), twenty-fives (375,925,400,850,175, etc.). This would be extremely helpful.
I'm sorry this is just beyond my ability, and I have tried and tried. I operate a school in India where I teach math, and we have had great success teaching number recognition and counting in English and Hindi using printed charts of numbers that fit different criteria like this, and I would like to adapt it to a mobile app, just to let you know why I'm asking. Many thanks.
var contents=new Array()
contents[0]='150'
contents[1]='375'
contents[2]='900'
*/
var spacing = "<br />"
var the_one
var z = 0
while (z<contents.length){
the_one=Math.floor(Math.random()*contents.length)
if (contents[the_one]!="_selected!"){
document.write(contents[the_one]+spacing)
contents[the_one]="_selected!"
z++
}
}

How to make fps run at the same pace across different clients

Both of the server and client have the code
setInterval(function(){
player.x++;
player.y++;
}, 20);
I have a node.js / socket.io server where the player's x and y are being updated every frame and sent to the client. The client is also having a different x and y being updated using the same logic. The client seems to be moving faster than the server though so it's making the game not in sync.. What should I be doing differently?
that's a huge and kinda complex topic, I'm not in the mood to google these topics for you; but a few hints/directions.
This ain't meant to be a full answer, but it's more explanation, a comment can take.
1st: don't increment values, neither in the back- nor in the frontend.
Define them as an animation: { startTime, startValue, endTime, endValue }. Now you can interpolate the current position at any time, independant of the interval.
2nd: you have to account for the time-offset between front- and backend.
3rd: check in the frontend for manipulations of the timer: this is a common way to cheat. Don't take the correctness of the clock for granted.
4th: you also have to account for the ping, when recieving actions from the frontend for example, you should subtract the ping to know when the action has really been made. And don't forget to check the ping over and over again: it might change over time.
And again, you can only trust your own clock, and you should check for manipulations (eg. artificially slowing down the connection). google ping-cheater, ...
finally: You're not the first one to create a real-time game. Search for these topics, they have been solved, and they have been asked by other people in the past.
Search especially in the flash-community. Flash still is a popular gaming-platform, and AS3-code should be pretty easy to understand and to port to JS.
It was actually really really easy, anyone with the same problem just read this article. https://www.viget.com/articles/time-based-animation
The simplest way to put it "move based on how much time has passed since you've last moved" So just find a deltaTime variable by subtracting time_now from time_then.
This is what my updatePosition function looks like now
self.updatePosition = function(){
var now_time = (new Date).getTime();
var delta_time = now_time - self.then_time;
self.x += delta_time * self.velocityX;
self.y += delta_time * self.velocityY;
self.then_time = now_time;
}
Just set the then_time in your initialization or whenever your character can first start moving.

Multi-tempo/meter js DAW

Has anyone implemented a javascript audio DAW with multiple tempo and meter change capabilities like most of the desktop daws (pro tools, sonar, and the like)? As far as I can tell, claw, openDAW, and web audio editor don't do this. Drawing a grid meter, converting between samples and MBT time, and rendering waveforms is easy when the tempo and meter do not change during the project, but when they do it gets quite a bit more complicated. I'm looking for any information on how to accomplish something like this. I'm aware that the source for Audacity is available, but I'd love to not have to dig through an enormous pile of code in a language I'm not an expert in to figure this out.
web-based DAW solutions exists.web-based DAW's are seen as SaaS(Software as a Service) applications.
They are lightweight and contain basic fundamental DAW features.
For designing rich client applications(RCA) you should take a look at GWT and Vaadin.
I recommend GWT because it is mature and has reusable components and its also AJAX driven.
Also here at musicradar site they have listed nine different browser based audio workstations.you can also refer to popcorn maker which is entirely javascript code.You can get some inspiration from there to get started.
You're missing the last step, which will make it easier.
All measures are relative to fractions of minutes, based on the time-signature and tempo.
The math gets a little more complex, now that you can't just plot 4/4 or 6/8 across the board and be done with it, but what you're looking at is running an actual time-line (whether drawn onscreen or not), and then figuring out where each measure starts and ends, based on either the running sum of a track's current length (in minutes/seconds), or based on the left-most take's x-coordinate (starting point) + duration...
or based on the running total of each measure's length in seconds, up to the current beat you care about.
var measure = { beats : 4, denomination : 4, tempo : 80 };
Given those three data-points, you should be able to say:
var measure_length = SECONDS_PER_MINUTE / measure.tempo * measure.beats;
Of course, that's currently in seconds. To get it in ms, you'd just use MS_PER_MINUTE, or whichever other ratio of minutes you'd want to measure by.
current_position + measure_length === start_of_next_measure;
You've now separated out each dimension required to allow you to calculate each measure on the fly.
Positioning each measure on the track, to match up with where it belongs on the timeline is as simple as keeping a running tally of where X is (the left edge of the measure) in ms (really in screen-space and project-coordinates, but ms can work fine for now).
var current_position = 0,
current_tempo = 120,
current_beats = 4,
current_denomination = 4,
measures = [ ];
measures.forEach(function (measure) {
if (measure.tempo !== current_tempo) {
/* draw tempo-change, set current_tempo */
/* draw time-signature */
}
if (measure.beats !== current_beats ||
measure.denomination !== current_denomination) {
/* set changes, draw time-signature */
}
draw_measure(measure, current_position);
current_position = MS_PER_MINUTE / measure.beats * measure.tempo;
});
Drawing samples just requires figuring out where you're starting from, and then sticking to some resolution (MS/MS*4/Seconds).
The added benefit of separating out the calculation of the time is that you can change the resolution of your rendering on the fly, by changing which time-scale you're comparing against (ms/sec/min/etc), so long as you re-render the whole thing, after scaling.
The rabbit hole goes deeper (for instance, actual audio tracks don't really care about measures/beats, though quantization-processes do), so to write a non-destructive, non-linear DAW, you can just set start-time and duration properties on views into your audio-buffer (or views into view-buffers of your audio buffer).
Those views would be the non-destructive windows that you can resize and drag around your track.
Then there's just the logic of figuring out snaps -- what your screen-space is, versus project-space, and when you click on a track's clip, which measure, et cetera, you're in, to do audio-snapping on resize/move.
Of course, to do a 1:1 recreation of ProTools in JS in the browser would not fly (gigs of RAM for one browser tab won't do, media capture API is still insufficient for multi-tracking, disk-writes are much, much more difficult in browser than in C++, in your OS of choice, et cetera), but this should at least give you enough to run with.
Let me know if I'm missing something.

Why does Google +1 record my mouse movements? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
This is only on pages with a Google +1 box on my website:
It seems to be firing off an event on every mouse move. Anyone know what it is doing? I searched on Google (perhaps I should try Bing for once on this one!) but no one seems to have written about it. Is it recording information about my visitors browsing habits? Is it some sort of CAPTCHA to detect human like behviour?
Example URL, press F12 in chrome, go to timeline and press record, then move your mouse around this page (it plus ones this question, don't worry):
https://plusone.google.com/u/0/_/+1/button?hl=en-US&jsh=r%3Bgc%2F22224365-adc8a19e#url=https://stackoverflow.com/questions/6667544/google-1-recording-mouse-move&size=tall&count=true&id=I1_1310488711647&parent=https://plusone.google.com/u/0/_/+1/button?hl=en-US&jsh=r%3Bgc%2F22224365-adc8a19e#url=https://stackoverflow.com/questions/6667544/google-1-recording-mouse-move&size=tall&count=true&id=I1_1310488711647
For what it's worth (I can see this is going to be a popular question), I don't think there is anything sinister behind it, it might even be a useless artifact/bug, but if it is doing some sort of tracking, well, it seems a little deceptive to me.
Google +1 privacy policy
http://www.google.com/intl/en/privacy/plusone/
Google +1 Button Privacy Policy
June 28, 2011
The Google Privacy Policy describes how we treat personal information
when you use Google’s products and services, including information
provided when you use the Google +1 button. In addition, the following
describes our additional privacy practices specific to your use of the
+1 button.
Information we collect and how it is shared
The Google +1 button is a way for you to share information publicly
with the world. The Google +1 button helps you and others receive
personalized content from Google and our partners. The fact that you
+1’d something will be recorded by Google, along with information about the page you were viewing when you clicked on the +1 button.
Your +1’s may appear to others as an annotation with your profile name
and photo in Google services (such as in search results or on your
Google Profile) or elsewhere on websites and ads on the Internet.
We will record information about your +1 activity in order to provide
you and other users with a better experience on Google services.
In order to use the Google +1 button, you need to have a public Google
Profile visible to the world, which at a minimum includes the name you
chose for the profile. That name will be used across Google services
and in some cases it may replace another name you’ve used when sharing
content under your Google Account. We may display your Google Profile
identity to people who have your email address or other identifying
information.
Use of the collected information
In addition to the above-described uses, the information you provide
to us is used subject to our main Google Privacy Policy.
We may share aggregate statistics related to users’ +1 activity with
the public, our users, and partners, such as publishers, advertisers,
or connected sites. For example, we may tell a publisher that “10% of
the people who +1’d this page are in Tacoma, Washington.”
Your choices
You may view the list of items you have +1’d on the +1 tab on your
Profile. You can remove individual items from that list.
You may opt out of seeing +1 recommendations on third-party websites
(including on ads on third-party sites) from people you know.
We will store data (such as your recent +1’s) locally in your browser.
You may be able to access and clear this information in your browser
settings.
More information
Google adheres to the U.S. Safe Harbor privacy principles. For more
information about the Safe Harbor framework or our registration, see
the Department of Commerce’s website.
It appears to be seeding a random number generator with your mouse movements.
The mouse move handler itself does something along the lines of the following:
var b = ((event.X << 16) + event.Y) * (new Date().getTime() % 1000000);
c = c * b % d;
if (previousMouseMoveHandler) previousMouseMoveHandler.call(arguments);
d is (screen.width * screen.width + screen.height) * 1000000, and c is a variable that starts out as 1.
All of this is wrapped in the scope of an anonymous function, which itself is immediately evaluated to return a function that is assigned to a property named "random". That returned function looks something like this:
var b = c;
b += parseInt(hash.substr(0,20), 16);
hash = MD5(hash);
return b / (d + Math.pow(16, 20));
hash, BTW, is a variable that starts out as the MD5 hash of the page's cookies, location, the new Date().getTime(), and Math.random().
(Note, of course, that Google may change the script returned at any time and hence invalidate this analysis)
The actual code that is being executed is derived from the Shindig code found here:
http://svn.apache.org/repos/asf/shindig/trunk/features/src/main/javascript/features/shindig.random/random.js
A secure random number is needed to ensure that the secure postMessage channel created here cannot be compromised by scripts on the page to execute arbitrary actions.
Here's an article that explains why using Math.random() is bad:
http://baagoe.com/en/RandomMusings/javascript/
If you can get your script loaded first, you could hook addEventListener and log everyone who is setting addEventListener and see who's doing it and then, by looking at the relevant code, see what they're doing.
Put this in place before the Google code loads:
var oldListener = document.addEventListener;
document.addEventListener = function(type, listener, capture) {
if (type == "mousedown" || type == "mouseup" || type == "mousemove") {
console.log("type=" + type + " listener=" + listener.toString().slice(0, 80));
}
return (oldListener.apply(this, arguments));
}
To see what was listening to window.onmousemove, you'd have to do it afterwards because it's just a variable assignment, not a function that you can intercept. So sometimes after the initialization code of the page runs, you would do this to log what was hooked up to it:
if (window.onmousemove) {
console.log(window.onmousemove.toString().slice(0,80));
}
In the uncluttered code as of Jul 22, you'll notice the onmousemove is part of the Gb.random class:
Gb.random = function () {
function a(a) {
var b = Jb();
b.update(a);
return b.ib()
}
var b = la.random(),
c = 1,
d = (screen[za] * screen[za] + screen[J]) * 1E6,
e = i.onmousemove || Db();
i.onmousemove = function (a) {
if (i.event) a = i.event;
var b = a.screenX + a.clientX << 16;
b += a.screenY + a.clientY;
b *= (new Date)[Ta]() % 1E6;
c = c * b % d;
return e[G](i, ka[x][Aa][G](arguments))
};
var f = a(k.cookie + "|" + k[B] + "|" + (new Date)[Ta]() + "|" + b);
return function () {
var b = c;
b += ia(f[cb](0, 20), 16);
f = a(f);
return b / (d + la.pow(16, 20))
}
}();
It's multiplying sum of x and y by 2^16 using bitshift, then adding some other dimensions and multiplying all this by time in milliseconds mod 1000000. This definitely looks like a randomizing algorithm.
I'm not sure why the page would need something like this, perhaps it's using a cookie, preventing automated +1 clicking? When you click the "+1" the login screen that pops up appears to have a random number appended as the hash, the url ends with "&hl=en-US#RANDOMNUMBER"
I bet you its "In-Page Analytics" Beta. Making a cursor and click heat-map.
I think that the paper by Guo and Agichtein from CHI 2010 http://www.mathcs.emory.edu/~qguo3/wip287-guo11.pdf can provide further ideas on why Google is doing that.
Apparently mouse movements is a rough proxy for eye movement and allows people to approximate eye tracking results.
They probably use it to measure how quickly users move from one UI item to another, how often clicks miss etc.
I normally have a deeply cynical view of invasive features but I don't think this is a privacy risk. It's shocking because it's so unusually fine-grained, but it's not very revealing. Does your mouse movement encode bank details? Porn?
Google and the like have plenty of high-quality data to track you with. Mouse coordinates have very limited application.
To go off-topic a bit:
To an extent, the more data you collect about people the more problems you have. I hear (from Schneier and the like) that intelligence agencies are suffering from the huge numbers of false positives triggered by their ever-accelerating data aquisition -- the signal-to-noise ratio is abysmal. I find this somewhat amusing.
It's impossible to tell for certain, what Google does with this mouse movement data. As you can see yourself, it's not returning loads and loads of information back to the server, therefore, nothing to worry about.
The first is probably a generic event handler. Reason why I think that is if you read the source, you can see that on the line before there is throw Error("Invalid listener argument"); and next or one after the next there's throw Error("Invalid event type"). Since the fired line is in between these two (event related) exceptions, I'm pretty sure that it's some kind of an event handler. Using debugger, it doesn't do anything really (doesn't jump to some other function) so it seems that it's there for future implementation.
The second function is identical to the first one. Since it's gTalk's I suppose it updates your status (away, online etc).
The third seems to be content updater or something similar, since you can see strings like cacheTimeout etc scattered around it.
My 2 cents.
this is really beyond from far fetched, but here it goes anyway ...
it revolves around the type of trajectory & curvature of a mousemovement from a start point towards different attractors take i.e. 2 items/links on a page.
http://sciencestage.com/v/26698/dynamics-and-embodiment-in-language-comprehension.html
in short, if you put two competing links/buttons and analyze the trajectory towards one of those links, you can deduce a pattern or how you reached the decision to click only 1 of those links (see vid around 13:00)

Detect loops in computer player in a cardgame

A while ago I created a small cardgame web app for fun. The player plays against the computer and mostly it works fine. Sometimes though the computer player gets into a loop, the point of the game is to lose all your cards and if you don't have a card to play you take the pile. Sometimes the computer plays x,y,z, takes the pile, plays x,yz, takes the pile etc.
I keep track of the moves I've made, so at any point I have an array that looks something like : [C2,D5,H2,S4,C5,H2,S4,C5,H2,S4,C5]
In this case I can see that I've gotten into a loop of playing H2,S4,C5, then taking the pile and then repeating.
So, the generalized problem is, what's the best way to detect repeating patterns in a list? I could probably whip something up using a simple for loop, trying to find the card I'm about to play and if I find that in position x then I could check whether the pattern from x to n repeats at position x-(n-x) to x, but this seems like the kind of problem that could have a nice algorithm for it. How would you code this given the following function signature:
function findLoops(previousMoves, nextMove, maxPatternLength) {
//Return [loopLength, loopCount] or null if there are no loops
}
p.s. this is not a homework assignment, the game exists and is at http://www.idiot-cardgame.com if anyone is interested :)
First the general question: Your suggested method
trying to find the card I'm about to play and if I find that in position x then I could check whether the pattern from x to n repeats at position x-(n-x) to x,
looks really good. I would suggest basically the same. It is O(n) and needs a fixed amount of storage, and is simple: what else would you wish for?
Second: You can check for repetition in games generally if you keep a hash table of all previous game states (complete state, nothing left out). Everytime you reach a new state look up if it is in the hashtable, if its in it: you game state is looping.
In Javascript you have builtin hastables so this is very easy to do with something similar like this:
new_state = next_move(old_state);
new_encoded_state = encode(new_state); // make it into a string
if (allstates[new_encoded_state]) {
// we are looping!
} else {
allstates[new_encoded_state] = 1;
// no looping
}
The variable allstates is not an Array but of type Object. You can have array like access with strings and this uses the Object as hastable.

Categories

Resources