We R Group Site Loading . . .
CMES R Group
<!--{{{-->

<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml'/>
<!--}}}-->
Background: #fff
Foreground: #000
PrimaryPale: #8cf
PrimaryLight: #18f
PrimaryMid: #04b
PrimaryDark: #014
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
/*{{{*/
body {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}

a {color:[[ColorPalette::PrimaryMid]];}
a:hover {background-color:[[ColorPalette::PrimaryMid]]; color:[[ColorPalette::Background]];}
a img {border:0;}

h1,h2,h3,h4,h5,h6 {color:[[ColorPalette::SecondaryDark]]; background:transparent;}
h1 {border-bottom:2px solid [[ColorPalette::TertiaryLight]];}
h2,h3 {border-bottom:1px solid [[ColorPalette::TertiaryLight]];}

.button {color:[[ColorPalette::PrimaryDark]]; border:1px solid [[ColorPalette::Background]];}
.button:hover {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::SecondaryLight]]; border-color:[[ColorPalette::SecondaryMid]];}
.button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::SecondaryDark]];}

.header {background:[[ColorPalette::PrimaryMid]];}
.headerShadow {color:[[ColorPalette::Foreground]];}
.headerShadow a {font-weight:normal; color:[[ColorPalette::Foreground]];}
.headerForeground {color:[[ColorPalette::Background]];}
.headerForeground a {font-weight:normal; color:[[ColorPalette::PrimaryPale]];}

.tabSelected{color:[[ColorPalette::PrimaryDark]];
	background:[[ColorPalette::TertiaryPale]];
	border-left:1px solid [[ColorPalette::TertiaryLight]];
	border-top:1px solid [[ColorPalette::TertiaryLight]];
	border-right:1px solid [[ColorPalette::TertiaryLight]];
}
.tabUnselected {color:[[ColorPalette::Background]]; background:[[ColorPalette::TertiaryMid]];}
.tabContents {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::TertiaryPale]]; border:1px solid [[ColorPalette::TertiaryLight]];}
.tabContents .button {border:0;}

#sidebar {}
#sidebarOptions input {border:1px solid [[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel {background:[[ColorPalette::PrimaryPale]];}
#sidebarOptions .sliderPanel a {border:none;color:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:hover {color:[[ColorPalette::Background]]; background:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:active {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]];}

.wizard {background:[[ColorPalette::PrimaryPale]]; border:1px solid [[ColorPalette::PrimaryMid]];}
.wizard h1 {color:[[ColorPalette::PrimaryDark]]; border:none;}
.wizard h2 {color:[[ColorPalette::Foreground]]; border:none;}
.wizardStep {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];
	border:1px solid [[ColorPalette::PrimaryMid]];}
.wizardStep.wizardStepDone {background:[[ColorPalette::TertiaryLight]];}
.wizardFooter {background:[[ColorPalette::PrimaryPale]];}
.wizardFooter .status {background:[[ColorPalette::PrimaryDark]]; color:[[ColorPalette::Background]];}
.wizard .button {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryLight]]; border: 1px solid;
	border-color:[[ColorPalette::SecondaryPale]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryPale]];}
.wizard .button:hover {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Background]];}
.wizard .button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::Foreground]]; border: 1px solid;
	border-color:[[ColorPalette::PrimaryDark]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryDark]];}

#messageArea {border:1px solid [[ColorPalette::SecondaryMid]]; background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]];}
#messageArea .button {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::SecondaryPale]]; border:none;}

.popupTiddler {background:[[ColorPalette::TertiaryPale]]; border:2px solid [[ColorPalette::TertiaryMid]];}

.popup {background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]]; border-left:1px solid [[ColorPalette::TertiaryMid]]; border-top:1px solid [[ColorPalette::TertiaryMid]]; border-right:2px solid [[ColorPalette::TertiaryDark]]; border-bottom:2px solid [[ColorPalette::TertiaryDark]];}
.popup hr {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::PrimaryDark]]; border-bottom:1px;}
.popup li.disabled {color:[[ColorPalette::TertiaryMid]];}
.popup li a, .popup li a:visited {color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:active {background:[[ColorPalette::SecondaryPale]]; color:[[ColorPalette::Foreground]]; border: none;}
.popupHighlight {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
.listBreak div {border-bottom:1px solid [[ColorPalette::TertiaryDark]];}

.tiddler .defaultCommand {font-weight:bold;}

.shadow .title {color:[[ColorPalette::TertiaryDark]];}

.title {color:[[ColorPalette::SecondaryDark]];}
.subtitle {color:[[ColorPalette::TertiaryDark]];}

.toolbar {color:[[ColorPalette::PrimaryMid]];}
.toolbar a {color:[[ColorPalette::TertiaryLight]];}
.selected .toolbar a {color:[[ColorPalette::TertiaryMid]];}
.selected .toolbar a:hover {color:[[ColorPalette::Foreground]];}

.tagging, .tagged {border:1px solid [[ColorPalette::TertiaryPale]]; background-color:[[ColorPalette::TertiaryPale]];}
.selected .tagging, .selected .tagged {background-color:[[ColorPalette::TertiaryLight]]; border:1px solid [[ColorPalette::TertiaryMid]];}
.tagging .listTitle, .tagged .listTitle {color:[[ColorPalette::PrimaryDark]];}
.tagging .button, .tagged .button {border:none;}

.footer {color:[[ColorPalette::TertiaryLight]];}
.selected .footer {color:[[ColorPalette::TertiaryMid]];}

.sparkline {background:[[ColorPalette::PrimaryPale]]; border:0;}
.sparktick {background:[[ColorPalette::PrimaryDark]];}

.error, .errorButton {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Error]];}
.warning {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryPale]];}
.lowlight {background:[[ColorPalette::TertiaryLight]];}

.zoomer {background:none; color:[[ColorPalette::TertiaryMid]]; border:3px solid [[ColorPalette::TertiaryMid]];}

.imageLink, #displayArea .imageLink {background:transparent;}

.annotation {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border:2px solid [[ColorPalette::SecondaryMid]];}

.viewer .listTitle {list-style-type:none; margin-left:-2em;}
.viewer .button {border:1px solid [[ColorPalette::SecondaryMid]];}
.viewer blockquote {border-left:3px solid [[ColorPalette::TertiaryDark]];}

.viewer table, table.twtable {border:2px solid [[ColorPalette::TertiaryDark]];}
.viewer th, .viewer thead td, .twtable th, .twtable thead td {background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::Background]];}
.viewer td, .viewer tr, .twtable td, .twtable tr {border:1px solid [[ColorPalette::TertiaryDark]];}

.viewer pre {border:1px solid [[ColorPalette::SecondaryLight]]; background:[[ColorPalette::SecondaryPale]];}
.viewer code {color:[[ColorPalette::SecondaryDark]];}
.viewer hr {border:0; border-top:dashed 1px [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::TertiaryDark]];}

.highlight, .marked {background:[[ColorPalette::SecondaryLight]];}

.editor input {border:1px solid [[ColorPalette::PrimaryMid]];}
.editor textarea {border:1px solid [[ColorPalette::PrimaryMid]]; width:100%;}
.editorFooter {color:[[ColorPalette::TertiaryMid]];}

#backstageArea {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::TertiaryMid]];}
#backstageArea a {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstageArea a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }
#backstageArea a.backstageSelTab {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
#backstageButton a {background:none; color:[[ColorPalette::Background]]; border:none;}
#backstageButton a:hover {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstagePanel {background:[[ColorPalette::Background]]; border-color: [[ColorPalette::Background]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]];}
.backstagePanelFooter .button {border:none; color:[[ColorPalette::Background]];}
.backstagePanelFooter .button:hover {color:[[ColorPalette::Foreground]];}
#backstageCloak {background:[[ColorPalette::Foreground]]; opacity:0.6; filter:'alpha(opacity:60)';}
/*}}}*/
/*{{{*/
* html .tiddler {height:1%;}

body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;}

h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
h4,h5,h6 {margin-top:1em;}
h1 {font-size:1.35em;}
h2 {font-size:1.25em;}
h3 {font-size:1.1em;}
h4 {font-size:1em;}
h5 {font-size:.9em;}

hr {height:1px;}

a {text-decoration:none;}

dt {font-weight:bold;}

ol {list-style-type:decimal;}
ol ol {list-style-type:lower-alpha;}
ol ol ol {list-style-type:lower-roman;}
ol ol ol ol {list-style-type:decimal;}
ol ol ol ol ol {list-style-type:lower-alpha;}
ol ol ol ol ol ol {list-style-type:lower-roman;}
ol ol ol ol ol ol ol {list-style-type:decimal;}

.txtOptionInput {width:11em;}

#contentWrapper .chkOptionInput {border:0;}

.externalLink {text-decoration:underline;}

.indent {margin-left:3em;}
.outdent {margin-left:3em; text-indent:-3em;}
code.escaped {white-space:nowrap;}

.tiddlyLinkExisting {font-weight:bold;}
.tiddlyLinkNonExisting {font-style:italic;}

/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
a.tiddlyLinkNonExisting.shadow {font-weight:bold;}

#mainMenu .tiddlyLinkExisting,
	#mainMenu .tiddlyLinkNonExisting,
	#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}

.header {position:relative;}
.header a:hover {background:transparent;}
.headerShadow {position:relative; padding:4.5em 0em 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:4.5em 0em 1em 1em; left:0px; top:0px;}

.siteTitle {font-size:3em;}
.siteSubtitle {font-size:1.2em;}

#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}

#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
#sidebarOptions {padding-top:0.3em;}
#sidebarOptions a {margin:0em 0.2em; padding:0.2em 0.3em; display:block;}
#sidebarOptions input {margin:0.4em 0.5em;}
#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
#sidebarOptions .sliderPanel input {margin:0 0 .3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}

.wizard {padding:0.1em 1em 0em 2em;}
.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;}
.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;}
.wizardStep {padding:1em 1em 1em 1em;}
.wizard .button {margin:0.5em 0em 0em 0em; font-size:1.2em;}
.wizardFooter {padding:0.8em 0.4em 0.8em 0em;}
.wizardFooter .status {padding:0em 0.4em 0em 0.4em; margin-left:1em;}
.wizard .button {padding:0.1em 0.2em 0.1em 0.2em;}

#messageArea {position:fixed; top:2em; right:0em; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;}
.messageToolbar {display:block; text-align:right; padding:0.2em 0.2em 0.2em 0.2em;}
#messageArea a {text-decoration:underline;}

.tiddlerPopupButton {padding:0.2em 0.2em 0.2em 0.2em;}
.popupTiddler {position: absolute; z-index:300; padding:1em 1em 1em 1em; margin:0;}

.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;}
.popup .popupMessage {padding:0.4em;}
.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0em;}
.popup li.disabled {padding:0.4em;}
.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;}
.listBreak {font-size:1px; line-height:1px;}
.listBreak div {margin:2px 0;}

.tabset {padding:1em 0em 0em 0.5em;}
.tab {margin:0em 0em 0em 0.25em; padding:2px;}
.tabContents {padding:0.5em;}
.tabContents ul, .tabContents ol {margin:0; padding:0;}
.txtMainTab .tabContents li {list-style:none;}
.tabContents li.listLink { margin-left:.75em;}

#contentWrapper {display:block;}
#splashScreen {display:none;}

#displayArea {margin:1em 17em 0em 14em;}

.toolbar {text-align:right; font-size:.9em;}

.tiddler {padding:1em 1em 0em 1em;}

.missing .viewer,.missing .title {font-style:italic;}

.title {font-size:1.6em; font-weight:bold;}

.missing .subtitle {display:none;}
.subtitle {font-size:1.1em;}

.tiddler .button {padding:0.2em 0.4em;}

.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
.isTag .tagging {display:block;}
.tagged {margin:0.5em; float:right;}
.tagging, .tagged {font-size:0.9em; padding:0.25em;}
.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
.tagClear {clear:both;}

.footer {font-size:.9em;}
.footer li {display:inline;}

.annotation {padding:0.5em; margin:0.5em;}

* html .viewer pre {width:99%; padding:0 0 1em 0;}
.viewer {line-height:1.4em; padding-top:0.5em;}
.viewer .button {margin:0em 0.25em; padding:0em 0.25em;}
.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}

.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;}
.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;}
table.listView {font-size:0.85em; margin:0.8em 1.0em;}
table.listView th, table.listView td, table.listView tr {padding:0px 3px 0px 3px;}

.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;}
.viewer code {font-size:1.2em; line-height:1.4em;}

.editor {font-size:1.1em;}
.editor input, .editor textarea {display:block; width:100%; font:inherit;}
.editorFooter {padding:0.25em 0em; font-size:.9em;}
.editorFooter .button {padding-top:0px; padding-bottom:0px;}

.fieldsetFix {border:0; padding:0; margin:1px 0px 1px 0px;}

.sparkline {line-height:1em;}
.sparktick {outline:0;}

.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
.zoomer div {padding:1em;}

* html #backstage {width:99%;}
* html #backstageArea {width:99%;}
#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em 0.3em 0.5em;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em 0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0em; right:0em;}
#backstageButton a {padding:0.1em 0.4em 0.1em 0.4em; margin:0.1em 0.1em 0.1em 0.1em;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel {display:none; z-index:100; position:absolute; margin:0em 3em 0em 3em; padding:1em 1em 1em 1em;}
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding:0.2em 0.4em 0.2em 0.4em;}
#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}

.whenBackstage {display:none;}
.backstageVisible .whenBackstage {display:block;}
/*}}}*/
/***
StyleSheet for use when a translation requires any css style changes.
This StyleSheet can be used directly by languages such as Chinese, Japanese and Korean which need larger font sizes.
***/
/*{{{*/
body {font-size:0.8em;}
#sidebarOptions {font-size:1.05em;}
#sidebarOptions a {font-style:normal;}
#sidebarOptions .sliderPanel {font-size:0.95em;}
.subtitle {font-size:0.8em;}
.viewer table.listView {font-size:0.95em;}
/*}}}*/
/*{{{*/
@media print {
#mainMenu, #sidebar, #messageArea, .toolbar, #backstageButton, #backstageArea {display: none ! important;}
#displayArea {margin: 1em 1em 0em 1em;}
/* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
noscript {display:none;}
}
/*}}}*/
<!--{{{-->
<div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<div class='headerShadow'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;

<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div class='headerForeground'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>

<div id='mainMenu' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>

<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='title' macro='view title'></div>

<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>

<div class='tagged' macro='tags'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
<!--{{{-->
<div class='toolbar' macro='toolbar +saveTiddler -cancelTiddler deleteTiddler'></div>

<div class='title' macro='view title'></div>
<div class='editor' macro='edit title'></div>
<div macro='annotations'></div>
<div class='editor' macro='edit text'></div>
<div class='editor' macro='edit tags'></div><div class='editorFooter'><span macro='message views.editor.tagPrompt'></span><span macro='tagChooser'></span></div>

<!--}}}-->
To get started with this blank TiddlyWiki, you'll need to modify the following tiddlers:
* SiteTitle & SiteSubtitle: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
* MainMenu: The menu (usually on the left)
* DefaultTiddlers: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
You'll also need to enter your username for signing your edits: <<option txtUserName>>
These InterfaceOptions for customising TiddlyWiki are saved in your browser

Your username for signing your edits. Write it as a WikiWord (eg JoeBloggs)

<<option txtUserName>>
<<option chkSaveBackups>> SaveBackups

<<option chkAutoSave>> AutoSave
<<option chkRegExpSearch>> RegExpSearch
<<option chkCaseSensitiveSearch>> CaseSensitiveSearch
<<option chkAnimate>> EnableAnimations

----
Also see AdvancedOptions
<<importTiddlers>>
|''Type:''|file|
|''URL:''|http://mptw.tiddlyspot.com|
|''Workspace:''|(default)|

This tiddler was automatically created to record the details of this server
|''Type:''|file|
|''URL:''|http://tiddlywiki.bidix.info|
|''Workspace:''|(default)|

This tiddler was automatically created to record the details of this server
|''Type:''|file|
|''URL:''|http://tw.lewcid.org|
|''Workspace:''|(default)|

This tiddler was automatically created to record the details of this server
|''Type:''|file|
|''URL:''|http://www.tiddlytools.com|
|''Workspace:''|(default)|

This tiddler was automatically created to record the details of this server
{{tableindex{
|[[Test1]]|[[Test2]]|[[subtopic3]]|
}}}
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='01macro='tiddler 01subtopicMenu'></div><div class='title' macro='view title'></div>

<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>
<!--}}}-->
!Some Basic Commands:
Once you have R running, here are the basic commands to open a data file. We are using the Wind Tower data "set1" for this example. Get the data from: WindData.

|!Command |!Comment |
|getwd() |returns your working directory |
|setwd("C:/..........")|sets your working directory |
|fnames <- dir(pattern = ".txt") |  create object "fnames" with a list of txt files in cwd |
|length(fname) | returns the number of txt files in fname |
|d <- read.table(fname[1], header = TRUE, sep = "\t") |input txt file #1 |
|dim(d) |returns the matrix dimensions of d, n rows x m cols |
|summary(d) |returns the variables (cols) in "d" |
|plot(d[,2], d[,3]) |plotting column 2 of d vs. column 3 of d |

''Sample Script''
{{{
fnames=dir(pattern=".txt")
length(fnames)
d <- read.table(fnames[1], header=TRUE, sep="\t")
dim(d)
summary(d)
# Generate a basic xy plot . . . . 
      plot(d[,2],d[,3],main="Wind Data",xlab="CH1-average",ylab="CH1-sd")
# Create linear vector from 1 to 144 as a proxy for observation time . . . . 
      time<-c(1:144)
# Now plot CH1 average wind speed against that time vector . . . . . 
      plot(time,d[,2],main="Wind Data",xlab="Time Interval (10 min.)",ylab="Average Wind Speed")
}}}
''OUTPUT:''

<html><img src="0606/windplot01.png" style="height:300px"></html>

!!
{{tableindex{
|[[Intro-0815]]|[[Data-0815]]|[[Transform-0815]]|[[ANOVA-0815]]|[[BlockAnova-0815]]|[[Tukey-0815]]|
}}}
<!--{{{-->

<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='0808' macro='tiddler 0808SubtopicMenu'></div><div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>
<!--}}}-->

{{tableindex{
|[[Intro-0909]]|[[Data-080909]]|[[PlotCode-080909]]|[[Plots-080909]]|
}}}
<!--{{{-->

<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='080909' macro='tiddler 080909SubtopicMenu'></div><div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>
<!--}}}-->

!Basic Plotting Commands:
# Get the merged wind data set: 
** __Disclaimer:__ //The wind tower data is @@confidential@@ and not for public distribution or comment.//
** option 1: [[download|0613/wind_data_ex.txt]]
** option 2: just include the url in the //read.table// command:
*** d <- read.table("http://icewater.cms.udel.edu/Rgroup/0613/wind_data_ex.txt", header = TRUE, sep = "\t") 
# Plot 1 [[basic xy plot|plot0613-01]]
# Plot 2 [[basic plot with labels|plot0613-02]]
# Plot 3 [[basic plot with lines|plot0613-03]]
# Plot 4 [[basic plot lines and points|plot0613-04]]
# Plot 5 [[basic plot lines and points in blue|plot0613-05]]
# Plot 6 [[basic plot lines and points in red with new symbols|plot0613-06]]
# Plot 7 [[symbol and color option codes|plot0613-07]]
# Plot 8 [[adding plot lines and text to existing plots|plot0613-08]]
# Plot 9 [[basic histogram|plot0613-09]]
# Plot 10 [[basic histogram with labels|plot0613-10]]
# Plot 11 [[basic histogram with labels with increasing the number of bins|plot0613-11]]
# Plot 12 [[basic histogram with labels with specifying the break points|plot0613-12]]
# Plot 13 [[basic histogram with labels with alternating colors|plot0613-13]]

!Basic Plotting with "ggplot2":
//Using the sample data above, the power (and complexity) of plotting in R can be seen in a simple [[ggplot2]] script. Most of the script just performs the necessary data re-organization.//

First step is to install the ggplot2 package on your computer:
{{{
install.packages("ggplot2")
}}}
15. Plot 14 [[ggplot wind data|plot0613-14]]
 
!!

! ''{{green{Data manipulation & description}}}'' for 20 and 27 June
! Basics
# Get ready:  @@d <- read.table("http://www.ocean.udel.edu/cms/dmiller/Rgroup/0613/wind_data_ex.txt", header = TRUE, sep = "\t")@@
# What will this do? @@d[1, ]@@ And this: @@d[1:5, c(1,3,5,7,9)]@@
# Now try: @@summary(d)@@
! Everything in R is an object
# Objects have //properties//: @@class(d)@@, @@attributes(d)@@, @@is.data.frame(d)@@, ...
# Objects have //methods//: @@summary(d)@@, @@methods(class="data.frame")@@, plot, ...
# Create lists, vectors, matrices (and arrays), //data frames//, //factors//, ...
# Query their properties: names, rownames, dimnames, nrow, ncol, length, dim, ...
! Questions?
#Try above functions on wind data set
! Accessing data
# Most often data will be in a //data frame//, with columns as variables and rows as observations
# Access values using //dataframe$variablename// notation: @@d$Seq_time[1:10]@@
# Or @@attach(d)@@, then use variable name directly: @@Seq_time[1:10]@@. Remember to @@detach(d)@@ when done.
# Or: @@d[1:10,"Seq_time"]@@. Try: @@d[1:10,c("Seq_time","CH1Avg")]@@ or even: @@d[1:10,c("Seq_time","CH1Avg", "CH2Avg","CH3Avg","CH4Avg","CH5Avg","CH6Avg")]@@
! Manipulating data
# Start with: @@dd=d[ 1:10, ]@@
# Extracting by //indexing//, including logical subscripting
** Work iteratively: @@dd[,"CH10Max"]@@, @@dd[,"CH10Max"]<nowiki>==</nowiki>10@@, so: @@dd[dd[,"CH10Max"]<nowiki>==</nowiki>10,]@@
** Logical operators: (type @@help("!")@@, //regular expressions// for pattern matching, see @@help.search("regular expressions")@@ and @@help("regex")@@
** Functions: subset, is.element , which, any, ...  @@subset(dd,hr<nowiki>==</nowiki>1,select=c(mo,dy,hr,mn))@@
# Removing rows or columns:
** Negative indices mean everything except: @@summary(d)@@, then @@names(d)@@, finally @@dd=d[ 1:10,-(54:57)]@@; try @@dd=dd[,-(8:9)]@@
# Adding rows or columns:
** Indexing: @@dd[11,]=99@@ or @@dd[,"newcol"]=99@@
** Whole rows or columns: rbind stacks frames vertically, and cbind adds columns of same length
# Recoding or transformations: @@dd[dd$CH10Max<nowiki>==</nowiki>10,"CH10Max" ]= 99@@ or @@dd[,"CH10Max"]=dd[,"CH10Max"]*2@@
# Sorting: //sort, order, sort.list//: @@dd[order(dd$mn),]@@
# Random selections: @@sample(10)@@, @@sample(100)[1:10]@@, so ... @@dd[sample(1:nrow(dd),4),]@@
# Grouping and aggregating: @@aggregate(dd[,8:9],by=list(dd$mn),median)@@ and change by= and function arguments
# Summing, averaging, et cetera, @@apply(dd,1,sum)@@ versus @@apply(dd,2,sum)@@, ... and see below
# Leftovers: //melt and cast, capply and tapply, cut, table, splitting and merging// and much, much more ...
# Missing and special values: NA, NaN, Inf and -Inf
**Use is.na to test (can be a bit tricky)
** Removing observations "pairwise" (i.e., only variables involved): @@dd[3,5]=NA@@, @@dd[is.na(dd$hr),]@@, @@dd[!is.na(dd$hr),]@@
** Removing observations with NA's casewise (=listwise) if any are missing: //for group discussion and homework exercise//
(Hint: complete.cases(dd), so how to list rows with NA? How to retain only rows with all values? See also na.omit)
! Questions and other examples?
# Note: Watch your attach(//data.frame//) and detach(//data.frame//) with ls, objects, search and rm
! Working with factors, building on ggplot2 example from last week ...
{{{
# Code from last week's ggplot example ...
library("ggplot2")
data_url <- c("http://www.ocean.udel.edu/cms/dmiller/Rgroup/0613/wind_data_ex.txt") 
d <- read.table(data_url, header=TRUE, sep="\t")
WindSpeedAvg <- d[,c(1,10,14,18,22,26,30)]
}}}
OK? @@summary(WindSpeedAvg)@@
{{{
mWS <- melt(WindSpeedAvg, id=c(1))
summary(mWS)
is.data.frame(mWS)
names(mWS)
names(mWS)=c("Seq_time","anem","windspeed")
}}}
Check: @@class(mWS$anem)@@ and @@levels(mWS$anem)@@
{{{
attach(mWS)
boxplot(windspeed~anem)
detach(mWS)

clipped=mWS[mWS$windspeed<12,]
summary(clipped)
boxplot(clipped$windspeed~clipped$anem) # or boxplot(windspeed~anem, data=clipped)
}}}
! Data description/stats
# "Plot your data //first//."

** @@stem(d$CH1Avg)@@, @@hist(d$CH1Avg)@@
{{{
hist(d$CH1Avg,prob=T)
lines(density(d$CH1Avg,bw=0.5))
rug(d$CH1Avg)
}}}
** @@qqnorm(d$CH1Avg)@@, @@qqline(d$CH1Avg)@@
# Basic descriptive stats
** mean, median, range, sum, var and sd, ...
** Counts: @@sum(mWS$anem<nowiki>==</nowiki>"CH1Avg" & mWS$windspeed<=5.13)@@
{{{
sc=cut(mWS[,"windspeed"],5)
table(mWS[,"anem"],sc)
}}}
# Basic stats tests
** t: @@test.data=dd[,"CH10Max"]@@ then @@t.test(test.data,mu=10)@@ or  @@t.test(dd[,"CH10Max"],dd[,"CH10Min"], paired=T)@@
** anova: @@table=aov(mWS$windspeed~mWS$anem)@@ then @@summary(table)@@
! All together now? 
# //Test for differences between anemometers two ways?//
# Two-sample t test: @@t.test(WindSpeedAvg$CH1Avg,WindSpeedAvg$CH5Avg,var.equal=T)@@
# Rearrange the data (given results of melt, above): 
{{{
attach(mWS)
keep=is.element(anem,c("CH1Avg","CH5Avg"))
one.vs.five=mWS[keep,]
nrow(one.vs.five)
detach()
}}}
Now for the anova: @@attach(one.vs.five)@@, @@summary(aov(windspeed~anem))@@, finally @@detach()@@

# //Same overall mean speeds obtained two different ways?//
# @@apply(WindSpeedAvg,2,mean)@@
# @@tapply(mWS[,"windspeed"],mWS$anem,mean)@@

//Are the results the same?//

! Quick-R web site has good, simple examples of R code for statistical workflows
See especially the [[Data Input|http://www.statmethods.net/input/index.html]] and [[Data Management|http://www.statmethods.net/management/index.html]] pages

! More?
Useful R functions at a glance on this [[R Reference card| http://cran.r-project.org/doc/contrib/refcard.pdf]] by Jonathan Baron
Exercise-based tutorial in [[Practice with R|http://wwwmaths.anu.edu.au/~johnm/courses/dm/rintro/r-tutorials.pdf]] by John Maindonald
More learning materials in [[Contributed Documentation|http://cran.r-project.org/other-docs.html]] at the CRAN site

! What do //you// want to see next?
# Stats basic or advanced?
# Reprise input/output, data manipulation, graphics and advanced graphics?

! Take home messages:
# Work iteratively and incrementally, in baby steps
# Corollary: Use temporary variables, multiple lines of code at first
# Start with the simple, then, slowly, make it complicated (and realistic)
# Often easiest to try something rather than think too hard about it or to look it up
# There are many ways to do something, be sure to arrive at one that works
# Learn from good code examples, but don't expect to write them (yet)
# The //object-ness// of R is key
# The "vibe of R" will come with practice
!
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='AAuse' macro='tiddler AAuseSubtopicMenu'></div><div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>

<!--}}}-->
!!~ONE-WAY ANOVA: Culture
{{{
> summary(aovout <- aov(DevoRate ~ Culture, M))
                  Df       Sum Sq      Mean Sq     F value    Pr(>F)    
Culture         6      0.047099     0.007850    17.346      < 2.2e-16 ***
Residuals   252     0.114044     0.000453                      
}}}

!!~ONE-WAY ANOVA: cult
{{{
> summary(aovout <- aov(DevoRate ~ cult, M))
                    Df       Sum Sq      Mean Sq     F value    Pr(>F)    
cult               3       0.041133     0.013711    29.133     3.131e-16 ***
Residuals   255       0.120010     0.000471 
}}}

!!~ONE-WAY BLOCK ANOVA: cult+rep
{{{
> summary(aovout <- aov(DevoRate ~ cult+plate, M))
                   Df       Sum Sq      Mean Sq     F value    Pr(>F)    
cult               3      0.041133     0.013711    29.8498    < 2.2e-16 ***
rep                1      0.003340     0.003340    7.2712      0.007475 ** 
Residuals   254      0.116670     0.000459                      
}}}

!!~TWO-WAY ANOVA: cult*rep
{{{
> summary(aovout <- aov(DevoRate ~ cult*plate, M))
                    Df       Sum Sq      Mean Sq     F value    Pr(>F)    
cult               3       0.041133     0.013711    30.2967    < 2.2e-16 ***
rep                1       0.003340     0.003340      7.3801     0.007052 ** 
cult:rep         2       0.002626     0.001313      2.9013     0.056789 .  
Residuals   252        0.114044     0.000453                                           
}}}


!
!
!!Boxplot
1. Simple boxplot: BoxPlot-agm
<html><img src="am/080604-PhyloMethylationBoxPlots.png" style="height:150px"></html>
!!
2. Black and White publication figures: BWplots-agm
<html><img src="am/080911-Fig6B.png" style="height:150px"><img src="am/080911-Fig6A.png" style="height:150px"></html>
!!


/***
|''Name:''|AnnotationsPlugin|
|''Description:''|Inline annotations for tiddler text.|
|''Author:''|Saq Imtiaz ( lewcid@gmail.com )|
|''Source:''|http://tw.lewcid.org/#AnnotationsPlugin|
|''Code Repository:''|http://tw.lewcid.org/svn/plugins|
|''Version:''|2.0|
|''Date:''||
|''License:''|[[Creative Commons Attribution-ShareAlike 3.0 License|http://creativecommons.org/licenses/by-sa/3.0/]]|
|''~CoreVersion:''|2.2.3|

!!Usage:
*{{{((text to annotate(annotation goes here)}}}
* To include the text being annotated, in the popup as a title, put {{{^}}} as the first letter of the annotation text.
** {{{((text to annotate(^annotation goes here)}}}

!!Examples:
Mouse over, the text below:
* ((banana(the best fruit in the world)))
* ((banana(^ the best fruit in the world)))

***/
// /%
config.formatters.unshift({name:"annotations",match:"\\(\\(",lookaheadRegExp:/\(\((.*?)\((\^?)((?:.|\n)*?)\)\)\)/g,handler:function(w){
this.lookaheadRegExp.lastIndex=w.matchStart;
var _2=this.lookaheadRegExp.exec(w.source);
if(_2&&_2.index==w.matchStart){
var _3=createTiddlyElement(w.output,"span",null,"annosub",_2[1]);
_3.anno=_2[3];
if(_2[2]){
_3.subject=_2[1];
}
_3.onmouseover=this.onmouseover;
_3.onmouseout=this.onmouseout;
_3.ondblclick=this.onmouseout;
w.nextMatch=_2.index+_2[0].length;
}
},onmouseover:function(e){
popup=createTiddlyElement(document.body,"div",null,"anno");
this.popup=popup;
if(this.subject){
wikify("!"+this.subject+"\n",popup);
}
wikify(this.anno,popup);
addClass(this,"annosubover");
Popup.place(this,popup,{x:25,y:7});
},onmouseout:function(e){
removeNode(this.popup);
this.popup=null;
removeClass(this,"annosubover");
}});
setStylesheet(".anno{position:absolute;border:2px solid #000;background-color:#DFDFFF; color:#000;padding:0.5em;max-width:15em;width:expression(document.body.clientWidth > (255/12) *parseInt(document.body.currentStyle.fontSize)?'15em':'auto' );}\n"+".anno h1, .anno h2{margin-top:0;color:#000;}\n"+".annosub{background:#ccc;}\n"+".annosubover{z-index:25; background-color:#DFDFFF;cursor:help;}\n","AnnotationStyles");


// %/
!
[[BACK to ADAM's Index|Adam]]
!!
!!BW Boxplot
"ggplot2" allows for THEMES to be added to plots as a separate layer. There is a theme for black and white publication figures called "theme_bw"
<html><img src="am/080911-Fig6A.png" style="height:300px"></html>
{{{
# boxplot - - - - - - - - - - - - - - - - - - - - 
p<-NULL
theme_bw$grid.colour="white"
p <-ggplot(data=D, aes(y=OBS,x=GRP)) +
	geom_boxplot(aes(fill=mOsm), colour="black", size=2) +
	scale_fill_grey(end=0.6) + 
	scale_y_continuous("Ratio Value") +
	scale_x_discrete("") +
	theme_bw
p$legend.position <- c(0.3,0.9)
p
grid.gedit("label", gp=gpar(fontsize=12, col="black"))
grid.gedit("ylabel", gp=gpar(fontsize=16, col="black"))
grid.gedit("xlabel", gp=gpar(fontsize=16, col="black"))
grid.gedit(gPath("xaxis","label"), gp=gpar(fontsize=18, col="black"))
}}}

!!BW XY plot with linear regression:
The black outline on points was achieved by double-plotting the data set, first in size 5 black circles and then with size 4 fill-color circles, which leaves a black edge visible.
<html><img src="am/080911-Fig6B.png" style="height:300px"></html>
{{{
p <-ggplot(data=d, aes(y=PO,x=RCR)) +
	geom_point(colour="black",size=5) +
	geom_point(aes(colour=mOsm),size=3) +
	stat_smooth(method="lm") +
	scale_colour_grey(end=0.6) + 
	scale_x_continuous("Respiratory Control Ratio") +
	scale_y_continuous("ADP:O") +
	theme_bw 
p$legend.position<-c(0.3,0.9)
p
grid.gedit("label", gp=gpar(fontsize=12, col="black"))
grid.gedit("ylabel", gp=gpar(fontsize=16, col="black"))
grid.gedit("xlabel", gp=gpar(fontsize=16, col="black"))
}}}
!!~ONE-WAY BLOCK ANOVA: cult+rep
{{{
> summary(aovout <- aov(DevoRate ~ cult+plate, M))
                   Df       Sum Sq      Mean Sq     F value    Pr(>F)    
cult               3      0.041133     0.013711    29.8498    < 2.2e-16 ***
rep                1      0.003340     0.003340    7.2712      0.007475 ** 
Residuals   254      0.116670     0.000459                      
}}}

<html><img src="0808/01boxplot2.png" style="height:400px"></html>

!!ANOVA PLOTS:
{{{
plot(aovout)
}}}
<html>
<img src="0808/anova1.png" style="height:400px"><br>
<img src="0808/anova2.png" style="height:400px"><br>
<img src="0808/anova3.png" style="height:400px"><br>
<img src="0808/anova4.png" style="height:400px">
</html>
!
!
[[BACK to ADAM's Index|Adam]]
!!
!!Boxplot
''Data from L.Kendall for genome methylation levels of different marine invertebrates.''
<html>
<img src="am/080604-PhyloMethylationBoxPlots.png" style="height:300px">
</html>
{{{
# import dataframe - - - - - - - - - - - - - - - - - - - - 
d=read.table('PhylumMethylation-LRK.txt', sep='\t', header=T)

# data setup . . . . . . . . 
m=melt(d)
names(m) <- c("phylum","methylation")
m$phylum <- as.factor(m$phylum)
D <- m[ which(m$methylation > '0'), ]

# boxplot - - - - - - - - - - - - - - - - - - - - 
ggopt(legend.position="none")
p <- ggplot(data=D, aes(y=methylation,x=phylum))
p + geom_boxplot(aes(fill=phylum), colour="black", outlier.colour="green", outlier.size=3) + scale_y_continuous("% Genome Methylation") 

# edit font size and font color of all labels . . . . 
grid.gedit("label", gp=gpar(fontsize=12, col="black"))
grid.gedit("ylabel", gp=gpar(fontsize=16, col="black"))
grid.gedit("xlabel", gp=gpar(fontsize=16, col="white"))
grid.gedit(gPath("xaxis","label"), gp=gpar(fontsize=18))

# list the GRID objects in the plot
grid.ls(grobs=TRUE)

}}}
!


! A reverse chronological listing:
Listed below are the notes or outlines of the meetings that we have held.
!!!

<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>Tuesday, 09 SEP:</html>''Next group meeting at 1000h; Cannon 202''
* Plotting with ggplot2 aesthetics options
* Summary of scripts and plots: [[Intro-0822]] 
!!!
<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>Friday, 15 AUG:</html>''Next group meeting at 1200h; Cannon 202''
* Data "melting"
* ANOVA
* Summary of scripts and plots: [[Intro-0815]]
!!!
<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>R Group Vacation = July:</html>''No meetings are scheduled for this month. We'll wait until August when we are all getting back onto a semester schedule to resume the weekly meeting.''
!!!
<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>Friday, 20 JUNE:</html>''Next group meeting at 1200h; Cannon 202''
* Data Manipulation
* Descriptive Statistics
* Summary of scripts and plots: [[20JUNE]]
!!!
<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>Friday, 13 JUNE:</html>''Next group meeting at 1200h; Cannon 202''
* Introduction to plot commands
* Quick look at the ggplot2 package
* Summary of scripts and plots: [[13JUNE]]
!!!

<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>Friday, 06 JUNE:</html>''Meeting Outline:''
* Install R
* Overview a few basic R commands
* Load Wind data set 1
* Summary of the R commands and script: [[06JUNE]]
!!!
<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>Wednesday, 28 MAY:</html>''Organizational Meeting''
!!!
Peter Cock at the Bioinformatics Program at Warwick University has some very good examples and scripts integrating with R and Python
[[URL LINK|http://www2.warwick.ac.uk/fac/sci/moac/currentstudents/peter_cock/r/]]
<html><img src="00/cock-page.png" style="height:350px"></html>
!!!
Background: #fff
Foreground: #000
PrimaryPale: #ddeeaa
PrimaryLight: #ddeeaa
PrimaryMid: #666633
PrimaryDark: #014
SecondaryPale: #bbdd88
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #666633
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #aacc88
Error: #f88
# Group ENTRIES by a common tag, 'xxxx'.
# Create subtopic menu:
** rename as ''//xxxx//SubtopicMenu''
** enter the ENTRY titles into the table cells
# Create the viewtemplate
** rename as ''//xxxx//ViewTemplate''
** edit this line in the body, to this syntax using the 'xxxx' tag name:
{{{
<class='xxxx' macro='tiddler xxxxSubtopicMenu'>
}}}
!!SUBTOPIC PAGE CONTENT
{{{
<html>
<div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>
TITLE OR HEADER OR DESCRIPTOR . . . .. 
</html>
1. [[x |1.11]]
2. [[y |1.12]]
3. [[z |1.13]]
!!
}}}
!!PLOT PAGE CONTENT
{{{
//header title//

<html><img src="00/xxxx.png" style="height:400px"></html>
[[BACK|XXTAGNAMEXX]]
!!!
}}}
!!
!!
[img[00/00-anim-codingpain.gif]]
''Dr. Adam G. Marsh''
645.4367
amarsh@udel.edu
!!
/***
|''Name:''|CryptoFunctionsPlugin|
|''Description:''|Support for cryptographic functions|
***/
//{{{
if(!version.extensions.CryptoFunctionsPlugin) {
version.extensions.CryptoFunctionsPlugin = {installed:true};

//--
//-- Crypto functions and associated conversion routines
//--

// Crypto "namespace"

function Crypto() {}

// Convert a string to an array of big-endian 32-bit words
Crypto.strToBe32s = function(str)
{
	var be = Array();
	var len = Math.floor(str.length/4);
	var i, j;
	for(i=0, j=0; i<len; i++, j+=4) {
		be[i] = ((str.charCodeAt(j)&0xff) << 24)|((str.charCodeAt(j+1)&0xff) << 16)|((str.charCodeAt(j+2)&0xff) << 8)|(str.charCodeAt(j+3)&0xff);
	}
	while (j<str.length) {
		be[j>>2] |= (str.charCodeAt(j)&0xff)<<(24-(j*8)%32);
		j++;
	}
	return be;
};

// Convert an array of big-endian 32-bit words to a string
Crypto.be32sToStr = function(be)
{
	var str = "";
	for(var i=0;i<be.length*32;i+=8)
		str += String.fromCharCode((be[i>>5]>>>(24-i%32)) & 0xff);
	return str;
};

// Convert an array of big-endian 32-bit words to a hex string
Crypto.be32sToHex = function(be)
{
	var hex = "0123456789ABCDEF";
	var str = "";
	for(var i=0;i<be.length*4;i++)
		str += hex.charAt((be[i>>2]>>((3-i%4)*8+4))&0xF) + hex.charAt((be[i>>2]>>((3-i%4)*8))&0xF);
	return str;
};

// Return, in hex, the SHA-1 hash of a string
Crypto.hexSha1Str = function(str)
{
	return Crypto.be32sToHex(Crypto.sha1Str(str));
};

// Return the SHA-1 hash of a string
Crypto.sha1Str = function(str)
{
	return Crypto.sha1(Crypto.strToBe32s(str),str.length);
};

// Calculate the SHA-1 hash of an array of blen bytes of big-endian 32-bit words
Crypto.sha1 = function(x,blen)
{
	// Add 32-bit integers, wrapping at 32 bits
	add32 = function(a,b)
	{
		var lsw = (a&0xFFFF)+(b&0xFFFF);
		var msw = (a>>16)+(b>>16)+(lsw>>16);
		return (msw<<16)|(lsw&0xFFFF);
	};
	// Add five 32-bit integers, wrapping at 32 bits
	add32x5 = function(a,b,c,d,e)
	{
		var lsw = (a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF)+(e&0xFFFF);
		var msw = (a>>16)+(b>>16)+(c>>16)+(d>>16)+(e>>16)+(lsw>>16);
		return (msw<<16)|(lsw&0xFFFF);
	};
	// Bitwise rotate left a 32-bit integer by 1 bit
	rol32 = function(n)
	{
		return (n>>>31)|(n<<1);
	};

	var len = blen*8;
	// Append padding so length in bits is 448 mod 512
	x[len>>5] |= 0x80 << (24-len%32);
	// Append length
	x[((len+64>>9)<<4)+15] = len;
	var w = Array(80);

	var k1 = 0x5A827999;
	var k2 = 0x6ED9EBA1;
	var k3 = 0x8F1BBCDC;
	var k4 = 0xCA62C1D6;

	var h0 = 0x67452301;
	var h1 = 0xEFCDAB89;
	var h2 = 0x98BADCFE;
	var h3 = 0x10325476;
	var h4 = 0xC3D2E1F0;

	for(var i=0;i<x.length;i+=16) {
		var j,t;
		var a = h0;
		var b = h1;
		var c = h2;
		var d = h3;
		var e = h4;
		for(j = 0;j<16;j++) {
			w[j] = x[i+j];
			t = add32x5(e,(a>>>27)|(a<<5),d^(b&(c^d)),w[j],k1);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=16;j<20;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),d^(b&(c^d)),w[j],k1);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=20;j<40;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),b^c^d,w[j],k2);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=40;j<60;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),(b&c)|(d&(b|c)),w[j],k3);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}
		for(j=60;j<80;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a>>>27)|(a<<5),b^c^d,w[j],k4);
			e=d; d=c; c=(b>>>2)|(b<<30); b=a; a = t;
		}

		h0 = add32(h0,a);
		h1 = add32(h1,b);
		h2 = add32(h2,c);
		h3 = add32(h3,d);
		h4 = add32(h4,e);
	}
	return Array(h0,h1,h2,h3,h4);
};


}
//}}}
!Plotting Data
Example plotting data from some of Jeremy Dann's work on measuring respiration rates in Antarctic sea urchin embryos during development at two different salinities. 
{{{
d=read.table("http://icewater.cms.udel.edu/Rgroup/080909/Sn-RespDevoSalinity.txt", sep='\t', header=T)
summary(d)
d$Salinity <- as.factor(d$Salinity)
names(d)[3] <- c("Resp")
D <- d[which(d$Resp < 500),]
}}}
There are TWO salinity treatments with a time vector and a data vector of respiration rates.

<html><img src="080909/shot_01.png" style="height:200px"></html>


!
!Data:
{{{
d <- read.table("http://icewater.cms.udel.edu/Rgroup/0808/DevoRate-34all.txt", header = TRUE, sep = "\t")
}}}
Note that the //read.table// function generates a square matrix. The number of observations in each group are not equal so the read.table import routine fills 'empty' cells in the matrix with zeros so that all columns have the same number of entries. The command:
{{{ 
d$B1
}}}
... generates this list:
{{{
 [1] 0.08472222 0.07991803 0.10143443 0.12192623 0.09118853 0.07991803 0.09016393 0.07889344
 [9] 0.08555328 0.09375000 0.09118853 0.10747664 0.09868421 0.10040984 0.09118853 0.12192623
[17] 0.09118853 0.11270492 0.11270492 0.08555328 0.09579439 0.10706967 0.09102564 0.07991803
[25] 0.11448598 0.09118853 0.07094595 0.11270492 0.05840164 0.05840164 0.11270492 0.11270492
[33] 0.07991803 0.09067623 0.09118853 0.08333333 0.09868421 0.11270492 0.00000000 0.00000000
[41] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
}}}
so  . . . just keep in mind that at this point the output from the 'summary' command includes those zeros in the values presented.

!Establish Factors:
Use the ''melt'' function to now reorganize the raw data so that each row contains the same information for an individual embryo, here that would be culture ID as a factor and development rate as a variable data observation.  
{{{
# data setup - - - - - - - - - - - - - - - -
m = melt(d)
names(m) <- c("Culture","DevoRate")
M <- m[which(m$DevoRate > '0'), ]
}}}
Now we can take a quick look at the data by calculating the mean of each culture x rep:
{{{
> aggregate(M$DevoRate, list(Culture=M$Culture), mean)
  Culture          x
1      A1 0.08365307
2      A2 0.06801401
3      B1 0.09427224
4      C1 0.10844354
5      C2 0.10463076
6      D1 0.09383111
7      D2 0.09443411
}}}

!Data Visualization:
<html><img src="0808/01boxplot.png" style="height:300px"></html>
{{{
# boxplot - - - - - - - - - - - - - - - - - - - - 
ggopt(legend.position="none")
p$legend.position<-c("none")
p <- ggplot(data=M, aes(y=DevoRate,x=Culture))
p + geom_boxplot(aes(fill=Culture), colour="black", outlier.colour="green", outlier.size=3) 
p + scale_y_continuous("Developmental Rate") 
}}}

!T-test
Simple input to check the plates in the A culture:
{{{
# T-TEST - - - - - - - - - 
a1 <- M[which(M$Culture=='A1'),]
a2 <- M[which(M$Culture=='A2'),]
t.test(a1$DevoRate,y=a2$DevoRate)
}}}
Output from R
{{{
	Welch Two Sample t-test

data:  a1$DevoRate and a2$DevoRate 
t = 3.4229, df = 90.993, p-value = 0.0009303
alternative hypothesis: true difference in means is not equal to 0 
95 percent confidence interval:
 0.006563469 0.024714645 
sample estimates:
 mean of x  mean of y 
0.08365307 0.06801401 
}}}
!
[[FrontPage]]
/***
|''Name:''|DeprecatedFunctionsPlugin|
|''Description:''|Support for deprecated functions removed from core|
***/
//{{{
if(!version.extensions.DeprecatedFunctionsPlugin) {
version.extensions.DeprecatedFunctionsPlugin = {installed:true};

//--
//-- Deprecated code
//--

// @Deprecated: Use createElementAndWikify and this.termRegExp instead
config.formatterHelpers.charFormatHelper = function(w)
{
	w.subWikify(createTiddlyElement(w.output,this.element),this.terminator);
};

// @Deprecated: Use enclosedTextHelper and this.lookaheadRegExp instead
config.formatterHelpers.monospacedByLineHelper = function(w)
{
	var lookaheadRegExp = new RegExp(this.lookahead,"mg");
	lookaheadRegExp.lastIndex = w.matchStart;
	var lookaheadMatch = lookaheadRegExp.exec(w.source);
	if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
		var text = lookaheadMatch[1];
		if(config.browser.isIE)
			text = text.replace(/\n/g,"\r");
		createTiddlyElement(w.output,"pre",null,null,text);
		w.nextMatch = lookaheadRegExp.lastIndex;
	}
};

// @Deprecated: Use <br> or <br /> instead of <<br>>

config.macros.br = {};
config.macros.br.handler = function(place)
{
	createTiddlyElement(place,"br");
};

// Find an entry in an array. Returns the array index or null
// @Deprecated: Use indexOf instead
Array.prototype.find = function(item)
{
	var i = this.indexOf(item);
	return i == -1 ? null : i;
};

// Load a tiddler from an HTML DIV. The caller should make sure to later call Tiddler.changed()
// @Deprecated: Use store.getLoader().internalizeTiddler instead
Tiddler.prototype.loadFromDiv = function(divRef,title)
{
	return store.getLoader().internalizeTiddler(store,this,title,divRef);
};

// Format the text for storage in an HTML DIV
// @Deprecated Use store.getSaver().externalizeTiddler instead.
Tiddler.prototype.saveToDiv = function()
{
	return store.getSaver().externalizeTiddler(store,this);
};

// @Deprecated: Use store.allTiddlersAsHtml() instead
function allTiddlersAsHtml()
{
	return store.allTiddlersAsHtml();
}

// @Deprecated: Use refreshPageTemplate instead
function applyPageTemplate(title)
{
	refreshPageTemplate(title);
}

// @Deprecated: Use story.displayTiddlers instead
function displayTiddlers(srcElement,titles,template,unused1,unused2,animate,unused3)
{
	story.displayTiddlers(srcElement,titles,template,animate);
}

// @Deprecated: Use story.displayTiddler instead
function displayTiddler(srcElement,title,template,unused1,unused2,animate,unused3)
{
	story.displayTiddler(srcElement,title,template,animate);
}

// @Deprecated: Use functions on right hand side directly instead
var createTiddlerPopup = Popup.create;
var scrollToTiddlerPopup = Popup.show;
var hideTiddlerPopup = Popup.remove;

// @Deprecated: Use right hand side directly instead
var regexpBackSlashEn = new RegExp("\\\\n","mg");
var regexpBackSlash = new RegExp("\\\\","mg");
var regexpBackSlashEss = new RegExp("\\\\s","mg");
var regexpNewLine = new RegExp("\n","mg");
var regexpCarriageReturn = new RegExp("\r","mg");

}
//}}}
@@apply(WindSpeedAvg,2,mean)@@  versus @@tapply(mWS[,"windspeed"],anem,mean)@@
/***
|!''Name:''|!''E''asily ''A''daptable ''S''ource ''E''ditor|
|''Description:''|this framework allows you to easily create commands that work on the current tiddler text selection in edit mode|
|''Version:''|0.1.0|
|''Date:''|13/01/2007|
|''Source:''|http://yann.perrin.googlepages.com/twkd.html#E.A.S.E|
|''Author:''|[[Yann Perrin|YannPerrin]]|
|''License:''|[[BSD open source license]]|
|''~CoreVersion:''|2.x|
|''Browser:''|Firefox 1.0.4+; Firefox 1.5; InternetExplorer 6.0|
***/
////Messages Definition
//{{{
config.messages.Ease = {
noselection:"nothing selected",
asktitle:"enter the new tiddler title",
exists:" already exists, please enter another title",
askForTagsLabel:"enter the new tiddler tags",
tiddlercreated:" tiddler created"

}
//}}}
////
//{{{
if (!window.TWkd) window.TWkd={context:{}};
if (!TWkd.Ease)
 TWkd.Ease = function (text,tooltip){
 this.text = text;
 this.tooltip = tooltip;
 this.modes = [];
 this.addMode = function(modeDefinition) {this.modes.push(modeDefinition);};
 this.handler = function(event,src,title) {
 TWkd.context.command = this;
 TWkd.context.selection=this.getSelection(title);
 if (this.modes.length==1) {
 this.modes[0].operation();
 }
 else {
 var popup = Popup.create(src);
 if(popup) {
 for (var i=0; i<this.modes.length; i++) {
 createTiddlyButton(createTiddlyElement(popup,"li"), this.modes[i].name, this.modes[i].tooltip, this.OperateFromButton, null, 'id'+i, null);
 }
 Popup.show(popup,false);
 event.cancelBubble = true;
 if (event.stopPropagation) event.stopPropagation();
 return false;
 }
 }
 };
 };

TWkd.Ease.prototype.OperateFromButton = function(e){
 var commandMode=this.getAttribute('Id').replace('id','');
 TWkd.context.command.modes[commandMode].operation();
};

TWkd.Ease.prototype.getTiddlerEditField = function(title,field){
 var tiddler = document.getElementById(story.idPrefix + title);
 if(tiddler != null){
 var children = tiddler.getElementsByTagName("*")
 var e = null;
 for (var t=0; t<children.length; t++){
 var c = children[t];
 if(c.tagName.toLowerCase() == "input" || c.tagName.toLowerCase() == "textarea"){
 if(!e) {e = c;}
 if(c.getAttribute("edit") == field){e = c;}
 }
 }
 if(e){return e;}
 }
} // closes getTiddlerEditField function definition
 
TWkd.Ease.prototype.getSelection = function(title,quiet) {
 var tiddlerTextArea = this.getTiddlerEditField(title,"text");
 var result = {};
 if (document.selection != null && tiddlerTextArea.selectionStart == null) {
 tiddlerTextArea.focus();
 var range = document.selection.createRange();
 var bookmark = range.getBookmark();
 var contents = tiddlerTextArea.value;
 var originalContents = contents;
 var marker = "##SELECTION_MARKER_" + Math.random() + "##";
 while(contents.indexOf(marker) != -1) {
 marker = "##SELECTION_MARKER_" + Math.random() + "##";
 }
 var selection = range.text;
 range.text = marker + range.text + marker;
 contents = tiddlerTextArea.value;
 result.start = contents.indexOf(marker);
 contents = contents.replace(marker, "");
 result.end = contents.indexOf(marker);
 tiddlerTextArea.value = originalContents;
 range.moveToBookmark(bookmark);
 range.select();
 }
 else {
 result.start=tiddlerTextArea.selectionStart;
 result.end=tiddlerTextArea.selectionEnd;
 }
 result.content=tiddlerTextArea.value.substring(result.start,result.end);
 result.source=title;
 if (!result.content&&!quiet) displayMessage(config.messages.Ease.noselection);
 return(result);
}//closes getSelection function definition

// replace selection or insert new content
TWkd.Ease.prototype.putInPlace=function(content,workplace) {
 var tiddlerText = this.getTiddlerEditField(workplace.source,"text");
 tiddlerText.value = tiddlerText.value.substring(0,workplace.start)+content+tiddlerText.value.substring(workplace.end);
}

// asking for title
TWkd.Ease.prototype.askForTitle = function(suggestion) {
 if (!suggestion)
 suggestion = "";
 var newtitle;
 while (!newtitle||store.tiddlerExists(newtitle))
 {
 if (store.tiddlerExists(newtitle))
 displayMessage(newtitle+config.messages.Ease.exists);
 newtitle = prompt(config.messages.Ease.asktitle,suggestion);
 if (newtitle==null)
 {
 displayMessage(config.messages.Ease.titlecancel);
 return(false);
 }
 }
 return(newtitle);
}//closes askForTitle function definition

// creation of a new tiddler
TWkd.Ease.prototype.newTWkdLibTiddler = function(title,content,from,askForTags){
 var tiddler = new Tiddler();
 tiddler.title = title;
 tiddler.modifier = config.options.txtUserName;
 tiddler.text = content;
 (from) ? tiddler.tags = [from] : tiddler.tags=[];
 if (askForTags)
 tiddler.tags = prompt(config.messages.Ease.askForTagsLabel,'[['+from+']]').readBracketedList();
 store.addTiddler(tiddler);
 //store.notifyAll();
 displayMessage(title+config.messages.Ease.tiddlercreated);
}

if (!TWkd.Mode)
 TWkd.Mode = function (name,tooltip,ask,operation) {
 this.name = name;
 this.tooltip = tooltip;
 this.ask = ask;
 this.operation = operation;
 };
//}}}
<div class="toolbar" macro="toolbar +saveTiddler closeOthers -cancelTiddler deleteTiddler"></div>
<div class="title" macro="view title"></div>
<div class="editLabel">Title</div><div class="editor" macro="edit title"></div>

<div class="editLabel">Tags</div><div class="editor" macro="edit tags"></div>
<div class="editorFooter"><span macro="message views.editor.tagPrompt"></span><span macro="tagChooser"></span></div>

<div macro='hideWhen ((tiddler.tags.contains("Contacts"))||(tiddler.title=="New Contact"))'>[[EditToolbar]]<div class='editor' macro='edit text'></div></div>
<div macro='showWhen ((tiddler.tags.contains("Contacts"))||(tiddler.title=="New Contact"))'><div class='editor'>

<table width='100%'>
<tr><th>Name</th><td><span macro='edit ContactFirstName'></span><span macro='edit ContactLastName'></span></td><td rowspan='4' width='50%' macro='edit text'></td></tr>
<tr><th>Adress</th><td><span macro='edit ContactStreetNumber'></span><span macro='edit ContactStreetName'></span><span macro='edit ContactZipCode'></span><span macro='edit ContactCity'></span></td></tr>

<tr><th>Phone</th><td><span macro='edit ContactPhone'></span></td></tr>
<tr><th>Email</th><td><span macro='edit ContactMail'><span></td></tr>

</table>
</div></div>
<div macro='toolbar Format Greek Hebrew Indent Notes Color Highlighting Tables'></div>
/***
|Name|FontSizePlugin|
|Created by|SaqImtiaz|
|Location|http://tw.lewcid.org/#FontSizePlugin|
|Version|1.0|
|Requires|~TW2.x|
!Description:
Resize tiddler text on the fly. The text size is remembered between sessions by use of a cookie.
You can customize the maximum and minimum allowed sizes.
(only affects tiddler content text, not any other text)

Also, you can load a TW file with a font-size specified in the url.
Eg: http://tw.lewcid.org/#font:110

!Demo:
Try using the font-size buttons in the sidebar, or in the MainMenu above.

!Installation:
Copy the contents of this tiddler to your TW, tag with systemConfig, save and reload your TW.
Then put {{{<<fontSize "font-size:">>}}} in your SideBarOptions tiddler, or anywhere else that you might like.

!Usage
{{{<<fontSize>>}}} results in <<fontSize>>

{{{<<fontSize font-size: >>}}} results in <<fontSize font-size:>>

!Customizing:
The buttons and prefix text are wrapped in a span with class fontResizer, for easy css styling.
To change the default font-size, and the maximum and minimum font-size allowed, edit the config.fontSize.settings section of the code below.

!Notes:
This plugin assumes that the initial font-size is 100% and then increases or decreases the size by 10%. This stepsize of 10% can also be customized.

!History:
*27-07-06, version 1.0 : prevented double clicks from triggering editing of containing tiddler.
*25-07-06,  version 0.9

!Code
***/

//{{{
config.fontSize={};

//configuration settings
config.fontSize.settings =
{
            defaultSize : 100,  // all sizes in %
            maxSize : 200,
            minSize : 40,
            stepSize : 10
};

//startup code
var fontSettings = config.fontSize.settings;

if (!config.options.txtFontSize)
            {config.options.txtFontSize = fontSettings.defaultSize;
            saveOptionCookie("txtFontSize");}
setStylesheet(".tiddler .viewer {font-size:"+config.options.txtFontSize+"%;}\n","fontResizerStyles");
setStylesheet("#contentWrapper .fontResizer .button {display:inline;font-size:105%; font-weight:bold; margin:0 1px; padding: 0 3px; text-align:center !important;}\n .fontResizer {margin:0 0.5em;}","fontResizerButtonStyles");

//macro
config.macros.fontSize={};
config.macros.fontSize.handler = function (place,macroName,params,wikifier,paramString,tiddler)
{

               var sp = createTiddlyElement(place,"span",null,"fontResizer");
               sp.ondblclick=this.onDblClick;
               if (params[0])
                           createTiddlyText(sp,params[0]);
               createTiddlyButton(sp,"+","increase font-size",this.incFont);
               createTiddlyButton(sp,"=","reset font-size",this.resetFont);
               createTiddlyButton(sp,"–","decrease font-size",this.decFont);
}

config.macros.fontSize.onDblClick = function (e)
{
             if (!e) var e = window.event;
             e.cancelBubble = true;
             if (e.stopPropagation) e.stopPropagation();
             return false;
}

config.macros.fontSize.setFont = function ()
{
               saveOptionCookie("txtFontSize");
               setStylesheet(".tiddler .viewer {font-size:"+config.options.txtFontSize+"%;}\n","fontResizerStyles");
}

config.macros.fontSize.incFont=function()
{
               if (config.options.txtFontSize < fontSettings.maxSize)
                  config.options.txtFontSize = (config.options.txtFontSize*1)+fontSettings.stepSize;
               config.macros.fontSize.setFont();
}

config.macros.fontSize.decFont=function()
{

               if (config.options.txtFontSize > fontSettings.minSize)
                  config.options.txtFontSize = (config.options.txtFontSize*1) - fontSettings.stepSize;
               config.macros.fontSize.setFont();
}

config.macros.fontSize.resetFont=function()
{

               config.options.txtFontSize=fontSettings.defaultSize;
               config.macros.fontSize.setFont();
}

config.paramifiers.font =
{
               onstart: function(v)
                  {
                   config.options.txtFontSize = v;
                   config.macros.fontSize.setFont();
                  }
};
//}}}
/***
|''Name:''|ForEachTiddlerPlugin|
|''Version:''|1.0.8 (2007-04-12)|
|''Source:''|http://tiddlywiki.abego-software.de/#ForEachTiddlerPlugin|
|''Author:''|UdoBorkowski (ub [at] abego-software [dot] de)|
|''Licence:''|[[BSD open source license (abego Software)|http://www.abego-software.de/legal/apl-v10.html]]|
|''Copyright:''|&copy; 2005-2007 [[abego Software|http://www.abego-software.de]]|
|''TiddlyWiki:''|1.2.38+, 2.0|
|''Browser:''|Firefox 1.0.4+; Firefox 1.5; InternetExplorer 6.0|
!Description

Create customizable lists, tables etc. for your selections of tiddlers. Specify the tiddlers to include and their order through a powerful language.

''Syntax:'' 
|>|{{{<<}}}''forEachTiddler'' [''in'' //tiddlyWikiPath//] [''where'' //whereCondition//] [''sortBy'' //sortExpression// [''ascending'' //or// ''descending'']] [''script'' //scriptText//] [//action// [//actionParameters//]]{{{>>}}}|
|//tiddlyWikiPath//|The filepath to the TiddlyWiki the macro should work on. When missing the current TiddlyWiki is used.|
|//whereCondition//|(quoted) JavaScript boolean expression. May refer to the build-in variables {{{tiddler}}} and  {{{context}}}.|
|//sortExpression//|(quoted) JavaScript expression returning "comparable" objects (using '{{{<}}}','{{{>}}}','{{{==}}}'. May refer to the build-in variables {{{tiddler}}} and  {{{context}}}.|
|//scriptText//|(quoted) JavaScript text. Typically defines JavaScript functions that are called by the various JavaScript expressions (whereClause, sortClause, action arguments,...)|
|//action//|The action that should be performed on every selected tiddler, in the given order. By default the actions [[addToList|AddToListAction]] and [[write|WriteAction]] are supported. When no action is specified [[addToList|AddToListAction]]  is used.|
|//actionParameters//|(action specific) parameters the action may refer while processing the tiddlers (see action descriptions for details). <<tiddler [[JavaScript in actionParameters]]>>|
|>|~~Syntax formatting: Keywords in ''bold'', optional parts in [...]. 'or' means that exactly one of the two alternatives must exist.~~|

See details see [[ForEachTiddlerMacro]] and [[ForEachTiddlerExamples]].

!Revision history
* v1.0.8 (2007-04-12)
** Adapted to latest TiddlyWiki 2.2 Beta importTiddlyWiki API (introduced with changeset 2004). TiddlyWiki 2.2 Beta builds prior to changeset 2004 are no longer supported (but TiddlyWiki 2.1 and earlier, of cause)
* v1.0.7 (2007-03-28)
** Also support "pre" formatted TiddlyWikis (introduced with TW 2.2) (when using "in" clause to work on external tiddlers)
* v1.0.6 (2006-09-16)
** Context provides "viewerTiddler", i.e. the tiddler used to view the macro. Most times this is equal to the "inTiddler", but when using the "tiddler" macro both may be different.
** Support "begin", "end" and "none" expressions in "write" action
* v1.0.5 (2006-02-05)
** Pass tiddler containing the macro with wikify, context object also holds reference to tiddler containing the macro ("inTiddler"). Thanks to SimonBaird.
** Support Firefox 1.5.0.1
** Internal
*** Make "JSLint" conform
*** "Only install once"

* v1.0.4 (2006-01-06)
** Support TiddlyWiki 2.0
* v1.0.3 (2005-12-22)
** Features: 
*** Write output to a file supports multi-byte environments (Thanks to Bram Chen) 
*** Provide API to access the forEachTiddler functionality directly through JavaScript (see getTiddlers and performMacro)
** Enhancements:
*** Improved error messages on InternetExplorer.
* v1.0.2 (2005-12-10)
** Features: 
*** context object also holds reference to store (TiddlyWiki)
** Fixed Bugs: 
*** ForEachTiddler 1.0.1 has broken support on win32 Opera 8.51 (Thanks to BrunoSabin for reporting)
* v1.0.1 (2005-12-08)
** Features: 
*** Access tiddlers stored in separated TiddlyWikis through the "in" option. I.e. you are no longer limited to only work on the "current TiddlyWiki".
*** Write output to an external file using the "toFile" option of the "write" action. With this option you may write your customized tiddler exports.
*** Use the "script" section to define "helper" JavaScript functions etc. to be used in the various JavaScript expressions (whereClause, sortClause, action arguments,...).
*** Access and store context information for the current forEachTiddler invocation (through the build-in "context" object) .
*** Improved script evaluation (for where/sort clause and write scripts).
* v1.0.0 (2005-11-20)
** initial version

!Code
***/
//{{{

	
//============================================================================
//============================================================================
//		   ForEachTiddlerPlugin
//============================================================================
//============================================================================

// Only install once
if (!version.extensions.ForEachTiddlerPlugin) {

if (!window.abego) window.abego = {};

version.extensions.ForEachTiddlerPlugin = {
	major: 1, minor: 0, revision: 8, 
	date: new Date(2007,3,12), 
	source: "http://tiddlywiki.abego-software.de/#ForEachTiddlerPlugin",
	licence: "[[BSD open source license (abego Software)|http://www.abego-software.de/legal/apl-v10.html]]",
	copyright: "Copyright (c) abego Software GmbH, 2005-2007 (www.abego-software.de)"

};

// For backward compatibility with TW 1.2.x
//
if (!TiddlyWiki.prototype.forEachTiddler) {
	TiddlyWiki.prototype.forEachTiddler = function(callback) {
		for(var t in this.tiddlers) {
			callback.call(this,t,this.tiddlers[t]);
		}
	};
}

//============================================================================
// forEachTiddler Macro
//============================================================================

version.extensions.forEachTiddler = {
	major: 1, minor: 0, revision: 8, date: new Date(2007,3,12), provider: "http://tiddlywiki.abego-software.de"};

// ---------------------------------------------------------------------------
// Configurations and constants 
// ---------------------------------------------------------------------------

config.macros.forEachTiddler = {
	 // Standard Properties
	 label: "forEachTiddler",
	 prompt: "Perform actions on a (sorted) selection of tiddlers",

	 // actions
	 actions: {
		 addToList: {},
		 write: {}
	 }
};

// ---------------------------------------------------------------------------
//  The forEachTiddler Macro Handler 
// ---------------------------------------------------------------------------

config.macros.forEachTiddler.getContainingTiddler = function(e) {
	while(e && !hasClass(e,"tiddler"))
		e = e.parentNode;
	var title = e ? e.getAttribute("tiddler") : null; 
	return title ? store.getTiddler(title) : null;
};

config.macros.forEachTiddler.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
	// config.macros.forEachTiddler.traceMacroCall(place,macroName,params,wikifier,paramString,tiddler);

	if (!tiddler) tiddler = config.macros.forEachTiddler.getContainingTiddler(place);
	// --- Parsing ------------------------------------------

	var i = 0; // index running over the params
	// Parse the "in" clause
	var tiddlyWikiPath = undefined;
	if ((i < params.length) && params[i] == "in") {
		i++;
		if (i >= params.length) {
			this.handleError(place, "TiddlyWiki path expected behind 'in'.");
			return;
		}
		tiddlyWikiPath = this.paramEncode((i < params.length) ? params[i] : "");
		i++;
	}

	// Parse the where clause
	var whereClause ="true";
	if ((i < params.length) && params[i] == "where") {
		i++;
		whereClause = this.paramEncode((i < params.length) ? params[i] : "");
		i++;
	}

	// Parse the sort stuff
	var sortClause = null;
	var sortAscending = true; 
	if ((i < params.length) && params[i] == "sortBy") {
		i++;
		if (i >= params.length) {
			this.handleError(place, "sortClause missing behind 'sortBy'.");
			return;
		}
		sortClause = this.paramEncode(params[i]);
		i++;

		if ((i < params.length) && (params[i] == "ascending" || params[i] == "descending")) {
			 sortAscending = params[i] == "ascending";
			 i++;
		}
	}

	// Parse the script
	var scriptText = null;
	if ((i < params.length) && params[i] == "script") {
		i++;
		scriptText = this.paramEncode((i < params.length) ? params[i] : "");
		i++;
	}

	// Parse the action. 
	// When we are already at the end use the default action
	var actionName = "addToList";
	if (i < params.length) {
	   if (!config.macros.forEachTiddler.actions[params[i]]) {
			this.handleError(place, "Unknown action '"+params[i]+"'.");
			return;
		} else {
			actionName = params[i]; 
			i++;
		}
	} 
	
	// Get the action parameter
	// (the parsing is done inside the individual action implementation.)
	var actionParameter = params.slice(i);


	// --- Processing ------------------------------------------
	try {
		this.performMacro({
				place: place, 
				inTiddler: tiddler,
				whereClause: whereClause, 
				sortClause: sortClause, 
				sortAscending: sortAscending, 
				actionName: actionName, 
				actionParameter: actionParameter, 
				scriptText: scriptText, 
				tiddlyWikiPath: tiddlyWikiPath});

	} catch (e) {
		this.handleError(place, e);
	}
};

// Returns an object with properties "tiddlers" and "context".
// tiddlers holds the (sorted) tiddlers selected by the parameter,
// context the context of the execution of the macro.
//
// The action is not yet performed.
//
// @parameter see performMacro
//
config.macros.forEachTiddler.getTiddlersAndContext = function(parameter) {

	var context = config.macros.forEachTiddler.createContext(parameter.place, parameter.whereClause, parameter.sortClause, parameter.sortAscending, parameter.actionName, parameter.actionParameter, parameter.scriptText, parameter.tiddlyWikiPath, parameter.inTiddler);

	var tiddlyWiki = parameter.tiddlyWikiPath ? this.loadTiddlyWiki(parameter.tiddlyWikiPath) : store;
	context["tiddlyWiki"] = tiddlyWiki;
	
	// Get the tiddlers, as defined by the whereClause
	var tiddlers = this.findTiddlers(parameter.whereClause, context, tiddlyWiki);
	context["tiddlers"] = tiddlers;

	// Sort the tiddlers, when sorting is required.
	if (parameter.sortClause) {
		this.sortTiddlers(tiddlers, parameter.sortClause, parameter.sortAscending, context);
	}

	return {tiddlers: tiddlers, context: context};
};

// Returns the (sorted) tiddlers selected by the parameter.
//
// The action is not yet performed.
//
// @parameter see performMacro
//
config.macros.forEachTiddler.getTiddlers = function(parameter) {
	return this.getTiddlersAndContext(parameter).tiddlers;
};

// Performs the macros with the given parameter.
//
// @param parameter holds the parameter of the macro as separate properties.
//				  The following properties are supported:
//
//						place
//						whereClause
//						sortClause
//						sortAscending
//						actionName
//						actionParameter
//						scriptText
//						tiddlyWikiPath
//
//					All properties are optional. 
//					For most actions the place property must be defined.
//
config.macros.forEachTiddler.performMacro = function(parameter) {
	var tiddlersAndContext = this.getTiddlersAndContext(parameter);

	// Perform the action
	var actionName = parameter.actionName ? parameter.actionName : "addToList";
	var action = config.macros.forEachTiddler.actions[actionName];
	if (!action) {
		this.handleError(parameter.place, "Unknown action '"+actionName+"'.");
		return;
	}

	var actionHandler = action.handler;
	actionHandler(parameter.place, tiddlersAndContext.tiddlers, parameter.actionParameter, tiddlersAndContext.context);
};

// ---------------------------------------------------------------------------
//  The actions 
// ---------------------------------------------------------------------------

// Internal.
//
// --- The addToList Action -----------------------------------------------
//
config.macros.forEachTiddler.actions.addToList.handler = function(place, tiddlers, parameter, context) {
	// Parse the parameter
	var p = 0;

	// Check for extra parameters
	if (parameter.length > p) {
		config.macros.forEachTiddler.createExtraParameterErrorElement(place, "addToList", parameter, p);
		return;
	}

	// Perform the action.
	var list = document.createElement("ul");
	place.appendChild(list);
	for (var i = 0; i < tiddlers.length; i++) {
		var tiddler = tiddlers[i];
		var listItem = document.createElement("li");
		list.appendChild(listItem);
		createTiddlyLink(listItem, tiddler.title, true);
	}
};

abego.parseNamedParameter = function(name, parameter, i) {
	var beginExpression = null;
	if ((i < parameter.length) && parameter[i] == name) {
		i++;
		if (i >= parameter.length) {
			throw "Missing text behind '%0'".format([name]);
		}
		
		return config.macros.forEachTiddler.paramEncode(parameter[i]);
	}
	return null;
}

// Internal.
//
// --- The write Action ---------------------------------------------------
//
config.macros.forEachTiddler.actions.write.handler = function(place, tiddlers, parameter, context) {
	// Parse the parameter
	var p = 0;
	if (p >= parameter.length) {
		this.handleError(place, "Missing expression behind 'write'.");
		return;
	}

	var textExpression = config.macros.forEachTiddler.paramEncode(parameter[p]);
	p++;

	// Parse the "begin" option
	var beginExpression = abego.parseNamedParameter("begin", parameter, p);
	if (beginExpression !== null) 
		p += 2;
	var endExpression = abego.parseNamedParameter("end", parameter, p);
	if (endExpression !== null) 
		p += 2;
	var noneExpression = abego.parseNamedParameter("none", parameter, p);
	if (noneExpression !== null) 
		p += 2;

	// Parse the "toFile" option
	var filename = null;
	var lineSeparator = undefined;
	if ((p < parameter.length) && parameter[p] == "toFile") {
		p++;
		if (p >= parameter.length) {
			this.handleError(place, "Filename expected behind 'toFile' of 'write' action.");
			return;
		}
		
		filename = config.macros.forEachTiddler.getLocalPath(config.macros.forEachTiddler.paramEncode(parameter[p]));
		p++;
		if ((p < parameter.length) && parameter[p] == "withLineSeparator") {
			p++;
			if (p >= parameter.length) {
				this.handleError(place, "Line separator text expected behind 'withLineSeparator' of 'write' action.");
				return;
			}
			lineSeparator = config.macros.forEachTiddler.paramEncode(parameter[p]);
			p++;
		}
	}
	
	// Check for extra parameters
	if (parameter.length > p) {
		config.macros.forEachTiddler.createExtraParameterErrorElement(place, "write", parameter, p);
		return;
	}

	// Perform the action.
	var func = config.macros.forEachTiddler.getEvalTiddlerFunction(textExpression, context);
	var count = tiddlers.length;
	var text = "";
	if (count > 0 && beginExpression)
		text += config.macros.forEachTiddler.getEvalTiddlerFunction(beginExpression, context)(undefined, context, count, undefined);
	
	for (var i = 0; i < count; i++) {
		var tiddler = tiddlers[i];
		text += func(tiddler, context, count, i);
	}
	
	if (count > 0 && endExpression)
		text += config.macros.forEachTiddler.getEvalTiddlerFunction(endExpression, context)(undefined, context, count, undefined);

	if (count == 0 && noneExpression) 
		text += config.macros.forEachTiddler.getEvalTiddlerFunction(noneExpression, context)(undefined, context, count, undefined);
		

	if (filename) {
		if (lineSeparator !== undefined) {
			lineSeparator = lineSeparator.replace(/\\n/mg, "\n").replace(/\\r/mg, "\r");
			text = text.replace(/\n/mg,lineSeparator);
		}
		saveFile(filename, convertUnicodeToUTF8(text));
	} else {
		var wrapper = createTiddlyElement(place, "span");
		wikify(text, wrapper, null/* highlightRegExp */, context.inTiddler);
	}
};


// ---------------------------------------------------------------------------
//  Helpers
// ---------------------------------------------------------------------------

// Internal.
//
config.macros.forEachTiddler.createContext = function(placeParam, whereClauseParam, sortClauseParam, sortAscendingParam, actionNameParam, actionParameterParam, scriptText, tiddlyWikiPathParam, inTiddlerParam) {
	return {
		place : placeParam, 
		whereClause : whereClauseParam, 
		sortClause : sortClauseParam, 
		sortAscending : sortAscendingParam, 
		script : scriptText,
		actionName : actionNameParam, 
		actionParameter : actionParameterParam,
		tiddlyWikiPath : tiddlyWikiPathParam,
		inTiddler : inTiddlerParam, // the tiddler containing the <<forEachTiddler ...>> macro call.
		viewerTiddler : config.macros.forEachTiddler.getContainingTiddler(placeParam) // the tiddler showing the forEachTiddler result
	};
};

// Internal.
//
// Returns a TiddlyWiki with the tiddlers loaded from the TiddlyWiki of 
// the given path.
//
config.macros.forEachTiddler.loadTiddlyWiki = function(path, idPrefix) {
	if (!idPrefix) {
		idPrefix = "store";
	}
	var lenPrefix = idPrefix.length;
	
	// Read the content of the given file
	var content = loadFile(this.getLocalPath(path));
	if(content === null) {
		throw "TiddlyWiki '"+path+"' not found.";
	}
	
	var tiddlyWiki = new TiddlyWiki();

	// Starting with TW 2.2 there is a helper function to import the tiddlers
	if (tiddlyWiki.importTiddlyWiki) {
		if (!tiddlyWiki.importTiddlyWiki(content))
			throw "File '"+path+"' is not a TiddlyWiki.";
		tiddlyWiki.dirty = false;
		return tiddlyWiki;
	}
	
	// The legacy code, for TW < 2.2
	
	// Locate the storeArea div's
	var posOpeningDiv = content.indexOf(startSaveArea);
	var posClosingDiv = content.lastIndexOf(endSaveArea);
	if((posOpeningDiv == -1) || (posClosingDiv == -1)) {
		throw "File '"+path+"' is not a TiddlyWiki.";
	}
	var storageText = content.substr(posOpeningDiv + startSaveArea.length, posClosingDiv);
	
	// Create a "div" element that contains the storage text
	var myStorageDiv = document.createElement("div");
	myStorageDiv.innerHTML = storageText;
	myStorageDiv.normalize();
	
	// Create all tiddlers in a new TiddlyWiki
	// (following code is modified copy of TiddlyWiki.prototype.loadFromDiv)
	var store = myStorageDiv.childNodes;
	for(var t = 0; t < store.length; t++) {
		var e = store[t];
		var title = null;
		if(e.getAttribute)
			title = e.getAttribute("tiddler");
		if(!title && e.id && e.id.substr(0,lenPrefix) == idPrefix)
			title = e.id.substr(lenPrefix);
		if(title && title !== "") {
			var tiddler = tiddlyWiki.createTiddler(title);
			tiddler.loadFromDiv(e,title);
		}
	}
	tiddlyWiki.dirty = false;

	return tiddlyWiki;
};


	
// Internal.
//
// Returns a function that has a function body returning the given javaScriptExpression.
// The function has the parameters:
// 
//	 (tiddler, context, count, index)
//
config.macros.forEachTiddler.getEvalTiddlerFunction = function (javaScriptExpression, context) {
	var script = context["script"];
	var functionText = "var theFunction = function(tiddler, context, count, index) { return "+javaScriptExpression+"}";
	var fullText = (script ? script+";" : "")+functionText+";theFunction;";
	return eval(fullText);
};

// Internal.
//
config.macros.forEachTiddler.findTiddlers = function(whereClause, context, tiddlyWiki) {
	var result = [];
	var func = config.macros.forEachTiddler.getEvalTiddlerFunction(whereClause, context);
	tiddlyWiki.forEachTiddler(function(title,tiddler) {
		if (func(tiddler, context, undefined, undefined)) {
			result.push(tiddler);
		}
	});
	return result;
};

// Internal.
//
config.macros.forEachTiddler.createExtraParameterErrorElement = function(place, actionName, parameter, firstUnusedIndex) {
	var message = "Extra parameter behind '"+actionName+"':";
	for (var i = firstUnusedIndex; i < parameter.length; i++) {
		message += " "+parameter[i];
	}
	this.handleError(place, message);
};

// Internal.
//
config.macros.forEachTiddler.sortAscending = function(tiddlerA, tiddlerB) {
	var result = 
		(tiddlerA.forEachTiddlerSortValue == tiddlerB.forEachTiddlerSortValue) 
			? 0
			: (tiddlerA.forEachTiddlerSortValue < tiddlerB.forEachTiddlerSortValue)
			   ? -1 
			   : +1; 
	return result;
};

// Internal.
//
config.macros.forEachTiddler.sortDescending = function(tiddlerA, tiddlerB) {
	var result = 
		(tiddlerA.forEachTiddlerSortValue == tiddlerB.forEachTiddlerSortValue) 
			? 0
			: (tiddlerA.forEachTiddlerSortValue < tiddlerB.forEachTiddlerSortValue)
			   ? +1 
			   : -1; 
	return result;
};

// Internal.
//
config.macros.forEachTiddler.sortTiddlers = function(tiddlers, sortClause, ascending, context) {
	// To avoid evaluating the sortClause whenever two items are compared 
	// we pre-calculate the sortValue for every item in the array and store it in a 
	// temporary property ("forEachTiddlerSortValue") of the tiddlers.
	var func = config.macros.forEachTiddler.getEvalTiddlerFunction(sortClause, context);
	var count = tiddlers.length;
	var i;
	for (i = 0; i < count; i++) {
		var tiddler = tiddlers[i];
		tiddler.forEachTiddlerSortValue = func(tiddler,context, undefined, undefined);
	}

	// Do the sorting
	tiddlers.sort(ascending ? this.sortAscending : this.sortDescending);

	// Delete the temporary property that holds the sortValue.	
	for (i = 0; i < tiddlers.length; i++) {
		delete tiddlers[i].forEachTiddlerSortValue;
	}
};


// Internal.
//
config.macros.forEachTiddler.trace = function(message) {
	displayMessage(message);
};

// Internal.
//
config.macros.forEachTiddler.traceMacroCall = function(place,macroName,params) {
	var message ="<<"+macroName;
	for (var i = 0; i < params.length; i++) {
		message += " "+params[i];
	}
	message += ">>";
	displayMessage(message);
};


// Internal.
//
// Creates an element that holds an error message
// 
config.macros.forEachTiddler.createErrorElement = function(place, exception) {
	var message = (exception.description) ? exception.description : exception.toString();
	return createTiddlyElement(place,"span",null,"forEachTiddlerError","<<forEachTiddler ...>>: "+message);
};

// Internal.
//
// @param place [may be null]
//
config.macros.forEachTiddler.handleError = function(place, exception) {
	if (place) {
		this.createErrorElement(place, exception);
	} else {
		throw exception;
	}
};

// Internal.
//
// Encodes the given string.
//
// Replaces 
//	 "$))" to ">>"

//	 "$)" to ">"
//
config.macros.forEachTiddler.paramEncode = function(s) {
	var reGTGT = new RegExp("\\$\\)\\)","mg");
	var reGT = new RegExp("\\$\\)","mg");
	return s.replace(reGTGT, ">>").replace(reGT, ">");
};

// Internal.
//
// Returns the given original path (that is a file path, starting with "file:")
// as a path to a local file, in the systems native file format.
//
// Location information in the originalPath (i.e. the "#" and stuff following)
// is stripped.
// 
config.macros.forEachTiddler.getLocalPath = function(originalPath) {
	// Remove any location part of the URL
	var hashPos = originalPath.indexOf("#");
	if(hashPos != -1)
		originalPath = originalPath.substr(0,hashPos);
	// Convert to a native file format assuming
	// "file:///x:/path/path/path..." - pc local file --> "x:\path\path\path..."

	// "file://///server/share/path/path/path..." - FireFox pc network file --> "\\server\share\path\path\path..."
	// "file:///path/path/path..." - mac/unix local file --> "/path/path/path..."
	// "file://server/share/path/path/path..." - pc network file --> "\\server\share\path\path\path..."

	var localPath;
	if(originalPath.charAt(9) == ":") // pc local file
		localPath = unescape(originalPath.substr(8)).replace(new RegExp("/","g"),"\\");
	else if(originalPath.indexOf("file://///") === 0) // FireFox pc network file
		localPath = "\\\\" + unescape(originalPath.substr(10)).replace(new RegExp("/","g"),"\\");
	else if(originalPath.indexOf("file:///") === 0) // mac/unix local file
		localPath = unescape(originalPath.substr(7));
	else if(originalPath.indexOf("file:/") === 0) // mac/unix local file
		localPath = unescape(originalPath.substr(5));
	else // pc network file
		localPath = "\\\\" + unescape(originalPath.substr(7)).replace(new RegExp("/","g"),"\\");	
	return localPath;
};

// ---------------------------------------------------------------------------
// Stylesheet Extensions (may be overridden by local StyleSheet)
// ---------------------------------------------------------------------------
//
setStylesheet(
	".forEachTiddlerError{color: #ffffff;background-color: #880000;}",
	"forEachTiddler");

//============================================================================
// End of forEachTiddler Macro
//============================================================================


//============================================================================
// String.startsWith Function
//============================================================================
//
// Returns true if the string starts with the given prefix, false otherwise.
//
version.extensions["String.startsWith"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
String.prototype.startsWith = function(prefix) {
	var n =  prefix.length;
	return (this.length >= n) && (this.slice(0, n) == prefix);
};



//============================================================================
// String.endsWith Function
//============================================================================
//
// Returns true if the string ends with the given suffix, false otherwise.
//
version.extensions["String.endsWith"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
String.prototype.endsWith = function(suffix) {
	var n = suffix.length;
	return (this.length >= n) && (this.right(n) == suffix);
};


//============================================================================
// String.contains Function
//============================================================================
//
// Returns true when the string contains the given substring, false otherwise.
//
version.extensions["String.contains"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
String.prototype.contains = function(substring) {
	return this.indexOf(substring) >= 0;
};

//============================================================================
// Array.indexOf Function
//============================================================================
//
// Returns the index of the first occurance of the given item in the array or 
// -1 when no such item exists.
//
// @param item [may be null]
//
version.extensions["Array.indexOf"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.indexOf = function(item) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == item) {
			return i;
		}
	}
	return -1;
};

//============================================================================
// Array.contains Function
//============================================================================
//
// Returns true when the array contains the given item, otherwise false. 
//
// @param item [may be null]
//
version.extensions["Array.contains"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.contains = function(item) {
	return (this.indexOf(item) >= 0);
};

//============================================================================
// Array.containsAny Function
//============================================================================
//
// Returns true when the array contains at least one of the elements 
// of the item. Otherwise (or when items contains no elements) false is returned.
//
version.extensions["Array.containsAny"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.containsAny = function(items) {
	for(var i = 0; i < items.length; i++) {
		if (this.contains(items[i])) {
			return true;
		}
	}
	return false;
};


//============================================================================
// Array.containsAll Function
//============================================================================
//
// Returns true when the array contains all the items, otherwise false.
// 
// When items is null false is returned (even if the array contains a null).
//
// @param items [may be null] 
//
version.extensions["Array.containsAll"] = {major: 1, minor: 0, revision: 0, date: new Date(2005,11,20), provider: "http://tiddlywiki.abego-software.de"};
//
Array.prototype.containsAll = function(items) {
	for(var i = 0; i < items.length; i++) {
		if (!this.contains(items[i])) {
			return false;
		}
	}
	return true;
};


} // of "install only once"

// Used Globals (for JSLint) ==============
// ... DOM
/*global 	document */
// ... TiddlyWiki Core
/*global 	convertUnicodeToUTF8, createTiddlyElement, createTiddlyLink, 
			displayMessage, endSaveArea, hasClass, loadFile, saveFile, 
			startSaveArea, store, wikify */
//}}}


/***
!Licence and Copyright
Copyright (c) abego Software ~GmbH, 2005 ([[www.abego-software.de|http://www.abego-software.de]])

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.

Neither the name of abego Software nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
***/

!Fo'rm'at menu
|''bold''|@@highlight@@|
|//italic//|[[hyperlink]]|
|__underline__||''''
!Greek menu
|{{greek{κλητοι̂ς}}}|{{gkindent{{{gkindent{{{gkindent{κλητοι̂ς}}}}}}}}}|
|{{gkindent{κλητοι̂ς}}}|{{gkindent{{{gkindent{{{gkindent{{{gkindent{κλητοι̂ς}}}}}}}}}}}}|
|{{gkindent{{{gkindent{κλητοι̂ς}}}}}}|{{gkindent{{{gkindent{{{gkindent{{{gkindent{{{gkindent{κλητοι̂ς}}}}}}}}}}}}}}}|
!!Hebrew menu
{{hebrewNoAlign{וַיָּקָם}}}
{{hebrewRightAlign{וַיָּקָם}}}
{{hebAlignAndIndent{וַיָּקָם}}}
{{hebAlignAndIndent{{{hebAlignAndIndent{וַיָּקָם}}}}}}
{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{וַיָּקָם}}}}}}}}}
{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{וַיָּקָם}}}}}}}}}}}}
{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{וַיָּקָם}}}}}}}}}}}}}}}
!Indent menu
{{engindent{Text}}}
{{engindent{{{engindent{Text}}}}}}
{{engindent{{{engindent{{{engindent{Text}}}}}}}}}
{{engindent{{{engindent{{{engindent{{{engindent{Text}}}}}}}}}}}}
{{engindent{{{engindent{{{engindent{{{engindent{{{engindent{Text}}}}}}}}}}}}}}}
!Notes menu
((syntax(add note here))) &#149; ((translation(add note here))) &#149; ((text(add note here))) &#149; ((gram(add note here))) ((Popup: your text here(your popup text here)))
!Color menu
{{red{Red}}} {{blue{Blue}}} {{green{Green}}} {{gold{Gold}}} {{gray{Gray}}} {{magenta{Magenta}}} {{purple{Purple}}} {{teal{Teal}}} {{burgundy{Burgundy}}}
!Highlighting menu
@@bgcolor(#ff6666):Red@@ @@bgcolor(#ccccff):Blue@@ @@Yellow@@ @@bgcolor(#99ff99):Green@@ @@bgcolor(#cc9966):Brown@@ @@bgcolor(#cccc99):Gray@@ @@bgcolor(#ff9933):Orange@@
!Tables menu
Invisible table: {{invisiblecomm{
|!Invisible table header|!Invisible table header|!invisible table header|
|data|data|data|
|data|data|data|
|data|data|data|
}}}
Sortable table:
|sortable|k
|Header1|Header2|Header3|h
|Aa|B3|data7|
|Ab|B2|data2|
|Ac|B1|data8|
Standard table:
|!Header|!Header|!Header|
|data|data|data|
|data|data|data|
|data|data|data|
Table cell colors:
|!Below is a light gray cell|!Below is a dark gray cell|!Below are regular cells|
|bgcolor(#eeeeee):text here|||
||bgcolor(#cccccc):text there||
|||text anywhere|
@@bgcolor(#cccc99):{{blue{NEXT Meeting: Tuesday 09 SEP @ 1000h}}}@@
@@GO TO SESSION PAGE:@@ [[Intro-0909]]
<html><div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><big><big><b><center>

<br>
CMES "R" Statistical Users Group
</b></big></big>
<br>
<br></center>
WE are a working group designed to foster the exchange of R tips and tricks among faculty and students using this package. WE encourage those unfamiliar with R to dive in and learn some basics, and along the way hope they will use R more routinely in their work.
<br><br><div style="color: rgb(00, 00, 00); font-family: Monaco;">
<i>
09 SEP:<br>We will meet on Tuesdays from 10-11 am in C202
</i>
</html>
!Try This: "SUBSTRING"
{{{
nfldata <- c("NE-Patriots","IN-Colts","TB-Buccaneers","SD-Chargers") 
mascot <- substring(nfldata,4,20)
}}}
Paste it into R and look at the contents of ''nfldata'' and ''mascot''.
!
<html>
<div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>

These pages (tabs above) are a collection of the various R figures that have been generated by the group. 
</html>
!!
1. [[A web overview called "Quick-R"|QuickR]]
2. [[Some good bioinformatics type applications|CockR]]
!!
/***
|Name:|HideWhenPlugin|
|Description:|Allows conditional inclusion/exclusion in templates|
|Version:|3.1 ($Rev: 3919 $)|
|Date:|$Date: 2008-03-13 02:03:12 +1000 (Thu, 13 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#HideWhenPlugin|
|Author:|Simon Baird <simon.baird@gmail.com>|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
For use in ViewTemplate and EditTemplate. Example usage:
{{{<div macro="showWhenTagged Task">[[TaskToolbar]]</div>}}}
{{{<div macro="showWhen tiddler.modifier == 'BartSimpson'"><img src="bart.gif"/></div>}}}
***/
//{{{

window.hideWhenLastTest = false;

window.removeElementWhen = function(test,place) {
	window.hideWhenLastTest = test;
	if (test) {
		removeChildren(place);
		place.parentNode.removeChild(place);
	}
};


merge(config.macros,{

	hideWhen: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( eval(paramString), place);
	}},

	showWhen: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !eval(paramString), place);
	}},

	hideWhenTagged: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.tags.containsAll(params), place);
	}},

	showWhenTagged: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !tiddler.tags.containsAll(params), place);
	}},

	hideWhenTaggedAny: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.tags.containsAny(params), place);
	}},

	showWhenTaggedAny: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !tiddler.tags.containsAny(params), place);
	}},

	hideWhenTaggedAll: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.tags.containsAll(params), place);
	}},

	showWhenTaggedAll: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !tiddler.tags.containsAll(params), place);
	}},

	hideWhenExists: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( store.tiddlerExists(params[0]) || store.isShadowTiddler(params[0]), place);
	}},

	showWhenExists: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !(store.tiddlerExists(params[0]) || store.isShadowTiddler(params[0])), place);
	}},

	hideWhenTitleIs: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.title == params[0], place);
	}},

	showWhenTitleIs: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.title != params[0], place);
	}},

	'else': { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !window.hideWhenLastTest, place);
	}}

});

//}}}


/***
|''Name:''|HistoryPlugin|
|''Description:''|Limits to only one tiddler open. Manages an history stack and provides macro to navigate in this history (<<history>><<back>><<forward>>).|
|''Version:''|1.0.0|
|''Date:''|2008-03-23|
|''Source:''|http://tiddlywiki.bidix.info/#HistoryPlugin|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''[[License]]:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.3.0|
***/
//{{{
	Story.prototype.tiddlerHistory = [];
	Story.prototype.historyCurrentPos = -1;
	Story.prototype.currentTiddler = null;
	Story.prototype.maxPos = 11;

	Story.prototype.old_history_displayTiddler = Story.prototype.displayTiddler;
	Story.prototype.displayTiddler = function(srcElement,title,template,animate,slowly)
	{
		title = ((typeof title === "string") ? title : title.title);
		//SinglePageMode
		if (this.currentTiddler) this.closeTiddler(this.currentTiddler);
		if (template == 2) {
			//switch to Edit mode : don't manage
			story.old_history_displayTiddler(null,title,template,animate,slowly);
			return; 
		}
		// if same tiddler no change
		if (this.tiddlerHistory[this.historyCurrentPos] == title) {
			this.currentTiddler = title;
			story.old_history_displayTiddler(null,title,template,animate,slowly);
			return;
		}
		if (this.historyCurrentPos == this.tiddlerHistory.length -1) {
			// bottom of stack
	    	this.tiddlerHistory.push(title);
		   	if (this.tiddlerHistory.length > 11) {
	                 this.tiddlerHistory.shift();
	       	} else {
		    this.historyCurrentPos += 1;
	            }

		} else {
			// middle of stack
		    this.historyCurrentPos += 1;
			if (this.tiddlerHistory[this.historyCurrentPos] != title) {
				// path change => cut history
				this.tiddlerHistory[this.historyCurrentPos] = title;
				var a = [];
				for(var i = 0; i <= this.historyCurrentPos;i++) {
					a[i] = this.tiddlerHistory[i];
				}
				this.tiddlerHistory = a;
			}
		}
		this.currentTiddler = title;
		story.old_history_displayTiddler(null,title,template,animate,true);
	        scrollTo(0, 1);
	}

	Story.prototype.old_history_closeTiddler = Story.prototype.closeTiddler;
	Story.prototype.closeTiddler = function(title,animate,slowly)
	{
		this.currentTiddler = null;
	    story.old_history_closeTiddler.apply(this,arguments);
	}

	config.macros.history = {};
	config.macros.history.action = function(event) {
	var popup = Popup.create(this);
		if(popup)
			{
	        if (!story.tiddlerHistory.length)
	            createTiddlyText(popup,"No history");
	        else
	           {
	           var c = story.tiddlerHistory.length;
			   for (i=0; i<c;i++ )
	               {
					var elmt = createTiddlyElement(popup,"li");
				   	var btn = createTiddlyButton(elmt,story.tiddlerHistory[i],story.tiddlerHistory[i],config.macros.history.onClick);
					btn.setAttribute("historyPos",i);
			       }
	           }
	        }
		Popup.show(popup,false);
		event.cancelBubble = true;
		if (event.stopPropagation) event.stopPropagation();
		return false;
	}
	config.macros.history.handler = function(place,macroName,params)
	{
		createTiddlyButton(place, 'history', 'history', config.macros.history.action);
	}

	config.macros.history.onClick = function(ev)
	{
		var e = ev ? ev : window.event;
		var historyPos = this.getAttribute("historyPos");
		story.historyCurrentPos = historyPos -1;
		story.displayTiddler(null,story.tiddlerHistory[historyPos]);
		return false;
	};

	config.macros.back = {};
	config.macros.back.action = function() {
	       if (story.historyCurrentPos > 0) {
				if (story.currentTiddler) story.closeTiddler(story.currentTiddler);
				story.historyCurrentPos = story.historyCurrentPos -2;
				story.displayTiddler(null,story.tiddlerHistory[story.historyCurrentPos+1]);
			} else {
				//if (story.currentTiddler) story.old_history_displayTiddler(null,story.currentTiddler);
				};
		return false;
	}
	config.macros.back.handler = function(place,macroName,params)
	{
		createTiddlyButton(place, '<<', 'back', config.macros.back.action,"backButton");
	}

	config.macros.forward = {};
	config.macros.forward.action = function() {
	       if (story.historyCurrentPos < story.tiddlerHistory.length -1) {
				if (story.currentTiddler) story.closeTiddler(story.currentTiddler);
				//story.historyCurrentPos = story.historyCurrentPos;
				story.displayTiddler(null,story.tiddlerHistory[story.historyCurrentPos+1]);
			} else {
				//if (story.currentTiddler) story.old_history_displayTiddler(null,story.currentTiddler);
			}
		return false;
	}
	config.macros.forward.handler = function(place,macroName,params)
	{
		createTiddlyButton(place, '>>', 'forward', config.macros.forward.action, "ibutton");
	}
//}}}
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='INTRO' macro='tiddler INTROSubtopicMenu'></div>
<div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>

<!--}}}-->
{{{
<html><img src="00/xxxx.png" style="height:300px"></html>
}}}

{{{
<html><table><tr>

<td><img src="00/xxxx.png" style="height:300px"></td>
<td><img src="00/xxxx.png" style="height:300px"></td>
</tr></table></html>

}}}
/***
|Name|InlineJavascriptPlugin|
|Source|http://www.TiddlyTools.com/#InlineJavascriptPlugin|
|Documentation|http://www.TiddlyTools.com/#InlineJavascriptPluginInfo|
|Version|1.9.2|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides||
|Description|Insert Javascript executable code directly into your tiddler content.|
''Call directly into TW core utility routines, define new functions, calculate values, add dynamically-generated TiddlyWiki-formatted output'' into tiddler content, or perform any other programmatic actions each time the tiddler is rendered.
!!!!!Documentation
>see [[InlineJavascriptPluginInfo]]
!!!!!Revisions
<<<
2008.03.03 [1.9.2] corrected declaration of wikifyPlainText() for 'TW 2.1.x compatibility fallback' (fixes Safari "parse error")
2008.02.23 [1.9.1] in onclick function, use string instead of array for 'bufferedHTML' attribute on link element (fixes IE errors)
2008.02.21 [1.9.0] 'onclick' scripts now allow returned text (or document.write() calls) to be wikified into a span that immediately follows the onclick link.  Also, added default 'return false' handling if no return value provided (prevents HREF from being triggered -- return TRUE to allow HREF to be processed).  Thanks to Xavier Verges for suggestion and preliminary code.
|please see [[InlineJavascriptPluginInfo]] for additional revision details|
2005.11.08 [1.0.0] initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.inlineJavascript= {major: 1, minor: 9, revision: 2, date: new Date(2008,3,3)};

config.formatters.push( {
	name: "inlineJavascript",
	match: "\\<script",
	lookahead: "\\<script(?: src=\\\"((?:.|\\n)*?)\\\")?(?: label=\\\"((?:.|\\n)*?)\\\")?(?: title=\\\"((?:.|\\n)*?)\\\")?(?: key=\\\"((?:.|\\n)*?)\\\")?( show)?\\>((?:.|\\n)*?)\\</script\\>",

	handler: function(w) {
		var lookaheadRegExp = new RegExp(this.lookahead,"mg");
		lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = lookaheadRegExp.exec(w.source)
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var src=lookaheadMatch[1];
			var label=lookaheadMatch[2];
			var tip=lookaheadMatch[3];
			var key=lookaheadMatch[4];
			var show=lookaheadMatch[5];
			var code=lookaheadMatch[6];
			if (src) { // load a script library
				// make script tag, set src, add to body to execute, then remove for cleanup
				var script = document.createElement("script"); script.src = src;
				document.body.appendChild(script); document.body.removeChild(script);
			}
			if (code) { // there is script code
				if (show) // show inline script code in tiddler output
					wikify("{{{\n"+lookaheadMatch[0]+"\n}}}\n",w.output);
				if (label) { // create a link to an 'onclick' script
					// add a link, define click handler, save code in link (pass 'place'), set link attributes
					var link=createTiddlyElement(w.output,"a",null,"tiddlyLinkExisting",wikifyPlainText(label));
					var fixup=code.replace(/document.write\s*\(/gi,'place.bufferedHTML+=(');
					link.code="function _out(place){"+fixup+"\n};_out(this);"

					link.tiddler=w.tiddler;
					link.onclick=function(){
						this.bufferedHTML="";
						try{ var r=eval(this.code);
							if(this.bufferedHTML.length || (typeof(r)==="string")&&r.length)
								var s=this.parentNode.insertBefore(document.createElement("span"),this.nextSibling);
							if(this.bufferedHTML.length)
								s.innerHTML=this.bufferedHTML;
							if((typeof(r)==="string")&&r.length) {
								wikify(r,s,null,this.tiddler);
								return false;
							} else return r!==undefined?r:false;
						} catch(e){alert(e.description||e.toString());return false;}
					};
					link.setAttribute("title",tip||"");
					var URIcode='javascript:void(eval(decodeURIComponent(%22(function(){try{';
					URIcode+=encodeURIComponent(encodeURIComponent(code.replace(/\n/g,' ')));
					URIcode+='}catch(e){alert(e.description||e.toString())}})()%22)))';
					link.setAttribute("href",URIcode);
					link.style.cursor="pointer";
					if (key) link.accessKey=key.substr(0,1); // single character only
				}
				else { // run inline script code
					var fixup=code.replace(/document.write\s*\(/gi,'place.innerHTML+=(');
					var code="function _out(place){"+fixup+"\n};_out(w.output);"

					try { var out=eval(code); } catch(e) { out=e.description?e.description:e.toString(); }
					if (out && out.length) wikify(out,w.output,w.highlightRegExp,w.tiddler);
				}
			}
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
		}
	}
} )
//}}}

// // Backward-compatibility for TW2.1.x and earlier
//{{{
if (typeof(wikifyPlainText)=="undefined") window.wikifyPlainText=function(text,limit,tiddler) {
	if(limit > 0) text = text.substr(0,limit);
	var wikifier = new Wikifier(text,formatter,null,tiddler);
	return wikifier.wikifyPlain();
}
//}}}
!Basic instructions
#Download the file to your hard drive by [[right-clicking and saving the link / target as...|webviewtw.html]] to the filename and location of your choice. Close this page and open your new file.
#Replace the title in the upper left by editing MainMenu.
#Add topics to MainMenu. Click on those topics to create the tiddlers for those topics. To your uninitiated web viewers they will appear to be separate webpages, but you and I know better!
#Edit DefaultTiddlers to include the names of the tiddlers that you want to appear when the ~TiddlyWiki is opened.
#If you want different colorpalettes than the ones provided, check [[here|http://www.giffmex.org/webviewtwexample.html#MoreColorPalettes!]] for more. Just import them from that file to this file.
#If you want to temporarily suspend the single-page-only feature, I recommend the toggle singlepage mode bookmarklet from ~TiddlyTools [[(link here)|http://www.tiddlytools.com/#InstantBookmarklets.]]
#Upload to your site using the UploadPlugin. [[Instructions here|http://www.giffmex.org/twfortherestofus.html#%5B%5BSimple%20instructions%20for%20BidiX's%20UploadPlugin%5D%5D]]
!15 AUG Introduction:
We are going to work with some of Dominique Cowart's data for developmental rates of an Antarctic sea urchin, //Sterechinus neumayeri//. During the course of her experiments, she used several batches of embryos (different parents) and what we want to examine here is whether or not in the control salinity at 34 o/oo there were any significant differences in developmental rates among those embryo cohorts.
<html><table><tr>
<td><img src="0808/McM--2005-08-31-912.jpg" style="height:170px"></td>
<td><img src="0808/Sterechinus-neumayeri.png" style="height:170px"></td>
</tr></table></html>
Individual embryos were placed in a 96-well incubation plate (below left) and then scored at 8 h time intervals for early cleavage stages. The cell division rate for each embryo was obtained as a linear regression of number of divisions per unit time (d^^-1^^) (below right).
<html><table><tr>
<td><img src="0808/Plate1.png" style="height:200px"></td>
<td><img src="0808/SnDevoRate.png" style="height:200px"></td>
</tr></table></html>
The data set we will be analyzing as a development rate for each individual embryo (n = 252) where each embryo is categorized to a replicate group within a cohort group:
|>|!Culture A|!Culture B|>|!Culture C|>|!Culture D|
| plate-A | plate-B | plate-A | plate-A | plate-B | plate-A | plate-B |
| 1.2560 | 1.2976 | 1.2357 | 1.4378 | 1.3965 | 1.1234 | 1.1986 |
| ... | ... | ... | ... | ... | ... | ... |
However, the data are not balanced in that ''Culture B'' has only one replicate and observation numbers are unequal among the replicates . . . which is very typical for any large experiment where everything doesn't quite go exactly the way you plan it out.
!
!Layers, Aesthetics, Grobs
ggplot2 is a powerful system of advanced plotting procedures. It uses the R "plot" functions but essentially contains a library of sophisticated default settings. Although it is described as an advanced graphics development tool, it still just uses the R plot functionality.

Rule #1: When in doubt, go to the [[ggplot2 website|http://had.co.nz/ggplot2/]]

Three primary elements:
# Layers
# Aesthetics
# Grobs
!
<html>

<div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>
Here are a series of PPT lectures developed for different R topics in a statistics course prepared by Garib N. Murshudov, University of York  (http://www.ysbl.york.ac.uk/~garib/mres_course/) 
</html>

@@LECTURES@@
1. [[Basic concepts from probability theory|00/Lecture01.ppt]]
2. [[Some standard probability distributions|00/Lecture02.ppt]]
3. [[Sampling and sampling distributions|00/Lecture03.ppt]]
4. [[Point estimation, interval estimation|00/Lecture04.ppt]]
5. [[Elementary hypothesis testing|00/Lecture05.ppt]]
6. [[Maximum likelihood|00/Lecture06.ppt]]
7. [[Bayesian estimation|00/Lecture07.ppt]]
8. [[Resampling techniques|00/Lecture08.ppt]]
9. [[Linear and generalised linear models|00/Lecture09.ppt]]
10. [[Basics of ANOVA|00/Lecture10.ppt]]
11. [[Log-linear and logistic models|00/Lecture11.ppt]]
12. [[Principal Component Analysis|00/Lecture12.ppt]]
13. [[Elements of factor analysis|00/Lecture13.ppt]]
14. [[Correspondence analysis|00/Lecture14.ppt]]
15. [[Metric scaling techniques|00/Lecture15.ppt]]
16. [[Elements of cluster analysis|00/Lecture16.ppt]]
17. [[Basics of procrustes analysis|00/Lecture17.ppt]] 
!!
/***
|''Name:''|LegacyStrikeThroughPlugin|
|''Description:''|Support for legacy (pre 2.1) strike through formatting|
|''Version:''|1.0.2|
|''Date:''|Jul 21, 2006|
|''Source:''|http://www.tiddlywiki.com/#LegacyStrikeThroughPlugin|
|''Author:''|MartinBudden (mjbudden (at) gmail (dot) com)|
|''License:''|[[BSD open source license]]|
|''CoreVersion:''|2.1.0|
***/

//{{{
// Ensure that the LegacyStrikeThrough Plugin is only installed once.
if(!version.extensions.LegacyStrikeThroughPlugin) {
version.extensions.LegacyStrikeThroughPlugin = {installed:true};

config.formatters.push(
{
	name: "legacyStrikeByChar",
	match: "==",
	termRegExp: /(==)/mg,
	element: "strike",
	handler: config.formatterHelpers.createElementAndWikify
});

} //# end of "install only once"

//}}}
{{menubox2{<html><div style="color: rgb(100, 100, 200); font-family: Monaco;"><big>We R Group</html>}}}{{menubox3{[img[00/r1.png]]}}}
<<search>>
!CONTENTS:
[[FrontPage]]
1. [[Resources|Software]]
2. [[Session Summaries]]
3. [[Calendar]]
4. [[Topics]]
5. [[Gallery]]
6. [[R Group]]

!!
{{tuduSlider{<<slider chkToolbox Toolbox 'Toolbox »'>>}}}
!site tooling:
[[Setup|Welcome to the Webview TiddlyWiki]]
[[SubTopics|ConfigSubTopics]]
[[Insert Figure|InFig]]
[[Emphasis Text|TextMonaco]]
!!
























<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml'/>
<!--}}}-->

<style type="text/css">#contentWrapper {display:none;}</style><div id="SplashScreen" style="border: 3px solid #ccc; display: block; text-align: center; width: 320px; margin: 100px auto; padding: 50px; color:#000; font-size: 28px; font-family:Tahoma; background-color:#eee;"><b>We R Group Site <blink>Loading . . . </blink></b></div>
!!Overlaying data on geographic maps 
<html>
<img src="mo/Provinces1.png" style="height:300px"><br>
<img src="mo/Provinces2.png" style="height:600px"><br>

</tr></table></html>
!
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='MicroGen' macro='tiddler MicroGenSubtopicMenu'></div><div class='title' macro='view title'></div>

<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>
<!--}}}-->
//{{{
config.options.chkSearchTitles=true;
config.options.chkSearchText=true;
config.options.chkSearchTags=true;
config.options.chkSearchFields=true;
config.options.chkSearchTitlesFirst=false;
config.options.chkSearchList=true;
config.options.chkSearchByDate=false;
config.options.chkSearchIncremental=true;
config.options.chkSearchShadows=false; 
//}}}
<html>
<div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>

A wide array of packages or subgroups of tailored scripts are available for R. Those that we are  'trying' to learn are listed below along with links to whatever documentation is available for them. 
</html>

@@PACKAGES@@
1. [[ADE4 is a comprehensive multivariate statistics package |00/ade4.pdf]]
2. [[GGPLOT2 is a very slick graphics package for high-end figures|ggplot2]]
3. [[MELT is a utility for re-arranging data matrices|00/R-melt-manual.pdf]]
!!
<!--{{{-->
<div id='mainMenu' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>

<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
/***
|''Name:''|PasswordOptionPlugin|
|''Description:''|Extends TiddlyWiki options with non encrypted password option.|
|''Version:''|1.0.2|
|''Date:''|Apr 19, 2007|
|''Source:''|http://tiddlywiki.bidix.info/#PasswordOptionPlugin|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''License:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.2.0 (Beta 5)|
***/
//{{{
version.extensions.PasswordOptionPlugin = {
	major: 1, minor: 0, revision: 2, 
	date: new Date("Apr 19, 2007"),
	source: 'http://tiddlywiki.bidix.info/#PasswordOptionPlugin',
	author: 'BidiX (BidiX (at) bidix (dot) info',
	license: '[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D]]',
	coreVersion: '2.2.0 (Beta 5)'
};

config.macros.option.passwordCheckboxLabel = "Save this password on this computer";
config.macros.option.passwordInputType = "password"; // password | text
setStylesheet(".pasOptionInput {width: 11em;}\n","passwordInputTypeStyle");

merge(config.macros.option.types, {
	'pas': {
		elementType: "input",
		valueField: "value",
		eventName: "onkeyup",
		className: "pasOptionInput",
		typeValue: config.macros.option.passwordInputType,
		create: function(place,type,opt,className,desc) {
			// password field
			config.macros.option.genericCreate(place,'pas',opt,className,desc);
			// checkbox linked with this password "save this password on this computer"

			config.macros.option.genericCreate(place,'chk','chk'+opt,className,desc);			
			// text savePasswordCheckboxLabel
			place.appendChild(document.createTextNode(config.macros.option.passwordCheckboxLabel));
		},
		onChange: config.macros.option.genericOnChange
	}
});

merge(config.optionHandlers['chk'], {
	get: function(name) {
		// is there an option linked with this chk ?
		var opt = name.substr(3);
		if (config.options[opt]) 
			saveOptionCookie(opt);
		return config.options[name] ? "true" : "false";
	}
});

merge(config.optionHandlers, {
	'pas': {
 		get: function(name) {
			if (config.options["chk"+name]) {
				return encodeCookie(config.options[name].toString());
			} else {
				return "";
			}
		},
		set: function(name,value) {config.options[name] = decodeCookie(value);}
	}
});

// need to reload options to load passwordOptions
loadOptionsCookie();

/*
if (!config.options['pasPassword'])
	config.options['pasPassword'] = '';

merge(config.optionsDesc,{
		pasPassword: "Test password"
	});
*/
//}}}
!Plotting Code
{{{
# Effect of Salinity of Respiration Rates of Sterechinus neumayeri
# Variables: salinity, development time, culture

# startup ggplot routines - - - - - - - - - - - - - - - - - - - - 
	library(ggplot2)
	
# import dataframe - - - - - - - - - - - - - - - - - - - - 
setwd("/Users/agm/01-WORK/05-Courses/2008.2-Rgroup/080909")
d=read.table("http://icewater.cms.udel.edu/Rgroup/080909/Sn-RespDevoSalinity.txt", sep='\t', header=T)
summary(d)
d$Salinity <- as.factor(d$Salinity)
names(d)[3] <- c("Resp")
D <- d[which(d$Resp < 500),]

# first data plot - - - - - - - - - - - - - - - - - - - 
p <- ggplot(data=D, aes(y=Resp,x=HPF)) + geom_point()
p

# second data plot - - - - - - - - - - - - - - - - - - - 
p <- ggplot(data=D, aes(y=Resp,x=HPF)) + 
	geom_point(aes(colour=Salinity))
p

# third data plot - - - - - - - - - - - - - - - - - - - 
p <- ggplot(data=D, aes(y=Resp,x=HPF)) +
	geom_point(aes(colour=Salinity)) +
	facet_grid(Salinity~.)
p


# create new dataframe with means and sd by trts - - - - - - - - - 
Dx  = aggregate(D$Resp, list(D$Salinity,D$HPF), mean)
names(Dx)[1] <- c("Salinity")
names(Dx)[2] <- c("HPF")
names(Dx)[3] <- c("Resp")
Dsd = aggregate(D$Resp, list(D$Salinity,D$HPF), sd)
names(Dsd)[3] <- c("sd")
Dx$sd <- Dsd$sd
Dx$high <- Dx$Resp+Dx$sd
Dx$low  <- Dx$Resp-Dx$sd

# xy mean plot - - - - - - - - - - - - - - -
p <-ggplot(data=Dx, aes(y=Resp,x=HPF)) +
	geom_errorbar(aes(max=high, min=low),width=0.2,colour="black") +
	geom_line(aes(colour=Salinity),size=2) +
	geom_point(aes(colour=as.factor(HPF)),size=3) +
	scale_y_continuous("Respiration Rate") +
	scale_x_continuous("Hours Post-Fertilization") +
	facet_grid(Salinity~.)
p$legend.position<-c("none")	
p

# stat_summary plot option - - - - - - - - - - - - 
library(Hmisc)
p <- NULL
p <-ggplot(data=D, aes(y=Resp,x=HPF)) +
	stat_summary(fun="mean_sdl", geom="errorbar", mult=1) +	stat_summary(fun="mean", geom="line", colour="red", size = 2) +
	stat_summary(fun="mean", geom="point", colour="blue", size = 3) +
	scale_y_continuous("Respiration Rate") +
	scale_x_continuous("Hours Post-Fertilization") +
	facet_grid(Salinity~.)
p$legend.position<-c("none")
p$background.fill <- c("white")
p$background.colour <- c("blue")
p

# list the GRID objects in the plot
grid.ls(grobs=TRUE)

# edit font size and font color of all labels . . . . 
grid.gedit("label", gp=gpar(fontsize=12, col="black"))
grid.gedit("ylabel", gp=gpar(fontsize=16, col="black"))
grid.gedit("xlabel", gp=gpar(fontsize=16, col="blue"))
grid.gedit(gPath("xaxis","label"), gp=gpar(fontsize=18))
}}}
!!Plot 1
<html><img src="080909/plot0.png" style="height:300px"></html>
!!Plot 2
<html><img src="080909/plot1.png" style="height:300px"></html>
!!Plot 3
<html><img src="080909/plot2.png" style="height:300px"></html>
!

{{tableindex{
|[[Ryan]]|[[Stephanie]]|[[Matt]]|[[Doug]]|[[Pat]]|[[Adam]]|
}}}
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='Plots' macro='tiddler PlotsSubtopicMenu'></div><div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>

<!--}}}-->
This a very thorough overview of R. It covers a lot of territory and is probably not a good site on which to start trying to learn R, but a great secondary site when you are ready to learn moRe . . . .
<html><img src="00/quickR.png" style="height:300px"></html>

[[QUICK-R Guide Link HERE|http://www.statmethods.net/index.html]]
!!!
<html><div style="color: rgb(100, 100, 150); font-family: Monaco;">
<img src="00/anim-codingpain.gif"><br>
<div style="color: rgb(20, 20, 200);"><big><b><i>coding is only just pain</i></b>

</html>
!Participant List:
|! NAME |! username at udel.edu |
|Doug Miller |dmiller |
|Matt Oliver |moliver |
|Adam Marsh |amarsh |
|Ryan Dale |ryandale |
|Tiffany Straza |tstraza |
|Matt Butler |mbutler |
|David Kirchman |kirchman |
|Pat Gaffney |pgaffney |
|Stephain Guida |guida |
|Ben Ciotti |ciotti |
|Adam Pimenta |apimenta |
|Ed Hale |ehale |
|Emily Maung |emaung |
|Eric Geiger |egeiger |
|Yoana Voynova |yvoynova |
|Doug White |dw |
|Glenn Christman | glennchr |
|Sharon Grim | sgrim01-at-gmail.com |
!
{{tableindex{
|[[Software]]|[[Tutorials]]|[[Guides]]|[[Lectures]]|[[Package Documentation]]|
}}}
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>

<div class='Resources' macro='tiddler ResourcesSubtopicMenu'></div><div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>
<!--}}}-->
R is a large collection of statistics routines that you utilize through several X11 windows. It has an integral scripting command language that access the stats routines and can direct graphics output to a separate display window.
<html><img src="00/r2.png" style="height:300px"></html>

![[Download the R package here|http://www.r-project.org/index.html]]
!!
<html>
<img src="rd/033-Hcodon-Haa-real.png" style="height:300px">
<img src="rd/033-Hcodon-Haa-synthetic.png" style="height:300px">

<img src="rd/RD-aafreq-vs-gc.png" style="height:100px">
</html>
//{{{
window.reportSearchResults=function(text,matches)
{
	var title=config.macros.search.reportTitle
	var q = config.options.chkRegExpSearch ? "/" : "'";
	var body="\n";

	// numbered list of links to matching tiddlers
	body+="\n<<<";
	for(var t=0;t<matches.length;t++) {
		var date=config.options.chkSearchByDate?(matches[t].modified.formatString('YYYY.0MM.0DD 0hh:0mm')+" "):"";
		body+="\n# "+date+"[["+matches[t].title+"]]";
	}
	body+="\n<<<\n";

	// create/update the tiddler
	var tiddler=store.getTiddler(title); if (!tiddler) tiddler=new Tiddler();
	tiddler.set(title,body,config.options.txtUserName,(new Date()),"excludeLists excludeSearch");
	store.addTiddler(tiddler); story.closeTiddler(title);

	// use alternate "search again" label in <<search>> macro
	var oldprompt=config.macros.search.label;
	config.macros.search.label="search again";

	// render/refresh tiddler
	story.displayTiddler(null,title,1);
	store.notify(title,true);

	// restore standard search label
	config.macros.search.label=oldprompt;

}

//}}}
/***
|Name|SearchOptionsPlugin|
|Source|http://www.TiddlyTools.com/#SearchOptionsPlugin|
|Documentation|http://www.TiddlyTools.com/#SearchOptionsPluginInfo|
|Version|2.6.1|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides|Story.prototype.search, TiddlyWiki.prototype.search, config.macros.search.onKeyPress|
|Description|extend core search function with additional user-configurable options|
Extend core search function with additional user-configurable options including generating a ''list of matching tiddlers'' instead of immediately displaying all matches.
!!!!!Documentation
>see [[SearchOptionsPluginInfo]]
!!!!!Configuration
<<<
<<option chkSearchTitles>> Search in titles
<<option chkSearchText>> Search in tiddler text
<<option chkSearchTags>> Search in tags
<<option chkSearchFields>> Search in data fields

<<option chkSearchShadows>> Search shadow tiddlers
<<option chkSearchTitlesFirst>> Show title matches first
<<option chkSearchByDate>> Sort matching tiddlers by date
<<option chkSearchList>> Show list of matches in [[SearchResults]]
<<option chkSearchIncremental>> Incremental (key-by-key) searching
<<<
!!!!!Revisions

<<<
2007.02.17 [2.6.1] added redefinition of config.macros.search.onKeyPress() to restore check to bypass key-by-key searching (i.e., when chkSearchIncremental==false), which had been unintentionally removed with v2.6.0
|please see [[SearchOptionsPluginInfo]] for additional revision details|
2005.10.18 [1.0.0] Initial Release
<<<
!!!!!Code
***/
//{{{
version.extensions.searchOptions = {major: 2, minor: 6, revision: 1, date: new Date(2007,2,17)};

if (config.options.chkSearchTitles===undefined) config.options.chkSearchTitles=true;
if (config.options.chkSearchText===undefined) config.options.chkSearchText=true;
if (config.options.chkSearchTags===undefined) config.options.chkSearchTags=true;
if (config.options.chkSearchFields===undefined) config.options.chkSearchFields=true;
if (config.options.chkSearchTitlesFirst===undefined) config.options.chkSearchTitlesFirst=false;
if (config.options.chkSearchList===undefined) config.options.chkSearchList=false;
if (config.options.chkSearchByDate===undefined) config.options.chkSearchByDate=false;
if (config.options.chkSearchIncremental===undefined) config.options.chkSearchIncremental=true;
if (config.options.chkSearchShadows===undefined) config.options.chkSearchShadows=false;

if (config.optionsDesc) {
	config.optionsDesc.chkSearchTitles="Search in tiddler titles";
	config.optionsDesc.chkSearchText="Search in tiddler text";
	config.optionsDesc.chkSearchTags="Search in tiddler tags";
	config.optionsDesc.chkSearchFields="Search in tiddler data fields";
	config.optionsDesc.chkSearchShadows="Search in shadow tiddlers";
	config.optionsDesc.chkSearchTitlesFirst="Search results show title matches first";
	config.optionsDesc.chkSearchList="Search results show list of matching tiddlers";
	config.optionsDesc.chkSearchByDate="Search results sorted by modification date ";
	config.optionsDesc.chkSearchIncremental="Incremental searching";
} else {
	config.shadowTiddlers.AdvancedOptions += "\n<<option chkSearchTitles>> Search in tiddler titles"

		+"\n<<option chkSearchText>> Search in tiddler text"
		+"\n<<option chkSearchTags>> Search in tiddler tags"
		+"\n<<option chkSearchFields>> Search in tiddler data fields"

		+"\n<<option chkSearchShadows>> Search in shadow tiddlers"
		+"\n<<option chkSearchTitlesFirst>> Search results show title matches first"
		+"\n<<option chkSearchList>> Search results show list of matching tiddlers"

		+"\n<<option chkSearchByDate>> Search results sorted by modification date"
		+"\n<<option chkSearchIncremental>> Incremental searching";
}

if (config.macros.search.reportTitle==undefined)
	config.macros.search.reportTitle="SearchResults";

config.macros.search.onKeyPress = function(e)
{
	if(!e) var e = window.event;
	switch(e.keyCode)
		{
		case 13: // Ctrl-Enter
		case 10: // Ctrl-Enter on IE PC
			config.macros.search.doSearch(this);
			break;
		case 27: // Escape
			this.value = "";
			clearMessage();
			break;
		}
	if (config.options.chkSearchIncremental) {
		if(this.value.length > 2)
			{
			if(this.value != this.getAttribute("lastSearchText"))
				{
				if(config.macros.search.timeout)
					clearTimeout(config.macros.search.timeout);
				var txt = this;
				config.macros.search.timeout = setTimeout(function() {config.macros.search.doSearch(txt);},500);
				}
			}
		else
			{
			if(config.macros.search.timeout)
				clearTimeout(config.macros.search.timeout);
			}
	}
}
//}}}

//{{{
Story.prototype.search = function(text,useCaseSensitive,useRegExp)
{
	highlightHack = new RegExp(useRegExp ? text : text.escapeRegExp(),useCaseSensitive ? "mg" : "img");
	var matches = store.search(highlightHack,config.options.chkSearchByDate?"modified":"title","excludeSearch");
	if (config.options.chkSearchByDate) matches=matches.reverse(); // most recent changes first
	var q = useRegExp ? "/" : "'";
	clearMessage();
	if (!matches.length) {
		if (config.options.chkSearchList) discardSearchResults();
		displayMessage(config.macros.search.failureMsg.format([q+text+q]));
	} else {
		if (config.options.chkSearchList) 
			reportSearchResults(text,matches);
		else {
			var titles = []; for(var t=0; t<matches.length; t++) titles.push(matches[t].title);
			this.closeAllTiddlers(); story.displayTiddlers(null,titles);
			displayMessage(config.macros.search.successMsg.format([matches.length, q+text+q]));
		}
	}
	highlightHack = null;
}

TiddlyWiki.prototype.search = function(searchRegExp,sortField,excludeTag)
{
	var candidates = this.reverseLookup("tags",excludeTag,false,sortField);

	// scan for matching titles first...
	var results = [];
	if (config.options.chkSearchTitles) {
		for(var t=0; t<candidates.length; t++)
			if(candidates[t].title.search(searchRegExp)!=-1)
				results.push(candidates[t]);
		if (config.options.chkSearchShadows)
			for (var t in config.shadowTiddlers)
				if ((t.search(searchRegExp)!=-1) && !store.tiddlerExists(t))
					results.push((new Tiddler()).assign(t,config.shadowTiddlers[t]));
	}
	// then scan for matching text, tags, or field data
	for(var t=0; t<candidates.length; t++) {
		if (config.options.chkSearchText && candidates[t].text.search(searchRegExp)!=-1)
			results.pushUnique(candidates[t]);
		if (config.options.chkSearchTags && candidates[t].tags.join(" ").search(searchRegExp)!=-1)
			results.pushUnique(candidates[t]);
		if (config.options.chkSearchFields && store.forEachField!=undefined) // requires TW2.1 or above
			store.forEachField(candidates[t],
				function(tid,field,val) { if (val.search(searchRegExp)!=-1) results.pushUnique(candidates[t]); },
				true); // extended fields only
	}
	// then check for matching text in shadows
	if (config.options.chkSearchShadows)
		for (var t in config.shadowTiddlers)
			if ((config.shadowTiddlers[t].search(searchRegExp)!=-1) && !store.tiddlerExists(t))
				results.pushUnique((new Tiddler()).assign(t,config.shadowTiddlers[t]));

	// if not 'titles first', or sorting by modification date,  re-sort results to so titles, text, tag and field matches are mixed together
	if(!sortField) sortField = "title";
	var bySortField=function (a,b) {if(a[sortField] == b[sortField]) return(0); else return (a[sortField] < b[sortField]) ? -1 : +1; }
	if (!config.options.chkSearchTitlesFirst || config.options.chkSearchByDate) results.sort(bySortField);

	return results;
}

// REPORT GENERATOR
if (!window.reportSearchResults) window.reportSearchResults=function(text,matches)
{
	var title=config.macros.search.reportTitle
	var q = config.options.chkRegExpSearch ? "/" : "'";
	var body="\n";

	// summary: nn tiddlers found matching '...', options used
	body+="''"+config.macros.search.successMsg.format([matches.length,q+"{{{"+text+"}}}"+q])+"''\n";
	body+="^^//searched in:// ";
	body+=(config.options.chkSearchTitles?"''titles'' ":"");
	body+=(config.options.chkSearchText?"''text'' ":"");
	body+=(config.options.chkSearchTags?"''tags'' ":"");
	body+=(config.options.chkSearchFields?"''fields'' ":"");
	body+=(config.options.chkSearchShadows?"''shadows'' ":"");
	if (config.options.chkCaseSensitiveSearch||config.options.chkRegExpSearch) {
		body+=" //with options:// ";
		body+=(config.options.chkCaseSensitiveSearch?"''case sensitive'' ":"");
		body+=(config.options.chkRegExpSearch?"''text patterns'' ":"");
	}
	body+="^^";

	// numbered list of links to matching tiddlers
	body+="\n<<<";
	for(var t=0;t<matches.length;t++) {
		var date=config.options.chkSearchByDate?(matches[t].modified.formatString('YYYY.0MM.0DD 0hh:0mm')+" "):"";
		body+="\n# "+date+"[["+matches[t].title+"]]";
	}
	body+="\n<<<\n";

	// open all matches button
	body+="<html><input type=\"button\" href=\"javascript:;\" ";
	body+="onclick=\"story.displayTiddlers(null,["

	for(var t=0;t<matches.length;t++)
		body+="'"+matches[t].title.replace(/\'/mg,"\\'")+"'"+((t<matches.length-1)?", ":"");
	body+="],1);\" ";
	body+="accesskey=\"O\" ";
	body+="value=\"open all matching tiddlers\"></html> ";

	// discard search results button
	body+="<html><input type=\"button\" href=\"javascript:;\" ";
	body+="onclick=\"story.closeTiddler('"+title+"'); store.deleteTiddler('"+title+"'); store.notify('"+title+"',true);\" ";
	body+="value=\"discard "+title+"\"></html>";

	// search again
	body+="\n\n----\n";
	body+="<<search \""+text+"\">>\n";
	body+="<<option chkSearchTitles>>titles ";
	body+="<<option chkSearchText>>text ";
	body+="<<option chkSearchTags>>tags";
	body+="<<option chkSearchFields>>fields";
	body+="<<option chkSearchShadows>>shadows";
	body+="<<option chkCaseSensitiveSearch>>case-sensitive ";
	body+="<<option chkRegExpSearch>>text patterns";
	body+="<<option chkSearchByDate>>sort by date";

	// create/update the tiddler
	var tiddler=store.getTiddler(title); if (!tiddler) tiddler=new Tiddler();
	tiddler.set(title,body,config.options.txtUserName,(new Date()),"excludeLists excludeSearch temporary");
	store.addTiddler(tiddler); story.closeTiddler(title);

	// use alternate "search again" label in <<search>> macro
	var oldprompt=config.macros.search.label;
	config.macros.search.label="search again";

	// render/refresh tiddler
	story.displayTiddler(null,title,1);
	store.notify(title,true);

	// restore standard search label
	config.macros.search.label=oldprompt;

}

if (!window.discardSearchResults) window.discardSearchResults=function()
{
	// remove the tiddler
	story.closeTiddler(config.macros.search.reportTitle);
	store.deleteTiddler(config.macros.search.reportTitle);
}
//}}}
<<<
# [[Adam]]
# [[Intro-0909]]
<<<
/***
Quick and dirtly palette switcher for 2.1.x
<<selectPalette>>
WARNING this will overwrite your ColorPalette tiddler.
***/

//{{{

merge(config.macros,{

	setPalette: {

		handler: function(place,macroName,params,wikifier,paramString,tiddler) {
			var paletteName = params[0] ? params[0] : tiddler.title;
			createTiddlyButton(place,"apply","Apply this palette",function(e) {
				config.macros.selectPalette.updatePalette(tiddler.title);
				return false;
			});
		}
	},

	selectPalette: {

		handler: function(place,macroName,params,wikifier,paramString,tiddler) {
			createTiddlyDropDown(place,this.onPaletteChange,this.getPalettes());
		},

		getPalettes: function() {
			var result = [
				{caption:"-select palette-", name:""},
				{caption:"(Default)", name:"(default)"}
			];
			var tagged = store.getTaggedTiddlers("palette","title");
			for(var t=0; t<tagged.length; t++)
				result.push({caption:tagged[t].title, name:tagged[t].title});
			return result;
		},

		onPaletteChange: function(e) {
			config.macros.selectPalette.updatePalette(this.value);
			return true;
		},

		updatePalette: function(title) {
			if (title != "") {
				store.deleteTiddler("ColorPalette");
				if (title != "(default)")
					store.saveTiddler("ColorPalette","ColorPalette",store.getTiddlerText(title),
								config.options.txtUserName,undefined,"");
				this.refreshPalette();
				if(config.options.chkAutoSave)
					saveChanges(true);
			}
		},

		refreshPalette: function() {
			config.macros.refreshDisplay.onClick();
		}
	}
});

//}}}

!
|! Meeting Date|!Topic|!Commands| !Page Name/Link |
| 10/07: |Data Journal: Tiffany Straza | | ??? |
| 09/30: |GIS Intro | | Miller |
| 09/23: |Data Journal: Tiffinay Straza | Intro to research data | Straza |
| 09/16: |~MatLab basics | Data manipulation, stats and plots | Miller |
| @@''09/09:''@@ |Plotting with ggplot2 "aesthetic" elements | ggplot2 lib | Marsh [[09 SEP|Intro-0909]] |
| 08/15: |Running an analysis of variance| ANOVA TUKEYHSD | Marsh [[15AUG|Intro-0815]] |
| 06/27: |Data manipulation & description, continued: Useful stuff|Let's pick up where we left off last week ... around point #4 under "Manipulating data" | Miller [[27JUNE|20JUNE]] |
| 06/20: |Data manipulation & description |Various R functions for manipulating and summarizing data | Miller [[20JUNE]] |
| 06/13: |Accessing & Plotting Data |plot, ggplot| Oliver [[13JUNE]] |
| 06/06: |General Overview |getwd, dir, summary | Oliver [[06JUNE]] |
!
<<search>><<closeAll>><<permaview>><<newTiddler>><<newTiddler title:"tagnameSubtopicMenu" tag:"SubtopicMenu" label:"new subtopic menu" text:"{{tableindex{
|[[subtopic1]]|[[subtopic2]]|[[subtopic3]]|
}}}">><<newTiddler title:"tagnameViewTemplate" tag:"excludeLists" label:"new viewtemplate" text:"<!--{{{-->

<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='xxxx' macro='tiddler xxxxSubtopicMenu'></div><div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div><div class='tagClear'></div>
<!--}}}-->

">><<saveChanges>>[[Formatting cheatsheet]]<<selectPalette>><<slider chkSliderOptionsPanel OptionsPanel "options »" "Change TiddlyWiki advanced options">>

<<tabs txtMainTab "Timeline" "Timeline" TabTimeline "All" "All tiddlers" TabAll "Tags" "All tags" TabTags "More" "More lists" TabMore>>

/***
|Name|SinglePageModePlugin|
|Source|http://www.TiddlyTools.com/#SinglePageModePlugin|
|Documentation|http://www.TiddlyTools.com/#SinglePageModePluginInfo|
|Version|2.8.2|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides|Story.prototype.displayTiddler(), Story.prototype.displayTiddlers()|
|Description|Show tiddlers one at a time with automatic permalink, or always open tiddlers at top/bottom of page.|
This plugin allows you to configure TiddlyWiki to navigate more like a traditional multipage web site with only one tiddler displayed at a time.
!!!!!Documentation
>see [[SinglePageModePluginInfo]]
!!!!!Configuration
<<<
<<option chkSinglePageMode>> Display one tiddler at a time
><<option chkSinglePageKeepFoldedTiddlers>> Don't auto-close folded tiddlers
><<option chkSinglePagePermalink>> Automatically permalink current tiddler

<<option chkTopOfPageMode>> Always open tiddlers at the top of the page
<<option chkBottomOfPageMode>> Always open tiddlers at the bottom of the page
<<option chkSinglePageAutoScroll>> Automatically scroll tiddler into view (if needed)

Notes:
* The "display one tiddler at a time" option can also be //temporarily// set/reset by including a 'paramifier' in the document URL: {{{#SPM:true}}} or {{{#SPM:false}}}.
* If more than one display mode is selected, 'one at a time' display takes precedence over both 'top' and 'bottom' settings, and if 'one at a time' setting is not used, 'top of page' takes precedence over 'bottom of page'.
* When using Apple's Safari browser, automatically setting the permalink causes an error and is disabled.
<<<
!!!!!Revisions
<<<
2008.03.14 [2.8.2] in displayTiddler(), if editing specified tiddler, just move it to top/bottom of story *without* re-rendering (prevents discard of partial edits).
| Please see [[SinglePageModePluginInfo]] for previous revision details |
2005.08.15 [1.0.0] Initial Release.  Support for BACK/FORWARD buttons adapted from code developed by Clint Checketts.
<<<

!!!!!Code
***/
//{{{
version.extensions.SinglePageMode= {major: 2, minor: 8, revision: 2, date: new Date(2008,3,14)};
//}}}
//{{{
config.paramifiers.SPM = { onstart: function(v) {
	config.options.chkSinglePageMode=eval(v);
	if (config.options.chkSinglePageMode && config.options.chkSinglePagePermalink && !config.browser.isSafari) {
		config.lastURL = window.location.hash;
		if (!config.SPMTimer) config.SPMTimer=window.setInterval(function() {checkLastURL();},1000);
	}
} };
//}}}
//{{{
if (config.options.chkSinglePageMode==undefined) config.options.chkSinglePageMode=false;
if (config.options.chkSinglePageKeepFoldedTiddlers==undefined) config.options.chkSinglePageKeepFoldedTiddlers=true;
if (config.options.chkSinglePagePermalink==undefined) config.options.chkSinglePagePermalink=true;
if (config.options.chkTopOfPageMode==undefined) config.options.chkTopOfPageMode=false;
if (config.options.chkBottomOfPageMode==undefined) config.options.chkBottomOfPageMode=false;
if (config.options.chkSinglePageAutoScroll==undefined) config.options.chkSinglePageAutoScroll=true;

if (config.optionsDesc) {
	config.optionsDesc.chkSinglePageMode="Display one tiddler at a time";
	config.optionsDesc.chkSinglePageKeepFoldedTiddlers="Don't auto-close folded tiddlers";
	config.optionsDesc.chkSinglePagePermalink="Automatically permalink current tiddler";
	config.optionsDesc.chkSinglePageAutoScroll="Automatically scroll tiddler into view (if needed)";
	config.optionsDesc.chkTopOfPageMode="Always open tiddlers at the top of the page";
	config.optionsDesc.chkBottomOfPageMode="Always open tiddlers at the bottom of the page";
} else {
	config.shadowTiddlers.AdvancedOptions += "\
		\n<<option chkSinglePageMode>> Display one tiddler at a time \
		\n<<option chkSinglePageKeepFoldedTiddlers>> Don't auto-close folded tiddlers \
		\n<<option chkSinglePagePermalink>> Automatically permalink current tiddler \
		\n<<option chkSinglePageAutoScroll>> Automatically scroll tiddler into view (if needed) \
		\n<<option chkTopOfPageMode>> Always open tiddlers at the top of the page \
		\n<<option chkBottomOfPageMode>> Always open tiddlers at the bottom of the page";
}
//}}}
//{{{
config.SPMTimer = 0;
config.lastURL = window.location.hash;
function checkLastURL()
{
	if (!config.options.chkSinglePageMode)
		{ window.clearInterval(config.SPMTimer); config.SPMTimer=0; return; }
	if (config.lastURL == window.location.hash) return; // no change in hash
	var tids=convertUTF8ToUnicode(decodeURIComponent(window.location.hash.substr(1))).readBracketedList();
	if (tids.length==1) // permalink (single tiddler in URL)
		story.displayTiddler(null,tids[0]);
	else { // restore permaview or default view
		config.lastURL = window.location.hash;
		if (!tids.length) tids=store.getTiddlerText("DefaultTiddlers").readBracketedList();
		story.closeAllTiddlers();
		story.displayTiddlers(null,tids);
	}
}

if (Story.prototype.SPM_coreDisplayTiddler==undefined)
	Story.prototype.SPM_coreDisplayTiddler=Story.prototype.displayTiddler;
Story.prototype.displayTiddler = function(srcElement,title,template,animate,slowly)
{
	var opt=config.options;
	if (opt.chkSinglePageMode) {
		// close all tiddlers except current tiddler, tiddlers being edited, and tiddlers that are folded (optional)
		story.forEachTiddler(function(tid,elem) {
			if (	tid==title
				|| elem.getAttribute("dirty")=="true"

				|| (opt.chkSinglePageKeepFoldedTiddlers && elem.getAttribute("folded")=="true"))
				return;
			story.closeTiddler(tid);
		});
	}
	else if (opt.chkTopOfPageMode)
		arguments[0]=null;
	else if (opt.chkBottomOfPageMode)
		arguments[0]="bottom";
	if (opt.chkSinglePageMode && opt.chkSinglePagePermalink && !config.browser.isSafari) {
		window.location.hash = encodeURIComponent(convertUnicodeToUTF8(String.encodeTiddlyLink(title)));
		config.lastURL = window.location.hash;
		document.title = wikifyPlain("SiteTitle") + " - " + title;
		if (!config.SPMTimer) config.SPMTimer=window.setInterval(function() {checkLastURL();},1000);
	}
	var tiddlerElem=document.getElementById(story.idPrefix+title); // ==null unless tiddler is already display
	if (tiddlerElem && tiddlerElem.getAttribute("dirty")=="true") { // editing... move tiddler without re-rendering
		var isTopTiddler=(tiddlerElem.previousSibling==null);
		if (!isTopTiddler && (opt.chkSinglePageMode || opt.chkTopOfPageMode))
			tiddlerElem.parentNode.insertBefore(tiddlerElem,tiddlerElem.parentNode.firstChild);
		else if (opt.chkBottomOfPageMode)
			tiddlerElem.parentNode.insertBefore(tiddlerElem,null);
		else this.SPM_coreDisplayTiddler.apply(this,arguments); // let CORE render tiddler
	} else
		this.SPM_coreDisplayTiddler.apply(this,arguments); // let CORE render tiddler
	var tiddlerElem=document.getElementById(story.idPrefix+title);
	if (tiddlerElem&&opt.chkSinglePageAutoScroll) {
		var yPos=ensureVisible(tiddlerElem); // scroll to top of tiddler
		var isTopTiddler=(tiddlerElem.previousSibling==null);
		if (opt.chkSinglePageMode||opt.chkTopOfPageMode||isTopTiddler)
			yPos=0; // scroll to top of page instead of top of tiddler
		if (opt.chkAnimate) // defer scroll until 200ms after animation completes
			setTimeout("window.scrollTo(0,"+yPos+")",config.animDuration+200); 
		else
			window.scrollTo(0,yPos); // scroll immediately
	}
}

if (Story.prototype.SPM_coreDisplayTiddlers==undefined)
	Story.prototype.SPM_coreDisplayTiddlers=Story.prototype.displayTiddlers;

Story.prototype.displayTiddlers = function() {
	// suspend single-page mode (and/or top/bottom display options) when showing multiple tiddlers
	var opt=config.options;
	var saveSPM=opt.chkSinglePageMode; opt.chkSinglePageMode=false;
	var saveTPM=opt.chkTopOfPageMode; opt.chkTopOfPageMode=false;
	var saveBPM=opt.chkBottomOfPageMode; opt.chkBottomOfPageMode=false;
	this.SPM_coreDisplayTiddlers.apply(this,arguments);
	opt.chkBottomOfPageMode=saveBPM;
	opt.chkTopOfPageMode=saveTPM;
	opt.chkSinglePageMode=saveSPM;
}
//}}}

CMES R Group
<html>
<div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>
These are the primary sources for getting R running on your computer.

</html>
1. [[Main page for R program information and download.|Rpackage]]
!!
/***
|''Name:''|SparklinePlugin|
|''Description:''|Sparklines macro|
***/
//{{{
if(!version.extensions.SparklinePlugin) {
version.extensions.SparklinePlugin = {installed:true};

//--
//-- Sparklines
//--

config.macros.sparkline = {};
config.macros.sparkline.handler = function(place,macroName,params)
{
	var data = [];
	var min = 0;
	var max = 0;
	var v;
	for(var t=0; t<params.length; t++) {
		v = parseInt(params[t]);
		if(v < min)
			min = v;
		if(v > max)
			max = v;
		data.push(v);
	}
	if(data.length < 1)
		return;
	var box = createTiddlyElement(place,"span",null,"sparkline",String.fromCharCode(160));
	box.title = data.join(",");
	var w = box.offsetWidth;
	var h = box.offsetHeight;
	box.style.paddingRight = (data.length * 2 - w) + "px";
	box.style.position = "relative";
	for(var d=0; d<data.length; d++) {
		var tick = document.createElement("img");
		tick.border = 0;
		tick.className = "sparktick";
		tick.style.position = "absolute";
		tick.src = "data:image/gif,GIF89a%01%00%01%00%91%FF%00%FF%FF%FF%00%00%00%C0%C0%C0%00%00%00!%F9%04%01%00%00%02%00%2C%00%00%00%00%01%00%01%00%40%02%02T%01%00%3B";
		tick.style.left = d*2 + "px";
		tick.style.width = "2px";
		v = Math.floor(((data[d] - min)/(max-min)) * h);
		tick.style.top = (h-v) + "px";
		tick.style.height = v + "px";
		box.appendChild(tick);
	}
};


}
//}}}
/***

''Inspired by [[TiddlyPom|http://www.warwick.ac.uk/~tuspam/tiddlypom.html]]''

|Name|SplashScreenPlugin|
|Created by|SaqImtiaz|
|Location|http://tw.lewcid.org/#SplashScreenPlugin|
|Version|0.21 |
|Requires|~TW2.08+|
!Description:
Provides a simple splash screen that is visible while the TW is loading.

!Installation
Copy the source text of this tiddler to your TW in a new tiddler, tag it with systemConfig and save and reload. The SplashScreen will now be installed and will be visible the next time you reload your TW.

!Customizing
Once the SplashScreen has been installed and you have reloaded your TW, the splash screen html will be present in the MarkupPreHead tiddler. You can edit it and customize to your needs.

!History
* 20-07-06 : version 0.21, modified to hide contentWrapper while SplashScreen is displayed.
* 26-06-06 : version 0.2, first release

!Code
***/
//{{{
var old_lewcid_splash_restart=restart;

restart = function()
{   if (document.getElementById("SplashScreen"))
        document.getElementById("SplashScreen").style.display = "none";
      if (document.getElementById("contentWrapper"))
        document.getElementById("contentWrapper").style.display = "block";
    
    old_lewcid_splash_restart();
   
    if (splashScreenInstall)
       {if(config.options.chkAutoSave)
			{saveChanges();}
        displayMessage("TW SplashScreen has been installed, please save and refresh your TW.");
        }
}


var oldText = store.getTiddlerText("MarkupPreHead");
if (oldText.indexOf("SplashScreen")==-1)
   {var siteTitle = store.getTiddlerText("SiteTitle");
   var splasher='\n\n<style type="text/css">#contentWrapper {display:none;}</style><div id="SplashScreen" style="border: 3px solid #ccc; display: block; text-align: center; width: 320px; margin: 100px auto; padding: 50px; color:#000; font-size: 28px; font-family:Tahoma; background-color:#eee;"><b>'+siteTitle +'</b> is loading<blink> ...</blink><br><br><span style="font-size: 14px; color:red;">Requires Javascript.</span></div>';
   if (! store.tiddlerExists("MarkupPreHead"))
       {var myTiddler = store.createTiddler("MarkupPreHead");}
   else
      {var myTiddler = store.getTiddler("MarkupPreHead");}
      myTiddler.set(myTiddler.title,oldText+splasher,config.options.txtUserName,null,null);
      store.setDirty(true);
      var splashScreenInstall = true;
}
//}}}
/*{{{*/
/*FONT ADJUSTMENTS*/
body {font-family: Trebuchet MS; font-size: 10pt;}
#mainMenu .tiddlyLinkExisting, #mainMenu .tiddlyLinkNonExisting {font-family: Trebuchet MS; font-size: 10pt;}
#mainMenu {font-family: Trebuchet MS; font-size: 10pt;}
#mainMenu h1 {font-size: 10pt;}
#mainMenu th {background-color:[[ColorPalette::SecondaryPale]]; color:[[ColorPalette::SecondaryDark]];}
#mainMenu table {border:none;}
#mainMenu tr {background-color:white;}
#mainMenu {background-color:[[ColorPalette::PrimaryLight]];}
.viewer {line-height: 1.7em;}
/*WIDEN MAINMENU*/
#mainMenu {width: 14.5em;}
#mainMenu {text-align: left;}
#displayArea {margin: 0em 17em 0em 17em;}
.teeny {font-size: 9pt; text-align: center;}
/*TABLE HEADER*/
.viewer th {color: #000; background-color: #eeeeee;} 
/*TIDDLER TOPMARGIN AND BUTTON BORDER*/
a.button{border: 0;} 
.viewer { margin-top: 0.1em; }
/*UNORDERED and ORDERED LISTS TWEAK*/
.viewer li {padding-top: 0.0em; padding-bottom: 0.0em;} 
/*LINELESS BLOCKQUOTES*/
.viewer blockquote {border-left: 0px; margin-top:0em; margin-bottom:0em; }

/* AGM text blocks: TiddlyWiki generates CODE elements for inline monospace blocks, and PRE
elements for multiline monospace blocks.  */
.viewer code {background-color: #FFFF99; font-size:10pt; font-family:arial; font-weight:normal}
.viewer pre {  background-color: #FFFF99; font-size:10pt; font-family:arial; font-weight:normal} 

/*HEADLINE COLOR, etc*/
h1,h2,h3,h4,h5 { color: #000; background: none; font-family: Trebuchet MS;}
/*TuDuSlider*/
.tuduSlider .button{font-family: Trebuchet MS; font-weight: bold; font-size: 10pt; color: black;}
/* GIFFMEX TWEAKS TO STYLESHEETPRINT (so that nothing but tiddler title and text are printed) */
@media print {#mainMenu {display: none ! important;}}
@media print {#topMenu {display: none ! important;}}
@media print {#sidebar {display: none ! important;}}
@media print {#messageArea {display: none ! important;}} 
@media print {#toolbar {display: none ! important;}}
@media print {.header {display: none ! important;}}
@media print {.tiddler .subtitle {display: none ! important;}}
@media print {.tiddler .toolbar {display; none ! important; }}
@media print {.tiddler .tagging {display; none ! important; }}
@media print {.tiddler .tagged {display; none ! important; }}
@media print {#displayArea {margin: 1em 1em 0em 1em;}}
@media print {.pageBreak {page-break-before: always;}}
/*CSS FOR BIBLE FORMATTING*/
.engindent {margin-left: 2em; display:block;}
.gkindent {font-family: Gentium; font-size: 16pt; margin-left: 2em; display:block;}
.greek {font-family: Gentium; font-size: 16pt;}
.hebrewNoAlign{font-family: Gentium; font-size: 20pt;}
.hebrewRightAlign{text-align:right; font-family: Gentium; font-size: 20pt; display:block;}
.hebAlignAndIndent{text-align:right; font-family: Gentium; font-size: 20pt; margin-right: 2em; display:block;}
.red {color: #ff3300; font-weight: bold;}
.blue {color: #0000cc; font-weight: bold;}
.green {color: #22bb00; font-weight: bold;}
.gold {color: #bbaa55; font-weight: bold;}
.purple {color: #9922ff; font-weight: bold;}
.gray {color: #777777; font-weight: bold;}
.magenta{color: #cc0066; font-weight: bold;}
.teal {color: #008888; font-weight: bold;}
.burgundy {color: #990000; font-weight: bold;}
.orange {color: #ff8866; font-weight: bold;}
/*INVISIBLE TABLE*/
.viewer .invisiblecomm table {border-color: white;}
.viewer .invisiblecomm table td { font-size: 1em; font-family: Verdana; border-color: white; padding: 10px 20px 10px 0px; text-align: left; vertical-align: top; padding-bottom: 20px;} 
.viewer .invisiblecomm table th {color:[[ColorPalette::PrimaryMid]]; background-color: white; border-color: white; font-family: Verdana; font-size: 1.2em; font-weight: bold; padding: 10px 20px 10px 0px; text-align: left; vertical-align: top;} 
.viewer .invisiblecomm table tr.leftColumn { background-color: #bbbbbb; }
/*OTHER TABLES*/
.menubox { display:block; padding:1em; -moz-border-radius:1em; border:1px solid; background:[[ColorPalette::TertiaryDark]]; color:#000; }
.menubox2 { display:block; padding: .25em; border:none; margin: 0; background:[[ColorPalette::TertiaryDark]]; [[ColorPalette::SecondaryDark]]; text-align: center; font-size: 1.6em;}
.menubox3 { display:block; padding:.25em; border:none; margin: 0; background:[[ColorPalette::TertiaryDark]]; [[ColorPalette::SecondaryDark]]; text-align: center; font-size: 2.5em;}
.viewer th {background-color:[[ColorPalette::SecondaryPale]]; [[ColorPalette::SecondaryDark]]}
.tableindex table, .tableindex td, .tableindex tr { font-size: 1em; border: solid white; background-color:[[ColorPalette::SecondaryPale]]; [[ColorPalette::SecondaryDark]]}
/*}}}*/
/*{{{*/
* html .tiddler {height:1%;}

body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;}

h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
h4,h5,h6 {margin-top:1em;}
h1 {font-size:1.35em;}
h2 {font-size:1.25em;}
h3 {font-size:1.1em;}
h4 {font-size:1em;}
h5 {font-size:.9em;}

hr {height:1px;}

a {text-decoration:none;}

dt {font-weight:bold;}

ol {list-style-type:decimal;}
ol ol {list-style-type:lower-alpha;}
ol ol ol {list-style-type:lower-roman;}
ol ol ol ol {list-style-type:decimal;}
ol ol ol ol ol {list-style-type:lower-alpha;}
ol ol ol ol ol ol {list-style-type:lower-roman;}
ol ol ol ol ol ol ol {list-style-type:decimal;}

.txtOptionInput {width:11em;}

#contentWrapper .chkOptionInput {border:0;}

.externalLink {text-decoration:underline;}

.indent {margin-left:3em;}
.outdent {margin-left:3em; text-indent:-3em;}
code.escaped {white-space:nowrap;}

.tiddlyLinkExisting {font-weight:bold;}
.tiddlyLinkNonExisting {font-style:italic;}

/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
a.tiddlyLinkNonExisting.shadow {font-weight:bold;}

#mainMenu .tiddlyLinkExisting,
	#mainMenu .tiddlyLinkNonExisting,
	#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}

.header {position:relative;}
.header a:hover {background:transparent;}
.headerShadow {position:relative; padding:4.5em 0em 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:4.5em 0em 1em 1em; left:0px; top:0px;}

.siteTitle {font-size:3em;}
.siteSubtitle {font-size:1.2em;}

#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}

#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
#sidebarOptions {padding-top:0.3em;}
#sidebarOptions a {margin:0em 0.2em; padding:0.2em 0.3em; display:block;}
#sidebarOptions input {margin:0.4em 0.5em;}
#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
#sidebarOptions .sliderPanel input {margin:0 0 .3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}

.wizard {padding:0.1em 1em 0em 1em;}
.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;}
.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0em 0em 0em 0em; margin:0.4em 0em 0.2em 0em;}
.wizardStep {padding:1em 1em 1em 1em;}
.wizard .button {margin:0.5em 0em 0em 0em; font-size:1.2em;}
.wizardFooter {padding:0.8em 0.4em 0.8em 0em;}
.wizardFooter .status {padding:0em 0.4em 0em 0.4em; margin-left:1em;}
.wizard .button {padding:0.1em 0.2em 0.1em 0.2em;}

#messageArea {position:fixed; top:2em; right:0em; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;}
.messageToolbar {display:block; text-align:right; padding:0.2em 0.2em 0.2em 0.2em;}
#messageArea a {text-decoration:underline;}

.tiddlerPopupButton {padding:0.2em 0.2em 0.2em 0.2em;}
.popupTiddler {position: absolute; z-index:300; padding:1em 1em 1em 1em; margin:0;}

.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;}
.popup .popupMessage {padding:0.4em;}
.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0em;}
.popup li.disabled {padding:0.4em;}
.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;}
.listBreak {font-size:1px; line-height:1px;}
.listBreak div {margin:1px 0;}

.tabset {padding:1em 0em 0em 0.5em;}
.tab {margin:0em 0em 0em 0.25em; padding:2px;}
.tabContents {padding:0.5em;}
.tabContents ul, .tabContents ol {margin:0; padding:0;}
.txtMainTab .tabContents li {list-style:none;}
.tabContents li.listLink { margin-left:.75em;}

#contentWrapper {display:block;}
splashScreen {display:none;}

#displayArea {margin:1em 17em 0em 14em;}

.toolbar {text-align:right; font-size:.9em;}

.tiddler {padding:1em 1em 0em 1em;}

.missing .viewer,.missing .title {font-style:italic;}

.title {font-size:1.6em; font-weight:bold;}

.missing .subtitle {display:none;}
.subtitle {font-size:1.1em;}

.tiddler .button {padding:0.2em 0.4em;}

.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
.isTag .tagging {display:block;}
.tagged {margin:0.5em; float:right;}
.tagging, .tagged {font-size:0.9em; padding:0.25em;}
.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
.tagClear {clear:both;}

.footer {font-size:.9em;}
.footer li {display:inline;}

.annotation {padding:0.5em; margin:0.5em;}

* html .viewer pre {width:99%; padding:0 0 0em 0;}
.viewer {line-height:1.0em; padding-top:0.0em;}
.viewer .button {margin:0em 0.25em; padding:0em 0.25em;}
.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}

.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;}
.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;}
table.listView {font-size:0.85em; margin:0.8em 1.0em;}
table.listView th, table.listView td, table.listView tr {padding:0px 3px 0px 3px;}

.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;}
.viewer code {font-size:1.2em; line-height:1.4em;}

.editor {font-size:1.1em;}
.editor input, .editor textarea {display:block; width:100%; font:inherit;}
.editorFooter {padding:0.25em 0em; font-size:.9em;}
.editorFooter .button {padding-top:0px; padding-bottom:0px;}

.fieldsetFix {border:0; padding:0; margin:1px 0px 1px 0px;}

.sparkline {line-height:1em;}
.sparktick {outline:0;}

.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
.zoomer div {padding:1em;}

* html #backstage {width:99%;}
* html #backstageArea {width:99%;}
#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em 0.3em 0.5em;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em 0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0em; right:0em;}
#backstageButton a {padding:0.1em 0.4em 0.1em 0.4em; margin:0.1em 0.1em 0.1em 0.1em;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel {display:none; z-index:100; position:absolute; margin:0em 3em 0em 3em; padding:1em 1em 1em 1em;}
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding:0.2em 0.4em 0.2em 0.4em;}
#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}

.whenBackstage {display:none;}
.backstageVisible .whenBackstage {display:block;}
/*}}}*/
Subtopic menus are menus at the top of the topic tiddlers, like the one above, which has three subtopics: "Welcome", "Instructions", and "Subtopic menu instructions". You can have a separate subtopic menu for as many topics as you add to your mainmenu. There are three steps to creating a new subtopic menu. You may do these steps in any order you wish:
#''Create tiddlers for each of the subtopics within a topic.'' Tag them all with one appropriate tag pertaining to the topic. This will link them all so that they appear in the subtopic menu.
#''Create a subtopic menu tiddler.'' This will be the tiddler where the menu that appears above the other tiddlers is stored. In the Sidebar, click on 'new subtopic menu'. Replace 'tagname' in the title with the name of the tag you added to the tiddlers above. Then add the title of your subtopic tiddlers in the table provided, within the double brackets {{{[[ ]]}}}. Three table cells have been provided. Delete or add table cells as needed.
#''Create a custom ~ViewTemplate for your topic.'' This will tell ~TiddlyWiki to show your subtopic menu at the top of all the tiddlers that you have tagged with that topic's tag. In the Sidebar, click on 'new viewtemplate'. Replace 'tagname' with the tag you added to the tiddlers above. Do this for the title of the tiddler, as well as in the two instances of 'tagname' in the viewtemplate's code (it will look like the line shown below before you change it).

<!--{{{-->
<div class='tagnameMacro='tiddler tagnameSubtopicmenu'></div>
<!--}}}-->
That's it. A menu of links to the tiddlers you have tagged and added to your subtopic menu tiddler should appear above the tiddler title of each of those tiddlers.
/***
|Name|TaggedTemplateTweak|
|Source|http://www.TiddlyTools.com/#TaggedTemplateTweak|
|Documentation|http://www.TiddlyTools.com/#TaggedTemplateTweakInfo|
|Version|1.1.0|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides|Story.prototype.chooseTemplateForTiddler()|
|Description|use alternative ViewTemplate/EditTemplate for tiddler's tagged with specific tag values|
This tweak extends story.chooseTemplateForTiddler() so that ''whenever a tiddler is marked with a specific tag value, it can be viewed and/or edited using alternatives to the standard tiddler templates.'' 
!!!!!Documentation
>see [[TaggedTemplateTweakInfo]]
!!!!!Revisions
<<<
2008.01.22 [*.*.*] plugin size reduction - documentation moved to [[TaggedTemplateTweakInfo]]
2007.06.23 [1.1.0] re-written to use automatic 'tag prefix' search instead of hard coded check for each tag.  Allows new custom tags to be used without requiring code changes to this plugin.
| please see [[TaggedTemplateTweakInfo]] for previous revision details |
2007.06.11 [1.0.0] initial release

<<<
!!!!!Code
***/
//{{{
version.extensions.taggedTemplate= {major: 1, minor: 1, revision: 0, date: new Date(2007,6,23)};
Story.prototype.taggedTemplate_chooseTemplateForTiddler = Story.prototype.chooseTemplateForTiddler
Story.prototype.chooseTemplateForTiddler = function(title,template)
{
	// get default template from core
	var template=this.taggedTemplate_chooseTemplateForTiddler.apply(this,arguments);

	// if the tiddler to be rendered doesn't exist yet, just return core result
	var tiddler=store.getTiddler(title); if (!tiddler) return template;

	// look for template whose prefix matches a tag on this tiddler
	for (t=0; t<tiddler.tags.length; t++) {
		var tag=tiddler.tags[t];
		if (store.tiddlerExists(tag+template)) { template=tag+template; break; }
		// try capitalized tag (to match WikiWord template titles)
		var cap=tag.substr(0,1).toUpperCase()+tag.substr(1);
		if (store.tiddlerExists(cap+template)) { template=cap+template; break; }
	}

	return template;
}
//}}}
{{{
<html>
<div style="color: rgb(100, 100, 150); font-family: Monaco;">
<big><big><b>
xxxx

</html>
}}}
/%
|Name|ToggleRightSidebar|
|Source|http://www.TiddlyTools.com/#ToggleRightSidebar|
|Version|1.0.0|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements <br>and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|script|
|Requires|InlineJavascriptPlugin|
|Overrides||
|Description|show/hide right sidebar (SideBarOptions)|

Usage: <<tiddler ToggleRightSidebar>>

Config settings:
	config.options.txtToggleRightSideBarLabelShow (◄)
	config.options.txtToggleRightSideBarLabelHide (►)
	config.options.txtToggleRightSideBarTipShow ("show right sidebar")
	config.options.txtToggleRightSideBarTipHide ("hide right sidebar")

%/<script label="show/hide right sidebar">

	var sb=document.getElementById('sidebar'); if (!sb) return;
	var show=sb.style.display=='none';
	if (!show) { sb.style.display='none'; var margin='1em'; }
	else { sb.style.display='block'; var margin=config.options.txtDisplayAreaRightMargin||''; }
	if (typeof(place)!='undefined') {
		place.innerHTML=show?
			config.options.txtToggleRightSideBarLabelHide:config.options.txtToggleRightSideBarLabelShow;
		place.title=show?
			config.options.txtToggleRightSideBarTipHide:config.options.txtToggleRightSideBarTipShow;
	}
	document.getElementById('displayArea').style.marginRight=margin;
	config.options.chkShowRightSidebar=show;
	saveOptionCookie('chkShowRightSidebar');
	var sm=document.getElementById('storyMenu'); if (sm) config.refreshers.content(sm);
	return false;
</script><script>
	if (config.options.chkShowRightSidebar==undefined)
		config.options.chkShowRightSidebar=true;
	if (!config.options.txtDisplayAreaRightMargin||!config.options.txtDisplayAreaRightMargin.length)
		config.options.txtDisplayAreaRightMargin="18em";
	if (config.options.txtToggleRightSideBarLabelShow==undefined)
		config.options.txtToggleRightSideBarLabelShow=config.browser.isSafari?"&#x25c0;":"&#x25c4;";
	if (config.options.txtToggleRightSideBarLabelHide==undefined)
		config.options.txtToggleRightSideBarLabelHide="&#x25ba;";
	if (config.options.txtToggleRightSideBarTipShow==undefined)
		config.options.txtToggleRightSideBarTipShow="show right sidebar";
	if (config.options.txtToggleRightSideBarTipHide==undefined)
		config.options.txtToggleRightSideBarTipHide="hide right sidebar";

	var show=config.options.chkShowRightSidebar;
	document.getElementById('sidebar').style.display=show?"block":"none";
	document.getElementById('displayArea').style.marginRight=show?
		config.options.txtDisplayAreaRightMargin:"1em";
	place.lastChild.innerHTML=show?
		config.options.txtToggleRightSideBarLabelHide:config.options.txtToggleRightSideBarLabelShow;
	place.lastChild.title=show?
		config.options.txtToggleRightSideBarTipHide:config.options.txtToggleRightSideBarTipShow;
	place.lastChild.style.fontWeight="normal";

</script>
|!History:|!<<back>>|>|!<<history>>|>|!<<forward>>|
|!Font size:|>|>|>|>|! <<fontSize>>|
|!Sidebar:|>|>|>|>|!<<tiddler ToggleRightSidebar>>|
''These are the summary interests of the group. As scripts are generated/explored within each topic area, a page will be created to provide easy access to those R tools from this index list.''
!
# R commands
** data input: go to > [[06JUNE]]
# Geographical Mapping
# ANOVA: go to > [[15AUG|Intro-0808]]
# Phylogenetic Analyses
# Multivariate Statistics
** RDA
** PCA
** CCA
** Resampling
# Data Managment
# Plotting & Graphics
** Basic XY Plots: go to > [[13JUNE]]
** Intro to ggplot2: go to > [[13JUNE]]
!
!Separate Culture and Plate ~IDs
{{{
M$cult   <- as.factor(substring(M$Culture,1,1))
M$plate <- as.factor(substring(M$Culture,2,2))

> aggregate(M$DevoRate, list(Culture=M$cult), mean)
  Culture          x
1       A    0.07574946
2       B    0.09427224
3       C    0.10663748
4       D    0.09417900
}}}

!Data Visualization:
<html><img src="0808/01boxplot2.png" style="height:400px"></html>
{{{
# boxplot - - - - - - - - - - - - - - - - - - - - 
ggopt(legend.position="none")
p$legend.position<-c("none")
p <- ggplot(data=M, aes(y=DevoRate,x=cult))
p + geom_boxplot(aes(fill=cult), colour="black", outlier.colour="green", outlier.size=3) 
p + scale_y_continuous("Developmental Rate") 
}}}
!
!!Multiple Comparison: Tukey's Highly Significant Differences
{{{
tukeyout <- TukeyHSD(aovout,"cult",ordered=T)
tukeyout
plot(tukeyout)
}}}
<html><img src="0808/tukeyplot.png" style="height:500px"></html>
!
<html>
<div style="color: rgb(100, 100, 150); font-family: Monaco;"><big><b>
These are a few of the tutorial resources for getting an introduction to R routines and data management.
</html>

1. [[Download a simple R tutorial by Verzani (PDF)|00/Tutorial-Verzani-SimpleR.pdf]]
2. [[Download a basic introduction to R by Owen (PDF; 60 pages)|00/Owen-TheRGuide.pdf]]
3. [[Download a general introduction to R by Venables (PDF; 100 pages)|00/R-Venables-Intro.pdf]]
4. [[Download an intermediate introduction to R by Lam (PDF; 200 pages)|00/R-Lam-Intro.pdf]]
5. [[Download WIND Tower sample data|WindData]]
!!
/***
|''Name:''|UploadPlugin|
|''Description:''|Save to web a TiddlyWiki|
|''Version:''|4.1.3|
|''Date:''|Feb 24, 2008|
|''Source:''|http://tiddlywiki.bidix.info/#UploadPlugin|
|''Documentation:''|http://tiddlywiki.bidix.info/#UploadPluginDoc|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''License:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.2.0|
|''Requires:''|PasswordOptionPlugin|
***/
//{{{
version.extensions.UploadPlugin = {
	major: 4, minor: 1, revision: 3,
	date: new Date("Feb 24, 2008"),
	source: 'http://tiddlywiki.bidix.info/#UploadPlugin',
	author: 'BidiX (BidiX (at) bidix (dot) info',
	coreVersion: '2.2.0'
};

//
// Environment
//

if (!window.bidix) window.bidix = {}; // bidix namespace
bidix.debugMode = false;	// true to activate both in Plugin and UploadService
	
//
// Upload Macro
//

config.macros.upload = {
// default values
	defaultBackupDir: '',	//no backup
	defaultStoreScript: "store.php",
	defaultToFilename: "index.html",
	defaultUploadDir: ".",
	authenticateUser: true	// UploadService Authenticate User
};
	
config.macros.upload.label = {
	promptOption: "Save and Upload this TiddlyWiki with UploadOptions",
	promptParamMacro: "Save and Upload this TiddlyWiki in %0",
	saveLabel: "save to web", 
	saveToDisk: "save to disk",
	uploadLabel: "upload"	

};

config.macros.upload.messages = {
	noStoreUrl: "No store URL in parmeters or options",
	usernameOrPasswordMissing: "Username or password missing"
};

config.macros.upload.handler = function(place,macroName,params) {
	if (readOnly)
		return;
	var label;
	if (document.location.toString().substr(0,4) == "http") 
		label = this.label.saveLabel;
	else
		label = this.label.uploadLabel;
	var prompt;
	if (params[0]) {
		prompt = this.label.promptParamMacro.toString().format([this.destFile(params[0], 
			(params[1] ? params[1]:bidix.basename(window.location.toString())), params[3])]);
	} else {
		prompt = this.label.promptOption;
	}
	createTiddlyButton(place, label, prompt, function() {config.macros.upload.action(params);}, null, null, this.accessKey);
};

config.macros.upload.action = function(params)
{
		// for missing macro parameter set value from options
		if (!params) params = {};
		var storeUrl = params[0] ? params[0] : config.options.txtUploadStoreUrl;
		var toFilename = params[1] ? params[1] : config.options.txtUploadFilename;
		var backupDir = params[2] ? params[2] : config.options.txtUploadBackupDir;
		var uploadDir = params[3] ? params[3] : config.options.txtUploadDir;
		var username = params[4] ? params[4] : config.options.txtUploadUserName;
		var password = config.options.pasUploadPassword; // for security reason no password as macro parameter	
		// for still missing parameter set default value
		if ((!storeUrl) && (document.location.toString().substr(0,4) == "http")) 
			storeUrl = bidix.dirname(document.location.toString())+'/'+config.macros.upload.defaultStoreScript;
		if (storeUrl.substr(0,4) != "http")
			storeUrl = bidix.dirname(document.location.toString()) +'/'+ storeUrl;
		if (!toFilename)
			toFilename = bidix.basename(window.location.toString());
		if (!toFilename)
			toFilename = config.macros.upload.defaultToFilename;
		if (!uploadDir)
			uploadDir = config.macros.upload.defaultUploadDir;
		if (!backupDir)
			backupDir = config.macros.upload.defaultBackupDir;
		// report error if still missing
		if (!storeUrl) {
			alert(config.macros.upload.messages.noStoreUrl);
			clearMessage();
			return false;
		}
		if (config.macros.upload.authenticateUser && (!username || !password)) {
			alert(config.macros.upload.messages.usernameOrPasswordMissing);
			clearMessage();
			return false;
		}
		bidix.upload.uploadChanges(false,null,storeUrl, toFilename, uploadDir, backupDir, username, password); 
		return false; 
};

config.macros.upload.destFile = function(storeUrl, toFilename, uploadDir) 
{
	if (!storeUrl)
		return null;
		var dest = bidix.dirname(storeUrl);
		if (uploadDir && uploadDir != '.')
			dest = dest + '/' + uploadDir;
		dest = dest + '/' + toFilename;
	return dest;
};

//
// uploadOptions Macro
//

config.macros.uploadOptions = {
	handler: function(place,macroName,params) {
		var wizard = new Wizard();
		wizard.createWizard(place,this.wizardTitle);
		wizard.addStep(this.step1Title,this.step1Html);
		var markList = wizard.getElement("markList");
		var listWrapper = document.createElement("div");
		markList.parentNode.insertBefore(listWrapper,markList);
		wizard.setValue("listWrapper",listWrapper);
		this.refreshOptions(listWrapper,false);
		var uploadCaption;
		if (document.location.toString().substr(0,4) == "http") 
			uploadCaption = config.macros.upload.label.saveLabel;
		else
			uploadCaption = config.macros.upload.label.uploadLabel;
		
		wizard.setButtons([
				{caption: uploadCaption, tooltip: config.macros.upload.label.promptOption, 
					onClick: config.macros.upload.action},
				{caption: this.cancelButton, tooltip: this.cancelButtonPrompt, onClick: this.onCancel}
				
			]);
	},
	options: [
		"txtUploadUserName",
		"pasUploadPassword",
		"txtUploadStoreUrl",
		"txtUploadDir",
		"txtUploadFilename",
		"txtUploadBackupDir",
		"chkUploadLog",
		"txtUploadLogMaxLine"		
	],
	refreshOptions: function(listWrapper) {
		var opts = [];
		for(i=0; i<this.options.length; i++) {
			var opt = {};
			opts.push();
			opt.option = "";
			n = this.options[i];
			opt.name = n;
			opt.lowlight = !config.optionsDesc[n];
			opt.description = opt.lowlight ? this.unknownDescription : config.optionsDesc[n];
			opts.push(opt);
		}
		var listview = ListView.create(listWrapper,opts,this.listViewTemplate);
		for(n=0; n<opts.length; n++) {
			var type = opts[n].name.substr(0,3);
			var h = config.macros.option.types[type];
			if (h && h.create) {
				h.create(opts[n].colElements['option'],type,opts[n].name,opts[n].name,"no");
			}
		}
		
	},
	onCancel: function(e)
	{
		backstage.switchTab(null);
		return false;
	},
	
	wizardTitle: "Upload with options",
	step1Title: "These options are saved in cookies in your browser",
	step1Html: "<input type='hidden' name='markList'></input><br>",
	cancelButton: "Cancel",
	cancelButtonPrompt: "Cancel prompt",
	listViewTemplate: {
		columns: [
			{name: 'Description', field: 'description', title: "Description", type: 'WikiText'},
			{name: 'Option', field: 'option', title: "Option", type: 'String'},
			{name: 'Name', field: 'name', title: "Name", type: 'String'}
			],
		rowClasses: [
			{className: 'lowlight', field: 'lowlight'} 
			]}
};

//
// upload functions
//

if (!bidix.upload) bidix.upload = {};

if (!bidix.upload.messages) bidix.upload.messages = {
	//from saving
	invalidFileError: "The original file '%0' does not appear to be a valid TiddlyWiki",
	backupSaved: "Backup saved",
	backupFailed: "Failed to upload backup file",
	rssSaved: "RSS feed uploaded",
	rssFailed: "Failed to upload RSS feed file",
	emptySaved: "Empty template uploaded",
	emptyFailed: "Failed to upload empty template file",
	mainSaved: "Main TiddlyWiki file uploaded",
	mainFailed: "Failed to upload main TiddlyWiki file. Your changes have not been saved",
	//specific upload
	loadOriginalHttpPostError: "Can't get original file",
	aboutToSaveOnHttpPost: 'About to upload on %0 ...',
	storePhpNotFound: "The store script '%0' was not found."

};

bidix.upload.uploadChanges = function(onlyIfDirty,tiddlers,storeUrl,toFilename,uploadDir,backupDir,username,password)
{
	var callback = function(status,uploadParams,original,url,xhr) {
		if (!status) {
			displayMessage(bidix.upload.messages.loadOriginalHttpPostError);
			return;
		}
		if (bidix.debugMode) 
			alert(original.substr(0,500)+"\n...");
		// Locate the storeArea div's 
		var posDiv = locateStoreArea(original);
		if((posDiv[0] == -1) || (posDiv[1] == -1)) {
			alert(config.messages.invalidFileError.format([localPath]));
			return;
		}
		bidix.upload.uploadRss(uploadParams,original,posDiv);
	};
	
	if(onlyIfDirty && !store.isDirty())
		return;
	clearMessage();
	// save on localdisk ?
	if (document.location.toString().substr(0,4) == "file") {
		var path = document.location.toString();
		var localPath = getLocalPath(path);
		saveChanges();
	}
	// get original
	var uploadParams = new Array(storeUrl,toFilename,uploadDir,backupDir,username,password);
	var originalPath = document.location.toString();
	// If url is a directory : add index.html
	if (originalPath.charAt(originalPath.length-1) == "/")
		originalPath = originalPath + "index.html";
	var dest = config.macros.upload.destFile(storeUrl,toFilename,uploadDir);
	var log = new bidix.UploadLog();
	log.startUpload(storeUrl, dest, uploadDir,  backupDir);
	displayMessage(bidix.upload.messages.aboutToSaveOnHttpPost.format([dest]));
	if (bidix.debugMode) 
		alert("about to execute Http - GET on "+originalPath);
	var r = doHttp("GET",originalPath,null,null,username,password,callback,uploadParams,null);
	if (typeof r == "string")
		displayMessage(r);
	return r;
};

bidix.upload.uploadRss = function(uploadParams,original,posDiv) 
{
	var callback = function(status,params,responseText,url,xhr) {
		if(status) {
			var destfile = responseText.substring(responseText.indexOf("destfile:")+9,responseText.indexOf("\n", responseText.indexOf("destfile:")));
			displayMessage(bidix.upload.messages.rssSaved,bidix.dirname(url)+'/'+destfile);
			bidix.upload.uploadMain(params[0],params[1],params[2]);
		} else {
			displayMessage(bidix.upload.messages.rssFailed);			
		}
	};
	// do uploadRss
	if(config.options.chkGenerateAnRssFeed) {
		var rssPath = uploadParams[1].substr(0,uploadParams[1].lastIndexOf(".")) + ".xml";
		var rssUploadParams = new Array(uploadParams[0],rssPath,uploadParams[2],'',uploadParams[4],uploadParams[5]);
		var rssString = generateRss();
		// no UnicodeToUTF8 conversion needed when location is "file" !!!
		if (document.location.toString().substr(0,4) != "file")
			rssString = convertUnicodeToUTF8(rssString);	
		bidix.upload.httpUpload(rssUploadParams,rssString,callback,Array(uploadParams,original,posDiv));
	} else {
		bidix.upload.uploadMain(uploadParams,original,posDiv);
	}
};

bidix.upload.uploadMain = function(uploadParams,original,posDiv) 
{
	var callback = function(status,params,responseText,url,xhr) {
		var log = new bidix.UploadLog();
		if(status) {
			// if backupDir specified
			if ((params[3]) && (responseText.indexOf("backupfile:") > -1))  {
				var backupfile = responseText.substring(responseText.indexOf("backupfile:")+11,responseText.indexOf("\n", responseText.indexOf("backupfile:")));
				displayMessage(bidix.upload.messages.backupSaved,bidix.dirname(url)+'/'+backupfile);
			}
			var destfile = responseText.substring(responseText.indexOf("destfile:")+9,responseText.indexOf("\n", responseText.indexOf("destfile:")));
			displayMessage(bidix.upload.messages.mainSaved,bidix.dirname(url)+'/'+destfile);
			store.setDirty(false);
			log.endUpload("ok");
		} else {
			alert(bidix.upload.messages.mainFailed);
			displayMessage(bidix.upload.messages.mainFailed);
			log.endUpload("failed");			
		}
	};
	// do uploadMain
	var revised = bidix.upload.updateOriginal(original,posDiv);
	bidix.upload.httpUpload(uploadParams,revised,callback,uploadParams);
};

bidix.upload.httpUpload = function(uploadParams,data,callback,params)
{
	var localCallback = function(status,params,responseText,url,xhr) {
		url = (url.indexOf("nocache=") < 0 ? url : url.substring(0,url.indexOf("nocache=")-1));
		if (xhr.status == httpStatus.NotFound)
			alert(bidix.upload.messages.storePhpNotFound.format([url]));
		if ((bidix.debugMode) || (responseText.indexOf("Debug mode") >= 0 )) {
			alert(responseText);
			if (responseText.indexOf("Debug mode") >= 0 )
				responseText = responseText.substring(responseText.indexOf("\n\n")+2);
		} else if (responseText.charAt(0) != '0') 
			alert(responseText);
		if (responseText.charAt(0) != '0')
			status = null;
		callback(status,params,responseText,url,xhr);
	};
	// do httpUpload
	var boundary = "---------------------------"+"AaB03x";	
	var uploadFormName = "UploadPlugin";
	// compose headers data
	var sheader = "";
	sheader += "--" + boundary + "\r\nContent-disposition: form-data; name=\"";
	sheader += uploadFormName +"\"\r\n\r\n";
	sheader += "backupDir="+uploadParams[3] +
				";user=" + uploadParams[4] +
				";password=" + uploadParams[5] +
				";uploaddir=" + uploadParams[2];
	if (bidix.debugMode)
		sheader += ";debug=1";
	sheader += ";;\r\n"; 
	sheader += "\r\n" + "--" + boundary + "\r\n";
	sheader += "Content-disposition: form-data; name=\"userfile\"; filename=\""+uploadParams[1]+"\"\r\n";
	sheader += "Content-Type: text/html;charset=UTF-8" + "\r\n";
	sheader += "Content-Length: " + data.length + "\r\n\r\n";
	// compose trailer data
	var strailer = new String();
	strailer = "\r\n--" + boundary + "--\r\n";
	data = sheader + data + strailer;
	if (bidix.debugMode) alert("about to execute Http - POST on "+uploadParams[0]+"\n with \n"+data.substr(0,500)+ " ... ");
	var r = doHttp("POST",uploadParams[0],data,"multipart/form-data; ;charset=UTF-8; boundary="+boundary,uploadParams[4],uploadParams[5],localCallback,params,null);
	if (typeof r == "string")
		displayMessage(r);
	return r;
};

// same as Saving's updateOriginal but without convertUnicodeToUTF8 calls
bidix.upload.updateOriginal = function(original, posDiv)
{
	if (!posDiv)
		posDiv = locateStoreArea(original);
	if((posDiv[0] == -1) || (posDiv[1] == -1)) {
		alert(config.messages.invalidFileError.format([localPath]));
		return;
	}
	var revised = original.substr(0,posDiv[0] + startSaveArea.length) + "\n" +
				store.allTiddlersAsHtml() + "\n" +
				original.substr(posDiv[1]);
	var newSiteTitle = getPageTitle().htmlEncode();
	revised = revised.replaceChunk("<title"+">","</title"+">"," " + newSiteTitle + " ");
	revised = updateMarkupBlock(revised,"PRE-HEAD","MarkupPreHead");
	revised = updateMarkupBlock(revised,"POST-HEAD","MarkupPostHead");
	revised = updateMarkupBlock(revised,"PRE-BODY","MarkupPreBody");
	revised = updateMarkupBlock(revised,"POST-SCRIPT","MarkupPostBody");
	return revised;
};

//
// UploadLog
// 
// config.options.chkUploadLog :
//		false : no logging
//		true : logging
// config.options.txtUploadLogMaxLine :
//		-1 : no limit
//      0 :  no Log lines but UploadLog is still in place
//		n :  the last n lines are only kept
//		NaN : no limit (-1)

bidix.UploadLog = function() {
	if (!config.options.chkUploadLog) 
		return; // this.tiddler = null
	this.tiddler = store.getTiddler("UploadLog");
	if (!this.tiddler) {
		this.tiddler = new Tiddler();
		this.tiddler.title = "UploadLog";
		this.tiddler.text = "| !date | !user | !location | !storeUrl | !uploadDir | !toFilename | !backupdir | !origin |";
		this.tiddler.created = new Date();
		this.tiddler.modifier = config.options.txtUserName;
		this.tiddler.modified = new Date();
		store.addTiddler(this.tiddler);
	}
	return this;
};

bidix.UploadLog.prototype.addText = function(text) {
	if (!this.tiddler)
		return;
	// retrieve maxLine when we need it
	var maxLine = parseInt(config.options.txtUploadLogMaxLine,10);
	if (isNaN(maxLine))
		maxLine = -1;
	// add text
	if (maxLine != 0) 
		this.tiddler.text = this.tiddler.text + text;
	// Trunck to maxLine
	if (maxLine >= 0) {
		var textArray = this.tiddler.text.split('\n');
		if (textArray.length > maxLine + 1)
			textArray.splice(1,textArray.length-1-maxLine);
			this.tiddler.text = textArray.join('\n');		
	}
	// update tiddler fields
	this.tiddler.modifier = config.options.txtUserName;
	this.tiddler.modified = new Date();
	store.addTiddler(this.tiddler);
	// refresh and notifiy for immediate update
	story.refreshTiddler(this.tiddler.title);
	store.notify(this.tiddler.title, true);
};

bidix.UploadLog.prototype.startUpload = function(storeUrl, toFilename, uploadDir,  backupDir) {
	if (!this.tiddler)
		return;
	var now = new Date();
	var text = "\n| ";
	var filename = bidix.basename(document.location.toString());
	if (!filename) filename = '/';
	text += now.formatString("0DD/0MM/YYYY 0hh:0mm:0ss") +" | ";
	text += config.options.txtUserName + " | ";
	text += "[["+filename+"|"+location + "]] |";
	text += " [[" + bidix.basename(storeUrl) + "|" + storeUrl + "]] | ";
	text += uploadDir + " | ";
	text += "[[" + bidix.basename(toFilename) + " | " +toFilename + "]] | ";
	text += backupDir + " |";
	this.addText(text);
};

bidix.UploadLog.prototype.endUpload = function(status) {
	if (!this.tiddler)
		return;
	this.addText(" "+status+" |");
};

//
// Utilities
// 

bidix.checkPlugin = function(plugin, major, minor, revision) {
	var ext = version.extensions[plugin];
	if (!
		(ext  && 
			((ext.major > major) || 
			((ext.major == major) && (ext.minor > minor))  ||
			((ext.major == major) && (ext.minor == minor) && (ext.revision >= revision))))) {
			// write error in PluginManager
			if (pluginInfo)
				pluginInfo.log.push("Requires " + plugin + " " + major + "." + minor + "." + revision);
			eval(plugin); // generate an error : "Error: ReferenceError: xxxx is not defined"

	}
};

bidix.dirname = function(filePath) {
	if (!filePath) 
		return;
	var lastpos;
	if ((lastpos = filePath.lastIndexOf("/")) != -1) {
		return filePath.substring(0, lastpos);
	} else {
		return filePath.substring(0, filePath.lastIndexOf("\\"));
	}
};

bidix.basename = function(filePath) {
	if (!filePath) 
		return;
	var lastpos;
	if ((lastpos = filePath.lastIndexOf("#")) != -1) 
		filePath = filePath.substring(0, lastpos);
	if ((lastpos = filePath.lastIndexOf("/")) != -1) {
		return filePath.substring(lastpos + 1);
	} else
		return filePath.substring(filePath.lastIndexOf("\\")+1);
};

bidix.initOption = function(name,value) {
	if (!config.options[name])
		config.options[name] = value;
};

//
// Initializations
//

// require PasswordOptionPlugin 1.0.1 or better
bidix.checkPlugin("PasswordOptionPlugin", 1, 0, 1);

// styleSheet
setStylesheet('.txtUploadStoreUrl, .txtUploadBackupDir, .txtUploadDir {width: 22em;}',"uploadPluginStyles");

//optionsDesc
merge(config.optionsDesc,{
	txtUploadStoreUrl: "Url of the UploadService script (default: store.php)",
	txtUploadFilename: "Filename of the uploaded file (default: in index.html)",
	txtUploadDir: "Relative Directory where to store the file (default: . (downloadService directory))",
	txtUploadBackupDir: "Relative Directory where to backup the file. If empty no backup. (default: ''(empty))",
	txtUploadUserName: "Upload Username",
	pasUploadPassword: "Upload Password",
	chkUploadLog: "do Logging in UploadLog (default: true)",
	txtUploadLogMaxLine: "Maximum of lines in UploadLog (default: 10)"

});

// Options Initializations
bidix.initOption('txtUploadStoreUrl','');
bidix.initOption('txtUploadFilename','');
bidix.initOption('txtUploadDir','');
bidix.initOption('txtUploadBackupDir','');
bidix.initOption('txtUploadUserName','');
bidix.initOption('pasUploadPassword','');
bidix.initOption('chkUploadLog',true);
bidix.initOption('txtUploadLogMaxLine','10');


// Backstage
merge(config.tasks,{
	uploadOptions: {text: "upload", tooltip: "Change UploadOptions and Upload", content: '<<uploadOptions>>'}
});
config.backstageTasks.push("uploadOptions");


//}}}

<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>

<div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
This is just a modest adaptation of ~TiddlyWiki for use as a webpage. I created it for my own use, but thought others might like an empty template of it. To see a working example of the Webview ~TiddlyWiki, [[see here|http://www.giffmex.org/webviewtwexample.html]]. ''Features of WebviewTW:''
*I have reduced as much clutter as possible, so as not to confuse first time visitors to your site: the header is gone, the sidebar hidden, and Tiddler elements such as author, date created, tagged and tagging have been removed. The mainmenu has a toolbox, which itself can be gutted if desired, when you are ready to upload.
*Only one tiddler opens at a time.
*There is a way to create a series of tiddlers linked in a colorful subtopic menu above the tiddler titles (the three squares above are an example of a subtopic menu and include the instructions necessary to create one). These are good just as subtopic menus, but are also meant for slideshows and linear tutorials and lessons. The idea is similar to the [[PresentationPlugin|http://lewcid.googlepages.com/presentation_empty_full.html#Documentation]], but this setup operates in a different way.
*Saving options have been set to ~SaveBackup:unchecked, and Animations:disabled, and the sidebar is hidden by default. (See [[z_configOptions]] to change these)
*In edit mode there are a number of easyEdit menus. See [[Formatting cheatsheet]] for details. There are also several color palettes to choose from (found in the Sidebar).
*The UploadPlugin and SplashScreenPlugin are installed. For directions for the UploadPlugin, see [[this external link|http://www.giffmex.org/twfortherestofus.html#%5B%5BSimple%20instructions%20for%20BidiX's%20UploadPlugin%5D%5D]]. My apologies to Alan Hecht, the creator of the ~WebViewPlugin - there is no relation between this adaptation and that plugin, which is not used here.
!!Lewes Wind Tower data (from Dana Veron)
__Disclaimer:__ Note that the data is @@confidential@@ and not for public distribution or comment. This small subset of data is insufficient to draw any conclusions about the power production of locating a wind turbine at CMES and is only used here for instructional purposes. 
# [[Data set 1|00/014120080511015.txt]]
# [[Data set 2|00/014120080512016.txt]]
# [[Data set 3|00/014120080511018.txt]]
# [[Data set 4|00/0141200805110151.txt]]
# [[Data set 5|00/0141200805110152.txt]]
# [[Data set 6|00/0141200805110181.txt]]
!
Background: #fff
Foreground: #000
PrimaryPale: #ccccff
PrimaryLight: #ccccff
PrimaryMid: #333366
PrimaryDark: #014
SecondaryPale: #bbbbff
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #333366
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #9999cc
Error: #f88
Background: #fff
Foreground: #000
PrimaryPale: #ffccff
PrimaryLight: #ffccff
PrimaryMid: #ff0066
PrimaryDark: #014
SecondaryPale: #ffcccc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #ff0066
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #ff99cc
Error: #f88
/***An adaptation of [[easyFormat]]***/
//{{{
config.commands.Color = new TWkd.Ease('Color','change the color of selected text');

config.commands.Color.addMode({
 name:'Red',
 tooltip:'turns selection red',
 operation:function(){
config.commands.Color.putInPlace("{{red{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Blue',
 tooltip:'turns selection blue',
 operation:function(){
config.commands.Color.putInPlace("{{blue{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Green',
 tooltip:'turns selection green',
 operation:function(){
config.commands.Color.putInPlace("{{green{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Gold',
 tooltip:'turns selection gold',
 operation:function(){
config.commands.Color.putInPlace("{{gold{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Gray',
 tooltip:'turns selection gray',
 operation:function(){
config.commands.Color.putInPlace("{{gray{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Magenta',
 tooltip:'turns selection magenta',
 operation:function(){
config.commands.Color.putInPlace("{{magenta{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Purple',
 tooltip:'turns selection purple',
 operation:function(){
config.commands.Color.putInPlace("{{purple{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Teal',
 tooltip:'turns selection teal',
 operation:function(){
config.commands.Color.putInPlace("{{teal{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Color.addMode({
 name:'Burgundy',
 tooltip:'turns selection burgundy',
 operation:function(){
config.commands.Color.putInPlace("{{burgundy{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
//}}}
/***
|!''Name:''|!easyFormat|
|''Description:''|the format command format selection according to your choice|
|''Version:''|0.1.0|
|''Date:''|13/01/2007|
|''Source:''|[[TWkd|http://yann.perrin.googlepages.com/twkd.html#easyFormat]]|
|''Author:''|[[Yann Perrin|YannPerrin]]|
|''License:''|[[BSD open source license]]|
|''~CoreVersion:''|2.x|
|''Browser:''|Firefox 1.0.4+; Firefox 1.5; InternetExplorer 6.0|
|''Requires:''|@@color:red;''E.A.S.E''@@|
***/
//{{{
config.commands.Format = new TWkd.Ease('Format','format selection accordingly to chosen mode');

config.commands.Format.addMode({
 name:'Bold',
 tooltip:'turns selection into bold text',
 operation:function(){
config.commands.Format.putInPlace("''"+TWkd.context.selection.content+"''",TWkd.context.selection);
 }
});
config.commands.Format.addMode({
 name:'Italic',
 tooltip:'turns selection into italic text',
 operation:function(){
config.commands.Format.putInPlace("//"+TWkd.context.selection.content+"//",TWkd.context.selection);
 }
});
config.commands.Format.addMode({
 name:'Underline',
 tooltip:'underlines selected text',
 operation:function(){
config.commands.Format.putInPlace("__"+TWkd.context.selection.content+"__",TWkd.context.selection);
 }
});
config.commands.Format.addMode({
 name:'Highlight',
 tooltip:'highlight selection',
 operation:function(){
config.commands.Format.putInPlace("@@"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
config.commands.Format.addMode({
 name:'Hyperlink',
 tooltip:'turns selection into a link using double brackets',
 operation:function(){
config.commands.Format.putInPlace("[["+TWkd.context.selection.content+"]]",TWkd.context.selection);
 }
});
//}}}
/***An adaptation of [[easyFormat]]***/
//{{{
config.commands.Greek = new TWkd.Ease('Greek','formatting for Greek text');

config.commands.Greek.addMode({
 name:'Greek',
 tooltip:'formats Greek text correctly',
 operation:function(){
config.commands.Greek.putInPlace("{{greek{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Greek.addMode({
 name:'GkIndent1x',
 tooltip:'formats Gk and indents text 1x',
 operation:function(){
config.commands.Greek.putInPlace("{{gkindent{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Greek.addMode({
 name:'GkIndent2x',
 tooltip:'formats Gk and indents text 2x',
 operation:function(){
config.commands.Greek.putInPlace("{{gkindent{{{gkindent{"+TWkd.context.selection.content+"}}}}}}",TWkd.context.selection);
 }
});
config.commands.Greek.addMode({
 name:'GkIndent3x',
 tooltip:'formats Gk and indents text 3x',
 operation:function(){
config.commands.Greek.putInPlace("{{gkindent{{{gkindent{{{gkindent{"+TWkd.context.selection.content+"}}}}}}}}}",TWkd.context.selection);
 }
});
config.commands.Greek.addMode({
 name:'GkIndent4x',
 tooltip:'formats Gk and indents text 4x',
 operation:function(){
config.commands.Greek.putInPlace("{{gkindent{{{gkindent{{{gkindent{{{gkindent{"+TWkd.context.selection.content+"}}}}}}}}}}}}",TWkd.context.selection);
 }
});
config.commands.Greek.addMode({
 name:'GkIndent5x',
 tooltip:'formats Gk and indents text 5x',
 operation:function(){
config.commands.Greek.putInPlace("{{gkindent{{{gkindent{{{gkindent{{{gkindent{{{gkindent{"+TWkd.context.selection.content+"}}}}}}}}}}}}}}}",TWkd.context.selection);
 }
});
//}}}
/***An adaptation of [[easyFormat]]***/
//{{{
config.commands.Hebrew = new TWkd.Ease('Hebrew','formatting for Hebrew text');

config.commands.Hebrew.addMode({
 name:'HebrewNoAlign',
 tooltip:'formats Hebrew text correctly',
 operation:function(){
config.commands.Hebrew.putInPlace("{{hebrewNoAlign{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Hebrew.addMode({
 name:'HebrewRightAlign',
 tooltip:'formats Hebrew text correctly and aligns text to the right',
 operation:function(){
config.commands.Hebrew.putInPlace("{{hebrewRightAlign{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Hebrew.addMode({
 name:'HebIndent1x',
 tooltip:'formats Heb and indents text 1x',
 operation:function(){
config.commands.Hebrew.putInPlace("{{hebAlignAndIndent{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Hebrew.addMode({
 name:'HebIndent2x',
 tooltip:'formats Heb and indents text 2x',
 operation:function(){
config.commands.Hebrew.putInPlace("{{hebAlignAndIndent{{{hebAlignAndIndent{"+TWkd.context.selection.content+"}}}}}}",TWkd.context.selection);
 }
});
config.commands.Hebrew.addMode({
 name:'HebIndent3x',
 tooltip:'formats Heb and indents text 3x',
 operation:function(){
config.commands.Hebrew.putInPlace("{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{"+TWkd.context.selection.content+"}}}}}}}}}",TWkd.context.selection);
 }
});
config.commands.Hebrew.addMode({
 name:'HebIndent4x',
 tooltip:'formats Heb and indents text 4x',
 operation:function(){
config.commands.Hebrew.putInPlace("{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{"+TWkd.context.selection.content+"}}}}}}}}}}}}",TWkd.context.selection);
 }
});
config.commands.Hebrew.addMode({
 name:'HebIndent5x',
 tooltip:'formats Heb and indents text 5x',
 operation:function(){
config.commands.Hebrew.putInPlace("{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{{{hebAlignAndIndent{"+TWkd.context.selection.content+"}}}}}}}}}}}}}}}",TWkd.context.selection);
 }
});
//}}}
/***
This is an adaptation of:
|!''Name:''|!easyFormat|
|''Description:''|the format command format selection according to your choice|
|''Version:''|0.1.0|
|''Date:''|13/01/2007|
|''Source:''|[[TWkd|http://yann.perrin.googlepages.com/twkd.html#easyFormat]]|
|''Author:''|[[Yann Perrin|YannPerrin]]|
|''License:''|[[BSD open source license]]|
|''~CoreVersion:''|2.x|
|''Browser:''|Firefox 1.0.4+; Firefox 1.5; InternetExplorer 6.0|
|''Requires:''|@@color:red;''E.A.S.E''@@|
***/
//{{{
config.commands.Highlighting = new TWkd.Ease('Highlighting','highlight selected text with a color chosen from the list');
config.commands.Highlighting.addMode({
 name:'Red',
 tooltip:'highlights selection red',
 operation:function(){
config.commands.Highlighting.putInPlace("@@bgcolor(#ff6666):"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
config.commands.Highlighting.addMode({
 name:'Blue',
 tooltip:'highlights selection blue',
 operation:function(){
config.commands.Highlighting.putInPlace("@@bgcolor(#ccccff):"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
config.commands.Highlighting.addMode({
 name:'Yellow',
 tooltip:'highlights selection yellow',
 operation:function(){
config.commands.Highlighting.putInPlace("@@"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
config.commands.Highlighting.addMode({
 name:'Green',
 tooltip:'highlights selection green',
 operation:function(){
config.commands.Highlighting.putInPlace("@@bgcolor(#99ff99):"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
config.commands.Highlighting.addMode({
 name:'Brown',
 tooltip:'highlights selection brown',
 operation:function(){
config.commands.Highlighting.putInPlace("@@bgcolor(#cc9966):"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
config.commands.Highlighting.addMode({
 name:'Grey',
 tooltip:'highlight selection',
 operation:function(){
config.commands.Highlighting.putInPlace("@@bgcolor(#cccc99):"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
config.commands.Highlighting.addMode({
 name:'Orange',
 tooltip:'turns selection into unicode text, for Greek characters',
 operation:function(){
config.commands.Highlighting.putInPlace("@@bgcolor(#ff9933):"+TWkd.context.selection.content+"@@",TWkd.context.selection);
 }
});
//}}}
/***An adaptation of [[easyFormat]]***/
//{{{
config.commands.Indent = new TWkd.Ease('Indent','indents selected text as a blockquote');

config.commands.Indent.addMode({
 name:'Indent1x',
 tooltip:'indents text 1x',
 operation:function(){
config.commands.Indent.putInPlace("{{engindent{"+TWkd.context.selection.content+"}}}",TWkd.context.selection);
 }
});
config.commands.Indent.addMode({
 name:'Indent2x',
 tooltip:'indents text 2x',
 operation:function(){
config.commands.Indent.putInPlace("{{engindent{{{engindent{"+TWkd.context.selection.content+"}}}}}}",TWkd.context.selection);
 }
});
config.commands.Indent.addMode({
 name:'Indent3x',
 tooltip:'indents text 3x',
 operation:function(){
config.commands.Indent.putInPlace("{{engindent{{{engindent{{{engindent{"+TWkd.context.selection.content+"}}}}}}}}}",TWkd.context.selection);
 }
});
config.commands.Indent.addMode({
 name:'Indent4x',
 tooltip:'indents text 4x',
 operation:function(){
config.commands.Indent.putInPlace("{{engindent{{{engindent{{{engindent{{{engindent{"+TWkd.context.selection.content+"}}}}}}}}}}}}",TWkd.context.selection);
 }
});
config.commands.Indent.addMode({
 name:'Indent5x',
 tooltip:'indents text 5x',
 operation:function(){
config.commands.Indent.putInPlace("{{engindent{{{engindent{{{engindent{{{engindent{{{engindent{"+TWkd.context.selection.content+"}}}}}}}}}}}}}}}",TWkd.context.selection);
 }
});
//}}}
/***An adaptation of [[easyFormat]]***/
//{{{
config.commands.Notes = new TWkd.Ease('Notes','add notes and popups');

config.commands.Notes.addMode({
 name:'Syntax',
 tooltip:'adds syntax note',
 operation:function(){
config.commands.Notes.putInPlace("((syntax(add note here)))",TWkd.context.selection);
 }
});
config.commands.Notes.addMode({
 name:'Translation',
 tooltip:'adds syntax note',
 operation:function(){
config.commands.Notes.putInPlace("&#149; ((translation(add note here)))",TWkd.context.selection);
 }
});
config.commands.Notes.addMode({
 name:'Text',
 tooltip:'adds textual note',
 operation:function(){
config.commands.Notes.putInPlace("&#149; ((text(add note here)))",TWkd.context.selection);
 }
});
config.commands.Notes.addMode({
 name:'Gramm.',
 tooltip:'adds grammatical note',
 operation:function(){
config.commands.Notes.putInPlace("&#149; ((gram(add note here)))",TWkd.context.selection);
 }
});
config.commands.Notes.addMode({
 name:'Popup',
 tooltip:'adds popup note to selected text',
 operation:function(){
config.commands.Notes.putInPlace("(("+TWkd.context.selection.content+"(add note here)))",TWkd.context.selection);
 }
});
//}}}
/***An adaptation of [[easyFormat]]***/
//{{{
config.commands.Tableheader = new TWkd.Ease('Tableheader','add the header row for a formatted table');

config.commands.Tableheader.addMode({
 name:'Invisible',
 tooltip:'adds the header row for a 3-column invisible table',
 operation:function(){
config.commands.Tableheader.putInPlace("XXXXX",TWkd.context.selection);
 }
});

config.commands.Tableheader.addMode({
 name:'Sortable',
 tooltip:'adds the header row for a 3-column sortable table',
 operation:function(){
config.commands.Tableheader.putInPlace("|sortable|k||||h",TWkd.context.selection);
 }
});

config.commands.Tableheader.addMode({
 name:'Standard',
 tooltip:'adds the header row for a 3-column standard table',
 operation:function(){
config.commands.Tableheader.putInPlace("|!|!|!|",TWkd.context.selection);
 }
});

//}}}
/***An adaptation of [[easyFormat]]***/
//{{{
config.commands.Tables = new TWkd.Ease('Tables','add preformatted empty tables');

config.commands.Tables.addMode({
 name:'Invisible',
 tooltip:'adds borderless table',
 operation:function(){
config.commands.Tables.putInPlace("{{invisiblecomm{\n|!|!|!|\n||||\n||||\n||||\n}}}",TWkd.context.selection);
 }
});
config.commands.Tables.addMode({
 name:'Sortable',
 tooltip:'adds a sortable table',
 operation:function(){
config.commands.Tables.putInPlace("|sortable|k\n||||h\n||||\n||||\n||||",TWkd.context.selection);
 }
});
config.commands.Tables.addMode({
 name:'Standard',
 tooltip:'adds a standard table',
 operation:function(){
config.commands.Tables.putInPlace("|!|!|!|\n||||\n||||\n||||",TWkd.context.selection);
 }
});
config.commands.Tables.addMode({
 name:'light gray cell',
 tooltip:'inserts a light gray color code into a table cell',
 operation:function(){
config.commands.Tables.putInPlace("bgcolor(#eeeeee):",TWkd.context.selection);
 }
});
config.commands.Tables.addMode({
 name:'dark gray cell',
 tooltip:'inserts a dark gray color code into a table cell',
 operation:function(){
config.commands.Tables.putInPlace("bgcolor(#cccccc):",TWkd.context.selection);
 }
});
//}}}
Graphics Plotting Package: http://had.co.nz/ggplot2/

<html><img src="00/ggplot2.png" style="height:150px"></html>
[[1. Download the general manual (PDF)|00/ggplot2-book.pdf]]
[[2. Download the package function list (PDF)|00/ggplot2.pdf]]
!!
Background: #fff
Foreground: #000
PrimaryPale: #eeeeee
PrimaryLight: #eeeeee
PrimaryMid: #666666
PrimaryDark: #014
SecondaryPale: #cccccc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #666666
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #bbbbbb
Error: #f88
Background: #fff
Foreground: #000
PrimaryPale: #ddeeaa
PrimaryLight: #ddeeaa
PrimaryMid: #666633
PrimaryDark: #014
SecondaryPale: #bbdd88
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #666633
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #aacc88
Error: #f88
{{{
plot(d[,1], d[,10]) ####basic plot
}}}
<html><img src="0613/p01.png" style="height:400px"></html>
!
[[BACK|13JUNE]]
!

{{{
plot(d[,1], d[,10], xlab = "Time", ylab = "CH1Avg", main = "Wind Plot") ####basic plot with labels
}}}
<html><img src="0613/p02.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
plot(d[,1], d[,10], xlab = "Time", ylab = "CH1Avg", main = "Wind Plot", type = "l") ####basic plot lines
}}}
<html><img src="0613/p03.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
plot(d[,1], d[,10], xlab = "Time", ylab = "CH1Avg", main = "Wind Plot", type = "o") ####basic plot lines and points
}}}
<html><img src="0613/p04.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
plot(d[,1], d[,10], xlab = "Time", ylab = "CH1Avg", main = "Wind Plot", type = "o", col = "blue") ####basic plot lines and points in blue
}}}
<html><img src="0613/p05.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
plot(d[,1], d[,10], xlab = "Time", ylab = "CH1Avg", main = "Wind Plot", type = "o", col = "red", pch = 15) ####basic plot lines and points in red with new symbols
}}}
<html><img src="0613/p06.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
plot(1:25, 1:25, pch = 1:25, col = 1:8) #####plot showing symbol and basic color combinations
plot(1:25, 1:25, pch = 1:25, col = 1:8, cex = 3) #####plot showing symbol and basic color combinations with larger size
}}}
<html><table><tr>
<td><img src="0613/p07a.png" style="height:300px"></td>

<td><img src="0613/p07b.png" style="height:300px"></td>
</tr></table></html>
!
[[BACK|13JUNE]]
!
{{{
plot(d[,1], d[,10], xlab = "Time", ylab = "Arbitrary value", main = "Wind Plot", type = "o", col = "red", pch = 1, cex = 1.5) ####basic plot lines and points in red with new symbols
points(d[,1], d[,11],  type = "o", col = "blue", pch = 20, cex = 1.5) ####adding plot lines to existing plots
text(2008.448, 20, "CH1Avg") ####adding text to existing plots
text(2008.452, 4, "CH1SD") #####adding text to existing plots
}}}

<html><img src="0613/p08.png" style="height:400px"></html>
!
[[BACK|13JUNE]]
!
{{{
hist(d[,10]) ###basic histogram
}}}
<html><img src="0613/p09.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
hist(d[,10], xlab = "CH1Avg", main = "Histogram of CH1Avg") ####basic histogram with labels
}}}
<html><img src="0613/p10.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
hist(d[,10], xlab = "CH1Avg", main = "Histogram of CH1Avg", breaks = 50) ####basic histogram with labels with increasing the number of bins
}}}
<html><img src="0613/p11.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
hist(d[,10], xlab = "CH1Avg", main = "Histogram of CH1Avg", breaks = c(min(d[,10]),3,5, 15,17, 20, max(d[,10]))) ####basic histogram with labels with specifying the break points
}}}
<html><img src="0613/p12.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
{{{
hist(d[,10], xlab = "CH1Avg", main = "Histogram of CH1Avg", breaks = 50, col = c("green", "red")) ####basic histogram with labels with alternating colors
}}}
<html><img src="0613/p13.png" style="height:400px"></html>

!
[[BACK|13JUNE]]
!
''First part of the R script just reformats the data.
This is called "casting" using the function "melt":''
{{{
#------- We R Group ------------
# SESSION 13JUNE:
# PLOTTING WITH GGPLOT2
#-------------------------------

# load the ggplot2 library
   library("ggplot2")

# input sample wind tower data . . . . . .
   data_url <- c("http://icewater.cms.udel.edu/Rgroup/0613/wind_data_ex.txt") 
   d <- read.table(data_url, header=TRUE, sep="\t")

# copy the AVERAGE data for anemometers 1-6 to new data.frame
   WindSpeedAvg <- d[,c(1,10,14,18,22,26,30)]

# reorganize the data using "melt" to combine
#      all windspeed obs into one variable and create a
#      new variable that contains the anemometer number (CH1....) 
   mWS <- melt(WindSpeedAvg, id=c(1))
   
# rename vars just for clarity . . . . . . . 
   names(mWS)[which(names(mWS)=="variable")] <- "anem"

   names(mWS)[which(names(mWS)=="value")] <- "windspeed"
   
# translate anemometer number into factor levels
   mWS$anem <- as.factor(mWS$anem)
}}}
!!
''Plot 14a is a single panel with the first 6 anemometers''
{{{
# PLOT 14a: single xy plot of anemometers 1-6. . . . . . . .
p <-ggplot(data=mWS,aes(x=Seq_time,y=windspeed)) +
    geom_line(aes(colour=anem),size=1) +
    geom_point(aes(colour=anem),size=1.5) +
    scale_y_continuous("Wind Speed (meters per second)") +
    scale_x_continuous("Observation Time (10 min intervals)")
p
}}}
<html><img src="0613/ggplot01.png" style="height:400px"></html>

!!
''Plot 14b is a grid of each separate anemometer in a vertical stack''
{{{
# PLOT 14b: grid plot of each anemometer separately . . . . . . .
p <- ggplot(data=mWS,aes(x=Seq_time,y=windspeed)) +
    geom_line(colour="black",size=1) +
    geom_point(aes(colour=anem),size=1) +
    facet_grid(anem ~ .) +
    scale_y_continuous("Wind Speed (meters per second)") +
    scale_x_continuous("Observation Time (10 min intervals)")
p$legend.position <- c("none")
p
}}}
<html><img src="0613/ggplot02.png" style="height:400px"></html>

!!
''Plot 14c is a histogram grid of each anemometer in a vertical stack''
{{{
# PLOT 14c: histogram plot of each anemometer . . . . . . .
p <- ggplot(data=mWS,aes(x=windspeed)) +
         geom_histogram(aes(fill=factor(windspeed))) +
         facet_grid(anem ~ .)
p$legend.position <- c("none")
p
}}}
<html><img src="0613/ggplot03.png" style="height:500px"></html>
!
[[BACK|13JUNE]]
!
Background: #fff
Foreground: #000
PrimaryPale: #ddccff
PrimaryLight: #ddccff
PrimaryMid: #5500aa
PrimaryDark: #014
SecondaryPale: #ddbbff
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #5500aa
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #ccaaff
Error: #f88
<?php
/***
! User settings
Edit these lines according to your need
***/
//{{{
$AUTHENTICATE_USER = true;	// true | false
$USERS = array(
	'UserName1'=>'Password1', 
	'UserName2'=>'Password2', 
	'UserName3'=>'Password3'); // set usernames and strong passwords
$DEBUG = false;				// true | false
$CLEAN_BACKUP = true; 		// during backuping a file, remove overmuch backups
$FOLD_JS = true; 			// if javascript files have been expanded during download the fold them
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//}}}
/***
!Code
No change needed under
***/
//{{{

/***
 * store.php - upload a file in this directory
 * version :1.6.1 - 2007/08/01 - BidiX@BidiX.info
 * 
 * see : 
 *	http://tiddlywiki.bidi.info/#UploadPlugin for usage
 *	http://www.php.net/manual/en/features.file-upload.php 
 *		for details on uploading files
 * usage : 
 *	POST  
 *		UploadPlugin[backupDir=<backupdir>;user=<user>;password=<password>;uploadir=<uploaddir>;[debug=1];;]
 *		userfile <file>

 *	GET
 *
 * each external javascript file included by download.php is change by a reference (src=...)
 *
 * Revision history
 * V1.6.1 - 2007/08/01
 * Enhancement: Add javascript folding
 * V1.6.0 - 2007/05/17
 * Enhancement: Add backup management
 * V1.5.2 - 2007/02/13
 * Enhancement: Add optional debug option in client parameters
 * V1.5.1 - 2007/02/01
 * Enhancement: Check value of file_uploads in php.ini. Thanks to Didier Corbière
 * V1.5.0 - 2007/01/15
 * Correct: a bug in moving uploadFile in uploadDir thanks to DaniGutiérrez for reporting
 * Refactoring
 * V 1.4.3 - 2006/10/17 
 * Test if $filename.lock exists for GroupAuthoring compatibility
 * return mtime, destfile and backupfile after the message line
 * V 1.4.2 - 2006/10/12
 *  add error_reporting(E_PARSE);
 * v 1.4.1 - 2006/03/15
 *	add chmo 0664 on the uploadedFile
 * v 1.4 - 2006/02/23
 * 	add uploaddir option :  a path for the uploaded file relative to the current directory
 *	backupdir is a relative path
 *	make recusively directories if necessary for backupDir and uploadDir
 * v 1.3 - 2006/02/17
 *	presence and value of user are checked with $USERS Array (thanks to PauloSoares)
 * v 1.2 - 2006/02/12 
  *	POST  
 *		UploadPlugin[backupDir=<backupdir>;user=<user>;password=<password>;]
 *		userfile <file>
*	if $AUTHENTICATE_USER
 *		presence and value of user and password are checked with 
 *		$USER and $PASSWORD
 * v 1.1 - 2005/12/23 
 *	POST  UploadPlugin[backupDir=<backupdir>]  userfile <file>
 * v 1.0 - 2005/12/12 
 *	POST userfile <file>

 *
 * Copyright (c) BidiX@BidiX.info 2005-2007
 ***/
//}}}

//{{{

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
	/*
	 * GET Request
	 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

		<title>BidiX.info - TiddlyWiki UploadPlugin - Store script</title>
	</head>
	<body>
		<p>
		<p>store.php V 1.6.1
		<p>BidiX@BidiX.info
		<p>&nbsp;</p>

		<p>&nbsp;</p>
		<p>&nbsp;</p>
		<p align="center">This page is designed to upload a <a href="http://www.tiddlywiki.com/">TiddlyWiki<a>.</p>

		<p align="center">for details see : <a href="http://TiddlyWiki.bidix.info/#HowToUpload">TiddlyWiki.bidix.info/#HowToUpload<a>.</p>	
	</body>
</html>
<?php
exit;
}

/*
 * POST Request
 */
	 
// Recursive mkdir
function mkdirs($dir) {
	if( is_null($dir) || $dir === "" ){
		return false;
	}
	if( is_dir($dir) || $dir === "/" ){
		return true;
	}
	if( mkdirs(dirname($dir)) ){
		return mkdir($dir);
	}
	return false;
}

function toExit() {
	global $DEBUG, $filename, $backupFilename, $options;
	if ($DEBUG) {
		echo ("\nHere is some debugging info : \n");
		echo("\$filename : $filename \n");
		echo("\$backupFilename : $backupFilename \n");
		print ("\$_FILES : \n");
		print_r($_FILES);
		print ("\$options : \n");
		print_r($options);
}
exit;
}

function ParseTWFileDate($s) {
	// parse date element
	preg_match ( '/^(\d\d\d\d)(\d\d)(\d\d)\.(\d\d)(\d\d)(\d\d)/', $s , $m );
	// make a date object
	$d = mktime($m[4], $m[5], $m[6], $m[2], $m[3], $m[1]);
	// get the week number
	$w = date("W",$d);

	return array(
		'year' => $m[1], 
		'mon' => $m[2], 
		'mday' => $m[3], 
		'hours' => $m[4], 
		'minutes' => $m[5], 
		'seconds' => $m[6], 
		'week' => $w);
}

function cleanFiles($dirname, $prefix) {
	$now = getdate();
	$now['week'] = date("W");

	$hours = Array();
	$mday = Array();
	$year = Array();
	
	$toDelete = Array();

	// need files recent first
	$files = Array();
	($dir = opendir($dirname)) || die ("can't open dir '$dirname'");
	while (false !== ($file = readdir($dir))) {
		if (preg_match("/^$prefix/", $file))
        array_push($files, $file);
    }
	$files = array_reverse($files);
	
	// decides for each file
	foreach ($files as $file) {
		$fileTime = ParseTWFileDate(substr($file,strpos($file, '.')+1,strrpos($file,'.') - strpos($file, '.') -1));
		if (($now['year'] == $fileTime['year']) &&

			($now['mon'] == $fileTime['mon']) &&
			($now['mday'] == $fileTime['mday']) &&
			($now['hours'] == $fileTime['hours']))
				continue;
		elseif (($now['year'] == $fileTime['year']) &&
			($now['mon'] == $fileTime['mon']) &&
			($now['mday'] == $fileTime['mday'])) {
				if (isset($hours[$fileTime['hours']]))
					array_push($toDelete, $file);
				else 
					$hours[$fileTime['hours']] = true;
			}
		elseif 	(($now['year'] == $fileTime['year']) &&
			($now['mon'] == $fileTime['mon'])) {
				if (isset($mday[$fileTime['mday']]))
					array_push($toDelete, $file);
				else
					$mday[$fileTime['mday']] = true;
			}
		else {
			if (isset($year[$fileTime['year']][$fileTime['mon']]))
				array_push($toDelete, $file);
			else
				$year[$fileTime['year']][$fileTime['mon']] = true;
		}
	}
	return $toDelete;
}

function replaceJSContentIn($content) {
	if (preg_match ("/(.*?)<!--DOWNLOAD-INSERT-FILE:\"(.*?)\"--><script\s+type=\"text\/javascript\">(.*)/ms", $content,$matches)) {
		$front = $matches[1];
		$js = $matches[2];
		$tail = $matches[3];
		if (preg_match ("/<\/script>(.*)/ms", $tail,$matches2)) {		
			$tail = $matches2[1];
		}
		$jsContent = "<script type=\"text/javascript\" src=\"$js\"></script>";
		$tail = replaceJSContentIn($tail);
		return($front.$jsContent.$tail);
	}
	else
		return $content;
}

// Check if file_uploads is active in php config
if (ini_get('file_uploads') != '1') {
   echo "Error : File upload is not active in php.ini\n";
   toExit();
}

// var definitions
$uploadDir = './';
$uploadDirError = false;
$backupError = false;
$optionStr = $_POST['UploadPlugin'];
$optionArr=explode(';',$optionStr);
$options = array();
$backupFilename = '';
$filename = $_FILES['userfile']['name'];
$destfile = $filename;

// get options
foreach($optionArr as $o) {
	list($key, $value) = split('=', $o);
	$options[$key] = $value;
}

// debug activated by client
if ($options['debug'] == 1) {
	$DEBUG = true;
}

// authenticate User
if (($AUTHENTICATE_USER)
	&& ((!$options['user']) || (!$options['password']) || ($USERS[$options['user']] != $options['password']))) {
	echo "Error : UserName or Password do not match \n";
	echo "UserName : [".$options['user']. "] Password : [". $options['password'] . "]\n";
	toExit();
}



// make uploadDir
if ($options['uploaddir']) {
	$uploadDir = $options['uploaddir'];
	// path control for uploadDir   
    if (!(strpos($uploadDir, "../") === false)) {
        echo "Error: directory to upload specifies a parent folder";
        toExit();
	}
	if (! is_dir($uploadDir)) {
		mkdirs($uploadDir);
	}
	if (! is_dir($uploadDir)) {
		echo "UploadDirError : $uploadDirError - File NOT uploaded !\n";
		toExit();
	}
	if ($uploadDir{strlen($uploadDir)-1} != '/') {
		$uploadDir = $uploadDir . '/';
	}
}
$destfile = $uploadDir . $filename;

// backup existing file
if (file_exists($destfile) && ($options['backupDir'])) {
	if (! is_dir($options['backupDir'])) {
		mkdirs($options['backupDir']);
		if (! is_dir($options['backupDir'])) {
			$backupError = "backup mkdir error";
		}
	}
	$backupFilename = $options['backupDir'].'/'.substr($filename, 0, strrpos($filename, '.'))
				.date('.Ymd.His').substr($filename,strrpos($filename,'.'));
	rename($destfile, $backupFilename) or ($backupError = "rename error");
	// remove overmuch backup
	if ($CLEAN_BACKUP) {
		$toDelete = cleanFiles($options['backupDir'], substr($filename, 0, strrpos($filename, '.')));
		foreach ($toDelete as $file) {
			$f = $options['backupDir'].'/'.$file;
			if($DEBUG) {
				echo "delete : ".$options['backupDir'].'/'.$file."\n";
			}
			unlink($options['backupDir'].'/'.$file);
		}
	}
}

// move uploaded file to uploadDir
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $destfile)) {
	if ($FOLD_JS) {
		// rewrite the file to replace JS content
		$fileContent = file_get_contents ($destfile);
		$fileContent = replaceJSContentIn($fileContent);
		if (!$handle = fopen($destfile, 'w')) {
	         echo "Cannot open file ($destfile)";
	         exit;
	    }
	    if (fwrite($handle, $fileContent) === FALSE) {
	        echo "Cannot write to file ($destfile)";
	        exit;
	    }
	    fclose($handle);
	}
    
	chmod($destfile, 0644);
	if($DEBUG) {
		echo "Debug mode \n\n";
	}
	if (!$backupError) {
		echo "0 - File successfully loaded in " .$destfile. "\n";
	} else {
		echo "BackupError : $backupError - File successfully loaded in " .$destfile. "\n";
	}
	echo("destfile:$destfile \n");
	if (($backupFilename) && (!$backupError)) {
		echo "backupfile:$backupFilename\n";
	}
	$mtime = filemtime($destfile);
	echo("mtime:$mtime");
} 
else {
	echo "Error : " . $_FILES['error']." - File NOT uploaded !\n";

}
toExit();
//}}}
?>
{{tableindex{
|[[Subject01]]|[[Subject02]]|[[subtopic3]]|
}}}
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>
<div class='topic1' macro='tiddler topic1SubtopicMenu'></div>
<div class='title' macro='view title'></div>

<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
<!--{{{-->
<div class='toolbar' macro='toolbar closeTiddler closeOthers +editTiddler > fields syncing permalink references jump'></div>

<div class='webview' macro='tiddler webviewindex'></div>
<div class='title' macro='view title'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
{{tableindex{
|[[Welcome|Welcome to the Webview TiddlyWiki]]|[[Instructions]]|[[Subtopic menu instructions]]|
}}}
config.options.chkSaveBackups = false;
config.options.chkEnableAnimations = false;
config.options.chkShowRightSidebar= false;
config.options.chkSinglePageMode= true;
config.options.chkSinglePagePermalink= false;