Thursday, February 3, 2011

Random Numbers in SQL

I needed a SQL query to insert a range of values randomly into each record of a table variable.

The SELECT statement would use the random number in conjunction with a CASE statement to pick from two different values to insert into a field, in effect tagging records randomly with one value or the other. 

My first attempt involved trying to grab the one's digit of the second of today's date via the getdate() function, and based on whether this value is even or odd, pick one or another of the values to assign to a field for the record I insert.
INSERT INTO @MyTableVariable (MyField)
SELECT

    CASE
        WHEN RIGHT(DATEPART(s, getdate()), 1) IN (0, 2, 4, 6, 8) THEN 32
        WHEN RIGHT(DATEPART(s, getdate()), 1) IN (1, 3, 5, 7, 9) THEN 39
    END AS MyField

FROM dbo.MyTable t

The result wasn't quite what I expected. Instead of one of each inserted value appearing randomly in the resulting table variable for MyField, the same value appeared each and every time.

As it turns out, I didn't realize that in the CASE statement, the seconds portion of the current time, the "seed" if you will, only got set once at the beginning of the SELECT. There is nothing in the statement to prompt the function to update the current time with every iteration, every record examined from MyTable, it only performs a one-off examination of the seconds and goes with that for the rest of the operation.


My solution involved using instead the one's digit of the integer primary key of the source table, like so.
INSERT INTO @MyTableVariable (MyField)
SELECT

    CASE                  
        WHEN RIGHT(t.ID, 1) IN (0, 2, 4, 6, 8) THEN 32        -- Even
        WHEN RIGHT(t.ID, 1) IN (1, 3, 5, 7, 9) THEN 39        -- Odd            
    END AS MyField

FROM dbo.MyTable t

In this case, the subset of data that I'm querying from MyTable is just that, a subset, which means that the primary key (ID) won't be in any particular order; there are plenty of opportunities for the one's digit to be odd or even. This provides a reasonably random sampling of records in the resulting table variable.





Thursday, January 27, 2011

Improve Firefox Performance with Processor Affinity

Firefox seems to frequently stutter or lag while doing seemingly trivial tasks like scrolling or even typing following the most recent Firefox 3 update.
 
Enter the concept of processor affinity, which enables you to direct applications to utilize one or more specific CPU cores in your multicore system. I discovered a blog post where the author describes creating a shortcut in Windows Vista or Windows 7 which will execute a given application with a specific processor affinity configuration.


PROCEDURE

  1. Copy and paste to create a copy of your current shortcut to Firefox on the Desktop.
  1. Pick a single CPU core, in decimal, to dedicate to Firefox, according to the chart below. I chose CPU 3 on my quad-core system.
0001 = 1 (CPU 0)
0010 = 2 (CPU 1)
0100 = 4 (CPU 2)
1000 = 8 (CPU 3)

  1. In the Target box, copy and paste one of the following lines (the first for 32-bit Windows, the second for 64-bit), and change x to match the value you chose in the above step (change the paths as necessary if your Firefox lives in a different location).
C:\Windows\System32\cmd.exe /c start "C:\Program Files\Mozilla Firefox\" /affinity x firefox.exe

C:\Windows\System32\cmd.exe /c start "C:\Program Files (x86)\Mozilla Firefox\" /affinity x firefox.exe


  1. Click OK to accept the changes, then close and reopen Firefox using the modified shortcut.

Windows XP also allows for changing the processor affinity setting for a given process via the Processes tab in Task Manager, but this setting is applied only for that instance of the application, so you can't use the above method to have a shortcut which automatically sets the affinity every time. If you try it, you'll get this error message:

Invalid switch - "/affinity"

Fortunately, a freeware utility called RunFirst exists which will perform in a similar manner, except it will by default assign only the first CPU core in the system to have affinity with the application you're running it with. To use it, create a batch file to execute firefox.exe like this:
      RunFirst.EXE "C:\Program Files\Mozilla Firefox\firefox.exe"


Now, Firefox has its very own CPU core to use on my Windows 7 system, which is advantageous in that the other applications running on my system need only contend with one core being potentially monopolized by some CPU-expensive operations which Firefox initiates.

I tend to browse with many (read: dozens) of tabs open simultaneously, as well as a plethora of add-ons installed such as AdBlock Plus, DownThemAll, FireBug, GreaseMonkey, FoxyTunes, Stylish, FiddlerSwitch, and more. Mine is hardly a “vanilla” setup, and given that these various add-ons let alone Firefox itself are developed by a variety of developers with a variety of coding styles, even bugs, it’s entirely likely that I’m a victim of chaos, that an unfortunate confluence of events are conspiring to kick my browsing experience in the teeth. 

At least this way, I'm letting Firefox do it's thing on just a single core, rather than having it bleed over onto the others and potentially making my other running processes unhappy.

So far, Firefox seems to be significantly more responsive than before!



Tuesday, January 11, 2011

Just Another Day...

This is January 11, 2011, or 1/11/2011 in middle endian format.

Some in numerological circles claim that this day is one of opportunity, but not without hardship. Others interested in conspiracy theories feel intuitively that something "big" will happen this day.

Really, though, isn't it just another day??

The Gregorian calendar is today used by much of the civilized world to track and organize days. Remarkable as it is that the international community could agree upon using this convention to track the passage of time, it's nevertheless a tool, like the clock, even the chip in computers used to store the date and time.

That's not to say this day is meaningless. People will be born, die, get married, have a birthday, have sex for the first time, celebrate an anniversary, enjoy their first day of vacation, and countless other activities which will etch this date as meaningful to them or their loved ones for the rest of their lives. 

In the meantime, though, the world keeps turning, and we're just along for the ride. The earth continues to journey as part of the Milky Way galaxy from its point of origin in the distant past to wherever it's destined to go at a speed of around several hundred kilometers per second.

The day surely is meaningful, as we are living it here and now, experiencing it. It has value if for no other reason than that we're here to participate in and enjoy it. Nevertheless, it's just a convention. I seriously doubt the universe cares how we keep track of the time we occupy in life, since it's been here and will likely still be here far longer than we ever will.



Saturday, January 8, 2011

Windows 7 to XP FIle Sharing Problems

Recently, I had serious issues with trying to enable file sharing between my newly-installed Windows 7 laptop and my Windows XP SP3 desktop.

Windows 7's Network and Sharing Center

I have a home wireless network, where my Windows 7 laptop, on wireless, normally shares files perfectly well with my Windows XP desktop. Inexplicably, one day the capability to share files via wireless ended; I couldn't even ping my XP desktop from my 7 laptop let alone browse its file shares, whether by computer name or IP address. And yet, over a wired connection, file sharing performed flawlessly!


Here's a list of what I tried:
  • Updated drivers for network hardware.
  • Disabled Windows Firewall on both machines.
  • Verified internet connectivity from the laptop.
  • Ensured both PCs share the same workgroup name.
  • Verified connectivity over wireless, from the laptop to the router.
  • Completely reinstalled the TCP/IP stack on the Windows XP computer.
  • Deleted and recreated routes using the ROUTE command on both computers.
  • Reinstalled the Link Layer Topology Discovery (LLTD) responder on the XP box. 
  • Followed Microsoft's docs on enabling File and Printer Sharing under Windows 7.
  • Verified that shared folders on both PCs had proper permissions.
  • Removed remnants of Norton Internet Security with the Norton Removal Tool from the XP box, which I'd long since uninstalled but remnants of which still remained.
  • Followed Microsoft's steps for sharing files among different Windows versions, including rerunning the network setup wizards for each respective operating system.

In spite of all these steps, I still couldn't even ping the XP box from the 7 laptop, and I couldn't see the XP box from the 7 laptop in the network, although I could see, but not access, the 7 laptop from the XP box.

The solution turned out to be unexpected.

A few years ago, I replaced the factory firmware of my venerable Buffalo WHR-HP-G54 wireless router with DD-WRT, a free, open-source, Linux-based firmware which can be applied as a drop-in replacement for the manufacturer firmware, and can expand the features of your router to boot.

The firmware, as with most anything in IT, is evolving, and it'd been some months since I'd last updated the version of DD-WRT; it was v24 SP1 from around August, 2010, whereas the newest version is v24 pre-SP2. Some other DD-WRT users had reported issues sharing files on their own networks. DD-WRT itself has an option under Wireless => Advanced Settings called AP Isolation, which allows you to prevent wirelessly networked devices from interacting with one another, and presumably with wired clients, via the router (in my case, this option has always been disabled).

At this point, my options were exhausted, so I took the plunge and updated the DD-WRT firmware. Even though the latest version is technically still in beta, it seemed worth a shot; I've never had trouble since first installing DD-WRT, and the fact that it allows you to preserve your existing settings without wiping the router's NVRAM made it even more appealing.

The result? It worked! Suddenly, rather than being met with the dreaded System Error 53 when attempting to map a network drive letter from the laptop to the desktop or trying to browse to a shared folder via Windows Explorer, I got a prompt asking me to authenticate to the XP box using my credentials, and finally regained access!

If you haven't updated your router's firmware in a while, it might be worth a shot, particularly if you use DD-WRT as I do and have perhaps encountered what might be a bug in your current version of the firmware. 

If you still have the factory firmware, I'd strongly suggest you consider replacing it with DD-WRT or another like Tomato, which can not only offer your router and network more stability and performance, but also unlock features that the manufacturer might not even offer in their own relatively anemic firmware.