fix version comparison for Yosemite

fix version comparison for Yosemite

property pTitle : "OmniFocus: Quick Stats"
property pVersion : "2.07.brett"

property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2"
property pstrMinOSX : "10.9"

property pTimeOut : 30

-- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript

-- Copyright  2012, 2013, 2014 Robin Trew
--
-- Permission is hereby granted, free of charge,
-- to any person obtaining a copy of this software
-- and associated documentation files (the "Software"),
-- to deal in the Software without restriction,
-- including without limitation the rights to use, copy,
-- modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons
-- to whom the Software is furnished to do so,
-- subject to the following conditions:
--
-- *******
-- The above copyright notice and this permission notice
-- shall be included in ALL copies
-- or substantial portions of the Software.
-- *******
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
-- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- Ver 0.8 adds clipboard option to dialogue
-- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script
-- Ver 1.0 slight simplification of the code
-- Ver 1.1 added count of Pending projects
-- Ver 1.2 added a count of available actions
-- Ver 1.3 added a break-down of unavailable actions
-- Ver 1.4 added count of Current projects to complement Pending projects
-- ver 1.5 replaced Applescript time function with SQL time expression
-- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF
--Ver 1.8 Adjusts handling of variant bundle identifiers generally
-- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ...

property pToClipboard : "Copy list to clipboard"

if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath()

set sysinfo to system info
set osver to system version of sysinfo

considering numeric strings
	if (osver < pstrMinOSX) then
		display dialog "This script requires OSX " & pstrMinOSX & " or higher: " & osver buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion
		return
	end if
end considering

tell application "Finder"
	set screen_resolution to bounds of window of desktop
	set height to item 4 of screen_resolution
	if height < 1024 then
		set brief to true
	else
		set brief to false
	end if
end tell

if pstrDBPath  "" then
	set inbox_cmd to "
	select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1);
	select '    Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0);
	select '    Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0);
	select null;
	"
	set folders_cmd to "
	select 'FOLDERS'	, count(*) from folder;
	select '    Active folders', count(*) from folder where effectiveActive=1;
	select '    Dropped folders', count(*) from folder where effectiveActive=0;
	select null;
	"
	set projects_cmd to "
	select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0;
	select '    Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active');
	select '            Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '            Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '    On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive');
	select '    Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done');
	select '    Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set lists_cmd to "
	select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1;
	select '    Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active');
	select '    On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive');
	select '    Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done');
	select '    Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set contexts_cmd to "
	select 'CONTEXTS', count(*) from context;
	select '    Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1);
	select '    On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0;
	select '    Dropped contexts', count(*) from context where effectiveActive=0;
	select null;
	"
	set groups_cmd to "
	select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0);
	select '    Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0);
	select '    Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0);
	select null;
	"
	set tasks_cmd to "
	select 'ALL TASKS', count(*) from task;
	select null;
	"
	set actions_cmd to "
	select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0);
	select '    Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0);
	select '    Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0));
	select '    Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and c.effectiveActive= 0;
	select '    Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1);
	select '        Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is not null and tp.status='inactive');
	select '        Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is not null and c.allowsNextAction=0);
	select '        Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1;
	select '        	Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=1;
	select '        	Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=0;
	select '        Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=0;
	select null;
	"
	set summary_cmd to "
	select 'SUMMARY';
	select '    Inbox available actions', count(*) from task where (inInbox=1) and (dateCompleted is null);
	select '    Due in next week', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01');
				/* and dateDue < strftime('%s','now','+7 days') - strftime('%s','2001-01-01'); */
	select '    Flagged projects and actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and tp.effectiveFlagged;
	select '    Due or Flagged', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and (tp.effectiveFlagged or (effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01')));
	select null;
	"
	if brief then
		set commands to summary_cmd & actions_cmd & projects_cmd & contexts_cmd
	else
		set commands to summary_cmd & actions_cmd & inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & tasks_cmd
	end if
	set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands)

	-- 		try
	set strList to do shell script strCmd
	-- 		on error
	-- 			display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return &
	-- 				"Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion
	-- 			return
	-- 		end try
	tell application id "sevs"
		activate
		if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion)
			is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList
	end tell
else
	tell application id "sevs"
		activate
		display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion
	end tell
end if

on FileExists(strPath)
	(do shell script "test -e " & strPath & " ; echo $?") = "0"
end FileExists

on GetCachePath()
	try
		tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2"
	on error
		error "OmniFocus not installed ..."
	end try
end GetCachePath

property pTitle : "OmniFocus: Quick Stats"
property pVersion : "2.07.brett"

property pstrDBPath : "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/com.omnigroup.OmniFocus/OmniFocusDatabase2"
property pstrMinOSX : "10.9"

property pTimeOut : 30

-- Original version: https://github.com/RobTrew/tree-tools/blob/master/OmniFocus%20scripts/Statistics/QuickStats.applescript

-- Copyright  2012, 2013, 2014 Robin Trew
--
-- Permission is hereby granted, free of charge,
-- to any person obtaining a copy of this software
-- and associated documentation files (the "Software"),
-- to deal in the Software without restriction,
-- including without limitation the rights to use, copy,
-- modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons
-- to whom the Software is furnished to do so,
-- subject to the following conditions:
--
-- *******
-- The above copyright notice and this permission notice
-- shall be included in ALL copies
-- or substantial portions of the Software.
-- *******
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
-- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- Ver 0.8 adds clipboard option to dialogue
-- Ver 0.9 gives an error message if the cache schema has changed, leading to an SQL error in the script
-- Ver 1.0 slight simplification of the code
-- Ver 1.1 added count of Pending projects
-- Ver 1.2 added a count of available actions
-- Ver 1.3 added a break-down of unavailable actions
-- Ver 1.4 added count of Current projects to complement Pending projects
-- ver 1.5 replaced Applescript time function with SQL time expression
-- Ver 1.7 Reorganizes menu, and attempts to enable access for .macappstore installations of OF
--Ver 1.8 Adjusts handling of variant bundle identifiers generally
-- Ver 2.00 Redraft of task breakdown, with progressive narrowing of criteria ...

property pToClipboard : "Copy list to clipboard"

if not FileExists(pstrDBPath) then set pstrDBPath to GetCachePath()

tell application "Finder"
	if (version < pstrMinOSX) then
		display dialog "This script requires OSX " & pstrMinOSX & " or higher" buttons {"OK"} default button 1 with title pTitle & "Ver. " & pVersion
		return
	end if

	set screen_resolution to bounds of window of desktop
	set height to item 4 of screen_resolution
	if height < 1024 then
		set brief to true
	else
		set brief to false
	end if
end tell

if pstrDBPath  "" then
	set inbox_cmd to "
	select 'INBOX GROUPS & ACTIONS', count(*) from task where (inInbox=1);
	select '    Inbox action groups', count(*) from task where (inInbox=1) and (childrenCount>0);
	select '    Inbox actions', count(*) from task where (inInbox=1) and (childrenCount=0);
	select null;
	"
	set folders_cmd to "
	select 'FOLDERS'	, count(*) from folder;
	select '    Active folders', count(*) from folder where effectiveActive=1;
	select '    Dropped folders', count(*) from folder where effectiveActive=0;
	select null;
	"
	set projects_cmd to "
	select 'PROJECTS', count(*) from projectInfo where containsSingletonActions=0;
	select '    Active projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='active');
	select '            Current projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart is null or t.dateToStart < (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '            Pending projects', count(*) from projectInfo p join task t on t.projectinfo=p.pk where (p.containsSingletonActions=0) and (p.folderEffectiveActive=1) and (p.status='active') and (t.dateToStart > (strftime('%s','now') - strftime('%s','2001-01-01')));
	select '    On-hold projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='inactive');
	select '    Completed projects', count(*) from projectInfo where (containsSingletonActions=0) and (status='done');
	select '    Dropped projects', count(*) from projectInfo where (containsSingletonActions=0) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set lists_cmd to "
	select 'SINGLE ACTION LISTS', count(*) from projectInfo where containsSingletonActions=1;
	select '    Active single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='active');
	select '    On-hold single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='inactive');
	select '    Completed single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (status='done');
	select '    Dropped single action lists', count(*) from projectInfo where (containsSingletonActions=1) and (( status='dropped') or (folderEffectiveActive=0));
	select null;
	"
	set contexts_cmd to "
	select 'CONTEXTS', count(*) from context;
	select '    Active contexts', count(*) from context where (effectiveActive=1) and (allowsNextAction=1);
	select '    On-hold contexts', count(*) from context where (effectiveActive=1) and allowsNextAction=0;
	select '    Dropped contexts', count(*) from context where effectiveActive=0;
	select null;
	"
	set groups_cmd to "
	select 'ACTION GROUPS', count(*) from task where (projectinfo is null) and (childrenCount>0);
	select '    Remaining action groups', count(*) from task where (projectinfo is null) and (dateCompleted is null) and (childrenCount>0);
	select '    Completed action groups', count(dateCompleted) from task where (projectinfo is null) and (childrenCount>0);
	select null;
	"
	set tasks_cmd to "
	select 'ALL TASKS', count(*) from task;
	select null;
	"
	set actions_cmd to "
	select 'ACTIONS', count(*) from task where (projectinfo is null) and (childrenCount=0);
	select '    Completed actions', count(dateCompleted) from task where (projectinfo is null) and (childrenCount=0);
	select '    Dropped project actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp where (projectinfo is null) and (childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is not null and (tp.status='dropped' or tp.folderEffectiveActive=0));
	select '    Dropped context actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and c.effectiveActive= 0;
	select '    Remaining actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1);
	select '        Actions in Projects on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is not null and tp.status='inactive');
	select '        Actions in Contexts on hold', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is not null and c.allowsNextAction=0);
	select '        Blocked actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1;
	select '        	Blocked by future start date', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=1;
	select '        	Sequentially blocked', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=1
				and tp.blockedByFutureStartDate=0;
	select '        Available actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				and (tp.context is null or c.allowsNextAction=1)
				and tp.blocked=0;
	select null;
	"
	set summary_cmd to "
	select 'SUMMARY';
	select '    Inbox available actions', count(*) from task where (inInbox=1) and (dateCompleted is null);
	select '    Due in next week', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (projectinfo is null) and (tp.childrenCount=0)  and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01');
				/* and dateDue < strftime('%s','now','+7 days') - strftime('%s','2001-01-01'); */
	select '    Flagged projects and actions', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and tp.effectiveFlagged;
	select '    Due or Flagged', count(*) from (task t left join projectinfo p on t.containingProjectinfo=p.pk) tp left join context c on tp.context=c.persistentIdentifier where (((projectinfo is null) and (tp.childrenCount=0))  or containsSingletonActions=0) and (dateCompleted is null)
				and (tp.containingProjectinfo is null or (tp.status !='dropped' and tp.folderEffectiveActive=1))
				and (tp.context is null or c.effectiveActive= 1)
				and (tp.containingProjectInfo is null or tp.status!='inactive')
				/* and (tp.context is null or c.allowsNextAction=1) */
				and tp.blockedByFutureStartDate=0
				and (tp.effectiveFlagged or (effectiveDateDue <= strftime('%s','now','+7 days') - strftime('%s','2001-01-01')));
	select null;
	"
	if brief then
		set commands to summary_cmd & actions_cmd & projects_cmd & contexts_cmd
	else
		set commands to summary_cmd & actions_cmd & inbox_cmd & folders_cmd & projects_cmd & lists_cmd & contexts_cmd & groups_cmd & tasks_cmd
	end if
	set strCmd to "sqlite3 -separator ': ' \"" & pstrDBPath & "\" " & quoted form of (commands)

	-- 		try
	set strList to do shell script strCmd
	-- 		on error
	-- 			display dialog "The SQL schema for the OmniFocus cache may have changed in a recent update of OF." & return & return &
	-- 				"Look on the OmniFocus user forums for an updated version of this script." buttons {"OK"} with title pTitle & "Ver. " & pVersion
	-- 			return
	-- 		end try
	tell application id "sevs"
		activate
		if button returned of (display dialog strList buttons {pToClipboard, "OK"} default button "OK" giving up after pTimeOut with title pTitle & " Ver. " & pVersion)
			is pToClipboard then tell application id "com.apple.finder" to set the clipboard to strList
	end tell
else
	tell application id "sevs"
		activate
		display dialog "OmniFocus cache not found ..." buttons {"OK"} default button 1 with title pTitle & " Ver. " & pVersion
	end tell
end if

on FileExists(strPath)
	(do shell script "test -e " & strPath & " ; echo $?") = "0"
end FileExists

on GetCachePath()
	try
		tell application "Finder" to tell (application file id "OFOC") to "$HOME/Library/Containers/com.omnigroup.OmniFocus2/Data/Library/Caches/" & its id & "/OmniFocusDatabase2"
	on error
		error "OmniFocus not installed ..."
	end try
end GetCachePath


Update the watch workers applescript to watch the celerybeat log file.

set broker to "h8.opera.com"
set workers to {"h6.opera.com", "h8.opera.com", "h9.opera.com", "h10.opera.com"}
set clock to "h6.opera.com"
tell application "iTerm"
    activate
    set myterm to (make new terminal)
    tell myterm
        set number of columns to 80
        set number of rows to 50
        repeat with workerhost in workers
            set worker to (make new session at the end of sessions)
            tell worker
                set name to workerhost
                set foreground color to "white"
                set background color to "black"
                set transparency to 0.1
                exec command "/bin/sh -i"
                write text "ssh root@" & workerhost & " 'tail -f /var/log/celeryd.log'"
            end tell
        end repeat
        set celerybeat to (make new session at the end of sessions)
        tell celerybeat
            set name to "celerybeat.log"
            set foreground color to "white"
            set background color to "black"
            set transparency to 0.1
            exec command "/bin/sh -i"
            write text "ssh root@" & clock & " 'tail -f /var/log/celerybeat.log'"
        end tell
        set rabbit to (make new session at the end of sessions)
        tell rabbit
            set name to "rabbit.log"
            set foreground color to "white"
            set background color to "black"
            set transparency to 0.1
            exec command "/bin/sh -i"
            write text "ssh root@" & broker & " 'tail -f /var/log/rabbitmq/rabbit.log'"
        end tell
        tell the first session
            activate
        end tell
    end tell
end tell

set broker to "h8.opera.com"
set workers to {"h6.opera.com", "h8.opera.com", "h9.opera.com", "h10.opera.com"}
tell application "iTerm"
    activate
    set myterm to (make new terminal)
    tell myterm
        set number of columns to 80
        set number of rows to 50
        repeat with workerhost in workers
            set worker to (make new session at the end of sessions)
            tell worker
                set name to workerhost
                set foreground color to "white"
                set background color to "black"
                set transparency to 0.1
                exec command "/bin/sh -i"
                write text "ssh root@" & workerhost & " 'tail -f /var/log/celeryd.log'"
            end tell
        end repeat
        set rabbit to (make new session at the end of sessions)
        tell rabbit
            set name to "rabbit.log"
            set foreground color to "white"
            set background color to "black"
            set transparency to 0.1
            exec command "/bin/sh -i"
            write text "ssh root@" & broker & " 'tail -f /var/log/rabbitmq/rabbit.log'"
        end tell
        tell the first session
            activate
        end tell
    end tell
end tell


archive script

archive script

FasdUAS 1.101.10
k
l?9 http://macscripter.net/viewtopic.php?id=40776, thevarium		r http://macscripter.net/viewtopic.php?id=40776, thevarium

l
KE Automatically archive messages in the inbox for one or more accounts
 Automatically archive messages in the inbox for one or more accounts
l based on their age.( based on their age.
l93 With some changes-simplifications by Cyril Niklausf With some changes-simplifications by Cyril Niklaus
l
l60 Set this value to the age of messages, in days,` Set this value to the age of messages, in days, !
 l"#"# which should not be archived#$$: which should not be archived!%&
%j'0
daystosave
daysToSave
'm-&()
(l)*+
*l,-,71 Set ARCHIVE_FOLDER to the top level folder where-..b Set ARCHIVE_FOLDER to the top level folder where+/0
/l121HB messages should be saved. There is no need to add On My Mac here.233 messages should be saved. There is no need to add On My Mac here.045
4j60
archivefolder
archiveFolder
6m7788Archived/Sorted59:
9l:;<
;l=>=>8 This should remain empty and will be assigned the name >??p This should remain empty and will be assigned the name <@A
@lBCB,& of any mailbox you have have selectedCDDL of any mailbox you have have selectedAEF
Ej
G0accountnamesaccountNames
GJ	HHI
ImJJKKFLM
LlMNO
NlPQP Modify thisQRR Modify thisOST
SlU
UrVW
VlX
XmYYZZMacintosh HD:Users:YOURUSER:Library:Application Scripts:com.apple.mail:stringtemp.scpt
Wo0
scriptpath
scriptPathT[\
[l]
]r^_
^l`
`Ia
.sysoloadscptfile
a4b

alis
bo0
scriptpath
scriptPath
_o0	thescript	theScript\cd
cldef
elGg
gOGhi
hkFjjkl
kllmn
mlopo82 Figure out the earliest date for messages we wantpqqd Figure out the earliest date for messages we wantnrs
rltut to leave in the mailboxuvv0 to leave in the mailboxswx
wr"yz
yl {
{\ |}
|l~
~I
.misccurdldt null
}l
]
o0
daystosave
daysToSave
1

days
zo0earliestdateearliestDatex
l##
r#/
l#)
n#)
1')

msbx
4#'

mvwr
m%&
o0accountnamesaccountNames
l00
X0F
kDA
lDD/) Set the Mailbox name of selected mailboxR Set the Mailbox name of selected mailbox
QDW
rGJ
oGH0
anaccountname
anAccountName
o0
themailbox
theMailbox
R
.ascrerr ********
kRW
lRRJDlog "Could not archive from " & (name of anAccountName as rich text)log "Could not archive from " & (name of anAccountName as rich text)
rRW
mRU

null
o0
themailbox
theMailbox
lXX
ZXA
>X]
oXY0
themailbox
theMailbox
mY\

null
k`=
l``+% Find the messages we want to archiveJ Find the messages we want to archive
l``B< In addition to mail older than X number of days it will notx In addition to mail older than X number of days it will not
l``A; archive any mail that is unread, flagged or marked as junkv archive any mail that is unread, flagged or marked as junk
r`
l`
6`
n`e
2ae

mssg
o`a0
themailbox
theMailbox
lh
Fh
Fi
Fj
=kt
1lp

isrd
mqs
boovtrue
=u~
1vz

isjk
m{}
boovfals
=
1

isfl
m
boovfals
A
1

drcv
o0earliestdateearliestDate
o0themessagestheMessages
l
X;
k6
l-- first we find the sender of the message
				set theSender to sender of currentMessage as string
				-- now we strip off the sender's domain (everything after the "@")
				set oldDelimiters to AppleScript's text item delimiters
				set AppleScript's text item delimiters to {"@"}
				try
					set theDomain to the second text item of theSender
					-- always set the text item delimiters back as soon as possible!
					set AppleScript's text item delimiters to ""
					-- and strip the last character off the domain, as it will be a ">"
					if theDomain contains ">" then
						set theDomain to leftStringFromRight(theDomain, ">") of theScript
					end if
					repeat
						-- If the senders domain contains multiple periods
						-- I remove anything to right of any period to
						-- capture just the Root domain
						if theDomain contains "." then
							set theDomain to leftStringFromRight(theDomain, ".") of theScript
						else
							exit repeat
						end if
					end repeat
					-- Format the domain so your folders look uniform
					-- This is the OCD in me
					set theDomain to theScript's capitalizeString(theDomain)
				on error
					-- If the domain could not be found then it sets the
					-- domain to Undetermined and archives those emails
					-- into one folder. But this could be used to exit
					-- current loop and leave the messsage alone
					set theDomain to "Undetermined"
					set AppleScript's text item delimiters to ""
				end try z-- first we find the sender of the message
				set theSender to sender of currentMessage as string
				-- now we strip off the sender's domain (everything after the "@")
				set oldDelimiters to AppleScript's text item delimiters
				set AppleScript's text item delimiters to {"@"}
				try
					set theDomain to the second text item of theSender
					-- always set the text item delimiters back as soon as possible!
					set AppleScript's text item delimiters to ""
					-- and strip the last character off the domain, as it will be a ">"
					if theDomain contains ">" then
						set theDomain to leftStringFromRight(theDomain, ">") of theScript
					end if
					repeat
						-- If the senders domain contains multiple periods
						-- I remove anything to right of any period to
						-- capture just the Root domain
						if theDomain contains "." then
							set theDomain to leftStringFromRight(theDomain, ".") of theScript
						else
							exit repeat
						end if
					end repeat
					-- Format the domain so your folders look uniform
					-- This is the OCD in me
					set theDomain to theScript's capitalizeString(theDomain)
				on error
					-- If the domain could not be found then it sets the
					-- domain to Undetermined and archives those emails
					-- into one folder. But this could be used to exit
					-- current loop and leave the messsage alone
					set theDomain to "Undetermined"
					set AppleScript's text item delimiters to ""
				end try
l,& Set the archive location based on theL Set the archive location based on the
l+% modified this to not sort by sender.J modified this to not sort by sender.
r
l
I
.misccurdldt null
o0	thedomain	theDomain
r
l~
b
b
o}}0
archivefolder
archiveFolder
m/
o||0	thedomain	theDomain~
o{{0mailboxnamemailboxName
lzz4. Find the top level mailbox.  If this does not\ Find the top level mailbox.  If this does not
lyy0* exist, we will get an error and bail out.T exist, we will get an error and bail out.
r
4x

x
mbxp

oww0
archivefolder
archiveFolder
	ovv0rootmailboxrootMailbox
lu
u
93 Find the domain archive mailbox.  If this does notf Find the domain archive mailbox.  If this does not
ltt exist, we create it.* exist, we create it.
Q(
r
lsr
n
4q
q
mbxp
l po
 c!"
!onn0	thedomain	theDomain
"mm
m
TEXTpo
oll0rootmailboxrootMailboxsr
okk0
domainmailbox
domainMailbox
Rjih
j.ascrerr ********ih
k(##$%
$Igf&
g.corecrel****nullf&e'(
e
kocl
'md
d
mbxp(c)b
c
prdt
)K**a+`
a
pnam
+l
,_^
,b
-.
-b	/0
/o]]0
archivefolder
archiveFolder
0m1122/
.o	\\0	thedomain	theDomain_^`b%3[
3r(45
4l$6ZY
6n$78
74$X9
X
mbxp
9l#:WV
:c#;<
;oUU0	thedomain	theDomain
<m"T
T
TEXTWV
8oSS0rootmailboxrootMailboxZY
5oRR0
domainmailbox
domainMailbox[=>
=I)4Q?@
Q.coremovenullobj
?o)*PP 0currentmessagecurrentMessage@OAN
O
insh
Ao-0MM0
domainmailbox
domainMailboxN>BL
Bl55KJIKJIL 0currentmessagecurrentMessage
oHH0themessagestheMessagesCG
Cl<<FEDFEDG0
anaccountname
anAccountName
o38CC0accountnamesaccountNames
imDDemalalis*OdeH+$Mail.appyir	 ApplicationsiU$Ode:Applications:Mail.appMail.appOdeApplications/Mail.app/fEF
ElBA@BA@FG?
Gl>=<>=<?;H:7IJ;H987690
daystosave
daysToSave80
archivefolder
archiveFolder70accountnamesaccountNames
6.aevtoappnull****:-I5K5KJJ4L32MN1
4.aevtoappnull****
LkGOOSPP[QQe0032M/./0
anaccountname
anAccountName. 0currentmessagecurrentMessageN'Y-,+*D)('&%$#"! R1
-0
scriptpath
scriptPath
,
alis
+.sysoloadscptfile*0	thescript	theScript
).misccurdldt null
(
days'0earliestdateearliestDate
&
mvwr
%
msbx
$
kocl
#
cobj
".corecnte********!0
themailbox
theMailbox

null

mssgR

isrd

isjk

isfl

drcv0themessagestheMessages0	thedomain	theDomain0mailboxnamemailboxName

mbxp0rootmailboxrootMailbox

TEXT0
domainmailbox
domainMailbox

prdt

pnam
.corecrel****null

insh
.coremovenullobj 1HEO*/jEO5*jb EO*k/,EcOb[l
khEWXaEOaa-a[[[[a,\Ze8\[a,\Zf8A\[a,\Zf8A\[a,\Z<A1E`O_[l
kh*jE`Oba%_%E`O*ab/E`O_a_a&/E`W:X*aa a!ba"%_%la#$O_a_a&/E`Oa%_l&OP[OYqOPYh[OYUascrޭ

FasdUAS 1.101.10
k
l?9 http://macscripter.net/viewtopic.php?id=40776, thevarium		r http://macscripter.net/viewtopic.php?id=40776, thevarium

l
KE Automatically archive messages in the inbox for one or more accounts
 Automatically archive messages in the inbox for one or more accounts
l based on their age.( based on their age.
l
l60 Set this value to the age of messages, in days,` Set this value to the age of messages, in days,
l# which should not be archived: which should not be archived !
 j"0
daystosave
daysToSave
"m-!#$
#l$%&
%l'('71 Set ARCHIVE_FOLDER to the top level folder where())b Set ARCHIVE_FOLDER to the top level folder where&*+
*l,-,C= messages should be saved. For mine I created a folder called-..z messages should be saved. For mine I created a folder called+/0
/l121GA Sorted which houses all of the sub folders created by the script233 Sorted which houses all of the sub folders created by the script045
4l676.( there is no need to add On My Mac here.788P there is no need to add On My Mac here.59:
9j;0
archivefolder
archiveFolder
;m<<==Archived/Sorted:>?
>l?@A
@lBCB>8 This should remain empty and will be assigned the name CDDp This should remain empty and will be assigned the name AEF
ElGHG,& of any mailbox you have have selectedHIIL of any mailbox you have have selectedFJK
Jj
L0accountnamesaccountNames
LJ	MMN
NmOOPPKQR
QlRST
SlUVUset scriptPath to ("Macintosh HD:Users:YOURUSER:Library:Application Scripts:com.apple.mail") Or another location of your choosingVWWset scriptPath to ("Macintosh HD:Users:YOURUSER:Library:Application Scripts:com.apple.mail") Or another location of your choosingTXY
XlZ
Zr[\
[l]
]m^^__Macintosh HD:Users:YOURUSER:Library:Application Scripts:com.apple.mail:stringtemp.scpt
\o0
scriptpath
scriptPathY`a
`lb
brcd
cle
eIf
.sysoloadscptfile
f4g

alis
go0
scriptpath
scriptPath
do0	thescript	theScriptahi
hlijk
jll
lOmn
mkoopq
plqrs
rltut82 Figure out the earliest date for messages we wantuvvd Figure out the earliest date for messages we wantswx
wlyzy to leave in the mailboxz{{0 to leave in the mailboxx|}
|r"~
~l
\
l
I
.misccurdldt null
l
]
o0
daystosave
daysToSave
1

days
o0earliestdateearliestDate}
l##
r#/
l#)
n#)
1')

msbx
4#'

mvwr
m%&
o0accountnamesaccountNames
l00
X0
kD
lDD/) Set the Mailbox name of selected mailboxR Set the Mailbox name of selected mailbox
QDW
rGJ
oGH0
anaccountname
anAccountName
o0
themailbox
theMailbox
R
.ascrerr ********
kRW
lRRJDlog "Could not archive from " & (name of anAccountName as rich text)log "Could not archive from " & (name of anAccountName as rich text)
rRW
mRU

null
o0
themailbox
theMailbox
lXX
ZX
>X]
oXY0
themailbox
theMailbox
mY\

null
k`
l``+% Find the messages we want to archiveJ Find the messages we want to archive
l``B< In addition to mail older than X number of days it will notx In addition to mail older than X number of days it will not
l``A; archive any mail that is unread, flagged or marked as junkv archive any mail that is unread, flagged or marked as junk
r`
l`
6`
n`e
2ae

mssg
o`a0
themailbox
theMailbox
lh
Fh
Fi
Fj
=kt
1lp

isrd
mqs
boovtrue
=u~
1vz

isjk
m{}
boovfals
=
1

isfl
m
boovfals
A
1

drcv
o0earliestdateearliestDate
o0themessagestheMessages
l
X
k
l.( first we find the sender of the messageP first we find the sender of the message
r
c
n
1

sndr
o 0currentmessagecurrentMessage
m

TEXT
o0	thesender	theSender
lF@ now we strip off the sender's domain (everything after the "@") now we strip off the sender's domain (everything after the "@")
r
n
1

txdl
1

ascr
o0
olddelimiters
oldDelimiters
r
J~
m@~
n
1}
}
txdl
1|
|
ascr
Q^
kC

r

l{z
n
4y
y
citm
mxx
oww0	thesender	theSender{z

ovv0	thedomain	theDomain
luuD> always set the text item delimiters back as soon as possible!| always set the text item delimiters back as soon as possible!
r
m
n
1t
t
txdl
1s
s
ascr
lr!"r!GA and strip the last character off the domain, as it will be a ">""## and strip the last character off the domain, as it will be a ">" $%
$Z&'qp
&E()
(ooo0	thedomain	theDomain
)m**++>
'r
,-
,n./
.In0mn*0leftstringfromrightleftStringFromRight012
1oll0	thedomain	theDomain23k
3m4455>km
/ojj0	thescript	theScript
-oii0	thedomain	theDomainqp%67
6T68
8k199:;
:lh<=h<60 If the senders domain contains multiple periods=>>` If the senders domain contains multiple periods;?@
?lgABgA2, I remove anything to right of any period toBCCX I remove anything to right of any period to@DE
DlfFGfF# capture just the Root domainGHH: capture just the Root domainEIe
IZ1JKdL
JEMN
Mocc0	thedomain	theDomain
NmOOPP.
Kr-QR
Qn)ST
SI)bUab*0leftstringfromrightleftStringFromRightUVW
Vo"``0	thedomain	theDomainWX_
Xm"%YYZZ._a
To^^0	thescript	theScript
Ro]]0	thedomain	theDomaind
LS01e7[\
[l77\]^\]5/ Format the domain so your folders look uniform^__^ Format the domain so your folders look uniform\`a
`l77[bc[b This is the OCD in mecdd, This is the OCD in meaeZ
er7Cfg
fn7?hi
hI8?YjXY$0capitalizestringcapitalizeStringjkW
ko8;VV0	thedomain	theDomainWX
io78UU0	thescript	theScript
goTT0	thedomain	theDomainZ
RSRQ
S.ascrerr ********RQ
kK^llmn
mlKKPopPo93 If the domain could not be found then it sets the pqqf If the domain could not be found then it sets the nrs
rlKKOtuOt71 domain to Undetermined and archives those emailsuvvb domain to Undetermined and archives those emailsswx
wlKKNyzNy60 into one folder. But this could be used to exitz{{` into one folder. But this could be used to exitx|}
|lKKM~M~0* current loop and leave the messsage aloneT current loop and leave the messsage alone}
rKR
mKNUndetermined
oLL0	thedomain	theDomainK
rS^
mSV
n
1Y]J
J
txdl
1VYI
I
ascrK
l__HGFHGF
l__EE,& Set the archive location based on theL Set the archive location based on the
r_p
l_lDC
b_l
b_h
o_dBB0
archivefolder
archiveFolder
mdg/
ohkAA0	thedomain	theDomainDC
o@@0mailboxnamemailboxName
lqq??4. Find the top level mailbox.  If this does not\ Find the top level mailbox.  If this does not
lqq>>0* exist, we will get an error and bail out.T exist, we will get an error and bail out.
rq
4q{=
=
mbxp
ouz<<0
archivefolder
archiveFolder
o;;0rootmailboxrootMailbox
l::93 Find the domain archive mailbox.  If this does notf Find the domain archive mailbox.  If this does not
l99 exist, we create it.* exist, we create it.
Q
r
l87
n
46
6
mbxp
l54
c
o330	thedomain	theDomain
m2
2
TEXT54
o110rootmailboxrootMailbox87
o000
domainmailbox
domainMailbox
R/.-
/.ascrerr ********.-
k
I,+
,.corecrel****null+*
*
kocl
m)
)
mbxp('
(
prdt
K&%
&
pnam
l$#
b
b
o""0
archivefolder
archiveFolder
m/
o!!0	thedomain	theDomain$#%'
r
l
n
4

mbxp
l
c
o0	thedomain	theDomain
m

TEXT
o0rootmailboxrootMailbox
o0
domainmailbox
domainMailbox
I
.coremovenullobj
o 0currentmessagecurrentMessage

insh
o0
domainmailbox
domainMailbox
l 0currentmessagecurrentMessage
o

0themessagestheMessages
l

	0
anaccountname
anAccountName
o380accountnamesaccountNames
nmemalalis*BobH+IMail.app!΅	 Applications߸΄IBob:Applications:Mail.appMail.appBobApplications/Mail.app/k
l
l<0
daystosave
daysToSave0
archivefolder
archiveFolder0accountnamesaccountNames
.aevtoappnull****-O
.aevtoappnull****
kX`j0
anaccountname
anAccountName 0currentmessagecurrentMessage7^*4OY0
scriptpath
scriptPath

alis
.sysoloadscptfile0	thescript	theScript
.misccurdldt null

days0earliestdateearliestDate

mvwr

msbx

kocl

cobj
.corecnte********0
themailbox
theMailbox

null

mssg

isrd

isjk

isfl

drcv0themessagestheMessages

sndr

TEXT0	thesender	theSender

ascr

txdl0
olddelimiters
oldDelimiters

citm0	thedomain	theDomain*0leftstringfromrightleftStringFromRight$0capitalizestringcapitalizeString0mailboxnamemailboxName

mbxp0rootmailboxrootMailbox0
domainmailbox
domainMailbox

prdt

pnam
.corecrel****null

insh
.coremovenullobj EO*/jEO*jb EO*k/,EcOb[l
khEWXaEOaa-a[[[[a,\Ze8\[a,\Zf8A\[a,\Zf8A\[a,\Z<A1E`OG_[l
kha,a&E`O_a,E`Oakv_a,FOp_a l/E`!Oa"_a,FO_!a#_!a$l+%E`!YhO&hZ_!a&_!a'l+%E`!Y[OYO_!k+(E`!WXa)E`!Oa*_a,FOba+%_!%E`,O*a-b/E`.O_.a-_!a&/E`/W:X*a-a0a1ba2%_!%la34O_.a-_!a&/E`/Oa5_/l6OP[OYOPYh[OYUUascrޭ


Tidied the shell script lines; added “.000” to each chapter marker time for compatibility

--
--  DASAppDelegate.applescript
--  itunes-concatenator
--
--  Created by David Schlachter on 2014-08-26.
--  Copyright (c) 2014 Red Eft Software. All rights reserved.
--

-- via http://macscripter.net/viewtopic.php?pid=173787 ; apparently needed for using arrays

script DASAppDelegate
	property parent : class "NSObject"

    global these_files, these_times, these_titles, the_index, the_pipes, theCounter, cmdPrefix

	-- IBOutlets
	property window : missing value
    property trackTable : missing value
    property catName : missing value
    property catArtist : missing value
    property catAlbum : missing value
    property catComposer : missing value
    property catGenre : missing value
    property catTrack : missing value
    property catTracks : missing value
    property catDisc : missing value
    property catDiscs : missing value

    -- Again, per macscripter, we'll set up bindings for the options
    property pcatName : ""
    property pcatArtist : ""
    property pcatAlbum : ""
    property pcatComposer : ""
    property pcatGenre : ""
    property pcatTrack : ""
    property pcatTracks : ""
    property pcatDisc : ""
    property pcatDiscs : ""

    -- Empty strings for each file name and location
    property pEachName : ""
    property pEachLocation : ""

    property these_titles : {}
    property these_files : {}
    property these_times: {}
    property the_index: {}
    property the_pipes: {}

    property theCounter : ""
    property cmdPrefix : "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;"

    on awakeFromNib()
        --
        -- Check for FFMPEG
        --
        -- (This works, but it's ugly!)
        --
        --
        try
            do shell script cmdPrefix & " if [ -x \"`/usr/bin/which ffmpeg`\" ];then exit 0;else exit 1;fi"
        on error number error_number
            display dialog "You must install FFMPEG to continue. \n\nYou may have to install Xcode Command Line Tools and Homebrew first. If you continue, we'll attempt to install them for you if they are not already present. \n\nIf you have already installed FFMPEG, ensure that it is in your bash path." buttons {"Quit","Install FFMPEG"} default button 2
            If button returned of result is "Install FFMPEG" then
                try
                    tell application "Terminal"
                        -- TODO: This should be cleaner -- Terminal in front, only one window, focus back to the cat'er afterwards
                        set newTab to do script cmdPrefix & "if [[ -x `which brew` ]];then brew install ffmpeg;else /usr/bin/ruby -e \"$(/usr/bin/curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)\";brew install ffmpeg;fi"
                        delay 4
                        repeat
                            delay 0.1
                            if not busy of newTab then exit repeat
                        end repeat
                    end tell
                     -- TODO: This needs a better test, i.e., check if ffmpeg is actually accessible on the path
                    display dialog "FFMPEG was successfully installed"
                    -- TODO: This should actually work! (Bring us back to the foreground)
                    activate current application
                on error number error_number
                    display dialog "FFMPEG did not successfully install"
                end try
            end If
            If button returned of result is "Quit" then
                -- Fix!
                current application's NSApp's terminate()
            end If
        end try
    end awakeFromNib

    on btnGetTracks_(sender)
        -- Code to add iTunes tracks to our list
        -- via http://dougscripts.com/itunes/itinfo/info02.php and http://www.randomsequence.com/articles/applescript-to-send-selected-itunes-tracks-using-mail/
        tell application "iTunes"
            set these_titles to {}
            set these_times to {}
            set these_files to {}
            set the_index to {}
            if selection is not {} then -- there ARE tracks selected...
                set mySelection to selection
                set i to 1
                repeat with aTrack in mySelection
                    if class of aTrack is file track then
                        set end of these_titles to ((name of aTrack) as string)
                        set end of these_times to ((time of aTrack) as string)
                        set end of these_files to (posix path of (get location of aTrack))
                        set end of the_index to (count of these_titles)
                    end if
                end repeat
            end if
        end tell
        -- via http://stackoverflow.com/questions/25537750/setstringvalue-with-applescript-list
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "\n"
        set disp_titles to these_titles as string
        trackTable's setStringValue_(disp_titles)
        set AppleScript's text item delimiters to olddelimeters
    end btnGetTracks_

    on btnConcatenate_(sender)
        set the_pipes to {}
        repeat with theIndex in the_index
            -- TODO: Needs error checking!
            -- TODO: We need to check what kind of audio files we have, then adjust accordingly
            do shell script (cmdPrefix & "ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text)
            log ("Processed file number" & theIndex) as text
            set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text)
        end repeat
        -- Run the actual concatenation command in ffmpeg, via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "|"
        set disp_thepipes to the_pipes as string
        do shell script (cmdPrefix & "ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4")
        set AppleScript's text item delimiters to olddelimeters
        -- Now let's create the chapter file
        repeat with theIndex in the_index
            if theIndex < 2 then
                do shell script ("/bin/echo \"00:00:00.000 " & (item theIndex of these_titles as text) & "\" > /private/tmp/chapters" as text)
                set theCounter to (do shell script (cmdPrefix & "ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'" as text) as string)
            else
                set theDateStamp to do shell script (cmdPrefix & "t="& (theCounter as text) & ";((sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d\" $hrs $min $sec);/bin/echo $timestamp" as text)
                do shell script ("/bin/echo \"" & (theDateStamp as text) & ".000 " & (item theIndex of these_titles as text) & "\" >> /private/tmp/chapters" as text)
                log ("Before the addition, theCounter is " & theCounter) as text
                set theCounter to do shell script (cmdPrefix & "t=" & theCounter & ";t=`echo $t\"+\\`ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'\\`\" | bc`;echo $t" as text)
                log ("After the addition, theCounter is " & theCounter) as text
            end if
        end repeat
        -- Clean up
        -- do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.mp4 /private/tmp/chapters"
        set theCounter to ""
    end btnConcatenate_

	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
	end applicationWillFinishLaunching_

	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits
		return current application's NSTerminateNow
	end applicationShouldTerminate_

end script

--
--  DASAppDelegate.applescript
--  itunes-concatenator
--
--  Created by David Schlachter on 2014-08-26.
--  Copyright (c) 2014 Red Eft Software. All rights reserved.
--

-- via http://macscripter.net/viewtopic.php?pid=173787 ; apparently needed for using arrays

script DASAppDelegate
	property parent : class "NSObject"

    global these_files, these_times, these_titles, the_index, the_pipes, theCounter

	-- IBOutlets
	property window : missing value
    property trackTable : missing value
    property catName : missing value
    property catArtist : missing value
    property catAlbum : missing value
    property catComposer : missing value
    property catGenre : missing value
    property catTrack : missing value
    property catTracks : missing value
    property catDisc : missing value
    property catDiscs : missing value

    -- Again, per macscripter, we'll set up bindings for the options
    property pcatName : ""
    property pcatArtist : ""
    property pcatAlbum : ""
    property pcatComposer : ""
    property pcatGenre : ""
    property pcatTrack : ""
    property pcatTracks : ""
    property pcatDisc : ""
    property pcatDiscs : ""

    -- Empty strings for each file name and location
    property pEachName : ""
    property pEachLocation : ""

    property these_titles : {}
    property these_files : {}
    property these_times: {}
    property the_index: {}
    property the_pipes: {}

    property theCounter : ""

    on awakeFromNib()
        --
        -- Check for FFMPEG
        --
        -- (This works, but it's ugly!)
        --
        --
        try
            do shell script "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi; if [ -x \"`/usr/bin/which ffmpeg`\" ];then exit 0;else exit 1;fi"
        on error number error_number
            display dialog "You must install FFMPEG to continue. \n\nYou may have to install Xcode Command Line Tools and Homebrew first. If you continue, we'll attempt to install them for you if they are not already present. \n\nIf you have already installed FFMPEG, ensure that it is in your bash path." buttons {"Quit","Install FFMPEG"} default button 2
            If button returned of result is "Install FFMPEG" then
                try
                    tell application "Terminal"
                        -- TODO: This should be cleaner -- Terminal in front, only one window, focus back to the cat'er afterwards
                        set newTab to do script "if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;if [[ -x `which brew` ]];then brew install ffmpeg;else /usr/bin/ruby -e \"$(/usr/bin/curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)\";brew install ffmpeg;fi"
                        delay 4
                        repeat
                            delay 0.1
                            if not busy of newTab then exit repeat
                        end repeat
                    end tell
                     -- TODO: This needs a better test, i.e., check if ffmpeg is actually accessible on the path
                    display dialog "FFMPEG was successfully installed"
                    -- TODO: This should actually work! (Bring us back to the foreground)
                    activate current application
                on error number error_number
                    display dialog "FFMPEG did not successfully install"
                end try
            end If
            If button returned of result is "Quit" then
                -- Fix!
                current application's NSApp's terminate()
            end If
        end try
    end awakeFromNib

    on btnGetTracks_(sender)
        -- Code to add iTunes tracks to our list
        -- via http://dougscripts.com/itunes/itinfo/info02.php and http://www.randomsequence.com/articles/applescript-to-send-selected-itunes-tracks-using-mail/
        tell application "iTunes"
            set these_titles to {}
            set these_times to {}
            set these_files to {}
            set the_index to {}
            if selection is not {} then -- there ARE tracks selected...
                set mySelection to selection
                set i to 1
                repeat with aTrack in mySelection
                    if class of aTrack is file track then
                        set end of these_titles to ((name of aTrack) as string)
                        set end of these_times to ((time of aTrack) as string)
                        set end of these_files to (posix path of (get location of aTrack))
                        set end of the_index to (count of these_titles)
                    end if
                end repeat
            end if
        end tell
        -- via http://stackoverflow.com/questions/25537750/setstringvalue-with-applescript-list
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "\n"
        set disp_titles to these_titles as string
        trackTable's setStringValue_(disp_titles)
        set AppleScript's text item delimiters to olddelimeters
    end btnGetTracks_

    on btnConcatenate_(sender)
        set the_pipes to {}
        repeat with theIndex in the_index
            -- TODO: Needs error checking!
            -- TODO: We need to check what kind of audio files we have, then adjust accordingly
            do shell script ("if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;ffmpeg -i \"" & (item theIndex of these_files as text) & "\" -c copy -bsf:v h264_mp4toannexb -f mpegts /private/tmp/concat" & theIndex & ".ts 2> /dev/null" as text)
            log ("Processed file number" & theIndex) as text
            set end of the_pipes to ("/private/tmp/concat" & theIndex & ".ts" as text)
        end repeat
        -- Run the actual concatenation command in ffmpeg, via https://trac.ffmpeg.org/wiki/How%20to%20concatenate%20(join,%20merge)%20media%20files
        set olddelimeters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to "|"
        set disp_thepipes to the_pipes as string
        do shell script ("if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;ffmpeg -f mpegts -i \"concat:" & (disp_thepipes as text) & "\" -c copy -bsf:a aac_adtstoasc /private/tmp/cat.mp4")
        set AppleScript's text item delimiters to olddelimeters
        -- Now let's create the chapter file
        repeat with theIndex in the_index
            if theIndex < 2 then
                do shell script ("/bin/echo \"00:00:00 " & (item theIndex of these_titles as text) & "\" > /private/tmp/chapters" as text)
                set theCounter to (do shell script ("if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'" as text) as string)
            else
                set theDateStamp to do shell script ("if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;t="& (theCounter as text) & ";((sec=t%60, t/=60, min=t%60, hrs=t/60));timestamp=$(printf \"%02d:%02d:%02d\" $hrs $min $sec);/bin/echo $timestamp" as text)
                do shell script ("/bin/echo \"" & (theDateStamp as text) & " " & (item theIndex of these_titles as text) & "\" >> /private/tmp/chapters" as text)
                log ("Before the addition, theCounter is " & theCounter) as text
                set theCounter to do shell script ("if [[ -r /etc/profile ]];then . /etc/profile;fi;if [[ -r ~/.bashrc ]];then . ~/.bashrc;fi;if [[ -r ~/.bash_profile ]];then . ~/.bash_profile;fi;t=" & theCounter & ";t=`echo $t\"+\\`ffprobe -loglevel panic -show_streams /private/tmp/concat" & (theIndex as text) & ".ts | egrep -m 1 'duration=[0-9]+\\.' | sed 's/duration=\\([0-9]*[0-9]\\)\\.[0-9]*/\\1/'\\`\" | bc`;echo $t" as text)
                log ("After the addition, theCounter is " & theCounter) as text
            end if
        end repeat
        -- Clean up
        -- do shell script "/bin/rm /private/tmp/concat* /private/tmp/cat.mp4 /private/tmp/chapters"
        set theCounter to ""
    end btnConcatenate_

	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
	end applicationWillFinishLaunching_

	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits
		return current application's NSTerminateNow
	end applicationShouldTerminate_

end script


Do not create empty stations object

Do not create empty stations object

tell application "Finder"
	set json_path to file "json.scpt" of folder of (path to me)
end tell
set json to load script (json_path as alias)

on is_running(appName)
	tell application "System Events" to (name of processes) contains appName
end is_running

set reply to json's createDict()
if is_running("Hermes") then
	reply's setkv("running", true)
	set hermesInfo to json's createDict()
--	set hermesStations to json's createDict()
	tell application "Hermes"
		hermesInfo's setkv("state", playback state as string)
		hermesInfo's setkv("volume", playback volume)

-- XXX: execution error: Hermes got an error: every station doesn’t understand the “count” message. (-1708)
--		repeat with theStation in stations
--			hermesStations's setkv("name", theStation's name)
--			hermesStations's setkv("id", theStation's station ID)
--		end repeat

		hermesInfo's setkv("title", current song's title)
		hermesInfo's setkv("artist", current song's artist)
		hermesInfo's setkv("album", current song's album)
		hermesInfo's setkv("artwork", current song's artwork URL)
		hermesInfo's setkv("rating", current song's rating)
		hermesInfo's setkv("position", playback position as integer)
		hermesInfo's setkv("duration", current song duration as integer)
		hermesInfo's setkv("station_name", current station's name)
		hermesInfo's setkv("station_id", current station's station ID)
	end tell
--	hermesInfo's setkv("stations", hermesStations)
	reply's setkv("info", hermesInfo)
else
	reply's setkv("running", false)
end if
return reply's toJson()

tell application "Finder"
	set json_path to file "json.scpt" of folder of (path to me)
end tell
set json to load script (json_path as alias)

on is_running(appName)
	tell application "System Events" to (name of processes) contains appName
end is_running

set reply to json's createDict()
if is_running("Hermes") then
	reply's setkv("running", true)
	set hermesInfo to json's createDict()
	set hermesStations to json's createDict()
	tell application "Hermes"
		hermesInfo's setkv("state", playback state as string)
		hermesInfo's setkv("volume", playback volume)

-- XXX: execution error: Hermes got an error: every station doesn’t understand the “count” message. (-1708)
--		repeat with theStation in stations
--			hermesStations's setkv("name", theStation's name)
--			hermesStations's setkv("id", theStation's station ID)
--		end repeat

		hermesInfo's setkv("title", current song's title)
		hermesInfo's setkv("artist", current song's artist)
		hermesInfo's setkv("album", current song's album)
		hermesInfo's setkv("artwork", current song's artwork URL)
		hermesInfo's setkv("rating", current song's rating)
		hermesInfo's setkv("position", playback position as integer)
		hermesInfo's setkv("duration", current song duration as integer)
		hermesInfo's setkv("station_name", current station's name)
		hermesInfo's setkv("station_id", current station's station ID)
	end tell
	hermesInfo's setkv("stations", hermesStations)
	reply's setkv("info", hermesInfo)
else
	reply's setkv("running", false)
end if
return reply's toJson()


Add deleteAllSlides

Add deleteAllSlides

on newPresentation(themeName)
	tell application "Keynote"
		activate
		-- FIXME: Make this selectable?
		set targetWidth to 1024 -- 1440 <-- higher resolution
		set targetHeight to 768 -- 1080 <-- higher resolution

		set props to {document theme:theme (themeName as string), width:targetWidth, height:targetHeight}

		set thisDocument to make new document with properties props
		return name of thisDocument
	end tell
end newPresentation

on openPresentation(posixPath)
	tell application "Keynote"
		open posixPath
	end tell
end openPresentation

on savePresentation(docname, posixPath)
	tell application "Keynote"
		save document named docname in POSIX file posixPath
	end tell
end savePresentation

on createSlide(docname, masterSlideName)
	try
		tell application "Keynote"
			tell document named docname
				set thisSlide to make new slide with properties {base slide:master slide masterSlideName}
			end tell
	  return thisSlide
		end tell
	on error
		return 0
	end try
end createSlide

on deleteAllSlides(docname)
	tell application "Keynote"
		tell document named docname to delete every slide
	end tell
end deleteAllSlides

on finalize(docname)
	tell application "Keynote"
		tell document named docname to delete slide 1
	end tell
end finalize

on themeMasters(docname)
	--	  tell application "Keynote" to get the name of every master slide of thisDocument
	tell application "Keynote"
		set names to the name of every master slide of document named docname
		return names
	end tell
end themeMasters

on addImage(docname, filepath)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
  tell application "Keynote"
	tell document named docname
		tell the current slide

			-- TO REPLACE A PLACEHOLDER OR EXISTING IMAGE:
			set thisPlaceholderImageItem to image 1
			-- change the value of the “file name” property of the image to be an HFS file reference to the replacement image file
		set macPath to POSIX file filepath as Unicode text
			set file name of thisPlaceholderImageItem to ¬
				alias macPath

		end tell
	end tell
  end tell
end addImage

on addTitle(docname, thisSlideTitle)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
	tell application "Keynote"
		tell document named docname
			tell the current slide
				if title showing is true then
					set the object text of the default title item to thisSlideTitle
				end if
			end tell
		end tell
	end tell
end addTitle

on addBody(docname, thisSlideBody)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
	tell application "Keynote"
		tell document named docname
			tell the current slide
				if body showing is true then
					set the object text of the default body item to thisSlideBody
				end if
			end tell
		end tell
	end tell
end addTitle

on newPresentation(themeName)
	tell application "Keynote"
		activate
		-- FIXME: Make this selectable?
		set targetWidth to 1024 -- 1440 <-- higher resolution
		set targetHeight to 768 -- 1080 <-- higher resolution

		set props to {document theme:theme (themeName as string), width:targetWidth, height:targetHeight}

		set thisDocument to make new document with properties props
		return name of thisDocument
	end tell
end newPresentation

on openPresentation(posixPath)
	tell application "Keynote"
		open posixPath
	end tell
end openPresentation

on savePresentation(docname, posixPath)
	tell application "Keynote"
		save document named docname in POSIX file posixPath
	end tell
end savePresentation

on createSlide(docname, masterSlideName)
	try
		tell application "Keynote"
			tell document named docname
				set thisSlide to make new slide with properties {base slide:master slide masterSlideName}
			end tell
	  return thisSlide
		end tell
	on error
		return 0
	end try
end createSlide

on finalize(docname)
	tell application "Keynote"
		tell document named docname to delete slide 1
	end tell
end finalize

on themeMasters(docname)
	--	  tell application "Keynote" to get the name of every master slide of thisDocument
	tell application "Keynote"
		set names to the name of every master slide of document named docname
		return names
	end tell
end themeMasters

on addImage(docname, filepath)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
  tell application "Keynote"
	tell document named docname
		tell the current slide

			-- TO REPLACE A PLACEHOLDER OR EXISTING IMAGE:
			set thisPlaceholderImageItem to image 1
			-- change the value of the “file name” property of the image to be an HFS file reference to the replacement image file
		set macPath to POSIX file filepath as Unicode text
			set file name of thisPlaceholderImageItem to ¬
				alias macPath

		end tell
	end tell
  end tell
end addImage

on addTitle(docname, thisSlideTitle)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
	tell application "Keynote"
		tell document named docname
			tell the current slide
				if title showing is true then
					set the object text of the default title item to thisSlideTitle
				end if
			end tell
		end tell
	end tell
end addTitle

on addBody(docname, thisSlideBody)
  (*
	FIXME: Use slide ID to adress slide instead of "current slide"
  *)
	tell application "Keynote"
		tell document named docname
			tell the current slide
				if body showing is true then
					set the object text of the default body item to thisSlideBody
				end if
			end tell
		end tell
	end tell
end addTitle


Used cleaner AppleScript with whose filter on application object

#!/usr/bin/osascript
# Query contact name with display name (alias)

on run argv
	tell application "Adium"
		set service_name to item 1 of argv
		set account_name to item 2 of argv
		set display_name to item 3 of argv
		set users to get every contact of account account_name of service service_name
		return (name of first contact whose display name is display_name) of account account_name of service service_name
	end tell
end run

#!/usr/bin/osascript
# Query contact name with display name (alias)

on run argv
	tell application "Adium"
		set service_name to item 1 of argv
		set account_name to item 2 of argv
		set display_name to item 3 of argv
		set users to get every contact of account account_name of service service_name
		repeat with user in users
			set dname to (display name of user)
			do shell script "echo " & dname
			if (dname = display_name) then
				return name of user
				exit repeat
			end if
		end repeat
	end tell
end run


compiled applescript

compiled applescript

FasdUAS 1.101.10
k
l
O
r

n

1

pbnd

n
m

cwin
1

desk
o0_b
	mMACSalistMacintosh HDGpH+E
Finder.appj_	 CoreServices`DEEE6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/
l
lO
OO
ON
kM
r;
l
e
1

pbnd
J  !"
!o0_x"#$
#o0_y$%&
%o0_w&'
'o0_h()
(r<B*+
*n<@,-
,4=@.

cobj
.m>?
-o<=0_b
+o0_vz)/
/rCM01
0JCI2234
3oCD0_x456
5mDE678
7oEF0_w89
9oFG0_vz
11IL

pbnd
4:

cwin
:m
m;;@alislMacintosh HDGpH+ETerminal.appn >e	 	Utilities?AEE2Macintosh HD:Applications:Utilities:Terminal.appTerminal.appMacintosh HD#Applications/Utilities/Terminal.app/
<=><
.aevtoappnull****0_b0_x0_y0_w0_h0_vz=?@A
.aevtoappnull****
?kOBBCC@A
;

desk

cwin

pbnd0_b

cobj0_x0_y0_w0_h0_vzP*,,,EUO=*k/5*,EE[k/EZ[l/EZ[m/EZ[/EZO/EOkv*,FUU>DD}ascr
ޭ

FasdUAS 1.101.10
k
l
O
r

n

1

pbnd

n
m

cwin
1

desk
o0_b
	mMACSalistMacintosh HDGpH+h
Finder.appmk"	 CoreServices͒hba6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/
l
lO
OO
ON
kM
r;
l
e
1

pbnd
J  !"
!o0_x"#$
#o0_y$%&
%o0_w&'
'o0_h()
(r<B*+
*n<@,-
,4=@.

cobj
.m>?
-o<=0_b
+o0_vz)/
/rCM01
0JCI2234
3oCD0_x456
5mDE678
7oEF0_w89
9oFG0_vz
11IL

pbnd
4:

cwin
:m
m;;@alislMacintosh HDGpH+͆Terminal.appg	 	Utilities͆ͅ2Macintosh HD:Applications:Utilities:Terminal.appTerminal.appMacintosh HD#Applications/Utilities/Terminal.app/
<=><
.aevtoappnull****0_b0_x0_y0_w0_h0_vz=?@A
.aevtoappnull****
?kOBBCC@A
;

desk

cwin

pbnd0_b

cobj0_x0_y0_w0_h0_vzP*,,,EUO=*k/5*,EE[k/EZ[l/EZ[m/EZ[/EZO/EOkv*,FUU>DD`
'%'ascr
ޭ


add killall at uninstaller.applescript

add killall at uninstaller.applescript

try
    display dialog "Are you sure you want to remove NoEjectDelay?" buttons {"Cancel", "OK"}
    if the button returned of the result is "OK" then
        try
            do shell script "test -f '/Library/Application Support/org.pqrs/NoEjectDelay/uninstall.sh'"
            try
                do shell script "sh '/Library/Application Support/org.pqrs/NoEjectDelay/uninstall.sh'" with administrator privileges
                display alert "NoEjectDelay has been uninstalled. Please restart OS X."
                do shell script "killall 'NoEjectDelay Utility'"
            on error
                display alert "Failed to uninstall NoEjectDelay."
            end try
        on error
            display alert "NoEjectDelay is not installed."
        end try
    end if
on error
    display alert "NoEjectDelay uninstallation was canceled."
end try

try
    display dialog "Are you sure you want to remove NoEjectDelay?" buttons {"Cancel", "OK"}
    if the button returned of the result is "OK" then
        try
            do shell script "test -f '/Library/Application Support/org.pqrs/NoEjectDelay/uninstall.sh'"
            try
                do shell script "sh '/Library/Application Support/org.pqrs/NoEjectDelay/uninstall.sh'" with administrator privileges
                display alert "NoEjectDelay has been uninstalled. Please restart OS X."
            on error
                display alert "Failed to uninstall NoEjectDelay."
            end try
        on error
            display alert "NoEjectDelay is not installed."
        end try
    end if
on error
    display alert "NoEjectDelay uninstallation was canceled."
end try


Implement isMavericksOrLater on the updater.

--
--  AppDelegate.applescript
--  PerianOpener
--
--  Created by C.W. Betts on 9/25/13.
--  Copyright (c) 2013 Perian Team. All rights reserved.
--

script AppDelegate
	property parent : class "NSObject"

	on isMavericksOrLater()
		set osver to system version of (system info)
		(* skip the first three characters: We don't run on pre-OS X systems,
		 and we won't reach Mac OS version 100 any time soon. *)
		set osList to characters 4 thru 6 of osver
		(* If we get a decimal as the last item, the second version value is greater than 10.
		 We're looking for Mac versions greater than nine. *)
		if (osList's item 3) is equal to "." then
			return yes
			else
			set preTen to osList's as text as real
			if preTen is greater than or equal to 9.0 then
				return yes
				else
				return no
			end if
		end if
	end isMavericksOrLater

	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
	end applicationWillFinishLaunching_

	on applicationDidFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
		tell current application's NSTimer to set theTimer to scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(10, me, "timerFired:", missing value, false)
	end applicationDidFinishLaunching_

	on timerFired_(timer)
		quit
	end timerFired_

	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits
		return current application's NSTerminateNow
	end applicationShouldTerminate_

	on application_openFiles_(appl, theFiles)

		set mavericks to isMavericksOrLater()
		if mavericks is true
		(* TODO: check for QuickTime 7, and point the user to the download location if they don't *)
		tell application id "com.apple.quicktimeplayer"
			repeat with theFile in theFiles's allObjects()
				set theFilePox to (theFile's fileSystemRepresentation())
				open theFilePox as POSIX file
			end repeat

			activate
		end tell

		else

		tell application "QuickTime Player"
			repeat with theFile in theFiles's allObjects()
				set theFilePox to (theFile's fileSystemRepresentation())
				open theFilePox as POSIX file
			end repeat

			activate
		end tell
		end
		quit

		return yes
	end application_openFiles_

end script

--
--  AppDelegate.applescript
--  PerianOpener
--
--  Created by C.W. Betts on 9/25/13.
--  Copyright (c) 2013 Perian Team. All rights reserved.
--

script AppDelegate
	property parent : class "NSObject"

	on isMavericksOrLater()
		-- TODO: Implement
		return yes
	end isMavericksOrLater

	on applicationWillFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
	end applicationWillFinishLaunching_

	on applicationDidFinishLaunching_(aNotification)
		-- Insert code here to initialize your application before any files are opened
		tell current application's NSTimer to set theTimer to scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(10, me, "timerFired:", missing value, false)
	end applicationDidFinishLaunching_

	on timerFired_(timer)
		quit
	end timerFired_

	on applicationShouldTerminate_(sender)
		-- Insert code here to do any housekeeping before your application quits
		return current application's NSTerminateNow
	end applicationShouldTerminate_

	on application_openFiles_(appl, theFiles)

		set mavericks to isMavericksOrLater()
		if mavericks is true
		tell application "com.apple.quicktimeplayer"
			repeat with theFile in theFiles's allObjects()
				set theFilePox to (theFile's fileSystemRepresentation())
				open theFilePox as POSIX file
			end repeat

			activate
		end tell

		else

		tell application "QuickTime Player"
			repeat with theFile in theFiles's allObjects()
				set theFilePox to (theFile's fileSystemRepresentation())
				open theFilePox as POSIX file
			end repeat

			activate
		end tell
		end
		quit

		return yes
	end application_openFiles_

end script


Work around an issue with iTunes 9 that causes it to delay a connection to remote speakers

(*
  Script object to make calling a defined function easier while in the
  iTunes and System Events name space.
*)
script remoteSpeakerFinder
  -- Given a list of buttons, find the remote speakers button
  -- by finding the first button with a name that isn't in a
  -- rejection list.
  on findCorrectButton (in_buttons)
    set buttons_to_skip to {"Burn Disc"}

    repeat with a_button in in_buttons
      try -- some buttons don't have names
        set the_name to name of a_button
        if buttons_to_skip does not contain {the_name} then
          return the_name
        end if
      end try
    end repeat

    return 16 -- default response
  end findCorrectButton
end script

(*
  Tell iTunes to use the "Mobile" set of remote speakers.
*)
tell application "System Events"
  tell process "iTunes"
     set the_buttons to (get buttons of window 1)
     set the_speaker_button to (remoteSpeakerFinder's findCorrectButton(the_buttons))

     -- Switch to the speakers in my bedroom
     set frontmost to true
     click button the_speaker_button of window 1
     key code 115                -- Home Key (first speaker in list)
     key code 125                -- Down Arrow
     key code 125                -- Down Arrow
     key code 36                 -- Return Key

     -- Wait for iTunes to connect to the speakers
     delay 5
  end tell
end tell

(*
  Script object to make calling a defined function easier while in the
  iTunes and System Events name space.
*)
script remoteSpeakerFinder
  -- Given a list of buttons, find the remote speakers button
  -- by finding the first button with a name that isn't in a
  -- rejection list.
  on findCorrectButton (in_buttons)
    set buttons_to_skip to {"Burn Disc"}

    repeat with a_button in in_buttons
      try -- some buttons don't have names
        set the_name to name of a_button
        if buttons_to_skip does not contain {the_name} then
          return the_name
        end if
      end try
    end repeat

    return 16 -- default response
  end findCorrectButton
end script

(*
  Tell iTunes to use the "Mobile" set of remote speakers.
*)
tell application "System Events"
  tell process "iTunes"
     set the_buttons to (get buttons of window 1)
     set the_speaker_button to (remoteSpeakerFinder's findCorrectButton(the_buttons))

     -- Switch to the speakers in my bedroom
     set frontmost to true
     click button the_speaker_button of window 1
     key code 115                -- Home Key (first speaker in list)
     key code 125                -- Down Arrow
     key code 125                -- Down Arrow
     key code 36                 -- Return Key
  end tell
end tell


JasonLeyba: Make reinstall.scpt system language independent.

r16964

#!/usr/bin/osascript
(*
Copyright 2012 Software Freedom Conservancy. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)

(*
This script can be used to quickly re-install the SafariDriver extension
during development.

Requirements:
- The extension must be manually installed before use
- This script must be run from the trunk.
*)

-- Keep this in sync with the name of the extension in the Info.plist
set EXTENSION to "WebDriver"

tell application "System Events"
	set ui_elements_enabled to UI elements enabled
end tell

if ui_elements_enabled is false then
	tell application "System Preferences"
		activate
		set current pane to pane id "com.apple.preference.universalaccess"
		display dialog "Please \"Enable access for assistive devices\" " & ¬
			"and try again..."
		error number -128
	end tell
end if

tell application "Safari" to activate

tell application "System Events"
	tell process "Safari"
		tell menu bar 1
			-- tell menu "Develop"
			tell menu bar item 8
				tell menu 1
					-- click menu item "Show Extension Builder"
					click menu item 7
				end tell
			end tell
		end tell

		delay 0.2

		-- https://discussions.apple.com/thread/2726674?start=0&tstart=0
		-- tell UI element 1 of scroll area 1 of window "Extension Builder"
		tell UI element 1 of scroll area 1 of window 1
			set found_extension to false
			set tc to (count (groups whose its images is not {}))
			repeat with i from 1 to tc
				if exists (static text 1 of group i) then
					set t_name to name of static text 1 of group i
					if t_name is EXTENSION then
						set found_extension to true
						-- click button "Reload" of UI element ("ReloadUninstall" & t_name)
						click button 1 of UI element 4
						exit repeat
					end if
				end if
				keystroke (character id 31)
				delay 0.2
			end repeat

			if found_extension is false then
				display dialog "Was unable to locate the extension \"" & EXTENSION ¬
					& "\"" & return & return ¬
					& "It must be manually installed before this script may be used."
				error number -128
			end if
		end tell
	end tell
end tell

tell application "Safari" to quit

#!/usr/bin/osascript
(*
Copyright 2012 Software Freedom Conservancy. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)

(*
This script can be used to quickly re-install the SafariDriver extension
during development.

Requirements:
- The extension must be manually installed before use
- This script must be run from the trunk.
*)

-- Keep this in sync with the name of the extension in the Info.plist
set EXTENSION to "WebDriver"

tell application "System Events"
	set ui_elements_enabled to UI elements enabled
end tell

if ui_elements_enabled is false then
	tell application "System Preferences"
		activate
		set current pane to pane id "com.apple.preference.universalaccess"
		display dialog "Please \"Enable access for assistive devices\" " & ¬
		    "and try again..."
		error number -128
	end tell
end if

tell application "Safari" to activate

tell application "System Events"
	tell process "Safari"
		tell menu bar 1
			tell menu "Develop"
				click menu item "Show Extension Builder"
				delay 1
			end tell
		end tell

		-- https://discussions.apple.com/thread/2726674?start=0&tstart=0
		tell UI element 1 of scroll area 1 of window "Extension Builder"
			set found_extension to false
			set tc to (count (groups whose its images is not {}))
			repeat with i from 1 to tc
				if exists (static text 1 of group i) then
					set t_name to name of static text 1 of group i
					if t_name is EXTENSION then
						set found_extension to true
						click button "Reload" of UI element ("ReloadUninstall" & t_name)
						exit repeat
					end if
				end if
				keystroke (character id 31)
				delay 0.2
			end repeat

			if found_extension is false then
				display dialog "Was unable to locate the extension \"" & EXTENSION ¬
				    & "\"" & return & return ¬
				    & "It must be manually installed before this script may be used."
				error number -128
			end if
		end tell
	end tell
end tell

tell application "Safari" to quit