Java & Programming 15 Oct 2007 08:02 pm

Reverse an Array in Place

I was just looking through some code. I noticed that an array needed to be reversed and that the original order was never needed again. This was a perfect time to reverse the array in place. This was Java so I looked in the Arrays class. But alas there wasn't a reverse for primitive arrays! Java Lists get a reverse method in the Collections class. But primitive arrays get no such love.

Also, I thought of using the asList method from Arrays, but that just seems like a ton of overhead.

So instead I wrote a quick little method for ints and any other primitive type.

Here is the int example:

JAVA:
  1. public static void reverseInPlace(int[] iar) {
  2.   final int length = iar.length;
  3.   final int halfLength = length / 2;
  4.   final int lengthMinus1 = length - 1;
  5.   for (int i = 0; i <halfLength; ++i) {
  6.     final int index2 = lengthMinus1 - i;
  7.  
  8.     //swap
  9.     int tmp = iar[i];
  10.     iar[i] = iar[index2];
  11.     iar[index2] = tmp;
  12.  }
  13. }

Basically, this method just swaps the items from the front to back until reaching the middle of the array. If the loop continued on, it would just switch everything back and the original order would be preserved!

The other implementations for the rest of the primitive types can be found here.

Process Explorer & Utilities & Windows 12 Oct 2007 01:27 pm

Yet Another Reason to Love Process Explorer — Part 2

This is a bit different from my last post about Process Explorer. Process Explorer is so powerful that I accidentally killed a different process than I wanted. This wasn't through some fancy schmancy search with regular expressions and kill accident. I just highlighted a process and clicked the Process Explorer Red X.

I then proceeded to click 'Yes' on the simple dialog: pe_are_you_sure_want_to_kill_xxxx.PNG.

Notice the blackened out word at the end of the Dialog's text? Well that is essentially what my brain did when I read that dialog.

So, long story short I killed the wrong process. Nothing seemed to break for a few hours. Then when I went to debug a couple of things, I wasn't able to connect to a service that was supposed to be running. I restarted somethings on my end, then remembered, "Oh yeah, I killed a random process earlier." I restarted the killed service and lo and behold everything started working again.

Lesson learned here kids: Don't kill random processes and then wonder why stuff breaks!

Process Explorer is part of the Microsoft Sysinternals set of utilities.

Javascript & Programming & Web 12 Oct 2007 12:40 pm

onbeforeunload IE7 Woes!

Was just having a problem getting the IE7 onbeforeunload event to be canceled. Found this blog about it: OnBeforeUnload, IE7, Assigning event handlers to null and the problems that arise.

Pretty simple, just wrap the return with a boolean:

JAVASCRIPT:
  1. var goodExit = false;
  2. window.onbeforeunload = confirmExit;
  3. function confirmExit()
  4. {
  5.   // normally this if-check wouldn't be here,
  6.   // cause the event handler was nulled elsewhere.
  7.   // But IE7 doesn't respect the null, and
  8.   // wants the handler to not return anything
  9.   // (not even null).
  10.   if (!goodExit)
  11.   {
  12.     return "Leaving this page will cause all unplaced orders to be discarded."+
  13.     "  Are you sure you want to leave the page?";
  14.   }
  15.   // notice no return statement here!
  16. }
  17. </script>
  18.  
  19.     . . . . .
  20.  
  21. <input type="image" src="<%=AppService.BASEDIR%>/images/lgrequest.gif" onclick="javascript: goodExit = true; window.onbeforeunload = null; document.forms[0].submit();" />

This example was stolen from Brandon Himes and his blog, The Busted Mug. Thank you Brandon!

Process Explorer & Utilities & Windows 08 Oct 2007 08:26 am

Yet Another Reason to Love Process Explorer — Part 1

Well, I just found another reason to love Process Explorer here: How To Identify What Programs Started svchost.exe in Windows.

This article describes how to use the command line and/or Process Explorer to find out what the hell svchost.exe is doing.

Open a command prompt and enter:

tasklist /svc /FI "IMAGENAME eq svchost.exe"

The above command will list all the svchost.exe processes and display the programs (DLL's) that have been started by svchost.exe.

Process Explorer is part of the Microsoft Sysinternals set of utilities.

Hopefully, this will become a series of posts. We'll see!

Java & Programming 05 Oct 2007 01:33 pm

A Good Reasoning to Nullify an Object!

If you overwrite a reference with a new object, the object is first created and /then/ the reference is overwritten, which means the object can be only GCed /after/ the new object has been created.

Usually this doesn’t matter. However, if you want to overwrite an object which is so big that it only fits once into the memory, you’ll need to null the reference before creating/assigning the new instance.

Eg:

//FatObject fits only once into memory
FatObject fatty;
fatty=new FatObject();
fatty=new FatObject();

Will bomb with OOME. Whereas…

FatObject fatty;
fatty=new FatObject();
fatty=null;
fatty=new FatObject();

Will be fine, because the second creation of the FatObject will trigger a full GC and the GC will be able to clear enough memory (since the old reference has been nulled).

Well, that rarely matters, but it’s good to know.

Jos Hirth wrote this in response to this post by Jeroen van Erp.

In this post, Jeroen was talking about a long standing bug/issue/misunderstanding of how Strings are handled in Java. The problem that occurs only comes up when taking a substring of a large String. If all that is wanted is the small substring, the substring must be wrapped by a new String call. This will allow the larger String to be garbage collected. Normally when a substring is taken, the underlying char array is shared. This is usually good practice, because it saves memory.

But, and this is a big but, if the substring is taken from a large string, then memory can be leaked, because a lot of memory is wasted in the underlying character array.

Now, why did I quote the above passage from the comment area? Cause I had never thought of the issue Jos brought up. It's interesting to think of an object of which only one can fit in memory. Let alone creating a second!

Uncategorized 05 Oct 2007 01:32 pm

Wow, it’s been a long time!

I haven't really posted in here for a long time.

But I think I am going to try to more. I want to turn this into a place where I take snippets of blogs or articles and place the relevant parts here. Keeping the links in this blog with the snippets will help me remember things. If the page disappears, well then at least I have this snippet!

(that is as long as this blog lives)

Life 15 Jul 2006 10:35 pm

Information Addiction

I have come to the realization that I must be addicted to information. If I am not actively involved in something like work, gaming, or watching TV, I have to be reading. It doesn't matter what.

I could be reading an article about Paris Hilton's latest escapades in the night life of LA. I could be reading an article about the coming processor war between AMD and Intel, and how they are competing for my hard earned cash. I could be reading a book about quantum physics and how the universe is really just a huge quantum computer.

I am not a big Mac fan, yet I read technical articles on its inner workings. Why do I do this? It doesn't help me with my day to day job. I don't have a Mac to tweak.

I read quantum physics books because I think it is cool to say, "I read a quantum physics book last week" (also I like the weirdness that is the submicroscopic realm).

Can the human mind process all this data into anything relevant? After all these articles are read, do I gain anything? Do I actually extract information?

I have actually caught my self feeling somewhat at a loss, when I go to my custom Google homepage and notice that I have read all the articles currently there. I am like "what do I do now?" Where do I find more stuff to read to fill this urge?

Why do I fill my brain with all this stuff? Can the brain actually fill up? Am I actually discarding things? Should I remember something that is now replaced by the latest antics of Tom Cruise? I hope I haven't lost anything important.

I am addicted to information...

Admitting it is half the battle, right?

Life & Technology 05 Jul 2006 04:32 pm

Rites of Passage

I was watching a TV show the other day. A girl was about to have her 13th birthday. This seems reasonable for a TV show to have.

The thing that caught my attention was the girl asked for a progression of things:

Girl: Can I get a cell phone?
Parents: No.

Girl: Can I get a pager (why anyone would want this in todays age is anyone's guess)?
Parents: No.

Girl: Can I at least get a computer in my bed room?
Parents: No.

Girl: Well, then could I get my own email address?
Parents: Well, we'll think about it.

... time in show progresses ...

Parents: Ok, you'll get your own email account, but we'll have the password and can check on any emails sent/received/deleted.
Girl (all giddy and overflowing with delight): Yay, this is the best birthday ever.

My question is: When did getting an email change into a Rite of Passage for young girls and/or boys. I can understand the parents wanting full access, but why is the girl giddy?

What happened to cars (or just even driving) being the main Rite of Passage?

Java & Programming & Technology 27 Jun 2006 04:53 pm

Changing the Color of a JCheckBox check in a JTable

Ever wanted to change the color of a JCheckBox in a JTable to the table's foreground color? Now you can!

Example Screenshot:
Lower Table has a white check instead of a black check!

This is a renderer for Booleans in a JTable.

JAVA:
  1. import java.awt.Color;
  2. import java.awt.Component;
  3. import java.awt.Graphics;
  4.  
  5. import javax.swing.JCheckBox;
  6. import javax.swing.JTable;
  7. import javax.swing.table.TableCellRenderer;
  8.  
  9. /**
  10. * This class implements a boolean renderer for a JTable.  It overrides the icon for the CheckBox to draw in the
  11. * foreground color.
  12. */
  13. public class BooleanRenderer extends JCheckBox implements TableCellRenderer {
  14.    public BooleanRenderer() {
  15.        super();
  16.        setHorizontalAlignment(JCheckBox.CENTER);
  17.        setIcon(new ColorableMetalCheckBoxIcon());
  18.    }
  19.  
  20.    public Component getTableCellRendererComponent(JTable table, Object value,
  21.                                                   boolean isSelected, boolean hasFocus, int row, int column) {
  22.        if (isSelected) {
  23.            setForeground(table.getSelectionForeground());
  24.            super.setBackground(table.getSelectionBackground());
  25.        } else {
  26.            setForeground(table.getForeground());
  27.            setBackground(table.getBackground());
  28.        }
  29.        setSelected((value != null && ((Boolean) value).booleanValue()));
  30.        return this;
  31.    }
  32.  
  33.    /**
  34.     * Changes the check box check mark to be the foreground color.<br/>
  35.     * <b>NOTE:</b>This was found here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4449413 .
  36.     */
  37.    static class ColorableMetalCheckBoxIcon extends javax.swing.plaf.metal.MetalCheckBoxIcon {
  38.        protected void drawCheck(Component c, Graphics g, int x, int y) {
  39.            final Color old = g.getColor();
  40.            g.setColor(c.getForeground());
  41.            super.drawCheck(c, g, x, y);
  42.            g.setColor(old);
  43.        }
  44.    }
  45. }

This is the corresponding Editor.

JAVA:
  1. import java.awt.Component;
  2.  
  3. import javax.swing.DefaultCellEditor;
  4. import javax.swing.JCheckBox;
  5. import javax.swing.JTable;
  6.  
  7. /**
  8. * This class implements a boolean editor for a JTable.  It overrides the icon for the CheckBox to draw in the
  9. * foreground color.
  10. */
  11. public class BooleanEditor extends DefaultCellEditor {
  12.  
  13.    public BooleanEditor() {
  14.        super(new JCheckBox());
  15.        JCheckBox c = (JCheckBox) getComponent();
  16.        c.setHorizontalAlignment(JCheckBox.CENTER);
  17.        c.setIcon(new BooleanRenderer.ColorableMetalCheckBoxIcon());
  18.    }
  19.  
  20.    public Component getTableCellEditorComponent(JTable table,
  21.                                                 Object value,
  22.                                                 boolean isSelected,
  23.                                                 int row,
  24.                                                 int column) {
  25.        JCheckBox c = (JCheckBox) getComponent();
  26.        if (isSelected) {
  27.            c.setForeground(table.getSelectionForeground());
  28.            c.setBackground(table.getSelectionBackground());
  29.        } else {
  30.            c.setForeground(table.getForeground());
  31.            c.setBackground(table.getBackground());
  32.        }
  33.        c.setSelected((value != null && ((Boolean) value).booleanValue()));
  34.        return c;
  35.    }
  36. }

Quick and Dirty Tester Program!

JAVA:
  1. import java.awt.Color;
  2. import java.awt.Dimension;
  3. import java.awt.FlowLayout;
  4.  
  5. import javax.swing.*;
  6. import javax.swing.table.AbstractTableModel;
  7. import javax.swing.table.DefaultTableModel;
  8.  
  9. /**
  10. * shows how to use the BooleanEditor and the BooleanRenderer.
  11. */
  12. public class JTableBooleanTester extends JFrame{
  13.     public JTableBooleanTester(){
  14.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.        
  16.         Dimension dim = new Dimension(200,75);
  17.        
  18.        
  19.         TestTableModel ttm = new TestTableModel();
  20.        
  21.         JTable table1 = new JTable(ttm);
  22.         table1.setForeground(Color.WHITE);
  23.         table1.setBackground(Color.DARK_GRAY);
  24.         JScrollPane sp1 = new JScrollPane(table1);
  25.         sp1.setPreferredSize(dim);
  26.        
  27.         JTable table2 = new JTable(ttm);
  28.         table2.setForeground(Color.WHITE);
  29.         table2.setBackground(Color.DARK_GRAY);
  30.         table2.setDefaultEditor(Boolean.class, new BooleanEditor());
  31.         table2.setDefaultRenderer(Boolean.class, new BooleanRenderer());
  32.         JScrollPane sp2 = new JScrollPane(table2);
  33.         sp2.setPreferredSize(dim);
  34.        
  35.         getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
  36.         getContentPane().add(sp1);
  37.         getContentPane().add(sp2);
  38.        
  39.         pack();
  40.     }
  41.  
  42.     public static void main(String[] args) throws Exception {
  43.         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  44.         SwingUtilities.invokeLater(new Runnable(){
  45.             public void run() {
  46.                 JFrame frame = new JTableBooleanTester();
  47.                 frame.setVisible(true);
  48.             }
  49.            
  50.         });
  51.     }
  52.    
  53.     static class TestTableModel extends AbstractTableModel{
  54.         Object[][] data = {{Boolean.TRUE, "Testing 1!"},{Boolean.FALSE,"Testing 2!"}};
  55.         Object[] names = {"Bool", "Something!"};
  56.        
  57.         public int getRowCount() {
  58.             return data.length;
  59.         }
  60.  
  61.         public int getColumnCount() {
  62.            
  63.             return names.length;
  64.         }
  65.  
  66.         public Object getValueAt(int rowIndex, int columnIndex) {
  67.             return data[rowIndex][columnIndex];
  68.         }
  69.        
  70.         public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
  71.             switch(columnIndex){
  72.             case 0:
  73.                 data[rowIndex][columnIndex] = aValue;
  74.             }
  75.             fireTableDataChanged();
  76.         }
  77.        
  78.         public boolean isCellEditable(int rowIndex, int columnIndex) {
  79.             return 0 == columnIndex;
  80.         }
  81.  
  82.         public Class getColumnClass(int columnIndex){
  83.             return data[0][columnIndex].getClass();
  84.         }
  85.     }
  86. }

Life 25 Jun 2006 09:37 am

Victorian Era vs Now Era

I once had a thought (yes it does happen). I don't know if I read the concept somewhere or if I actually thought it up originally.

It seems we have had a total swapping of signals since the Victorian Era. In the Victorian Era both men and women wanted to be pale. If you were tanned, that meant you spent all your time outside. In this era outside meant hard work in the fields and whatnot.

Nowadays, if you are pale it means that you are hard at work inside an office, factory, etc. If you are tanned, it means you are sitting around outside doing nothing at the beach, pool, etc.

I don't want to take away from our farmers, construction workers, and produce pickers. These are important jobs. They still get tan from hard work outside. I was talking about the rich folk, who do nothing all day (*cough*P. Hilton*cough*).

Next Page »