I successfully compiled my program. Now how do I run it? - javascript

I want to solve Project Euler Problem 1:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Here's my code:
\documentclass[10pt,a4paper]{article}
\usepackage{hyperref}
\newcommand*\rfrac[2]{{}^{#1}\!/_{#2}}
\title{Solution to Project Euler Problem 1}
\author{Aadit M Shah}
\begin{document}
\maketitle
We want to find the sum of all the multiples of 3 or 5 below 1000. We can use the formula of the $n^{th}$ triangular number\footnote{\url{http://en.wikipedia.org/wiki/Triangular_number}} to calculate the sum of all the multiples of a number $m$ below 1000. The formula of the $n^{th}$ triangular number is:
\begin{equation}
T_n = \sum_{k = 1}^n k = 1 + 2 + 3 + \ldots + n = \frac{n (n + 1)}{2}
\end{equation}
If the last multiple of $m$ below 1000 is $x$ then $n = \rfrac{x}{m}$. The sum of all the multiples of $m$ below 1000 is therefore:
\begin{equation}
m \times T_{\frac{x}{m}} = m \times \sum_{k = 1}^{\frac{x}{m}} k = \frac{x (\frac{x}{m} + 1)}{2}
\end{equation}
Thus the sum of all the multiples of 3 or 5 below 1000 is equal to:
\begin{equation}
3 \times T_{\frac{999}{3}} + 5 \times T_{\frac{995}{5}} - 15 \times T_{\frac{990}{15}} = \frac{999 \times 334 + 995 \times 200 - 990 \times 67}{2}
\end{equation}
\end{document}
I compiled it successfully using pdflatex:
$ pdflatex Problem1.tex
This is pdfTeX, Version 3.14159265-2.6-1.40.15 (TeX Live 2014/Arch Linux) (preloaded format=pdflatex)
.
.
.
Output written on Problem1.pdf (1 page, 106212 bytes).
Transcript written on Problem1.log.
It generated the following output PDF file along with a bunch of other files with scary extensions:
How do I run this PDF file so that it computes the solution? I know the solution to the problem but I want to know how to execute the PDF file to compute the solution.
The reason why I prefer LaTeX over other programming languages is because it supports literate programming, an approach to programming introduced by Donald Knuth, the creator of TeX and one of the greatest computer scientists of all time.
Edit: It would also be nice to be able to print the computed solution either on the screen or on paper. Computing the solution without printing it is useful for heating the room but it is so hot already with the onset of summer and global warming. In addition, printing the solution would teach me how to write a hello world program in LaTeX.

So, today seems to be a safe day to tackle this problem...
The OP does not seem to be quite so PDF-savvy.
However, he obviously is quite a literate LaTeX guy.
Which means, he also must be knowing TeX very well, given he is so much of a Donald Knuth admirer...
So much for the preliminaries.
Now for the real meat.
First, to quote the official PDF-1.7 specification document:
PDF is not a programming language, and a PDF file is not a program.
(p. 92, Section 7.10.1)
However, the pre-decessor of the PDF format, PostScript, IS a Turing-complete programming language... Turing-complete, just as TeX is, the creation of Donald Knuth, one of the greatest computer scientists of all time.
PostScript files, on the other hand, ARE programs, and can easily be executed by PostScript printers (though this execution time cannot reliably be determined in advance).
Hence, and second, the OP should be able to find a way to convert his hi-level LaTeX code to low-level TeX code.
That code needs to emit a PostScript program, which in turn can be executed by a PostScript printer.
Writing that TeX code should be trivial for somebody like the OP, once he is given the PostScript code that should be the result of his TeX code.
I myself am not so well-versed with the TeX aspect of that problem solving procedure.
However, I can help with the PostScript.
The PostScript which the OP's TeX code should produce goes like this (there are for sure more optimized versions possible -- this is only a first, quick'n'dirty shot at it):
%!PS
% define variables
/n1 999 def
/t1 334 def
/n2 995 def
/t2 200 def
/n3 990 def
/s1 67 def
/t3 2 def
% run the computational code
n1 t1 mul
n2 t2 mul
n3 s1 mul
sub
add
t3 div
% print result on printer, not on <stdout>
/Helvetica findfont
24 scalefont
setfont
30 500 moveto
(Result for 'Project Euler Problem No. 1' :) show
/Helvetica-Bold findfont
48 scalefont
setfont
80 400 moveto
( ) cvs show
showpage
Send this PostScript code to a PostScript printer, and it will compute and print the solution.
Update
To answer one of the comments: If you replace the last section of PostScript code starting with /Helvetica findfont with a simple print statement, it will not do what you might imagine.
print does not cause the printer to output paper. Instead it asks the PostScript interpreter to write the topmost item on the stack (which must be a (string)!) to the standard output channel. (If the topmost item on the stack is not of type (string), it will trigger a typecheck PostScript error.)
So sending a modified PostScript file (where print has replaced the last section of my PS code) to the printer will not work (unless that printer supports the interactive executive PostScript mode -- which is not a standard part of the PostScript language). It will work however if you feed that file to Ghostscript in a terminal or cmd.exe window.

You can't run pdf files. You need to use the latex command instead of pdflatex. e.g.
latex Problem1.tex
Here's some documentation

Related

Exponential growth one-liner function fails on one test but not others?

Can anyone debug this for me? I've been staring at it and testing things for hours but can't seem to get it working. I'm starting to wonder whether the coding challenge web app is wrong and I'm right!
The task is this:
Find the number of generations it would take for a population p0 to surpass a max population p given that the population increases by percent% plus aug every generation
My one-liner is as follows:
nbYear = (p0, percent, aug, p) => {
return Array(999).fill().filter((_,i)=>Array(i+1).fill().map((_,j)=>j==0?p0:0).reduce((y,_)=>Math.round(y*percent/100+y+aug))<=p).length;
}
The code I've written passes on 100 tests but fails on one in particular (they don't disclose the input paramters on which it failed). All it says is that the function gave the output: 51 when it should have been 50
I've concluded that the one test for which it failed must have been for a value over 999.

H.264 decoding failing to parse unusual frame headers

I'm reading an H.264 stream from a camera on a raspberry pi. I'm trying to pass this to Broadway via websockets to render in a web page.
The stream contains NAL units, and I'm chunking it on the [0,0,0,1] start prefix code, to send and then decode NAL units individually. I think that's working fine, but Broadway can't decode the result I end up with.
Digging into the parsing code I've based this on though, it seems to be expecting the 5th byte (straight after the start prefix code) to be either:
0x65 - an I frame
0x41 - a P frame
0x67 - an SPS frame
0x68 - a PPS frame
I've seen a lot of mention of these elsewhere too. All the units I have coming through though seem to start with (in order):
0x27 0x64 (1st unit)
0x28 0xEE (2nd unit)
0x25 0x88 (3rd unit, then intermittently later on)
0x21 0x9A (every single other unit in the stream)
What do these headers mean in an H.264 stream? Do they suggest something about what I need to do to match Broadway's expectations?
(If the full code would be useful to understand this better, see https://github.com/pimterry/pi-cam/tree/d801de9b)
This was a red herring: the actual issue for me here was that some existing frame dropping logic meant that I wasn't passing Broadway the first few frames in the stream, and it was failing to render. Replaying the SPS and PPS frames for all new connections and making sure they're never dropped has fixed the issue nicely.
I also did work out what these bytes are though, which helped, and may be useful for others for reference:
Hex Binary NAL type Meaning
0x65 = 11 00101 = type 5 Coded slice of an IDR picture (I-frame)
0x41 = 10 00001 = type 1 Coded slice of a non-IDR picture (P-frame)
0x27 = 01 00111 = type 7 Sequence parameter set (B-frame)
0x28 = 01 01000 = type 8 Picture parameter set (B-frame)
0x25 = 01 00101 = type 5 Coded slice of an IDR picture (B-frame)
0x21 = 01 00001 = type 1 Coded slice of a non-IDR picture (B-frame)
Special thanks to Jaromanda X though - the NAL units article [here] and the nal_ref_idc article made working this out much easier.

Get RGB color of coordinates: Adobe Illustrator

I'm using ExtendScript to work on JavaScript for Adobe Illustrator 2015. Is there any way I could get RGB values from a coordinate in the code below?
// declares a document
var doc = app.activeDocument;
// sets x and y coordinates to get color from
var xPosition = 70.0;
var yPosition = 64.0;
This is what needs work:
// gets rgb values
double redValue = doc.getRGBColor(xPosition, yPosition).red;
double greenValue = doc.getRGBColor(xPosition, yPosition).red;
double blueValue = doc.getRGBColor(xPosition, yPosition).red;
I've googled quite a bit and found this.
It doesn't work, though, either because it was posted in 2009, or because it was meant to be in photoshop.
A solution to the problem or translation of that post would be greatly appreciated.
[EDIT: My apologies for giving essentially an AppleScript answer to your ExtendScript question. I was just looking over AS questions and forgot I went to a different section. I can only hope that you are on a Mac. If not, I guess I'll just eat my downvotes and weep.]
There is a workaround. The advantage of it (and part of the workaround nature of it) is that it works in all apps. The downside is that it requires python (which should be on your Mac anyway - fairly easy to install if not), and two pieces of third party software (both free), "checkModifierKeys" and "cliclick". I've been using a script that appears in my script menu for years.
The python part is described here: http://thechrisgreen.blogspot.com/2013/04/python-script-for-getting-pixel-color.html
This script can be saved, made executable and invoked using the AS do shell script command.
and the rest of it, for selecting a point on the screen and for waiting for the control key to be pressed (that's how mine works) is pretty simple.
The basic checkModifierKeys part (which waits until the Control key is pressed) is:
set controlIsDown to false
repeat until (controlIsDown)
set initialCheck to ((do shell script "/usr/local/bin/checkModifierKeys control"))
if initialCheck = "1" then set controlIsDown to true
end repeat
The cliclick part (which gets the coordinates) is:
set xyGrabbed to do shell script "/usr/local/bin/cliclick p"
It may seem like a long way to go for it, but it works great. My version converts the rgb value to hex with this handler, which is useful for my purposes:
to makeHex(theNumber) --was anInteger
--Converts an unsigned integer to a two-digit hexadecimal value
set theResult to ""
repeat with theIndex from 1 to 0 by -1
set theBase to (16 ^ theIndex) as integer
if theNumber is greater than or equal to theBase then
set theMultiplier to ((theNumber - (theNumber mod theBase)) / theBase) as integer
set theResult to theResult & item theMultiplier of ¬
{1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"}
set theNumber to (theNumber - theBase * theMultiplier)
else
set theResult to (theResult & "0")
end if
end repeat
theResult
end makeHex
Yes, this solution doesn't work, because in vector editors such as Illustrator, color is applied to vector item (path) on the whole not to separate pixels. Even if you work with pixel image in illistrator there are no scripting functions to get pixel color.
I think it could be achieved via the rather monstrous solution:
Rasterize the artrboard.
Create Object Mosaic (where one tile ~> one pixel).
Figure out which one of the tiles lies underneath the given coordinates and pick its color.

Duplicates found in JavaScript created UUID from browser ad unit [duplicate]

This relates to this question. I am using the code below from this answer to generate a UUID in JavaScript:
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
This solution appeared to be working fine, but I am getting collisions. Here's what I have:
A web application running in Google Chrome.
16 users.
about 4000 UUIDs have been generated in the past two months by these users.
I got about 20 collisions - e.g., a new UUID generated today was the same as about two months ago (different user).
What is causing this issue and how can I avoid it?
My best guess is that Math.random() is broken on your system for some reason (bizarre as that sounds). This is the first report I've seen of anyone getting collisions.
node-uuid has a test harness that you can use to test the distribution of hex digits in that code. If that looks okay then it's not Math.random(), so then try substituting the UUID implementation you're using into the uuid() method there and see if you still get good results.
[Update: Just saw Veselin's report about the bug with Math.random() at startup. Since the problem is only at startup, the node-uuid test is unlikely to be useful. I'll comment in more detail on the devoluk.com link.]
Indeed there are collisions, but only under Google Chrome. Check out my experience on the topic in Google Chrome random number generator issue
It seems like collisions only happen on the first few calls of Math.random. Because if you just run the createGUID / testGUIDs method above (which obviously was the first thing I tried), it just works without any collisions whatsoever.
So to make a full test one needs to restart Google Chrome, generate 32 byte, restart Chrome, generate, restart, generate, etc.
Just so that other folks can be aware of this - I was running into a surprisingly large number of apparent collisions using the UUID generation technique mentioned here. These collisions continued even after I switched to seedrandom for my random number generator. That had me tearing my hair out, as you can imagine.
I eventually figured out that the problem was (almost?) exclusively associated with Google's web crawler bots. As soon as I started ignoring requests with "googlebot" in the user-agent field, the collisions disappeared. I'm guessing that they must cache the results of JS scripts in some semi-intelligent way, with the end result that their spidering browser can't be counted on to behave the way that normal browsers do.
Just an FYI.
The answer that originally posted this UUID solution was updated on 2017-06-28:
A good article from Chrome developers discussing the state of Math.random PRNG quality in Chrome, Firefox, and Safari. tl;dr - As of late-2015 it's "pretty good", but not cryptographic quality. To address that issue, here's an updated version of the above solution that uses ES6, the crypto API, and a bit of JS wizardy I can't take credit for:
function uuidv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
console.log(uuidv4());
I just ran a rudimentary test of 100,000 iterations in Chrome using the UUID algorithm you posted, and I didn't get any collisions. Here's a code snippet:
var createGUID = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
var testGUIDs = function(upperlimit) {
alert('Doing collision test on ' + upperlimit + ' GUID creations.');
var i=0, guids=[];
while (i++<upperlimit) {
var guid=createGUID();
if (guids.indexOf(guid)!=-1) {
alert('Collision with ' + guid + ' after ' + i + ' iterations');
}
guids.push(guid);
}
alert(guids.length + ' iterations completed.');
}
testGUIDs(100000);
The answers here deal with "what's causing the issue?" (Chrome Math.random seed issue) but not "how can I avoid it?".
If you are still looking for how to avoid this issue, I wrote this answer a while back as a modified take on Broofa's function to get around this exact problem. It works by offsetting the first 13 hex numbers by a hex portion of the timestamp, meaning that even if Math.random is on the same seed it will still generate a different UUID unless generated at the exact same millisecond.

Seed-based world generation using sin

I'm tried to make some world generation mechanism using Math.random() whenever I needed something random, but then decided that I wanted it seed-based, so, given a seed, I changed all of the Math.random() to Math.sin(seed++)/2+0.5, hoping it would do the same thing, but would be the same if the seed was the same seed.
Then someone made me notice that the sin wave hasn't got even distribution, and finally I saw why some of my code was working strangely.
I was wondering if there was a simple fix, or if there isn't, another very simple seed based randomizer like this
So, I looked at your method, t1wc, and I found that it isn't actually evenly distributed. It is significantly more likely to spit out numbers near 0 or near 1 than it is to spit out numbers near 0.5, for example. This is just a consequence of the way that the sine function works.
Instead, you might try using a method called Blum Blum Shub (named after the authors of the original paper, wonderfully). It is evenly distributed and quite fast. Given a seed, it works as follows:
Square the seed and put the result in a temporary variable (x).
Take the mod of x base M.
M is a product of two large primes.
The value of x is a new seed to be used for future calculations.
Return x/M as your pseudo-random number. It will be evenly distributed between 0 and 1.
Below is a simple implementation of a Blum Blum Shub:
var SeededRand = function(seed, mod1, mod2)
{
return function()
{
seed = (seed*seed) % (mod1*mod2);
return seed/(mod1*mod2);
};
};
If you want to make a new random number generator, you just call:
var rand = SeededRand(seed, mod1, mod2);
Where seed is some initial seed (1234567890 works well), and mod1 and mod2 are some large primes (7247 and 7823 work well). rand is just a variable that I've defined to hold the output.
Now, to start getting random values, you just call:
rand();
Which will spit out a different value each time you run it.
If you have any questions, please ask!
There is a very nice seed-based randomizing script already made. It can be found here.
ok guys, found out this is what I'm really looking for:
(((Math.sin(seed.value++)/2+0.5)*10000)%100)/100
It sends out even spreaded numbers, and I guess it's a lot simpler than any other number generator I've seen

Categories