Showing posts with label Windows. Show all posts
Showing posts with label Windows. Show all posts

Monday, 30 December 2013

Window Snapper

Many programs have a nice dividers in their GUI - and you can usually drag the divider to resize the panels on either side. I've often been a little frustrated when resizing windows to tile them to fill the screen. Perhaps a Word document on the left, a PDF in the upper right, and email in the lower right. It was quite tedious, and because of that I didn't do it often, and I feel this slightly diminished the power of windows. So I wrote an AutoHotkey script and now I have what I wanted.

To use it, while the script is running, you can right-button drag window borders, and the script will move all neighbouring window edges at the same time. The script will grab window borders within 10 pixels (configurable) of the border/s you are right-button dragging. It also assumes a seven pixel wide window resize border, but that's also configurable at the top of the script. You can resize from edges or corners - giving you lots of power when resizing windows.

The most common use-case I have is with just two windows positioned with Win+Left and Win+Right (like explained here). With this script you can resize both windows effortlessly.

Here's an example of it in action:
 I can resize all five windows with one right-button drag, in the area where the four window corners meet in the middle of the screen. If I drag towards the upper right, I can get something like this:
 And things like this are possible too, but unsnapping window edges like I've done below with the left and right can be a little fiddly. I could potentially add something like Ctrl+Right-Click to only resize windows actually near the mouse...
Please have a go with the window snapper script. Please let me know what you think after using it!

Creative Commons License

Saturday, 22 June 2013

Hard to Find Excel Tidbit

A short post this week. I recalled that there was a syntax for Excel ranges in VBA. I searched online, but couldn't find much, so here is the tidbit: Ranges can be specified using square brackets. If you used named ranges a lot, this turn out quite nice. So if you have a named range called ImportantInfo, you can refer to it as ... [ImportantInfo]! And it may not provide the method list when you type a full stop after it, but it IS a range object, so you can use it like this:

    Answer = [ImportantInfo].Offset(RowCount, ColumnCount).Text
    MsgBox "The cell Sheet2!E3 contains """ & [Sheet2!E3] & """."
    Dim Cell As Range
    For Each Cell In [B1:B3]
        MsgBox Cell.Text
    Next Cell


One of the reasons I think it's neat when used for named ranges is that with most named ranges in square brackets, you don't have to specify the sheet to disambiguate it. That makes for shorter, and thus easier to read code.

Enjoy!

Saturday, 15 June 2013

Linked Lists in VBA (Excel)

I use Microsoft Excel quite a bit. And recently we had a challenge at work to validate lane use signal displays using conflict matrices. Well, I had some Lisp written to generate sequences given a set of allowed 'transitions'. So I wanted to put that logic into Excel, which meant VBA. I thought it would be quick, but it took about two and a half full days of work... Part of porting over my logic was creating a linked list class named "List" in VBA. It is my first VBA class module (yay!). Here's the code in the "Node" class module:

'' Linked Lists in VBA is released under a BSD licence. Author: Jonathan F Johansen
Option Explicit
Public Car As Variant
Public Cdr As List


Public Function ToString() As String
    ToString = "[" & PlainListString() & "]"
End Function

Public Function PlainListString() As String
    If Cdr Is Nothing Then
        PlainListString = CStr(Car)
    Else
        PlainListString = CStr(Car) & ", " & Cdr.PlainListString()
    End If
End Function


I had more in the class module, but took most of the methods out of there because I wanted to treat Nothing as the empty list. Here are the functions from a separate module:

'' Linked Lists in VBA is released under a BSD licence. Author: Jonathan F Johansen
Option Explicit

'' Making Lists:

Function Cons(Item As Variant, Optional Rest As List) As List
    Set Cons = New List
    Cons.Car = Item
    Set Cons.Cdr = Rest
End Function

Function
MakeList(ParamArray Items() As Variant) As List
    On Error GoTo ZeroLength ' Leaving MakeList as Nothing.
    Dim I As Long
    For I = UBound(Items) To LBound(Items) Step -1
        Set MakeList = Cons(Items(I), MakeList)
    Next I
ZeroLength:
End Function

'' Working with Lists

Function
Append(aList As List, OtherList As List) As List
    If aList Is Nothing Then
        Set Append = OtherList
    ElseIf OtherList Is Nothing Then
        Set Append = aList
    ElseIf aList.Cdr Is Nothing Then
        Set Append = Cons(aList.Car, OtherList)
    Else
        Set Append = Cons(aList.Car, Append(aList.Cdr, OtherList))
    End If
End Function

Function
Reverse(aList As List, Optional OntoFrontOf As List) As List
    If aList Is Nothing Then
        Set Reverse = OntoFrontOf
    Else
        Set Reverse = Reverse(aList.Cdr, Cons(aList.Car, OntoFrontOf))
    End If
End Function

Function
Length(aList As List) As Long
    If aList Is Nothing Then Exit Function 'Returning 0
    Length = 1 + Length(aList.Cdr)
End Function

Function
Member(Item As Variant, aList As List) As Boolean
    If aList Is Nothing Then Exit Function
    If aList.Car = Item Then
        Member = True
    ElseIf aList.Cdr Is Nothing Then
        Member = False
    Else
        Member = Member(Item, aList.Cdr)
    End If
End Function

Function
Replace(OldItem As Variant, NewItem As Variant, aList As List) As List
    If aList Is Nothing Then
    ElseIf aList.Cdr Is Nothing Then
        If aList.Car = OldItem Then
            Set Replace = Cons(NewItem)
        Else
            Set Replace = aList
        End If
    Else
        If aList.Car = OldItem Then
            Set Replace = Cons(NewItem, Replace(OldItem, NewItem, aList.Cdr))
        Else
            Set Replace = Cons(aList.Car, Replace(OldItem, NewItem, aList.Cdr))
        End If
    End If
End Function

Function
Remove(Item As Variant, aList As List) As List
    If aList Is Nothing Then Exit Function
    If Item = aList.Car Then
        Set Remove = Remove(Item, aList.Cdr)
    Else
        Set Remove = Cons(aList.Car, Remove(Item, aList.Cdr))
    End If
End Function

Function
Count(Item As Variant, List As List) As Long
    If List Is Nothing Then Exit Function
    If List.Car = Item Then Count = 1
    Count = Count + Count(Item, List.Cdr)
End Function

Function
CountMaxConsecutive(Item As Variant, List As List) As Long
    If List Is Nothing Then Exit Function
    Dim Rest As List, Count As Long
    Set Rest = List
    Do Until Rest Is Nothing
        If Rest.Car = Item Then
            Count = Count + 1
        Else
            Count = 0
        End If
        If Count > CountMaxConsecutive Then CountMaxConsecutive = Count
        Set Rest = Rest.Cdr
    Loop
End Function

Function
CellTextToList(aRange As Range) As List
    Dim I As Long
    If IsEmpty(aRange) Then Exit Function
    For I = aRange.Cells.Count To 1 Step -1
        Set CellTextToList = Cons(aRange.Cells(I).Text, CellTextToList)
    Next I
End Function

Function
ListToRow(aList As List, Target As Range) As Range
    Dim List As List
    Set List = aList
    Set ListToRow = Target
    Do Until List Is Nothing
        ListToRow = List.Car
        Set ListToRow = ListToRow.Offset(0, 1)
        Set List = List.Cdr
    Loop
End Function


I found it useful, but it could do with a few more utilities. One interesting thing is that looping over a list isn't to complex, as you can see in the last function above. You just declare a local List variable and then use a Do Until localList Is Nothing, and at the end of the loop body, Set localList = localList.Cdr. If you don't declare a local list, but modify the argument, you'll find that the list is chewed up in the caller's scope too...

Here are some examples of the List in action:
Option Explicit

Sub TestLinkedLists()
    MsgBox Cons("a", Cons("b")).ToString
    MsgBox Length(MakeList(1, 2, 3, 4, 5))
    MsgBox Reverse(MakeList(1, 2, 3, 4, 5)).ToString
    MsgBox MakeList(1, 2, 3, 4, 5).ToString
    MsgBox Member(4, MakeList(1, 2, 3, 4, 5))
    MsgBox Member(4, Nothing)
    MsgBox Append(MakeList(1, 2, 3, 4), MakeList(5, 6, 7)).ToString
    MsgBox Replace(4, "four", MakeList(1, 2, 3, 4, 5)).ToString
    MsgBox Remove(3, MakeList(1, 2, 3, 4, 5)).ToString
    MsgBox Count(True, MakeList(False,True,True,True,False,True))
    MsgBox CountMaxConsecutive(True, _

                     MakeList(False, True, True, True, False, True))
    MsgBox CellTextToList(Range("A2:A6")).ToString
    MsgBox "List output to B2, range returned is " _
         & ListToRow(CellTextToList(Range("A2:A6")), Range("C2")).Address _
         & " ready to go for something else..."

End Sub


If you've read the code, you might notice the liberal use of recursion, and the use of functional style. I used recursion a lot in the spreadsheet, and I think this List class helped a lot.

The code on this page is collected into an Excel spreadsheet for convenience too. You can download it from here. As noted in the code comments, the code is released under the BSD license - and I'd love to hear from you if you use it or extend it. Enjoy!

Friday, 24 May 2013

Notepad++ Find and Replace

I think Notepad++ is a great program. I use it a lot at work and at home. I have used it to process text in various ways. I really like Notepad++'s find and replace options, especially since the Regular Expression engine was updated to PCRE. A great post on Notepad++'s find and replace can be found on Mark's Speechblog. In the examples below, don't type in the double quotes. Here are a few Find and Replace searches I have found useful:

This one turns new lines into commas with spaces. I use it to convert a column of Excel data into text as a comma separated list. I've since written an AutoHotkey script to do this too (because I do this so often), which will be the topic of a future post.
Search Mode: Extended
Find: "\r\n"
Replace with: ", "

This finds a specific second column of freeform text from several other columns with digits. The second find string converts a line like "11937577    M0609/VD06   108721      11933802    198024      11933835" into just "M0609/VD06".
Search Mode: Regular expression
Find: "\d+ +(.+)" and "\d+ +(.+) +\d+ +\d+ +\d+ +\d+"
Replace with: "\1"

This one uses start and end of line anchors to ensure the whole line is matched, and grabs the last column. It converts something like "108608     Left turn MVT from Road SEB to Ave NEB    NULL       9      7774/SEB/LQ" into "7774/SEB/LQ".
Search Mode: Regular expression
Find: "^.* +(.+)$"
Replace with: "\1"

This one puts a capital M in front of lines that begin with a digit.
Search Mode: Regular expression
Find: "^(\d)"
Replace with: "M\1"

This one splits some text in a specific tabular form into separate lines.
Search Mode: Regular expression
Find: "(\d+/[^\t\r\n]*\t[^\t\r\n]*\t[^\t\r\n]*\t(SB|NB)\t[^\t\r\n]*\t[^\t\r\n]*\t[^\t\r\n]*\t[^\t\r\n]*\t[^\t\r\n]*\t)"
Replace with: "\1\r\n"

This one removes a tab from the end of a line if it has any. I should have put the last \t in the above regular expression outside of the group, as in "(...[^\t\r\n]*)\t".
Search Mode: Regular expression
Find: "\t$"
Replace with: "" (nothing)

For this find and replace, I wanted to wrap everything on non-empty lines with some other text (in this case it's for a custom SQL query).
Search Mode: Regular expression
Find: "^(.+)$"
Replace with: "   or v.Identifier like '%\1%'"

Have fun with Notepad++!

Saturday, 19 January 2013

Random Scripts in Various Languages

In the last few weeks of work, I've come across several different languages to perform different tasks. They were useful, so I've included them below.

PowerShell

The first one is PowerShell. We used it to extract data for a customer. It's a temporary measure - their business intelligence server will be able to do this for them soon. The idea was to automate calling some SQL queries on a server and exporting the results as CSV. Of interest is that I set the culture to get a specific datetime format (I know, I could get the same effect in SQL). Here is some cleansed parts of the script:

$startDate = "11 Oct 2012"
$days = "1"

$prefix = "declare @StartDate datetime, @EndDate datetime
set @StartDate = DATEADD(HH, -10, '$startDate')
set @EndDate = DATEADD(DD, $days, @StartDate)"

$culture = [System.Globalization.CultureInfo]::InvariantCulture.Clone()
$culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"
$culture.DateTimeFormat.LongTimePattern = "HH:mm"
[System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture
[System.Threading.Thread]::CurrentThread.CurrentCulture = $culture


Write-Output "Extract $days day(s) worth of data from ${startDate}:"

Write-Host "Extracting Performance Log data..."
$query = "$prefix

select Column_Names etc."

.....
$data = Custom-Call-SQL $query
Write-Host "Exporting CSV file..."
$data | Export-CSV PerformanceData.csv -encoding ascii -notype

.....

To run a PowerShell script, put it in a file named something like "script.ps1", open a Powershell prompt (should be under Accessories in the Start menu), and enter the script file and path.

AutoHotkey

The next one was an unusual (to me) use for AutoHotkey. I say unusual, because I didn't think AutoHotkey would be great at working with large files, but it was. It combines the whole contents of several files from sub-folders "Day 2" to "Day 7" into one master file. The reason I went to AutoHotkey is that the files were too big for Notepad++. Here is the script:

#NoEnv
#SingleInstance force
SendMode Input
SetWorkingDir %A_ScriptDir%

OutputFile = PerformanceData.csv
Loop, 6
{
  Day := A_Index+1
  From = Day %Day%\%OutputFile%
  CombineLines(From, OutputFile)
}
MsgBox, Finished copying content to %OutputFile%.
Return

CombineLines(fromfile, tofile)
{

  ;; The "to" file is open for the whole loop for efficiency when done this way.  Loop, Read, %fromfile%, %tofile%
  {
    FileAppend, %A_LoopReadLine%`n
  }
}


To run an AutoHotkey script like this one, copy the contents into a file like "script.ahk" and double click it (assuming you have AutoHotkey installed).

Unix Find and Grep

The next one is from my friend Michael Gleeson. It's a Unix command, and it searches the files in a directory for the <string>, and prints the file and matching line to standard output. It is:

find . -type f -print0 | xargs -0 grep <string>

Regular Expressions

The second last one is for (Perl compatible) regular expressions. Notepad++ was updated to use Perl compatible regular expressions as of version 6. Notepad++ can use regular expressions for "Find and Replace". Doing so is a great feature - it gives you great flexibility to not only find bits of text that match specific patterns, but to also intelligently rearrange or replace those bits of text. I used it recently to change date formats in some of the files I generated with the above scripts. The find text was "(\d{2})/(\d{2})/(\d{4})", and the replace text was "\2-\1-\3". The parentheses in the find text create variables you can use in the replacement text. In our case, we have created three variables. They are named \1, \2 and \3. In the replace text, I've swapped the variables around, because I am converting American Month-Day-Year format to an Australian Day-Month-Year format.


Performing a find and replace in Notepad++ with the above terms replaces "02/27/1900" with "27-02-1900", etc.

See also a post on Mark's Speechblog for more on Notepad++'s powerful find and replace (pre version 6). Also, I'm told that a Unix command, sed (stream editor) can do similar things, and a lot more (see here for a great page about sed).

Visual Basic


The last one is from Visual Basic. I use this in an Excel file, to find a single file. It opens a standard file selector dialog. It's a function, so you call it when you want a file. The function returns a Boolean indicating whether a file was successfully selected, and it puts the file name into the ByRef argument. Here it is:

Function GetAFileName(ByRef FileName As String) As Boolean
' Actually browse for a file to import.
    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogOpen)
    fd.AllowMultiSelect = False
    GetAFileName = (fd.Show = -1)
    If GetAFileName Then
        FileName = fd.SelectedItems(1)
    End If
    Set fd = Nothing
End Function


Have you got any random scripts of your own? Please share them below.

Saturday, 24 November 2012

Window Peeler

I've said before that AutoHotkey is a great program that every Windows users should have and use. Here's yet another use I found for it to make my (and yours) life easier. Have you ever had two full-screen windows on the same monitor and wanted to switch between them quickly? I encounter that situation regularly. With two or three monitors, I use one in portrait orientation for email and viewing documents, and the others for everything else. To switch between windows, the Task Bar, Alt+Tab and Windows+Tab are great, but when I have 20+ windows open, it can take a fair bit of fiddling and time to switch between email and documents on the same monitor. I wanted a better solution. So I wrote this script (download):

;;;; Window Peeler - Show next window under mouse pointer
#NoEnv ;; Standard prelude
#SingleInstance force
SendMode Input

SetWorkingDir %A_ScriptDir%

;; Pick one of your mouse buttons (XButton1 = Back, XButton2 = Forward, MButton = middle button, LButton = left button, etc.) and use it here:
XButton1::
  MouseGetPos,,, WinId
  WinSet, Bottom,, ahk_id %WinId%
  ;MouseGetPos,,, WinId
  ;WinActivate, ahk_id %WinId%
Return


It moves the window under the cursor to the back when the back button is pressed on your mouse (assuming you have that button). That leaves the next window down on top! The two commented out lines of code activate that window, but I like it without that because it makes the script run quicker. It's a very simple script.

To make it trigger on another combination, for example Control+RightMouseButton, replace XButton1:: with ^RButton:: (^ is for Control).

P.S. Note that mouse software may interfere with the Back and Forward mouse button events. In the Logitech software, I had to set the action for that button to Other: Generic Button.

What do you think? Please leave a comment.

Saturday, 10 November 2012

Some Random Windows Tips


Having used Windows 7 for a while now, I an glad I discovered the Windows Button shortcuts. For me, they save a lot of fiddling with windows. For example, take the Windows+Arrows shortcuts. You may have noticed that it is possible to full-screen (maximise) a window by dragging it to the top of the screen, and to half-screen a window by dragging it to the side of the screen. But if you have multiple monitors, you'll notice that you can't half-screen a window by dragging to the edge of a monitor that abuts another monitor. Do not despair, it's still possible with the Windows+Arrows shortcuts! Here are the basics:
Half-screen a window by dragging it to the left, or pressing Windows+Left.
Moving in the other direction works as well:
Half-screen a window by dragging it to the right, or pressing Windows+Right.
To maximise a window, just press Windows+Up. If you have multiple monitors, you can 'hop' a window around by repeatedly pressing Windows+Left or Windows+Right combination:
Moving a window through all monitors and half-screen positions by repeatedly pressing Windows+Right (or Windows+Left).

Here are some more of my favourite Windows key combinations:
  • Windows+D shows the desktop by minimising all windows (like Windows+M);
  • Windows+E opens an explorer window;
  • Windows+L locks the computer;
  • Windows+Tab does a 3D version of Alt-Tabbing.
Many more shortcuts can be found here. While we're on the topic of Windows, here are some other tidbits:
  • Ever had a window that is off-screen and you can't get it back? To get it back, activate the window from the Start Menu, and then press Alt+Space, then M, then press an arrow key (any will do), then move the mouse. I've used this trick since Windows XP to bring back rogue windows.
  • To run a program quickly from the keyboard, just press the Windows key, then type in the first few letters of your program's name. If you type enough of the name for it to be the first choice in the Start menu, you can press enter to run it.
Got some favourite Windows shortcuts of your own? Let me know it the comments.