Random Noise

cat /dev/random >> /dev/dsp

BDA Graph using GraphEdit for Genpix

leave a comment »

genpix-graph genpix-graph-2

Pictures speak thousand words.

Written by Vivek Unune

January 1, 2013 at 4:53 pm

Posted in VC++

Tagged with ,

ssh: Server refused our key

leave a comment »

I know you must be banging your head against the wall over this. I did.

Make sure use are logged in as the user you want to give ssh permission to:

su sshuser
cd ~/

All you need to do is fix the permissions and owner on .ssh and authorized_keys:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown sshuser:sshuser ~/.ssh
chown sshuser:sshuser ~/.ssh/authorized_keys

This should do the work.

Written by Vivek Unune

December 17, 2012 at 4:47 pm

Posted in linux

Tagged with , ,

Windows 8 or not to Windows 8

leave a comment »

I clearly remember how exited I was when I got the Windows XP Beta CD with one of the magazines my friend use to subscribe (BYTE?). I used Windows 98 then. And I knew in and out of the OS like nothing else. After observing the UI overhaul in XP I was truly impressed. I actually use to peek inside the system dlls for cool icons shipped with XP.

Fast Forward 10 years and I’m in same situation. After using Windows 7 for over 2 years – I have my brain wired to it. And I love it. I have a win7 on laptop and HTPC which run 24/7. With dedicated linux NAS to store media. Windows 8  RTM was out on MSDN over two months ago, immediately I wanted to take it for a spin. So, I installed it on my HTPC. After two months all I can say is that the pain is unbelievable!

1. Start button – I must be the millionth person to say this. Listen MS – ability to view installed applications and quickly access it is necessary. Now you would argue you can do the same from Metro screen. No – it takes up lot of scrolling and searching for the “tile” and trying to recognize the icon for that application! I end up creating shortcuts of all the frequent programs on desktop -which is ugly. Even my wife misses the start button utterly. Utter pain without it.

2. Take me directly to desktop if I’m using a desktop! - Why do we have the metro welcome/lock screen? Then again I have to go through the metro apps screen to get to desktop!

3. Dropping out the HD codecs and filters! – the whole idea of skipping the hd codecs was pretty lame on MS part. I have a sizable bluray and hd library stored on NAS. With AV receiver and a flat screen hooked to the HTPC – it needs hd codecs out of the box to play these files. After the first day of installation – my wife got frustrated as to why those files aren’t working anymore. She resorted to the win7 laptop instead. When I was back from work I had to install FFDshow filters to get the files to work. Seriously MS – if people have to end up using opensource directshow filters why bother paying for windows at all. I will be more than happy to install Ubuntu or Openelec (XBMC).

4. I’m a power user and let me control my machine – The biggest gripe that I have is getting things done. It has become difficult on Windows 8 to perform day-today activities. Like accessing Control Panel, Searching for files, Shutting down PC, Restarting it, accessing Device manager etc. It is a desktop not a tablet. I was so use to accessing the search. running any app was just few keys away! Why take out the search? Why is Shut Down under Settings?

5. Mouse vs. touch gestures – When I park my mouse at right edge of the desktop it shows me unnecessary options. Also while trying to close a window using the ‘x’,  the options shows up. Again while trying to open the first app (windows explorer) on the task bar. It is not only confusing but frustrating. If I’m using a desktop and when I have no devices that support touch guestures - why does windows enable touch gestures?

After two months of using Win8, yesterday I went back to Windows 7.

Written by Vivek Unune

October 25, 2012 at 9:08 pm

Posted in Uncategorized

Managing personal media and Custom NAS

with one comment

For over a year I used Buffalo Linkstation Duo Pro with 2x1TB mirrored drives. It served me well, but it was starting to gradually fill up – pictures, videos, taxes/documents, more pictures. And there were other things I wanted to move from my local drives, but still needed them to be accessible on-demand – ISOs – Linux, Windows, IDE installers, Old code etc. And then was wife’s music collection, docs etc.

Judging from above I came up with following requirements:

1. At least 4-6TB space. Future proof for 3-4 years
2. Gigabit Network Capable. I’m done with slooow speed NAS
3. Expandable. Add more space as needed.

There were three options available:
Plan A – Buy new NAS drive(s) – solves the problem for now. Average cost $300
Plan B – Build a new low power PC, install FreeNAS or something similar. Move the old NAS drives to this and add more drives. Around $300-$500
Plan C – Purchase Cloud Storage subscription – varies, from monthly to year plans.

Considering the requirements, clearly my options were limited to Plan B. Plan A and Plan C were pre-baked solutions that did not offer me what I really needed. Plan B meant I needed to spend some time for this project.

Components:

I’m a big fan of Micro Center because I can pickup components as and when I need them. Also, they offer pretty good deals and match NewEgg’s prices – minus the shipping costs. Returning stuff is hastle free as well.

So I started looking for best motherboard to get the job done. Essentially, I was looking for a mordern (but not latest and greatest) mobo that had 6 SATA ports, on board graphics chip and a gigabit ethernet. So, I picked up the cheapest one – Gigabyte GA-78LMT-S2P for $43 after MIR, Sempron 145 – 45W, Diablotek EVO Mid Tower ATX case, a 500W power supply and 2x1TB drives.

After spending sometime with the board, I realized that there is a known issue with the GA-78LMT-S2P – it fails to recognize the drives when switched to AHCI mode!! So back I returned it and got the next in line Asrock 880GM-LE FX. This one cost me $10 more, but has a better graphics chip (HD 4250). Not that I would need it. I installed the CPU and spare 4GB ram that I had. Sempron’s can be unlocked to a dual core CPUs, this one didn’t. But that was OK since I needed less power hungry machine. Then I plugged in four drives (500GB, 750GB, 2x1TB new drives)

Software:

I Initially installed FreeNAS on a 8GB flash drive. Now, all my drives were ntfs and soon enough I ran into issues. Drives were failing to mount since they had errors – threre is no way to fix them on linux. These needed to be fixed by connecting them to a windows machine and running CHDISK /force. I took a step back(read below), and thought that if all my drives are ntfs why not run windows instead? More over Windows 8 has this new feature so that you can run it off a usb drive!

New requirement:

At least 32GB is needed for Windows-To-Go. Which meant I need to buy a 32GB flash drive. So I did – Sandisk Glide 32 GB. Installing windows 8 on the flash drive is real pain. With help of GImageX you can copy the install.wim image on to the flash drive. The copy took around 90 minutes!! Argh! Booting from the flash drive and initial setup took around 30 minutes more! Also, using windows-to-go is really really really slow. I cannot stress it enough. Partly the issue was the Sandisk Glide drive but I think more due to how windows worked. It kept hammering the flash drive. I read that USB 3.0 will improve the speed a little and in any case my 880GM-LE FX board didn’t have it. Finally I gave in.

So where was I? I have to convert all my drives to etx3/4 and move around few TB of data. Before I returned the 32GB flash drive, I CHDISK’d all my drives so at least they would mount on FreeNAS PartedMagic. Then I connected the new drives, formatted them to ext4 and copied over the data to new drives, formatted the nas drives to ext4 and copy back the data from new drives. Same for the old 500GB and 750GB – rinse repeat.

FreeNAS vs OpenMediaVault:

In short, OpenMediaVault is what you want. Stable, functional and actively developed.
Returned the dreadfully slow Sandisk Glide and installed OpenMediaValut on 8GB Kingston G3 drive.
Configured the shares and ftp. For detailed setup please read this blog

Performance:

The last but not the least goal was to have gigabit copy speeds. I set the 9K MTU on the interface using the web interface and I was all set. I get around 80Mb/s copy speeds which I’m pretty satisfied.

Expandability:

I ended up removing the 500GB drive and moving all the important documents to it. I will pair that with another 500GB in a Raid 0 configuration. With 5 drives, I now have almost 4.75 TB of space. With 5 more drive slots to go  - it can continue to expand as needed.

As an engineers we are always on a quest to solve problems and in the process we sometimes over-engineer things. I think this to be true in this case. However, the new NAS would be good for another 3-4 years.

Written by Vivek Unune

September 4, 2012 at 6:12 pm

Posted in linux, NAS

Blackberry: ContentHandler and ApplicationMenuItem

with one comment

ContentHandler gives us the ability to register our application, so that our app is invoked automatically
when user clicks to open particular type of a file. ContentHandler uses ‘Server – Client’ model.
Client requests for processing a file type and Server processes it. All the application-filetype bindings are
stored in a Registry, the client must query this registry to find out if there are any handlers available for that
file type. Then invoke it.

To make our app a ‘Server’, we need to implement RequestListener. See below for sample implementation of a mp3 file handler.

It is important to register our app. It is recommended to perform/verify registration once during device startup.
You shoud pass an argument say “startup” during startup to differentiate from other entry points.
In eclipse this can be configured by editing the App_Descriptor.xml.

Also note that APP_IDs used for registration must be unique and failure to do so will render your app unusable.

package com.serialize.apps;

public class Mp3Player extends UiApplication implements RequestListener {
	public static final long MY_APP_KEY = 0x4a23b634ab2baf78L;
	public static final String MY_APP_CLASS = Mp3Player.class.getName();
	public static final String MY_APP_ID = "com.serialize.Mp3Player"
	private Invocation pending;
	private ContentHandlerServer server;
	
	public Mp3Player() {
		try {
			this.server = Registry.getServer(MY_APP_CLASS);
			//start listening formp3 invocation requests
			this.server.setListener(this);	
		} catch (ContentHandlerException e) {
		}					
	}

	public static void main(String[] args) {
		// On device startup register our app
		if (args != null && args.length > 0 && args[0].equals("startup")) {
			ensureRegistration();
		} else {			
			Mp3Player app = new Mp3Player();
			app.enterEventDispatcher();
		}
	}

	private static void ensureRegistration() {
		Object o = RuntimeStore.getRuntimeStore().get(MY_APP_KEY);
		// register only if not done already.
		if (o == null) {
			String[] types = {"audio/mp3"};
			String[] suffixes = {".mp3"};            
			String[] actions = {ContentHandler.ACTION_OPEN};
			String[] actionNames = {"Open with Mp3Player"}; 
			ActionNameMap[] actionNameMaps = {new ActionNameMap(actions,actionNames,"en")};


			Registry registry = Registry.getRegistry(MY_APP_CLASS);
		
			try {
				// Register our app as mp3 content handler
				registry.register(MY_APP_CLASS, types ,	suffixes , actions , actionNameMaps, MY_APP_ID, null);

				/* Register Menu Item here */
				new Mp3MenuItem().registerInstance();			
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/* Utility method to perform invocation from other classes */
	public synchronized static void invoke(String className, String fileName, byte[] contents) {

		Invocation request = new Invocation();
		request.setID(MY_APP_ID); // request Mp3Player
		request.setURL(fileName);
		request.setData(contents); // set byte array if we have it
		request.setType("audio/mp3");

		// we don't care about the response
		request.setResponseRequired(false);

		try {
			Registry registry = Registry.getRegistry(className);
			registry.invoke(request);
		} catch (Exception ex) {
			System.out.println(className + ": Error occured while opening file");
		}
	}	
	
	public synchronized void invocationRequestNotify(ContentHandlerServer handler) {

		pending = handler.getRequest(false);
		
		if (pending != null) {
			byte[] contents = getContents();
			if (contents != null && contents.length != 0) {
				// TODO: Implement your Main screen and push it on the stack
				// remember that pushScreen is non blocking
				pushScreen(new Mp3PlayerScreen(contents));
				
				// notify the server that we are handling the invocation
				this.server.finish(pending, Invocation.OK);
			}
			else{
				// Close this instance or else you'll get "previous instance still active"
				// So we stop listening to invocation requests
				System.exit(0);
			}			
		} else {
			// Stop listening to invocation requests
			System.exit(0);
		}			
	}

	// Reads data from the invocation request
	// The invocation may contain associated byte array or URL to a file
	// or it could have associated stream (say network stream).
	private byte[] getContents() {
		InputStream is = null;
		StreamConnection sc = null;
		FileConnection fc = null;
		try {
			String filename = null;
			byte[] data = null;
			synchronized (this) {
			
				filename = pending.getURL();
				
				/* try to get associated byte array */
				if(filename.toLowerCase().indexOf("mp3") != -1) {
					data = pending.getData();
				}
				else {
				    // if file name did not end with mp3, don't handle it
					filename = null;
				}
			}
			
			// if we retrieved a byte array
			if (data != null && data.length > 0) {
				return data;
			} else if (filename != null) {
				
				// this is blocking call. use thread instead [e.g for network connection.]
				Connection conn = pending.open(false);
				
				// if this is a file connection the file is already on our phone
				// remember that a FileConnection is also a StreamConnection, 
				// so check FileConnection first				
				if (conn instanceof FileConnection) {
					fc = (FileConnection) conn;
					is = fc.openInputStream();
					
					return IOUtilities.streamToBytes(is);
				} else {
					sc = (StreamConnection) conn;
					is = sc.openInputStream();
					return IOUtilities.streamToBytes(is);
					// TODO: Save the array to SD Card?
				}

			}
		} catch (Exception ex) {
			System.out.println("Error occured while reading file.");
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (fc != null) {
					fc.close();
				}
				if (sc != null) {
					sc.close();
				}
			} catch (Exception ex) {

			}
		}
		return new byte[0];
	}
}

Implementing the ApplicationMenuItem:

Although you may not need to implement a custom context menu item, it is particularly useful when there are
other third party applications already handling the same file type.

ApplicationMenuItem provides an alternate entry point, i.e a way to add a custom menu item when a specific application is running.
For example File Browser or Email app. To do this you have to register your implementation with ApplicationMenuItemRepository,
once registered that instance will be cached in memory until the device is on. But this repository gets wiped out every time the device is rebooted.

So it is a good practice to register once per startup(see above). Now, if you have a UIApplication and it has an icon, user will
start it by selecting it. In this case we have to make sure that we do not register our menu item twice. For this we will have to
use RuntimeStore to save state of our registration.

ApplicationMenuItem construct takes a context, if you are registering this menu item for specific files, mime type of the file type
must be passed as context. This especially important when you are registering your menu item with File Browser.

Important gotcha here is that when you request for an invocation, and the server is not running,
the server will be initialized before the invocation request is made.

package com.serialize.apps;

public class Mp3MenuItem extends ApplicationMenuItem {
	public static final long MP3_MENU_ITEM_KEY = 0x1a23b6c6ab2b1075L;

	public Mp3MenuItem() {
		/* will only be shown if the file mime type matches the context */ 
		super("audio/mp3", 500000); // order is found by trial and error method
	}

	/* This will be menu item text */
	public String toString() {
		return "Open MP3 File";
	}

	public void registerInstance() {
		/* verify Registration */
		Object o = RuntimeStore.getRuntimeStore().remove(MP3_MENU_ITEM_KEY);
		 if(o == null) {
			ApplicationMenuItemRepository amir = ApplicationMenuItemRepository.getInstance();
			// Gets Mp3Player descriptor, since this method is called from ensureRegistration()
			ApplicationDescriptor ad_startup = ApplicationDescriptor.currentApplicationDescriptor();
			ApplicationDescriptor ad_gui = new ApplicationDescriptor(ad_startup, new String[] {"menuitem_entry"});
			
			/* Register for File Browser */
			amir.addMenuItem(ApplicationMenuItemRepository.MENUITEM_FILE_EXPLORER, this, ad_gui);	 	
			RuntimeStore.getRuntimeStore().put(MP3_MENU_ITEM_KEY, this);
		 }
	}

	/* Mp3Player main() will be called before call to this function */
	public Object run(Object context) {
		if (context != null && context instanceof String) {
			String inputFile = (String) context;

			// excecution control is automatically passed to Mp3Player.invocationRequestNotify() after this
			Mp3Player.invoke(getClass().getName(), inputFile, null);
		}
		return context;
	}
}

Written by Vivek Unune

June 30, 2010 at 2:40 am

Posted in blackberry, Java

Tagged with ,

MSBuild Task: Solution and Project dependencies

leave a comment »

Few months ago I needed to use MSbuild to build solution. Sounds simple right? Yeah, but not quite.
Somehow, my msbuild failed with project dependency issues. It turns out that MSBuild doesn’t respect project dependencies in a solution. Google “msbuild solution dependencies” and you’ll find various post complaining about the problem with MSBuild.

I modified the MSBuild task found here to get projects in a solution file in dependency order.

You can then call the task to get the projects and compile them in order:

<Target Name="BuildProjects">
		<GetProjecsInOrder Solution="$(MSBuildProjectDirectory)\MySolution.sln">
		  <Output ItemName="ProjectFiles" TaskParameter="Output"/>
		</GetProjecsInOrder>

		<MSBuild Projects="%(ProjectFiles.FullPath)"
				 Targets="Build"
				 Properties="Configuration=Release"/>
</Target>

You can download the modified source from http://www.esnips.com/doc/8e232db4-21ac-4d93-90dc-2a8bc4db34a8/MSBuildTasks

Written by Vivek Unune

December 16, 2009 at 8:50 pm

Posted in .NET

Tagged with

IDataReader GetValue Extension method

with 2 comments

It is offten desired to get a value from DataReader using column name with known Type. For example you want to get a string value of column ‘first_name’ and int value of column ‘account_number’. The following extension method makes it easy to fetch values from a DataReader using Type and column name:

public static class ReaderHelper
{
    public static bool IsNullableType(Type valueType)
    {
        return (valueType.IsGenericType &&
            valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
    }

    public static T GetValue<T>(this IDataReader reader, string columnName)
    {
        object value = reader[columnName];
        Type valueType = typeof(T);
        if (value != DBNull.Value)
        {
            if (!IsNullableType(valueType))
            {
                return (T)Convert.ChangeType(value, valueType);
            }
            else
            {
                NullableConverter nc = new NullableConverter(valueType);
                return (T)Convert.ChangeType(value, nc.UnderlyingType);
            }
        }
        return default(T);
    }
}

It can be used as:

User GetUser(IDataReader reader)
{
    User user = new User();
    user.FirstName = reader.GetValue<string>("first_name");
    user.LastName = reader.GetValue<string>("last_name");
    user.Email = reader.GetValue<string>("email");
    user.AccountNumber = reader.GetValue<int>("account_number");
    user.NumberOfVehiclesOwned = reader.GetValue<int?>("vehicle_count"); // nullable data field
    return user;
}

Written by Vivek Unune

July 15, 2009 at 9:27 pm

Posted in .NET

Tagged with ,

Follow

Get every new post delivered to your Inbox.