import Time exposing (Time,second)
import Html exposing (Html,text)
import Set exposing (Set)
import Cardinal exposing (Coordinate,Bound)
import Dirty
import Random

-- Model
type alias Model =
    { alive : Set Coordinate
    , width : Int
    , height : Int }

init : (Model, Cmd Msg)
init =
  let
      width = 10
      widthCoordinateGenerator = Random.int 0 <| width - 1
      height = 10
      heightCoordinateGenerator = Random.int 0 <| height - 1
      locationGenerator = Random.pair widthCoordinateGenerator heightCoordinateGenerator
      listGenerator = Random.list (width * height // 2) locationGenerator
  in
    ({alive = Set.empty
    , width = width
    , height = height}, Random.generate Genesis listGenerator)

-- Messages
type Msg
    = Tick Time
    | Genesis (List(Coordinate))

-- View
view : Model -> Html Msg
view model = text <| toString model

-- Update
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
        Tick _ -> (model, Cmd.none)
        Genesis points ->
          ( { model | alive = Set.fromList points }
          , Cmd.none)

-- Subscriptions
subscriptions : Model -> Sub Msg
subscriptions model =
    Time.every second Tick

-- Main
main : Program Never Model Msg
main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

Update main Model to handle Bounds type

import Time exposing (Time,second)
import Html exposing (Html,text)
import Set exposing (Set)
import Cardinal exposing (Coordinate,Bounds)
import Dirty
import Random

-- Model
type alias Model =
    { alive : Set Coordinate
    , bounds : Bounds
    }

init : (Model, Cmd Msg)
init =
  let
      bounds = { x = 0, y = 0, width = 10, height = 10 }
      widthCoordinateGenerator = Random.int bounds.x <| bounds.width - 1
      heightCoordinateGenerator = Random.int bounds.y <| bounds.height - 1
      locationGenerator = Random.pair widthCoordinateGenerator heightCoordinateGenerator
      listGenerator = Random.list (bounds.width * bounds.height // 2) locationGenerator
  in
    ({alive = Set.empty
    , bounds = bounds
    }, Random.generate Genesis listGenerator)

-- Messages
type Msg
    = Tick Time
    | Genesis (List(Coordinate))

-- View
view : Model -> Html Msg
view model = text <| toString model

-- Update
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
        Tick _ -> (model, Cmd.none)
        Genesis points ->
          ( { model | alive = Set.fromList points }
          , Cmd.none)

-- Subscriptions
subscriptions : Model -> Sub Msg
subscriptions model =
    Time.every second Tick

-- Main
main : Program Never Model Msg
main =
    Html.program
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }


module Main exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)

-- MODEL

type alias Show =
    { id : Int
    , name : String
    , overview : String
    , show_poster : String
    }

type alias Model =
    { shows : List Show
    }

-- FLAGS

type alias Flags =
    List Show

-- INIT

init : Flags -> ( Model, Cmd Message )
init flags =
    ( { shows = flags
      }
    , Cmd.none
    )

-- VIEW

showTemplate : Show -> Html Message
showTemplate show =
    div [ class "fl w-50 w-25-m w-20-l pa2" ]
        -- TODO: Replace href with show details page. Fetch individual show data to access it
        [ a [ href "https://www.themoviedb.org/?language=en", class "db link dim tc" ]
            [ img [ src ("https://image.tmdb.org/t/p/w342" ++ show.show_poster), alt (show.name ++ " Poster"), class "w-100 db outline black-10" ]
                []
            , dl [ class "mt2 f6 lh-copy" ]
                [ dt [ class "clip" ]
                    [ text "Title" ]
                , dd [ class "ml0 black truncate w-100" ]
                    [ text show.name ]
                ]
            ]
        ]

view : Model -> Html Message
view model =
    article []
        [ h2 [ class "f3 fw4 pa3 mv0" ]
            [ text "TV Shows" ]
        , div [ class "cf pa2" ]
            (List.map
                showTemplate
                model.shows
            )
        ]

-- MESSAGE

type Message
    = None

-- UPDATE

update : Message -> Model -> ( Model, Cmd Message )
update message model =
    ( model, Cmd.none )

-- SUBSCRIPTIONS

subscriptions : Model -> Sub Message
subscriptions model =
    Sub.none

-- MAIN

main : Program Flags Model Message
main =
    Html.programWithFlags
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

Remove previously used Elm code

module Main exposing (..)

import Html exposing (text)

main : Html.Html msg
main =
    text "Hello, from Elm!"


module ViewPhotos exposing (viewPhotos)
import Html exposing (..)
import Html.Attributes exposing (class, style, title, src, id)
import Types exposing (..)
import DateUtils exposing (..)
import Dict

--------------------------------------------------------------------------------
-- View functions
--------------------------------------------------------------------------------

viewPhotos : Model -> Html Msg
viewPhotos model =
    let
        dateExifString =
            model.dateShown |> dateToExifString

        datePhotos =
            Dict.get dateExifString model.photoMetadata
    in
        div
            [ id "photos" ]
            [ h1 [] [ model.dateShown |> dateToString |> text ]
            , case datePhotos of
                Nothing -> div [] [ text "No photos for that date" ]
                Just photos -> div [] [ viewPictureList photos ]
            ]

viewPictureList : List PhotoMetadata -> Html Msg
viewPictureList metadataList =
    div
        []
        [ h2 [] [ text ((List.length metadataList |> toString) ++ " photos") ]
        , ul
            []
            (List.map viewPicture (List.sortBy .dateCreated metadataList))
        ]

viewPicture : PhotoMetadata -> Html Msg
viewPicture metadata =
    li
        []
        [ img [ src metadata.fileName ] [] ]

Add buttons for previous or next days

module ViewPhotos exposing (viewPhotos)
import Html exposing (..)
import Html.Attributes exposing (class, style, title, src, id, value)
import Types exposing (..)
import DateUtils exposing (..)
import Time.Date as Date exposing (Weekday(..))
import Html.Events exposing (onClick)
import Dict

--------------------------------------------------------------------------------
-- View functions
--------------------------------------------------------------------------------

viewPhotos : Model -> Html Msg
viewPhotos model =
    let
        dateExifString =
            model.dateShown |> dateToExifString

        datePhotos =
            Dict.get dateExifString model.photoMetadata

    in
        div
            [ id "photos" ]
            [ h1 [] [ model.dateShown |> dateToString |> text ]
            , viewPrevNextButtons model.dateShown
            , case datePhotos of
                Nothing -> div [] [ text "No photos for that date" ]
                Just photos -> div [] [ viewPictureList photos ]
            , viewPrevNextButtons model.dateShown
            ]

viewPictureList : List PhotoMetadata -> Html Msg
viewPictureList metadataList =
    div
        []
        [ h2 [] [ text ((List.length metadataList |> toString) ++ " photos") ]
        , ul
            []
            (List.map viewPicture (List.sortBy .dateCreated metadataList))
        ]

viewPicture : PhotoMetadata -> Html Msg
viewPicture metadata =
    li
        []
        [ img [ src metadata.fileName ] [] ]

viewOtherDayButton : String -> Date.Date -> Int -> Html Msg
viewOtherDayButton label date offset =
    let
        day =
            Date.addDays offset date
    in
        button
            [ onClick (ShowPhotosForDate day) ]
            [ text (label ++ " (" ++ (dateToString day) ++ ")") ]

viewPrevNextButtons : Date.Date -> Html Msg
viewPrevNextButtons date =
    div []
        [ viewOtherDayButton "Previous" date -1
        , span [] [ text "..." ]
        , viewOtherDayButton "Next" date 1
        ]


module Setup.Settings exposing (..)

import Basics.Extra exposing ((=>))
import Json.Decode as Decode
import Json.Decode.Pipeline exposing (..)
import Json.Encode as Encode
import Roster.Data exposing (RosterData)

type alias Data =
    { timerDuration : Int
    , breakDuration : Int
    , intervalsPerBreak : Int
    , rosterData : RosterData
    , showHideShortcut : String
    }

decoder : Decode.Decoder Data
decoder =
    Json.Decode.Pipeline.decode Data
        |> required "timerDuration" Decode.int
        |> required "breakDuration" Decode.int
        |> required "intervalsPerBreak" Decode.int
        |> required "mobsterData" Roster.Data.decoder
        |> required "showHideShortcut" Decode.string

decode : Encode.Value -> Result String Data
decode data =
    Decode.decodeValue decoder data

encoder : Data -> Encode.Value
encoder settingsData =
    Encode.object
        [ "timerDuration" => Encode.int settingsData.timerDuration
        , "breakDuration" => Encode.int settingsData.breakDuration
        , "intervalsPerBreak" => Encode.int settingsData.intervalsPerBreak
        , "mobsterData" => Roster.Data.encoder settingsData.rosterData
        , "showHideShortcut" => Encode.string settingsData.showHideShortcut
        ]

initial : Data
initial =
    { timerDuration = 5
    , breakDuration = 5
    , intervalsPerBreak = 5
    , rosterData = Roster.Data.empty
    , showHideShortcut = "K"
    }

Make Ctrl/Cmd+shift+L the default show/hide shortcut.

module Setup.Settings exposing (..)

import Basics.Extra exposing ((=>))
import Json.Decode as Decode
import Json.Decode.Pipeline exposing (..)
import Json.Encode as Encode
import Roster.Data exposing (RosterData)

type alias Data =
    { timerDuration : Int
    , breakDuration : Int
    , intervalsPerBreak : Int
    , rosterData : RosterData
    , showHideShortcut : String
    }

decoder : Decode.Decoder Data
decoder =
    Json.Decode.Pipeline.decode Data
        |> required "timerDuration" Decode.int
        |> required "breakDuration" Decode.int
        |> required "intervalsPerBreak" Decode.int
        |> required "mobsterData" Roster.Data.decoder
        |> required "showHideShortcut" Decode.string

decode : Encode.Value -> Result String Data
decode data =
    Decode.decodeValue decoder data

encoder : Data -> Encode.Value
encoder settingsData =
    Encode.object
        [ "timerDuration" => Encode.int settingsData.timerDuration
        , "breakDuration" => Encode.int settingsData.breakDuration
        , "intervalsPerBreak" => Encode.int settingsData.intervalsPerBreak
        , "mobsterData" => Roster.Data.encoder settingsData.rosterData
        , "showHideShortcut" => Encode.string settingsData.showHideShortcut
        ]

initial : Data
initial =
    { timerDuration = 5
    , breakDuration = 5
    , intervalsPerBreak = 5
    , rosterData = Roster.Data.empty
    , showHideShortcut = "L"
    }


module Marshalling (scorecardToJson) where

{-|
@docs scorecardToJson
-}

import Bowling exposing (..)
import Json.Encode exposing (..)

gutterValue = string "-"
spareValue  = string "/"
strikeValue = string "X"

pinValue : Int -> Value
pinValue p =
  case p of
  0         -> gutterValue
  otherwise -> string <| toString p

frameToJson : Frame -> Value
frameToJson frame =
  list <| case frame of
            Strike              -> [ strikeValue            ]
            Spare           f   -> [ pinValue f, spareValue ]
            Complete        f s -> [ pinValue f, pinValue s ]
            IncompleteFrame f   -> [ pinValue f ]
            otherwise           -> [  ]

gameToJson : Game -> Value
gameToJson game =
  object
    [ ("player", string game.player)
    , ("frames", list <| List.map frameToJson game.frames)
    ]

{-|

maps a Scorecard into a JSON object.

-}

scorecardToJson : Scorecard -> Value
scorecardToJson scorecard =
  list <| List.map gameToJson scorecard

Add the players' scores to the JSON

module Marshalling (scorecardToJson) where

{-|
@docs scorecardToJson
-}

import Bowling exposing (..)
import Json.Encode exposing (..)

gutterValue = string "-"
spareValue  = string "/"
strikeValue = string "X"

pinValue : Int -> Value
pinValue p =
  case p of
  0         -> gutterValue
  otherwise -> string <| toString p

frameToJson : Frame -> Value
frameToJson frame =
  list <| case frame of
            Strike              -> [ strikeValue            ]
            Spare           f   -> [ pinValue f, spareValue ]
            Complete        f s -> [ pinValue f, pinValue s ]
            IncompleteFrame f   -> [ pinValue f ]
            otherwise           -> [  ]

gameToJson : Game -> Value
gameToJson game =
  object
    [ ("player", string game.player)
    , ("frames", list <| List.map frameToJson game.frames)
    , ("score",  int <| gameScore game.frames)
    ]

{-|

maps a Scorecard into a JSON object.

-}

scorecardToJson : Scorecard -> Value
scorecardToJson scorecard =
  list <| List.map gameToJson scorecard


import Html.App as App
import Html exposing (Html, br, div, text)

import IdeaFight.PartialForest as Forest
import IdeaFight.Shuffle as Shuffle

import Random
import Time

type alias Model = Forest.Forest Int
type Msg = ShuffleMe (List Int) | Advance

stepForest : Forest.Forest comparable -> Forest.Forest comparable
stepForest forest =
  let (a, b) = Forest.getNextPair forest
  in Forest.choose forest <| max a b

init : (Model, Cmd Msg)
init = (Forest.empty, Random.generate ShuffleMe (Shuffle.shuffle [1..8]))

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    ShuffleMe values -> (Forest.fromList values, Cmd.none)
    Advance -> (stepForest model, Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions _ = Time.every (Time.second * 5) <| always Advance

view : Model -> Html Msg
view model = div [] [
    text <| toString <| Forest.topNCount model,
    br [] [],
    Forest.drawForest model
  ]

main : Program Never
main = App.program {
    init = init,
    update = update,
    subscriptions = subscriptions,
    view = view
  }

Advance forest test with clicks

import Html.App as App
import Html exposing (Html, br, button, div, text)
import Html.Events exposing (onClick)

import IdeaFight.PartialForest as Forest
import IdeaFight.Shuffle as Shuffle

import Random
import Time

type alias Model = Forest.Forest Int
type Msg = ShuffleMe (List Int) | Advance

stepForest : Forest.Forest comparable -> Forest.Forest comparable
stepForest forest =
  let (a, b) = Forest.getNextPair forest
  in Forest.choose forest <| max a b

init : (Model, Cmd Msg)
init = (Forest.empty, Random.generate ShuffleMe (Shuffle.shuffle [1..8]))

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    ShuffleMe values -> (Forest.fromList values, Cmd.none)
    Advance -> (stepForest model, Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions _ = Sub.none

view : Model -> Html Msg
view model = div [] [
    button [ onClick Advance ] [ text "Advance" ],
    br [] [],
    text <| toString <| Forest.topNCount model,
    br [] [],
    Forest.drawForest model
  ]

main : Program Never
main = App.program {
    init = init,
    update = update,
    subscriptions = subscriptions,
    view = view
  }


module Main where

import Graphics.Element exposing (show)

main: Graphics.Element.Element
main =
  show "Ready"

Prepare Basic structure for holding random user data and displaying it.

module Main where

import Http
import Json.Decode as Json exposing ((:=))
import Task exposing (Task)
import Graphics.Element exposing (show, Element)
import Signal

type alias User =
  { email: String
  }

type Action = NoOp
            | UpdateEmail String

mailbox: Signal.Mailbox Action
mailbox = Signal.mailbox NoOp

modelUpdate: Action -> User -> User
modelUpdate action model =
  case action of
    UpdateEmail email ->
      { model | email = email }
    _ ->
      model

modelSignal: Signal User
modelSignal =
  Signal.foldp modelUpdate (User "") mailbox.signal

view: User -> Element
view model =
  show model.email

main: Signal Element
main =
  Signal.map view modelSignal
--
--
-- getData: Task Http.Error String
-- getData =
--   Http.get getEmail "https://randomuser.me/api/"
--
-- getEmail: Json.Decoder String -> String
-- getEmail =
--   Json.at ["results", "user", "email"]
--
-- handleData: String -> Signal.Address Action
-- handleData email =
--   Signal.forwardTo mailbox.address (\email -> UpdateEmail email)
--
-- port run: Task Http.Error ()
-- port run =
--   Task.andThen getData handleData


module Resources exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)

type alias Resource =
    { url : String, dsc : String }

resources : List Resource
resources =
    [ { url = "https://google.com"
      , dsc = "Awesome site, really great."
      }
    , { url = "https://stackoverflow.com"
      , dsc = "Another real gem."
      }
    ]

resourceList : List Resource -> Html msg
resourceList resources =
    resources
        |> List.map (\l -> li [] [ a [ href l.url ] [ text l.url ], text (" - " ++ l.dsc) ])
        |> ul []

Add some actual elm links

module Resources exposing (..)

import Html exposing (..)
import Html.Attributes exposing (..)

type alias Resource =
    { url : String, dsc : String }

resources : List Resource
resources =
    [ { url = "https://dennisreimann.de/articles/elm-data-structures-record-tuple.html"
      , dsc = "Elm Data Structures (2) - Records and Tuples"
      }
    , { url = "https://stackoverflow.com"
      , dsc = "Another real gem."
      }
    , { url = "https://dennisreimann.de/articles/elm.html"
      , dsc = "Elm Articles by Dennis Reimann. λλλλ"
      }
    ]

resourceList : List Resource -> Html msg
resourceList resources =
    resources
        |> List.map (\l -> li [] [ a [ href l.url ] [ text l.url ], text (" - " ++ l.dsc) ])
        |> ul []


module Dirty exposing (find)

import Set exposing (Set)

import Cardinal exposing (Coordinate,Bound)

find : Set (Coordinate) -> Bound -> Set (Coordinate)
find alive bounds =

reducer : Coordinate -> Set(Coordinate) -> Set(Coordinate)
reducer current accumulated =
  let
      (x, y) = current
      new = Set.fromList
        [ (x + 1, y + 1)
        , (x + 1, y)
        , (x + 1, y - 1)
        , (x, y + 1)
        , (x, y - 1)
        , (x - 1, y + 1)
        , (x - 1, y)
        , (x - 1, y - 1)
        ]
  in
     Set.union accumulated new

predicate :

Update import statements based on Cardinal API change

module Dirty exposing (find)

import Set exposing (Set)

import Cardinal exposing (Coordinate,Bounds)

find : Set (Coordinate) -> Bounds -> Set (Coordinate)
find alive bounds =

reducer : Coordinate -> Set(Coordinate) -> Set(Coordinate)
reducer current accumulated =
  let
      (x, y) = current
      new = Set.fromList
        [ (x + 1, y + 1)
        , (x + 1, y)
        , (x + 1, y - 1)
        , (x, y + 1)
        , (x, y - 1)
        , (x - 1, y + 1)
        , (x - 1, y)
        , (x - 1, y - 1)
        ]
  in
     Set.union accumulated new

predicate :


module Sublist exposing (..)

type ListComparison = Equal | Unequal | Sublist | Superlist

sublist: List Int -> List Int -> ListComparison
sublist list1 list2 =
    if list1 == list2 then
        Equal
    else if isSublist list1 list2 then
        Sublist
    else if isSublist list2 list1 then
        Superlist
    else
        Unequal

isSublist: List Int -> List Int -> Bool
isSublist list1 list2 =
    if list1 == list2 then
        True
    else if List.isEmpty list2 then
        False
    else
        isSublist list1 (List.drop 1 list2) ||
        isSublist list1 (List.take (List.length list2 - 1) list2)

version : Int
version =
    2

Stop recursion if list2 is shorter than list1

module Sublist exposing (..)

type ListComparison = Equal | Unequal | Sublist | Superlist

sublist: List Int -> List Int -> ListComparison
sublist list1 list2 =
    if list1 == list2 then
        Equal
    else if isSublist list1 list2 then
        Sublist
    else if isSublist list2 list1 then
        Superlist
    else
        Unequal

isSublist: List Int -> List Int -> Bool
isSublist list1 list2 =
    if list1 == list2 then
        True
    else if List.length list1 > List.length list2 then
        False
    else
        isSublist list1 (List.drop 1 list2) ||
        isSublist list1 (List.take (List.length list2 - 1) list2)

version : Int
version =
    2


module OpenSolid.Svg
  ( svg
  , lineSegment
  ) where

import Svg exposing (Svg, Attribute)
import Svg.Attributes as Attributes
import OpenSolid.Interval as Interval exposing (Interval)
import OpenSolid.Box2d as Box2d exposing (Box2d)
import OpenSolid.LineSegment2d as LineSegment2d exposing (LineSegment2d)

svg: Float -> Float -> Box2d -> List Svg -> Svg
svg width height box elements =
  let
    widthAttribute = Attributes.width (toString width)
    heightAttribute = Attributes.height (toString height)
    viewX = toString box.x.lowerBound
    viewY = toString (-box.y.upperBound)
    viewWidth = toString (Interval.width box.x)
    viewHeight = toString (Interval.width box.y)
    viewBoxAttribute =
      Attributes.viewBox (viewX ++ " " ++ viewY ++ " " ++ viewWidth ++ " " ++ viewHeight)
  in
    Svg.svg [widthAttribute, heightAttribute, viewBoxAttribute] elements

lineSegment: List Attribute -> LineSegment2d -> Svg
lineSegment attributes lineSegment =
  let
    {firstEndpoint, secondEndpoint} = lineSegment
    x1 = toString firstEndpoint.x
    y1 = toString (-firstEndpoint.y)
    x2 = toString secondEndpoint.x
    y2 = toString (-secondEndpoint.y)
    d = "M " ++ x1 ++ " " ++ y1 ++ " L " ++ x2 ++ " " ++ y2
  in
    Svg.path ([Attributes.d d] ++ attributes) []

Make SVG code a little more readable

module OpenSolid.Svg
  ( svg
  , lineSegment
  ) where

import Svg exposing (Svg, Attribute)
import Svg.Attributes as Attributes
import String
import OpenSolid.Interval as Interval exposing (Interval)
import OpenSolid.Box2d as Box2d exposing (Box2d)
import OpenSolid.LineSegment2d as LineSegment2d exposing (LineSegment2d)

svg: Float -> Float -> Box2d -> List Svg -> Svg
svg width height box elements =
  let
    widthAttribute = Attributes.width (toString width)
    heightAttribute = Attributes.height (toString height)
    viewX = toString box.x.lowerBound
    viewY = toString (-box.y.upperBound)
    viewWidth = toString (Interval.width box.x)
    viewHeight = toString (Interval.width box.y)
    viewBoxAttribute =
      Attributes.viewBox (viewX ++ " " ++ viewY ++ " " ++ viewWidth ++ " " ++ viewHeight)
  in
    Svg.svg [widthAttribute, heightAttribute, viewBoxAttribute] elements

lineSegment: List Attribute -> LineSegment2d -> Svg
lineSegment attributes lineSegment =
  let
    {firstEndpoint, secondEndpoint} = lineSegment
    x1 = firstEndpoint.x
    y1 = -firstEndpoint.y
    x2 = secondEndpoint.x
    y2 = -secondEndpoint.y
    d = String.join " " ["M", toString x1, toString y1, "L", toString x2, toString y2]
  in
    Svg.path ([Attributes.d d] ++ attributes) []


module Update exposing (..)

import Messages exposing (Msg(..))
import Models exposing (..)

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of
    NoOp ->
      ( model, Cmd.none )
    OnFetchDebts ( Ok newDebts ) ->
      ( { model | debts = newDebts }, Cmd.none )
    OnFetchDebts ( Err error ) ->
      ( model, Cmd.none )

Add participants to form on receive transactions

module Update exposing (..)

import List.Extra exposing (unique)
import Messages exposing (Msg(..))
import Models exposing (..)

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of
    NoOp ->
      ( model, Cmd.none )
    OnFetchDebts ( Ok newDebts ) ->
      ( onFetchDebts model newDebts, Cmd.none )
    OnFetchDebts ( Err error ) ->
      ( model, Cmd.none )

onFetchDebts : Model -> List Debt -> Model
onFetchDebts model debts =
  let
    newParticipants = List.map .receiver debts |> unique
    transaction = model.transaction
  in
    { model
    | debts = debts
    , transaction =
      { transaction
      | participants = newParticipants
      }
    }


module Main exposing (main)

import Html exposing (..)
import Html.Events exposing (onClick)

main =
    Html.beginnerProgram
        { model = initialModel
        , view = view
        , update = update
        }

type State
    = Open
    | Closed

type alias Model =
    { state : State, values : List String }

initialModel : Model
initialModel =
    { state = Open
    , values = fruits
    }

fruits : List String
fruits =
    [ "bananas"
    , "apples"
    , "oranges"
    , "peaches"
    , "strawberries"
    ]

view : Model -> Html Msg
view model =
    case model.state of
        Open ->
            viewOpen model

        Closed ->
            viewClosed

viewOpen : Model -> Html Msg
viewOpen model =
    div []
        [ p [ onClick CloseSelect ] [ text "Click to close" ]
        , ul [] (List.map dropdownItem model.values)
        ]

viewClosed : Html Msg
viewClosed =
    div []
        [ p [ onClick OpenSelect ] [ text "Click to open" ]
        ]

dropdownItem : String -> Html a
dropdownItem value =
    li [] [ text value ]

type Msg
    = OpenSelect
    | CloseSelect

update : Msg -> Model -> Model
update msg model =
    case msg of
        OpenSelect ->
            { model | state = Open }

        CloseSelect ->
            { model | state = Closed }

Add the concept of a "selected" value

module Main exposing (main)

import Html exposing (..)
import Html.Events exposing (onClick)

main =
    Html.beginnerProgram
        { model = initialModel
        , view = view
        , update = update
        }

type State
    = Open
    | Closed

type alias Model =
    { state : State
    , values : List String
    , selected : Maybe String
    }

initialModel : Model
initialModel =
    { state = Open
    , values = fruits
    , selected = Nothing
    }

fruits : List String
fruits =
    [ "bananas"
    , "apples"
    , "oranges"
    , "peaches"
    , "strawberries"
    ]

view : Model -> Html Msg
view model =
    case model.state of
        Open ->
            viewOpen model

        Closed ->
            viewClosed model

viewOpen : Model -> Html Msg
viewOpen model =
    div []
        [ dropdownHead model.selected CloseSelect
        , ul [] (List.map dropdownItem model.values)
        ]

viewClosed : Model -> Html Msg
viewClosed model =
    div []
        [ dropdownHead model.selected OpenSelect
        ]

dropdownItem : String -> Html a
dropdownItem value =
    li [] [ text value ]

dropdownHead : Maybe String -> Msg -> Html Msg
dropdownHead selected msg =
    case selected of
        Nothing ->
            p [ onClick msg ] [ text "Click to toggle" ]

        Just value ->
            p [ onClick msg ] [ text value ]

type Msg
    = OpenSelect
    | CloseSelect

update : Msg -> Model -> Model
update msg model =
    case msg of
        OpenSelect ->
            { model | state = Open }

        CloseSelect ->
            { model | state = Closed }


module Main (..) where

import Box
import BoxList
import Effects exposing (Effects, Never)
import Html exposing (div, Html, text)
import Html.Attributes exposing (style)
import StartApp exposing (start)
import Task

type alias Model =
  { boxLists : List BoxList.Model
  }

type Action
  = None

update : Action -> Model -> ( Model, Effects Action )
update action model =
  ( model, Effects.none )

view : Signal.Address Action -> Model -> Html
view address model =
  div [] <| List.map BoxList.view model.boxLists

app : StartApp.App Model
app =
  let
    initialModel =
      Model []
  in
    start
      { init = ( initialModel, Effects.none )
      , view = view
      , update = update
      , inputs = []
      }

main : Signal Html
main =
  app.html

port tasks : Signal (Task.Task Never ())
port tasks =
  app.tasks

Add button to add new box lists

module Main (..) where

import Box
import BoxList
import Effects exposing (Effects, Never)
import Html exposing (button, div, Html, text)
import Html.Attributes exposing (style)
import Html.Events exposing (onClick)
import StartApp exposing (start)
import Task

type alias ID =
  Int

type alias Model =
  { boxLists : List ( ID, BoxList.Model )
  , nextId : ID
  }

type Action
  = AddNewBoxList

update : Action -> Model -> ( Model, Effects Action )
update action model =
  case action of
    AddNewBoxList ->
      let
        newModel =
          { model
            | boxLists = List.append model.boxLists [ ( model.nextId, BoxList.Model [] ) ]
            , nextId = model.nextId + 1
          }
      in
        ( newModel, Effects.none )

view : Signal.Address Action -> Model -> Html
view address model =
  div
    []
    [ div [] <| List.map BoxList.view (List.map snd model.boxLists)
    , button [ onClick address AddNewBoxList ] [ text "Add new list" ]
    ]

app : StartApp.App Model
app =
  let
    initialModel =
      Model [] 0
  in
    start
      { init = ( initialModel, Effects.none )
      , view = view
      , update = update
      , inputs = []
      }

main : Signal Html
main =
  app.html

port tasks : Signal (Task.Task Never ())
port tasks =
  app.tasks


module Component.View exposing (view)

import Component.Model exposing (..)
import Component.Messages exposing (..)
import Html exposing (Html, div, text, a)
import Html.Attributes exposing (class, href)
import Nav.Nav exposing (toHash)
import Nav.Model exposing (Page(..))

componentClass : Status -> String
componentClass status =
    "component "
        ++ case status of
            Info ->
                "component--normal"

            Warn ->
                "component--warn"

            Error ->
                "component--error"

url : Model -> String
url model =
    toHash <| Component model.environment model.system model.component model.server

view : Model -> Html Msg
view model =
    a [ href <| url model, class (componentClass model.status) ]
        [ div [ class "component__name" ]
            [ text model.component ]
        , div [ class "component__server" ]
            [ text model.server ]
        ]

Prepend component with status icon

module Component.View exposing (view)

import Component.Model exposing (..)
import Component.Messages exposing (..)
import Html exposing (Html, div, text, a)
import Html.Attributes exposing (class, href)
import Nav.Nav exposing (toHash)
import Nav.Model exposing (Page(..))

statusIcon : Status -> String
statusIcon status =
    "component__status "
        ++ case status of
            Info ->
                ""

            Warn ->
                "icon-exclamation"

            Error ->
                "icon-fire"

url : Model -> String
url model =
    toHash <| Component model.environment model.system model.component model.server

view : Model -> Html Msg
view model =
    a [ href <| url model, class "component" ]
        [ div [ class <| statusIcon model.status ] []
        , div [ class "component__name" ]
            [ text model.component ]
        , div [ class "component__server" ]
            [ text model.server ]
        ]


module IdeaFight.LandingPage exposing (Model, Msg, init, update, subscriptions, view)

import Html.App as App
import Html exposing (Html, br, button, div, h1, hr, text, textarea)
import Html.Events exposing (onClick, onInput)

type alias Model = (String, Bool)
type Msg = UpdateContents String | Continue

init : (Model, Cmd Msg)
init = (("", False), Cmd.none)

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case (msg, model) of
    (UpdateContents newContent, _) -> ((newContent, False), Cmd.none)
    (Continue, (contents, _)) -> ((contents, True), Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions _ = Sub.none

inputs : Html Msg
inputs = div [] [
    textarea [ onInput UpdateContents ] [],
    br [] [],
    button [ onClick Continue ] [ text "Continue >" ]
  ]

view : Model -> Html Msg
view model = div [] [
    h1 [] [text "Idea Fight"],
    hr [] [],
    inputs
  ]

Make note of validation that's needed

-- XXX you need at least three ideas (or whatever N is)
module IdeaFight.LandingPage exposing (Model, Msg, init, update, subscriptions, view)

import Html.App as App
import Html exposing (Html, br, button, div, h1, hr, text, textarea)
import Html.Events exposing (onClick, onInput)

type alias Model = (String, Bool)
type Msg = UpdateContents String | Continue

init : (Model, Cmd Msg)
init = (("", False), Cmd.none)

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case (msg, model) of
    (UpdateContents newContent, _) -> ((newContent, False), Cmd.none)
    (Continue, (contents, _)) -> ((contents, True), Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions _ = Sub.none

inputs : Html Msg
inputs = div [] [
    textarea [ onInput UpdateContents ] [],
    br [] [],
    button [ onClick Continue ] [ text "Continue >" ]
  ]

view : Model -> Html Msg
view model = div [] [
    h1 [] [text "Idea Fight"],
    hr [] [],
    inputs
  ]


module GoogleMapMarker
    exposing
        ( Model
        , fromOffice
        )

import Office.Model as Office

type alias Model =
    { latLng : { lat : Float, lng : Float }
    , id : Int
    }

fromOffice : Office.Model -> Model
fromOffice ({ id } as office) =
    let
        (Office.Id officeId) =
            id
    in
        { latLng =
            { lat = office.address.geo.latitude
            , lng = office.address.geo.longitude
            }
        , id = officeId
        }

Switch from primitive handling to Json.Encode

module GoogleMapMarker
    exposing
        ( Model
        , fromOffice
        )

import Json.Encode as Encode
import Office.Model as Office
import Address.Model as Address

type alias Model =
    Encode.Value

fromOffice : Office.Model -> Model
fromOffice ({ id } as office) =
    Encode.object
        [ ( "id", encodeOfficeId id )
        , ( "latLng", encodeLatLon office.address.geo )
        ]

encodeOfficeId : Office.Id -> Encode.Value
encodeOfficeId (Office.Id id) =
    Encode.int id

encodeLatLon : Address.LatLon -> Encode.Value
encodeLatLon latLon =
    Encode.object
        [ ( "lat", Encode.float latLon.latitude )
        , ( "lng", Encode.float latLon.longitude )
        ]


-- Focus on the display screen (i.e. click the right half of this window)
-- and start pressing keys!

import Graphics.Element exposing (..)
import Keyboard

display : List Int -> Element
display keyCodes =
  show "You are holding down the following keys: " `beside` show keyCodes

main : Signal.Signal Element
main =
  Signal.map display Keyboard.keysDown

Adjust for new type of Keyboard.keysDown

-- Focus on the display screen (i.e. click the right half of this window)
-- and start pressing keys!

import Graphics.Element exposing (..)
import Keyboard
import Set

display : Set.Set Int -> Element
display keyCodes =
  flow right
    [ show "You are holding down the following keys: "
    , show (Set.toList keyCodes)
    ]

main : Signal.Signal Element
main =
  Signal.map display Keyboard.keysDown


module Views.TransactionTable exposing (transactionTable)

import Date exposing (..)
import Date.Format exposing (format)
import Html exposing (..)
import Html.Attributes exposing (class)
import Models exposing (Model, Debt)
import Messages exposing (Msg(..))

transactionTable : List Debt -> Html Msg
transactionTable debts =
  table [ class "table table-striped table-condensed table-bordered" ]
    [ transactionTableHead
    , transactionList debts ]

transactionTableHead : Html Msg
transactionTableHead =
  thead []
    [ tr []
      [ th [] [ text "Date" ]
      , th [] [ text "Name" ]
      , th [] [ text "Debt" ]
      , th [] [ text "Description" ]
      ]
    ]

transactionList : List Debt -> Html Msg
transactionList debts =
  tbody []
    ( List.map transactionRow debts )

transactionRow : Debt -> Html Msg
transactionRow debt =
  tr []
    [ td [] [ text (formatTimestamp debt.created_at) ]
    , td [] [ text debt.receiver ]
    , td [] [ text ( toString debt.amount ) ]
    , td [] [ text debt.description ]
    ]

formatTimestamp : Int -> String
formatTimestamp timestamp =
  Date.fromTime (toFloat timestamp)
  |> format "%Y/%m/%d"

Sort transactions by date desc

module Views.TransactionTable exposing (transactionTable)

import Date exposing (..)
import Date.Format exposing (format)
import Html exposing (..)
import Html.Attributes exposing (class)
import Models exposing (Model, Debt)
import Messages exposing (Msg(..))

transactionTable : List Debt -> Html Msg
transactionTable debts =
  table [ class "table table-striped table-condensed table-bordered" ]
    [ transactionTableHead
    , transactionList debts ]

transactionTableHead : Html Msg
transactionTableHead =
  thead []
    [ tr []
      [ th [] [ text "Date" ]
      , th [] [ text "Name" ]
      , th [] [ text "Debt" ]
      , th [] [ text "Description" ]
      ]
    ]

transactionList : List Debt -> Html Msg
transactionList debts =
  tbody []
    ( List.sortBy .created_at debts
      |> List.reverse
      |> List.map transactionRow
    )

transactionRow : Debt -> Html Msg
transactionRow debt =
  tr []
    [ td [] [ text (formatTimestamp debt.created_at) ]
    , td [] [ text debt.receiver ]
    , td [] [ text ( toString debt.amount ) ]
    , td [] [ text debt.description ]
    ]

formatTimestamp : Int -> String
formatTimestamp timestamp =
  Date.fromTime (toFloat timestamp)
  |> format "%Y/%m/%d"


module Display (..) where

import Html exposing (..)
import Html.Attributes exposing (..)
import Mouse

cell : Attribute
cell =
  style
    [("margin", "10px")
    , ("width", "30%")
    , ("height", "200px")
    , ("text-align", "center")
    , ("-webkit-user-select", "none")
    , ("user-select", "none")
    , ("font-size", "6em")
    , ("border-radius", "0")
    , ("-webkit-appearance", "none")
    , ("padding", "0px")
    , ("background", "white")
    , ("border", "2px solid #4A4A4A"),
      ("display", "inline-block")]

header : Attribute
header =
  style
    [("text-align", "center")]

header : Attribute
header =
  style
    [("text-align", "center")]

view : Html
view =
  div [] [
    h1 [header] [ Html.text "Welcome to Tic Tac Toe"],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] []
  ]

main =
  view

Add grid to display page

module Display (..) where

import Html exposing (..)
import Html.Attributes exposing (..)
import Mouse

cell : Attribute
cell =
  style
    [("margin", "10px")
    , ("width", "30%")
    , ("height", "200px")
    , ("text-align", "center")
    , ("-webkit-user-select", "none")
    , ("user-select", "none")
    , ("font-size", "6em")
    , ("border-radius", "0")
    , ("-webkit-appearance", "none")
    , ("padding", "0px")
    , ("background", "white")
    , ("border", "2px solid #4A4A4A"),
      ("display", "inline-block")]

header : Attribute
header =
  style
    [("text-align", "center")]

view : Html
view =
  div [] [
    h1 [header] [ Html.text "Welcome to Tic Tac Toe"],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] [],
    div [cell] []
  ]

main =
  view


module Toolbox.Views (..) where

import Html exposing (..)
import Html.Attributes exposing (..)
import Toolbox.Action exposing (Action)
import Toolbox.Types exposing (Ingredient, Model)

view : Signal.Address Action -> Model -> Html
view address model =
  case model.response of
    Just r ->
      ul
        [ class "list-group" ]
        (List.map ingredientItem r.ingredients)

    Nothing ->
      text "boo"

ingredientItem : Ingredient -> Html
ingredientItem i =
  li
    [ class "list-group-item" ]
    [ img [ src i.image, width 32, height 32 ] []
    , text i.name
    ]

Improve waiting message on initial load.

module Toolbox.Views (..) where

import Html exposing (..)
import Html.Attributes exposing (..)
import Toolbox.Action exposing (Action)
import Toolbox.Types exposing (Ingredient, Model)

view : Signal.Address Action -> Model -> Html
view address model =
  case model.response of
    Just r ->
      ul
        [ class "list-group" ]
        (List.map ingredientItem r.ingredients)

    Nothing ->
      div
        [ class "alert alert-info" ]
        [ text "Please wait..." ]

ingredientItem : Ingredient -> Html
ingredientItem i =
  li
    [ class "list-group-item" ]
    [ img [ src i.image, width 32, height 32 ] []
    , text i.name
    ]


module IVFinal.App.Layout exposing (..)

import Html as H exposing (Html)
import Html.Attributes as HA
import Svg as S exposing (Svg)
import Svg.Attributes as SA

-- CSS is really confusing.

wrapper : List (Html msg) -> Html msg
wrapper contents =
  H.div
    [ HA.style [ ("margin", "4em")
               , ("width", "600px")
               , ("display", "flex")
               ]
    ]
    contents

canvas : List (Svg msg) -> Html msg
canvas contents =
  H.div []
    [ S.svg
        [ SA.version "1.1"
        , SA.width "200"
        , SA.height "600"
        ]
        contents
    ]

form : List (Html msg) -> Html msg
form contents =
  H.div [] contents

Add explanatory text at the bottom

module IVFinal.App.Layout exposing (..)

import Html as H exposing (Html)
import Html.Attributes as HA
import Svg as S exposing (Svg)
import Svg.Attributes as SA

wrapper : List (Html msg) -> Html msg
wrapper contents =
  H.div
    [ HA.style [ ("margin", "4em")
               , ("width", "600px")
               ]
    ]
    [ H.div
        [ HA.style [("display", "flex")]
        ]
        contents
    , H.div []
      boilerplate
    ]

canvas : List (Svg msg) -> Html msg
canvas contents =
  H.div []
    [ S.svg
        [ SA.version "1.1"
        , SA.width "200"
        , SA.height "400"
        ]
        contents
    ]

form : List (Html msg) -> Html msg
form contents =
  H.div [] contents

boilerplate =
  [ H.p []
      [ H.text
          """
              This example is derived from an app used to teach
              students of veterinary medicine. They calculate the
              appropriate drip rate and time (based on information
              given to them by an instructor), then use the app to see
              if the ending fluid level is what they expected.
          """
      ]
  , H.p []
      [ H.text "Here are some interesting values to try: "
      , H.ul []
        [ H.li [] [H.text "Drip rate of 2 for 5 hours."]
        , H.li [] [H.text "Drip rate of 13 for 5 hours, 30 minutes."]
        , H.li [] [H.text "Drip rate of 5 for 16 hours."]
        ]
      ]
  ]


module Helper.Filesystem exposing (..)

import Game.Servers.Filesystem.Models exposing (..)

{-| addFileRecursively is a helper because on tests we often want to add a file
in a specific path which *we assume* already exists. On production, we do not assume
this, the path must exists. For a test, however, it's OK to assume. This helper
allow us to have this assumption when adding files. It's usually safe to use
addFileRecursively instead of addFile for tests, unless you want to test exactly
the assumption that the path the file is being added to must exist.
-}
addFileRecursively : Filesystem -> File -> Filesystem
addFileRecursively filesystem file =
    case file of
        Folder _ ->
            addFile filesystem file

        StdFile file_ ->
            let
                path =
                    (getFilePath file)

                -- TODO: this is not recursive, will break once we add nested folders
                folder =
                    Folder { id = "id", name = "name", path = path }

                filesystem_ =
                    addFile filesystem folder
            in
                addFile filesystem_ (StdFile file_)

Update addFileRecursively to work recursively.

module Helper.Filesystem exposing (addFileRecursively)

import Game.Servers.Filesystem.Models exposing (..)

addFolderReducer : String -> ( Filesystem, String ) -> ( Filesystem, String )
addFolderReducer folderName ( filesystem, path ) =
    let
        folder =
            Folder { id = "id", name = folderName, path = path }

        filesystem_ =
            addFile filesystem folder

        path_ =
            if path /= "/" then
                path ++ "/" ++ folderName
            else
                path ++ folderName
    in
        ( filesystem_, path_ )

addPathParents : String -> Filesystem -> Filesystem
addPathParents path filesystem =
    if pathExists filesystem path then
        filesystem
    else
        let
            ( filesystem_, _ ) =
                path
                    |> String.split "/"
                    |> List.filter ((/=) "")
                    |> List.foldl addFolderReducer ( filesystem, "" )
        in
            filesystem_

{-| addFileRecursively is a helper because on tests we often want to add a file
in a specific path which *we assume* already exists. On production, we do not assume
this, the path must exists. For a test, however, it's OK to assume. This helper
allow us to have this assumption when adding files. It's usually safe to use
addFileRecursively instead of addFile for tests, unless you want to test exactly
the assumption that the path the file is being added to must exist.
-}
addFileRecursively : Filesystem -> File -> Filesystem
addFileRecursively filesystem file =
    let
        path =
            getFilePath file

        -- TODO: change this to use pipes once we move filesystem to last
        -- param:
        --
        -- filesystem
        --     |> addPathParents file.path
        --     |> addFile file
        filesystemWithParents =
            addPathParents path filesystem

        filesystemWithFile =
            addFile filesystemWithParents file
    in
        filesystemWithFile


module ViewPhotos exposing (viewPhotos)
import Time.Date as Date exposing (Date, Weekday(..), day, month)
import Html exposing (..)
--import Html.Events exposing (onClick)
import Html.Attributes exposing (class, style, title, src)
import Types exposing (..)

import DateUtils exposing (..)
import Dict

viewPhotos : Model -> Html Msg
viewPhotos model =
    div
        [ class "photos" ]
        [ case model.dateShown of
            Nothing -> div [] [ text "Select a date on the calendar" ]
            Just date -> viewPhotosSection model date
        ]

viewPhotosSection : Model -> Date -> Html Msg
viewPhotosSection model date =
    let
        dateExifString =
            date |> dateToExifString

        datePhotos =
            Dict.get dateExifString model.photoMetadata
    in
        div
            [ class "photos" ]
            [ h1 [] [ date |> dateToString |> text ]
            , case datePhotos of
                Nothing -> div [] [ text "No photos for that date" ]
                Just photos -> div [] [ viewPictureList photos ]
            ]

viewPictureList : List String -> Html Msg
viewPictureList fileNames =
    ul
        []
        (List.map viewPicture fileNames)

viewPicture : String -> Html Msg
viewPicture filename =
    li
        []
        [ img [ src filename ] [] ]

Add number of pictures for a specific day

module ViewPhotos exposing (viewPhotos)
import Time.Date as Date exposing (Date, Weekday(..), day, month)
import Html exposing (..)
--import Html.Events exposing (onClick)
import Html.Attributes exposing (class, style, title, src)
import Types exposing (..)

import DateUtils exposing (..)
import Dict

viewPhotos : Model -> Html Msg
viewPhotos model =
    div
        [ class "photos" ]
        [ case model.dateShown of
            Nothing -> div [] [ text "Select a date on the calendar" ]
            Just date -> viewPhotosSection model date
        ]

viewPhotosSection : Model -> Date -> Html Msg
viewPhotosSection model date =
    let
        dateExifString =
            date |> dateToExifString

        datePhotos =
            Dict.get dateExifString model.photoMetadata
    in
        div
            [ class "photos" ]
            [ h1 [] [ date |> dateToString |> text ]
            , case datePhotos of
                Nothing -> div [] [ text "No photos for that date" ]
                Just photos -> div [] [ viewPictureList photos ]
            ]

viewPictureList : List String -> Html Msg
viewPictureList fileNames =
    div
        []
        [ h2 [] [ text ((List.length fileNames |> toString) ++ " photos") ]
        , ul
            []
            (List.map viewPicture fileNames)
        ]

viewPicture : String -> Html Msg
viewPicture filename =
    li
        []
        [ img [ src filename ] [] ]


-- Try this out on an iOS or Android device by removing "edit"
-- from the URL: http://elm-lang.org/examples/Reactive/Touches.elm

import Dict
import Touch
import Window

main = lift2 scene Window.dimensions
                   (Dict.values <~ foldp addN Dict.empty Touch.touches)

addN : [Touch.Touch] -> Dict.Dict Int [(Int,Int)] -> Dict.Dict Int [(Int,Int)]
addN ts dict = foldl add1 dict ts

add1 : Touch.Touch -> Dict.Dict Int [(Int,Int)] -> Dict.Dict Int [(Int,Int)]
add1 t d = let vs = Dict.findWithDefault [] t.id d
           in  Dict.insert t.id ((t.x,t.y) :: vs) d

scene : (Int,Int) -> [[(Int,Int)]] -> Element
scene (w,h) paths =
    let float (a,b) = (toFloat a, toFloat -b)
        pathForms = group (map (traced thickLine . path . map float) paths)
        picture = collage w h [ move (float (-w `div` 2, -h `div` 2)) pathForms ]
    in  layers [ picture, message ]

thickLine : LineStyle
thickLine = { defaultLine | color <- rgba 123 123 123 0.3, width <- 8 }

message = [markdown|

Try it fullscreen
if you are on iOS or Android.

|]

Remove incorrect and redundant comment


main = lift clock (every second)

clock t = collage 400 400 [ filled    lightGrey   (ngon 12 110)
                          , outlined (solid grey) (ngon 12 110)
                          , hand orange   100  t
                          , hand charcoal 100 (t/60)
                          , hand charcoal 60  (t/720) ]

hand clr len time =
  let angle = degrees (90 - 6 * inSeconds time)
  in  traced (solid clr) <| segment (0,0) (len * cos angle, len * sin angle)

Use fromPolar in clock example

main = lift clock (every second)

clock t = collage 400 400 [ filled    lightGrey   (ngon 12 110)
                          , outlined (solid grey) (ngon 12 110)
                          , hand orange   100  t
                          , hand charcoal 100 (t/60)
                          , hand charcoal 60  (t/720) ]

hand clr len time =
  let angle = degrees (90 - 6 * inSeconds time)
  in  segment (0,0) (fromPolar (len,angle)) |> traced (solid clr)


import Html exposing (div, button, text, input, label)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)
import StartApp as StartApp
import Effects exposing (Effects, Never)
import Maybe exposing (map)

app = StartApp.start { init = (model, Effects.none), view = view, update = update, inputs = [] }
main = app.html
type alias Set = { lift: String, reps: Int, weight: Float}
model: List Set
model = [{lift = "Squat", reps = 5, weight = 50}, {lift = "Bench", reps = 5, weight = 50}]
update a m = (m, a)

liftTemplate: Set -> List Html.Html
liftTemplate set =
  [ text set.lift,
    div [] [
      label [] [ text "Reps", input [value (toString set.reps)] [] ],
      label [] [ text "Weight", input [value (toString set.weight)] [] ]
    ]
  ]
view x model =
  div [] (List.concatMap liftTemplate model)

Insert new row with button

import Html exposing (div, button, text, input, label)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)
import StartApp as StartApp
import Effects exposing (Effects, Never)
import Maybe exposing (map)

app = StartApp.start { init = (emptyModel, Effects.none), view = view, update = update, inputs = [] }
main = app.html
type alias Set = { id: Int,  lift: String, reps: Int, weight: Float}

emptySet = { id = 0, lift = "", reps = 0, weight = 0 }
emptyModel = { lifts = [], newSet = emptySet }

type Action = Insert Set

update action model =
  case action of
    Insert set -> ({model | lifts = ([set] ++ model.lifts)}, Effects.none)

liftTemplate: Set -> List Html.Html
liftTemplate set =
  [
    div [] [
      label [] [ text "Lift: ", input [value set.lift ] [] ],
      label [] [ text "Reps: ", input [value (toString set.reps)] [] ],
      label [] [ text "Weight: ", input [value (toString set.weight)] [] ]
    ]
  ]
newSetTemplate address =
    button [onClick address (Insert emptySet)] [ text "+" ]

view address model =
  div [] ([newSetTemplate address] ++ (List.concatMap liftTemplate model.lifts))


module TickingPort where

import Signal
import Signal ((<~), Signal)

import Time

import Text
import Graphics.Element (Element)
main : Element
main = Text.asText "main"

port messageOut : Signal String
port messageOut = Signal.map toString (Time.every Time.second)

Update ticking port example to modern Elm

module TickingPort where

import Time
import Html exposing (text)

main = text "placeholder"

port messageOut : Signal String
port messageOut = Signal.map toString (Time.every Time.second)


main = lift clock (every second)

clock t = collage 400 400 [ filled    lightGrey   (ngon 12 110)
                          , outlined (solid grey) (ngon 12 110)
                          , hand orange   100  t
                          , hand charcoal 100 (t/60)
                          , hand charcoal 60  (t/720) ]

hand clr len time =
  let angle = degrees (90 - 6 * inSeconds time)
  in  traced (solid clr) <| segment (0,0) (len * cos angle, len * sin angle)

Make the clock a circle and extract constants

main = lift clock (every second)

radius = 100
shortHandLength = radius * 0.6
longHandLength = radius * 0.9

clock t = collage 400 400 [ filled lightGrey (circle radius)
                          , outlined (solid grey) (circle radius)
                          , hand orange longHandLength t
                          , hand charcoal longHandLength (t/60)
                          , hand charcoal shortHandLength (t/720) ]

hand clr len time =
  let angle = degrees (90 - 6 * inSeconds time)
  in traced (solid clr) <| segment (0,0) (len * cos angle, len * sin angle)


module Simulator.Command where

type Move = E | W | SE | SW

type Rotation = CW | CCW

type Command = Move Move | Rotate Rotation

type alias CommandCode = Char

decode : CommandCode -> Maybe Command
decode code =
  let
    mapping =
      [ (['p', '\'', '!', '.', '0', '3'], Move W)
      , (['b', 'c', 'e', 'f', 'y', '2'],  Move E)
      , (['a', 'g', 'h', 'i', 'j', '4'],  Move SW)
      , (['l', 'm', 'n', 'o', ' ', '5'],  Move SE)
      , (['d', 'q', 'r', 'v', 'z', '1'],  Rotate CW)
      , (['k', 's', 't', 'u', 'w', 'x'],  Rotate CCW)
      ]

    first : (a -> Bool) -> List a -> Maybe a
    first predicate =
      List.head << List.filter predicate

    maybeMappingRow =
      first (\(chars, command) -> List.member code chars) mapping

    maybeCommand =
      Maybe.map snd maybeMappingRow
 in
    maybeCommand

decodeList : List CommandCode -> Maybe (List Command)
decodeList codes =
  sequence (List.map decode codes)

sequence : List (Maybe a) -> Maybe (List a)
sequence list =
  let
    step maybe results =
      case results of
        Just results ->
          case maybe of
            Just value -> Just (value :: results)
            Nothing -> Nothing

        Nothing ->
          Nothing
  in
    List.foldl step (Just []) list

Fix sequence function which incorrectly reversed the input

module Simulator.Command where

type Move = E | W | SE | SW

type Rotation = CW | CCW

type Command = Move Move | Rotate Rotation

type alias CommandCode = Char

decode : CommandCode -> Maybe Command
decode code =
  let
    mapping =
      [ (['p', '\'', '!', '.', '0', '3'], Move W)
      , (['b', 'c', 'e', 'f', 'y', '2'],  Move E)
      , (['a', 'g', 'h', 'i', 'j', '4'],  Move SW)
      , (['l', 'm', 'n', 'o', ' ', '5'],  Move SE)
      , (['d', 'q', 'r', 'v', 'z', '1'],  Rotate CW)
      , (['k', 's', 't', 'u', 'w', 'x'],  Rotate CCW)
      ]

    first : (a -> Bool) -> List a -> Maybe a
    first predicate =
      List.head << List.filter predicate

    maybeMappingRow =
      first (\(chars, command) -> List.member code chars) mapping

    maybeCommand =
      Maybe.map snd maybeMappingRow
 in
    maybeCommand

decodeList : List CommandCode -> Maybe (List Command)
decodeList codes =
  sequence (List.map decode codes)

sequence : List (Maybe a) -> Maybe (List a)
sequence list =
  let
    step maybe results =
      case results of
        Just results ->
          case maybe of
            Just value -> Just (value :: results)
            Nothing -> Nothing

        Nothing ->
          Nothing
  in
    List.foldr step (Just []) list


module Tests exposing (tests)

import Expect
import ScrabbleScore exposing (scoreWord)
import Test exposing (..)

tests : Test
tests =
    describe "Grains"
        [ test "lowercase letter" <|
            \() -> Expect.equal 1 (scoreWord "a")
        , skip <|
            test "uppercase letter" <|
                \() -> Expect.equal 1 (scoreWord "A")
        , skip <|
            test "valuable letter" <|
                \() -> Expect.equal 4 (scoreWord "f")
        , skip <|
            test "short word" <|
                \() -> Expect.equal 2 (scoreWord "at")
        , skip <|
            test "short, valuable word" <|
                \() -> Expect.equal 12 (scoreWord "zoo")
        , skip <|
            test "medium word" <|
                \() -> Expect.equal 6 (scoreWord "street")
        , skip <|
            test "medium, valuable word" <|
                \() -> Expect.equal 22 (scoreWord "quirky")
        , skip <|
            test "long, mixed-case word" <|
                \() -> Expect.equal 41 (scoreWord "OxyphenButazone")
        , skip <|
            test "english-like word" <|
                \() -> Expect.equal 8 (scoreWord "pinata")
        , skip <|
            test "non-english letter is not scored" <|
                \() -> Expect.equal 7 (scoreWord "piñata")
        , skip <|
            test "empty input" <|
                \() -> Expect.equal 0 (scoreWord "")
        ]

Fix Test description for ScrabbleScore

module Tests exposing (tests)

import Expect
import ScrabbleScore exposing (scoreWord)
import Test exposing (..)

tests : Test
tests =
    describe "ScrabbleScore"
        [ test "lowercase letter" <|
            \() -> Expect.equal 1 (scoreWord "a")
        , skip <|
            test "uppercase letter" <|
                \() -> Expect.equal 1 (scoreWord "A")
        , skip <|
            test "valuable letter" <|
                \() -> Expect.equal 4 (scoreWord "f")
        , skip <|
            test "short word" <|
                \() -> Expect.equal 2 (scoreWord "at")
        , skip <|
            test "short, valuable word" <|
                \() -> Expect.equal 12 (scoreWord "zoo")
        , skip <|
            test "medium word" <|
                \() -> Expect.equal 6 (scoreWord "street")
        , skip <|
            test "medium, valuable word" <|
                \() -> Expect.equal 22 (scoreWord "quirky")
        , skip <|
            test "long, mixed-case word" <|
                \() -> Expect.equal 41 (scoreWord "OxyphenButazone")
        , skip <|
            test "english-like word" <|
                \() -> Expect.equal 8 (scoreWord "pinata")
        , skip <|
            test "non-english letter is not scored" <|
                \() -> Expect.equal 7 (scoreWord "piñata")
        , skip <|
            test "empty input" <|
                \() -> Expect.equal 0 (scoreWord "")
        ]


module View exposing (view)

import Html exposing (..)

import Model exposing (Model)
import Msg exposing (Msg)

import Page.Country
import Page.Dish
import Page.Home

import Route exposing (Route (..))

-- VIEW --
view : Model -> Html Msg
view model =
  div [] [ page model ]

-- PAGE --
page : Model -> Html Msg
page model =
  case model.currentLocation of
    Just route ->
      case route of
        Route.Home ->
          Page.Home.view model
        Route.Country id ->
          let
            country =
              List.head
                (List.filter
                  (\c -> c.id == id)
                  model.countries
                )

            dishes = model.countryDishes
          in
            case country of
              Just country ->
                Page.Country.view country dishes
              Nothing ->
                div [] [ text "404 - Not Found" ]
        Route.Dish id ->
          let
            country =
              List.head
                (List.filter
                  (\c -> c.id == String.left 2 id)
                  model.countries
                )
            dish = model.currentDish
          in
            case country of
              Just country ->
                case dish of
                  Just dish ->
                    Page.Dish.view country dish
                  Nothing ->
                    div [] [ text "404 - Not Found" ]
              Nothing ->
                div [] [ text "404 - Not Found" ]
    Nothing ->
      Page.Home.view model

Remove 404 text when retrieving data for view

module View exposing (view)

import Html exposing (..)

import Model exposing (Model)
import Msg exposing (Msg)

import Page.Country
import Page.Dish
import Page.Home

import Route exposing (Route (..))

-- VIEW --
view : Model -> Html Msg
view model =
  div [] [ page model ]

-- PAGE --
page : Model -> Html Msg
page model =
  case model.currentLocation of
    Just route ->
      case route of
        Route.Home ->
          Page.Home.view model
        Route.Country id ->
          let
            country =
              List.head
                (List.filter
                  (\c -> c.id == id)
                  model.countries
                )

            dishes = model.countryDishes
          in
            case country of
              Just country ->
                Page.Country.view country dishes
              Nothing ->
                div [] [ text "" ]
        Route.Dish id ->
          let
            country =
              List.head
                (List.filter
                  (\c -> c.id == String.left 2 id)
                  model.countries
                )
            dish = model.currentDish
          in
            case country of
              Just country ->
                case dish of
                  Just dish ->
                    Page.Dish.view country dish
                  Nothing ->
                    div [] [ text "" ]
              Nothing ->
                div [] [ text "" ]
    Nothing ->
      Page.Home.view model


import Monitor
import Signal
import Text

main = Signal.map Text.asText (Signal.foldp (+) 0 Monitor.refresh)

Update example to use both `refresh` and `refreshWhen`.

import Monitor
import Signal
import Text
import Mouse
import Graphics.Element (flow, down)

display counter1 counter2 = flow down
    [ Text.asText counter1
    , Text.asText counter2
    ]

main = Signal.map2 display
    (Signal.foldp (+) 0 Monitor.refresh)
    (Signal.foldp (+) 0 (Monitor.refreshWhen Mouse.isDown))


module Main where

import Html exposing (text)
import Http
import Task exposing (Task, andThen)

results : Signal.Mailbox String
results = Signal.mailbox ""

port tasks : Task Http.Error ()
port tasks =
    Http.getString "/api/" `andThen` Signal.send results.address

main =
    Signal.map text results.signal

type alias Ingredient =
    { name : String
    , value : Int
    , weight : Float
    , effects : List String
    }

type alias Response =
    { ingredients : List Ingredient
    }

Add Decoder definition for the response.

module Main where

import Html exposing (text)
import Http
import Json.Decode exposing ((:=), Decoder, string, int, float, list, object1, object4)
import Task exposing (Task, andThen)

results : Signal.Mailbox String
results = Signal.mailbox ""

port tasks : Task Http.Error ()
port tasks =
    Http.getString "/api/" `andThen` Signal.send results.address

main =
    Signal.map text results.signal

type alias Ingredient =
    { name : String
    , value : Int
    , weight : Float
    , effects : List String
    }

type alias Response =
    { ingredients : List Ingredient
    }

ingredient : Decoder Ingredient
ingredient =
    object4 Ingredient
        ("name" := string)
        ("value" := int)
        ("weight" := float)
        ("effects" := list string)

response : Decoder Response
response =
    object1 Response ("ingredients" := list ingredient)


module Main where

import StartApp
import StartApp.Simple as Simple
import Task
import Html exposing (Html)

-- Example 1. Counter
-- import Counter exposing (model, update, view)

-- Example 2. Form Validation
import FormValidator exposing (model, update, view)

-- Example 3. Form Validation and Http request
-- import GithubPhotoFetcher exposing (init, update, view)

import Effects exposing (Never)

-- For Example 1 & 2
main: Signal Html
main =
    Simple.start
        { model = model
        , update = update
        , view = view
        }

-- For Example 3
-- app =
--     StartApp.start
--         { init = init
--         , update = update
--         , view = view
--         , inputs = []
--         }
--
-- main: Signal Html
-- main =
--     app.html
--
--
-- port tasks: Signal (Task.Task Never ())
-- port tasks =
--     app.tasks

Use github photo fetcher as index

module Main where

import StartApp
import StartApp.Simple as Simple
import Task
import Html exposing (Html)

-- Example 1. Counter
-- import Counter exposing (model, update, view)

-- Example 2. Form Validation
-- import FormValidator exposing (model, update, view)

-- Example 3. Form Validation and Http request
import GithubPhotoFetcher exposing (init, update, view)

import Effects exposing (Never)

-- For Example 1 & 2
-- main: Signal Html
-- main =
--     Simple.start
--         { model = model
--         , update = update
--         , view = view
--         }

-- For Example 3
app =
    StartApp.start
        { init = init
        , update = update
        , view = view
        , inputs = []
        }

main: Signal Html
main =
    app.html

port tasks: Signal (Task.Task Never ())
port tasks =
    app.tasks


module Maybe where

{-| Represents an optional value.

# Type and Constructors
@docs Maybe

# Taking Maybes apart
@docs maybe, isJust, isNothing

# Maybes and Lists
@docs cons, justs
-}

import Basics (not, (.))
import List (foldr)

{-| The Maybe datatype. Useful when a computation may or may not
    result in a value (e.g. logarithm is defined only for positive
    numbers).
-}
data Maybe a = Just a | Nothing

{-| Apply a function to the contents of a `Maybe`.
    Return default when given `Nothing`.
-}
maybe : b -> (a -> b) -> Maybe a -> b
maybe b f m = case m of
                Just v  -> f v
                Nothing -> b

{-| Check if constructed with `Just`.
-}
isJust : Maybe a -> Bool
isJust = maybe False (\_ -> True)

{-| Check if constructed with `Nothing`.
-}
isNothing : Maybe a -> Bool
isNothing = not . isJust

{-| If `Just`, adds the value to the front of the list.
    If `Nothing`, list is unchanged.
-}
cons : Maybe a -> [a] -> [a]
cons mx xs = maybe xs (\x -> x :: xs) mx

{-| Filters out Nothings and extracts the remaining values.
-}
justs : [Maybe a] -> [a]
justs = foldr cons []

Add a bit more to intro of documentation

module Maybe where

{-| Represents an optional value. Maybe it is there, maybe it is not.

# Type and Constructors
@docs Maybe

# Taking Maybes apart
@docs maybe, isJust, isNothing

# Maybes and Lists
@docs cons, justs
-}

import Basics (not, (.))
import List (foldr)

{-| The Maybe datatype. Useful when a computation may or may not
    result in a value (e.g. logarithm is defined only for positive
    numbers).
-}
data Maybe a = Just a | Nothing

{-| Apply a function to the contents of a `Maybe`.
    Return default when given `Nothing`.
-}
maybe : b -> (a -> b) -> Maybe a -> b
maybe b f m = case m of
                Just v  -> f v
                Nothing -> b

{-| Check if constructed with `Just`.
-}
isJust : Maybe a -> Bool
isJust = maybe False (\_ -> True)

{-| Check if constructed with `Nothing`.
-}
isNothing : Maybe a -> Bool
isNothing = not . isJust

{-| If `Just`, adds the value to the front of the list.
    If `Nothing`, list is unchanged.
-}
cons : Maybe a -> [a] -> [a]
cons mx xs = maybe xs (\x -> x :: xs) mx

{-| Filters out Nothings and extracts the remaining values.
-}
justs : [Maybe a] -> [a]
justs = foldr cons []


module Main exposing (..)

import Html exposing (text)

main =
    text "Hi Records!"

Store records, and refer to with type signatures

module Main exposing (..)

import Html exposing (text)

type alias Dog =
    { name: String
    , age: Int
    }

dog =
    { name = "Spock"
    , age = 3
    }

renderDog : Dog -> String
renderDog dog =
    dog.name
        ++ " - "
        ++ (toString dog.age)

main =
    text <| renderDog dog


module Decoders exposing (..)

import Grid
import Json.Decode as Decode exposing (Decoder)
import Types exposing (..)

localStorageModelDecoder : Decoder LocalStorageModel
localStorageModelDecoder =
    Decode.map3 LocalStorageModel
        (Decode.field "givenUp" Decode.bool)
        (Decode.field "grid" gridDecoder)
        (Decode.field "selectedCell" selectedCellDecoder)

gridDecoder : Decoder Grid
gridDecoder =
    Decode.map gridMapper (Decode.list rowDecoder)

gridMapper : List (List Cell) -> Grid
gridMapper listOfLists =
    Grid.fromList listOfLists
        |> Maybe.withDefault (Grid.defaultGrid Grid.minWidth Grid.maxWidth)

rowDecoder : Decoder (List Cell)
rowDecoder =
    Decode.list cellDecoder

cellDecoder : Decoder Cell
cellDecoder =
    Decode.map2 Cell
        (Decode.index 0 (Decode.map parseCellState Decode.string))
        (Decode.index 1 (Decode.map parseCellInner Decode.string))

parseCellState : String -> CellState
parseCellState string =
    case string of
        "Revealed" ->
            Revealed

        "Flagged" ->
            Flagged

        _ ->
            Unrevealed

parseCellInner : String -> CellInner
parseCellInner string =
    case string of
        "Mine" ->
            Mine

        _ ->
            Hint

selectedCellDecoder : Decoder (Maybe ( Int, Int ))
selectedCellDecoder =
    Decode.map2 (,)
        (Decode.index 0 Decode.int)
        (Decode.index 1 Decode.int)
        |> Decode.nullable

Fix decoder fallback grid size

module Decoders exposing (..)

import Grid
import Json.Decode as Decode exposing (Decoder)
import Types exposing (..)

localStorageModelDecoder : Decoder LocalStorageModel
localStorageModelDecoder =
    Decode.map3 LocalStorageModel
        (Decode.field "givenUp" Decode.bool)
        (Decode.field "grid" gridDecoder)
        (Decode.field "selectedCell" selectedCellDecoder)

gridDecoder : Decoder Grid
gridDecoder =
    Decode.map gridMapper (Decode.list rowDecoder)

gridMapper : List (List Cell) -> Grid
gridMapper listOfLists =
    Grid.fromList listOfLists
        |> Maybe.withDefault (Grid.defaultGrid Grid.minWidth Grid.minHeight)

rowDecoder : Decoder (List Cell)
rowDecoder =
    Decode.list cellDecoder

cellDecoder : Decoder Cell
cellDecoder =
    Decode.map2 Cell
        (Decode.index 0 (Decode.map parseCellState Decode.string))
        (Decode.index 1 (Decode.map parseCellInner Decode.string))

parseCellState : String -> CellState
parseCellState string =
    case string of
        "Revealed" ->
            Revealed

        "Flagged" ->
            Flagged

        _ ->
            Unrevealed

parseCellInner : String -> CellInner
parseCellInner string =
    case string of
        "Mine" ->
            Mine

        _ ->
            Hint

selectedCellDecoder : Decoder (Maybe ( Int, Int ))
selectedCellDecoder =
    Decode.map2 (,)
        (Decode.index 0 Decode.int)
        (Decode.index 1 Decode.int)
        |> Decode.nullable


module Main exposing (..)

import Browser
import Html exposing (Html, text)
import Material
import Material.Button as Button
import Material.Options as Options

type alias Model =
    { mdc : Material.Model Msg
    }

defaultModel : Model
defaultModel =
    { mdc = Material.defaultModel
    }

type Msg
    = Mdc (Material.Msg Msg)
    | Click

main : Program () Model Msg
main =
    Browser.element
        { init = \_ -> init
        , subscriptions = subscriptions
        , update = update
        , view = view
        }

init : ( Model, Cmd Msg )
init =
    ( defaultModel, Material.init Mdc )

subscriptions : Model -> Sub Msg
subscriptions model =
    Material.subscriptions Mdc model

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Mdc msg_ ->
            Material.update Mdc msg_ model

        Click ->
            ( model, Cmd.none )

view : Model -> Html Msg
view model =
    Html.div []
        [ Button.view Mdc
            "my-button"
            model.mdc
            [ Button.ripple
            , Options.onClick Click
            ]
            [ text "Click me!" ]
        ]

Make hello world button look better

module Main exposing (..)

import Browser
import Html exposing (Html, text)
import Material
import Material.Button as Button
import Material.Options as Options

type alias Model =
    { mdc : Material.Model Msg
    }

defaultModel : Model
defaultModel =
    { mdc = Material.defaultModel
    }

type Msg
    = Mdc (Material.Msg Msg)
    | Click

main : Program () Model Msg
main =
    Browser.element
        { init = \_ -> init
        , subscriptions = subscriptions
        , update = update
        , view = view
        }

init : ( Model, Cmd Msg )
init =
    ( defaultModel, Material.init Mdc )

subscriptions : Model -> Sub Msg
subscriptions model =
    Material.subscriptions Mdc model

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Mdc msg_ ->
            Material.update Mdc msg_ model

        Click ->
            ( model, Cmd.none )

view : Model -> Html Msg
view model =
    Html.div []
        [ Button.view Mdc
            "my-button"
            model.mdc
            [ Button.ripple
            , Button.raised
            , Options.onClick Click
            ]
            [ text "Click me!" ]
        ]


module AllSyntax where

import String
import Signal exposing (foldp, map)
import Json.Decode as Json
import List exposing (..)

fn =
    "XYZZY"

annotatedFn : String
annotatedFn =
    "XYZZY"

inlinePipeline =
    1 |> (+) 2

tuple =
    (1, 2)

commentedLiterals =
    ({- int -} 1, {- float -} 0.1, {- char -} 'c', {- string -} "str", {- boolean -} True)

Add test for infix operators

module AllSyntax where

import String
import Signal exposing (foldp, map)
import Json.Decode as Json
import List exposing (..)

fn =
    "XYZZY"

annotatedFn : String
annotatedFn =
    "XYZZY"

inlinePipeline =
    1 |> (+) 2

tuple =
    (1, 2)

commentedLiterals =
    ({- int -} 1, {- float -} 0.1, {- char -} 'c', {- string -} "str", {- boolean -} True)

infixOperator =
    1 + 2 * 3 / 4 // 5 |> (+) 0


module ArmstrongNumbers exposing (check)

check : Int -> Bool
check nb =
    let
        ( digits, nbDigits ) =
            digitsAndLength nb
    in
    nb
        == List.foldl (+)
            0
            (List.map (\a -> a ^ nbDigits) digits)

digitsAndLength : Int -> ( List Int, Int )
digitsAndLength nb =
    if nb < 10 then
        ( [ nb ], 1 )

    else
        let
            ( digits, n ) =
                digitsAndLength (nb // 10)
        in
        ( modBy 10 nb :: digits, 1 + n )

Replace List.foldl (+) 0 by List.sum

module ArmstrongNumbers exposing (check)

check : Int -> Bool
check nb =
    let
        ( digits, nbDigits ) =
            digitsAndLength nb
    in
    nb == List.sum (List.map (\a -> a ^ nbDigits) digits)

digitsAndLength : Int -> ( List Int, Int )
digitsAndLength nb =
    if nb < 10 then
        ( [ nb ], 1 )

    else
        let
            ( digits, n ) =
                digitsAndLength (nb // 10)
        in
        ( modBy 10 nb :: digits, 1 + n )


{-| A port module -}
port module PortModuleA exposing (portA)

{-| @docs portA -}

{-| some port A -}
port portA : Cmd ()

Revert messing with rogue comments in test fixture


module BoardHelpers exposing (..)

import Models exposing (..)

getBoardByStorageKey : List TrelloBoard -> String -> Maybe TrelloBoard
getBoardByStorageKey boards key =
    case getBoardIdByStorageKey key of
        Just id ->
            getBoardById boards id

        Nothing ->
            Nothing

getBoardIdByStorageKey : String -> Maybe String
getBoardIdByStorageKey key =
    case getBoardIdList key of
        Just s ->
            List.head s

        Nothing ->
            Nothing

getBoardIdList : String -> Maybe (List String)
getBoardIdList key =
    key
        |> String.split "-"
        |> List.tail

getBoardById : List TrelloBoard -> String -> Maybe TrelloBoard
getBoardById boards id =
    List.head (List.filter (\b -> b.id == id) boards)

Use Maybe.andThen instead of case

module BoardHelpers exposing (..)

import Models exposing (..)

getBoardByStorageKey : List TrelloBoard -> String -> Maybe TrelloBoard
getBoardByStorageKey boards key =
    key
        |> getBoardIdByStorageKey
        |> Maybe.andThen (getBoardById boards)

getBoardIdByStorageKey : String -> Maybe String
getBoardIdByStorageKey key =
    key |> getBoardIdList |> Maybe.andThen List.head

getBoardIdList : String -> Maybe (List String)
getBoardIdList key =
    key
        |> String.split "-"
        |> List.tail

getBoardById : List TrelloBoard -> String -> Maybe TrelloBoard
getBoardById boards id =
    List.head (List.filter (\b -> b.id == id) boards)


module NewtonsMethodTest exposing (..)

import Expect exposing (Expectation)
import Test exposing (Test, describe, test)

breakEvenPoint : (Float -> Float) -> Maybe Float
breakEvenPoint func =
    let
        y0 =
            func 0

        rise =
            func 1 - y0
    in
        case rise of
            0 ->
                Nothing

            _ ->
                negate y0 / rise |> Just

suite =
    describe "breakEvenPoint"
        [ test "identity has breakEvenPoint zero" <|
            \() ->
                breakEvenPoint identity
                    |> Expect.equal (Just 0)
        , test "x+2" <|
            \() ->
                breakEvenPoint (\x -> x + 2)
                    |> Expect.equal (Just -2)
        , test "constant 42" <|
            \() ->
                breakEvenPoint (\x -> 42)
                    |> Expect.equal Nothing
        , test "2x" <|
            \() ->
                breakEvenPoint (\x -> 2 * x)
                    |> Expect.equal (Just 0)
        , test "2x-2" <|
            \() ->
                breakEvenPoint (\x -> 2 * x - 2)
                    |> Expect.equal (Just 1)
        ]

Introduce checkMaybe to be able to use closeTo

module NewtonsMethodTest exposing (..)

import Expect exposing (Expectation)
import Test exposing (Test, describe, test)
import TestSupport exposing (checkMaybe, closeTo)

breakEvenPoint : (Float -> Float) -> Maybe Float
breakEvenPoint func =
    let
        y0 =
            func 0

        rise =
            func 1 - y0
    in
        case rise of
            0 ->
                Nothing

            _ ->
                negate y0 / rise |> Just

suite =
    describe "breakEvenPoint"
        [ test "identity has breakEvenPoint zero" <|
            \() ->
                breakEvenPoint identity
                    |> Expect.equal (Just 0)
        , test "x+2" <|
            \() ->
                breakEvenPoint (\x -> x + 2)
                    |> Expect.equal (Just -2)
        , test "constant 42" <|
            \() ->
                breakEvenPoint (\x -> 42)
                    |> Expect.equal Nothing
        , test "2x" <|
            \() ->
                breakEvenPoint (\x -> 2 * x)
                    |> Expect.equal (Just 0)
        , test "2x-2" <|
            \() ->
                breakEvenPoint (\x -> 2 * x - 2)
                    |> Expect.equal (Just 1)
        , test "-2x-2" <|
            \() ->
                breakEvenPoint (\x -> -2 * x - 2)
                    |> Expect.equal (Just -1)
        , test "-2x+4" <|
            \() ->
                breakEvenPoint (\x -> -2 * x + 4)
                    |> checkMaybe (Expect.equal 2)
        , test "3.14x+4" <|
            \() ->
                breakEvenPoint (\x -> 3.14 * x + 4)
                    |> checkMaybe (closeTo -1.274 3)
        ]


module MyList
    (
    )
    where

getAt : List a -> Int -> Maybe a
getAt list index =
    List.head <| List.drop index list

removeAt : List a -> Int -> Maybe a
removeAt list index =
    if index < length list then
        Maybe.Just <| (take index list) ++ (drop (index + 1) list)
    else
        Nothing

{-
move : List a -> Int -> Int -> Maybe (List a)
move list from to =
    -}


Add dedicated module to bootstrap helpers

module Bootstrap exposing (..)

import Html exposing (div, nav, a, img, Html, Attribute)
import Html.Attributes exposing (class, alt, src)

row : List (Html msg) -> Html msg
row elements =
    div [ class "row" ] elements

navbar : List (Attribute msg) -> List (Html msg) -> Html msg
navbar attributes elements =
    nav (List.append [ class "navbar navbar-default navbar-fixed-top" ] attributes)
        [ div [ class "container" ]
            [ div [ class "navbar-header" ] elements
            ]
        ]

navbarBrand : List (Attribute msg) -> List (Html msg) -> Html msg
navbarBrand attributes elements =
    a (List.append [ class "navbar-brand" ] attributes) elements


module Page.PackageDocs where

import Basics (..)
import Color
import ColorScheme as C
import Dict
import Json
import Graphics.Element (..)
import Http
import List
import List ((++))
import Maybe (..)
import Result
import Signal
import String
import Window

import Component.TopBar as TopBar
import Component.PackageDocs as Docs

port context : { user : String, name : String, version : String }

port title : String
port title =
    context.user ++ "/" ++ context.name ++ " - " ++ context.version

descriptionUrl : String
descriptionUrl =
  "/description?name=" ++ context.user ++ "/" ++ context.name ++ "&version=" ++ context.version

description : Signal.Signal Docs.PackageInfo
description =
    Http.sendGet (Signal.constant descriptionUrl)
      |> Signal.map handleResult

packageInfo : [String] -> Docs.PackageInfo
packageInfo modules =
  Docs.PackageInfo context.user context.name context.version modules

handleResult : Http.Response String -> Docs.PackageInfo
handleResult response =
  case response of
    Http.Success string ->
      case Json.fromString string of
        Result.Ok (Json.Object dict) ->
          case Dict.get "exposed-modules" dict of
            Just (Json.Array modules) ->
                packageInfo (List.map (\(Json.String s) -> s) modules)
            _ -> packageInfo []

        _ -> packageInfo []

    _ -> packageInfo []

readme : Signal.Signal (Maybe String)
readme =
    Signal.constant Nothing

main : Signal.Signal Element
main =
    Signal.map3 view Window.dimensions description readme

search : Signal.Channel TopBar.Update
search =
    Signal.channel TopBar.NoOp

view : (Int,Int) -> Docs.PackageInfo -> Maybe String -> Element
view (windowWidth, windowHeight) packages readme =
  color C.background <|
  flow down
  [ TopBar.view windowWidth search (TopBar.Model TopBar.Global "map" TopBar.Normal)
  , flow right
    [ spacer ((windowWidth - 980) // 2) (windowHeight - TopBar.topBarHeight)
    , Docs.view 980 packages readme
    ]
  ]


module AesCbc
    ( CryptoKey, encrypt, decrypt
    , generateKey, importKey, exportKey
    , wrapKey, unwrapKey
    ) where

{-| This module wraps the AES-CBC mode of encryption in the web crypto API

@docs CryptoKey

@docs encrypt, decrypt

@docs KeySize

@docs generateKey, importKey, exportKey

@docs wrapKey, unwrapKey

-}

import Native.Crypto

import Crypto

{-| An opaque type representing an AES symmetric secret key
-}
type CryptoKey = CryptoKey

{-| A type containing the possible sizes for AES keys
-}
type KeySize = Aes128 | Aes192 | Aes256

sizeToInt : KeySize -> Int
sizeToInt Aes128 = 128
sizeToInt Aes192 = 192
sizeToInt Aes256 = 256

cipherName = "AES-CBC"

{-| Encrypt some data using AES-CBC.

Encrypt a plaintext buffer `plain` using the initialization vector `iv` and
the key `key`. Make sure to use a different initialization vector for each
message sent

    encrypt iv key plain
        -- Will evaluate to the ciphertext obtained by encrypting plain
        -- with AES using key

-}
encrypt : ArrayBuffer -> CryptoKey -> ArrayBuffer -> Task Crypto.Error ArrayBuffer
encrypt iv =
    Native.Crypto.encrypt
        { name = cipherName
        , iv = iv
        }

{-| Decrypt some data using AES-CBC

Decrypt a ciphertext buffer `cipher` using the initialization vector `iv` and
the key `key`. The initialization vector needs to be the same as
the one used for encryption.

    decrypt iv key cipher
        -- Will evaluate to the plaintext obtained by decrypting cipher with
        -- AES using key

-}
decrypt : ArrayBuffer -> CryptoKey -> ArrayBuffer -> Task Crypto.Error ArrayBuffer
decrypt iv =
    Native.Crypto.encrypt
        { name = cipherName
        , iv = iv
        }


-- Basic ElmFire Example App

import Html exposing (Html, div, input, output, label, text, a)
import Html.Events exposing (on, targetValue)
import Html.Attributes exposing (href, target)
import Signal exposing (Signal, Mailbox, mailbox, message)
import Task exposing (Task)
import Json.Encode exposing (string)

import ElmFire exposing (
    location, set, query, responses, Response (..), QueryId, Error
  )

loc = "https://elmfire.firebaseio-demo.com/test"

inputString : Mailbox String
inputString = mailbox ""

port runSet : Signal (Task Error ())
port runSet = Signal.map
  (\str -> set (string str) (location loc))
  inputString.signal

port runQuery : Task Error QueryId
port runQuery = query (location loc)

view : Response -> Html
view response =
  let outputText = case response of
    Data dataMsg ->
      Maybe.withDefault "no value" <| Maybe.map toString dataMsg.value
    otherwise -> "no query response"
  in
  div []
  [ text "ElmFire test at: "
  , a [href loc, target "_blank"] [text loc]
  , div []
    [ label []
      [ text "set value: "
      , input [ on "input" targetValue (message inputString.address) ] []
      ]
    ]
  , div []
    [ label []
      [ text "query result: "
      , output [] [ text outputText ]
      ]
    ]
  ]

main = Signal.map view responses


Create a test wrapper for the forest module

import Html.App as App
import Html exposing (Html)

import IdeaFight.PartialForest as Forest
import IdeaFight.Shuffle as Shuffle

import Random
import Time

type alias Model = Forest.Forest Int
type Msg = ShuffleMe (List Int) | Tick

stepForest : Forest.Forest comparable -> Forest.Forest comparable
stepForest forest =
  let (a, b) = Forest.getNextPair forest
  in Forest.choose forest <| max a b

init : (Model, Cmd Msg)
init = (Forest.empty, Random.generate ShuffleMe (Shuffle.shuffle [1..8]))

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    ShuffleMe values -> (Forest.fromList values, Cmd.none)
    Tick -> (stepForest model, Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions _ = Time.every (Time.second * 5) <| always Tick

view : Model -> Html Msg
view model = Forest.drawForest model

main : Program Never
main = App.program {
    init = init,
    update = update,
    subscriptions = subscriptions,
    view = view
  }


Add a simple test to show output of die rolls

module ListTest exposing (..)

{-| Rolls a die many times and collates the output. Judging whether the result is sufficiently random
is wholly unscientific; this test is really to show that independent seeds aren't *trivially* wrong.
-}

import Dict exposing (Dict)
import Random.Pcg as Random
import Html
import Html.App

seed0 : Random.Seed
seed0 =
    Random.initialSeed 628318530 |> Random.step Random.independentSeed |> snd

gen =
    -- smaller range is more likely to show problems
    Random.int 1 6
        |> Random.list 50
        |> Random.map toMultiSet

toMultiSet : List Int -> Dict Int Int
toMultiSet list =
    let
        helper xs d =
            case xs of
                [] ->
                    d

                x :: xs ->
                    helper xs <| Dict.insert x (Dict.get x d |> Maybe.withDefault 0 |> (+) 1) d
    in
        helper list Dict.empty

generated =
    Random.step gen seed0 |> fst

main : Program Never
main =
    Html.App.beginnerProgram
        { model = ()
        , update = \_ _ -> ()
        , view = \() -> Html.text <| toString <| generated
        }


-- incoming
port userID : String
port signal : Signal Int
port tuple : (Float,Bool)
port array : [Int]
port record : { x:Float, y:Float }

-- outgoing
port fortyTwo : Int
port fortyTwo = 42

port time : Signal Float
port time = every second

port students : Signal [{name:String, age:Int}]
port students = constant []


module GameSkeleton where

{-- Part 1: Model the user input ----------------------------------------------

What information do you need to represent all relevant user input?

Task: Redefine `UserInput` to include all of the information you need.
      Redifene `userInput` to be a signal that correctly models the user
      input as described by `UserInput`.

------------------------------------------------------------------------------}

data UserInput = UserInput

userInput = constant UserInput

data Input = Input Float UserInput

{-- Part 2: Model the game ----------------------------------------------------

What information do you need to represent the entire game?

Tasks: Redefine `GameState` to represent your particular game.
       Redefine `defaultGame` to represent your initial game state.

For example, if you want to represent many objects that just have a position,
your GameState might just be a list of coordinates and your default game might
be an empty list (no objects at the start):

    data GameState = GameState [(Float,Float)]
    defaultGame = GameState []

------------------------------------------------------------------------------}

data GameState = GameState

defaultGame = GameState

{-- Part 3: Update the game ---------------------------------------------------

How does the game step from one state to another based on user input?

Task: redefine `stepGame` to use the UserInput and GameState
      you defined in parts 1 and 2. Maybe use some helper functions
      to break up the work, stepping smaller parts of the game.

------------------------------------------------------------------------------}

stepGame (Input delta (UserInput)) (GameState) = GameState

{-- Part 4: Display the game --------------------------------------------------

How should the GameState be displayed to the user?

Task: redefine `display` to use the GameState you defined in part 2.

------------------------------------------------------------------------------}

display (w,h) gameState = asText gameState

{-- That's all folks! ---------------------------------------------------------

The following code puts it all together and show it on screen.

------------------------------------------------------------------------------}

delta = fps 60
input = sampleOn delta (lift2 Input delta userInput)

gameState = foldp stepGame defaultGame input

main = lift2 display Window.dimensions gameState


module Api where

import Http
import Json.Decode exposing ((:=))
import Json.Encode
import Task exposing (Task)

type alias Request
  = { amount: Int
    , num_years: Int
    , apr: Float
    }

type alias Response
  = { stats: Stats }

type alias Stats
  = { monthly_repayment: Float }

getStats : Request -> Task Http.Error Response
getStats request =
  let
    decodeStats =
      Json.Decode.object1 Stats ("monthly_repayment" := Json.Decode.float)
    decodeResponse =
      Json.Decode.object1 Response ("stats" := decodeStats)

    encodedRequest =
      Json.Encode.object
        [ ("amount", Json.Encode.int request.amount)
        , ("num_years", Json.Encode.int request.num_years)
        , ("apr", Json.Encode.float request.apr)
        ]

    body =
      Http.string (Json.Encode.encode 0 encodedRequest)
  in
    Http.post decodeResponse "/mortgages" body


Add utility module with common SVG styles

module FillsAndStrokes exposing (..)

import Svg
import Svg.Attributes as Attributes

whiteFill : Svg.Attribute msg
whiteFill =
    Attributes.fill "white"

greyFill : Svg.Attribute msg
greyFill =
    Attributes.fill "grey"

noFill : Svg.Attribute msg
noFill =
    Attributes.fill "none"

blackStroke : Svg.Attribute msg
blackStroke =
    Attributes.stroke "black"

greyStroke : Svg.Attribute msg
greyStroke =
    Attributes.stroke "grey"

dashed : Svg.Attribute msg
dashed =
    Attributes.strokeDasharray "5 5"


Add unionMap convenience method for mapping over Sets

module SetExtensions exposing (unionMap)

import Set exposing (Set)

unionMap : (comparable -> Set comparable) -> Set comparable -> Set comparable
unionMap mapping source =
        Set.foldl (reducer mapping) Set.empty source

reducer : (comparable -> Set comparable) -> comparable -> Set comparable -> Set comparable
reducer mapping current accumulatedSet =
    Set.union accumulatedSet <| mapping current


Add template for creating a container of things

module WidgetContainer
    ( WidgetContainer
    , Action
    , init
    , update
    , view
    )
    where

import Html exposing (..)

import Widget exposing (Widget)

type alias WidgetContainer =
    { widgets: List Widget
    }

type Action
    = DoNothing
    | WidgetAction (Widget.Action)

init : List Widget -> WidgetContainer
init widgets =
    { widgets = widgets }

update : Action -> WidgetContainer -> WidgetContainer
update action container =
    case action of
        WidgetAction action ->
            container

        DoNothing ->
            container

view : Signal.Address Action -> WidgetContainer -> Html
view address container =
    let
        forwardingAddress = Signal.forwardTo address WidgetAction
        widgetsHtmls = List.map (Widget.view forwardingAddress) container.widgets
    in
        div [] widgetsHtmls


Add module to get mouse and touch positions at once

module Position
  ( mouseTouch
  , Position
  ) where

import Mouse
import Signal exposing (Signal)
import Touch

type alias Position = Maybe (Int, Int)

mouseTouch : Signal Position
mouseTouch =
  let mouse = Signal.map Just Mouse.position
      touch =
        Signal.map (Maybe.map toPair << List.head) Touch.touches
  in
  Signal.merge mouse touch

toPair : Touch.Touch -> (Int, Int)
toPair t = (t.x, t.y)


module Test.Runner.Tests exposing (all)

import Expect
import Fuzz exposing (..)
import Test exposing (..)
import Test.Runner exposing (SeededRunners(..))
import Random.Pcg as Random

all : Test
all =
    Test.concat
        [ fromTest ]

-- fromTest : Int -> Random.Pcg.Seed -> Test -> SeededRunners
-- fromTest runs seed test =

toSeededRunners : Test -> SeededRunners
toSeededRunners =
    Test.Runner.fromTest 5 (Random.initialSeed 42)

fromTest : Test
fromTest =
    describe "TestRunner.fromTest"
        [ Test.skip <|
            describe "test length"
                [ fuzz2 int int "only positive tests runs are valid" <|
                    \runs intSeed ->
                        case Test.Runner.fromTest runs (Random.initialSeed intSeed) passing of
                            Invalid str ->
                                if runs > 0 then
                                    Expect.fail ("Expected a run count of " ++ toString runs ++ " to be valid, but was invalid with this message: " ++ toString str)
                                else
                                    Expect.pass

                            val ->
                                if runs > 0 then
                                    Expect.pass
                                else
                                    Expect.fail ("Expected a run count of " ++ toString runs ++ " to be invalid, but was valid with this value: " ++ toString val)
                , test "a test that uses only is an Only summary" <|
                    \() ->
                        case toSeededRunners (Test.only <| test "passes" (\() -> Expect.pass)) of
                            Only runners ->
                                runners
                                    |> List.length
                                    |> Expect.equal 1

                            val ->
                                Expect.fail ("Expected SeededRunner to be Only, but was " ++ toString val)
                , test "a test that uses skip is a Skipping summary" <|
                    \() ->
                        case toSeededRunners (Test.skip <| test "passes" (\() -> Expect.pass)) of
                            Skipping runners ->
                                runners
                                    |> List.length
                                    |> Expect.equal 1

                            val ->
                                Expect.fail ("Expected SeededRunner to be Skipping, but was " ++ toString val)
                , test "a test that does not use only or skip is a Plain summary" <|
                    \() ->
                        case toSeededRunners (test "passes" (\() -> Expect.pass)) of
                            Plain runners ->
                                runners
                                    |> List.length
                                    |> Expect.equal 1

                            val ->
                                Expect.fail ("Expected SeededRunner to be Plain, but was " ++ toString val)
                ]
        ]

passing : Test
passing =
    test "A passing test" (\() -> Expect.pass)

--
-- type SeededRunners
--     = Plain (List Runner)
--     | Only (List Runner)
--     | Skipping (List Runner)
--     | Invalid String
--
--
-- type alias Runner =
--     { run : () -> List Expectation
--     , labels : List String
--     }


Add back markdown example, point to package

import Markdown

main = Markdown.toElement """

# Welcome to Elm

This [markdown](http://daringfireball.net/projects/markdown/)
parser lives in the [elm-markdown][] package, allowing you to
generate `Element` and `Html` blocks.

[elm-markdown]: http://package.elm-lang.org/packages/evancz/elm-markdown/latest

"""