12/30/10

Happy New Year!

Translations by Google Translate API.

LanguageTranslationPhonetic Pronunciation
AfrikaansVoorspoedige Nuwe Jaar!
AlbanianGëzuar Vitin e Ri!
Arabicسنة جديدة سعيدة
ArmenianՇնորհավոր Նոր ՏարիShnorhavor Nor Tari
BelarusianЗ Новым годам!Z Novym hodam!
BulgarianЧестита Нова Година!Chestita Nova Godina!
CatalanFeliç Any Nou!
Chinese Simplified新年快乐Xīnnián kuàilè!
Chinese Traditional新年快樂Xīnnián kuàilè!
CroatianSretna Nova Godina!
CzechŠťastný Nový Rok!
DanishGodt Nytår!
DutchGelukkig Nieuw Jaar!
EstonianHead uut Aastat!
FilipinoMasaya Bagong Taon!
FinnishHyvää Uutta Vuotta!
FrenchJoyeux Nouvel An!
GalicianFeliz Ano!
GermanGlückliches Neues Jahr!
GreekΕυτυχισμένο το Νέο Έτος!Ef̱tychisméno to Néo Étos
Haitian CreoleKontan Ane Nouvo!
Hebrewשנה טובה
Hindiनया साल मुबारक हो!Nayā sāla mubāraka hō!
HungarianBoldog Új Évet!
IcelandicGleðilegt Nýtt Ár!
IndonesianSelamat Tahun Baru!
IrishAthbhliain faoi mhaise daoibh!
ItalianFelice Anno Nuovo!
Japanese明けましておめでとうございますAkemashite omedetōgozaimasu
Korean새해 복 많이saehae bog manh-i
LatvianLaimīgu Jauno gadu!
LithuanianLaimingų Naujųjų Metų!
MacedonianСреќна Нова Година!Sreḱna Nova Godina!
MalaySelamat Tahun Baru!
MalteseSena l-ġdida Kuntenti!
NorwegianGodt Nytt År!
Persianرسید سال نوی خوشی
PolishSzczęśliwego Nowego Roku!
PortugueseFeliz Ano Novo!
RomanianAn Nou Fericit!
RussianС Новым годом!S Novym godom!
SerbianСрећна Нова година!Srećna Nova godina!
SlovakŠťastný Nový Rok!
SlovenianSrečno novo leto!
SpanishFeliz Año Nuevo!
SwahiliFuraha ya Mwaka Mpya!
SwedishGott Nytt År!
Thaiสวัสดีปีใหม่S̄wạs̄dī pī h̄ım̀
TurkishMutlu yıllar!
UkrainianЗ Новим роком!Z Novym rokom!
VietnameseChúc mừng năm mới
WelshBlwyddyn Newydd Dda!
Yiddishגליקלעך ניו יאָר

12/5/10

SQL Server Command Line Utility - SqlCmd

http://msdn.microsoft.com/en-us/library/ms162773.aspx
path: c:\program files\microsoft sql server\100\tools\binn\sqlcmd.exe

powershell examples
- execute command-line query, connect using SQL Server Authentication
  &sqlcmd -S SERVER -d DB -U LOGIN -P 'PASSWORD' -q 'select getdate()'

- execute command-line query, connect using SQL Server Authentication, password prompt
  &sqlcmd -S SERVER -d DB -U LOGIN -q 'select getdate()'

- execute command-line query, connect using Windows Authentication
  &sqlcmd -S SERVER -d DB -E -q 'select getdate()'
    
- execute sql script file
  &sqlcmd -S SERVER -d DB -E -i x:\sql\script1.sql

- execute all sql script files in a folder
  gci x:\sql\ *.* | %{ &sqlcmd -S SERVER -d DB -E -i $_.fullname }
  
- exit or quit

- command-line options
  [-? show syntax summary]
  [-a packetsize]
  [-A dedicated admin connection]
  [-b On error batch abort]
  [-c cmdend]
  [-C Trust Server Certificate]
  [-d use database name]
  [-e echo input]
  [-E trusted connection]
  [-f <codepage> | i:<codepage>[,o:<codepage>]]
  [-h headers]
  [-H hostname]
  [-i inputfile]
  [-I Enable Quoted Identifiers]
  [-k[1|2] remove[replace] control characters]
  [-l login timeout]
  [-L[c] list servers[clean output]]
  [-m errorlevel]
  [-N Encrypt Connection]
  [-o outputfile]
  [-p[1] print statistics[colon format]]
  [-P password]
  [-q "cmdline query"]
  [-Q "cmdline query" and exit]
  [-r[0|1] msgs to stderr]
  [-R use client regional setting]
  [-s colseparator]
  [-S server]
  [-t query timeout]
  [-u unicode output]
  [-U login id]
  [-v var = "value"...]
  [-V severitylevel]
  [-w screen width]
  [-W remove trailing spaces]
  [-x disable variable substitution]
  [-X[1] disable commands, startup script, enviroment variables [and exit]]
  [-y variable length type display width]
  [-Y fixed length type display width]
  [-z new password]
  [-Z new password and exit]

11/15/10

PInvoke SetWindowText PowerShell Script

P/Invoke examples for the SetWindowText Windows API Function.
These examples set the window text/title for Notepad.exe.
#get notepad window handle
$notepad = get-process notepad
$notepad.mainWindowHandle //100000, intptr structure

$pinvoke::setWindowText($notepad.mainWindowHandle, "a")

#auto-convert int to intptr
$pinvoke::setWindowText(100000, "b")

#create intptr
#out-null to suppress bool result
$pinvoke::setWindowText((new-object intPtr(100000)), "c") | out-null

$pinvoke::setWindowTextCustomWrapper(100000)

Implementation #1 simply exposes the SetWindowText method, the member definition uses C# syntax.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, String lpString);

'@

Implementation #2, same as #1 but written on one line.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition '[DllImport("user32.dll", CharSet = CharSet.Auto)]public static extern bool SetWindowText(IntPtr hwnd, String lpString);'

Implementation #3, SetWindowText is private, add custom wrapper method.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool SetWindowText(IntPtr hwnd, String lpString);

public static void SetWindowTextCustomWrapper(IntPtr handle)
{
string customText = string.Format("handle: {0}", handle);
SetWindowText(handle, customText);
}

'@


11/3/10

Git Custom Difftool Configuration

Original solution by David Tchepak: Setting up Git difftool on Windows

This example shows the configuration for ExamDiff Pro.
Tested on Windows 7 and msysgit version 1.7.3.1

1. Set the path environment variable to include "c:\program files\git\cmd\;"
2. Create a shell script wrapper file, note the forward slashes in the executable path
#c:\program files\git\cmd\diff.sh
#!/bin/sh
"c:/program files/examdiff pro/examdiff.exe" "$1" "$2" | cat

3. Edit the .gitconfig file
#c:\users\john\.gitconfig
[diff]
tool = examdiff

[difftool "examdiff"]
cmd = diff.sh "$LOCAL" "$REMOTE"
...

4. Verify it works, run the difftool command: git difftool --no-prompt


Setting Windows Path Environment Variable with PowerShell

#get all environment vars
gi env:
(gi env:) | sort name

#get path value
gi env:path
(gi env:path).value
(gi env:path).value.split(';')
(gi env:path).value.split(';') | sort

#set path value (note the "$" prefix)
$env:path = 'c:\windows;c:\windows\system32;'

8/20/10

Visual Studio 2010 Keyboard Shortcuts

v5-11

ctl + R, ctl + R         refactor rename

ctl + alt + R            view web browser

ctl + R, T               run tests in current context
ctl + R, ctl + T         debug tests in current context
ctl + R, A               run all tests in solution
ctl + R, ctl + A         debug all tests in solution

ctl + \, ctl + M         tfs team explorer
alt + V, E, I            tfs view history
alt + V, E, H            tfs view pending changes
alt + V, E, S            tfs view source code explorer

ctl + M, ctl + G         goto mvc view/controller

ctl + I                  incremental search
ctl + shf + I            reverse incremental search
ctl + F3                 find using current selection
ctl + ]                  match braces, opening & closing
ctl + shf + ]            select code between braces

ctl + M, ctl + H         hide selection
ctl + M, ctl + U         unhide selection
ctl + M, ctl + O         collapse to definitions
ctl + M, ctl + T         collapse tag - htm, aspx
ctl + M, ctl + M         toggle outline expansion, current section
ctl + M, ctl + L         toggle all outlining
ctl + K, ctl + K         toggle bookmark
ctl + E, ctl + W         toggle word wrap

ctl + K, ctl + C         comment selection
ctl + K, ctl + U         uncomment selection

ctl + K, ctl + X         code snippet
ctl + K, ctl + B         code snippet manager
ctl + shf + U            uppercase selection
ctl + U                  lowercase selection

ctl + alt + O            output window
ctl + alt + C            call stack
ctl + alt + I            immediate window
ctl + alt + A            command window

ctl + alt + T            document outline window, use w/htm files
ctl + alt + U            modules window

ctl + \, E               error list window
ctl + \, ctl + E         error list window

ctl + alt + V, A         autos window
ctl + alt + V, L         locals window
shf + F9                 quick watch
ctl + alt + W, 1         watch 1 window (1-4)
ctl + alt + B            breakpoints window
ctl + F9                 toggle enable breakpoint
ctl + shf + F9           delete all breakpoints

ctl + K, ctl + W         bookmark window
ctr + \, D               code definition window

ctl + -                  navigate backward
ctl + shf + -            navigate forward
ctl + F6                 navigate open windows forward
ctl + shf + F6           navigate open windows backward

ctl + tab                select open windows dialog
ctl + shf + tab          select open windows dialog backward
ctl + alt + down arrow   list open documents
ctl + alt + P            attach to process

shf + alt + enter        toggle full screen
alt + U                  restore from full screen
ctl + f2                 focus on navigation bar
alt + W, W               show windows window
alt + -                  show float/dock window menu

F5                       start debugging
ctl + F5                 start without debugging
shf + F5                 stop debugging
alt + num + *            show next statement
ctl + shf + F10          set next statement
ctl + F10                run to cursor
shf + F10                context menu, popup

ctl + shf + B            build solution
alt + B, R               rebuild solution
alt + B, U               build current project
alt + B, E               rebuild current project
alt + B, G               build webform page/user control
ctl + break              cancel build

ctl + alt + L            view solution explorer, highlight active file
alt + enter              show file properties/property pages for active item in solution explorer
shf + F4                 show property pages for active project/solution in solution explorer
F4                       show file properties for active item in solution explorer

ctl + F4                 close active code window
F9                       toggle breakpoint
F10                      debug step over
F11                      debug step into
shf + F11                debug step out
f12                      goto definition
ctl + alt + J            object browser
ctl + alt + S            server explorer

//command window (ctl + alt + A)
File.Close               closes currently selected window, including solution explorer
File.TfsHistory          tfs history for currently selected file
View.F#Interactive       f# interactive

//F#
ctl + alt + F            f# interactive
alt + enter              send selected code to f# interactive

//SQL
ctl + shf + E            execute sql
ctl + F5                 validate sql syntax
ctl + shf + alt + R      show/hide sql results pane, toggle
ctl + T                  show results as text
ctl + shf + E            show results as grid

5/18/10

Blocking Websites with the Hosts File

#v5-12
#http://blog.expressionsoftware.com/2010/05/ad-block-host-file-entries.html

#mac
#  path: /etc/hosts
#  ls -1alt /etc/hosts*
#  head -20 /etc/hosts

#windows
#  path: C:\windows\system32\drivers\etc\hosts
#  gci C:\windows\system32\drivers\etc\hosts* -force
#  gc C:\windows\system32\drivers\etc\hosts | select -first 20

127.0.0.1 spam.com
127.0.0.1 f.ads.com
127.0.0.1 www.msn.com

5/11/10

Checkout One File from SVN

A Slik SVN/PowerShell workaround for the SVN missing feature - checking out just a few select files instead of the entire folder.
$svnFolder = 'https://dev.co.com/svn/project1'
$workingFolder = 'c:\temp\svn'
$file = 'foo.cs'

#checkout just the folder, checkout depth "only this item"
&svn checkout $svnFolder $workingFolder --depth=empty

#method 1: cd to working folder, update using file name
cd $workingFolder
&svn update $file

#method 2: update using file full path name
$file = join-path $workingFolder $file
&svn update $file

5/8/10

PowerShell Registry Script

Four variations for reading registry keys.
HKLM and HKCU are PowerShell drives for HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER registry hives.

Windows startup entries.
getRegistryV1 hklm:\software\microsoft\windows\currentversion\run
getRegistryV1 hkcu:\software\microsoft\windows\currentversion\run
function getRegistryV1($key)
{
  $key = get-item $key
  $values = get-itemProperty $key.psPath  #gp alias for get-itemProperty
  $values
}

function getRegistryV2($key)
{
  $key = get-item $key
  $values = get-itemProperty $key.psPath
  foreach ($value in $key.property)
  {
    "$value = $($values.$value)"  #subexpression $()
  }
}

function getRegistryV3($key)
{
  $key = get-item $key
  $maxKeyNameLen = ($key.property | %{$_.length} | measure -max).maximum
  $values = get-itemProperty $key.psPath
  foreach ($value in $key.property)
  {
    "{0,-$maxKeyNameLen} = {1}" -f $value, $values.$value  #format left-aligned width
  }
}

function getRegistryV4($key)
{
  $key = get-item $key
  $maxKeyNameLen = ($key.property | %{$_.length} | measure -max).maximum
  $values = get-itemProperty $key.psPath
  $key.property | %{"{0,-$maxKeyNameLen} = {1}" -f $_, $values.$_}  #format left-aligned width
}

5/5/10

ASP.NET 4/IIS ManagedPipelineHandler Error

ASP.NET 4 error on Windows 7/IIS 7.5
HTTP Error 500.21 - Internal Server Error
Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list.

To fix, install ASP.NET 4 using the .NET 4 ASP.NET IIS Registration Tool.
See documentation for differences between the -i and -ir options.
c:\windows\microsoft.net\framework\v4.0.30319\aspnet_regiis.exe -i

5/2/10

Testing String Format in PowerShell

'{0:x2}' -f 10
[string]::format('{0:x2}', 10)
0a

Testing String Format in F# Interactive

printf "%02x" 10;;
System.String.Format("{0:x2}", 10);;
open System;;
String.Format("{0:x2}", 10);;
val it : string = "0a"

4/19/10

PowerShell List Dates Script

listDates '01-01' 7                       #01-01-2010
listDates '01-01' 7 'M-d'                 #1-1
listDates '01-01' 14 'ddd MM-dd'          #Fri 01-01
listDates '01-01-2011' 30                 #01-01-2011
listDates '01-01' 60 'MMM dd yyyy - ddd'  #Jan 01 2010 - Fri
function listDates($startDate, $daysCount, $format='MM-dd-yyyy')
{
  $startDate = [datetime]$startDate
  0..($daysCount-1) |
    %{
        $startDate.addDays($_).toString($format)  #console - show date
     }
}

4/9/10

HTTP Error Codes 401 and 500 on IIS 7 and ASP.NET

To fix these errors on Windows 7 Pro, add the user group/account to the web folder and set permissions.

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
User Group: IIS_IUSRS

HTTP Error 401.3 - Unauthorized
You do not have permission to view this directory or page because of the access control list (ACL) configuration or encryption settings for this resource on the Web server.
User Account: IUSR

Permissions:
read
read and execute
list folder contents

4/8/10

PowerShell File Concatenation Script

Concatenates text files into a single file for printing, text-zip-attachments, etc.
File index is included at the top of the output file.
function concatFiles($outFile)
{
  begin
  {
    $date = get-date
    [string[]] $filelist = @()  #empty string array
    $filebreak = '-'*32
  }
  process
  {
    #for process-block vars, append data using +=
    $_.fullname  #or "$_", console - show file name
    $filelist += $_.fullname
    $filedata += "$filebreak`nfile: $_`n"
    $filedata += gc $_.fullname | out-string  #use out-string to restore linebreaks
  }
  end
  {
    $filecount = $filelist.length
    "{0} files" -f $filecount  #console - show file count
    $fileheader = "{0}`n" -f $date.toString('MM-dd-yy HH:mm:ss')
    $fileheader += "concat output file: {0}`n{1} files" -f $outFile, $filecount
    $fileheader            >> $outFile
    $filelist              >> $outFile
    $filedata + $filebreak >> $outFile
  }
}


Concatenate all text files
gci c:\docs\* -inc *.txt -rec | concatFiles c:\temp\out.txt

#powershell console output
C:\docs\file1.txt
C:\docs\file7.txt
2 files

#file output
03-01-11 14:09:22
concat output file: c:\temp\out.txt
2 files
C:\docs\file1.txt
C:\docs\file7.txt
--------------------------------
file: C:\docs\file1.txt
file 1
...
--------------------------------
file: C:\docs\file7.txt
file 7
...
--------------------------------


Concatenate files modified on Jan 1 2011 or later
$files = "*.htm","*.css","*.js"
gci c:\docs\* -inc $files -rec -force -ea silentlycontinue |
  ?{$_.lastwritetime -gt [datetime]'01-01-2011'} | concatFiles c:\temp\out.txt

3/31/10

Insert String Every N Characters

This PowerShell v2 script inserts a string every N characters. The interval is specified using the regex repetition operator, {min,max}.
$a = 'abcdefghijklmnopqrstuvwxyz'
([regex]::matches($a, '.{1,3}') | %{$_.value}) -join ' '
([regex]::matches($a, '.{1,8}') | %{$_.value}) -join '..'
([regex]::matches($a, '.{1}') | %{$_.value}) -join '-'

#output
abc def ghi jkl mno pqr stu vwx yz
abcdefgh..ijklmnop..qrstuvwx..yz
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z

3/22/10

PowerShell Download File Script

This script downloads files asynchronously. It uses the .NET WebClient DownloadFileAsync method.
Note that the download file path must exist.
downloadFile 'http://www.foo.com/foo.iso' 'c:\temp\foo.iso'

function downloadFile($uri, $filename)
{
  $webClient = new-object net.webclient
  $webClient.downloadFileAsync($uri, $filename)
}

3/15/10

JavaScript Namespaces

Two variations for implementing JavaScript namespaces.
The abc namespace syntax is the simplest and useful when only public members are being wrapped.
The xyz namespace syntax can be used for public and private members.
var abc =
{
  version: '1.0',
  foo: function()
  {
    return 'abc.foo';
  }
};

var xyz = function()
{
  //private
  var _version = '2.0';
  function _foo()
  {
    return 'xyz.foo';
  }

  //public
  return {
    version: _version,  //access private var
    foo: function()
    {
      return _foo();  //access private fx
    },
    bar: function(text)
    {
      return 'xyz.bar ' + text;
    }
  };
}();  //self invoking fx

Examples
abc.foo();
abc.version;

xyz.foo();
xyz.bar('test');
xyz.version;

//output
abc.foo
1.0

xyz.foo
xyz.bar test
2.0

Object Graphs in Firebug Watch Window

A slightly modified version showing sub namespaces, eg abc.demo.foo()
var abc = {};
abc.demo =
{
  version: '1.1',
  foo: function()
  {
    return 'abc.demo.foo';
  }
};

var xyz = {};
xyz.demo = function()
{
  //private
  var _version = '2.1';
  function _foo()
  {
    return 'xyz.demo.foo';
  }

  //public
  return {
    version: _version,  //access private var
    foo: function()
    {
      return _foo();  //access private fx
    },
    bar: function(text)
    {
      return 'xyz.demo.bar ' + text;
    }
  };
}();  //self invoking fx

If you use libraries with nested namespaces, local references improve performance by minimizing member lookup.
var abcd = abc.demo;
abcd.foo();
abcd.version;

3/13/10

Hash Message Digest Comparisons

Hash    Bits  Bytes
MD5     128   16  (128/8 = 16)
SHA1    160   20
SHA224  224   28
SHA256  256   32
SHA384  384   48
SHA512  512   64

3/9/10

Password Entropy

Entropy Information Theory - Wikipedia
Password Strength - Wikipedia

Entropy Bits Formula
log N / log 2
N is the number of possible symbols in set
#PowerShell
[math]::log($N)/[math]::log(2)
Entropy Table to 256 Bits
Set Count  Bits Per Char  Set Characters
10         3.322          numeric 0-9
26         4.7            case insensitive alpha a-z
36         5.17           case insensitive alphanumeric a-z, 0-9
52         5.7            case sensitive alpha a-z, A-Z
62         5.954          case sensitive alphanumeric a-z, A-Z, 0-9
94         6.555          ascii characters a-z, A-Z, 0-9, symbols
95         6.57           ascii characters a-z, A-Z, 0-9, symbols including space

Len N=10     N=26     N=36     N=52     N=62     N=94     N=95
1   3.322    4.7      5.17     5.7      5.954    6.555    6.57
2   6.644    9.401    10.34    11.401   11.908   13.109   13.14
3   9.966    14.101   15.51    17.101   17.863   19.664   19.71
4   13.288   18.802   20.68    22.802   23.817   26.218   26.279
5   16.61    23.502   25.85    28.502   29.771   32.773   32.849
6   19.932   28.203   31.02    34.203   35.725   39.328   39.419
7   23.253   32.903   36.189   39.903   41.679   45.882   45.989
8   26.575   37.604   41.359   45.604   47.634   52.437   52.559
9   29.897   42.304   46.529   51.304   53.588   58.991   59.129
10  33.219   47.004   51.699   57.004   59.542   65.546   65.699
11  36.541   51.705   56.869   62.705   65.496   72.1     72.268
12  39.863   56.405   62.039   68.405   71.45    78.655   78.838
13  43.185   61.106   67.209   74.106   77.405   85.21    85.408
14  46.507   65.806   72.379   79.806   83.359   91.764   91.978
15  49.829   70.507   77.549   85.507   89.313   98.319   98.548
16  53.151   75.207   82.719   91.207   95.267   104.873  105.118
17  56.473   79.907   87.889   96.907   101.221  111.428  111.688
18  59.795   84.608   93.059   102.608  107.176  117.983  118.257
19  63.117   89.308   98.229   108.308  113.13   124.537  124.827
20  66.439   94.009   103.399  114.009  119.084  131.092  131.397
21  69.76    98.709   108.568  119.709  125.038  137.646  137.967
22  73.082   103.41   113.738  125.41   130.992  144.201  144.537
23  76.404   108.11   118.908  131.11   136.947  150.756  151.107
24  79.726   112.811  124.078  136.811  142.901  157.31   157.677
25  83.048   117.511  129.248  142.511  148.855  163.865  164.246
26  86.37    122.211  134.418  148.211  154.809  170.419  170.816
27  89.692   126.912  139.588  153.912  160.763  176.974  177.386
28  93.014   131.612  144.758  159.612  166.717  183.528  183.956
29  96.336   136.313  149.928  165.313  172.672  190.083  190.526
30  99.658   141.013  155.098  171.013  178.626  196.638  197.096
31  102.98   145.714  160.268  176.714  184.58   203.192  203.666
32  106.302  150.414  165.438  182.414  190.534  209.747  210.235
33  109.624  155.115  170.608  188.115  196.488  216.301  216.805
34  112.946  159.815  175.777  193.815  202.443  222.856  223.375
35  116.267  164.515  180.947  199.515  208.397  229.411  229.945
36  119.589  169.216  186.117  205.216  214.351  235.965  236.515
37  122.911  173.916  191.287  210.916  220.305  242.52   243.085
38  126.233  178.617  196.457  216.617  226.259  249.074  249.655
39  129.555  183.317  201.627  222.317  232.214  255.629  256.224
40  132.877  188.018  206.797  228.018  238.168  262.184
41  136.199  192.718  211.967  233.718  244.122
42  139.521  197.418  217.137  239.418  250.076
43  142.843  202.119  222.307  245.119  256.03
44  146.165  206.819  227.477  250.819
45  149.487  211.52   232.647  256.52
46  152.809  216.22   237.817
47  156.131  220.921  242.986
48  159.453  225.621  248.156
49  162.774  230.322  253.326
50  166.096  235.022  258.496
51  169.418  239.722
52  172.74   244.423
53  176.062  249.123
54  179.384  253.824
55  182.706  258.524
56  186.028
57  189.35
58  192.672
59  195.994
60  199.316
61  202.638
62  205.96
63  209.281
64  212.603
65  215.925
66  219.247
67  222.569
68  225.891
69  229.213
70  232.535
71  235.857
72  239.179
73  242.501
74  245.823
75  249.145
76  252.467
77  255.788
78  259.11

3/8/10

Alpha

95 characters, including space

0123456789
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
 `!@#$%^&*()-=[]\;',./~_+{}|:"<>?

2/6/10

PowerShell Asynchronous Background Jobs

PowerShell Background Jobs - MSDN.
Requires PowerShell v2.

Job Cmdlets
start-job
get-job
receive-job
stop-job
start-job {
  #...
}

#with parameters
start-job {param($p1, $p2)
  $p1
  $p2
} -argumentList 'foo', 123

#output
foo
123

#execute N times
start-job {
  1..3 |
    %{
        (get-date).toString('HH:mm:ss')
        sleep 1
     }
}

#output
20:32:51
20:32:52
20:32:53

#execute N times with script block begin-process-end clause
start-job {
  begin
  {
    'begin script...'
  }
  process
  {
    1..3 | %{(get-date).toString('HH:mm:ss'); sleep 1;}
  }
  end
  {
    'end script...'
  }
}

#output
begin script...
20:35:42
20:35:43
20:35:44
end script...

#infinite loop, stop job during sleep interval
start-job {param($sleep)
  while ($true)
  {
    #...

    $now = get-date
    'sleep {0}, {1} - {2}' -f $sleep, $now.toString('HH:mm:ss'), $now.addSeconds($sleep).toString('HH:mm:ss')
    sleep $sleep
  }
} -argumentList 60

#output
sleep 60, 20:41:06 - 20:42:06
sleep 60, 20:42:06 - 20:43:06

2/5/10

Generic Array to String Function

ArrayToString returns an array as a formatted string. This generic function works with arrays of all types.
//C#
using System.Text;

namespace ExpressionSoftware.System
{
    public static class Array
    {
        public static string ArrayToString<T>(T[] array, string format)
        {
            return ArrayToString(array, format, 16);
        }

        public static string ArrayToString<T>(T[] array, string format, int stringBuilderItemCapacity)
        {
            var sb = new StringBuilder(array.Length * stringBuilderItemCapacity);
            foreach (T item in array)
            {
                sb.AppendFormat(format, item);
            }
            return sb.ToString();
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.System
open System.Text

type Array =
  
  //stringBuilderItemCapacity is an optional int parameter
  static member ArrayToString(array:'a[], format:string, ?stringBuilderItemCapacity:int) =
    
    let stringBuilderItemCapacity =
      match stringBuilderItemCapacity with
        | Some(stringBuilderItemCapacity) -> stringBuilderItemCapacity
        | None -> 16

    let sb = new StringBuilder(array.Length * stringBuilderItemCapacity)
    array |> Array.iter(fun b -> sb.AppendFormat(format, b) |> ignore)
    sb.ToString()

#PowerShell
function arrayToString($array, $format)
{
  $array | %{$result += ($format -f $_)}
  $result
}

Examples
//C#
byte[] bytes = { 0, 1, 255 };
int[] ints = { int.MinValue, -1, 0, 256, int.MaxValue };
float[] floats = { -9.99f, 0f, 3.14159f };
char[] chars = { 'a', 'b', 'c', '1', '2', '3' };
string[] strings = { "xyz", "789" };

Debug.WriteLine(Array.ArrayToString(bytes, "{0}", 3));
Debug.WriteLine(Array.ArrayToString(bytes, "{0} "));
Debug.WriteLine(Array.ArrayToString(ints, "{0} "));
Debug.WriteLine(Array.ArrayToString(floats, "{0} "));
Debug.WriteLine(Array.ArrayToString(chars, "{0}", 1));
Debug.WriteLine(Array.ArrayToString(chars, "{0},", 2));
Debug.WriteLine(Array.ArrayToString(strings, "{0} ", 4));

//F#
let bytes = [|0uy; 1uy; 255uy|]
let ints = [|Int32.MinValue; -1; 0; 256; Int32.MaxValue|]
let floats = [|-9.99f; 0.0f; 3.14159f|]
let chars = [|'a'; 'b'; 'c'; '1'; '2'; '3'|]
let strings = [|"xyz"; "789"|]

Array.ArrayToString(bytes, "{0}", 3) |> (fun s -> printfn "%s" s)
Array.ArrayToString(bytes, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(ints, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(floats, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(chars, "{0}", 1) |> (fun s -> printfn "%s" s)
Array.ArrayToString(chars, "{0},", 2) |> (fun s -> printfn "%s" s)
Array.ArrayToString(strings, "{0} ", 4) |> (fun s -> printfn "%s" s)

#PowerShell
[byte[]]$bytes = 0, 1, 255
[int[]] $ints = [int32]::MinValue, -1, 0, 256, [int32]::MaxValue
[single[]] $floats = -9.99, 0, 3.14159
[char[]] $chars = 'a', 'b', 'c', '1', '2', '3'
[string[]] $strings = 'xyz', '789'

arrayToString $bytes '{0}'
arrayToString $bytes '{0} '
arrayToString $ints '{0} '
arrayToString $floats '{0} '
arrayToString $chars '{0}'
arrayToString $chars '{0},'
arrayToString $strings '{0} '

Output
01255
0 1 255 
-2147483648 -1 0 256 2147483647 
-9.99 0 3.14159 
abc123
a,b,c,1,2,3,
xyz 789 


1/31/10

jQuery Template Page

This page can be used for quick-start jQuery development.
jQuery v1.4.x is loaded from the Google AJAX Libraries API site.
Page caching is disabled via meta tags to make it easy to test changes.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Template</title>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<style type="text/css">body,input,button{font-family:Verdana,Sans-Serif;font-size:.9em;}</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
  //$(document).ready(function(){alert('DOM ready');});
  //$(document).ready(f1);
  function f1()
  {
    alert('f1() - DOM ready');
  }

  function f2()
  {
    var input = $.trim($("#input1").val());
    $("#label1").text(input);
  }
</script>
</head>
<body>
  <!--form & submit button allows user to submit by pressing enter key 
    while input text box has focus - instead of having to manually click 
    button or tabbing to button and pressing space key-->
  <form action="">
    <label id="label1">label1</label><br />
    <input id="input1" type="text" maxlength="32" title="input" /><br />
    <input type="submit" />
  </form>
  
  <script type="text/javascript">
    $("form").submit(function(){f2(); return false;});
  </script>
</body>
</html>