philihp.com

New in Java 7: switch()ing on Strings

Finally, Java can switch on Strings! No more inefficient strings of if/else chains or Hash lookups or translation into Enums. Finally just clean readable and intuitive code.

switch(suit) {
  case "club":
  case "diamond":
    trickValue = 20;
    break;
  case "heart":
  case "spade":
    trickValue = 30;
    break;
  case "no-trump":
    trickValue = 40;
    break;
}

It’s actually just syntactic sugar. The java compiler renders this all down to int switching by pre-computing the .hashcode() of all of the labels since they have to be constants anyway (unlike languages like PHP where you can do some really neat shenanigans). Because this still renders down to primitives, Java still gets the jump table optimizations that were the whole motivation of the switch construct in the first place.

If you use Eclipse, switching on a String will still probably give you an error. It wasn’t until September 2011′s release (3.7.1) that this was implemented. There were versions of Indigo that didn’t support this, so you’ll need the latest one.

SOPA Strike, January 18

On January 18, this website is going on strike.

Your website can too, just put this into the header of your HTML:

<script>
var a=new Date;
if(18==a.getDate() && 0==a.getMonth() && 2012==a.getFullYear())
  window.location="http://sopastrike.com/strike";
</script>

How to Create an Empty SAS Dataset

If you were to do this in SAS to create an empty SAS dataset:

data mytable;
run;

It would actually create a dataset with one row. The data step cycles through once, hits the end (run), outputs a row, then comes back and finds it has no more rows to process so it stops. To stop this one row from being output, try this instead:

data mytable;
  stop;
run;

DIY LED Hula Hoop

UPDATE: I’ll be making a lot more of these, but I don’t want to horde the know-how of how to do it. Anyone with a soldering iron can make one, so I’m sharing what I know.

Bill of materials

So I made an LED hula hoop. It has 96 LEDs, 105 different modes, and lasts about 3.5 hours at full brightness. It’s also the only hoop I’ve seen that displays a message using persistence of vision.

Batteries

The batteries are wired in parallel so they basically just add up the mAh capacity. If they were wired up in series, the voltage would add instead. The hoop would work with just one, but then the mass wouldn’t be evenly distributed and the hoop balance would be a little off. And it would also go dead in half an hour. They start out sending 4.2 volts, but slowly drop until it hits 3.3 volts (the actual discharge characteristics depend on the temperature). They are the same size and shape as AA batteries, but keep in mind, AA batteries are 1.5v, and these are not.

The batteries are wired up behind a Tenergy 32003 to protect them from overdraining and overcharging. When in use, the hoop will actually cut off before the voltage goes too low to prevent damage to the batteries. The circuit protects from overcharging too, but so does the charger. The 32003 didn’t want any more than 4.2 volts, so finding a wall-wart charger was a little difficult. I ended up wiring a charger directly into an extra charger for 18650s. It only charges at 600 mA, so I’m sure there’s a more appropriate charger out there.

LEDs

The LEDs operate on a daisy chained controller, and come printed on a pretty flexible strip. 5050 RGB LEDs are mounted about every 2.5 inches. The LEDs are rated at 5 volts, but will dim when given lower voltage. I was actually able to overcharge them and get them brighter, but was warned this would burn the drivers if I kept at it so I stopped. My original plan was actually to run on 7.4 volts to keep them this bright.

Arduino

At Bonnaroo 2010, I met this guy who had built his girlfriend a hoop, and was a huge help in this one. He pointed out that the Pro Mini can run off of anywhere from 3 volts to 5 volts. The difference is really just the crystal operating at 8 or 16 mHz (for stability concerns). So that made things a lot simpler.

The LED strip has two inputs for power, and two wires going to the Arduino for data and clock. The library that Adafruit provides for it lets us use any two pins on the Arduino to control it via bit-banged software SPI. However, if you happen to have pins 11 and 13 free (which we do), then you can use hardware SPI and get roughly 3-4 times the speed which makes POV at high speeds (i.e. while hooping) possible. If you edit the source of the LPD8806 library, you can change the SPI clock divider to go even faster, but you’ll have to worry about interference.

I used pins 2, 3, and 4 for pushbutton switches. 4 can be moved around, but 2 and 3 were pretty important because I send the arduino its sleep mode to save power. External interrupts pull it out and wake it up, but only pins 2 and 3 can do this.

So basically there’s an “off” button, a “mode” button, and a “color” button. The modes cycle through various modes of “Solid”, “Dragonfly”, “Strobe”, “Chasers”, “Chasers with statics”, “Rainbow”, and POV. The colors cycle through various colors, except for the chasers, where you can cycle through all the colors, and keep cycling through adding another chaser every time, up to 5. The POV mode displays the logo of Carrot Creative. Space is pretty cramped on the chip, so it’s just stored as an on/off bitmask, 32 pixels high (so each column is 1 32-bit int). The first few columns are green, so I just did that bit manually.

Assembly

Probably the most frustrating part of this project is the assembly. It’s important for everything to be snug inside of the hoop so it doesn’t rattle, and wrapping it in bubble wrap greatly helps this, but the bubble wrap grips the sides of the tube. Taping three unraveled coat hangers together, and using them to pull the strip through helped a lot. Another thing to watch out for is that the contacts need to be insulated and wrapped in electrical tape so you don’t get shorts inside the tube which are nearly impossible to find and fix without a complete disassembly.

Source Code & EAGLE Wiring Diagrams

Please stop creating links with target=”_new”.

Just stop. This is wrong; instead, use this:

target="_blank"

I don’t know who started these nasty rumors that “_new” would open up in a new browser. As far back as I can tell, no browser has ever recognized “_new”.

The whole point of the target dates back to when browsers used frames to split up your browser. If you had a link in a sidebar on the left, and you wanted that link to open up in the main frame to the right, you would specify “main” as the name of that frame in your frameset page, and target=”main” in your links on the sidebar. When the user would click on a link in the sidebar, the browser would say “hmm, I’m supposed to open this up in the ‘main’ frame, do I have one named that?”. If it didn’t, it would open up the link in a new window, and give that window the name of the target of the link. This is what would happen with target=”_new”; a new browser would open up with a name of “_new”.

The problem is this if you click on this first link, then read it and go “oh that’s interesting” and click on some links in it to goto further pages on it, everything seems fine. But then if you click this second link below, and then the third link, they open up in the same browser!

If only they had a target of “_blank”, they would all open up in a new browser every time.

It’s a simple fix. Just stop using target=”_new”.

You keep using that word. I do not think it means what you think it means. – Inigo Montoya

Or just stop opening links in new browsers all together; it has been considered bad usability for over a decade now. The user will open your links up in a new window if they want to.

Using Eclipse WTP with Maven’s eclipse:eclipse Goal

If you use Maven’s “eclipse:eclipse” goal to generate a project descriptor for eclipse, by default you’re just going to get a plain Java project. You’ll have to add in the Dynamic Web facet in order to tell Eclipse that you can deploy this project in a web container. The easy way around this is to configure the maven-eclipse-plugin in the pom.xml file like this:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-eclipse-plugin</artifactId>
  <version>2.8</version>
  <configuration>
    <wtpContextName>some/url/context</wtpContextName>
    <wtpversion>1.5</wtpversion>
  </configuration>
</plugin>

Also, I like to download sources and Javadoc, which makes navigating in Eclipse a lot easier. This can be done like this.

<plugin>
  ...
  <configuration>
    <downloadSources>true</downloadSources>
    <downloadJavadocs>true</downloadJavadocs>
  </configuration>
</plugin>

Supposing you also want your project to have JPA facets, or other additional project facets you could also add them in like this

<plugin>
  ...
  <configuration>
    <additionalProjectFacets>
      <jpt.jpa>2.0</jpt.jpa>
    </additionalProjectFacets>
  </configuration>
</plugin>

And all of these can be combined to do this

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-eclipse-plugin</artifactId>
  <version>2.8</version>
  <configuration>
    <wtpContextName>list</wtpContextName>
    <wtpversion>1.5</wtpversion>
    <downloadSources>true</downloadSources>
    <downloadJavadocs>true</downloadJavadocs>
    <additionalProjectFacets>
      <jpt.jpa>2.0</jpt.jpa>
    </additionalProjectFacets>
  </configuration>
</plugin>

Servlet Filters mapped to JSPs in Tomcat

Servlet filters were introduced in the Servlet 2.3 spec a long time ago. They’re basically classes that you can add to any Java webapp that intercept every request and can do anything you can imagine (e.g., compress output, translate, handle authentication, the only limit is yourself). They’re added into the web.xml file where every webapp starts, and since every webapp framework builds off of a servlet, they can be used with every webapp regardless of the framework. And they’re part of the Servlet spec, not the J2EE spec, so you don’t need a bloated container to use them; you can use them in Tomcat. Basically, what I’m saying is, they’re really useful wherever you are, no matter what you’re doing.

To install a servlet filter in your web.xml, you’d do something like this:

<filter>
  <filter-name>jpa-filter</filter-name>
  <filter-class>com.philihp.utils.EntityManagerFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>jpa-filter</filter-name>
  <servlet-name>action</servlet-name>
</filter-mapping>

Where the filter will filter any servlet named “action” — which in this case is the name of my Struts 1.3 controller that I had defined earlier. Rather than specify a servlet-name, you’re allowed to use a url-pattern, but according to Sun, the url-pattern has to begin with a "/" slash, so the following does not work.

<filter-mapping>
  <filter-name>jpa-filter</filter-name>
  <url-pattern>/*.jsp</url-pattern>
</filter-mapping>

JSPs are essentially servlets, compiled from JSP code the first time they’re run. But you don’t have to define every JSP file in your web.xml file, because they’re already defined by the container. There’s a servlet (in tomcat, it’s the Jasper engine) mapped to /*.jsp. In the Tomcat guts, you can find it at conf/web.xml, which is the basis web.xml file; every webapp deployed in Tomcat is actually extended from this file

<servlet>
  <servlet-name>jsp</servlet-name>
  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>

Since JSPs are essentially running as the servlet name “jsp”, you can attach a servlet-filter to them with a filter-mapping similar to this:

<filter-mapping>
  <filter-name>jpa-filter</filter-name>
  <servlet-name>jsp</servlet-name>
</filter-mapping>

How to get the Last Day of a Month in SAS

SAS has a really neat function called intnx, which will increment a date to the next of an interval.

For example, if you have a date (any date. maybe the current date?), you can get the date of the first day of the next month by doing this:

data _null_;
  d = '11JUN2011'd;
  format d date9.;
  put d;
  d = intnx('month',d,1);
  put d;
run;

Which outputs

11JUN2011
01JUL2011

But to get the “Last Day” of the current month, you have to be clever. The last day of the current month is the day before the first day of the next month. SAS Dates are internally stored as a number of days since some point, so just subtract one from it.

data _null_;
  d = '11JUN2011'd;
  format d date9.;
  put d;
  d = intnx('month',d,1)-1;
  put d;
run;

Which outputs

11JUN2011
30JUN2011

Maximum sizes of MySQL Blob Fields

This is not immediately obvious from the documentation(, which as it seems is often the case, was written for people who just like to read documentation, and not for people who are looking for answers).

The maximum sizes of the MySQL Blob fields are as follows:

Type What They Say It Needs That Means You Get
TINYBLOB L+1 bytes, where L < 28 256 bytes
BLOB L+2 bytes, where L < 216 65 kilobytes
MEDIUMBLOB L+3 bytes, where L < 224 16 megabytes
LONGBLOB L+4 bytes, where L < 232 4 gigabytes

There. Now it’s on the Internet and people can find the answer to this question. The world is a better place.

This is how I feel about C

I don’t think C gets enough credit. Sure, C doesn’t love you. C isn’t about love–C is about thrills. C hangs around in the bad part of town. C knows all the gang signs. C has a motorcycle, and wears the leathers everywhere, and never wears a helmet, because that would mess up C’s punked-out hair. C likes to give cops the finger and grin and speed away. Mention that you’d like something, and C will pretend to ignore you; the next day, C will bring you one, no questions asked, and toss it to you with a you-know-you-want-me smirk that makes your heart race. Where did C get it? “It fell off a truck,” C says, putting away the boltcutters. You start to feel like C doesn’t know the meaning of “private” or “protected”: what C wants, C takes. This excites you. C knows how to get you anything but safety. C will give you anything but commitment

In the end, you’ll leave C, not because you want something better, but because you can’t handle the intensity. C says “I’m gonna live fast, die young, and leave a good-looking corpse,” but you know that C can never die, not so long as C is still the fastest thing on the road.

Anonymous on 4chan