Code snippets
Python – Search key in a Dictionary by value
by edy_3dz on Feb.13, 2012, under Code snippets
If you need to get the key of an item from a Dictionary in Python, supposing that the items are unique, here’s an easy way to do it:
def find_key(dic, val): """return the key of dictionary dic given the value""" return [k for k, v in dic.iteritems() if v == val][0]
where dic is the dictionary, and val is the value for whose key you are looking for.
C# – Copying a file with the same name without overwriting
by edy_3dz on May.29, 2011, under Code snippets
I recently encountered a situation where I needed to copy some files over a location where files with the same name already existed, and overwriting them wasn’t an option. So, the following code snippet verifies if a file with the same name already exists, in case which it tries to put a number after the file’s name.
public static void FileCopyWithoutOverwriting(string sourceFile, string fileName, string destinationPath)
{
// if destinationPath doesn't add with a slash, add one
if ((destinationPath.EndsWith("\\") || destinationPath.EndsWith("/")) == false)
destinationPath += "\\";
try
{
// if file already exists in destination
if (File.Exists(destinationPath + fileName))
{
// counter
int count = 1;
// extract extension
FileInfo info = new FileInfo(sourceFile);
string ext = info.Extension;
string prefix;
// if it has an extension, append it to a .
if (ext.Length > 0)
{
// get filename without extension
prefix = fileName.Substring(0, fileName.Length - ext.Length);
ext = "." + ext;
}
else
prefix = fileName;
// while not found an valid destination file name, increase counter
while (File.Exists(destinationPath + fileName))
{
fileName = prefix + "(" + count.ToString() + ")" + ext;
count++;
}
// copy file
File.Copy(sourceFile, destinationPath + fileName);
}
else
{
File.Copy(sourceFile, destinationPath + fileName);
}
Console.WriteLine("File copy done.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("The caller does not have the required permission.");
}
catch (ArgumentException)
{
Console.WriteLine("One of the arguments is invalid.");
}
catch (PathTooLongException)
{
Console.WriteLine("The specified path, file name, or both exceed the system-defined maximum length.");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("At least one of the specified paths are invalid.");
}
catch (FileNotFoundException)
{
Console.WriteLine("{0} was not found", sourceFile);
}
catch (IOException)
{
Console.WriteLine("An I/O error has occurred.");
}
catch (NotSupportedException)
{
Console.WriteLine("Source filename is in invalid format.");
}
}
I hope that you’ll find this helpful
UPDATE: A made a better version, with exception handling too.
Changing Yahoo Messenger’s status using C#
by edy_3dz on Aug.31, 2010, under Code snippets
Some people asked me how I change Yahoo Messenger’s status in my application called Emoticon Status Generator. So I’ll make public the code snippet that I used to accomplish this.
[DllImport("USER32.DLL", EntryPoint="FindWindowA",
CallingConvention=CallingConvention.StdCall)]
private static extern IntPtr FindWindow(string sClassName,
string sWindowName);
[DllImport("USER32.DLL", EntryPoint="PostMessageA",
CallingConvention=CallingConvention.StdCall)]
private static extern bool PostMessage(IntPtr hWnd, uint iMsg,
long wParam, long lParam);
void ChangeYahooStatus (string newStatus)
{
// Get the current signed in user
RegistryKey keyYahooPager =
Registry.CurrentUser.OpenSubKey("Software\\Yahoo\\Pager");
string userName = (string)keyYahooPager.GetValue ("Yahoo! User ID");
keyYahooPager.Close();
// Now open the current user's profile and set the new status message
// We have to pass true to OpenSubKey to request write access
RegistryKey keyYahooCustomMessages =
Registry.CurrentUser.OpenSubKey ("Software\\Yahoo\\Pager\\profiles\\"
+ userName + "\\Custom Msgs", true);
// Set the 5th message, seems like yahoo messenger has the
//functionality to move the newly set message up as the first one.
keyYahooCustomMessages.SetValue ("5_W", newStatus);
keyYahooCustomMessages.Close ();
// We are done setting the value in the registry. We now need to notify
// Yahoo Messenger of this change
// Find the Messenger window and send it the notification
// 0x111: WM_COMMAND
// 0x188: Code 392
IntPtr hWndY = FindWindow ("YahooBuddyMain", null);
PostMessage (hWndY, 0x111, 0x188, 0);
}
It should work with Yahoo Messenger 9 and 10, not tested with other versions.
I hope that you’ll find useful this code snippet in developing some nice piece of software.