Friday, May 31, 2013

In bash: pick a file at random out of a tree...and do something with it

This is a random one-liner (I cheated and used semicolons, so sue me) I came up with recently while desiring something random out of my random video collection to watch.

The ingredients to this one-liner are as follows:

nFiles=$(find ./ -name '*.avi' | wc -l)
The number of files to sample from.
chooseFile=$[$RANDOM*$nFiles/32767]
The line of output from which a file will be picked. $RANDOM is a bash variable that will always be a random number that ranges from 0 to 32767 each time it is referenced.
awk '{if (NR=='$chooseFile'){print $0;}}'
Pick a line of output and echo it.

Now, of course, to print this random file's path:

nFiles=$(find ./ -name '*.avi' | wc -l); chooseFile=$[$RANDOM*nFiles/32767]; find ./ -name '*.avi' | awk '{if (NR=='$chooseFile'){print $0;}}'

To use it as an argument is just one more simple step:

mplayer "$(nFiles=$(find ./ -name '*.avi' | wc -l); chooseFile=$[$RANDOM*nFiles/32767]; find ./ -name '*.avi' | awk '{if (NR=='$chooseFile'){print $0;}}')"

Wrapping in double-quotes allows the code inside of $( and ) (which gets executed, and its text entered right there in the command line) to evaluate while not letting any spaces or shell metacharacters that might lie in the printed path text get interpreted as marks that delineate shell arguments.

Thursday, December 20, 2012

Vital information about the end of the world

Back in my '09 visit to Montana, I visited these two guys my dad befriended when he first moved there. Knowing that I'm an astronomy buff, they showed me this:

(click to embiggen)

I didn't know what to say, really; I was speechless. Instead, I shrugged, said "approximately the size of the moon? Can't wait to see that" and snapped this photo, which has been lost in the pile of bits until now. There were a few other pages in the informational goldmine that featured predictions of other great disasters for the three years that were to come (from 2009), but sadly, I neglected to take pictures of them. I think one of them predicted Rebecca Black's Friday. If only I had only been more diligent as the data packrat I'm wont to be...

Well, better late than never, right?

Saturday, October 13, 2012

Something I Shall Attempt

I recently was in communication with a human resources representative from Google, and learned some about their hiring process. She recommended Project Euler as a refresher in algorithms. I said I would be ready in three weeks. I shall give myself two for the "first stage", in which I shall attempt to solve five problems per day, so that I have completed a total of 70 problems October 26th.

In the process of writing this blog post my motivations changed from making the statement of "hey, look at me" so that I would be more inclined to keep my word to "good heavens, I really need some accountability so that I follow through with this." I am loathe to post answers publicly on this blog (because that would be like spoiling a puzzle and denying others the opportunity to solve it on their own) so I implore any mathematically inclined people out there who knew me at the University or otherwise to hold me accountable. Send me an email (demitri.morgan@gmail.com). Before submitting an answer to Project Euler I'll email it to you. I give every such volunteer permission (and encouragement) to e-harrass me if I am not forthcoming with solutions.

There will be a few days (October 19, 20 & 21) when I will not be at my computer, and thus not able to complete a solution. I will, however, attempt to come up with an algorithm for solving each problem, return on Sunday the 21st, and put it into code.

This may sound like pathetic bravado or delusions of grandeur, but I don't care how far I've fallen. but I'm bored with not giving myself intellectual challenges often enough. Instead of pleasure reading myself to sleep I'll sup on head-scratching and hard thinking in attempt to re-awaken mathematical problem-solving in myself.

Saturday, October 6, 2012

This needs to exist.

If I had time and money, I'd start a business. Specifically, a website. This website would be the Yelp of grocery stores.

Imagine this, only only live, with local prices, updated whenever a grocery store updates their prices via product database integration. Grocery stores would use it for promotions and attracting customers by showcasing their deals. Customers will use it to have something akin to this, only online and stored in an online profile wherein prices are seen in real-time and they can mix and match to save time and money.

For a monthly service charge, consumers would be granted additional features, among them a mobile application (that would open locations for them in Google Maps/Navigate) and access to a tool that allows them to put in their starting point address, cost of gas, gas mileage of their vehicle, and their shopping list, and find (for any given day) the least costly grocery shopping route. That's where the fun happens; the underpinnings of the website would be an optimization problem like that of the traveling salesman.

For a monthly service charge, businesses would be granted the tools to automatically push and synchronize changes in their prices to the online database. Furthermore, as consumers add usage data, businesses could be provided with statistical predictions of how many more customers would be drawn to their store after the adjustment of any item's price. This would give them a means to gauge the elasticity of demand and adjust their prices to maximize profit.

Why does this interest me?
  • It involves numerical methods, ergo it is awesome.
  • It addresses a fundamental human need: to forage for victuals.
  • It optimizes the effort to fulfill said human need, reducing gasoline consumption and wasted resources, time being one of them. That would free up resources for other pursuits.
  • It exposes and makes readily available information where previously the best way of getting that information was physically going to a store.
  • It's something that I want, so I could use it myself.
That being said, why does this not exist yet?

Saturday, September 15, 2012

In which many thousands of Facebookers can't think outside the square (yet some can)

Disclaimer: this is going to come across as very self-righteous and elitist to everyone who hasn't taken a college-level course in math, and pretentious/sloppy/arrogant to everyone else. So sue me, I'm inebriated and need an excuse to add a post to this blog. Tomorrow I'll probably regret it, considering how it's not a good idea to drink and derive.


A recent brain teaser has been making the rounds on Facebook. Take a look at the screenshot I made of it. I mean, sweet Jesus, that averages over 1.3 comments per second. I congratulate The Inquisitr for finding a very easy way to draw hundreds of thousands of eyes in one direction.

To be fair, I noticed at least one person in each 100+ swath of comments who got it right. Now, as for the puzzle itself, we can strain ourselves looking at the figure in every way imaginable, or we can use...MATH! Here's the comment I tossed into ocean (and subsequently edited, to remove length units from what should be dimensionless expressions):
Squares of length L1: 4^2
Squares of length L2: 2
Squares of length L2/2: 8
Squares of length L1*2: (4-2+1)^2 = 3^2
Squares of length L1*3: (4-3+1)^2 = 2^2
Squares of length L1*4: 1

All in all, if my drunken arithmetic is correct, that would be a total of 40 squares.
Here's what I meant by $L_1$ and $L_2$:
$L_1$
The squares of which there are four in each direction in the large "containing" square
$L_2$
(Which I later discovered was of equal length to L1) the two squares that are "superimposed" above and below the center of the figure. Whatever, I didn't hold a ruler up to the screen and was too lazy to use a pixel ruler.
$\frac{L_2}{2}$
Those $L_2$ squares are split into quadrants by the lines in the main 4x4 "grid"

Now, here's what I meant by the rest of it: if you think of a size of square (in the unit $L_1$) as having two degrees of freedom in position (horizontal and vertical) that's two in the exponent of the number of possible positions in a given direction (since all dimensions are the same, stick 'em all together as factors and it's a power of that one number: the length). Now, in this grid, it takes only a little observation to note that in any given direction, a square of a round number of units in length can occupy a number of positions one greater than the number of units in the grid minus its own length. Square that number, and voila, the number of squares of that length in the figure.

Take a square of size 2, for instance. Allow it to sit on an edge. There are two positions it could scoot over to (the two more units to the other edge), so with the position it is in, that makes three. A total of the grid size (4) minus the length of the square (2) plus the position it occupies (1), making $N_{L_i}=(4-i+1)^2$. For the squares composed of multiple other squares in the grid, therefore, we have:

\[ N_{tot}=\sum_{i=1}^{4}{(4-i+1)^2} \]

Combined with the other squares (the two "superimposed" squares that are each cut into four more squares by grid lines (making a total of 8+2 = 10 squares) this gives us a total of 40. Now why, pray tell, did I think of figuring it out this way? Countless times when I did math homework, each time learning new techniques, I contemplated in hindsight how I had always done things the hard way before then, and how, if I had taken sufficient time to study the problem, I could have been able to understand it in a broader and more abstract sense. This is the essence of most mathematics (and physics, for that matter): to use such understanding to generalize problems into timeless kernels of fact that can be efficiently re-used for all problems that fall into the same form.

"An equation is for eternity."

Albert Einstein

Whether equations appear useful here and now is of no concern; the important fact remains that they exist and we've found them, so that should they ever be needed there is no need to re-invent them as proverbial wheels, nor to solve the problem at hand in a primitive and inefficient way. They're like tools. Don't Be a Primitive Pete.

The general application of the above expression is that given a square grid of arbitrary length n, the total number of squares in the grid is:

\[N_{tot} = \sum_{i=1}^{n}{(n-i+1)^2} \]

Note how the only effort required was to change 4 to "n". That's a lot less than straining one's eyes over a 100x100 grid of squares while the brain overheats from the menial tasks of counting and exclusivity handed to short-term memory.

So there you have it. Kids, listen to your math teachers, for the love of all that makes civilization great.

Monday, May 23, 2011

"mydata" : Python script for rsync shorthand

This script is for those messy ones of us who have copies of all their personal files on multiple different machines/storage devices but with a possibly different folder structure at each location, and want to synchronize them using rsync. It's quick, it's simple and it makes rsync way easier to use.

Saturday, April 23, 2011

LUKS/XScreenSaver 1/2-factor authentication with a USB drive/password

Late last month (couldn't write about it then; had taxes, the physics GRE, and the spring Nasa EAP poster symposium to work on), I began a project: setting up Xubuntu Linux on an old Acer Aspire AS1691 for my dear old dad, who has always been quite open with me about his general dislike for computers, and his being a neo-luddite. But I wasn't just going to set up a user-friendly GNU/Linux environment for him on the thing: I made it my goal to make it secure and easy to use at the same time.