calculating memory usage in javascript - javascript

I have written a program in Javascript which reads numbers from a file ,sorts them and then writes them back to the file.But I not able able to find a suitable method or tool to get the memory usage of the program.(something like Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); in java).If someone could please give me a lead I would be thankful.
Here is the code.
<html>
<script>
var oRequest;
var data=new Array();
var b= new Array();
var j
var k;
var temp;
var temp1;
if(document.all) {
oRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
else {
oRequest = new XMLHttpRequest();
}
oRequest.open("GET", "file:///C:/numbers.txt", true);
oRequest.send(null);
numbers= oRequest.responseText.split("\n");
for (var i = 0;i<(numbers.length-1);i++)
{
numbers[i] = parseInt(numbers[i],10);
}
var d = new Date();
var start = d.getTime();
for(var i=0;i<numbers.length;i++)
{
for(j=0;j<(numbers.length-1);j++)
{
if(numbers[j]>numbers[j+1])
{
temp=numbers[j+1];
numbers[j+1] = numbers[j];
numbers[j] = temp;
}
}}
var g = new Date();
var end =g.getTime();
var diff=(end-start);
</script>
<script>
function WriteFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile("C:\\BubbleJS.txt", true);
for(i=0;i<5000;i++)
{
fh.WriteLine(numbers[i]);
}
fh.WriteLine("\n");
fh.WriteLine("The time required for sorting is "+diff+" Milliseconds");
fh.Close();
}
</script>
<form>
<body background="Bubble.png">
<h1> </h1>
<input type="button" onClick='alert("Directing to Home Page"); window.location = "Home Page.html"' value="Back to Home Page">
<input type="button" onClick=WriteFile(); value="Begin Sorting!"
style="width: 174px; margin-left: 0px">
</form>
</html>

The JavaScript language and core libraries do not provide a way to view or calculate the memory usage of the runtime.
Your only hope is to find a library (e.g. ActiveX plugin, etc.) which can do it for you. Note that the developer tools of some popular web browsers (Chrome, Firefox, possibly others) provide a memory profiling graphical interface, so perhaps there are programmatic hooks you can find; however, if they exist they almost definitely won't work cross-browser.

Related

How do I access sub-child attributes in xml using javascript or jQuery?

I'm new to code development and I'm trying to build a project to help me retain the skills I have learned. In doing so, I've hit a snag.
I am trying to pull a couple of attributes from nodes in an XML file but having trouble getting to what I need. I need to be able to pull the "number" from the node parent and the team "code" for each team listed in the node. The number of teams fluctuate between 2 and 6. Here's a sample of the XML.
My code is below. When it runs, it will get the bye week data but it won't load the teams. Several posts that I've read have had a similar issue but with some other technology or data structure in place that didn't apply to what I'm working with here (as far as I could tell). Any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Bye Week</title>
<script>
var xmlhttp;
window.onload = function()
{
var url = "https://www.fantasyfootballnerd.com/service/byes/xml/test/";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = byeWeeks;
xmlhttp.send();
}
function byeWeeks()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var theXML = xmlhttp.responseXML.documentElement.getElementsByTagName('Week');
for(var i = 0; i < theXML.length; i++)
{
var week = theXML[i].getAttribute('number');
var team = theXML[i].getElementsByTagName('Team');
var out = "<b>" + team + "</b><br/>";
out += "Bye Week: " + week + "<br/>";
console.group('Output for ' + team);
console.log('Bye Week: ' + week);
console.log();
console.groupEnd();
document.getElementById('result').innerHTML += out
}
}
}
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>
As per the attached xml structure it seems the team node can be multiple inside a week node, so you would have to iterate over the team nodes in order to extract the code.
var week = theXML[i].getAttribute('number');
var teams = theXML[i].getElementsByTagName('Team');
teams.forEach(function(team) {
console.log(team.getAttribute('code'));
});
I'm not familiar with fantasy football but I'm assuming each week there is two teams that you want to retrieve. To access the child element attributes for week try:
var team1Name = theXML[i].childNodes[0].getAttribute("name");
var team2Name = theXML[i].childNodes[1].getAttribute("name");
team1Name should be holding "washington redskins"
team2Name should be holding "florida panthers"
if you want the team code just replace "name" with "code"
if you're not sure how many teams there are the following code should work
var teams = [];
for each (team in theXML[i].childNodes){
teams.push(team.getAttribute("name"));
}
//at this point teams will hold an array of team names playing that week
#Ashish Khandelwal
Here's the updated code with the array that I referenced earlier (I tried to post it as a comment on our conversation string but it was too long). The XML can be found here.
<!DOCTYPE html>
<html>
<head>
<title>Bye Week</title>
<script>
var xmlhttp;
window.onload = function()
{
var url = "https://www.fantasyfootballnerd.com/service/byes/xml/test/";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = byeWeeks;
xmlhttp.send();
}
function byeWeeks()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var theXML = xmlhttp.responseXML.documentElement.getElementsByTagName('Week');
for(var i = 0; i < theXML.length; i++)
{
var week = theXML[i].getAttribute('number');
var teams = theXML[i].getElementsByTagName('Team');
Array.from(teams).forEach(function(team) {
console.log(team.getAttribute('code'));
});
console.group('Output for ' + team);
console.log('Bye Week: ' + week);
console.log(theXML[i]);
console.log(teams.push(team.getAttribute("code")));
console.groupEnd();
document.getElementById('result').innerHTML += out
}
}
}
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>

How to set byte[] property of ActiveX component from Javascript?

I'd like to set RTF formatted calendar entries, but don't know how to pass the byte[] to the ActiveX object, i.e. the RTFBody property.
The following code reads the RTFBody property after some content has been set - so reading the byte[] is working, but when I try to write exactly the same content (+ trailing 0) back, neither an U/Int8Array nor a Scripting.Directory works.
Maybe it's possible to workaround with some .NET objects, but I don't know how to instanciate those Non-ActiveX components. An alternative solution shouldn't require to script the formattings, e.g. "go to line 2 and make it bold", i.e. I like to generate the rtf via a template and only paste the result into the calendar object.
I'm aware that this has to be eventually encoded in Windows-1252, but for a start I simply want to see the same bytes to be written successfully. The script is executed within a HTA context - so script security is not an issue.
<html>
<head>
<hta:application id="foo" applicationname="foo" version="1" navigable="yes" sysMenu="yes"></hta>
</head>
<script language="JavaScript" type="text/javascript">
function doit2() {
var rtfBody =
"{\\rtf1\\ansi\\ansicpg1252\\deff0\\nouicompat\\deflang1031{\\fonttbl{\\f0\\fswiss\\fcharset0 Calibri;}}\r\n"+
"{\\*\\generator Riched20 14.0.7155.5000;}{\\*\\mmathPr\\mwrapIndent1440}\\viewkind4\\uc1\r\n"+
"\\pard\\f0\\fs22 bla\\par\r\n"+
"}\r\n";
// https://github.com/mathiasbynens/windows-1252
var rtfBody1252 = rtfBody; // windows1252.encode(rtfBody);
var dict = new ActiveXObject("Scripting.Dictionary");
for (var i = 0; i < rtfBody1252.length; i++) {
dict.add(i, rtfBody1252.charCodeAt(i));
}
dict.add(rtfBody1252.length, 0);
// Alternative setting via U/Int8Array also doesn't work ...
// var buf = new ArrayBuffer(rtfBody1252.length+1);
// var bufView = new Int8Array(buf);
// for (var i=0, strLen=rtfBody1252.length; i<strLen; i++) {
// bufView[i] = rtfBody1252.charCodeAt(i);
// }
// bufView[rtfBody1252.length] = 0;
var myOlApp = new ActiveXObject("Outlook.Application");
var nameSpace = myOlApp.GetNameSpace("MAPI");
var recipient = nameSpace.CreateRecipient("user#host.com");
var cFolder = nameSpace.GetSharedDefaultFolder(recipient,9);
var appointment = cFolder.Items.Add(1);
appointment.Subject = "Subject";
appointment.Location = "Location";
appointment.Start = "22.02.2017 17:00";
appointment.Duration = "120";
appointment.Categories = "deleteme";
appointment.Body = "bla";
var va = new VBArray(appointment.RTFBody).toArray();
var bla = String.fromCharCode.apply(null, va);
document.forms[0].output.value = bla;
// var bla2 = windows1252.decode(bla);
appointment.RTFBody = dict.Items();
appointment.ReminderSet = "true";
appointment.Save();
entryId = appointment.EntryId;
appointment.Display();
delete appointment;
delete cFolder;
delete recipient;
delete nameSpace;
delete myOlApp;
}
</script>
<body>
<form>
<input type="button" onclick="doit2()" value="doit"/>
<textarea name="output" rows="5" cols="50"></textarea>
</form>
</body>
</html>

How to display images one at a time through loop with HTML/Javascript?

I'm not one of those people that grew up with programming, or have experienced in high school. I just recently started the basics in College. What I have below is my javascript/html that I have been working on Visual Studio 2012. My goal for it is to display the images one at a time by pressing a button called "Next Name" (as you can see I created a "form" at the bottom of my code). But as I have it now, it prints out all the images in my "hw1.txt" at the same time. Under my for loop, I tried "result = "";" and then "displayList.innerHTML = result;" hoping to just print out one image at least. I tried other things, but it just left my code messy. Please I need help. Any advice, pointers, or whatever is good. Can you also explain your answers in a way that I'll understand too? Just think of me as you're talking to a child or something haha. Thanks.
Note: in "hw1.txt" every 3rd index (starting from index 0) is the name of people, and the index next to it (myArray[i + 1]) is the image file (inside the .txt it goes like 1.jpg, 2.jpg, 3.jpg, and so on...)
<br/>
<span id="displayList">Photo here.</span>
<script type=text/javascript>
if (typeof ActiveXObject != "undefined") // IE
var req = new ActiveXObject("Microsoft.XMLHTTP");
else // Other browsers
var req = new XMLHttpRequest();
req.open('GET', 'hw1.txt', false);
req.send(null);
s = req.responseText;
var myArray = s.split(";");
var result = "";
function nextItem() {
for (i = 3; i < myArray.length; i = i + 3)
result = result + "<img src='" + myArray[i + 1] + "'/>";
displayList.innerHTML = result;
}
</script>
<form name="ClickNext">
<input type="button" value="Next Name" onclick="nextItem()" />
</form>
<span id="displayList">Photo here.</span>
<script type=text/javascript>
if (typeof ActiveXObject != "undefined") // IE
var req = new ActiveXObject("Microsoft.XMLHTTP");
else // Other browsers
var req = new XMLHttpRequest();
req.open('GET', 'hw1.txt', false);
req.send(null);
s = req.responseText;
var myArray = s.split(","); //if images are comma(,) seperated then just split it from comma
var index = 0;
function nextItem() {
if(typeof myArray[index] !== 'undefined') {
displayList.innerHTML = "<img src='" + myArray[index] + "'/>";
index += 1;
}
}
</script>
<form name="ClickNext">
<input type="button" value="Next Name" onclick="nextItem()" />
</form>
First off you don't need the form around that input since you don't really send a form.
Secound you should add an id to your input ( or <a></a> or <button></button> ) such as id="next_name" or I guess you can keep the old way of calling an event. :P
Then, you should:
var position = 0;
var result = '';
document.getElementById('next_name').onclick = function(){
if(position < myArray.length){
result = result + "<img src='" + myArray[position + 1] + "'/>";
displayList.innerHTML = result;
position++;
}
};
The idea is to use a variable to memorize your position within your list of image srouces. Once you use one, you increment your position within the list so next time a user clicks that button you add a different image.

HTML/JS pagination? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
jQuery Pagination Plugin
I am trying to add a pagination of some kind on my website: www.metallica-gr.net and although I tried some of the jquery ones I had a hard time understanding how I would implement it on my site.
Here's how my site is built, and how articles are displayed. Is it possible to make pagination for this?
http://imageshack.us/a/img268/249/paginationq.jpg
If you only have a bunch of static files then you would probably be better off just creating the links yourself. I think these types of things are more useful with dynamic websites. Something to this effect.
<html>
<head>
<script type="text/javascript">
var baseUrl="www.mysite.com?page=";
var forwardLinkId ="fwdLink";
var backwardLinkId = "bwdLink";
function SetForwardUrl(forwardLink)
{
var page = gup(pageNumber)
var fwd = document.getElementById(forwardLink);
var fwd.href = baseUrl + (page.ToNumber() + 1);
}
function SetBackworddUrl(backwordLink)
{
var page = gup(pageNumber)
var bwd = document.getElementById(backwordLink);
var bwd .href = baseUrl + (page.ToNumber() - 1);
}
function gup(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
document.onload = function() {
SetForwardUrl(fwdLink);
SetBackwardUrl(bwdLink);
}
</script>
</head>
<body>
<a id="fwdLink" /> <a id="bwdLink" />
</body>
</html>

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

Categories