How to load an random number in ["random number"] code - javascript

Hi this is my cocde to load an xml file:
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
this.url = url;
xmlLoader.load(new URLRequest("C:\Documents and Settings\...books.xml"));
function LoadXML(e:Event):void {
xmlData = new XML(e.target.data);
trace(xmlData.author.text()[0]);
}
but I want to generate a random number in this line trace(xmlData.author.text()[0]);
so instead of [0] there needs to be an random number between the [ ]

Continuation from comments; you can't just copy and paste your way through a problem - you have to apply a little thought...
// break down the problem, if this line returning
// an array lets assign it to a variable.
var authorText = xmlData.author.text();
// random index should be within the bounds of the array length
var random = Math.floor( Math.random() * authorText.length );
// put it together
trace( authorText[random] );
Assuming the rest of your code is okay then this should work - here's a demo in javascript though I suspect you are doing something in actionscript / flash (though they both conform to ECMAScript so it should work just the same).

Related

Leading and trailing zeros in numbers

I am working on a project where I require to format incoming numbers in the following way:
###.###
However I noticed some results I didn't expect.
The following works in the sense that I don't get an error:
console.log(07);
// or in my case:
console.log(007);
Of course, it will not retain the '00' in the value itself, since that value is effectively 7.
The same goes for the following:
console.log(7.0);
// or in my case:
console.log(7.000);
JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:
const leadingValue = 007;
const trailingValue = 7.00;
console.log(leadingValue, trailingValue); // both are exactly 7
But what I find curious is the following: the moment I combine these two I get a syntax error:
// but not this:
console.log(007.000);
1) Can someone explain why this isn't working?
I'm trying to find a solution to store numbers/floats with the exact precision without using string.
2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?
What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.
1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)
2) Here's how you can achieve your formatting using Intl.NumberFormat...
var myformat = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 3,
minimumFractionDigits: 3
});
console.log(myformat.format(7)); // prints 007.000
Hi
You can use an aproach that uses string funtions .split .padStart and .padEnd
Search on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
Here you have an example:
const x = 12.1;
function formatNumber( unformatedNumber) {
const desiredDecimalPad = 3;
const desiredNonDecimalPad = 3;
const unformatedNumberString = unformatedNumber.toString();
const unformatedNumberArr = unformatedNumberString.split('.');
const decimalStartPadded = unformatedNumberArr[0].padStart(desiredDecimalPad, '0');
const nonDecimalEndPadded = unformatedNumberArr[1].padEnd(desiredNonDecimalPad, '0');
const formatedNumberString = decimalStartPadded + '.' + nonDecimalEndPadded;
return formatedNumberString;
}
console.log(formatNumber(x))

d3.format thousand separator on variables?

Hello I'm yet again stuck on d3...
I'd like to know how to use a thousand seperator on a variable all the examples I've managed to find seem to be on static data.
This is what I've tried so far:
d3.csv("OrderValueToday.csv", function(obj) {
var text = 'Today = £';
var totalSales = text + d3.format(",") + obj[0].Today;
svgLabel = d3.select("#label").append("h2")
.text (totalSales);
});
However it just outputs a load a stuff on the webpage this is it:
Today = £function (n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a; if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}20000
So all I want is to be able to make the totalSales value have thousand separators so like 20,000 everything else I've tried doesnt do anything. I've read this https://github.com/mbostock/d3/wiki/Formatting but didnt see what I could do for my scenario.
Any help would be greatly appreciated. Cheers
Specifying a d3.format returns a formatting function, which you must then call as a function, passing in the number to be formatted as an argument:
var myNumber = 22400;
d3.format(',')(myNumber); // returns '22,400'
Sometimes you will see a format function stored as a variable like this:
var commaFormat = d3.format(',');
commaFormat(1234567); // returns '1,234,567'
In your case, you could do the following:
var totalSales = text + d3.format(',')(obj[0].Today);

Incrementing Number Inside String

For a client's requirement, I have set out several images as follows:
img/img1.jpg
img/img2.jpg
img/img3.jpg
...
img/img4.jpg.
Now, I need to make the function that loads images dynamic. At the moment, the current solution is as follows:
// Grab the last image path
var lastImagePath = $("lastImage").attr("src");
// Increment the value.
var nextImagePath = "img/img" + (+lastImagePath.replace("img/img").replace(".jpg") + 1) + ".jpg";
// So on.
I was wondering if there's a cleaner way to increment the number?
Slightly cleaner:
var nextImagePath = lastImagePath.replace(/\d+/, function (n) { return ++n; });
This uses the version of replace that accepts a regular expression and a function.

Random URL redirect from array

/**
* Political Animals
* contentscript.js is loaded on each page(s) listed in manifest.json
* This plugin replaces all the images on the website of news sites with pictures of
* animals in suits, as a commentary on what the news has become. Made for Web 2
* November 20, 2013
*/
//Random Image array
var arrayImg = ['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg','http://ny-image0.etsy.com/il_fullxfull.85564656.jpg','http://afraidofmice.com/blog/wp-content/uploads/2011/08/berkleyill.jpg','http://elizabethmarshallgalleryblog.files.wordpress.com/2011/05/etsy-panda-for-blog1.jpg','http://moesewco.typepad.com/.a/6a00e5500684b488330120a5c7cf3a970c-300wi','http://ih3.redbubble.net/image.13276877.5059/flat,800x800,070,f.u1.jpg','http://www.tildeshop.com/blog/wp-content/uploads/2012/09/SeaLionFemale-21.jpg'];
//redirect
var acceptedWebsites =['www.cnn.com', 'www.nytimes.com', 'www.latimes.com', 'www.washingtonpost.com', 'www.nbcnews.com', 'www.foxnews.com'];
var currentUrl = document.location.href;
var referrer = currentUrl.match(/:\/\/(.[^/]+)/)[1];
//Making sure the code does what I want it to. As long as the link shows a number greater than -1, then the site extension is working
console.log(referrer);
console.log(acceptedWebsites.indexOf(referrer));
//var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
//document.location.href = url;
// image source goes through the following script function
$('img').each(function(){
// creating the randomizing
var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
//Takes the current array and applies the source with the random function
$(this).attr('src', random);
//removing the stretch
var theWidth = $(this).width();
var theHeight = $(this).height();
if (theWidth < theHeight) {
$(this).height(150);
}
else {
$(this).width(150);
}
});
//alert ("Go to any of the follow websites: fox.com, nbc.com, nytimes.com, latimes.com, or cnn.com");
I have this array in javascript. I want to have it so that the user is automatically redirected to one of the links from the array, possibly randomly. I don't know if I can do this in javascript. I am using this for a chrome extension, so I don't know if I can use php.
These are fantastic answers, except they constantly redirect. I want it so that they are just redirected to one from the array once, not constantly redirect.
**Edit 2: I added my whole code because something is causing there to be a constant redirect instead of only once.
**Edit 3: I updated my code. The console.log proves that my new variables work and do ==-1. How can I use them to redirect?
Get a random URL from the array, and redirect ?
if ( acceptedWebsites.indexOf(document.location.href) == -1 ) {
var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
document.location.href = url;
}
Try the following:
var acceptedWebsites =['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
var number = Math.floor(Math.random() * acceptedWebsites.length);
number will generate a random number between 1 and the number of entries in your acceptedwebsites array.
window.location = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
The basic jist of the logic would be...
var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
var randomLink = Math.floor(Math.random() * acceptedWebsites.length);
window.location = acceptedWebsites[randomLink];
// Get random site
var randomSite = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
// redirect to selected site
window.location = randomSite;
Generate a "random" key and use window.location.href to redirect the user. Others have posted the same approach, though with less explanation. I'm giving my best to let you actually understand what happens here.
Note that most of this code is comments. It looks longer than it actually is.
var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
// This function returns a random key for an array
function randomKey(arr) {
// Math.random() returns a number between 0 and 0.99999...
// If you multiply this value with the length of an array, you get a
// random floating point number between 0 and that length.
// Use Math.floor() to round it down to the next integer
return Math.floor(Math.random() * arr.length);
}
// Select a random website from the array
var key = randomKey(acceptedWebsites);
var newLocation = acceptedWebsites[key];
// Redirect the user
window.location.href = newLocation;
Try this solution:
var size = acceptedWebsites.length;
var x = Math.floor((Math.random()* size)+1);
Now use loop for value x-1 like
var location = acceptedWebsites[x-1];
window.location.href = location;
If we run this in loop ,we will get different value of x every time between 0-size of array and then we can use that random value to randomly redirect.
window.location doesn't work since content scripts are unprivileged. Further more, window.location.href returns the current location, but it is not a method so you cannot overwrite it.
you'll need to:
Send redirect url from a content script to a background page:
var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
chrome.extension.sendRequest({redirect: url });
In a background page update tab's url which would cause redirect:
chrome.extension.onRequest.addListener(function(request, sender) {
chrome.tabs.update(sender.tab.id, {url: request.redirect});
});

Finding the difference between two fields using JavaScript in iText

I would like to find difference between two fields using JavaScript in iText.
I am able to find the sum of them using below code:
PdfStamper stamperResult = new PdfStamper(readersectionResult, new FileOutputStream(RESULT_NEW));
stamperResult .addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"total2\")')");
Is there any way to find the difference using 'AFSimple_Calculate' similar to what I did in the above code snippet?
Thanks for editing! I tried your suggestion but it does not seem to work for some reason.
stamperResult.addJavaScript(" var total1 = this.getField(\"value1\"); var total2 = this.getField (\"value2\"); var subtr = this.getField(\"total\"); subtr.value = total1.value - total2.value;");
I separated newlines by spaces and added right escape characters.
I was also thinking of using a different logic for subtraction using AF methods : like this
stamperResult.addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"-total2\")')");
In the above code I was trying to add -(negative value) to total 2 so that it will be subtracted from total1 though the AF method is still 'SUM'.
But that does not work.
The below simple code seem to work :
stamperResult.addJavaScript("var nameField = this.getField('total');" +
"nameField.setAction('Calculate'," +
"'subtract()');" +
"" +"function subtract(){this.getField('total').value
= (this.getField('total_1').value -this.getField('total_2').value); }");
I updated your question because it contained many spelling errors. I didn't edit the code snippet because I don't know what the original code snippet is like. In any case: I think something went wrong during the copy/paste process, as I don't think your code snippet compiles in its current state.
In any case: as far as I know the AF-methods (the AF stands for Adobe Forms) may not be present in every viewer, and as far as I know Adobe didn't implement a way to subtract values from each other in the AFSimple_Calculate method.
For these two reasons, you may prefer regular JavaScript instead of using a pre-canned function that may or may not be pre-canned.
This regular JavaScript may look like this:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var subtr = this.getField("difference");
subtr.value = total1.value - total2.value;
I'm not sure if that answers your question. Maybe you just want:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var namefield = total1.value - total2.value;
You can put these lines inside a String using the right escape characters and replacing the newlines by spaces or newline characters.
Of course, you need to trigger this code somewhere. Below you'll find an example that puts the negative value of the content of a value1 field into a value2 field.
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("js.pdf"));
document.open();
writer.addJavaScript("function makeNegative() { this.getField('value2').value = -(this.getField('value1').value); } ");
Rectangle rect1 = new Rectangle(40, 740, 200, 756);
TextField value = new TextField(writer, rect1, "value1");
value.setBorderColor(GrayColor.GRAYBLACK);
value.setBorderWidth(0.5f);
PdfFormField field = value.getTextField();
field.setAdditionalActions(PdfName.BL, PdfAction.javaScript("makeNegative();", writer));
writer.addAnnotation(field);
Rectangle rect2 = new Rectangle(40, 710, 200, 726);
TextField neg = new TextField(writer, rect2, "value2");
neg.setBorderColor(GrayColor.GRAYBLACK);
neg.setBorderWidth(0.5f);
writer.addAnnotation(neg.getTextField());
document.close();
}
Note that I used a Blur action. This means the method will be triggered as soon as you select another field after filling out the value1 field.

Categories