text:
package com.gistlabs.mechanize.document.html;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.gistlabs.mechanize.Mechanize;
import com.gistlabs.mechanize.document.AbstractDocument;
import com.gistlabs.mechanize.document.html.form.Forms;
import com.gistlabs.mechanize.document.html.image.Images;
import com.gistlabs.mechanize.document.link.Links;
import com.gistlabs.mechanize.document.node.Node;
import com.gistlabs.mechanize.exceptions.MechanizeExceptionFactory;
import com.gistlabs.mechanize.util.apache.ContentType;

/**
 * @author Martin Kersten <Martin.Kersten.mk@gmail.com>
 */
public class HtmlDocument extends AbstractDocument {
	public static Collection<String> CONTENT_MATCHERS = Arrays.asList(
					ContentType.TEXT_HTML.getMimeType(),
					ContentType.APPLICATION_ATOM_XML.getMimeType(),
					ContentType.APPLICATION_XHTML_XML.getMimeType(),
					ContentType.APPLICATION_XML.getMimeType());

	private HtmlElements htmlElements;

	private String baseUri;

	public HtmlDocument(final Mechanize agent, final HttpRequestBase request, final HttpResponse response) {
		super(agent, request, response);
	}

	@Override
	public HtmlElement getRoot() {
		return htmlElements().getRoot();
	}

	@Override
	public HtmlElement find(String csss) {
		return (HtmlElement)super.find(csss);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<? extends HtmlElement> findAll(String csss) {
		return (List<? extends HtmlElement>) super.findAll(csss);
	}

	@Override
	protected void loadPage() throws Exception {
		Document jsoup = Jsoup.parse(getInputStream(), getContentEncoding(response), getUri());
		setBaseUri(jsoup.head().baseUri());
		this.htmlElements = new HtmlElements(this, jsoup);
	}

	private void setBaseUri(final String baseUri) {
		if (! this.getUri().equals(baseUri))
			this.baseUri = baseUri;
	}

	@Override
	public String getUri() {
		return this.baseUri==null ? super.getUri() : this.baseUri;
	}

	@Override
	protected Links loadLinks() {
		List<? extends Node> links = htmlElements().findAll("a");
		return new Links(this, links);
	}

	@Override
	protected Forms loadForms() {
		List<? extends Node> forms = htmlElements().findAll("form");
		return new Forms(this, forms);
	}

	@Override
	protected Images loadImages() {
		List<HtmlElement> images = htmlElements().findAll("img");
		return new Images(this, images);
	}

	public HtmlElements htmlElements() {
		if(htmlElements == null)
			try {
				loadPage();
			} catch (Exception e) {
				throw MechanizeExceptionFactory.newException(e);
			}
		return htmlElements;
	}

	/**
	 * Returns the title of the page or null.
	 */
	@Override
	public String getTitle() {
		HtmlElement title = htmlElements().find("title");
		return title != null ? title.getText() : null;
	}

	/**
	 * Serialize the contents of this page into a string
	 *
	 * @return
	 */
	@Override
	public String asString() {
		return htmlElements.toString();
	}

}


text:
from django.urls import include, path
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('advanced_filters/', include('advanced_filters.urls'))
]

redpajama_set_name: RedPajamaGithub


text:
local PANEL = {}

function PANEL:Init()

	self:PerformLayout()

	self.Wait = CurTime() + 5
	self.Pos = 1
	self.YPos = 220
	self.ListMode = true
	self.DrawTbl = {}
	self.Awards = {}

	self.Lists = {}
	self.Lists[1] = { 5, ScrW() * 0.30, "Survivors", function() return self:GetSurvivors() end, "bot/whoo2.wav" }
	self.Lists[2] = { ScrW() * 0.50 - ScrW() * 0.15, ScrW() * 0.30, "Top  Killers", function() return self:GetTopKillers() end, "weapons/357_fire2.wav" }
	self.Lists[3] = { ScrW() - ( ScrW() * 0.30 ) - 5, ScrW() * 0.30, "Big  Spenders", function() return self:GetTopSpenders() end, "physics/metal/chain_impact_soft1.wav" }

	local x, w = ScrW() * 0.50 - ScrW() * 0.15, ScrW() * 0.65 - 5

	self:ListNewAward( { x, w, "Grey Matter:", "got the most headshots.", function() return self:GetStatMax( "Headshot" ) end, "zombie craniums", "player/headshot1.wav" } )
	self:ListNewAward( { x, w, "Silent Partner:", "got the most kill assists.", function() return self:GetStatMax( "Assist" ) end, "assists", "weapons/357/357_spin1.wav" } )
	self:ListNewAward( { x, w, "Longshot:", "got the longest distance kill.", function() return self:GetStatMax( "Longshot" ) end, "feet", "weapons/fx/nearmiss/bulletLtoR05.wav" } )
	self:ListNewAward( { x, w, "Big Game Hunter:", "dismembered the most zombies with a shotgun.", function() return self:GetStatMax( "Meat" ) end, "zombies poached", "nuke/gore/blood01.wav", true } )
	self:ListNewAward( { x, w, "Bullet Hose:", "used the most ammunition.", function() return self:GetStatMax( "Bullets" ) end, "rounds fired", "player/pl_shell1.wav" } )
	self:ListNewAward( { x, w, "Meat Grinder:", "butchered the most zombies with a melee weapon.", function() return self:GetStatMax( "Knife" ) end, "melee kills", "weapons/knife/knife_hit2.wav", true } )
	self:ListNewAward( { x, w, "Demolitionist:", "killed the most zombies with explosives.", function() return self:GetStatMax( "Explode" ) end, "unidentified bodies", "weapons/underwater_explode3.wav", true } )
	self:ListNewAward( { x, w, "Firebug:", "ignited the most zombies.", function() return self:GetStatMax( "Igniter" ) end, "crispy corpses", "ambient/fire/mtov_flame2.wav", true } )
	self:ListNewAward( { x, w, "Kleptomaniac:", "picked up the most items.", function() return self:GetStatMax( "Loot" ) end, "items taken", "items/itempickup.wav" } )
	self:ListNewAward( { x, w, "Broke The Bank:", "bought the most expensive weapon.", function() return self:GetStatMax( "Pricey" ) end, GAMEMODE.CurrencyName .. "s spent", "ambient/office/coinslot1.wav" } )
	self:ListNewAward( { x, w, "Meet The Engineer:", "built the most barricades.", function() return self:GetStatMax( "Wood" ) end, "barricades built", "npc/dog/dog_servo6.wav", true } )
	self:ListNewAward( { x, w, "Brain Munch:", "dealt the most damage to humans.", function() return self:GetStatMax( "ZedDamage" ) end, "health points", "npc/zombie/zombie_voice_idle2.wav", true } )
	self:ListNewAward( { x, w, "Get To Ze Choppa:", "was the first to reach the evacuation zone.", function() return self:GetStatMax( "Evac" ) end, nil, "ambient/machines/spinup.wav", true } )
	self:ListNewAward( { x, w, "Martyr:", "was the first human to die.", function() return self:GetStatMax( "Martyr" ) end, nil, "npc/crow/alert1.wav", true } )
	self:ListNewAward( { x, w, "Unhealthy Glow:", "was irradiated the most.", function() return self:GetStatMax( "Rad" ) end, "malignant tumors", "player/geiger3.wav", true } )
	self:ListNewAward( { x, w, "Cum Dumpster:", "was infected by zombies the most.", function() return self:GetStatMax( "Infections" ) end, "infections", "ambient/voices/cough1.wav", true } )
	self:ListNewAward( { x, w, "Accident Prone:", "took the most damage from zombies.", function() return self:GetStatMax( "Damage" ) end, "damage", "bot/pain2.wav" } )
	self:ListNewAward( { x, w, "Roleplayer:", "did jack shit.", function() return self:GetWorstPlayer() end, "kills", "ambient/sheep.wav" } )
	//self:ListNewAward( { x, w, "Piss Poor:", "spent the least " .. GAMEMODE.CurrencyName .. "s.", function() return self:GetStatMin( "Spent" ) end, GAMEMODE.CurrencyName .. "s spent", "bot/i_got_nothing.wav" } )

end

function PANEL:ListNewAward( tbl )

	table.insert( self.Awards, tbl )

end

function PANEL:GetWorstPlayer()

	local min = 9000
	local ply = NULL

	for k,v in pairs( player.GetAll() ) do

		if v:Frags() < min then

			min = v:Frags()
			ply = v

		end

	end

	return ply, min

end

function PANEL:GetStatMin( name )

	local min = 9000
	local ply = NULL

	for k,v in pairs( PlayerStats ) do

		if v.Stats and ( v.Stats[ name ] or 0 ) < min then

			min = ( v.Stats[ name ] or 0 )
			ply = v.Player

		end

	end

	return ply, min

end

function PANEL:GetStatMax( name )

	local max = -1
	local ply = NULL

	for k,v in pairs( PlayerStats ) do

		if v.Stats and ( v.Stats[ name ] or 0 ) > max then

			max = ( v.Stats[ name ] or 0 )
			ply = v.Player

		end

	end

	return ply, max

end

function PANEL:GetSurvivors()

	local tbl = {}

	for k,v in pairs( team.GetPlayers( TEAM_ARMY ) ) do

		table.insert( tbl, { v } )

	end

	return tbl

end

function PANEL:GetTopSpenders()

	local num = math.min( #player.GetAll(), 5 )
	local tbl = {}
	local ignore = {}

	for i=1, num do

		local count = -1
		local ply = NULL

		for k,v in pairs( PlayerStats ) do

			if v.Stats and ( v.Stats[ "Spent" ] or 0 ) > count and not table.HasValue( ignore, v.Player ) then

				ply = v.Player
				count = ( v.Stats[ "Spent" ] or 0 )

			end

		end

		if ply != NULL then

			table.insert( tbl, { ply, count } )
			table.insert( ignore, ply )

		end

	end

	return tbl

end

function PANEL:GetTopKillers()

	local num = math.min( #player.GetAll(), 5 )
	local plys = player.GetAll()
	local tbl = {}

	for i=1, num do

		local count = -1
		local ply = NULL
		local pos = 0

		for k,v in pairs( plys ) do

			if v:Frags() > count then

				ply = v
				pos = k
				count = v:Frags()

			end

		end

		if ply != NULL then

			table.remove( plys, pos )
			table.insert( tbl, { ply, ply:Frags() } )

		end

	end

	return tbl

end

function PANEL:PerformLayout()

	self:SetSize( ScrW(), ScrH() )

end

function PANEL:AddList( pos, width, title, players, sound )

	surface.PlaySound( sound )

	table.insert( self.DrawTbl, { X = pos + width * 0.5, Y = 35, Text = title, Style = TEXT_ALIGN_CENTER, Font = "EndGameBig" } )

	if not players[1] then return end

	local ypos = 60

	for k,v in pairs( players ) do

		local list = vgui.Create( "PlayerPanel" )
		list:SetPlayerEnt( v[1] )
		list:SetCount( v[2] )
		list:SetTall( 26 )
		list:SetWide( width )
		list:SetPos( pos, ypos )

		ypos = ypos + 31

	end

end

function PANEL:AddAward( ypos, pos, width, title, desc, ply, amt, append, sound, condition )

	if condition and amt < 1 then

		self.Wait = 0

		return

	end

	surface.PlaySound( sound )

	self.YPos = self.YPos + 31
	self.Wait = CurTime() + 1.5

	table.insert( self.DrawTbl, { X = pos + 2, Y = ypos + 5, Text = title, Style = TEXT_ALIGN_LEFT, Font = "EndGame" } )

	local offset = 150

	local list = vgui.Create( "PlayerPanel" )
	list:SetPlayerEnt( ply )
	list:SetDescription( desc )
	list:SetTall( 26 )
	list:SetWide( width - offset )
	list:SetPos( pos + offset, ypos )

	if append then

		list:SetCount( amt .. " " .. append )

	end

end

function PANEL:Think()

	if self.Wait and self.Wait < CurTime() then

		self.Wait = CurTime() + 0.5

		if self.ListMode then

			local alist = self.Lists[ self.Pos ]

			self:AddList( alist[1], alist[2], alist[3], alist[4](), alist[5] )

			self.Pos = self.Pos + 1

			if self.Pos > #self.Lists then

				self.ListMode = false
				self.Wait = CurTime() + 1.5
				self.Pos = 1

			end

		else

			local alist = self.Awards[ self.Pos ]

			local ply, amt = alist[5]()

			self:AddAward( self.YPos, alist[1], alist[2], alist[3], alist[4], ply, amt, alist[6], alist[7], alist[8] )

			self.Pos = self.Pos + 1

			if self.Pos > #self.Awards then

				self.Wait = nil

			end

		end

	end

end

function PANEL:Paint()

	for k,v in pairs( self.DrawTbl ) do

		draw.SimpleText( v.Text, v.Font, v.X, v.Y, Color( 255, 255, 255 ), v.Style, v.Style )

	end

end

derma.DefineControl( "EndGame", "The end-game stat page", PANEL, "PanelBase" )


text:
public class Client{
  public static void main(String[] args){
    LRUCache test = new LRUCache(3);
    //Set
    System.out.println("Capacity: " + test.capacity);
    test.set(1, 1);
    test.set(2, 2);
    test.set(3, 3);
    System.out.println("Test: " + test.toString());
    test.set(4, 4);
    System.out.println("Now going above capacity (should replace 1 with 4): " + test.toString());
    test.set(4, 70);
    System.out.println("Test that changing val only works as expected: " + test.toString());
    /*
    test.set(5, 5);
    test.set(6, 6);
    System.out.println("Test that refreshing works (1): " + test.toString());
    test.set(4, 71);
    System.out.println("Test that refreshing works (2): " + test.toString());
    /*
    //Get
    System.out.println("get(4): " + test.get(4));
    System.out.println("Test: " + test.toString());

    //More
    LRUCache test2 = new LRUCache(2);
    test2.set(2, 1);
    System.out.println("test2:" + test2.toString());
    test2.set(2, 2);
    System.out.println("test2:" + test2.toString());
    System.out.println("get(2): " + test2.get(2));
/*
    For large number of inputs
    LRUCache test3 = new LRUCache(10000);
    for(int i=0; i<15000; i++){
      test3.set(i, i);
      if (i%2 == 0){ test3.get(i/2); }
    }
    System.out.println("Test3: " +test3.toString());

    LinkedList l = new LinkedList();
    System.out.println("l: " + l.toString());
    l.add(5);
    System.out.println("After adding 5:" + l.toString());
    LinkedList.Node removed = l.removeFirst();
    System.out.println("After removing first: " + l.toString());
    System.out.println("And the removed element: " + removed.toString());
*/

  }
}


text:
package com.snowplowanalytics.snowplow.enrich
package common.enrichments.registry.sqlquery

// json4s
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.parseJson
import org.json4s.jackson.JsonMethods.asJsonNode

// specs2
import org.specs2.Specification
import org.specs2.scalaz.ValidationMatchers

// Iglu
import com.snowplowanalytics.iglu.client.{ SchemaKey, JsonSchemaPair }

// This library
import common.outputs.EnrichedEvent

object SqlQueryEnrichmentIntegrationTest {
  def continuousIntegration: Boolean = sys.env.get("CI") match {
    case Some("true") => true
    case _ => false
  }

  /**
   * Helper function creating almost real [[JsonSchemaPair]] for context/unstruct event
   * out of *valid* JSON string and [[SchemaKey]].
   * Useful only if we're passing unstruct event or custom context (but not derived) straight into
   * SqlQueryEnrichment.lookup method
   *
   * WARNING: this is REQUIRED to test custom contexts (not derived!) and unstruct event
   */
  def createPair(key: SchemaKey, validJson: String): JsonSchemaPair = {
    val hierarchy = parseJson(s"""{"rootId":null,"rootTstamp":null,"refRoot":"events","refTree":["events","${key.name}"],"refParent":"events"}""")
    (key, asJsonNode(("data", parseJson(validJson)) ~ ("hierarchy", hierarchy) ~ ("schema", key.toJValue)))
  }

  def createDerived(key: SchemaKey, validJson: String): JObject =
    ("schema", key.toSchemaUri) ~ ("data", parseJson(validJson))
}

import SqlQueryEnrichmentIntegrationTest._
class SqlQueryEnrichmentIntegrationTest extends Specification with ValidationMatchers { def is =
  skipAllUnless(continuousIntegration) ^
  s2"""
  This is an integration test for the SqlQueryEnrichment
  Basic case        $e1
  All-features test $e2
  """

  val SCHEMA_KEY = SchemaKey("com.snowplowanalytics.snowplow.enrichments", "sql_query_enrichment_config", "jsonschema", "1-0-0")

  def e1 = {
    val configuration = parseJson(
      """
        |{
        |  "vendor": "com.snowplowanalytics.snowplow.enrichments",
        |  "name": "sql_query_enrichment_config",
        |  "enabled": true,
        |  "parameters": {
        |    "inputs": [],
        |    "database": {
        |      "postgresql": {
        |        "host": "localhost",
        |        "port": 5432,
        |        "sslMode": false,
        |        "username": "enricher",
        |        "password": "supersecret1",
        |        "database": "sql_enrichment_test"
        |      }
        |    },
        |    "query": {
        |      "sql": "SELECT 42 AS \"singleColumn\""
        |    },
        |    "output": {
        |      "expectedRows": "AT_MOST_ONE",
        |      "json": {
        |        "schema": "iglu:com.acme/singleColumn/jsonschema/1-0-0",
        |        "describes": "ALL_ROWS",
        |        "propertyNames": "AS_IS"
        |      }
        |    },
        |    "cache": {
        |      "size": 3000,
        |      "ttl": 60
        |    }
        |  }
        |}
      """.stripMargin)

    val event = new EnrichedEvent

    val config = SqlQueryEnrichmentConfig.parse(configuration, SCHEMA_KEY)
    val context = config.flatMap(_.lookup(event, Nil, Nil, Nil))

    val correctContext = parseJson(
      """
        |{
        |  "schema": "iglu:com.acme/singleColumn/jsonschema/1-0-0",
        |  "data": {
        |    "singleColumn": 42
        |  }
        |}
      """.stripMargin)

    context must beSuccessful.like {
      case List(json) => json must beEqualTo(correctContext)
    }
  }

  /**
   * Most complex test, it tests:
   * + POJO inputs
   * + unstruct event inputs
   * + derived and custom contexts
   * + colliding inputs
   * + cache
   */
  def e2 = {

    val configuration = parseJson(
      """
        |{
        |  "vendor": "com.snowplowanalytics.snowplow.enrichments",
        |  "name": "sql_query_enrichment_config",
        |  "enabled": true,
        |  "parameters": {
        |    "inputs": [
        |      {
        |        "placeholder": 1,
        |        "pojo": {
        |          "field": "geo_city"
        |        }
        |      },
        |
        |      {
        |        "placeholder": 2,
        |        "json": {
        |          "field": "derived_contexts",
        |          "schemaCriterion": "iglu:org.openweathermap/weather/jsonschema/*-*-*",
        |          "jsonPath": "$.dt"
        |        }
        |      },
        |
        |      {
        |        "placeholder": 3,
        |        "pojo": {
        |          "field": "user_id"
        |        }
        |      },
        |
        |      {
        |        "placeholder": 3,
        |        "json": {
        |           "field": "contexts",
        |           "schemaCriterion": "iglu:com.snowplowanalytics.snowplow/client_session/jsonschema/1-*-*",
        |           "jsonPath": "$.userId"
        |         }
        |      },
        |
        |      {
        |        "placeholder": 4,
        |        "json": {
        |           "field": "contexts",
        |           "schemaCriterion": "iglu:com.snowplowanalytics.snowplow/geolocation_context/jsonschema/1-1-*",
        |           "jsonPath": "$.speed"
        |        }
        |      },
        |
        |      {
        |        "placeholder": 5,
        |        "json": {
        |           "field": "unstruct_event",
        |           "schemaCriterion": "iglu:com.snowplowanalytics.monitoring.kinesis/app_initialized/jsonschema/1-0-0",
        |           "jsonPath": "$.applicationName"
        |        }
        |      }
        |    ],
        |
        |    "database": {
        |      "postgresql": {
        |        "host": "localhost",
        |        "port": 5432,
        |        "sslMode": false,
        |        "username": "enricher",
        |        "password": "supersecret1",
        |        "database": "sql_enrichment_test"
        |      }
        |    },
        |    "query": {
        |      "sql": "SELECT city, country, pk FROM enrichment_test WHERE city = ? AND date_time = ? AND name = ? AND speed = ? AND aux = ?;"
        |    },
        |    "output": {
        |      "expectedRows": "AT_MOST_ONE",
        |      "json": {
        |        "schema": "iglu:com.acme/demographic/jsonschema/1-0-0",
        |        "describes": "ALL_ROWS",
        |        "propertyNames": "CAMEL_CASE"
        |      }
        |    },
        |    "cache": {
        |      "size": 3000,
        |      "ttl": 60
        |    }
        |  }
        |}
      """.stripMargin)

    val event1 = new EnrichedEvent
    event1.setGeo_city("Krasnoyarsk")
    val weatherContext1 = createDerived(SchemaKey("org.openweathermap", "weather", "jsonschema", "1-0-0"), """{"main":{"humidity":78.0,"pressure":1010.0,"temp":260.91,"temp_min":260.15,"temp_max":261.15},"wind":{"speed":2.0,"deg":250.0,"var_end":270,"var_beg":200},"clouds":{"all":75},"weather":[{"main":"Snow","description":"light snow","id":600,"icon":"13d"},{"main":"Mist","description":"mist","id":701,"icon":"50d"}],"dt":"2016-01-07T10:10:34.000Z"}""")
    event1.setUser_id("alice")
    val geoContext1 = createPair(SchemaKey("com.snowplowanalytics.snowplow", "geolocation_context", "jsonschema", "1-1-0"), """ {"latitude": 12.5, "longitude": 32.1, "speed": 10.0} """ )
    val ue1 = createPair(SchemaKey("com.snowplowanalytics.monitoring.kinesis", "app_initialized", "jsonschema", "1-0-0"), """ {"applicationName": "ue_test_krsk"} """)

    val event2 = new EnrichedEvent
    event2.setGeo_city("London")
    val weatherContext2 = createDerived(SchemaKey("org.openweathermap", "weather", "jsonschema", "1-0-0"), """{"main":{"humidity":78.0,"pressure":1010.0,"temp":260.91,"temp_min":260.15,"temp_max":261.15},"wind":{"speed":2.0,"deg":250.0,"var_end":270,"var_beg":200},"clouds":{"all":75},"weather":[{"main":"Snow","description":"light snow","id":600,"icon":"13d"},{"main":"Mist","description":"mist","id":701,"icon":"50d"}],"dt":"2016-01-08T10:00:34.000Z"}""")
    event2.setUser_id("bob")
    val geoContext2 = createPair(SchemaKey("com.snowplowanalytics.snowplow", "geolocation_context", "jsonschema", "1-1-0"), """ {"latitude": 12.5, "longitude": 32.1, "speed": 25.0} """ )
    val ue2 = createPair(SchemaKey("com.snowplowanalytics.monitoring.kinesis", "app_initialized", "jsonschema", "1-0-0"), """ {"applicationName": "ue_test_london"} """)

    val event3 = new EnrichedEvent
    event3.setGeo_city("New York")
    val weatherContext3 = createDerived(SchemaKey("org.openweathermap", "weather", "jsonschema", "1-0-0"), """{"main":{"humidity":78.0,"pressure":1010.0,"temp":260.91,"temp_min":260.15,"temp_max":261.15},"wind":{"speed":2.0,"deg":250.0,"var_end":270,"var_beg":200},"clouds":{"all":75},"weather":[{"main":"Snow","description":"light snow","id":600,"icon":"13d"},{"main":"Mist","description":"mist","id":701,"icon":"50d"}],"dt":"2016-02-07T10:10:00.000Z"}""")
    event3.setUser_id("eve")
    val geoContext3 = createPair(SchemaKey("com.snowplowanalytics.snowplow", "geolocation_context", "jsonschema", "1-1-0"), """ {"latitude": 12.5, "longitude": 32.1, "speed": 2.5} """ )
    val ue3 = createPair(SchemaKey("com.snowplowanalytics.monitoring.kinesis", "app_initialized", "jsonschema", "1-0-0"), """ {"applicationName": "ue_test_ny"} """)

    val event4 = new EnrichedEvent
    event4.setGeo_city("London")
    val weatherContext4 = createDerived(SchemaKey("org.openweathermap", "weather", "jsonschema", "1-0-0"), """{"main":{"humidity":78.0,"pressure":1010.0,"temp":260.91,"temp_min":260.15,"temp_max":261.15},"wind":{"speed":2.0,"deg":250.0,"var_end":270,"var_beg":200},"clouds":{"all":75},"weather":[{"main":"Snow","description":"light snow","id":600,"icon":"13d"},{"main":"Mist","description":"mist","id":701,"icon":"50d"}],"dt":"2016-01-08T10:00:34.000Z"}""")
    event4.setUser_id("eve")  // This should be ignored because of clientSession4
    val clientSession4 = createPair(SchemaKey("com.snowplowanalytics.snowplow", "client_session", "jsonschema", "1-0-1"), """ { "userId": "bob", "sessionId": "123e4567-e89b-12d3-a456-426655440000", "sessionIndex": 1, "previousSessionId": null, "storageMechanism": "SQLITE" } """ )
    val geoContext4 = createPair(SchemaKey("com.snowplowanalytics.snowplow", "geolocation_context", "jsonschema", "1-1-0"), """ {"latitude": 12.5, "longitude": 32.1, "speed": 25.0} """ )
    val ue4 = createPair(SchemaKey("com.snowplowanalytics.monitoring.kinesis", "app_initialized", "jsonschema", "1-0-0"), """ {"applicationName": "ue_test_london"} """)

    val config = SqlQueryEnrichmentConfig.parse(configuration, SCHEMA_KEY)

    val context1 = config.flatMap(_.lookup(event1, List(weatherContext1), List(geoContext1), List(ue1)))
    val result_context1 = parseJson(
      """|{"schema":"iglu:com.acme/demographic/jsonschema/1-0-0",
        |  "data": {
        |    "city": "Krasnoyarsk",
        |    "country": "Russia",
        |    "pk": 1}}""".stripMargin)

    val context2 = config.flatMap(_.lookup(event2, List(weatherContext2), List(geoContext2), List(ue2)))
    val result_context2 = parseJson(
      """|{"schema":"iglu:com.acme/demographic/jsonschema/1-0-0",
        |  "data": {
        |    "city": "London",
        |    "country": "England",
        |    "pk": 2}}""".stripMargin)

    val context3 = config.flatMap(_.lookup(event3, List(weatherContext3), List(geoContext3), List(ue3)))
    val result_context3 = parseJson(
      """|{"schema":"iglu:com.acme/demographic/jsonschema/1-0-0",
        |  "data": {
        |    "city": "New York",
        |    "country": "USA",
        |    "pk": 3}}
      """.stripMargin)

    val context4 = config.flatMap(_.lookup(event4, List(weatherContext4), List(geoContext4, clientSession4), List(ue4)))
    val result_context4 = parseJson(
      """|{"schema":"iglu:com.acme/demographic/jsonschema/1-0-0",
        |  "data": {
        |    "city": "London",
        |    "country": "England",
        |    "pk": 2}}""".stripMargin)

    val res1 = context1 must beSuccessful.like { case List(ctx) => ctx must beEqualTo(result_context1) }
    val res2 = context2 must beSuccessful.like { case List(ctx) => ctx must beEqualTo(result_context2) }
    val res3 = context3 must beSuccessful.like { case List(ctx) => ctx must beEqualTo(result_context3) }
    val res4 = context4 must beSuccessful.like { case List(ctx) => ctx must beEqualTo(result_context4) }
    val cache = config.map(_.cache.actualLoad) must beSuccessful.like { case size => size must beEqualTo(3) }

    res1.and(res2).and(res3).and(res4).and(cache)
  }
}


text:
<?php
namespace Aura\Filter\Rule\Sanitize;

class MinTest extends AbstractSanitizeTest
{
    protected $min = 4;

    protected function getArgs()
    {
        return array($this->min);
    }

    public function providerTo()
    {
        return array(
            array(array(), false, array()),
            array(1, true, 4),
            array(2, true, 4),
            array(3, true, 4),
            array(4, true, 4),
            array(5, true, 5),
            array(6, true, 6),
        );
    }
}


text:
@extends('layouts.master')

@section('content')

A place to show a post.

@endsection


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// If directory files changes too often, don't rescan directory more than once
// per specified interval
var SIMULTANEOUS_RESCAN_INTERVAL = 1000;
// Used for operations that require almost instant rescan.
var SHORT_RESCAN_INTERVAL = 100;

/**
 * Data model of the file manager.
 *
 * @constructor
 * @param {DirectoryEntry} root File system root.
 * @param {boolean} singleSelection True if only one file could be selected
 *                                  at the time.
 * @param {boolean} showGData Defines whether GData root should be should
 *   (regardless of its mounts status).
 * @param {MetadataCache} metadataCache The metadata cache service.
 */
function DirectoryModel(root, singleSelection, showGData, metadataCache) {
  this.root_ = root;
  this.metadataCache_ = metadataCache;
  this.fileList_ = new cr.ui.ArrayDataModel([]);
  this.fileListSelection_ = singleSelection ?
      new cr.ui.ListSingleSelectionModel() : new cr.ui.ListSelectionModel();

  this.showGData_ = showGData;

  this.runningScan_ = null;
  this.pendingScan_ = null;
  this.rescanTimeout_ = undefined;
  this.scanFailures_ = 0;

  // DirectoryEntry representing the current directory of the dialog.
  this.currentDirEntry_ = root;

  this.fileList_.prepareSort = this.prepareSort_.bind(this);

  this.rootsList_ = new cr.ui.ArrayDataModel([]);
  this.rootsListSelection_ = new cr.ui.ListSingleSelectionModel();

  /**
   * A map root.fullPath -> currentDirectory.fullPath.
   * @private
   * @type {Object.<string, string>}
   */
  this.currentDirByRoot_ = {};

  // The map 'name' -> callback. Callbacks are function(entry) -> boolean.
  this.filters_ = {};
  this.setFilterHidden(true);

  /**
   * @private
   * @type {Object.<string, boolean>}
   */
  this.volumeReadOnlyStatus_ = {};
}

/**
 * The name of the directory containing externally
 * mounted removable storage volumes.
 */
DirectoryModel.REMOVABLE_DIRECTORY = 'removable';

/**
 * The name of the directory containing externally
 * mounted archive file volumes.
 */
DirectoryModel.ARCHIVE_DIRECTORY = 'archive';

/**
 * Type of a root directory.
 * @enum
 */
DirectoryModel.RootType = {
  DOWNLOADS: 'downloads',
  ARCHIVE: 'archive',
  REMOVABLE: 'removable',
  GDATA: 'gdata'
};

/**
* The name of the downloads directory.
*/
DirectoryModel.DOWNLOADS_DIRECTORY = 'Downloads';

/**
* The name of the gdata provider directory.
*/
DirectoryModel.GDATA_DIRECTORY = 'gdata';

/**
 * DirectoryModel extends cr.EventTarget.
 */
DirectoryModel.prototype.__proto__ = cr.EventTarget.prototype;

/**
 * @return {cr.ui.ArrayDataModel} Files in the current directory.
 */
DirectoryModel.prototype.getFileList = function() {
  return this.fileList_;
};

/**
 * @return {MetadataCache} Metadata cache.
 */
DirectoryModel.prototype.getMetadataCache = function() {
  return this.metadataCache_;
};

/**
 * Sort the file list.
 * @param {string} sortField Sort field.
 * @param {string} sortDirection "asc" or "desc".
 */
DirectoryModel.prototype.sortFileList = function(sortField, sortDirection) {
  this.fileList_.sort(sortField, sortDirection);
};

/**
 * @return {cr.ui.ListSelectionModel|cr.ui.ListSingleSelectionModel} Selection
 * in the fileList.
 */
DirectoryModel.prototype.getFileListSelection = function() {
  return this.fileListSelection_;
};

/**
 * @return {DirectoryModel.RootType} Root type of current root.
 */
DirectoryModel.prototype.getRootType = function() {
  return DirectoryModel.getRootType(this.currentDirEntry_.fullPath);
};

/**
 * @return {string} Root name.
 */
DirectoryModel.prototype.getRootName = function() {
  return DirectoryModel.getRootName(this.currentDirEntry_.fullPath);
};

/**
 * @return {boolean} True if current directory is read only.
 */
DirectoryModel.prototype.isReadOnly = function() {
  return this.isPathReadOnly(this.getCurrentRootPath());
};

/**
 * @param {strin} path Path to check.
 * @return {boolean} True if the |path| is read only.
 */
DirectoryModel.prototype.isPathReadOnly = function(path) {
  switch (DirectoryModel.getRootType(path)) {
    case DirectoryModel.RootType.REMOVABLE:
      return !!this.volumeReadOnlyStatus_[DirectoryModel.getRootPath(path)];
    case DirectoryModel.RootType.ARCHIVE:
      return true;
    case DirectoryModel.RootType.DOWNLOADS:
      return false;
    case DirectoryModel.RootType.GDATA:
      return util.isOffline();
    default:
      return true;
  }
};

/**
 * @return {boolean} If current directory is system.
 */
DirectoryModel.prototype.isSystemDirectory = function() {
  var path = this.currentDirEntry_.fullPath;
  return path == '/' ||
         path == '/' + DirectoryModel.REMOVABLE_DIRECTORY ||
         path == '/' + DirectoryModel.ARCHIVE_DIRECTORY;
};

/**
 * @return {boolean} If the files with names starting with "." are not shown.
 */
DirectoryModel.prototype.isFilterHiddenOn = function() {
  return !!this.filters_['hidden'];
};

/**
 * @param {boolean} value Whether files with leading "." are hidden.
 */
DirectoryModel.prototype.setFilterHidden = function(value) {
  if (value) {
    this.addFilter('hidden',
                   function(e) {return e.name.substr(0, 1) != '.';});
  } else {
    this.removeFilter('hidden');
  }
};

/**
 * @return {DirectoryEntry} Current directory.
 */
DirectoryModel.prototype.getCurrentDirEntry = function() {
  return this.currentDirEntry_;
};

/**
 * @return {string} Path for the current directory.
 */
DirectoryModel.prototype.getCurrentDirPath = function() {
  return this.currentDirEntry_.fullPath;
};

/**
 * @private
 * @return {Array.<string>} Names of selected files.
 */
DirectoryModel.prototype.getSelectedNames_ = function() {
  var indexes = this.fileListSelection_.selectedIndexes;
  var dataModel = this.fileList_;
  if (dataModel) {
    return indexes.map(function(i) {
      return dataModel.item(i).name;
    });
  }
  return [];
};

/**
 * @private
 * @param {Array.<string>} value List of names of selected files.
 */
DirectoryModel.prototype.setSelectedNames_ = function(value) {
  var indexes = [];
  var dataModel = this.fileList_;

  function safeKey(key) {
    // The transformation must:
    // 1. Never generate a reserved name ('__proto__')
    // 2. Keep different keys different.
    return '#' + key;
  }

  var hash = {};

  for (var i = 0; i < value.length; i++)
    hash[safeKey(value[i])] = 1;

  for (var i = 0; i < dataModel.length; i++) {
    if (hash.hasOwnProperty(safeKey(dataModel.item(i).name)))
      indexes.push(i);
  }
  this.fileListSelection_.selectedIndexes = indexes;
};

/**
 * @private
 * @return {string} Lead item file name.
 */
DirectoryModel.prototype.getLeadName_ = function() {
  var index = this.fileListSelection_.leadIndex;
  return index >= 0 && this.fileList_.item(index).name;
};

/**
 * @private
 * @param {string} value The name of new lead index.
 */
DirectoryModel.prototype.setLeadName_ = function(value) {
  for (var i = 0; i < this.fileList_.length; i++) {
    if (this.fileList_.item(i).name == value) {
      this.fileListSelection_.leadIndex = i;
      return;
    }
  }
};

/**
 * @return {cr.ui.ArrayDataModel} The list of roots.
 */
DirectoryModel.prototype.getRootsList = function() {
  return this.rootsList_;
};

/**
 * @return {Entry} Directory entry of the current root.
 */
DirectoryModel.prototype.getCurrentRootDirEntry = function() {
  return this.rootsList_.item(this.rootsListSelection_.selectedIndex);
};

/**
 * @return {string} Root path for the current directory (parent directory is
 *     not navigatable for the user).
 */
DirectoryModel.prototype.getCurrentRootPath = function() {
  return DirectoryModel.getRootPath(this.currentDirEntry_.fullPath);
};

/**
 * @return {cr.ui.ListSingleSelectionModel} Root list selection model.
 */
DirectoryModel.prototype.getRootsListSelectionModel = function() {
  return this.rootsListSelection_;
};

/**
 * Add a filter for directory contents.
 * @param {string} name An identifier of the filter (used when removing it).
 * @param {function(Entry):boolean} filter Hide file if false.
 */
DirectoryModel.prototype.addFilter = function(name, filter) {
  this.filters_[name] = filter;
  this.rescanSoon();
};

/**
 * Remove one of the directory contents filters, specified by name.
 * @param {string} name Identifier of a filter.
 */
DirectoryModel.prototype.removeFilter = function(name) {
  delete this.filters_[name];
  this.rescanSoon();
};

/**
 * Schedule rescan with short delay.
 */
DirectoryModel.prototype.rescanSoon = function() {
  this.scheduleRescan(SHORT_RESCAN_INTERVAL);
};

/**
 * Schedule rescan with delay. Designed to handle directory change
 * notification.
 */
DirectoryModel.prototype.rescanLater = function() {
  this.scheduleRescan(SIMULTANEOUS_RESCAN_INTERVAL);
};

/**
 * Schedule rescan with delay. If another rescan has been scheduled does
 * nothing. File operation may cause a few notifications what should cause
 * a single refresh.
 * @param {number} delay Delay in ms after which the rescan will be performed.
 */
DirectoryModel.prototype.scheduleRescan = function(delay) {
  if (this.rescanTimeout_ && this.rescanTimeout_ <= delay)
    return;  // Rescan already scheduled.

  var self = this;
  function onTimeout() {
    self.rescanTimeout_ = undefined;
    self.rescan();
  }
  this.rescanTimeout_ = setTimeout(onTimeout, delay);
};

/**
 * Rescan current directory. May be called indirectly through rescanLater or
 * directly in order to reflect user action.
 */
DirectoryModel.prototype.rescan = function() {
  if (this.rescanTimeout_) {
    clearTimeout(this.rescanTimeout_);
    this.rescanTimeout_ = undefined;
  }

  var fileList = [];
  var successCallback = (function() {
    this.replaceFileList_(fileList);
    cr.dispatchSimpleEvent(this, 'rescan-completed');
  }).bind(this);

  if (this.runningScan_) {
    if (!this.pendingScan_)
      this.pendingScan_ = this.createScanner_(fileList, successCallback);
    return;
  }

  this.runningScan_ = this.createScanner_(fileList, successCallback);
  this.runningScan_.run();
};

/**
 * @private
 * @param {Array.<Entry>|cr.ui.ArrayDataModel} list File list.
 * @param {function} successCallback Callback on success.
 * @return {DirectoryModel.Scanner} New Scanner instance.
 */
DirectoryModel.prototype.createScanner_ = function(list, successCallback) {
  var self = this;
  function onSuccess() {
    self.scanFailures_ = 0;
    successCallback();
    if (self.pendingScan_) {
      self.runningScan_ = self.pendingScan_;
      self.pendingScan_ = null;
      self.runningScan_.run();
    } else {
      self.runningScan_ = null;
    }
  }

  function onFailure() {
    self.scanFailures_++;
    if (self.scanFailures_ <= 1)
      self.rescanLater();
  }

  return new DirectoryModel.Scanner(
      this.currentDirEntry_,
      list,
      onSuccess,
      onFailure,
      this.prefetchCacheForSorting_.bind(this),
      this.filters_);
};

/**
 * @private
 * @param {Array.<Entry>} entries List of files.
 */
DirectoryModel.prototype.replaceFileList_ = function(entries) {
  cr.dispatchSimpleEvent(this, 'begin-update-files');
  this.fileListSelection_.beginChange();

  var selectedNames = this.getSelectedNames_();
  // Restore leadIndex in case leadName no longer exists.
  var leadIndex = this.fileListSelection_.leadIndex;
  var leadName = this.getLeadName_();

  var spliceArgs = [].slice.call(entries);
  spliceArgs.unshift(0, this.fileList_.length);
  this.fileList_.splice.apply(this.fileList_, spliceArgs);

  this.setSelectedNames_(selectedNames);
  this.fileListSelection_.leadIndex = leadIndex;
  this.setLeadName_(leadName);
  this.fileListSelection_.endChange();
  cr.dispatchSimpleEvent(this, 'end-update-files');
};

/**
 * Cancels waiting and scheduled rescans and starts new scan.
 *
 * If the scan completes successfully on the first attempt, the callback will
 * be invoked and a 'scan-completed' event will be dispatched.  If the scan
 * fails for any reason, we'll periodically retry until it succeeds (and then
 * send a 'rescan-complete' event) or is cancelled or replaced by another
 * scan.
 *
 * @private
 * @param {function} callback Called if scan completes on the first attempt.
 *   Note that this will NOT be called if the scan fails but later succeeds.
 */
DirectoryModel.prototype.scan_ = function(callback) {
  if (this.rescanTimeout_) {
    clearTimeout(this.rescanTimeout_);
    this.rescanTimeout_ = 0;
  }
  if (this.runningScan_) {
    this.runningScan_.cancel();
    this.runningScan_ = null;
  }
  this.pendingScan_ = null;

  var onDone = function() {
    cr.dispatchSimpleEvent(this, 'scan-completed');
    callback();
  }.bind(this);

  // Clear the table first.
  this.fileList_.splice(0, this.fileList_.length);
  cr.dispatchSimpleEvent(this, 'scan-started');
  if (this.currentDirEntry_ == this.unmountedGDataEntry_) {
    onDone();
    return;
  }
  this.runningScan_ = this.createScanner_(this.fileList_, onDone);
  this.runningScan_.run();
};

/**
 * @private
 * @param {Array.<Entry>} entries Files.
 * @param {function} callback Callback on done.
 */
DirectoryModel.prototype.prefetchCacheForSorting_ = function(entries,
                                                             callback) {
  var field = this.fileList_.sortStatus.field;
  if (field) {
    this.prepareSortEntries_(entries, field, callback);
  } else {
    callback();
  }
};

/**
 * Delete the list of files and directories from filesystem and
 * update the file list.
 * @param {Array.<Entry>} entries Entries to delete.
 * @param {function()=} opt_callback Called when finished.
 */
DirectoryModel.prototype.deleteEntries = function(entries, opt_callback) {
  var downcount = entries.length + 1;

  var onComplete = opt_callback ? function() {
    if (--downcount == 0)
      opt_callback();
  } : function() {};

  var fileList = this.fileList_;
  for (var i = 0; i < entries.length; i++) {
    var entry = entries[i];

    var onSuccess = function(removedEntry) {
      var index = fileList.indexOf(removedEntry);
      if (index >= 0)
        fileList.splice(index, 1);
      onComplete();
    }.bind(null, entry);

    util.removeFileOrDirectory(
        entry,
        onSuccess,
        util.flog('Error deleting ' + entry.fullPath, onComplete));
  }
  onComplete();
};

/**
 * @param {string} name Filename.
 */
DirectoryModel.prototype.onEntryChanged = function(name) {
  var currentEntry = this.currentDirEntry_;
  var dm = this.fileList_;
  var self = this;

  function onEntryFound(entry) {
    self.prefetchCacheForSorting_([entry], function() {
      // Do nothing if current directory changed during async operations.
      if (self.currentDirEntry_ != currentEntry)
        return;

      var index = self.findIndexByName_(name);
      if (index >= 0)
        dm.splice(index, 1, entry);
      else
        dm.splice(dm.length, 0, entry);
    });
  };

  function onError(err) {
    // Do nothing if current directory changed during async operations.
    if (self.currentDirEntry_ != currentEntry)
      return;
    if (err.code != FileError.NOT_FOUND_ERR) {
      self.rescanLater();
      return;
    }

    var index = self.findIndexByName_(name);
    if (index >= 0)
      dm.splice(index, 1);
  };

  util.resolvePath(this.currentDirEntry_, name, onEntryFound, onError);
};

/**
 * @private
 * @param {string} name Filename.
 * @return {number} The index in the fileList.
 */
DirectoryModel.prototype.findIndexByName_ = function(name) {
  var dm = this.fileList_;
  for (var i = 0; i < dm.length; i++)
    if (dm.item(i).name == name)
      return i;
  return -1;
};

/**
 * Rename the entry in the filesystem and update the file list.
 * @param {Entry} entry Entry to rename.
 * @param {string} newName New name.
 * @param {function} errorCallback Called on error.
 * @param {function} opt_successCallback Called on success.
 */
DirectoryModel.prototype.renameEntry = function(entry, newName, errorCallback,
                                                opt_successCallback) {
  var self = this;
  function onSuccess(newEntry) {
    self.prefetchCacheForSorting_([newEntry], function() {
      var fileList = self.fileList_;
      var index = fileList.indexOf(entry);
      if (index >= 0)
        fileList.splice(index, 1, newEntry);
      self.selectEntry(newName);
      // If the entry doesn't exist in the list it mean that it updated from
      // outside (probably by directory rescan).
      if (opt_successCallback)
        opt_successCallback();
    });
  }
  entry.moveTo(this.currentDirEntry_, newName, onSuccess, errorCallback);
};

/**
 * Checks if current directory contains a file or directory with this name.
 * @param {string} newName Name to check.
 * @param {function(boolean, boolean?)} callback Called when the result's
 *     available. First parameter is true if the entry exists and second
 *     is true if it's a file.
 */
DirectoryModel.prototype.doesExist = function(newName, callback) {
  util.resolvePath(this.currentDirEntry_, newName,
      function(entry) {
        callback(true, entry.isFile);
      },
      callback.bind(window, false));
};

/**
 * Creates directory and updates the file list.
 *
 * @param {string} name Directory name.
 * @param {function} successCallback Callback on success.
 * @param {function} errorCallback Callback on failure.
 */
DirectoryModel.prototype.createDirectory = function(name, successCallback,
                                                    errorCallback) {
  var self = this;
  function onSuccess(newEntry) {
    self.prefetchCacheForSorting_([newEntry], function() {
      var fileList = self.fileList_;
      var existing = fileList.slice().filter(
          function(e) { return e.name == name; });

      if (existing.length) {
        self.selectEntry(name);
        successCallback(existing[0]);
      } else {
        self.fileListSelection_.beginChange();
        fileList.splice(0, 0, newEntry);
        self.selectEntry(name);
        self.fileListSelection_.endChange();
        successCallback(newEntry);
      }
    });
  }

  this.currentDirEntry_.getDirectory(name, {create: true, exclusive: true},
                                     onSuccess, errorCallback);
};

/**
 * Changes directory. Causes 'directory-change' event.
 *
 * @param {string} path New current directory path.
 */
DirectoryModel.prototype.changeDirectory = function(path) {
  this.resolveDirectory(path, function(directoryEntry) {
    this.changeDirectoryEntry_(false, directoryEntry);
  }.bind(this), function(error) {
    console.error('Error changing directory to ' + path + ': ', error);
  });
};

/**
 * Resolves absolute directory path. Handles GData stub.
 * @param {string} path Path to the directory.
 * @param {function(DirectoryEntry} successCallback Success callback.
 * @param {function(FileError} errorCallback Error callback.
 */
DirectoryModel.prototype.resolveDirectory = function(path, successCallback,
                                                     errorCallback) {
  if (this.unmountedGDataEntry_ &&
      DirectoryModel.getRootType(path) == DirectoryModel.RootType.GDATA) {
    // TODO(kaznacheeev): Currently if path points to some GData subdirectory
    // and GData is not mounted we will change to the fake GData root and
    // ignore the rest of the path. Consider remembering the path and
    // changing to it once GDdata is mounted. This is only relevant for cases
    // when we open the File Manager with an URL pointing to GData (e.g. via
    // a bookmark).
    successCallback(this.unmountedGDataEntry_);
    return;
  }

  if (path == '/') {
    successCallback(this.root_);
    return;
  }

  this.root_.getDirectory(path, {create: false},
                          successCallback, errorCallback);
};

/**
 * Changes directory. If path points to a root (except current one)
 * then directory changed to the last used one for the root.
 *
 * @param {string} path New current directory path or new root.
 */
DirectoryModel.prototype.changeDirectoryOrRoot = function(path) {
  if (DirectoryModel.getRootPath(path) == this.getCurrentRootPath()) {
    this.changeDirectory(path);
  } else if (this.currentDirByRoot_[path]) {
    this.resolveDirectory(
        this.currentDirByRoot_[path],
        this.changeDirectoryEntry_.bind(this, false),
        this.changeDirectory.bind(this, path));
  } else {
    this.changeDirectory(path);
  }
};

/**
 * Change the current directory to the directory represented by a
 * DirectoryEntry.
 *
 * Dispatches the 'directory-changed' event when the directory is successfully
 * changed.
 *
 * @private
 * @param {boolean} initial True if it comes from setupPath and
 *                          false if caused by an user action.
 * @param {DirectoryEntry} dirEntry The absolute path to the new directory.
 * @param {function} opt_callback Executed if the directory loads successfully.
 */
DirectoryModel.prototype.changeDirectoryEntry_ = function(initial, dirEntry,
                                                          opt_callback) {
  var previous = this.currentDirEntry_;
  this.currentDirEntry_ = dirEntry;
  function onRescanComplete() {
    if (opt_callback)
      opt_callback();
    // For tests that open the dialog to empty directories, everything
    // is loaded at this point.
    chrome.test.sendMessage('directory-change-complete');
  }
  this.updateRootsListSelection_();
  this.scan_(onRescanComplete);
  this.currentDirByRoot_[this.getCurrentRootPath()] = dirEntry.fullPath;

  var e = new cr.Event('directory-changed');
  e.previousDirEntry = previous;
  e.newDirEntry = dirEntry;
  e.initial = initial;
  this.dispatchEvent(e);
};

/**
 * Change the state of the model to reflect the specified path (either a
 * file or directory).
 *
 * @param {string} path The root path to use
 * @param {function=} opt_loadedCallback Invoked when the entire directory
 *     has been loaded and any default file selected.  If there are any
 *     errors loading the directory this will not get called (even if the
 *     directory loads OK on retry later). Will NOT be called if another
 *     directory change happened while setupPath was in progress.
 * @param {function=} opt_pathResolveCallback Invoked as soon as the path has
 *     been resolved, and called with the base and leaf portions of the path
 *     name, and a flag indicating if the entry exists. Will be called even
 *     if another directory change happened while setupPath was in progress,
 *     but will pass |false| as |exist| parameter.
 */
DirectoryModel.prototype.setupPath = function(path, opt_loadedCallback,
                                              opt_pathResolveCallback) {
  var overridden = false;
  function onExternalDirChange() { overridden = true }
  this.addEventListener('directory-changed', onExternalDirChange);

  var resolveCallback = function(exists) {
    this.removeEventListener('directory-changed', onExternalDirChange);
    if (opt_pathResolveCallback)
      opt_pathResolveCallback(baseName, leafName, exists && !overridden);
  }.bind(this);

  var changeDirectoryEntry = function(entry, initial, exists, opt_callback) {
    resolveCallback(exists);
    if (!overridden)
      this.changeDirectoryEntry_(initial, entry, opt_callback);
  }.bind(this);

  var INITIAL = true;
  var EXISTS = true;

  // Split the dirname from the basename.
  var ary = path.match(/^(?:(.*)\/)?([^\/]*)$/);

  if (!ary) {
    console.warn('Unable to split default path: ' + path);
    changeDirectoryEntry(this.root_, INITIAL, !EXISTS);
    return;
  }

  var baseName = ary[1];
  var leafName = ary[2];

  function onLeafFound(baseDirEntry, leafEntry) {
    if (leafEntry.isDirectory) {
      baseName = path;
      leafName = '';
      changeDirectoryEntry(leafEntry, INITIAL, EXISTS);
      return;
    }

    // Leaf is an existing file, cd to its parent directory and select it.
    changeDirectoryEntry(baseDirEntry,
                         !INITIAL /*HACK*/,
                         EXISTS,
                         function() {
                           this.selectEntry(leafEntry.name);
                           if (opt_loadedCallback)
                             opt_loadedCallback();
                         }.bind(this));
    // TODO(kaznacheev): Fix history.replaceState for the File Browser and
    // change !INITIAL to INITIAL. Passing |false| makes things
    // less ugly for now.
  }

  function onLeafError(baseDirEntry, err) {
    // Usually, leaf does not exist, because it's just a suggested file name.
    if (err.code != FileError.NOT_FOUND_ERR)
      console.log('Unexpected error resolving default leaf: ' + err);
    changeDirectoryEntry(baseDirEntry, INITIAL, !EXISTS);
  }

  var onBaseError = function(err) {
    console.log('Unexpected error resolving default base "' +
                baseName + '": ' + err);
    if (path != this.getDefaultDirectory()) {
      // Can't find the provided path, let's go to default one instead.
      resolveCallback(!EXISTS);
      if (!overridden)
        this.setupDefaultPath(opt_loadedCallback);
    } else {
      // Well, we can't find the downloads dir. Let's just show something,
      // or we will get an infinite recursion.
      changeDirectoryEntry(this.root_, opt_loadedCallback, INITIAL, !EXISTS);
    }
  }.bind(this);

  var onBaseFound = function(baseDirEntry) {
    if (!leafName) {
      // Default path is just a directory, cd to it and we're done.
      changeDirectoryEntry(baseDirEntry, INITIAL, !EXISTS);
      return;
    }

    util.resolvePath(this.root_, path,
                     onLeafFound.bind(this, baseDirEntry),
                     onLeafError.bind(this, baseDirEntry));
  }.bind(this);

  var root = this.root_;
  if (!baseName)
    baseName = this.getDefaultDirectory();
  root.getDirectory(baseName, {create: false}, onBaseFound, onBaseError);
};

/**
 * @param {function} opt_callback Callback on done.
 */
DirectoryModel.prototype.setupDefaultPath = function(opt_callback) {
  this.setupPath(this.getDefaultDirectory(), opt_callback);
};

/**
 * @return {string} The default directory.
 */
DirectoryModel.prototype.getDefaultDirectory = function() {
  return '/' + DirectoryModel.DOWNLOADS_DIRECTORY;
};

/**
 * @param {string} name Filename.
 */
DirectoryModel.prototype.selectEntry = function(name) {
  var dm = this.fileList_;
  for (var i = 0; i < dm.length; i++) {
    if (dm.item(i).name == name) {
      this.selectIndex(i);
      return;
    }
  }
};

/**
 * @param {number} index Index of file.
 */
DirectoryModel.prototype.selectIndex = function(index) {
  // this.focusCurrentList_();
  if (index >= this.fileList_.length)
    return;

  // If a list bound with the model it will do scrollIndexIntoView(index).
  this.fileListSelection_.selectedIndex = index;
};

/**
 * Cache necessary data before a sort happens.
 *
 * This is called by the table code before a sort happens, so that we can
 * go fetch data for the sort field that we may not have yet.
 * @private
 * @param {string} field Sort field.
 * @param {function} callback Called when done.
 */
DirectoryModel.prototype.prepareSort_ = function(field, callback) {
  this.prepareSortEntries_(this.fileList_.slice(), field, callback);
};

/**
 * @private
 * @param {Array.<Entry>} entries Files.
 * @param {string} field Sort field.
 * @param {function} callback Called when done.
 */
DirectoryModel.prototype.prepareSortEntries_ = function(entries, field,
                                                        callback) {
  this.metadataCache_.get(entries, 'filesystem', function(properties) {
    callback();
  });
};

/**
 * Get root entries asynchronously.
 * @private
 * @param {function(Array.<Entry>)} callback Called when roots are resolved.
 * @param {boolean} resolveGData See comment for updateRoots.
 */
DirectoryModel.prototype.resolveRoots_ = function(callback, resolveGData) {
  var groups = {
    downloads: null,
    archives: null,
    removables: null,
    gdata: null
  };
  var self = this;

  metrics.startInterval('Load.Roots');
  function done() {
    for (var i in groups)
      if (!groups[i])
        return;

    self.updateVolumeReadOnlyStatus_(groups.removables);
    callback(groups.downloads.
             concat(groups.gdata).
             concat(groups.archives).
             concat(groups.removables));
    metrics.recordInterval('Load.Roots');
  }

  function append(index, values, opt_error) {
    groups[index] = values;
    done();
  }

  function onDownloads(entry) {
    groups.downloads = [entry];
    done();
  }

  function onDownloadsError(error) {
    groups.downloads = [];
    done();
  }

  function onGData(entry) {
    console.log('GData found:', entry);
    self.unmountedGDataEntry_ = null;
    groups.gdata = [entry];
    done();
  }

  function onGDataError(error) {
    console.log('GData error: ', error);
    self.unmountedGDataEntry_ = {
      unmounted: true,  // Clients use this field to distinguish a fake root.
      toURL: function() { return '' },
      fullPath: '/' + DirectoryModel.GDATA_DIRECTORY
    };
    groups.gdata = [self.unmountedGDataEntry_];
    done();
  }

  var root = this.root_;
  root.getDirectory(DirectoryModel.DOWNLOADS_DIRECTORY, { create: false },
                    onDownloads, onDownloadsError);
  util.readDirectory(root, DirectoryModel.ARCHIVE_DIRECTORY,
                     append.bind(this, 'archives'));
  util.readDirectory(root, DirectoryModel.REMOVABLE_DIRECTORY,
                     append.bind(this, 'removables'));
  if (this.showGData_) {
    if (resolveGData) {
      root.getDirectory(DirectoryModel.GDATA_DIRECTORY, { create: false },
                        onGData, onGDataError);
    } else {
      onGDataError('lazy mount');
    }
  } else {
    groups.gdata = [];
  }
};

/**
* @param {function} opt_callback Called when all roots are resolved.
* @param {boolean} opt_resolveGData If true GData should be resolved for real,
*                                   If false a stub entry should be created.
*/
DirectoryModel.prototype.updateRoots = function(opt_callback,
                                                opt_resolveGData) {
  var self = this;
  this.resolveRoots_(function(rootEntries) {
    var dm = self.rootsList_;
    var args = [0, dm.length].concat(rootEntries);
    dm.splice.apply(dm, args);

    self.updateRootsListSelection_();

    if (opt_callback)
      opt_callback();
  }, opt_resolveGData);
};

/**
 * Change root. In case user already opened the root, the last selected
 * directory will be selected.
 * @param {string} rootPath The path of the root.
 */
DirectoryModel.prototype.changeRoot = function(rootPath) {
  if (this.currentDirByRoot_[rootPath]) {
    var onFail = this.changeDirectory.bind(this, rootPath);
    this.changeDirectory(this.currentDirByRoot_[rootPath], onFail);
  } else {
    this.changeDirectory(rootPath);
  }
};

/**
 * Find roots list item by root path.
 *
 * @param {string} path Root path.
 * @return {number} Index of the item.
 * @private
 */
DirectoryModel.prototype.findRootsListItem_ = function(path) {
  var roots = this.rootsList_;
  for (var index = 0; index < roots.length; index++) {
    if (roots.item(index).fullPath == path)
      return index;
  }
  return -1;
};

/**
 * @private
 */
DirectoryModel.prototype.updateRootsListSelection_ = function() {
  var rootPath = DirectoryModel.getRootPath(this.currentDirEntry_.fullPath);
  this.rootsListSelection_.selectedIndex = this.findRootsListItem_(rootPath);
};

/**
 * @param {Array.<DirectoryEntry>} roots Removable volumes entries.
 * @private
 */
DirectoryModel.prototype.updateVolumeReadOnlyStatus_ = function(roots) {
  var status = this.volumeReadOnlyStatus_ = {};
  for (var i = 0; i < roots.length; i++) {
    status[roots[i].fullPath] = false;
    chrome.fileBrowserPrivate.getVolumeMetadata(roots[i].toURL(),
        function(systemMetadata, path) {
          status[path] = !!(systemMetadata && systemMetadata.isReadOnly);
        }.bind(null, roots[i].fullPath));
  }
};

/**
 * Prepare the root for the unmount.
 *
 * @param {string} rootPath The path to the root.
 */
DirectoryModel.prototype.prepareUnmount = function(rootPath) {
  var index = this.findRootsListItem_(rootPath);
  if (index == -1) {
    console.error('Unknown root entry', rootPath);
    return;
  }
  var entry = this.rootsList_.item(index);

  // We never need to remove this attribute because even if the unmount fails
  // the onMountCompleted handler calls updateRoots which creates a new entry
  // object for this volume.
  entry.unmounting = true;

  // Re-place the entry into the roots data model to force re-rendering.
  this.rootsList_.splice(index, 1, entry);

  if (rootPath == this.rootPath) {
    // TODO(kaznacheev): Consider changing to the most recently used root.
    this.changeDirectory(this.getDefaultDirectory());
  }
};

/**
 * @param {string} path Any path.
 * @return {string} The root path.
 */
DirectoryModel.getRootPath = function(path) {
  var type = DirectoryModel.getRootType(path);

  if (type == DirectoryModel.RootType.DOWNLOADS)
    return '/' + DirectoryModel.DOWNLOADS_DIRECTORY;
  if (type == DirectoryModel.RootType.GDATA)
    return '/' + DirectoryModel.GDATA_DIRECTORY;

  function subdir(dir) {
    var end = path.indexOf('/', dir.length + 2);
    return end == -1 ? path : path.substr(0, end);
  }

  if (type == DirectoryModel.RootType.ARCHIVE)
    return subdir(DirectoryModel.ARCHIVE_DIRECTORY);
  if (type == DirectoryModel.REMOVABLE_DIRECTORY)
    return subdir(DirectoryModel.REMOVABLE_DIRECTORY);
  return '/';
};

/**
 * @param {string} path Any path.
 * @return {string} The name of the root.
 */
DirectoryModel.getRootName = function(path) {
  var root = DirectoryModel.getRootPath(path);
  var index = root.lastIndexOf('/');
  return index == -1 ? root : root.substring(index + 1);
};

/**
 * @param {string} path A path.
 * @return {string} A root type.
 */
DirectoryModel.getRootType = function(path) {
  function isTop(dir) {
    return path.substr(1, dir.length) == dir;
  }

  if (isTop(DirectoryModel.DOWNLOADS_DIRECTORY))
    return DirectoryModel.RootType.DOWNLOADS;
  if (isTop(DirectoryModel.GDATA_DIRECTORY))
    return DirectoryModel.RootType.GDATA;
  if (isTop(DirectoryModel.ARCHIVE_DIRECTORY))
    return DirectoryModel.RootType.ARCHIVE;
  if (isTop(DirectoryModel.REMOVABLE_DIRECTORY))
    return DirectoryModel.RootType.REMOVABLE;
  return '';
};

/**
 * @param {string} path A path.
 * @return {boolean} True if it is a path to the root.
 */
DirectoryModel.isRootPath = function(path) {
  if (path[path.length - 1] == '/')
    path = path.substring(0, path.length - 1);
  return DirectoryModel.getRootPath(path) == path;
};

/**
 * @constructor
 * @extends cr.EventTarget
 * @param {DirectoryEntry} dir Directory to scan.
 * @param {Array.<Entry>|cr.ui.ArrayDataModel} list Target to put the files.
 * @param {function} successCallback Callback to call when (and if) scan
 *     successfully completed.
 * @param {function} errorCallback Callback to call in case of IO error.
 * @param {function(Array.<Entry>):void, Function)} preprocessChunk
 *     Callback to preprocess each chunk of files.
 * @param {Object.<string, function(Entry):Boolean>} filters The map of filters
 *     for file entries.
 */
DirectoryModel.Scanner = function(dir, list, successCallback, errorCallback,
                                  preprocessChunk, filters) {
  this.cancelled_ = false;
  this.list_ = list;
  this.dir_ = dir;
  this.reader_ = null;
  this.filters_ = filters;
  this.preprocessChunk_ = preprocessChunk;
  this.successCallback_ = successCallback;
  this.errorCallback_ = errorCallback;
};

/**
 * Extends EventTarget.
 */
DirectoryModel.Scanner.prototype.__proto__ = cr.EventTarget.prototype;

/**
 * Cancel scanner.
 */
DirectoryModel.Scanner.prototype.cancel = function() {
  this.cancelled_ = true;
};

/**
 * Start scanner.
 */
DirectoryModel.Scanner.prototype.run = function() {
  metrics.startInterval('DirectoryScan');

  this.reader_ = this.dir_.createReader();
  this.readNextChunk_();
};

/**
 * @private
 */
DirectoryModel.Scanner.prototype.readNextChunk_ = function() {
  this.reader_.readEntries(this.onChunkComplete_.bind(this),
                           this.errorCallback_);
};

/**
 * @private
 * @param {Array.<Entry>} entries File list.
 */
DirectoryModel.Scanner.prototype.onChunkComplete_ = function(entries) {
  if (this.cancelled_)
    return;

  if (entries.length == 0) {
    this.successCallback_();
    this.recordMetrics_();
    return;
  }

  // Splice takes the to-be-spliced-in array as individual parameters,
  // rather than as an array, so we need to perform some acrobatics...
  var spliceArgs = [].slice.call(entries);

  for (var filterName in this.filters_) {
    spliceArgs = spliceArgs.filter(this.filters_[filterName]);
  }

  var self = this;
  self.preprocessChunk_(spliceArgs, function() {
    spliceArgs.unshift(0, 0);  // index, deleteCount
    self.list_.splice.apply(self.list_, spliceArgs);

    // Keep reading until entries.length is 0.
    self.readNextChunk_();
  });
};

/**
 * @private
 */
DirectoryModel.Scanner.prototype.recordMetrics_ = function() {
  metrics.recordInterval('DirectoryScan');
  if (this.dir_.fullPath ==
      '/' + DirectoryModel.DOWNLOADS_DIRECTORY) {
    metrics.recordMediumCount('DownloadsCount', this.list_.length);
  }
};


text:
/* $Id: ClpSimplexDual.hpp 1761 2011-07-06 16:06:24Z forrest $ */
// Copyright (C) 2002, International Business Machines
// Corporation and others.  All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
/*
   Authors

   John Forrest

 */
#ifndef ClpSimplexDual_H
#define ClpSimplexDual_H

#include "ClpSimplex.hpp"

/** This solves LPs using the dual simplex method

    It inherits from ClpSimplex.  It has no data of its own and
    is never created - only cast from a ClpSimplex object at algorithm time.

*/

class ClpSimplexDual : public ClpSimplex {

public:

     /**@name Description of algorithm */
     //@{
     /** Dual algorithm

         Method

        It tries to be a single phase approach with a weight of 1.0 being
        given to getting optimal and a weight of updatedDualBound_ being
        given to getting dual feasible.  In this version I have used the
        idea that this weight can be thought of as a fake bound.  If the
        distance between the lower and upper bounds on a variable is less
        than the feasibility weight then we are always better off flipping
        to other bound to make dual feasible.  If the distance is greater
        then we make up a fake bound updatedDualBound_ away from one bound.
        If we end up optimal or primal infeasible, we check to see if
        bounds okay.  If so we have finished, if not we increase updatedDualBound_
        and continue (after checking if unbounded). I am undecided about
        free variables - there is coding but I am not sure about it.  At
        present I put them in basis anyway.

        The code is designed to take advantage of sparsity so arrays are
        seldom zeroed out from scratch or gone over in their entirety.
        The only exception is a full scan to find outgoing variable for
        Dantzig row choice.  For steepest edge we keep an updated list
        of infeasibilities (actually squares).
        On easy problems we don't need full scan - just
        pick first reasonable.

        One problem is how to tackle degeneracy and accuracy.  At present
        I am using the modification of costs which I put in OSL and some
        of what I think is the dual analog of Gill et al.
        I am still not sure of the exact details.

        The flow of dual is three while loops as follows:

        while (not finished) {

          while (not clean solution) {

             Factorize and/or clean up solution by flipping variables so
         dual feasible.  If looks finished check fake dual bounds.
         Repeat until status is iterating (-1) or finished (0,1,2)

          }

          while (status==-1) {

            Iterate until no pivot in or out or time to re-factorize.

            Flow is:

            choose pivot row (outgoing variable).  if none then
        we are primal feasible so looks as if done but we need to
        break and check bounds etc.

        Get pivot row in tableau

            Choose incoming column.  If we don't find one then we look
        primal infeasible so break and check bounds etc.  (Also the
        pivot tolerance is larger after any iterations so that may be
        reason)

            If we do find incoming column, we may have to adjust costs to
        keep going forwards (anti-degeneracy).  Check pivot will be stable
        and if unstable throw away iteration and break to re-factorize.
        If minor error re-factorize after iteration.

        Update everything (this may involve flipping variables to stay
        dual feasible.

          }

        }

        TODO's (or maybe not)

        At present we never check we are going forwards.  I overdid that in
        OSL so will try and make a last resort.

        Needs partial scan pivot out option.

        May need other anti-degeneracy measures, especially if we try and use
        loose tolerances as a way to solve in fewer iterations.

        I like idea of dynamic scaling.  This gives opportunity to decouple
        different implications of scaling for accuracy, iteration count and
        feasibility tolerance.

        for use of exotic parameter startFinishoptions see Clpsimplex.hpp
     */

     int dual(int ifValuesPass, int startFinishOptions = 0);
     /** For strong branching.  On input lower and upper are new bounds
         while on output they are change in objective function values
         (>1.0e50 infeasible).
         Return code is 0 if nothing interesting, -1 if infeasible both
         ways and +1 if infeasible one way (check values to see which one(s))
         Solutions are filled in as well - even down, odd up - also
         status and number of iterations
     */
     int strongBranching(int numberVariables, const int * variables,
                         double * newLower, double * newUpper,
                         double ** outputSolution,
                         int * outputStatus, int * outputIterations,
                         bool stopOnFirstInfeasible = true,
                         bool alwaysFinish = false,
                         int startFinishOptions = 0);
     /// This does first part of StrongBranching
     ClpFactorization * setupForStrongBranching(char * arrays, int numberRows,
               int numberColumns, bool solveLp = false);
     /// This cleans up after strong branching
     void cleanupAfterStrongBranching(ClpFactorization * factorization);
     //@}

     /**@name Functions used in dual */
     //@{
     /** This has the flow between re-factorizations
         Broken out for clarity and will be used by strong branching

         Reasons to come out:
         -1 iterations etc
         -2 inaccuracy
         -3 slight inaccuracy (and done iterations)
         +0 looks optimal (might be unbounded - but we will investigate)
         +1 looks infeasible
         +3 max iterations

         If givenPi not NULL then in values pass
      */
     int whileIterating(double * & givenPi, int ifValuesPass);
     /** The duals are updated by the given arrays.
         Returns number of infeasibilities.
         After rowArray and columnArray will just have those which
         have been flipped.
         Variables may be flipped between bounds to stay dual feasible.
         The output vector has movement of primal
         solution (row length array) */
     int updateDualsInDual(CoinIndexedVector * rowArray,
                           CoinIndexedVector * columnArray,
                           CoinIndexedVector * outputArray,
                           double theta,
                           double & objectiveChange,
                           bool fullRecompute);
     /** The duals are updated by the given arrays.
         This is in values pass - so no changes to primal is made
     */
     void updateDualsInValuesPass(CoinIndexedVector * rowArray,
                                  CoinIndexedVector * columnArray,
                                  double theta);
     /** While updateDualsInDual sees what effect is of flip
         this does actual flipping.
     */
     void flipBounds(CoinIndexedVector * rowArray,
                     CoinIndexedVector * columnArray);
     /**
         Row array has row part of pivot row
         Column array has column part.
         This chooses pivot column.
         Spare arrays are used to save pivots which will go infeasible
         We will check for basic so spare array will never overflow.
         If necessary will modify costs
         For speed, we may need to go to a bucket approach when many
         variables are being flipped.
         Returns best possible pivot value
     */
     double dualColumn(CoinIndexedVector * rowArray,
                       CoinIndexedVector * columnArray,
                       CoinIndexedVector * spareArray,
                       CoinIndexedVector * spareArray2,
                       double accpetablePivot,
                       CoinBigIndex * dubiousWeights);
     /// Does first bit of dualColumn
     int dualColumn0(const CoinIndexedVector * rowArray,
                     const CoinIndexedVector * columnArray,
                     CoinIndexedVector * spareArray,
                     double acceptablePivot,
                     double & upperReturn, double &bestReturn, double & badFree);
     /**
         Row array has row part of pivot row
         Column array has column part.
         This sees what is best thing to do in dual values pass
         if sequenceIn==sequenceOut can change dual on chosen row and leave variable in basis
     */
     void checkPossibleValuesMove(CoinIndexedVector * rowArray,
                                  CoinIndexedVector * columnArray,
                                  double acceptablePivot);
     /**
         Row array has row part of pivot row
         Column array has column part.
         This sees what is best thing to do in branch and bound cleanup
         If sequenceIn_ < 0 then can't do anything
     */
     void checkPossibleCleanup(CoinIndexedVector * rowArray,
                               CoinIndexedVector * columnArray,
                               double acceptablePivot);
     /**
         This sees if we can move duals in dual values pass.
         This is done before any pivoting
     */
     void doEasyOnesInValuesPass(double * givenReducedCosts);
     /**
         Chooses dual pivot row
         Would be faster with separate region to scan
         and will have this (with square of infeasibility) when steepest
         For easy problems we can just choose one of the first rows we look at

         If alreadyChosen >=0 then in values pass and that row has been
         selected
     */
     void dualRow(int alreadyChosen);
     /** Checks if any fake bounds active - if so returns number and modifies
         updatedDualBound_ and everything.
         Free variables will be left as free
         Returns number of bounds changed if >=0
         Returns -1 if not initialize and no effect
         Fills in changeVector which can be used to see if unbounded
         and cost of change vector
         If 2 sets to original (just changed)
     */
     int changeBounds(int initialize, CoinIndexedVector * outputArray,
                      double & changeCost);
     /** As changeBounds but just changes new bounds for a single variable.
         Returns true if change */
     bool changeBound( int iSequence);
     /// Restores bound to original bound
     void originalBound(int iSequence);
     /** Checks if tentative optimal actually means unbounded in dual
         Returns -3 if not, 2 if is unbounded */
     int checkUnbounded(CoinIndexedVector * ray, CoinIndexedVector * spare,
                        double changeCost);
     /**  Refactorizes if necessary
          Checks if finished.  Updates status.
          lastCleaned refers to iteration at which some objective/feasibility
          cleaning too place.

          type - 0 initial so set up save arrays etc
               - 1 normal -if good update save
           - 2 restoring from saved
     */
     void statusOfProblemInDual(int & lastCleaned, int type,
                                double * givenDjs, ClpDataSave & saveData,
                                int ifValuesPass);
     /** Perturbs problem (method depends on perturbation())
         returns nonzero if should go to dual */
     int perturb();
     /** Fast iterations.  Misses out a lot of initialization.
         Normally stops on maximum iterations, first re-factorization
         or tentative optimum.  If looks interesting then continues as
         normal.  Returns 0 if finished properly, 1 otherwise.
     */
     int fastDual(bool alwaysFinish = false);
     /** Checks number of variables at fake bounds.  This is used by fastDual
         so can exit gracefully before end */
     int numberAtFakeBound();

     /** Pivot in a variable and choose an outgoing one.  Assumes dual
         feasible - will not go through a reduced cost.  Returns step length in theta
         Return codes as before but -1 means no acceptable pivot
     */
     int pivotResultPart1();
     /** Get next free , -1 if none */
     int nextSuperBasic();
     /** Startup part of dual (may be extended to other algorithms)
         returns 0 if good, 1 if bad */
     int startupSolve(int ifValuesPass, double * saveDuals, int startFinishOptions);
     void finishSolve(int startFinishOptions);
     void gutsOfDual(int ifValuesPass, double * & saveDuals, int initialStatus,
                     ClpDataSave & saveData);
     //int dual2(int ifValuesPass,int startFinishOptions=0);
     void resetFakeBounds(int type);

     //@}
};
#endif


text:
FROM python:2.7

# Install requirements first (so they get cached between builds)
ADD requirements requirements
RUN pip install -r requirements/docker.txt

# Add code into container
ADD . /app/
WORKDIR /app/

# Environment variables
ENV PYTHONPATH=/app/
ENV DJANGO_SETTINGS_MODULE=wagtaildemo.settings.docker

# Create database
RUN django-admin.py migrate --noinput
RUN django-admin.py load_initial_data

# Compress static files
RUN django-admin.py collectstatic --noinput
RUN django-admin.py compress
RUN python -m whitenoise.gzip /app/static/

CMD uwsgi --ini uwsgi.ini
EXPOSE 80


text:
package com.localhop.swipe.viewpagersupport;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import com.localhop.R;

/**
 * Draws a line for each page. The current page line is colored differently
 * than the unselected page lines.
 */
public class UnderlinePageIndicator extends View implements PageIndicator {
    private static final int INVALID_POINTER = -1;
    private static final int FADE_FRAME_MS = 30;

    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private boolean mFades;
    private int mFadeDelay;
    private int mFadeLength;
    private int mFadeBy;

    private ViewPager mViewPager;
    private ViewPager.OnPageChangeListener mListener;
    private int mScrollState;
    private int mCurrentPage;
    private float mPositionOffset;

    private int mTouchSlop;
    private float mLastMotionX = -1;
    private int mActivePointerId = INVALID_POINTER;
    private boolean mIsDragging;

    private final Runnable mFadeRunnable = new Runnable() {
      @Override public void run() {
        if (!mFades) return;

        final int alpha = Math.max(mPaint.getAlpha() - mFadeBy, 0);
        mPaint.setAlpha(alpha);
        invalidate();
        if (alpha > 0) {
          postDelayed(this, FADE_FRAME_MS);
        }
      }
    };

    public UnderlinePageIndicator(Context context) {
        this(context, null);
    }

    public UnderlinePageIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.vpiUnderlinePageIndicatorStyle);
    }

    public UnderlinePageIndicator(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if (isInEditMode()) return;

        final Resources res = getResources();

        //Load defaults from resources
        //final boolean defaultFades = res.getBoolean(R.bool.default_underline_indicator_fades);
        //final int defaultFadeDelay = res.getInteger(R.integer.default_underline_indicator_fade_delay);
        //final int defaultFadeLength = res.getInteger(R.integer.default_underline_indicator_fade_length);
        final int defaultSelectedColor = res.getColor(R.color.default_underline_indicator_selected_color);

        //Retrieve styles attributes
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.UnderlinePageIndicator, defStyle, 0);

        //setFades(a.getBoolean(R.styleable.UnderlinePageIndicator_fades, defaultFades));
        setSelectedColor(a.getColor(R.styleable.UnderlinePageIndicator_selectedColor, defaultSelectedColor));
        //setFadeDelay(a.getInteger(R.styleable.UnderlinePageIndicator_fadeDelay, defaultFadeDelay));
        //setFadeLength(a.getInteger(R.styleable.UnderlinePageIndicator_fadeLength, defaultFadeLength));

        Drawable background = a.getDrawable(R.styleable.UnderlinePageIndicator_android_background);
        if (background != null) {
          setBackgroundDrawable(background);
        }

        a.recycle();

        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
    }

    public boolean getFades() {
        return mFades;
    }

    public void setFades(boolean fades) {
        if (fades != mFades) {
            mFades = fades;
            if (fades) {
                post(mFadeRunnable);
            } else {
                removeCallbacks(mFadeRunnable);
                mPaint.setAlpha(0xFF);
                invalidate();
            }
        }
    }

    public int getFadeDelay() {
        return mFadeDelay;
    }

    public void setFadeDelay(int fadeDelay) {
        mFadeDelay = fadeDelay;
    }

    public int getFadeLength() {
        return mFadeLength;
    }

    public void setFadeLength(int fadeLength) {
        mFadeLength = fadeLength;
        mFadeBy = 0xFF / (mFadeLength / FADE_FRAME_MS);
    }

    public int getSelectedColor() {
        return mPaint.getColor();
    }

    public void setSelectedColor(int selectedColor) {
        mPaint.setColor(selectedColor);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mViewPager == null) {
            return;
        }
        final int count = mViewPager.getAdapter().getCount();
        if (count == 0) {
            return;
        }

        if (mCurrentPage >= count) {
            setCurrentItem(count - 1);
            return;
        }

        final int paddingLeft = getPaddingLeft();
        final float pageWidth = (getWidth() - paddingLeft - getPaddingRight()) / (1f * count);
        final float left = paddingLeft + pageWidth * (mCurrentPage + mPositionOffset);
        final float right = left + pageWidth;
        final float top = getPaddingTop();
        final float bottom = getHeight() - getPaddingBottom();
        canvas.drawRect(left, top, right, bottom, mPaint);
    }

    public boolean onTouchEvent(MotionEvent ev) {
        if (super.onTouchEvent(ev)) {
            return true;
        }
        if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) {
            return false;
        }

        final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
                mLastMotionX = ev.getX();
                break;

            case MotionEvent.ACTION_MOVE: {
                final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
                final float x = MotionEventCompat.getX(ev, activePointerIndex);
                final float deltaX = x - mLastMotionX;

                if (!mIsDragging) {
                    if (Math.abs(deltaX) > mTouchSlop) {
                        mIsDragging = true;
                    }
                }

                if (mIsDragging) {
                    mLastMotionX = x;
                    if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) {
                        mViewPager.fakeDragBy(deltaX);
                    }
                }

                break;
            }

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                if (!mIsDragging) {
                    final int count = mViewPager.getAdapter().getCount();
                    final int width = getWidth();
                    final float halfWidth = width / 2f;
                    final float sixthWidth = width / 6f;

                    if ((mCurrentPage > 0) && (ev.getX() < halfWidth - sixthWidth)) {
                        if (action != MotionEvent.ACTION_CANCEL) {
                            mViewPager.setCurrentItem(mCurrentPage - 1);
                        }
                        return true;
                    } else if ((mCurrentPage < count - 1) && (ev.getX() > halfWidth + sixthWidth)) {
                        if (action != MotionEvent.ACTION_CANCEL) {
                            mViewPager.setCurrentItem(mCurrentPage + 1);
                        }
                        return true;
                    }
                }

                mIsDragging = false;
                mActivePointerId = INVALID_POINTER;
                if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();
                break;

            case MotionEventCompat.ACTION_POINTER_DOWN: {
                final int index = MotionEventCompat.getActionIndex(ev);
                mLastMotionX = MotionEventCompat.getX(ev, index);
                mActivePointerId = MotionEventCompat.getPointerId(ev, index);
                break;
            }

            case MotionEventCompat.ACTION_POINTER_UP:
                final int pointerIndex = MotionEventCompat.getActionIndex(ev);
                final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
                if (pointerId == mActivePointerId) {
                    final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                    mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
                }
                mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
                break;
        }

        return true;
    }

    @Override
    public void setViewPager(ViewPager viewPager) {
        if (mViewPager == viewPager) {
            return;
        }
        if (mViewPager != null) {
            //Clear us from the old pager.
            mViewPager.setOnPageChangeListener(null);
        }
        if (viewPager.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        mViewPager = viewPager;
        mViewPager.setOnPageChangeListener(this);
        invalidate();
        post(new Runnable() {
            @Override public void run() {
                if (mFades) {
                    post(mFadeRunnable);
                }
            }
        });
    }

    @Override
    public void setViewPager(ViewPager view, int initialPosition) {
        setViewPager(view);
        setCurrentItem(initialPosition);
    }

    @Override
    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            throw new IllegalStateException("ViewPager has not been bound.");
        }
        mViewPager.setCurrentItem(item);
        mCurrentPage = item;
        invalidate();
    }

    @Override
    public void notifyDataSetChanged() {
        invalidate();
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        mScrollState = state;

        if (mListener != null) {
            mListener.onPageScrollStateChanged(state);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        mCurrentPage = position;
        mPositionOffset = positionOffset;
        if (mFades) {
            if (positionOffsetPixels > 0) {
                removeCallbacks(mFadeRunnable);
                mPaint.setAlpha(0xFF);
            } else if (mScrollState != ViewPager.SCROLL_STATE_DRAGGING) {
                postDelayed(mFadeRunnable, mFadeDelay);
            }
        }
        invalidate();

        if (mListener != null) {
            mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }
    }

    @Override
    public void onPageSelected(int position) {
        if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
            mCurrentPage = position;
            mPositionOffset = 0;
            invalidate();
            mFadeRunnable.run();
        }
        if (mListener != null) {
            mListener.onPageSelected(position);
        }
    }

    @Override
    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mListener = listener;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState)state;
        super.onRestoreInstanceState(savedState.getSuperState());
        mCurrentPage = savedState.currentPage;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPage = mCurrentPage;
        return savedState;
    }

    static class SavedState extends BaseSavedState {
        int currentPage;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPage = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPage);
        }

        @SuppressWarnings("UnusedDeclaration")
        public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}