<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Wise on Tech &#187; Code Snippets</title>
	<atom:link href="http://www.wiseontech.com/category/code/feed" rel="self" type="application/rss+xml" />
	<link>http://www.wiseontech.com</link>
	<description>Hacks, scripts and ideas for the refined geek.</description>
	<lastBuildDate>Thu, 22 Jul 2010 14:48:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Assorted, Scattered JavaScript Notes</title>
		<link>http://www.wiseontech.com/code/assorted-scattered-javascript-notes</link>
		<comments>http://www.wiseontech.com/code/assorted-scattered-javascript-notes#comments</comments>
		<pubDate>Mon, 05 Oct 2009 17:33:50 +0000</pubDate>
		<dc:creator>Jonathan Wise</dc:creator>
				<category><![CDATA[Code Snippets]]></category>

		<guid isPermaLink="false">http://www.wiseontech.com/?p=249</guid>
		<description><![CDATA[Boolean(value) method returns false for falsey values, true for truthy values falsy: false, null, undefined, "", 0, NaN truthy: everything else: "0", "false" + as a leading operator converts a string to a number: +"42" = 42. Same as Number("42") = 42), parseInt("42", 10) = 42 +"3" + (+"4") = 7 === !== do not [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Boolean(value) method returns false for falsey values, true for truthy values</strong><br />
falsy: false, null, undefined, "", 0, NaN<br />
truthy: everything else: "0", "false"</p>
<p><strong>+ as a leading operator converts a string to a number:</strong> +"42" = 42. Same as Number("42") = 42), parseInt("42", 10) = 42<br />
+"3" + (+"4") = 7</p>
<p>=== !== do not do type coercion, slightly faster</p>
<p>if (a) {<br />
return a.member;<br />
} else {<br />
return a;<br />
}<br />
<strong>can be written as</strong><br />
return a &amp;&amp; a.member;<br />
<strong>if the first operand is truthy, return the second operand, else, return the first</strong></p>
<p><strong>but for || if the first operand is truthy, return the first operand, else, return the second:</strong><br />
var last = input || somethingElse;<br />
<strong>so if input is truthy, then last is input, otherwise set last to somethingElse</strong></p>
<p><strong>you can label loops and break them by label:</strong><br />
myloop: for (whatever)<br />
{<br />
break myloop;<br />
}</p>
<p><strong>//other loop</strong><br />
for (var name in object) {<br />
if (object.hasOwnProperty(name))        <strong>//avoids looking at objects we might have inherited from</strong><br />
{<br />
name <strong>//is the current member</strong><br />
object[name] <strong>//is the current member value</strong><br />
}<br />
}</p>
<p><strong>//multiple conditions in switch statements</strong><br />
switch(something) {<br />
case ";";<br />
case ",";<br />
case ".";<br />
isPunctuation();<br />
break;<br />
default:<br />
somethingElse();<br />
}</p>
<p><strong>//exceptions and object literals</strong><br />
throw new Error(myReason);</p>
<p>throw {         <strong>//create an "object literal" creates an exception object on the fly</strong><br />
name: myexceptionName,<br />
message: reason<br />
};</p>
<p><strong>//object literals</strong><br />
an object literal is wrapped in { }<br />
a name can be a names or a value<br />
values are any type<br />
: seperates names and values<br />
, seperates pairs<br />
object literals can be used anywhere a value can appear<br />
var myObject = {name: "Jack", 'goto': 'Jail', grade: 'A', level: 3};<br />
var myName = myObject.name;     <strong>//extracts "Jack"</strong><br />
var destination = myObject['goto'];     //extracts "Jail"<br />
var destination = myObject["name"];     //extracts "Jack"<br />
var destination = myObject[goto];       //returns an error because goto is a reserved word, hence the other notation</p>
<p><strong>//maker function</strong><br />
function maker (name, grade)<br />
{<br />
var it = {}; <strong>//makes a new empty object, good shorthand</strong><br />
it.name = name;<br />
it.grade = grade;<br />
return it;<br />
}<br />
var myObject = maker("Jack", "A");</p>
<p><strong>//an object with an object as a member, shorthanded</strong><br />
var myObject = {<br />
name: "jack",<br />
grade: "a",<br />
clothes: {<br />
pants: 'blue',<br />
shirt: 'red'<br />
}<br />
};</p>
<p><strong>//if you have more than a couple parameters in a function, why not make them an object?</strong><br />
function myfunc(pa, pb, pc, pd, pe, pf)<br />
myfunc(pa, pb, pc, pd, pe, pf)<br />
<strong>vs.</strong><br />
function myfunc(specs)<br />
myfunc({ pa: '1', pc: '3', pb:'2', ... })</p>
<p><em><strong>** note: variables that are not var'ed become implicitly global</strong></em></p>
<p><strong>//specify object's prototype on creation? linkage -- doesn't really exist</strong><br />
var newObject = object(otherObject);<br />
<strong>//gives it a secret pointer to otherObject, but the secret pointer is used for retrieving only NOT storing</strong><br />
<strong>//object (lowercase) is a method that Yahoo made up<br />
//different than</strong><br />
var newObject = Object() which equals: var newObject = object(Object.prototype)</p>
<p>delete myObject[memberName];    <strong>//deletes (sets to undefined) a member of an object</strong></p>
<p>myArray[myArray.length] = 3     <strong>//appends to end of array (same as pop)</strong></p>
<p>var myArray[]   <strong>//creates a new array?</strong></p>
 <img src="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?view=1&post_id=249" width="1" height="1" style="display: none;" /><img src="http://www.wiseontech.com/?ak_action=api_record_view&id=249&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.wiseontech.com/code/assorted-scattered-javascript-notes/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Mail.app with multiple users &#8212; using AppleScript!</title>
		<link>http://www.wiseontech.com/hack/using-mailapp-with-multiple-users-using-applescript</link>
		<comments>http://www.wiseontech.com/hack/using-mailapp-with-multiple-users-using-applescript#comments</comments>
		<pubDate>Sun, 06 Jan 2008 19:15:07 +0000</pubDate>
		<dc:creator>Jonathan Wise</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Hacks]]></category>
		<category><![CDATA[AppleScript]]></category>
		<category><![CDATA[Mail]]></category>

		<guid isPermaLink="false">http://software.jonandnic.com/hack/using-mailapp-with-multiple-users-using-applescript</guid>
		<description><![CDATA[OK, this is pretty brilliant -- and SO simple. Here's the setup: my wife and I share a Mac at home. For memory reasons, among others, I don't want to use Fast User Switching, and because of my automated tasks, I don't want the primary account to ever be logged out. So all many of [...]]]></description>
			<content:encoded><![CDATA[<p>OK, this is pretty brilliant -- and SO simple.</p>
<p>Here's the setup: my wife and I share a Mac at home. For memory reasons, among others, I don't want to use Fast User Switching, and because of my automated tasks, I don't want the primary account to ever be logged out. So all many of our programs need to be set-up for two different users. Firefox has user profiles, that once configured, works perfect. Mail.app has no such thing. What I decided to then, was write an AppleScript that would switch Mail.app between users for us. This example is for two users, but it could be edited for more. Here's how to use it:</p>
<ul>
<li>Setup Mail accounts for each user</li>
<li>Modify the script to prompt for each user you have, and reference their account name</li>
<li>Replace your Mail.app dock icon with a link to your AppleScript (you can even give it the Mail.app icon)</li>
<li>Whenever you launch Mail, you'll be asked which user you want to use</li>
<li>Even better than that, you can switch users just by clicking the Mail icon in your dock again. You don't even have to close down Mail!</li>
</ul>
<p>The result looks like this whenever you invoke the script, and launches/reconfigures Mail within two seconds. Set the delay to longer if Mail.app takes longer to start on your Mac.</p>
<p><img class="size-medium wp-image-268" title="mailprompt" src="http://www.wiseontech.com/wp-content/uploads/2008/01/mailprompt1-300x94.png" alt="" /></p>
<p>The code is dead simple, and took me only moments to put together. Note that the delays and the order in which things are done is important so that it doesn't hang waiting for Mail to start if its not already open.<br />
<code><br />
-- Mail Account Chooser, by Jonathan Wise<br />
-- Add user profiles to Mail.app<br />
display dialog "Choose the Mail account to use" buttons {"Jonathan", "Elizabeth"} default button 1 with icon note<br />
if the button returned of the result is "Jonathan" then<br />
  tell application "Mail"<br />
    activate<br />
    delay 2<br />
    set enabled of account "Elizabeth Home" to false<br />
    set enabled of account "Jonathan Home" to true<br />
  end tell<br />
else<br />
  tell application "Mail"<br />
    activate<br />
    delay 2<br />
    set enabled of account "Jonathan Home" to false<br />
    set enabled of account "Elizabeth Home" to true<br />
  end tell<br />
end if<br />
</code></p>
 <img src="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?view=1&post_id=32" width="1" height="1" style="display: none;" /><img src="http://www.wiseontech.com/?ak_action=api_record_view&id=32&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.wiseontech.com/hack/using-mailapp-with-multiple-users-using-applescript/feed</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
		<item>
		<title>Detecting the presence of a given font in .NET</title>
		<link>http://www.wiseontech.com/code/detecting-the-presence-of-a-given-font-in-net</link>
		<comments>http://www.wiseontech.com/code/detecting-the-presence-of-a-given-font-in-net#comments</comments>
		<pubDate>Mon, 19 Nov 2007 15:26:26 +0000</pubDate>
		<dc:creator>Jonathan Wise</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://software.jonandnic.com/code/detecting-the-presence-of-a-given-font-in-net</guid>
		<description><![CDATA[Maybe this seems obvious to other people, but I couldn't find anything in Google on it. Maybe I didn't know the right keywords to search for. At any rate, lets say you have an application that's optimized for a specific font -- but you can't guarantee that font is installed. You might want to, as [...]]]></description>
			<content:encoded><![CDATA[<p>Maybe this seems obvious to other people, but I couldn't find anything in Google on it. Maybe I didn't know the right keywords to search for.</p>
<p>At any rate, lets say you have an application that's optimized for a specific font -- but you can't guarantee that font is installed. You might want to, as a contingency, fall-back to a different font -- maybe one that isn't quite as attractive, but that you know for sure will be present. This other font might have slightly different sizing, so in the case where you fall back, you might want to tweak your UI widgets, or alignment margins and widths, to look better if the fall-back is used. Here's my solution (C#)...</p>
<p><code>Font fnt = new Font("GoodLookinFont", 10);<br />
if (fnt.FontFamily.Name != "GoodLookinFont")<br />
{<br />
//adjust display for fall-back font<br />
}<br />
</code></p>
<p>What happens is simple: .Net attempts to create a Font object using your preferred font. If it can't find that font on the local system, it will instead create the Font object using  "Microsoft Sans Serif." If the Font object's FontFamily Name is not what you expect, you know you'll have to adjust your display.</p>
 <img src="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?view=1&post_id=29" width="1" height="1" style="display: none;" /><img src="http://www.wiseontech.com/?ak_action=api_record_view&id=29&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.wiseontech.com/code/detecting-the-presence-of-a-given-font-in-net/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automagic</title>
		<link>http://www.wiseontech.com/code/automagic</link>
		<comments>http://www.wiseontech.com/code/automagic#comments</comments>
		<pubDate>Wed, 12 Sep 2007 03:43:46 +0000</pubDate>
		<dc:creator>Jonathan Wise</dc:creator>
				<category><![CDATA[Code Snippets]]></category>
		<category><![CDATA[Home Theater]]></category>
		<category><![CDATA[Mac]]></category>
		<category><![CDATA[OS X]]></category>

		<guid isPermaLink="false">http://software.jonandnic.com/hack/automagic</guid>
		<description><![CDATA[Well my previous post on Symlinks was only partially right. It turns out iTunes doesn’t work very well when it has to share its library. If either computer decides it needs to write anything to the library database, it locks the other out. I had other problems with symlinking iCal’s database — it seems to [...]]]></description>
			<content:encoded><![CDATA[<p>Well my previous post on Symlinks was only partially right. It turns out iTunes doesn’t work very well when it has to share its library. If either computer decides it needs to write anything to the library database, it locks the other out. I had other problems with symlinking iCal’s database — it seems to keep a cache somewhere that I can’t find. So I had to resort to some AppleScripting — maybe the most elite AppleScript I’ve ever written. Here’s everything, some scripted, some not, that our computers do automatically for us…</p>
<p><strong>Media Synchronization</strong></p>
<p>My uber-script runs at 1:00am on the iMac. It starts by cleaning out the downloads folder, deleting any downloaded TV shows over 21 days old, then moves any downloaded music into the appropriate folder and adds it to the local iTunes library. Then it gets really clever, and logs into the remote Home Theater Mac over SSH and begins sending it instructions. It shuts down the remote iTunes, deletes its Library (which is a data island, because we do all our media maintenance on the iMac) and copies over the iMac’s iTunes Library. Note that it copies the Library only — the music remains on a network share that both computers have access to.<br />
Then, once both iTunes are in sync, it starts up the remote iTunes which triggers a sync with my iPhone, getting me a playlist of my most recent music, plus my favorites (I only have a 4GB so I have to manage well) and does something similar locally to sync Nic’s iPod.</p>
<p>Both computers use the network shared Videos folder to populate FrontRow with our movies and TV content.</p>
<p><strong>Calendar Synchronization</strong></p>
<p>I failed to get WebDAV up and running on my new host, and Symlinks didn’t work out. But a wonderful and free service called <a href="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?url=aHR0cDovL3d3dy5pY2FseC5jb20v">iCalX</a> came to the rescue. Microsoft finally added WebDAV publishing to Outlook 2007, so I publish my work calendar from there, my personal calendar syncs from my iPhone with the Home Theater Mac and from there to iCalX, and Nic publishes her calendar from the iMac. Any WebDAV client can subscribe to them and iCalX provides a nice little PHP iCalendar view online.</p>
<p><strong>Address Book Synchronization</strong></p>
<p>The OS X Address Book doesn’t complain too much about sharing its library between two computers, and provides little other utility for syncing or sharing (unless you want to pay $99 a year for .Mac — an otherwise useless service). I explored lots of options, but the only unattended one is Exchange syncing (or Kerio), and I don’t want to run a mail server any more. So I finally just decided to let Address Book share. The only caveat is that to make sure Address Book’s on multiple machines match up you have to quit Address Book to dump its in-memory cache and force it to re-read the database. It was easy enough to add some quit, open and hide commands to my uber-script, and that seems to solve the problem. Putting those commands in before each iTunes syncs with its connected portable device makes sure that both the iPhone and iPod have the latest contacts.</p>
<p>Nic’s cell phone is still a non-Apple device, but it syncs nicely over Bluetooth. A little app called <a href="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?url=aHR0cDovL3d3dy5hcHBsZS5jb20vZG93bmxvYWRzL21hY29zeC9zeXN0ZW1fZGlza191dGlsaXRpZXMvcHJveGltaXR5Lmh0bWw=">Proximity</a> detects when she comes into range of the Home Theater Mac, and fires a tiny AppleScript that does an automatic sync for her. A little blue light on her phone is the only indicator that its even happening.</p>
<p><strong>Document Backup</strong></p>
<p>This is actually another potentially useful service of .Mac, but I’m too cheap to be sold that easily. A really nice online service called <a href="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?url=aHR0cHM6Ly9tb3p5LmNvbS8/cmVmPTlYTURCMw==">Mozy</a> provides free back-ups up to 2GB, and unlimited back-up for $5 a month (sign-up with that link and get me more free space!) We just eeked in under the 2GB mark backing up all our documents. This happens automatically every Sunday night at 1:00am, in place of the usual media sync.<br />
I’ll be taking a semi-annual physical back-up of our document, music and pictures — pictures are copied between both Macs anyway. I have yet to figure out a way to back up 280GB of videos, save for having a second hard drive stored elsewhere, but I think, in case of a fire, we can live with only losing our movie collection.</p>
<p><strong>Cleaning up</strong></p>
<p>After either scheduled task (media sync or back-up, depending on the night of the week) the iMac goes to sleep until 9:00am, or until called for, while the Home Theater Mac studiously downloads things it thinks we might want to watch.</p>
<p>My script is likely pretty unique to our set-up, but I had to search long and hard to find the various parts that make it work — sending script instructions to a remote Mac over SSH was particularly tricky — so I’m posting it here for anyone who’s interested in picking it apart.</p>
<ul>
<li><a href="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?url=aHR0cDovL3d3dy53aXNlb250ZWNoLmNvbS93cC1jb250ZW50L3VwbG9hZHMvMjAwNy8xMC9kYWlseW1haW50ZW5hbmNlLnR4dA==" title=\"dailymaintenance.txt\">Download the Uberscript here!<br />
</a></li>
</ul>
<p>One other thing to be aware of, much of the script works against a shared drive, so it needs to be mounted for this to work. I use a little app called <a href="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?url=aHR0cDovL2ptLm1hcmluby5mcmVlLmZyLz9zd2l0Y2g9c3dfJmFtcDt0aXRsZT1hdXRvbW91bnRtYWtlcg==">Automount Maker</a> to get my media share to mount on boot, but its possible for the volume to get dismounted during the day (our microwave interferes with our wireless, for example, because there are so many wireless networks around, and that can kill the connection). I’d love to hear any ideas on how to make sure a volume stays mounted!</p>
 <img src="http://www.wiseontech.com/wp-content/plugins/feed-statistics.php?view=1&post_id=9" width="1" height="1" style="display: none;" /><img src="http://www.wiseontech.com/?ak_action=api_record_view&id=9&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.wiseontech.com/code/automagic/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
