Here is an example of using python to post to twitter.
def twit(login, password, msg):
payload= {'status' : msg, 'source' : 'TinyBlurb'}
payload= urllib.urlencode(payload)
base64string = base64.encodestring('%s:%s' % (login, password))[:-1]
headers = {'Authorization': "Basic %s" % base64string}
url = "http://twitter.com/statuses/update.xml"
result = urlfetch.fetch(url, payload=payload, method=urlfetch.POST, headers=headers)
return result.content
Wednesday, April 22, 2009
Tuesday, April 21, 2009
Friday, April 10, 2009
Returning immutable collections
Many times it is desirable to return an internal collection object to consumers of your class.
For example:
The method above works, but has a draw back. The elements of your internalObjects list are now mutable outside your control. In C++ you might try to return const& instead to get around this problem, but how do you solve this in Java?
The first approach might be to return a copy. e.g:
This has the desired effect but with a couple of disadvantages. First you had to perform the copy which could be a performance bottleneck. Second the consumer may no longer point to the same objects if you modify your internalObject class.
The best way, that I know of, to do this is as follows:
The returned list still points to internal list, but is read only. Also, just to be pedantic, I've marked the list as final which means the reference will never change which is more correct for this example.
I hope that helps, leave comments on what you think.
@developresource
For example:
class Foo {
List _internalObjects = new ArrayList();
List getList() {
return _internalObjects;
}
}
The method above works, but has a draw back. The elements of your internalObjects list are now mutable outside your control. In C++ you might try to return const& instead to get around this problem, but how do you solve this in Java?
The first approach might be to return a copy. e.g:
class Foo {
List _internalObjects = new ArrayList();
List getList() {
List copy = new ArrayList();
copy.addAll(_internalObjects);
return copy;
}
}
This has the desired effect but with a couple of disadvantages. First you had to perform the copy which could be a performance bottleneck. Second the consumer may no longer point to the same objects if you modify your internalObject class.
The best way, that I know of, to do this is as follows:
class Foo {
final List _internalObjects = new ArrayList();
List getList() {
return new AbstractList() {
@Override
public Object get(int index)
{
return _internalObjects.get(index);
}
@Override
public int size()
{
return _internalObjects.size();
}
};
}
}
The returned list still points to internal list, but is read only. Also, just to be pedantic, I've marked the list as final which means the reference will never change which is more correct for this example.
I hope that helps, leave comments on what you think.
@developresource
Friday, March 27, 2009
Add new line at end of file.
Working on a cross platform c++ project I find it annoying that Linux requires a new line at the end of each file. I constantly forget to do this.
I wrote this simple macro which will add the new line each time you save a file.
You don't need the whole thing. Most of this is generated in EnvironmentEvents but saved here for posterity.
I wrote this simple macro which will add the new line each time you save a file.
You don't need the whole thing. Most of this is generated in EnvironmentEvents but saved here for posterity.
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module EnvironmentEvents
#Region "Automatically generated code, do not modify"
'Automatically generated code, do not modify
'Event Sources Begin
Public WithEvents DTEEvents As EnvDTE.DTEEvents
Public WithEvents DocumentEvents As EnvDTE.DocumentEvents
Public WithEvents WindowEvents As EnvDTE.WindowEvents
Public WithEvents TaskListEvents As EnvDTE.TaskListEvents
Public WithEvents FindEvents As EnvDTE.FindEvents
Public WithEvents OutputWindowEvents As EnvDTE.OutputWindowEvents
Public WithEvents SelectionEvents As EnvDTE.SelectionEvents
Public WithEvents BuildEvents As EnvDTE.BuildEvents
Public WithEvents SolutionEvents As EnvDTE.SolutionEvents
Public WithEvents SolutionItemsEvents As EnvDTE.ProjectItemsEvents
Public WithEvents MiscFilesEvents As EnvDTE.ProjectItemsEvents
Public WithEvents DebuggerEvents As EnvDTE.DebuggerEvents
Public WithEvents ProjectsEvents As EnvDTE.ProjectsEvents
Public WithEvents TextDocumentKeyPressEvents As EnvDTE80.TextDocumentKeyPressEvents
Public WithEvents CodeModelEvents As EnvDTE80.CodeModelEvents
Public WithEvents DebuggerProcessEvents As EnvDTE80.DebuggerProcessEvents
Public WithEvents DebuggerExpressionEvaluationEvents As EnvDTE80.DebuggerExpressionEvaluationEvents
'Event Sources End
'End of automatically generated code
#End Region
Private Sub DocumentEvents_DocumentOpened(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentOpened
End Sub
Private Sub DocumentEvents_DocumentSaved(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentSaved
Dim textSelection As EnvDTE.TextSelection
textSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
textSelection.EndOfDocument(True)
textSelection.EndOfLine()
If textSelection.Text <> vbCrLf Then
textSelection.Text = textSelection.Text & vbCrLf
End If
End Sub
End Module
Visual Studio Macros for source control.
Visual Studio allows for users to customize the environment by writing macros. With Visual Studio 2008 the macros can be written in VB.Net. VB.Net is a very powerful language as it can use any of the standard .NET object, and in addition it has access to Visual Studios ENVDTE object.
The following set of macros replace the buggy Perforce source control plugin.
The following set of macros replace the buggy Perforce source control plugin.
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Public Module MiscCommands
Sub P4Add()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "add " + filename)
End Sub
Sub P4Edit()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "edit " + filename)
End Sub
Sub P4Diff()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "diff " + filename)
End Sub
Sub P4Revert()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "revert " + filename)
End Sub
Sub P4Opened()
ChDir("c:\p4")
ExecuteCommand("p4.exe", "opened")
End Sub
Sub P4History()
Dim filename As String = DTE.ActiveWindow.Document.FullName
ChDir("c:\p4")
ExecuteCommand("p4.exe", "filelog " + filename)
End Sub
Public Sub ExecuteCommand(ByVal filename As String, ByVal arguments As String)
Dim p As New System.Diagnostics.Process
p.StartInfo.UseShellExecute = False
p.StartInfo.FileName = filename
p.StartInfo.Arguments = arguments
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardError = True
p.Start()
p.WaitForExit()
WriteToMyNewPane(filename + " " + arguments, p.StandardOutput.ReadToEnd + p.StandardError.ReadToEnd)
End Sub
Public Sub WriteToMyNewPane(ByVal command As String, ByVal results As String)
Dim win As Window = _
DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
Dim ow As OutputWindow = win.Object
Dim owPane As OutputWindowPane
Dim cnt As Integer = ow.OutputWindowPanes.Count
owPane = ow.OutputWindowPanes.Item(1)
owPane.OutputString(command & vbCrLf)
owPane.OutputString(results & vbCrLf)
owPane.Activate()
End Sub
Sub OpenFile()
Dim fileName As String = InputBox("Open file:")
If String.IsNullOrEmpty(fileName) Then
Return
End If
Dim item As EnvDTE.ProjectItem = DTE.Solution.FindProjectItem(fileName)
If item Is Nothing Then
MsgBox("File not found", MsgBoxStyle.Exclamation)
Return
End If
item.Open()
item.Document.Activate()
End Sub
End Module
Thursday, February 5, 2009
C# Key Listener
CodeGuru has this post:
This post will describe how to do this in C#. We will approach this by creating an executable that could be loaded at startup. It will listen for the F12 keyboard event and present a message box.
Create a new C# Console project in Visual Studio, call it 'ListenForHotkey.'
We will use a windows hook to notify our application when a key is pressed. So in the Program.cs file you should define four win32 API's. SetWindowsHookEx, UnhookWindowsHookEx, GetModuleName, CallNextHookEx. We'll also define a delegate for the callback, and some constants.
Here is the Program.cs with these definitions.
In the code above we've defined a delegate called LowLevelKeyboardProc that is the signature of the callback. Let's add our callback.
Our callback simply prints that a key was pressed then calls the next hook if applicable. This is important else another application that register a hook may not be called.
Lastly we should register our hook, and run the app. This is done in the main method.
In main we register the callback then call Application.Run() which puts the app in an infinite loop by waiting for any system messages. When the program is ready to exit we unregister our hook.
That's it.
Hope it helps.
Hi All
Looking for a little help..
I would like to create a process that runs on both a Windows XP and Vista Machines that loads on startup, what this process will do is, on the "F12" keypress it brings up a simple form that a user fills in some details then clicks on send, then it goes back to sleep and waits on the "F12" key being pressed.
Never created a process before so any help is appreciated.
Cheers
Djbell
This post will describe how to do this in C#. We will approach this by creating an executable that could be loaded at startup. It will listen for the F12 keyboard event and present a message box.
Create a new C# Console project in Visual Studio, call it 'ListenForHotkey.'
We will use a windows hook to notify our application when a key is pressed. So in the Program.cs file you should define four win32 API's. SetWindowsHookEx, UnhookWindowsHookEx, GetModuleName, CallNextHookEx. We'll also define a delegate for the callback, and some constants.
Here is the Program.cs with these definitions.
using System;
using System.Runtime.InteropServices; //Used for dll import
using System.Diagnostics; //'Process'
namespace ListenForHotkey
{
static class Program
{
[STAThread]
static void Main()
{
}
// Define win32 api calls.
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
//Define delegate for the callback.
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
//Define constants
private const int WH_KEYBOARD_LL = 13;
}
}
In the code above we've defined a delegate called LowLevelKeyboardProc that is the signature of the callback. Let's add our callback.
// Callback, executed when hook is triggered. In our case on keydown.
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
System.Console.WriteLine("key pressed");
//Call next hook in chain.
return CallNextHookEx(m_hookId, nCode, wParam, lParam);
}
Our callback simply prints that a key was pressed then calls the next hook if applicable. This is important else another application that register a hook may not be called.
Lastly we should register our hook, and run the app. This is done in the main method.
[STAThread]
static void Main()
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
m_hookId = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, GetModuleHandle(curModule.ModuleName), 0);
}
System.Windows.Forms.Application.Run();
UnhookWindowsHookEx(m_hookId);
}
In main we register the callback then call Application.Run() which puts the app in an infinite loop by waiting for any system messages. When the program is ready to exit we unregister our hook.
That's it.
Hope it helps.
GWT Programming Concepts
GWT Programming Concepts
This tutorial will introduce the architecture of GWT. It is aimed at programmers with little or no Java experience, but with reasonable experience with other programming languages using object oriented programming.
GWT is a single application. It consists of a series of panels. There may be a single panel onto which other panels are places, or multiple panels. You create and place Widgets onto these panels. Widgets are items like hyperlinks, textbox's, buttons, etc. With each of these widgets you can attach event listeners that will be execute when appropriate. For example you can attach a click listener to a button and when the user clicks the button, the action will be performed.
The important part of GWT is that panels and widgets are added using Java code.
Each widget (which includes a Panel) is an object that is derived from a number of base classes. For example:
UIObject : the base class with properties or methods:
* Size
* Width
* toString
Widget : derived from UIObject (so has its properties and methods), extended by:
* attached
* parent
FocusWidget : derived from Widget (so has its properties and methods), extended by:
* ClickListenerCollection
* addClickListener
Button : derived from FocusWidget (so has its properties and methods), extended by:
* getHTML
* setHTML
So through a series of inherited commands, the Panel object is instructed by GWT to deliver its HTML. Before delivering its own html, it instructs its children objects to deliver their html. Before their delivery, they also ask their children. And so on, until there are no unpolled children. In this way, the panel's html incorporates all the required html for all of its children.
So as a programmer, all you need to do is to slap down some panels, add some widgets containing the text, buttons, menu items, response to button clicks etc that you want and save it.
The command to "compile" the program takes all the Java objects you have created in your code, pulls out the required html and programmed actions and creates a final html container with a large amount of Javascript that writes the html you instructed through your Java objects.
far more functional and much more fun.
This tutorial will introduce the architecture of GWT. It is aimed at programmers with little or no Java experience, but with reasonable experience with other programming languages using object oriented programming.
GWT is a single application. It consists of a series of panels. There may be a single panel onto which other panels are places, or multiple panels. You create and place Widgets onto these panels. Widgets are items like hyperlinks, textbox's, buttons, etc. With each of these widgets you can attach event listeners that will be execute when appropriate. For example you can attach a click listener to a button and when the user clicks the button, the action will be performed.
The important part of GWT is that panels and widgets are added using Java code.
Each widget (which includes a Panel) is an object that is derived from a number of base classes. For example:
UIObject : the base class with properties or methods:
* Size
* Width
* toString
Widget : derived from UIObject (so has its properties and methods), extended by:
* attached
* parent
FocusWidget : derived from Widget (so has its properties and methods), extended by:
* ClickListenerCollection
* addClickListener
Button : derived from FocusWidget (so has its properties and methods), extended by:
* getHTML
* setHTML
So through a series of inherited commands, the Panel object is instructed by GWT to deliver its HTML. Before delivering its own html, it instructs its children objects to deliver their html. Before their delivery, they also ask their children. And so on, until there are no unpolled children. In this way, the panel's html incorporates all the required html for all of its children.
So as a programmer, all you need to do is to slap down some panels, add some widgets containing the text, buttons, menu items, response to button clicks etc that you want and save it.
The command to "compile" the program takes all the Java objects you have created in your code, pulls out the required html and programmed actions and creates a final html container with a large amount of Javascript that writes the html you instructed through your Java objects.
far more functional and much more fun.
Subscribe to:
Posts (Atom)