Project Euler 30

July 12th, 2008

static void Main(string[] args){

var numbers = Enumerable.Range(2, 999999);var fifthps = from n in numbers where n == fifthp(n) select n;

Console.WriteLine(fifthps.Sum());Console.ReadLine();}

static IEnumerable<double> digits(double num){

double remainder = num;

while (remainder > 9){

double next = Math.Truncate(remainder/10);yield return remainder - next * 10;remainder = next;

}

yield return remainder;}

static double fifthp(double num){

var d = from n in digits(num) select Math.Pow(n, 5);return d.Sum();}

Earthquake in Chengdu and Mianyang China

May 12th, 2008

I woke up to the sound of CCTV News blaring the tidings that a magnitude 7.8 earthquake just hit the most populated area of China.  Most westerners have heard of major Chinese cities like Shanghai, Beijing, Hong Kong, Guangzhou — and even Nanjing, Hangzhou, Suzhou, and Shenzhen.  But few know about Chongqing; the biggest city in China, with more than 30 million people.

The earthquake was centered on a line between Chengdu and Mianyang in Sichuan province, just outside Chongqing.  This is an area with relatively modest foreign influence, but massive population.  Because of its central position between north and south, as well as access to cheap hydroelectric power, Microsoft is building a massive data center in Chengdu, a joint venture with HP billed as the “largest high-availability data center in Asia”.

Scoble is reporting that several people twittered the earthquake as it happened.  This is no surprise, since roughly 1 out of every 5 people in China would be able to feel an earthquake of that magnitude centered in Chengdu.  We are talking about a population the size of the U.S. population who would feel the earthquake, even if you assume that the north and south were completely unaffected.  There would be hundreds or thousands of English-speaking expats in Shanghai who could feel it.

It’s silly in the extreme to act like twitter is somehow breaking news, though.  Masses of people within China found out about the earthquake as it was happening via messages from friends on QQ (which is massively more popular than twitter), and CCTV carried the news almost instantly.  I suppose it’s cute that some English-speaking expats using echo-chamber technology were able to *also* report the event on twitter, but even the tweetscan example seems a bit lame to me.  When I search for tweets with the word “地震”, tweetscan gives me nothing — apparently tweetscan doesn’t care about Chinese.  Perhaps this explains why Scoble and BBC are reporting only English tweets from China.

Building a Startup in a Week

April 25th, 2008

My co-worker, Kevin, recently filmed the pilot episode of a new reality series on “A Startup in a Week”.  A team of startup guys, including Adam Loving, built a Facebook app to raise money for good causes like building a school in Cambodia.

There are 5 episodes, and some fun drama — debates over how to monetize the app, some politics with the non-profit, and so on.  But the team is pretty productive.  The designer is amazingly fast with Maya, and Adam cranks out code in no time.  There was no staging here; this was all done in an actual week with no collusion beforehand.

I’ve embedded episode 4 here, which has links back to episodes 1-3.  You should probably start at episode 1; over on Adam’s blog.  Each episode goes pretty quickly.


A Startup A Week - Episode 1 Day 4

Processing iTunes Library with LINQ

April 11th, 2008

Fresh from the inaugural cabal of ‘08, I wanted to do some automated processing tasks on my iTunes library.  I was delighted to see how easy it is to do this using LINQ to XML.

The iTunes library XML file is a rather awkward format.  The semantics are dependant on document node ordering, which is just unwieldy.  You can see a sample here.  In order to make the file more easy to query, I transformed it to a format like this:

<song>
  <TrackID>1999</TrackID>
  <Name>Classid</Name>
  <Artist>The Ace Of Clubs</Artist>
  <AlbumArtist>The Ace Of Clubs (Luke Vibert)</AlbumArtist>
  <Album>Benefist</Album>
  <Genre>Acid Disco</Genre>
  <Kind>MPEG audio file</Kind>
  <Size>9255508</Size>
  <TotalTime>385462</TotalTime>
  <TrackNumber>4</TrackNumber>
  <Year>2007</Year>
  <DateModified>2007-08-31T08:37:18Z</DateModified>
  <DateAdded>2008-03-09T18:37:50Z</DateAdded>
  <BitRate>192</BitRate>
  <SampleRate>44100</SampleRate>
  <SortAlbumArtist>Ace Of Clubs (Luke Vibert)</SortAlbumArtist>
  <SortArtist>Ace Of Clubs</SortArtist>
  <PersistentID>76F0C7752DA0CE57</PersistentID>
  <TrackType>File</TrackType>
  <Location>
    file://localhost/C:/data/music/Copied/copied%2009-04-07/luke%20viber
    t%20as%20ace%20of%20clubs%20-%20benefist/The%20Ace%20Of%20Clubs%20-%2004%20-%20C
    lassid.mp3
  </Location>
  <FileFolderCount>-1</FileFolderCount>
  <LibraryFolderCount>-1</LibraryFolderCount>
</song>

using the following LINQ code:

var rawsongs = from song in loaded.Descendants("plist").Descendants("dict").Descendants("dict").Descendants("dict")
        select new XElement("song",
            from key in song.Descendants("key")
            select new XElement(
                ((string)key).Replace(" ",""),
                (string)(XElement)key.NextNode)
                );

var songs = from song in rawsongs where song.Element("Location") != null select song;

Note that the code doesn’t actually read the file until I query; it transforms in a streaming manner.  Once I created the streaming filter, I could run queries like the following.

Show all protected (DRMd) songs:

from song in songs where song.Element("Protected") != null select song

Count the number of each type of song:

from song in songs
group song by (string)song.Element("Kind")
  into MyGroup
  select new { Key = MyGroup.Key, Count = MyGroup.Count() }

Count songs by rating:

from song in songs
group song by (string)song.Element("Rating")
  into MyGroup
  select new { Key = MyGroup.Key, Count = MyGroup.Count() }

From here it is trivial to do things like:

  • Eliminate duplicate files
  • Mirror ratings from the library to the file metadata
  • Create playlists with protected files to "archive" them
  • Find files which aren’t matched across playlist and hard drive

From an awkward file format to queries that are as easy as cake.  LINQ to XML is pretty sweet!

More on "Cultural Genocide" in Tibet

April 3rd, 2008

A number of people have asked me for more details about the situation in Tibet.  I’ve realized that I have a tendency to excoriate the hypocrisy in the press without necessarily offering much additional in the way of compensatory education.  So I’d like to remedy things by explaining the facts in more detail.

First, read this excellent paper from UCLA: "How Repressive is the Chinese Government in Tibet?".  I find the analysis to still be relatively biased toward a western viewpoint, but far more factual than the typical newspaper report.  You should definitely read it, but I’ll highlight some of the key facts:

  1. Population of ethnic Tibetans has grown dramatically during the period of time when they were supposedly being swamped by Han Chinese.
  2. Chinese government allows Tibetans to have 4+ children, while Han Chinese are permitted only 1 child.
  3. Han population live almost entirely in the cities, working reconstruction contracts, and tend to get the hell out of town as soon as they can.
  4. While Han Chinese culture may be influencing Tibetan youngsters to abandon their traditions (which are not that old or traditional, BTW); western culture is influencing them more.

The paper concludes that Tibetans may be suffering from "social and economic marginalization", but there is no concerted effort to commit cultural or ethnic genocide, and in fact the Chinese government is engaged in what amounts to an affirmative action program to attempt to offset some of this marginalization.

I largely agree with this conclusion.  When you have a nation with 1 billion Han Chinese and 6 million Tibetans, it’s going to be very difficult for Tibetans to gain an economic or cultural edge.  Han Chinese culture is chauvinistic.  Nothing malicious about it; that’s just the way it is.

Furthermore, the efforts of the Chinese government to lift Tibetans seem to me to be more honest and consistent than the efforts of U.S. in affirmative action.  A far larger percentage of black and latino men in America are in prison today than are Tibetan men in prison in China.  The rabble-rousers would like you to believe that Tibetans in China are treated like Rodney King, but the media were only able to capture footage of Tibetans massacring innocent Chinese women and children.

The "religious freedom" arguments are also hollow.  One thing people don’t realize is that there is no right of free assembly in China, and religions are strictly regulated by the government.  Trust me; these restrictions are strongly supported by the Han Chinese, and they would vote the restrictions back in if they were relaxed.  That’s just the way it is.

Take the Christian Church in China, for example.  The government stuffed the church with Cardinals selected by the communist party.  The pope excommunicated the Cardinals.  The Cardinals happily continue to serve as heads of the church.  This is how religions work in China.  But this is normal.  The Tibetan monks have more autonomy than any other religious group in China.

It’s interesting, isn’t it?  George Bush ignores the situation of black and latino people in America, while claiming that the less-severe marginalization of Tibetans is a "human rights" issue.  He doesn’t say a word about the Christian church in China being controlled by the government, but demands that the religious dictator head of a buddhist death cult be given sovereignty over the central government.  And he argues that the Tibetans are being too heavily influenced by Chinese culture, while the Tibetan exile government has become essentially a puppet and mouthpiece of the western "cult of liberty" and a pawn for the neocons C.I.A.