text:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

/// <summary>
/// Inspector class used to view and edit UIFonts.
/// </summary>

[CustomEditor(typeof(UIFont))]
public class UIFontInspector : Editor
{
	enum View
	{
		Nothing,
		Atlas,
		Font,
	}

	enum FontType
	{
		Normal,
		Reference,
		Dynamic,
	}

	static View mView = View.Font;
	static bool mUseShader = false;

	UIFont mFont;
	FontType mType = FontType.Normal;
	UIFont mReplacement = null;
	string mSymbolSequence = "";
	string mSymbolSprite = "";
	BMSymbol mSelectedSymbol = null;

	public override bool HasPreviewGUI () { return mView != View.Nothing; }

	void OnSelectFont (Object obj)
	{
		// Undo doesn't work correctly in this case... so I won't bother.
		//NGUIEditorTools.RegisterUndo("Font Change");
		//NGUIEditorTools.RegisterUndo("Font Change", mFont);

		mFont.replacement = obj as UIFont;
		mReplacement = mFont.replacement;
		UnityEditor.EditorUtility.SetDirty(mFont);
		if (mReplacement == null) mType = FontType.Normal;
	}

	void OnSelectAtlas (Object obj)
	{
		if (mFont != null)
		{
			NGUIEditorTools.RegisterUndo("Font Atlas", mFont);
			mFont.atlas = obj as UIAtlas;
			MarkAsChanged();
		}
	}

	void MarkAsChanged ()
	{
		List<UILabel> labels = NGUIEditorTools.FindAll<UILabel>();

		foreach (UILabel lbl in labels)
		{
			if (UIFont.CheckIfRelated(lbl.bitmapFont, mFont))
			{
				lbl.bitmapFont = null;
				lbl.bitmapFont = mFont;
			}
		}
	}

	public override void OnInspectorGUI ()
	{
		mFont = target as UIFont;
		NGUIEditorTools.SetLabelWidth(80f);

		GUILayout.Space(6f);

		if (mFont.replacement != null)
		{
			mType = FontType.Reference;
			mReplacement = mFont.replacement;
		}
		else if (mFont.dynamicFont != null)
		{
			mType = FontType.Dynamic;
		}

		GUILayout.BeginHorizontal();
		FontType fontType = (FontType)EditorGUILayout.EnumPopup("Font Type", mType);
		GUILayout.Space(18f);
		GUILayout.EndHorizontal();

		if (mType != fontType)
		{
			if (fontType == FontType.Normal)
			{
				OnSelectFont(null);
			}
			else
			{
				mType = fontType;
			}

			if (mType != FontType.Dynamic && mFont.dynamicFont != null)
				mFont.dynamicFont = null;
		}

		if (mType == FontType.Reference)
		{
			ComponentSelector.Draw<UIFont>(mFont.replacement, OnSelectFont, true);

			GUILayout.Space(6f);
			EditorGUILayout.HelpBox("You can have one font simply point to " +
				"another one. This is useful if you want to be " +
				"able to quickly replace the contents of one " +
				"font with another one, for example for " +
				"swapping an SD font with an HD one, or " +
				"replacing an English font with a Chinese " +
				"one. All the labels referencing this font " +
				"will update their references to the new one.", MessageType.Info);

			if (mReplacement != mFont && mFont.replacement != mReplacement)
			{
				NGUIEditorTools.RegisterUndo("Font Change", mFont);
				mFont.replacement = mReplacement;
				UnityEditor.EditorUtility.SetDirty(mFont);
			}
			return;
		}
		else if (mType == FontType.Dynamic)
		{
#if UNITY_3_5
			EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
			Font fnt = EditorGUILayout.ObjectField("TTF Font", mFont.dynamicFont, typeof(Font), false) as Font;

			if (fnt != mFont.dynamicFont)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.dynamicFont = fnt;
			}

			Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

			if (mFont.material != mat)
			{
				NGUIEditorTools.RegisterUndo("Font Material", mFont);
				mFont.material = mat;
			}

			GUILayout.BeginHorizontal();
			int size = EditorGUILayout.IntField("Default Size", mFont.defaultSize, GUILayout.Width(120f));
			FontStyle style = (FontStyle)EditorGUILayout.EnumPopup(mFont.dynamicFontStyle);
			GUILayout.Space(18f);
			GUILayout.EndHorizontal();

			if (size != mFont.defaultSize)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.defaultSize = size;
			}

			if (style != mFont.dynamicFontStyle)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.dynamicFontStyle = style;
			}
#endif
		}
		else
		{
			NGUIEditorTools.DrawSeparator();

			ComponentSelector.Draw<UIAtlas>(mFont.atlas, OnSelectAtlas, true);

			if (mFont.atlas != null)
			{
				if (mFont.bmFont.isValid)
				{
					NGUIEditorTools.DrawAdvancedSpriteField(mFont.atlas, mFont.spriteName, SelectSprite, false);
				}
				EditorGUILayout.Space();
			}
			else
			{
				// No atlas specified -- set the material and texture rectangle directly
				Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

				if (mFont.material != mat)
				{
					NGUIEditorTools.RegisterUndo("Font Material", mFont);
					mFont.material = mat;
				}
			}

			// For updating the font's data when importing from an external source, such as the texture packer
			bool resetWidthHeight = false;

			if (mFont.atlas != null || mFont.material != null)
			{
				TextAsset data = EditorGUILayout.ObjectField("Import Data", null, typeof(TextAsset), false) as TextAsset;

				if (data != null)
				{
					NGUIEditorTools.RegisterUndo("Import Font Data", mFont);
					BMFontReader.Load(mFont.bmFont, NGUITools.GetHierarchy(mFont.gameObject), data.bytes);
					mFont.MarkAsChanged();
					resetWidthHeight = true;
					Debug.Log("Imported " + mFont.bmFont.glyphCount + " characters");
				}
			}

			if (mFont.bmFont.isValid)
			{
				Texture2D tex = mFont.texture;

				if (tex != null && mFont.atlas == null)
				{
					// Pixels are easier to work with than UVs
					Rect pixels = NGUIMath.ConvertToPixels(mFont.uvRect, tex.width, tex.height, false);

					// Automatically set the width and height of the rectangle to be the original font texture's dimensions
					if (resetWidthHeight)
					{
						pixels.width = mFont.texWidth;
						pixels.height = mFont.texHeight;
					}

					// Font sprite rectangle
					GUI.backgroundColor = new Color(0.4f, 1f, 0f, 1f);
					pixels = EditorGUILayout.RectField("Pixel Rect", pixels);
					GUI.backgroundColor = Color.white;

					// Create a button that can make the coordinates pixel-perfect on click
					GUILayout.BeginHorizontal();
					{
						Rect corrected = NGUIMath.MakePixelPerfect(pixels);

						if (corrected == pixels)
						{
							GUI.color = Color.grey;
							GUILayout.Button("Make Pixel-Perfect");
							GUI.color = Color.white;
						}
						else if (GUILayout.Button("Make Pixel-Perfect"))
						{
							pixels = corrected;
							GUI.changed = true;
						}
					}
					GUILayout.EndHorizontal();

					// Convert the pixel coordinates back to UV coordinates
					Rect uvRect = NGUIMath.ConvertToTexCoords(pixels, tex.width, tex.height);

					if (mFont.uvRect != uvRect)
					{
						NGUIEditorTools.RegisterUndo("Font Pixel Rect", mFont);
						mFont.uvRect = uvRect;
					}
					//NGUIEditorTools.DrawSeparator();
					EditorGUILayout.Space();
				}
			}
		}

		// The font must be valid at this point for the rest of the options to show up
		if (mFont.isDynamic || mFont.bmFont.isValid)
		{
			if (mFont.atlas == null)
			{
				mView = View.Font;
				mUseShader = false;

				float pixelSize = EditorGUILayout.FloatField("Pixel Size", mFont.pixelSize, GUILayout.Width(120f));

				if (pixelSize != mFont.pixelSize)
				{
					NGUIEditorTools.RegisterUndo("Font Change", mFont);
					mFont.pixelSize = pixelSize;
				}
			}
			EditorGUILayout.Space();
		}

		// Preview option
		if (!mFont.isDynamic && mFont.atlas != null)
		{
			GUILayout.BeginHorizontal();
			{
				mView = (View)EditorGUILayout.EnumPopup("Preview", mView);
				GUILayout.Label("Shader", GUILayout.Width(45f));
				mUseShader = EditorGUILayout.Toggle(mUseShader, GUILayout.Width(20f));
			}
			GUILayout.EndHorizontal();
		}

		// Dynamic fonts don't support emoticons
		if (!mFont.isDynamic && mFont.bmFont.isValid)
		{
			if (mFont.atlas != null)
			{
				if (NGUIEditorTools.DrawHeader("Symbols and Emoticons"))
				{
					NGUIEditorTools.BeginContents();

					List<BMSymbol> symbols = mFont.symbols;

					for (int i = 0; i < symbols.Count; )
					{
						BMSymbol sym = symbols[i];

						GUILayout.BeginHorizontal();
						GUILayout.Label(sym.sequence, GUILayout.Width(40f));
						if (NGUIEditorTools.DrawSpriteField(mFont.atlas, sym.spriteName, ChangeSymbolSprite))
							mSelectedSymbol = sym;

						if (GUILayout.Button("Edit", GUILayout.Width(40f)))
						{
							if (mFont.atlas != null)
							{
								NGUISettings.atlas = mFont.atlas;
								NGUISettings.selectedSprite = sym.spriteName;
								NGUIEditorTools.Select(mFont.atlas.gameObject);
							}
						}

						GUI.backgroundColor = Color.red;

						if (GUILayout.Button("X", GUILayout.Width(22f)))
						{
							NGUIEditorTools.RegisterUndo("Remove symbol", mFont);
							mSymbolSequence = sym.sequence;
							mSymbolSprite = sym.spriteName;
							symbols.Remove(sym);
							mFont.MarkAsChanged();
						}
						GUI.backgroundColor = Color.white;
						GUILayout.EndHorizontal();
						GUILayout.Space(4f);
						++i;
					}

					if (symbols.Count > 0)
					{
						GUILayout.Space(6f);
					}

					GUILayout.BeginHorizontal();
					mSymbolSequence = EditorGUILayout.TextField(mSymbolSequence, GUILayout.Width(40f));
					NGUIEditorTools.DrawSpriteField(mFont.atlas, mSymbolSprite, SelectSymbolSprite);

					bool isValid = !string.IsNullOrEmpty(mSymbolSequence) && !string.IsNullOrEmpty(mSymbolSprite);
					GUI.backgroundColor = isValid ? Color.green : Color.grey;

					if (GUILayout.Button("Add", GUILayout.Width(40f)) && isValid)
					{
						NGUIEditorTools.RegisterUndo("Add symbol", mFont);
						mFont.AddSymbol(mSymbolSequence, mSymbolSprite);
						mFont.MarkAsChanged();
						mSymbolSequence = "";
						mSymbolSprite = "";
					}
					GUI.backgroundColor = Color.white;
					GUILayout.EndHorizontal();

					if (symbols.Count == 0)
					{
						EditorGUILayout.HelpBox("Want to add an emoticon to your font? In the field above type ':)', choose a sprite, then hit the Add button.", MessageType.Info);
					}
					else GUILayout.Space(4f);

					NGUIEditorTools.EndContents();
				}
			}
		}
	}

	/// <summary>
	/// "New Sprite" selection.
	/// </summary>

	void SelectSymbolSprite (string spriteName)
	{
		mSymbolSprite = spriteName;
		Repaint();
	}

	/// <summary>
	/// Existing sprite selection.
	/// </summary>

	void ChangeSymbolSprite (string spriteName)
	{
		if (mSelectedSymbol != null && mFont != null)
		{
			NGUIEditorTools.RegisterUndo("Change symbol", mFont);
			mSelectedSymbol.spriteName = spriteName;
			Repaint();
			mFont.MarkAsChanged();
		}
	}

	/// <summary>
	/// Draw the font preview window.
	/// </summary>

	public override void OnPreviewGUI (Rect rect, GUIStyle background)
	{
		mFont = target as UIFont;
		if (mFont == null) return;
		Texture2D tex = mFont.texture;

		if (mView != View.Nothing && tex != null)
		{
			Material m = (mUseShader ? mFont.material : null);

			if (mView == View.Font && mFont.sprite != null)
			{
				NGUIEditorTools.DrawSprite(tex, rect, mFont.sprite, Color.white, m);
			}
			else
			{
				NGUIEditorTools.DrawTexture(tex, rect, new Rect(0f, 0f, 1f, 1f), Color.white, m);
			}
		}
	}

	/// <summary>
	/// Sprite selection callback.
	/// </summary>

	void SelectSprite (string spriteName)
	{
		NGUIEditorTools.RegisterUndo("Font Sprite", mFont);
		mFont.spriteName = spriteName;
		Repaint();
	}
}


text:
    padding-top: 25px;
}

#parameters a {
    color: #00aadf;
}

#parameters .column-label {
    font-size: 22px;
}

#parameters .border-box {
    border: solid black 1px;
    border-radius: 5px;
    overflow: auto;
    min-height: 500px;
    max-height: 500px;
}

#parameters .available-box {
}

#parameters md-list.parameter-list {
    padding: 0;
}

#parameters md-list.parameter-list md-input-container {
    margin: 18px 0 0 0;
}

#parameters .parameter-list .ng-hide {
    visibility: hidden;
    display: initial !important;
}

#parameters .md-list-item-text {
    padding-left: 10px;
}

#parameters .list-item {
    border-top: solid black 1px;
}

#parameters .outbound-parameters {
    margin-left: 15px;
    margin-right: 15px;
    position: relative;
}

#parameters .outbound-parameter-row {
    padding: 8px 0 8px 16px;
}

#parameters .parameter-name {
    font-weight: bold;
    text-transform: capitalize;
}

#parameters .no-parameters-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#parameters .selected-headers-row {
    padding: 8px;
}

#parameters .outbound-background-grey {
    background-color: #f0f1f2;
}

#parameters .selected-headers {
    font-size: 20px;
    font-weight: bold;
}

#parameters .outbound-parameters md-input-container {
    margin: 0;
    max-height: 30px;
}

#parameters .outbound-parameters .static-text {
    position: relative;
    top: 10px;
}

#parameters .outbound-parameters .hidden-box {
 background-color: #f0f1f2;
}

#parameters .outbound-parameters md-input-container {
    background-color: white;
}

#parameters .outbound-parameters md-input-container.md-input-has-value label, #parameters .outbound-parameters md-input-container.md-input-focused label {
    color: rgba(0,0,0,0.54) !important;
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.tools.eclipse.appengine.validation;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PositionalXmlScannerTest {

  @Test
  public void testParse() throws SAXException, IOException {
    byte[] bytes = "<root><child></child></root>".getBytes(StandardCharsets.UTF_8);
    Document document = PositionalXmlScanner.parse(bytes);

    NodeList rootNode = document.getElementsByTagName("root");
    assertEquals(1, rootNode.getLength());

    NodeList childNode = document.getElementsByTagName("child");
    assertEquals(1, childNode.getLength());
  }

  @Test
  public void testParse_emptyXml() throws SAXException, IOException {
    byte[] bytes = "".getBytes(StandardCharsets.UTF_8);
    Document document = PositionalXmlScanner.parse(bytes);
    assertNull(document);
  }

}


text:
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings, LambdaCase #-}

module Main where

import Brick
  ( Widget, App(..), AttrMap, BrickEvent(..), Next, EventM
  , (<=>), (<+>), txt, continue, halt, attrMap, on, fg
  , defaultMain, showFirstCursor, padBottom, Padding(Max,Pad)
  , padAll, padLeft
  )
import Brick.Widgets.BetterDialog (dialog)
import Brick.Widgets.Border (hBorder)
import Brick.Widgets.Edit.EmacsBindings
  ( Editor, renderEditor, handleEditorEvent, getEditContents, editContentsL
  , editorText
  )
import Brick.Widgets.List
  ( List, listMoveDown, listMoveUp, listMoveTo, listSelectedElement
  , listSelectedAttr, list
  )
import Brick.Widgets.List.Utils (listSimpleReplace)
import Graphics.Vty
  (Event(EvKey), Modifier(MCtrl,MMeta), Key(..), defAttr, black, white, green)

import Control.Exception (SomeException, try)
import Control.Monad (msum, when, void)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Except (runExceptT)
import Data.Functor.Identity (Identity(..), runIdentity)
import Data.Maybe (fromMaybe, fromJust)
import Data.Monoid ((<>), First(..), getFirst)
import qualified Data.Semigroup as Sem
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Text.Zipper (gotoEOL, textZipper)
import qualified Data.Vector as V
import qualified Hledger as HL
import qualified Hledger.Read.JournalReader as HL
import Lens.Micro ((&), (.~))
import qualified Options.Applicative as OA
import Options.Applicative
  ( ReadM, Parser, value, help, long, metavar, switch, helper, fullDesc, info
  , header, short, (<|>), eitherReader, execParser
  )
import System.Directory (getHomeDirectory)
import System.Environment (lookupEnv)
import System.Environment.XDG.BaseDir (getUserConfigFile)
import System.Exit (exitFailure, exitSuccess)
import System.IO (hPutStr, hPutStrLn, stderr)
import qualified Text.Megaparsec as P
import qualified Text.Megaparsec.Char as P

import Brick.Widgets.CommentDialog
import Brick.Widgets.HelpMessage
import Brick.Widgets.Border.Utils (borderLeft)
import ConfigParser hiding (parseConfigFile)
import DateParser
import Model
import View

import Data.Version (showVersion)
import qualified Paths_hledger_iadd as Paths

data AppState = AppState
  { asEditor :: Editor Name
  , asStep :: Step
  , asJournal :: HL.Journal
  , asContext :: List Name Text
  , asSuggestion :: Maybe Text
  , asMessage :: Text
  , asFilename :: FilePath
  , asDateFormat :: DateFormat
  , asMatchAlgo :: MatchAlgo
  , asDialog :: DialogShown
  , asInputHistory :: [Text]
  }

data Name = HelpName | ListName | EditorName | CommentName
  deriving (Ord, Show, Eq)

data CommentType = TransactionComment | CurrentComment

instance Show CommentType where
  show TransactionComment = "Transaction comment"
  show CurrentComment = "Comment"

data DialogShown = NoDialog
                 | HelpDialog (HelpWidget Name)
                 | QuitDialog
                 | AbortDialog
                 | CommentDialog CommentType (CommentWidget Name)

myHelpDialog :: DialogShown
myHelpDialog = HelpDialog (helpWidget HelpName bindings)

myCommentDialog :: CommentType -> Text -> DialogShown
myCommentDialog typ comment =
  CommentDialog typ (commentWidget CommentName (T.pack $ show typ) comment)

bindings :: KeyBindings
bindings = KeyBindings
  [ ("Denial",
     [ ("C-c, C-d", "Quit without saving the current transaction")
     , ("Esc", "Abort the current transaction or exit when at toplevel")
     ])
  , ("Anger",
     [ ("F1, Alt-?", "Show help screen")])
  , ("Bargaining",
     [ ("C-n", "Select the next context item")
       , ("C-p", "Select the previous context item")
       , ("Tab", "Insert currently selected answer into text area")
       , ("C-z", "Undo")
       , (";", "Edit comment for current prompt")
       , ("Alt-;", "Edit transaction comment")
       ])
  , ("Acceptance",
     [ ("Ret", "Accept the currently selected answer")
     , ("Alt-Ret", "Accept the current answer verbatim, ignoring selection")
     ])]

draw :: AppState -> [Widget Name]
draw as = case asDialog as of
  HelpDialog h -> [renderHelpWidget h, ui]
  QuitDialog -> [quitDialog, ui]
  AbortDialog -> [abortDialog, ui]
  CommentDialog _ c -> [renderCommentWidget c, ui]
  NoDialog -> [ui]

  where ui =  txt "New Transaction:"
          <=> padAll 1 (borderLeft $ padLeft (Pad 1) $ viewState (asStep as))
          <=> hBorder
          <=> (viewQuestion (asStep as)
               <+> viewSuggestion (asSuggestion as)
               <+> txt ": "
               <+> renderEditor True (asEditor as))
          <=> hBorder
          <=> expand (viewContext (asContext as))
          <=> hBorder
          <=> viewMessage (asMessage as)

        quitDialog = dialog "Quit" "Really quit without saving the current transaction? (Y/n)"
        abortDialog = dialog "Abort" "Really abort this transaction (Y/n)"

setComment :: CommentType -> Text -> Step -> Step
setComment TransactionComment = setTransactionComment
setComment CurrentComment     = setCurrentComment

-- TODO Refactor to remove code duplication in individual case statements
event :: AppState -> BrickEvent Name Event -> EventM Name (Next AppState)
event as (VtyEvent ev) = case asDialog as of
  HelpDialog helpDia -> case ev of
    EvKey key []
      | key `elem` [KChar 'q', KEsc] -> continue as { asDialog = NoDialog }
      | otherwise                    -> do
          helpDia' <- handleHelpEvent helpDia ev
          continue as { asDialog = HelpDialog helpDia' }
    _ -> continue as
  QuitDialog -> case ev of
    EvKey key []
      | key `elem` [KChar 'y', KEnter] -> halt as
      | otherwise -> continue as { asDialog = NoDialog }
    _ -> continue as
  AbortDialog -> case ev of
    EvKey key []
      | key `elem` [KChar 'y', KEnter] ->
        liftIO (reset as { asDialog = NoDialog }) >>= continue
      | otherwise -> continue as { asDialog = NoDialog }
    _ -> continue as
  CommentDialog typ dia -> handleCommentEvent ev dia >>= \case
    CommentContinue dia' ->
      continue as { asDialog = CommentDialog typ dia'
                  , asStep = setComment typ (commentDialogComment dia') (asStep as)
                  }
    CommentFinished comment ->
      continue as { asDialog = NoDialog
                  , asStep = setComment typ comment (asStep as)
                  }

  NoDialog -> case ev of
    EvKey (KChar 'c') [MCtrl] -> case asStep as of
      DateQuestion _ -> halt as
      _              -> continue as { asDialog = QuitDialog }
    EvKey (KChar 'd') [MCtrl] -> case asStep as of
      DateQuestion _ -> halt as
      _              -> continue as { asDialog = QuitDialog }
    EvKey (KChar 'n') [MCtrl] -> continue as { asContext = listMoveDown $ asContext as
                                             , asMessage = ""}
    EvKey KDown [] -> continue as { asContext = listMoveDown $ asContext as
                                  , asMessage = ""}
    EvKey (KChar 'p') [MCtrl] -> continue as { asContext = listMoveUp $ asContext as
                                             , asMessage = ""}
    EvKey KUp [] -> continue as { asContext = listMoveUp $ asContext as
                               , asMessage = ""}
    EvKey (KChar '\t') [] -> continue (insertSelected as)
    EvKey (KChar ';') [] ->
      continue as { asDialog = myCommentDialog CurrentComment (getCurrentComment (asStep as)) }
    EvKey (KChar ';') [MMeta] ->
      continue as { asDialog = myCommentDialog TransactionComment (getTransactionComment (asStep as)) }
    EvKey KEsc [] -> case asStep as of
      DateQuestion _
        | T.null (editText as) -> halt as
        | otherwise -> liftIO (reset as) >>= continue
      _ -> continue as { asDialog = AbortDialog }
    EvKey (KChar 'z') [MCtrl] -> liftIO (doUndo as) >>= continue
    EvKey KEnter [MMeta] -> liftIO (doNextStep False as) >>= continue
    EvKey KEnter [] -> liftIO (doNextStep True as) >>= continue
    EvKey (KFun 1) [] -> continue as { asDialog = myHelpDialog }
    EvKey (KChar '?') [MMeta] -> continue as { asDialog = myHelpDialog, asMessage = "Help" }
    _ -> (AppState <$> handleEditorEvent ev (asEditor as)
                   <*> return (asStep as)
                   <*> return (asJournal as)
                   <*> return (asContext as)
                   <*> return (asSuggestion as)
                   <*> return ""
                   <*> return (asFilename as))
                   <*> return (asDateFormat as)
                   <*> return (asMatchAlgo as)
                   <*> return NoDialog
                   <*> return (asInputHistory as)
         >>= liftIO . setContext >>= continue
event as _ = continue as

reset :: AppState -> IO AppState
reset as = do
  sugg <- suggest (asJournal as) (asDateFormat as) (DateQuestion "")
  return as
    { asStep = DateQuestion ""
    , asEditor = clearEdit (asEditor as)
    , asContext = ctxList V.empty
    , asSuggestion = sugg
    , asMessage = "Transaction aborted"
    }

setContext :: AppState -> IO AppState
setContext as = do
  ctx <- flip listSimpleReplace (asContext as) . V.fromList <$>
         context (asJournal as) (asMatchAlgo as) (asDateFormat as) (editText as) (asStep as)
  return as { asContext = ctx }

editText :: AppState -> Text
editText = T.concat . getEditContents . asEditor

-- | Add a tranaction at the end of a journal
--
-- Hledgers `HL.addTransaction` adds it to the beginning, but our suggestion
-- system expects newer transactions to be at the end.
addTransactionEnd :: HL.Transaction -> HL.Journal -> HL.Journal
addTransactionEnd t j = j { HL.jtxns = HL.jtxns j ++ [t] }

doNextStep :: Bool -> AppState -> IO AppState
doNextStep useSelected as = do
  let inputText = editText as
      name = fromMaybe (Left inputText) $
               msum [ Right <$> if useSelected then snd <$> listSelectedElement (asContext as) else Nothing
                    , Left <$> asMaybe (editText as)
                    , Left <$> asSuggestion as
                    ]
  s <- nextStep (asJournal as) (asDateFormat as) name (asStep as)
  case s of
    Left err -> return as { asMessage = err }
    Right (Finished trans) -> do
      liftIO $ addToJournal trans (asFilename as)
      sugg <- suggest (asJournal as) (asDateFormat as) (DateQuestion "")
      return AppState
        { asStep = DateQuestion ""
        , asJournal = addTransactionEnd trans (asJournal  as)
        , asEditor = clearEdit (asEditor as)
        , asContext = ctxList V.empty
        , asSuggestion = sugg
        , asMessage = "Transaction written to journal file"
        , asFilename = asFilename as
        , asDateFormat = asDateFormat as
        , asMatchAlgo = asMatchAlgo as
        , asDialog = NoDialog
        , asInputHistory = []
        }
    Right (Step s') -> do
      sugg <- suggest (asJournal as) (asDateFormat as) s'
      ctx' <- ctxList . V.fromList <$> context (asJournal as) (asMatchAlgo as) (asDateFormat as) "" s'
      return as { asStep = s'
                , asEditor = clearEdit (asEditor as)
                , asContext = ctx'
                , asSuggestion = sugg
                , asMessage = ""
                -- Adhere to the 'undo' behaviour: when in the final
                -- confirmation question, 'undo' jumps back to the last amount
                -- question instead of to the last account question. So do not
                -- save the last empty account answer which indicates the end
                -- of the transaction.
                -- Furthermore, don't save the input if the FinalQuestion is
                -- answered by 'n' (for no).
                , asInputHistory = case (asStep as,s') of
                    (FinalQuestion _ _, _) -> asInputHistory as
                    (_, FinalQuestion _ _) -> asInputHistory as
                    _                    -> inputText : asInputHistory as
                }

doUndo :: AppState -> IO AppState
doUndo as = case undo (asStep as) of
  Left msg -> return as { asMessage = "Undo failed: " <> msg }
  Right step -> do
    sugg <- suggest (asJournal as) (asDateFormat as) step
    setContext $ as { asStep = step
                    , asEditor = setEdit lastInput (asEditor as)
                    , asSuggestion = sugg
                    , asMessage = "Undo."
                    , asInputHistory = historyTail
                    }
    where (lastInput,historyTail) =
            case asInputHistory as of
              x:t -> (x,t)
              [] -> ("",[])

insertSelected :: AppState -> AppState
insertSelected as = case listSelectedElement (asContext as) of
  Nothing -> as
  Just (_, line) -> as { asEditor = setEdit line (asEditor as) }

asMaybe :: Text -> Maybe Text
asMaybe t
  | T.null t  = Nothing
  | otherwise = Just t

attrs :: AttrMap
attrs = attrMap defAttr
  [ (listSelectedAttr, black `on` white)
  , (helpAttr <> "title", fg green)
  ]

clearEdit :: Editor n -> Editor n
clearEdit = setEdit ""

setEdit :: Text -> Editor n -> Editor n
setEdit content edit = edit & editContentsL .~ zipper
  where zipper = gotoEOL (textZipper [content] (Just 1))

addToJournal :: HL.Transaction -> FilePath -> IO ()
addToJournal trans path = appendFile path (moveEmptyLine $ HL.showTransactionUnelided trans)
  where
    -- showTransactionUnelided adds an empty line to the end of the transaction. We want
    -- the empty line to be at the start instead, to allow it to be added to a
    -- journal that doesn't end with a newline.
    moveEmptyLine :: String -> String
    moveEmptyLine = unlines . ("":) . init . lines

--------------------------------------------------------------------------------
-- Command line and config parsing
--------------------------------------------------------------------------------

data CommonOptions f = CommonOptions
  { optLedgerFile :: f FilePath
  , optDateFormat :: f String
  , optMatchAlgo  :: f MatchAlgo
  }

instance Sem.Semigroup (CommonOptions Maybe) where
  (<>) opt1 opt2 =
    let opt1' = optNatTrans First opt1
        opt2' = optNatTrans First opt2
    in optNatTrans getFirst $ CommonOptions
       { optLedgerFile = optLedgerFile opt1' <> optLedgerFile opt2'
       , optDateFormat = optDateFormat opt1' <> optDateFormat opt2'
       , optMatchAlgo = optMatchAlgo opt1' <> optMatchAlgo opt2'
       }

instance Monoid (CommonOptions Maybe) where
  mappend = (Sem.<>)
  mempty = CommonOptions Nothing Nothing Nothing

optNatTrans :: (forall a. f a -> g a) -> CommonOptions f -> CommonOptions g
optNatTrans nat opts = CommonOptions
  { optLedgerFile = nat $ optLedgerFile opts
  , optDateFormat = nat $ optDateFormat opts
  , optMatchAlgo = nat $ optMatchAlgo opts
  }

optFromJust :: CommonOptions Identity -> CommonOptions Maybe -> CommonOptions Identity
optFromJust def opts =
  optNatTrans (Identity . fromJust) ( opts <> optNatTrans (Just . runIdentity) def)

data CmdLineOptions = CmdLineOptions
  { cmdCommon :: CommonOptions Maybe
  , cmdDumpConfig :: Bool
  , cmdVersion :: Bool
  }

data ConfOptions = ConfOptions { confCommon :: CommonOptions Maybe }

defaultOptions :: FilePath -> CommonOptions Identity
defaultOptions home = CommonOptions
  { optLedgerFile = Identity (ledgerPath home)
  , optDateFormat = Identity "[[%y/]%m/]%d"
  , optMatchAlgo = Identity Substrings
  }

ledgerPath :: FilePath -> FilePath
ledgerPath home = home <> "/.hledger.journal"

configPath :: IO FilePath
configPath = getUserConfigFile "hledger-iadd" "config.conf"

-- | Megaparsec parser for MatchAlgo, used for config file parsing
parseMatchAlgo :: OParser MatchAlgo
parseMatchAlgo =  (P.string "fuzzy" *> pure Fuzzy)
              <|> (P.string "substrings" *> pure Substrings)

-- | ReadM parser for MatchAlgo, used for command line option parsing
readMatchAlgo :: ReadM MatchAlgo
readMatchAlgo = eitherReader reader
  where
    reader str
      | str == "fuzzy" = return Fuzzy
      | str == "substrings" = return Substrings
      | otherwise = Left "Expected \"fuzzy\" or \"substrings\""

-- | Parser for our config file
confParser :: CommonOptions Identity -> OptParser ConfOptions
confParser def = fmap ConfOptions $ CommonOptions
  -- TODO Convert leading tilde to home
  <$> (Just <$> option "file" (runIdentity $ optLedgerFile def) "Path to the journal file")
  <*> (Just <$> option "date-format" (runIdentity $ optDateFormat def) "Format used to parse dates")
  <*> (Just <$> customOption "completion-engine" matchAlgo (T.toLower $ T.pack $ show matchAlgo)
      ( "Algorithm used to find completions for account names. Possible values are:\n"
      <> "  - substrings: Every word in the search string has to occur somewhere in the account name\n"
      <> "  - fuzzy: All letters from the search string have to appear in the name in the same order"
      )
      "string"
      parseMatchAlgo
      )

  where matchAlgo = runIdentity (optMatchAlgo def)

-- | IO Action to read and parse config file
parseConfigFile :: IO ConfOptions
parseConfigFile = do
  path <- configPath
  home <- getHomeDirectory
  let def = defaultOptions home

  try (T.readFile path) >>= \case
    Left (_ :: SomeException) -> return (parserDefault $ confParser def)
    Right res -> case parseConfig path res (confParser def) of
      Left err -> do
        putStr (P.errorBundlePretty err)
        exitFailure
      Right res' -> return res'

-- | command line option parser
cmdOptionParser :: Parser CmdLineOptions
cmdOptionParser = CmdLineOptions
  <$> (CommonOptions
       <$> OA.option (Just <$> OA.str)
           (  long "file"
           <> short 'f'
           <> metavar "FILE"
           <> value Nothing
           <> help "Path to the journal file"
           )
       <*> OA.option (Just <$> OA.str)
             (  long "date-format"
             <> metavar "FORMAT"
             <> value Nothing
             <> help "Format used to parse dates"
             )
      <*> OA.option (Just <$> readMatchAlgo)
            (  long "completion-engine"
            <> metavar "ENGINE"
            <> value Nothing
            <> help "Algorithm for account name completion. Possible values: \"fuzzy\", \"substrings\"")
      )
  <*> switch
        ( long "dump-default-config"
       <> help "Print an example configuration file to stdout and exit"
        )
  <*> switch
        ( long "version"
       <> help "Print version number and exit"
        )

parseEnvVariables :: IO (CommonOptions Maybe)
parseEnvVariables = do
  maybeFilePath <- lookupEnv "LEDGER_FILE"
  return mempty
    { optLedgerFile = maybeFilePath }

main :: IO ()
main = do
  home <- getHomeDirectory
  path <- configPath
  let defOpts = defaultOptions home

  cmdOpts <- execParser $ info (helper <*> cmdOptionParser) $
               fullDesc <> header "A terminal UI as drop-in replacement for hledger add."

  when (cmdVersion cmdOpts) $ do
    putStrLn $ "This is hledger-iadd version " <> showVersion Paths.version
    exitSuccess

  when (cmdDumpConfig cmdOpts) $ do
    T.putStrLn $ "# Write this to " <> T.pack path <> "\n"
    T.putStrLn (parserExample $ confParser defOpts)
    exitSuccess

  confOpts <- parseConfigFile

  envOpts <- parseEnvVariables

  -- The order of precedence here is:
  -- arguments > environment > config file
  let opts = optFromJust defOpts $ cmdCommon cmdOpts <> envOpts <> confCommon confOpts

  date <- case parseDateFormat (T.pack $ runIdentity $ optDateFormat opts) of
    Left err -> do
      hPutStr stderr "Could not parse date format: "
      T.hPutStr stderr err
      exitFailure
    Right res -> return res

  let path = runIdentity $ optLedgerFile opts
  journalContents <- T.readFile path

  runExceptT (HL.parseAndFinaliseJournal HL.journalp HL.definputopts path journalContents) >>= \case
    Left err -> hPutStrLn stderr err >> exitFailure
    Right journal -> do
      let edit = editorText EditorName (txt . T.concat) (Just 1) ""

      sugg <- suggest journal date (DateQuestion "")

      let welcome = "Welcome! Press F1 (or Alt-?) for help. Exit with Ctrl-d."
          matchAlgo = runIdentity $ optMatchAlgo opts
          as = AppState edit (DateQuestion "") journal (ctxList V.empty) sugg welcome path date matchAlgo NoDialog []

      void $ defaultMain app as

    where app = App { appDraw = draw
                    , appChooseCursor = showFirstCursor
                    , appHandleEvent = event
                    , appAttrMap = const attrs
                    , appStartEvent = return
                    } :: App AppState Event Name

expand :: Widget n -> Widget n
expand = padBottom Max

ctxList :: V.Vector e -> List Name e
ctxList v = (if V.null v then id else listMoveTo 0) $ list ListName v 1


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Event'
        db.create_table('multilingual_events_event', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('start_date', self.gf('django.db.models.fields.DateTimeField')()),
            ('is_published', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('creation_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)),
        ))
        db.send_create_signal('multilingual_events', ['Event'])

        # Adding model 'EventTitle'
        db.create_table('multilingual_events_eventtitle', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('title', self.gf('django.db.models.fields.CharField')(max_length=512)),
            ('description', self.gf('django.db.models.fields.TextField')(blank=True)),
            ('event', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['multilingual_events.Event'])),
            ('language', self.gf('django.db.models.fields.CharField')(max_length=5)),
        ))
        db.send_create_signal('multilingual_events', ['EventTitle'])

    def backwards(self, orm):
        # Deleting model 'Event'
        db.delete_table('multilingual_events_event')

        # Deleting model 'EventTitle'
        db.delete_table('multilingual_events_eventtitle')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'multilingual_events.event': {
            'Meta': {'ordering': "['-start_date']", 'object_name': 'Event'},
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'start_date': ('django.db.models.fields.DateTimeField', [], {}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
        },
        'multilingual_events.eventtitle': {
            'Meta': {'object_name': 'EventTitle'},
            'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'event': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['multilingual_events.Event']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '5'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '512'})
        }
    }

    complete_apps = ['multilingual_events']


text:
<TITLE>Review for Flawless (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Flawless (1999)

reviewed by
"Average Joe" Barlow

FLAWLESS
A movie review by Joe Barlow
(c) Copyright 1999

STARRING: Robert De Niro, Philip Seymour Hoffman
DIRECTOR: Joel Schumacher
WRITER: Joel Schumacher
RATED: R
RELEASED: 1999

You have to pity poor Joel Schumacher. Not only is he accused of
single-handedly destroying the Batman franchise, but his last film,
the bleak 8mm, was ridiculed by the majority of critics in America. I
can visualize Schumacher's conversation with himself: "Hmm... I've
just made several critical duds in a row. What am I doing wrong? Let's
see. The Batman films and 8mm all share dark, creepy atmospheres, and
that genre's obviously not working for me. Let's go the opposite route
on the follow-up."

It's almost cute the way Schumacher rolls with the punches, and it's
no surprise that in Flawless, a title that almost dares critics not to
like the movie, the writer/director tries to play it safe... or at
least as safe as any film which centers around a flamboyant
transvestite can be considered to be. Everything here seems
specifically constructed to avoid offensiveness or friction, and it's
the movie's single biggest problem: everything has been so homogenized
that what could have been a fascinating film comes out as a cinematic
vanilla pudding, lacking any sort of flavor whatsoever.

Walter Koonz (Robert De Niro) is a cranky ex-cop and raging homophobe
who finds himself partially paralyzed and unable to speak properly
after suffering a stroke. Embarrassed by his condition, Koonz begins
taking voice lessons from Rusty Zimmerman (Philip Seymour Hoffman), a
local transvestite who adheres to every gay stereotype and cliche'
imaginable. You'll no doubt be shocked to learn that as they grow
closer, they form a deep bond. Just consider this the low-calorie
version of As Good as it Gets.

Flawless desperately wants to be The Odd Couple, and there are moments
in which it comes close, drawing us into the lives of the characters
as they come to terms with each other and their differences. Both De
Niro and Hoffman are engaging actors, with Hoffman's bubbling screen
persona serving as a brilliant counterpoint to Hoffman's gruff
demeanor. They each have a firm handle on two very challenging
characters (De Niro actually wore weights in his clothes to help him
prepare for his role as a stroke victim), and they work well together.

But sadly, the performances are all Flawless has going for it. The few
sparks of fire De Niro and Hoffman are able to inject into the story
are quickly extinguished by Schumacher's adherence to the lowest
common denominator, such as the laughable finale, which is so deeply
mired in cliches that it's hard to resist the temptation to hurl
popcorn at the screen. Nor is the drama helped by the unimaginative
shooting methods employed by Schumacher. We may as well be watching a
TV sitcom--or a play.

I'll give Schumacher an 'A' for effort: with Flawless he's
demonstrated a willingness to deviate from his previous work, and he's
created a film with the potential for power and drama. Unfortunately,
the director does not yet appear to have either the confidence or
ability to helm a project which requires such depth; hence, we're
treated to countless gay stereotypes and unimaginative plot twists
(Stolen drug money? Yawn). Oh well. It was a nice try, Joel, and I
mean that. Maybe next time.

     RATING: ** out of a possible ****

Copyright (c)1999 by Joe Barlow. This review may not be reproduced
without the written consent of the author.

E-Mail: jbarlow@earthling.net
Joe Barlow on Film: http://www.ipass.net/~jbarlow/film.htm

If you'd like to receive new film reviews by e-mail, please write to:
joefilm-subscribe@listbot.com.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
Markdown for GUS (Salesforce ticketing system)

This is a **Chrome Extension** and/or **TamperMonkey userscript**. It works on Classic and Lightning interfaces.

This extension will take common ways of conveying meaning in your text and apply formatting to them. It supports all common markdown formatting and will also look for other common ways of conveying formatting and convert it to markdown then HTML.

* * *

## Install Instructions

**In Chrome:**

Download/install this extension. Click on the extension to enable/disable it on the current page.

* https://chrome.google.com/webstore/search/gus%20markdown

**In other browsers:**

Download TamperMonkey or a similar extension

* http://tampermonkey.net

Then use use the `rolledAnyBrowser.js` script:

* https://raw.githubusercontent.com/jwilcurt-salesforce-com/gus-markdown/master/dist/rolledAnyBrowserScript.js

Copy/paste that script into your TamperMonkey instance.

* * *

## Why Markdown in Gus?

Markdown is used on websites that cater to programmers:

* GitHub
* GitLab
* BitBucket
* StackOverflow
* HackerNews
* CodePen
* Medium
* Reddit
* Gitter
* Discord
* Slack
* etc.

GUS markets itself as a tool for programmers, however without markdown support, it is hard to take it serious. It's become an expectation that tools for developers should support markdown natively. Until that time, this extension/script fills in the gap.

* * *

# Markdown examples:

* * *

```
* Example
* of
  * a
    * bulleted
* list
```

* Example
* of
  * a
    * bulleted
* list

* * *

```
1. Example
   1. of a
      1. ordered
1. list
```

1. Example
   1. of a
      1. ordered
1. list

* * *

```
If you surround text with one asterisk it will *become italic*.
```
If you surround text with one asterisk it will *become italic*.

* * *

```
If you surround text with two asterisks it will **become bold**.
```
If you surround text with two asterisks it will **become bold**.

* * *

```
If you surround text with three asterisks it will ***become bold italic***.
```
If you surround text with three asterisks it will ***become bold italic***.

* * *

```
If you surround text with one grave it will `become inline code`.
```

If you surround text with one grave it will `become inline code`.

* * *

To create multiline codeblocks use 3 graves, a file extension (optional), a return, your code, a return, and 3 graves.

    ```js
    if (usingMultilineCodeBlock) {
        var explaination = 'Multiline codeblocks use ' +
            '3 graves, ' +
            'a file extension (optional), ' +
            'a return, ' +
            'your code, ' +
            'a return, ' +
            'and 3 graves.';
        console.log(explanation);
    }
    ```

```js
if (usingMultilineCodeBlock) {
    var explaination = 'Multiline codeblocks use ' +
        '3 graves, ' +
        'a file extension (optional), ' +
        'a return, ' +
        'your code, ' +
        'a return, ' +
        'and 3 graves.';
    console.log(explanation);
}
```

* * *

Horrizontal rules can be created with asterisks or hyphens:

```
* * *
---
```

* * *
---

You can also add a link in your text, like so:

```
To learn more about Markdown syntax, [click here](https://daringfireball.net/projects/markdown/syntax).
```

To learn more about Markdown syntax, [click here](https://daringfireball.net/projects/markdown/syntax).

Until markdown is officially supported by GUS, it is probably better to structure your links like this however, so that it will still look nice for those who do not have the gus-markdown extension:

```
To learn more about Markdown syntax:

* https://daringfireball.net/projects/markdown/syntax
```

To learn more about Markdown syntax:

* https://daringfireball.net/projects/markdown/syntax


text:
require_relative 'converter'
require_relative 'wrapper'
require_relative 'viewer'
require_relative 'watcher'

module GHPreview
  class Previewer

    def initialize(md_filepath, options = {})
      Wrapper.generate_template_with_fingerprinted_stylesheet_links

      @md_filepath = md_filepath
      @application = options[:application]

      options[:watch] ? listen : open
    end

    def listen
      puts "Previewing #{@md_filepath}. CTRL-C to stop."
      Watcher.watch @md_filepath do
        open
      end
    end

    def open
      html = Converter.to_html(File.read(@md_filepath))
      html = Wrapper.wrap_html(html)
      Viewer.view_html html, @application
    end

  end
end


text:
<?php

namespace SilverStripe\AssetAdmin\Tests\Forms;

use SilverStripe\AssetAdmin\Controller\AssetAdmin;
use SilverStripe\AssetAdmin\Extensions\CampaignAdminExtension;
use SilverStripe\AssetAdmin\Forms\FileFormFactory;
use SilverStripe\AssetAdmin\Forms\FolderFormFactory;
use SilverStripe\AssetAdmin\Forms\ImageFormFactory;
use SilverStripe\AssetAdmin\Tests\Forms\FileFormBuilderTest\FileExtension;
use Silverstripe\Assets\Dev\TestAssetStore;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Folder;
use SilverStripe\Assets\Image;
use SilverStripe\Core\Config\Config;
use SilverStripe\Dev\SapphireTest;
use SilverStripe\Forms\LiteralField;

class FileFormBuilderTest extends SapphireTest
{
    protected static $fixture_file = 'FileFormBuilderTest.yml';

    protected static $extra_dataobjects = [
        FileFormBuilderTest\FileOwner::class,
    ];

    protected function setUp(): void
    {
        parent::setUp();

        // Dynamically assign fileowner as owner (otherwise it pollutes other tests)
        FileFormBuilderTest\FileOwner::config()->set('owns', ['OwnedFile']);

        // Set backend and base url
        TestAssetStore::activate('FileFormBuilderTest');

        /** @var File $testfile */
        $testfile = $this->objFromFixture(File::class, 'file1');
        $testfile->setFromLocalFile(__DIR__ . '/fixtures/testfile.txt', 'files/testfile.txt');
        $testfile->write();

        /** @var Image $testimage */
        $testimage = $this->objFromFixture(Image::class, 'image1');
        $testimage->setFromLocalFile(__DIR__ . '/fixtures/testimage.png', 'files/testimage.png');
    }

    protected function tearDown(): void
    {
        TestAssetStore::reset();
        parent::tearDown();
    }

    public function testEditFileForm()
    {
        // Ensure campaign-admin extension is not applied!
        Config::modify()->remove(FileFormFactory::class, 'extensions');

        $this->logInWithPermission('ADMIN');

        $file = $this->objFromFixture(File::class, 'file1');
        $controller = new AssetAdmin();
        $builder = new FileFormFactory();
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file, 'RequireLinkText' => false]);

        // Verify file form is scaffolded correctly
        $this->assertEquals('EditForm', $form->getName());

        // Test fields exist
        /** @var LiteralField $fileSpecsField */
        $fileSpecsField = $form->Fields()->fieldByName('AssetEditorHeaderFieldGroup.FileSpecs');
        $fileSpecs = $fileSpecsField->getContent();
        $this->assertEquals(
            '
11 bytes Draft
',
            $fileSpecs
        );

        /** @var LiteralField $iconFullField */
        $iconFullField = $form->Fields()->fieldByName('PreviewImage');
        $state = $iconFullField->getSchemaStateDefaults();
        $this->assertEquals($file->Parent()->ID, $state['data']['parentid']);
        $this->assertStringContainsString('testfile.txt', $state['data']['url']);
        $this->assertTrue($state['data']['exists']);
        $this->assertStringContainsString('document_92.png', $state['data']['preview']);
        $this->assertEquals('document', $state['data']['category']);

        $uploaded = $form->Fields()->fieldByName('Editor.Details.Created');
        $this->assertEquals(
            $file->Created,
            $uploaded->dataValue()
        );

        // Test actions exist
        $this->assertNotNull($form->Actions()->fieldByName('Actions.action_save'));
        $this->assertNotNull($form->Actions()->fieldByName('Actions.action_publish'));
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_replacefile'));
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_delete'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_unpublish'));

        // Add to campaign should not be there by default
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_addtocampaign'));

        // Add extension for campaign-admin
        Config::modify()->merge(
            FileFormFactory::class,
            'extensions',
            [CampaignAdminExtension::class]
        );

        $builder = new FileFormFactory();
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file, 'RequireLinkText' => false]);

        // Add to campaign should now be available
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_addtocampaign'));
    }

    public function testEditFileFormWithPermissions()
    {
        // Add extension for campaign-admin
        FileFormFactory::add_extension(CampaignAdminExtension::class);
        // Add extension to simulate different permissions
        File::add_extension(FileExtension::class);

        $this->logInWithPermission('ADMIN');

        /** @var File $file */
        $file = $this->objFromFixture(File::class, 'file1');
        $controller = new AssetAdmin();
        $builder = new FileFormFactory();

        FileExtension::$canDelete = false;
        FileExtension::$canPublish = false;
        FileExtension::$canEdit = false;
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file, 'RequireLinkText' => false]);
        $this->assertNull($form->Actions()->fieldByName('PopoverActions'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_delete'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_replacefile'));

        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_addtocampaign'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_unpublish'));

        FileExtension::$canDelete = false;
        FileExtension::$canPublish = true;
        FileExtension::$canEdit = false;
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file, 'RequireLinkText' => false]);
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_delete'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_replacefile'));
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_addtocampaign'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_unpublish'));

        FileExtension::$canDelete = true;
        FileExtension::$canPublish = false;
        FileExtension::$canEdit = false;
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file]);
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_delete'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_replacefile'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_addtocampaign'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_unpublish'));

        FileExtension::$canDelete = false;
        FileExtension::$canPublish = false;
        FileExtension::$canEdit = true;
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file]);
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_delete'));
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_replacefile'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_addtocampaign'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_unpublish'));

        FileExtension::$canDelete = true;
        FileExtension::$canPublish = true;
        FileExtension::$canUnpublish = true;
        FileExtension::$canEdit = true;
        $file->publishSingle();
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file, 'RequireLinkText' => false]);
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_delete'));
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_replacefile'));
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_addtocampaign'));
        $this->assertNotNull($form->Actions()->fieldByName('PopoverActions.action_unpublish'));

        FileFormFactory::remove_extension(CampaignAdminExtension::class);
        File::remove_extension(FileExtension::class);
    }

    /**
     * Ensure unpublish has owner count
     */
    public function testUnpublishOwners()
    {
        $this->logInWithPermission('ADMIN');

        // Publish one of the owners
        /** @var FileFormBuilderTest\FileOwner $owner1 */
        $owner1 = $this->objFromFixture(FileFormBuilderTest\FileOwner::class, 'owner1');
        $owner1->publishSingle();

        /** @var File $file */
        $file = $this->objFromFixture(File::class, 'file1');
        $file->publishSingle();

        // Build new form
        $controller = new AssetAdmin();
        $builder = new FileFormFactory();

        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file, 'RequireLinkText' => false]);
        $unpublishAction = $form->Actions()->fieldByName('PopoverActions.action_unpublish');
        $this->assertNotNull($unpublishAction);
        $this->assertEquals(1, $unpublishAction->getSchemaData()['data']['owners']);
    }

    public function testCreateFileForm()
    {
        $this->logInWithPermission('ADMIN');

        $file = $this->objFromFixture(File::class, 'file1');
        $controller = new AssetAdmin();
        $builder = new FileFormFactory();
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $file, 'RequireLinkText' => false]);

        // Test fields
        /** @var LiteralField $fileSpecsField */
        $fileSpecsField = $form->Fields()->fieldByName('AssetEditorHeaderFieldGroup.FileSpecs');
        $this->assertEquals(
            '
11 bytes Draft
',
            $fileSpecsField->getContent()
        );

        // Test actions
        $this->assertNotNull($form->Actions()->fieldByName('Actions.action_save'));
    }

    public function testEditImageForm()
    {
        $this->logInWithPermission('ADMIN');

        $image = $this->objFromFixture(Image::class, 'image1');
        // write so that PreviewImageField could load this later on
        $image->write();
        $controller = new AssetAdmin();
        $builder = new ImageFormFactory();
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $image]);

        // Check thumbnail
        // Note: force_resample is turned off for testing
        /** @var LiteralField $iconFullField */
        $iconFullField = $form->Fields()->fieldByName('PreviewImage');
        $state = $iconFullField->getSchemaStateDefaults();
        $this->assertEquals($image->Parent()->ID, $state['data']['parentid']);
        $this->assertStringContainsString('testimage.png', $state['data']['url']);
        $this->assertTrue($state['data']['exists']);
        $this->assertMatchesRegularExpression('#testimage__.*\.png$#', $state['data']['preview']);
        $this->assertEquals('image', $state['data']['category']);
    }

    public function testInsertImageForm()
    {
        $this->logInWithPermission('CMS_ACCESS');

        $image = $this->objFromFixture(Image::class, 'image1');
        $controller = new AssetAdmin();
        $builder = new ImageFormFactory();
        $form = $builder->getForm(
            $controller,
            'EditForm',
            ['Record' => $image, 'Type' => FileFormFactory::TYPE_INSERT_MEDIA]
        );

        // Check thumbnail
        // Note: force_resample is turned off for testing
        $altTextField = $form->Fields()->dataFieldByName('AltText');
        $this->assertNotNull($altTextField);

        // Ensure "insert" button exists
        $this->assertTrue($image->canView());
        $this->assertNotNull($form->Actions()->fieldByName('action_insert'));
    }

    public function testInsertImageFormDenied()
    {
        $this->logInWithPermission('SOME_PERMISSION');

        $image = $this->objFromFixture(Image::class, 'image1');
        $controller = new AssetAdmin();
        $builder = new ImageFormFactory();
        $form = $builder->getForm(
            $controller,
            'EditForm',
            ['Record' => $image, 'Type' => FileFormFactory::TYPE_INSERT_MEDIA]
        );

        // Ensure "insert" button does not exist
        $this->assertFalse($image->canView());
        $this->assertNull($form->Actions()->fieldByName('action_insert'));
    }

    public function testInsertFileForm()
    {
        $this->logInWithPermission('CMS_ACCESS');

        $image = $this->objFromFixture(Image::class, 'image1');
        $controller = new AssetAdmin();
        $builder = new ImageFormFactory();
        $form = $builder->getForm(
            $controller,
            'EditForm',
            ['Record' => $image, 'Type' => FileFormFactory::TYPE_INSERT_LINK, 'RequireLinkText' => false]
        );

        // Ensure form contains correct fields
        $this->assertNotNull($form->Fields()->dataFieldByName('Description'));
        $this->assertNotNull($form->Fields()->dataFieldByName('TargetBlank'));

        // Don't show dimension tags
        $this->assertNull($form->Fields()->dataFieldByName('InsertWidth'));
    }

    public function testFolderForm()
    {
        $this->logInWithPermission('ADMIN');

        $folder = $this->objFromFixture(Folder::class, 'parent');
        $controller = new AssetAdmin();
        $builder = new FolderFormFactory();
        $form = $builder->getForm($controller, 'EditForm', ['Record' => $folder]);

        // Check fields
        $this->assertNull($form->Fields()->fieldByName('FileSpecs'));
        $this->assertNull($form->Fields()->fieldByName('Editor.Details.ClickableURL'));
        $this->assertNull($form->Fields()->fieldByName('Editor.Usage'));

        /** @var LiteralField $iconFullField */
        $iconFullField = $form->Fields()->fieldByName('PreviewImage');
        $state = $iconFullField->getSchemaStateDefaults();
        $this->assertEquals($folder->Parent()->ID, $state['data']['parentid']);
        $this->assertTrue($state['data']['exists']);
        $this->assertStringContainsString('folder_icon_large.png', $state['data']['preview']);
        $this->assertEquals('folder', $state['data']['category']);

        // Check actions
        $this->assertNotNull($form->Actions()->fieldByName('action_save'));
        $this->assertNotNull($form->Actions()->dataFieldByName('action_delete'));
        $this->assertNull($form->Actions()->fieldByName('action_publish'));
        $this->assertNull($form->Actions()->dataFieldByName('action_publish'));
        $this->assertNull($form->Actions()->dataFieldByName('action_unpublish'));
        $this->assertNull($form->Actions()->fieldByName('PopoverActions.action_replacefile'));
    }

    public function testScaffolderFactory()
    {
        $controller = new AssetAdmin();
        $this->assertInstanceOf(FileFormFactory::class, $controller->getFormFactory(File::singleton()));
        $this->assertInstanceOf(ImageFormFactory::class, $controller->getFormFactory(Image::singleton()));
        $this->assertInstanceOf(FolderFormFactory::class, $controller->getFormFactory(Folder::singleton()));
    }
}


text:
package ch.epfl.bbp.uima.topicmodels.inferencer
import ch.epfl.bbp.uima.topicmodels.dca.DCAFiles

/**
 * Provides topic inference for DCA models.
 * Based on Mallet topic inferencer.
 */
class DCAInference(dcaDirectoryPath: String, dcaStem: String, averaged: Boolean = true, trainingCorpusSize: Int = 0) extends DocumentInference {
  private val corpusSize = if (trainingCorpusSize <= 0) DCAFiles.estimateTrainingCorpusSize(dcaDirectoryPath, dcaStem)
  else trainingCorpusSize

  private val wordProbs:Array[Array[Double]] = null // FIXMEren DCAFiles.getTermTopicProbabilityMatrix(dcaDirectoryPath, dcaStem, averaged)
  private val alpha = DCAFiles.getAlpha(dcaDirectoryPath, dcaStem)
  private val beta = DCAFiles.getThetaPrior(dcaDirectoryPath, dcaStem)
  private val dict = DCAFiles.getTokenDict(dcaDirectoryPath, dcaStem)

  private val minferencer = new MalletBasedInferencer(DCAFiles.getTermTopicCountsMatrix(dcaDirectoryPath, dcaStem, corpusSize, averaged, dict.size), alpha, beta: Double, dict)

  /**
   * Estimates the topic probability distribution for a document.
   */
  override def getTopicDistribution(doc: List[String], totalCycles: Int, burnin: Int): Array[Double] = {
    minferencer.inference(doc, totalCycles, burnin)
  }

  override def getTopicsDistributionForWord(w: String, topicDist: Array[Double]): Array[Double] = {
    try { // FIXME Caused by: java.lang.ArrayIndexOutOfBoundsException: 89099
      dict.get(w) match {
        case Some(id) =>
          (wordProbs(id) zip topicDist)
            .map(x => x._1 * x._2)
        case None => Array.fill(topicDist.size)(0.0)
      }
    } catch {
      case _ => Array.fill(topicDist.size)(0.0)
    }
  }
}


text:
import veMerc from "./veMerc.json";
import veMill from "./veMill.json";

export { veMerc, veMill };


text:
'use strict';

var assert = require('assert');
var fs     = require('fs');
var path   = require('path');
var yaml   = require('../../lib/js-yaml');

var badThings = [];

global.makeBadThing = function (thing) {
  badThings.push(thing);
};

test('Function constructor must not allow to execute any code while parsing.', function () {
  var filename = path.join(__dirname, 'parse-function-security.yml'),
      contents = fs.readFileSync(filename, 'utf8');

  assert.throws(function () { yaml.load(contents); }, yaml.YAMLException);
  assert.deepEqual(badThings, []);
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2011 The Android Open Source Project

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

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

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

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/basic"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

    <LinearLayout android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">

        <LinearLayout android:orientation="vertical"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content">

            <TextView android:id="@+id/textview_password_default"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:textSize="32dip"
                    android:text="@string/textview_password_default_text"
            />

            <EditText android:id="@+id/edittext_password_default"
                      android:layout_height="wrap_content"
                      android:layout_width="match_parent"
                      android:textSize="32dip"
                      android:password="true"
                    />

            <TextView android:id="@+id/textview_default"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:textSize="32dip"
                    android:text="@string/textview_default_text"
            />

            <EditText android:id="@+id/edittext_default"
                      android:layout_height="wrap_content"
                      android:layout_width="match_parent"
                      android:textSize="32dip"
                    />

            <TextView android:id="@+id/textview_ltr"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:textSize="32dip"
                      android:text="@string/textview_ltr_text"
                    />

            <EditText android:id="@+id/edittext_ltr"
                      android:layout_height="wrap_content"
                      android:layout_width="match_parent"
                      android:textSize="32dip"
                      android:textDirection="ltr"
                    />

            <TextView android:id="@+id/textview_rtl"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:textSize="32dip"
                      android:text="@string/textview_rtl_text"
                    />

            <EditText android:id="@+id/edittext_rtl"
                      android:layout_height="wrap_content"
                      android:layout_width="match_parent"
                      android:textSize="32dip"
                      android:textDirection="rtl"
                    />

        </LinearLayout>

        <Button android:id="@+id/button_alert_dialog"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="@string/button_alert_dialog_text"
                android:textSize="32dip"
                />

        <EditText xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/edittext_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:textSize="32dip"
            android:scrollHorizontally="true"
            android:ellipsize="end"
            android:text="@string/url"
            />

        <LinearLayout
            android:layout_width="600dip"
            android:layout_height="128dip"
            android:layout_gravity="center_vertical"
            android:orientation="horizontal"
            style="@android:style/Widget.Holo.Spinner"
            >
            <LinearLayout
                android:layout_width="0dip"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:orientation="vertical"
                >
                <TextView
                    android:id="@+id/spinner_line_1"
                    android:layout_width="match_parent"
                    android:layout_height="0dip"
                    android:layout_weight="1"
                    android:textSize="16dip"
                    android:singleLine="true"
                    android:ellipsize="end"
                    android:gravity="left|center_vertical"
                    android:text="@string/button_text"
                    />
            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

    </ScrollView>

</FrameLayout>


text:
package com.exemple.ecommerce.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Bean Product
 * @author L4ngu0r
 */
@Entity
@Table(name = "products")
public class Product {

	@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String nom;
	private String description;
	private float price;

	public Product(){

	}

	public Product(String nom, String description, float price) {
		this.nom = nom;
		this.description = description;
		this.price = price;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getNom() {
		return nom;
	}
	public void setNom(String nom) {
		this.nom = nom;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
}


text:
Positioning Objects on a new xCode Game
=

It makes absolutely no sense but for whatever reason, if you create a new game within xCode 7.0, you have to configure a few things to make sprites appear properly on the page. Here are the key things you'll need to "fix".

### Edit the GameViewController
You need to replace ```viewDidLoad()``` with ```viewWillLayoutSubviews()```.  For peace of mind, simply remove viewDidLoad completely.

Your code will look like this:
<pre>
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        if let scene = GameScene(fileNamed:"GameScene") {
            // Configure the view.
            let skView = self.view as! SKView
            skView.showsFPS = true
            skView.showsNodeCount = true

            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true

            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = .AspectFill

            scene.size = skView.bounds.size

            skView.presentScene(scene)
        }

    }
</pre>

Resources
-
- [Best explanation of the problem](http://www.ymc.ch/en/ios-7-sprite-kit-setting-up-correct-scene-dimensions)
- [Understanding SKSceneScaleMode](http://blog.infinitecortex.com/2014/01/spritekit-understanding-skscene-scalemode/): This will explain the different types of scale modes and how they can affect your game. This will clearly explain why it would be very challenging to build a game that worked in both portrait and landscape


text:
set -ux

echo factaplus > perfMethods.txt
echo bitola >> perfMethods.txt
echo arrowsmith >> perfMethods.txt
echo jaccard >> perfMethods.txt
echo preferentialattachment >> perfMethods.txt
echo amw >> perfMethods.txt
echo ltc-amw >> perfMethods.txt

python=~/miniconda_install/myproject/bin/python

# Get the full number of terms in the wordlist
allTermsCount=`cat umlsWordlist.Final.txt | wc -l`

#/usr/bin/time -v bash ../analysis/runSVD.sh --dimension $allTermsCount --svNum 500 --matrix finalDataset/training.cooccurrences --outU perf.svd.training.U --outV perf.svd.training.V --outSV perf.svd.training.SV --mirror --binarize &> perf.log.svdTraining

#exit 0

/usr/bin/time -v ../anniVectors/generateAnniVectors --cooccurrenceData finalDataset/trainingAndValidation.cooccurrences --occurrenceData finalDataset/trainingAndValidation.occurrences --sentenceCount `cat finalDataset/trainingAndValidation.sentenceCounts` --vectorsToCalculate finalDataset/trainingAndValidation.ids --outIndexFile perf.anni.trainingAndValidation.index --outVectorFile perf.anni.trainingAndValidation.vectors &> perf.log.anniVectors

/usr/bin/time -v bash ../analysis/runSVD.sh --dimension $allTermsCount --svNum 500 --matrix finalDataset/training.cooccurrences --outU perf.svd.training.U --outV perf.svd.training.V --outSV perf.svd.training.SV --mirror --binarize &> perf.log.svdTraining

/usr/bin/time -v bash ../analysis/runSVD.sh --dimension $allTermsCount --svNum 500 --matrix finalDataset/trainingAndValidation.cooccurrences --outU perf.svd.trainingAndValidation.U --outV perf.svd.trainingAndValidation.V --outSV perf.svd.trainingAndValidation.SV --mirror --binarize &> perf.log.svdTrainingAndValidation

while read method
do
	/usr/bin/time -v $python ../analysis/separate/$method.py --cooccurrenceFile finalDataset/trainingAndValidation.cooccurrences --occurrenceFile finalDataset/trainingAndValidation.occurrences --sentenceCount finalDataset/trainingAndValidation.sentenceCounts --relationsToScore combinedData.testing.coords --outFile perf.out.$method &> perf.log.$method

done < perfMethods.txt

method=anni
/usr/bin/time -v $python ../analysis/separate/$method.py --cooccurrenceFile finalDataset/trainingAndValidation.cooccurrences --occurrenceFile finalDataset/trainingAndValidation.occurrences --sentenceCount finalDataset/trainingAndValidation.sentenceCounts --relationsToScore combinedData.testing.coords --anniVectors anni.trainingAndValidation.vectors --anniVectorsIndex anni.trainingAndValidation.index --outFile perf.out.$method &> perf.log.$method

optimalSV=`cat parameters.sv`
/usr/bin/time -v $python ../analysis/calcSVDScores.py --svdU svd.trainingAndValidation.U --svdV svd.trainingAndValidation.V --svdSV svd.trainingAndValidation.SV --relationsToScore combinedData.testing.coords --outFile perf.out.svd --sv $optimalSV &> perf.log.svd

grep 'System time' perf.log.* > perf.summary.time
grep 'Maximum resident set size' perf.log.* > perf.summary.mem


text:
import pytest
import astroid
from pylint.testutils import MessageTest
from pylint.testutils import CheckerTestCase

from pylint_plugins import PrintFunction

@pytest.fixture(scope="module")
def test_case():
    class TestPrintFunction(CheckerTestCase):
        CHECKER_CLASS = PrintFunction

    test_case = TestPrintFunction()
    test_case.setup_method()
    return test_case

def test_print_function(test_case):
    node = astroid.extract_node("print('hello')")
    with test_case.assertAddsMessages(
        MessageTest(test_case.CHECKER_CLASS.name, node=node, line=1, col_offset=0)
    ):
        test_case.walk(node)

    node = astroid.extract_node("module.print('hello')")
    with test_case.assertNoMessages():
        test_case.walk(node)


text:
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

from django.test import TestCase
from django.db import models
import re

from randomslug.models import *
from randomslug.validators import sluglen

from .models import Slug

class SluglenTest(TestCase):
    def setUp(self):
        self.default = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'
        self.custom = '-gda985'

    def test_valid_slugs_default_characters(self):
        valids = ['xCodJFRc', '1fGkb_2234', 'dfsNFDe_1', '023BBDf']
        for slug in valids:
            self.assertNotEqual(sluglen(slug, self.default), 0)
        self.assertEqual(sluglen(valids[0], self.default), 8)
        self.assertEqual(sluglen(valids[1], self.default), 5)
        self.assertEqual(sluglen(valids[2], self.default), 7)
        self.assertEqual(sluglen(valids[3], self.default), 7)

    def test_invalid_slugs_default_characters(self):
        invalids = ['xC_odJFRc', '1&&&fGkb_2234', '_dfsNFDe_1', '%023BBDf']
        for slug in invalids:
            self.assertEqual(sluglen(slug, self.default), 0)

    def test_valid_slugs_custom_characters(self):
        valids = ['gda985_12', '95-_3', 'ga-9_9999']
        for slug in valids:
            self.assertNotEqual(sluglen(slug, self.custom), 0)
        self.assertEqual(sluglen(valids[0], self.custom), 6)
        self.assertEqual(sluglen(valids[1], self.custom), 3)
        self.assertEqual(sluglen(valids[2], self.custom), 4)

    def test_invalid_slugs_custom_characters(self):
        invalids = ['gcda985_12', '4495-_3', 'ga-33239_9999']
        for slug in invalids:
            self.assertEqual(sluglen(slug, self.custom), 0)

class SlugifyTest(TestCase):
    def setUp(self):
        self.default = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'
        self.value = "".join(random.choice(self.default) for x in range(10))
        self.pattern = r'^(?P<slug>[' + self.default + ']+)(_\d+)?$'

    def test_generated_slug_length(self):
        slug = slugify(self.value)
        self.assertEqual(sluglen(slug, self.default), 10)
        slug = slugify(self.value, 4)
        self.assertEqual(sluglen(slug, self.default), 10)

    def test_generated_slug_pattern(self):
        slug = slugify(self.value)
        self.assertNotEqual(re.match(self.pattern, slug), None)

class RandomSlugFieldTest(TestCase):
    def setUp(self):
        self.default = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'
        self.pattern = r'^(?P<slug>[' + self.default + ']+)(_\d+)?$'

    def test_slug_length(self):
        slugfield = RandomSlugField(10)
        self.assertEqual(slugfield.slug_length, 10)

    def test_slug_in_model(self):
        slugmodel = Slug()
        self.assertEqual(slugmodel.slug, u'')
        slugmodel.save()
        self.assertIsNotNone(slugmodel.slug)
        self.assertEqual(sluglen(slugmodel.slug, self.default), 10)
        self.assertIsNotNone(re.match(self.pattern, slugmodel.slug))

    def test_slug_db_type(self):
        slugfield = RandomSlugField()
        self.assertEqual(slugfield.db_type(None), 'varchar(10)')
        slugfield = RandomSlugField(5)
        self.assertEqual(slugfield.db_type(None), 'varchar(5)')


text:
/**
 * Provides a base class for anything wrapping a text input.
 */
wesabe.$class('wesabe.views.widgets.BaseField', wesabe.views.widgets.BaseWidget, function($class, $super, $package) {
  // import jQuery as $
  var $ = jQuery;

  $class.DOM_EVENT_MAP = {
    keydown: 'onKeyDown', keypress: 'onKeyPress', keyup: 'onKeyUp',
    blur: 'onBlur', focus: 'onFocus',
    change: 'onChange', pollingchange: 'onPollingChange'};

  $.extend($class.prototype, {
    _value: null,
    _changeWatcher: null,

    init: function(element, delegate) {
      var me = this;

      if (!element)
        element = $('<input type="text">');

      $super.init.call(me, element);

      // bind the events that subclasses or delegates declare themselves interested in
      var delegates = [me];
      if (delegate) delegates.push(delegate);

      var domBindings = {};

      $.each($class.DOM_EVENT_MAP, function(key, method) {
        domBindings[method] = 0;
        $.each(delegates, function(i, d) {
          if (d[method]) {
            element.bind(key, function(event){ d[method].call(d, event, me) });
            domBindings[method]++;
          }
        });
      });

      if (domBindings.onPollingChange > 0)
        this._startWatchingForChanges();

      element.attr('autocomplete', 'off');
    },

    value: function() {
      return this.get('element').val();
    },

    setValue: function(value) {
      this.get('element').val(value);
    },

    name: function() {
      return this.get('element').attr('name');
    },

    setName: function(name) {
      this.get('element').attr('name', name);
    },

    isEnabled: function() {
      return !this.get('element').attr('disabled');
    },

    setEnabled: function(enabled) {
      this.get('element').attr('disabled', !enabled);
      if (!enabled)
        this.blur();
    },

    clear: function() {
      this.get('element').val('');
    },

    focus: function() {
      var element = this.get('element');
      if (element.length) element[0].focus();
    },

    blur: function() {
      this.get('element').blur();
    },

    clearAndBlur: function() {
      this.clear();
      this.blur();
    },

    isEmpty: function() {
      return !this.get('element').val();
    },

    selectAllAndFocus: function() {
      var element = this.get('element');
      element.caret(0, element.val().length);
      this.focus();
    },

    _startWatchingForChanges: function(msToWait) {
      var me = this;
      me._value = me.get('value');
      (function() {
        if (me._value !== me.get('value')) {
          me._value = me.get('value');
          me.get('element').trigger('pollingchange');
        }
        me._changeWatcher = setTimeout(arguments.callee, msToWait || 50);
      })();
    },

    _stopWatchingForChanges: function() {
      clearTimeout(this._changeWatcher);
    },

    destroy: function() {
      this._stopWatchingForChanges();
      $super.destroy.apply(this, arguments);
    }
  });
});


text:
void ofApp::setup(){

    a.setup();
    a.highlightColor = ofColor::pink;
    a.mainColor = ofColor::yellow;

    b.setup();
    b.highlightColor = ofColor::pink;
    b.mainColor = ofColor::darkCyan;

    c.setup();
    c.highlightColor = ofColor::pink;
    c.mainColor = ofColor::darkMagenta;

}

//--------------------------------------------------------------
void ofApp::update(){

    b.update();
    a.update();

    c.update();

    ofHideCursor();

    // go through every edge, calc its orientation
    // go through every point, calc its distance to closest edge, store that
    // try to do something with orientation...

}

//--------------------------------------------------------------
void ofApp::draw(){

    ofColor tempCo;
    tempCo.setHex(0x300032);
    tempCo = ofColor::peachPuff;
    //tempCo.setBrightness(tempCo.getBrightness() * ofMap(mouseX, 0, ofGetWidth(), 0, 1));
    ofBackground(tempCo);

    b.draw();

    ofEnableBlendMode(OF_BLENDMODE_MULTIPLY);

    ofTranslate(100,0);
    c.draw();

    ofTranslate(-300,0);
    a.draw();

    ofEnableAlphaBlending();

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){

}

//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}


text:
Links
*****

Articles
========

- `Catch Jackrabbit and the Java Content Repository API`_

Performance
===========

- http://article.gmane.org/gmane.comp.apache.jackrabbit.devel/3994

Testing
=======

- `Speedy unit testing with Jackrabbit`_

.. _`Catch Jackrabbit and the Java Content Repository API`: http://www.artima.com/lejava/articles/contentrepositoryP.html
.. _`Speedy unit testing with Jackrabbit`: http://jbossdna.blogspot.com/2008/02/unit-testing-jackrabbit.html


text:
package editor;

import griffon.core.artifact.GriffonView;
import griffon.metadata.ArtifactProviderFor;
import org.codehaus.griffon.runtime.swing.artifact.AbstractSwingGriffonView;

import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.util.Objects;

@ArtifactProviderFor(GriffonView.class)
public class EditorView extends AbstractSwingGriffonView {
    private EditorModel model;
    private ContainerView parentView;
    private String tabName;

    private JScrollPane tab;
    private JTextArea editor;

    @Override
    public void initUI() {
        editor = new JTextArea();
        editor.setEditable(true);
        editor.setEnabled(true);

        model.getDocument().addPropertyChangeListener("contents", (e) -> editor.setText((String) e.getNewValue()));

        tab = new JScrollPane();
        tab.putClientProperty("mvcIdentifier", getMvcGroup().getMvcId());
        tab.setViewportView(editor);

        editor.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                updateDirtyStatus();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateDirtyStatus();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateDirtyStatus();
            }

            private void updateDirtyStatus() {
                model.getDocument().setDirty(!Objects.equals(editor.getText(), model.getDocument().getContents()));
            }
        });

        JTabbedPane tabGroup = parentView.getTabGroup();
        tabGroup.addTab(tabName, tab);
        tabGroup.setSelectedIndex(tabGroup.getTabCount() - 1);
    }

    public JTextArea getEditor() {
        return editor;
    }

    @Override
    public void mvcGroupDestroy() {
        parentView.getTabGroup().remove(tab);
    }
}