text:
package net.liftweb
package util

import org.apache.commons.codec.binary.Base64
import java.io.{InputStream, ByteArrayOutputStream, ByteArrayInputStream, Reader, File, FileInputStream, BufferedReader}
import java.security.{SecureRandom, MessageDigest}
import javax.crypto._
import javax.crypto.spec._
import scala.xml.{Node, XML}
import common._

object SecurityHelpers extends StringHelpers with IoHelpers with SecurityHelpers

/**
 * The SecurityHelpers trait provides functions to:<ul>
 * <li> generate random numbers
 * <li> generate keys
 * <li> encrypt/decrypt keys
 * <li> create SHA, SHA-256, MD5 hashs (can be hex encoded)
 * </ul>
 */
trait SecurityHelpers {
  self: StringHelpers with IoHelpers =>

  /** short alias for java.security.SecureRandom */
  private val _random = new SecureRandom

  private def withRandom[T](f: SecureRandom => T): T =
    _random.synchronized(f(_random))

  /** return a random Long modulo a number */
  def randomLong(mod: Long): Long = withRandom(random => math.abs(random.nextLong) % mod)

  /** return a random int modulo a number */
  def randomInt(mod: Int): Int = withRandom(random => math.abs(random.nextInt) % mod)

  /**
   * return true only 'percent' times when asked repeatedly.
   * This function is used in the Skittr example to get a random set of users
   * @param percent percentage as a double number <= 1.0
   */
  def shouldShow(percent: Double): Boolean = withRandom(_.nextDouble <= percent)

  private final def cleanArray(in: Array[Byte]): Array[Byte] = in.filter(a => a >= 32 && a <= 127)

  /** encode a Byte array in Base 64 */
  def base64Encode(in: Array[Byte]): String = new String(cleanArray((new Base64).encode(in)))

  /** encode a Byte array in Base 64 in a way that's safe for use in URLs */
  def base64EncodeURLSafe(in: Array[Byte]): String = new String(Base64.encodeBase64URLSafe(in))

  /** decode a String in Base 64 */
  def base64Decode(in: String): Array[Byte] = (new Base64).decode(in.getBytes("UTF-8"))

  /** create a MD5 digest from a Byte array */
  def md5(in: Array[Byte]): Array[Byte] = (MessageDigest.getInstance("MD5")).digest(in)

  /** create a MD5 digest from a String */
  def md5(in: String): String = new String(cleanArray((new Base64) encode md5(in.getBytes("UTF-8"))))

  /** create a SHA hash from a Byte array */
  def hash(in : Array[Byte]) : Array[Byte] = {
    (MessageDigest.getInstance("SHA")).digest(in)
  }

  /** create a SHA hash from a String */
  def hash(in: String) : String = {
    new String(cleanArray((new Base64) encode (MessageDigest.getInstance("SHA")).digest(in.getBytes("UTF-8"))))
  }

   /** create a SHA hash from a String */
  def hashHex(in: String) : String = {
    Helpers.hexEncode(MessageDigest.getInstance("SHA").digest(in.getBytes("UTF-8")))
  }

  /** Compare two strings in a way that does not vary if the strings
   * are determined to be not equal early (test every byte... avoids
   * timing attackes */
  def secureEquals(s1: String, s2: String): Boolean = (s1, s2) match {
    case (null, null) => true
    case (null, _) => false
    case (_, null) => false
    case (a, b) => secureEquals(a.getBytes("UTF-8"), b.getBytes("UTF-8"))
  }

  /** Compare two byte arrays in a way that does not vary if the arrays
   * are determined to be not equal early (test every byte... avoids
   * timing attackes */
  def secureEquals(s1: Array[Byte], s2: Array[Byte]): Boolean = (s1, s2) match {
    case (null, null) => true
    case (null, _) => false
    case (_, null) => false
    case (a, b) => {
      val la = a.length
      val lb = b.length
      var ret = true
      var pos = 0
      while (pos < la && pos < lb) {
        ret &= (a(pos) == b(pos))
        pos += 1
      }
      ret && la == lb
    }
  }

  /** create a SHA-256 hash from a Byte array */
  def hash256(in : Array[Byte]) : Array[Byte] = {
    (MessageDigest.getInstance("SHA-256")).digest(in)
  }

  /** create a SHA-256 hash from a String */
  def hash256(in : String): String = {
    new String(cleanArray((new Base64) encode (MessageDigest.getInstance("SHA-256")).digest(in.getBytes("UTF-8"))))
  }

  /** create an hex encoded SHA hash from a Byte array */
  def hexDigest(in: Array[Byte]): String = {
    val binHash = (MessageDigest.getInstance("SHA")).digest(in)
    hexEncode(binHash)
  }

  /** create an hex encoded SHA-256 hash from a Byte array */
  def hexDigest256(in: Array[Byte]): String = {
    val binHash = (MessageDigest.getInstance("SHA-256")).digest(in)
    hexEncode(binHash)
  }

  def hexDecode(str: String): Array[Byte] = {
    val max = str.length / 2
    val ret = new Array[Byte](max)
    var pos = 0

    def byteOf(in: Char): Int = in match {
      case '0' => 0
      case '1' => 1
      case '2' => 2
      case '3' => 3
      case '4' => 4
      case '5' => 5
      case '6' => 6
      case '7' => 7
      case '8' => 8
      case '9' => 9
      case 'a' | 'A' => 10
      case 'b' | 'B' => 11
      case 'c' | 'C' => 12
      case 'd' | 'D' => 13
      case 'e' | 'E' => 14
      case 'f' | 'F' => 15
        case _ => 0
    }

    while (pos < max) {
      val two = pos * 2
      val ch: Char = str.charAt(two)
      val cl: Char = str.charAt(two + 1)
      ret(pos) = (byteOf(ch) * 16 + byteOf(cl)).toByte
      pos += 1
    }

    ret
  }

  /** encode a Byte array as hexadecimal characters */
  def hexEncode(in: Array[Byte]): String = {
    val sb = new StringBuilder
    val len = in.length
    def addDigit(in: Array[Byte], pos: Int, len: Int, sb: StringBuilder) {
      if (pos < len) {
        val b: Int = in(pos)
        val msb = (b & 0xf0) >> 4
        val lsb = (b & 0x0f)
        sb.append((if (msb < 10) ('0' + msb).asInstanceOf[Char] else ('a' + (msb - 10)).asInstanceOf[Char]))
        sb.append((if (lsb < 10) ('0' + lsb).asInstanceOf[Char] else ('a' + (lsb - 10)).asInstanceOf[Char]))

        addDigit(in, pos + 1, len, sb)
      }
    }
    addDigit(in, 0, len, sb)
    sb.toString
  }

}


text:
package com.svetroid.main;

import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel;

import java.util.ArrayList;
import java.util.List;

public class Whitelist {

  private List<String> guilds = new ArrayList<>();
  private List<String> channels = new ArrayList<>();

  public List<String> getGuilds() {
    return guilds;
  }

  public List<String> getChannels() {
    return channels;
  }

  public void add(Guild guild) {
    guilds.add(guild.getId());
  }

  public void add(TextChannel channel) {
    channels.add(channel.getId());
  }

  public void remove(Guild guild) {
    guilds.remove(guild.getId());
  }

  public void remove(TextChannel channel) {
    channels.remove(channel.getId());
  }

}

redpajama_set_name: RedPajamaGithub


text:
require_relative '../model'

module Judopay
  class Preauth < Model
    @resource_path = 'transactions/preauths'
    @valid_api_methods = [:all]
  end
end


text:
<?php

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\Bundle\AsseticBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

/**
 * Finishes configuration of the Sprockets filter.
 *
 * @author Kris Wallsmith <kris@symfony.com>
 */
class SprocketsFilterPass implements CompilerPassInterface {
	public function process(ContainerBuilder $container) {
		if (!$container->hasDefinition('assetic.filter.sprockets')) {
			return;
		}

		$filter = $container->getDefinition('assetic.filter.sprockets');
		foreach ($container->getParameter('assetic.filter.sprockets.include_dirs') as $dir) {
			$filter->addMethodCall('addIncludeDir', array($dir));
		}
	}
}


text:
class Keyword < ActiveRecord::Base
  scope :find_keyword, lambda {
    |str| where('lower(name) like ?', "#{str.downcase}%")
  }

  has_many :project_interests
  has_many :projects, through: :project_interests

  has_many :user_interests
  has_many :users, through: :user_interests
end


text:
'use strict';

var React = require('React');

var Composer = React.createClass({
  componentWillReceiveProps: function(nextProps) {
    React.findDOMNode(this);
    return foo(React.findDOMNode(this.refs.input));
  },

  foo: function() {
    var ref = 'foo';
    var element = this.refs[ref];
    var domNode = React.findDOMNode(element);
  },

  bar: function() {
    var thing = this.refs.foo;
    React.findDOMNode(thing);
  },

  foobar: function() {
    passThisOn(React.findDOMNode(this.refs.main.refs.list));
  },
});

var SomeDialog = React.createClass({
  render: function() {
    call(this.refs.SomeThing);
    return (
      <div />
    );
  },
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>FTCAndroidLibrary: com.lasarobotics.library.util.RollingAverage< T extends Number > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

FTCAndroidLibrary

Main Page

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

com

lasarobotics

library

util

RollingAverage

Public Member Functions |
List of all members

com.lasarobotics.library.util.RollingAverage< T extends Number > Class Template Reference

Public Member Functions

 	RollingAverage (int capacity)

void 	addValue (T value)

int 	getCapacity ()

void 	setCapacity (int capacity)

void 	clear ()

int 	getSize ()

double 	getAverage ()

double 	getTotal ()

Detailed Description

Structure that performs a continuous rolling average on values Uses doubles as internal structures

The documentation for this class was generated from the following file:

ftc-library/src/main/java/com/lasarobotics/library/util/RollingAverage.java

<address class="footer">
Generated by

 1.8.10
</address>


text:
(function () {
  'use strict';

  angular
    .module('sites')
    .controller('SitesListController', SitesListController);

  SitesListController.$inject = ['SitesService', 'Authentication'];

  function SitesListController(SitesService, Authentication) {
    var vm = this;

    vm.sites = SitesService.query();
    vm.authentication = Authentication;
    vm.remove = remove;

    function remove (site) {
      if(site) {
        for(var i in vm.sites) {
          if(vm.sites[i] === site) {
            site = new SitesService(vm.sites[i]);
            site.$remove();
            vm.sites.splice(i, 1);
          }
        }
      }
    }
  }
})();


text:
<TITLE>Review for Postino, Il (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Postino, Il (1994)

reviewed by
Joan Ellis

                               THE POSTMAN
                       A film review by Joan Ellis
                    Copyright 1995 Nebbadoon Syndicate

     THE POSTMAN is a beautiful, heartbreaking movie about a very
different kind of friendship in an outpost of the old world.  Mario
(Massimo Troisi), the reluctant fisherman in a fishermen's culture,
catches cold every time he sets foot in a boat. He takes a modest job
delivering mail by bicycle to Pablo Neruda (Phillipe Noiret), the
renowned poet living in exile from Chile. Poetry becomes their
connection.

     The friendship of the unlikely pair speaks the sad truth that we
can rarely tell our friends about the inner forces that drive us
through life. Much later, in despair, Mario returns to the poet's house
to revisit the place that had once been alive with the sounds and
sights of emotional discovery.  In the silence that now envelops it,
the loss of joy is simply overwhelming.  It is a wrenching scene.

     Mario has a face of piercing intelligence with sharply angled
cheekbones and the saddest eyes you will ever see. He has fallen in
love with Beatrice, and he turns to the poet, Neruda, for help in
overcoming the halting awkwardness he brings to the courtship. The
friendship between the exalted poet and the postman is sublime, the
sadness of it is unbearable.

     The simple dedication, "To our friend Massimo," is a deeply simple
tribute to Massimo Troisi, the actor who died at 41, one day after
filming ended and just before the surgery he had postponed in order to
finish the film.  Hobbled by illness during the production, he was
driven to deliver this message about heartbreak and friendship. We can
all be grateful that he felt so strongly.

Film Critic :  JOAN ELLIS
Word Count  :  267
Studio      :  Miramax
Rating      :  PG

For all Ellis reviews, see http://movie.infocom.net (which has a search engine)
or send any email to: movie@telecomp.com
Feel free to reuse as long as source acknowledged.
Please send information regarding reuse to 'nebbadoon@telecomp.com'

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

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

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

Broken URLs inthe reviews are the responsibility of the author.

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

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


text:
package com.systemincloud.example.backgroundsubtraction.common;

import com.systemincloud.ext.vip.modeler.api.javatask.data.Image;
import com.systemincloud.modeler.tasks.javatask.api.InputPort;
import com.systemincloud.modeler.tasks.javatask.api.JavaTask;
import com.systemincloud.modeler.tasks.javatask.api.OutputPort;
import com.systemincloud.modeler.tasks.javatask.api.annotations.InputPortInfo;
import com.systemincloud.modeler.tasks.javatask.api.annotations.JavaTaskInfo;
import com.systemincloud.modeler.tasks.javatask.api.annotations.OutputPortInfo;
import com.systemincloud.modeler.tasks.javatask.api.data.Int32;

@JavaTaskInfo
public class YuvSeparator extends JavaTask {

	@InputPortInfo(name = "In", dataType = Image.class)
	public InputPort in;
	@OutputPortInfo(name = "Y", dataType = Int32.class)
	public OutputPort y;
	@OutputPortInfo(name = "U", dataType = Int32.class)
	public OutputPort u;
	@OutputPortInfo(name = "V", dataType = Int32.class)
	public OutputPort v;

	@Override
	public void execute(int grp) {
		Image img = in.getData(Image.class);
		int[] inValues = img.getValues();
		int[] yValues = new int[inValues.length];
		int[] uValues = new int[inValues.length];
		int[] vValues = new int[inValues.length];

		for(int i = 0; i < inValues.length; i++) {
			int red = (inValues[i] >> 16) & 0xFF;
			int green = (inValues[i] >> 8) & 0xFF;
			int blue = inValues[i] & 0xFF;

			yValues[i] = (int) (0.299 * red + 0.597 * green + 0.114 * blue);
			uValues[i] = (int) (-0.147 * red - 0.289 * green + 0.436 * blue);
			vValues[i] = (int) (0.615 * red - 0.515 * green - 0.1 * blue);
		}
		y.putData(new Int32(img.getDimensions(), yValues));
		u.putData(new Int32(img.getDimensions(), uValues));
		v.putData(new Int32(img.getDimensions(), vValues));
	}
}


text:
import boto
import sure  # noqa
import requests
from moto import mock_dynamodb2
from moto.dynamodb2 import dynamodb_backend2
from boto.exception import JSONResponseError
from tests.helpers import requires_boto_gte
try:
    import boto.dynamodb2
except ImportError:
    print "This boto version is not supported"

@requires_boto_gte("2.9")
@mock_dynamodb2
def test_list_tables():
    name = 'TestTable'
    #{'schema': }
    dynamodb_backend2.create_table(name,schema=[
        {u'KeyType': u'HASH', u'AttributeName': u'forum_name'},
        {u'KeyType': u'RANGE', u'AttributeName': u'subject'}
    ])
    conn =  boto.dynamodb2.connect_to_region(
            'us-west-2',
        aws_access_key_id="ak",
        aws_secret_access_key="sk")
    assert conn.list_tables()["TableNames"] == [name]

@requires_boto_gte("2.9")
@mock_dynamodb2
def test_list_tables_layer_1():
    dynamodb_backend2.create_table("test_1",schema=[
        {u'KeyType': u'HASH', u'AttributeName': u'name'}
    ])
    dynamodb_backend2.create_table("test_2",schema=[
        {u'KeyType': u'HASH', u'AttributeName': u'name'}
    ])
    conn =  boto.dynamodb2.connect_to_region(
        'us-west-2',
        aws_access_key_id="ak",
        aws_secret_access_key="sk")

    res = conn.list_tables(limit=1)
    expected = {"TableNames": ["test_1"], "LastEvaluatedTableName": "test_1"}
    res.should.equal(expected)

    res = conn.list_tables(limit=1, exclusive_start_table_name="test_1")
    expected = {"TableNames": ["test_2"]}
    res.should.equal(expected)

@requires_boto_gte("2.9")
@mock_dynamodb2
def test_describe_missing_table():
    conn =  boto.dynamodb2.connect_to_region(
        'us-west-2',
        aws_access_key_id="ak",
        aws_secret_access_key="sk")
    conn.describe_table.when.called_with('messages').should.throw(JSONResponseError)

@requires_boto_gte("2.9")
@mock_dynamodb2
def test_sts_handler():
    res = requests.post("https://sts.amazonaws.com/", data={"GetSessionToken": ""})
    res.ok.should.be.ok
    res.text.should.contain("SecretAccessKey")


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>QueryPager (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.service.pager

Interface QueryPager

All Known Implementing Classes:

MultiPartitionPager, RangeNamesQueryPager, RangeSliceQueryPager, SinglePartitionPager

public interface QueryPager

Perform a query, paging it by page of a given size.

 This is essentially an iterator of pages. Each call to fetchPage() will
 return the next page (i.e. the next list of rows) and isExhausted()
 indicates whether there is more page to fetch. The pageSize will
 either be in term of cells or in term of CQL3 row, depending on the
 parameters of the command we page.

 Please note that the pager might page within rows, so there is no guarantee
 that successive pages won't return the same row (though with different
 columns every time).

 Also, there is no guarantee that fetchPage() won't return an empty list,
 even if isExhausted() return false (but it is guaranteed to return an empty
 list *if* isExhausted() return true). Indeed, isExhausted() does *not*
 trigger a query so in some (fairly rare) case we might not know the paging
 is done even though it is.

Field Summary

Fields

Modifier and Type
Field and Description

static QueryPager
EMPTY

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

ReadExecutionController
executionController()

Starts a new read operation.

PartitionIterator
fetchPage(int pageSize,
         ConsistencyLevel consistency,
         ClientState clientState)

Fetches the next page.

PartitionIterator
fetchPageInternal(int pageSize,
                 ReadExecutionController executionController)

Fetches the next page internally (in other, this does a local query).

boolean
isExhausted()

Whether or not this pager is exhausted, i.e.

int
maxRemaining()

The maximum number of cells/CQL3 row that we may still have to return.

PagingState
state()

Get the current state of the pager.

Field Detail

EMPTY

static final QueryPager EMPTY

Method Detail

fetchPage

PartitionIterator fetchPage(int pageSize,
                            ConsistencyLevel consistency,
                            ClientState clientState)
                     throws RequestValidationException,
                            RequestExecutionException

Fetches the next page.

Parameters:

pageSize - the maximum number of elements to return in the next page.

consistency - the consistency level to achieve for the query.

clientState - the ClientState for the query. In practice, this can be null unless
 consistency is a serial consistency.

Returns:

the page of result.

Throws:

RequestValidationException

RequestExecutionException

executionController

ReadExecutionController executionController()

Starts a new read operation.

 This must be called before fetchPageInternal and passed to it to protect the read.
 The returned object must be closed on all path and it is thus strongly advised to
 use it in a try-with-ressource construction.

Returns:

a newly started order group for this QueryPager.

fetchPageInternal

PartitionIterator fetchPageInternal(int pageSize,
                                    ReadExecutionController executionController)
                             throws RequestValidationException,
                                    RequestExecutionException

Fetches the next page internally (in other, this does a local query).

Parameters:

pageSize - the maximum number of elements to return in the next page.

executionController - the ReadExecutionController protecting the read.

Returns:

the page of result.

Throws:

RequestValidationException

RequestExecutionException

isExhausted

boolean isExhausted()

Whether or not this pager is exhausted, i.e. whether or not a call to
 fetchPage may return more result.

Returns:

whether the pager is exhausted.

maxRemaining

int maxRemaining()

The maximum number of cells/CQL3 row that we may still have to return.
 In other words, that's the initial user limit minus what we've already
 returned (note that it's not how many we *will* return, just the upper
 limit on it).

state

PagingState state()

Get the current state of the pager. The state can allow to restart the
 paging on another host from where we are at this point.

Returns:

the current paging state. Will return null if paging is at the
 beginning. If the pager is exhausted, the result is undefined.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
<!doctype html>

  <link rel=stylesheet href="../node_modules/codemirror/lib/codemirror.css">
  <link rel="stylesheet" href="../node_modules/codemirror/addon/hint/show-hint.css">
  <link rel="stylesheet" href="../node_modules/codemirror/addon/dialog/dialog.css">
  <meta charset="utf-8">
  <link rel=stylesheet href="docs.css">
  <link rel=stylesheet href="demo/demo.css">
  <title>Tern Demo</title>

    Tern: Intelligent JavaScript tooling
    Demo
    Docs
    Code

Tern demo

This editor is hooked up to Tern. The drop-down in the top right
corner lists the commands and keyboard shortcuts available. Output and
function argument hints will appear in the bar below the editor.

  <select id="commands">
    <option>commands...</option>
    <option value=complete>Autocomplete (ctrl-space)</option>
    <option value=jumptodef>Jump to definition (alt-.)</option>
    <option value=findtype>Find type of (ctrl-i)</option>
    <option value=rename>Rename variable (ctrl-q)</option>
    <option value=addfile>Add a new file</option>
    <option value=delfile>Remove this file</option>
  </select>
  <form>

    <textarea id=code name=code>
// Use ctrl-space to complete something
co
document.body.a

// Put the cursor in or after an expression, press ctrl-i to
// find its type

var foo = ["array", "of", "strings"];
var bar = foo.slice(0, 2).join("").split("a")[0];

// Works for locally defined types too.

function CTor() { this.size = 10; }
CTor.prototype.hallo = "hallo";

var baz = new CTor;
baz.

// You can press ctrl-q when the cursor is on a variable name to
// rename it. Try it with CTor...

// When the cursor is in an argument list, the arguments are
// shown below the editor.

[1].reduce(  );

// And a little more advanced code...

(function(exports) {
  exports.randomElt = function(arr) {
    return arr[Math.floor(arr.length * Math.random())];
  };
  exports.strList = "foo".split("");
  exports.intList = exports.strList.map(function(s) { return s.charCodeAt(0); });
})(window.myMod = {});

var randomStr = myMod.randomElt(myMod.strList);
var randomInt = myMod.randomElt(myMod.intList);

// A test of the requirejs plug-in. Check the 'test_dep.js' tab,
// notice that the test variable.

requirejs(["test_dep.js"], function(test) {
  var word = test.capitalize(test.garble("coconut"));
  console.log(word);
});
</textarea></form>

define(function() {
  return {
    capitalize: function(word) {
      return word.charAt(0).toUpperCase() + word.slice(1);
    },
    garble: function(word) {
      return word.replace(/[auiyoe]/g, function() {
        return "auiyoe".charAt(Math.floor(Math.random() * 6));
      });
    }
  };
});


text:
module Util.Socket
  ( connectSocket,
    serverSocket,
    acceptSocket,
    closeSock,
    Socket (),
  )
where

import Data.Word
import Network.Socket
import UnliftIO
import Data.Text (Text)
import qualified Data.Text as Text

--------------------------------------------------------------------------------
connectSocket :: Text -> Word16 -> IO Socket
connectSocket hostName portNumber = do
  (sock, sa) <- createSocket hostName (Just portNumber)
  handleAny (\e -> closeSock sock >> throwIO e) $ do
    setSocketOption sock NoDelay 1
    connect sock sa
    return sock

serverSocket :: Text -> IO (Socket, Word16)
serverSocket hostName = do
  (sock, sa) <- createSocket hostName Nothing
  handleAny (\e -> closeSock sock >> throwIO e) $ do
    bind sock sa
    listen sock 5
    port <- socketPort sock
    return (sock, fromIntegral port)

acceptSocket :: Socket -> IO Socket
acceptSocket sock = do
  (sock', _sa) <- accept sock
  handleAny (\e -> closeSock sock' >> throwIO e) $ do
    setSocketOption sock' NoDelay 1
    return sock'

closeSock :: Socket -> IO ()
closeSock = close

createSocket ::
  MonadIO m =>
  Text ->
  Maybe Word16 ->
  m (Socket, SockAddr)
createSocket hostName portNumber =
  liftIO $ do
    ai <- addrInfo
    sock <- socket (addrFamily ai) (addrSocketType ai) (addrProtocol ai)
    return (sock, addrAddress ai)
  where
    addrInfo = do
      let hints =
            defaultHints
              { addrFlags =
                  [ AI_CANONNAME,
                    AI_NUMERICSERV,
                    AI_ADDRCONFIG
                  ],
                addrFamily = AF_INET,
                addrSocketType = Stream
              }
      (ai : _) <-
        getAddrInfo
          (Just hints)
          (Just (Text.unpack hostName))
          (show <$> portNumber)
      return ai


text:
set -ex

bundle install

rake compile


text:
package web

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	prom_testutil "github.com/prometheus/client_golang/prometheus/testutil"
	"github.com/stretchr/testify/require"

	"github.com/prometheus/prometheus/config"
	"github.com/prometheus/prometheus/notifier"
	"github.com/prometheus/prometheus/rules"
	"github.com/prometheus/prometheus/scrape"
	"github.com/prometheus/prometheus/tsdb"
)

func TestMain(m *testing.M) {
	// On linux with a global proxy the tests will fail as the go client(http,grpc) tries to connect through the proxy.
	os.Setenv("no_proxy", "localhost,127.0.0.1,0.0.0.0,:")
	os.Exit(m.Run())
}

func TestGlobalURL(t *testing.T) {
	opts := &Options{
		ListenAddress: ":9090",
		ExternalURL: &url.URL{
			Scheme: "https",
			Host:   "externalhost:80",
			Path:   "/path/prefix",
		},
	}

	tests := []struct {
		inURL  string
		outURL string
	}{
		{
			// Nothing should change if the input URL is not on localhost, even if the port is our listening port.
			inURL:  "http://somehost:9090/metrics",
			outURL: "http://somehost:9090/metrics",
		},
		{
			// Port and host should change if target is on localhost and port is our listening port.
			inURL:  "http://localhost:9090/metrics",
			outURL: "https://externalhost:80/metrics",
		},
		{
			// Only the host should change if the port is not our listening port, but the host is localhost.
			inURL:  "http://localhost:8000/metrics",
			outURL: "http://externalhost:8000/metrics",
		},
		{
			// Alternative localhost representations should also work.
			inURL:  "http://127.0.0.1:9090/metrics",
			outURL: "https://externalhost:80/metrics",
		},
	}

	for _, test := range tests {
		inURL, err := url.Parse(test.inURL)

		require.NoError(t, err)

		globalURL := tmplFuncs("", opts)["globalURL"].(func(u *url.URL) *url.URL)
		outURL := globalURL(inURL)

		require.Equal(t, test.outURL, outURL.String())
	}
}

type dbAdapter struct {
	*tsdb.DB
}

func (a *dbAdapter) Stats(statsByLabelName string) (*tsdb.Stats, error) {
	return a.Head().Stats(statsByLabelName), nil
}

func (a *dbAdapter) WALReplayStatus() (tsdb.WALReplayStatus, error) {
	return tsdb.WALReplayStatus{}, nil
}

func TestReadyAndHealthy(t *testing.T) {
	t.Parallel()

	dbDir, err := ioutil.TempDir("", "tsdb-ready")
	require.NoError(t, err)
	defer func() { require.NoError(t, os.RemoveAll(dbDir)) }()

	db, err := tsdb.Open(dbDir, nil, nil, nil, nil)
	require.NoError(t, err)

	opts := &Options{
		ListenAddress:  ":9090",
		ReadTimeout:    30 * time.Second,
		MaxConnections: 512,
		Context:        nil,
		Storage:        nil,
		LocalStorage:   &dbAdapter{db},
		TSDBDir:        dbDir,
		QueryEngine:    nil,
		ScrapeManager:  &scrape.Manager{},
		RuleManager:    &rules.Manager{},
		Notifier:       nil,
		RoutePrefix:    "/",
		EnableAdminAPI: true,
		ExternalURL: &url.URL{
			Scheme: "http",
			Host:   "localhost:9090",
			Path:   "/",
		},
		Version:  &PrometheusVersion{},
		Gatherer: prometheus.DefaultGatherer,
	}

	opts.Flags = map[string]string{}

	webHandler := New(nil, opts)

	webHandler.config = &config.Config{}
	webHandler.notifier = &notifier.Manager{}
	l, err := webHandler.Listener()
	if err != nil {
		panic(fmt.Sprintf("Unable to start web listener: %s", err))
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		err := webHandler.Run(ctx, l, "")
		if err != nil {
			panic(fmt.Sprintf("Can't start web handler:%s", err))
		}
	}()

	// Give some time for the web goroutine to run since we need the server
	// to be up before starting tests.
	time.Sleep(5 * time.Second)

	resp, err := http.Get("http://localhost:9090/-/healthy")
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	cleanupTestResponse(t, resp)

	for _, u := range []string{
		"http://localhost:9090/-/ready",
		"http://localhost:9090/classic/graph",
		"http://localhost:9090/classic/flags",
		"http://localhost:9090/classic/rules",
		"http://localhost:9090/classic/service-discovery",
		"http://localhost:9090/classic/targets",
		"http://localhost:9090/classic/status",
		"http://localhost:9090/classic/config",
	} {
		resp, err = http.Get(u)
		require.NoError(t, err)
		require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
		cleanupTestResponse(t, resp)
	}

	resp, err = http.Post("http://localhost:9090/api/v1/admin/tsdb/snapshot", "", strings.NewReader(""))
	require.NoError(t, err)
	require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
	cleanupTestResponse(t, resp)

	resp, err = http.Post("http://localhost:9090/api/v1/admin/tsdb/delete_series", "", strings.NewReader("{}"))
	require.NoError(t, err)
	require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
	cleanupTestResponse(t, resp)

	// Set to ready.
	webHandler.Ready()

	for _, u := range []string{
		"http://localhost:9090/-/healthy",
		"http://localhost:9090/-/ready",
		"http://localhost:9090/classic/graph",
		"http://localhost:9090/classic/flags",
		"http://localhost:9090/classic/rules",
		"http://localhost:9090/classic/service-discovery",
		"http://localhost:9090/classic/targets",
		"http://localhost:9090/classic/status",
		"http://localhost:9090/classic/config",
	} {
		resp, err = http.Get(u)
		require.NoError(t, err)
		require.Equal(t, http.StatusOK, resp.StatusCode)
		cleanupTestResponse(t, resp)
	}

	resp, err = http.Post("http://localhost:9090/api/v1/admin/tsdb/snapshot", "", strings.NewReader(""))
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	cleanupSnapshot(t, dbDir, resp)
	cleanupTestResponse(t, resp)

	resp, err = http.Post("http://localhost:9090/api/v1/admin/tsdb/delete_series?match[]=up", "", nil)
	require.NoError(t, err)
	require.Equal(t, http.StatusNoContent, resp.StatusCode)
	cleanupTestResponse(t, resp)
}

func TestRoutePrefix(t *testing.T) {
	t.Parallel()
	dbDir, err := ioutil.TempDir("", "tsdb-ready")
	require.NoError(t, err)
	defer func() { require.NoError(t, os.RemoveAll(dbDir)) }()

	db, err := tsdb.Open(dbDir, nil, nil, nil, nil)
	require.NoError(t, err)

	opts := &Options{
		ListenAddress:  ":9091",
		ReadTimeout:    30 * time.Second,
		MaxConnections: 512,
		Context:        nil,
		TSDBDir:        dbDir,
		LocalStorage:   &dbAdapter{db},
		Storage:        nil,
		QueryEngine:    nil,
		ScrapeManager:  nil,
		RuleManager:    nil,
		Notifier:       nil,
		RoutePrefix:    "/prometheus",
		EnableAdminAPI: true,
		ExternalURL: &url.URL{
			Host:   "localhost.localdomain:9090",
			Scheme: "http",
		},
	}

	opts.Flags = map[string]string{}

	webHandler := New(nil, opts)
	l, err := webHandler.Listener()
	if err != nil {
		panic(fmt.Sprintf("Unable to start web listener: %s", err))
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go func() {
		err := webHandler.Run(ctx, l, "")
		if err != nil {
			panic(fmt.Sprintf("Can't start web handler:%s", err))
		}
	}()

	// Give some time for the web goroutine to run since we need the server
	// to be up before starting tests.
	time.Sleep(5 * time.Second)

	resp, err := http.Get("http://localhost:9091" + opts.RoutePrefix + "/-/healthy")
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	cleanupTestResponse(t, resp)

	resp, err = http.Get("http://localhost:9091" + opts.RoutePrefix + "/-/ready")
	require.NoError(t, err)
	require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
	cleanupTestResponse(t, resp)

	resp, err = http.Post("http://localhost:9091"+opts.RoutePrefix+"/api/v1/admin/tsdb/snapshot", "", strings.NewReader(""))
	require.NoError(t, err)
	require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
	cleanupTestResponse(t, resp)

	resp, err = http.Post("http://localhost:9091"+opts.RoutePrefix+"/api/v1/admin/tsdb/delete_series", "", strings.NewReader("{}"))
	require.NoError(t, err)
	require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
	cleanupTestResponse(t, resp)

	// Set to ready.
	webHandler.Ready()

	resp, err = http.Get("http://localhost:9091" + opts.RoutePrefix + "/-/healthy")
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	cleanupTestResponse(t, resp)

	resp, err = http.Get("http://localhost:9091" + opts.RoutePrefix + "/-/ready")
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	cleanupTestResponse(t, resp)

	resp, err = http.Post("http://localhost:9091"+opts.RoutePrefix+"/api/v1/admin/tsdb/snapshot", "", strings.NewReader(""))
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, resp.StatusCode)
	cleanupSnapshot(t, dbDir, resp)
	cleanupTestResponse(t, resp)

	resp, err = http.Post("http://localhost:9091"+opts.RoutePrefix+"/api/v1/admin/tsdb/delete_series?match[]=up", "", nil)
	require.NoError(t, err)
	require.Equal(t, http.StatusNoContent, resp.StatusCode)
	cleanupTestResponse(t, resp)
}

func TestDebugHandler(t *testing.T) {
	for _, tc := range []struct {
		prefix, url string
		code        int
	}{
		{"/", "/debug/pprof/cmdline", 200},
		{"/foo", "/foo/debug/pprof/cmdline", 200},

		{"/", "/debug/pprof/goroutine", 200},
		{"/foo", "/foo/debug/pprof/goroutine", 200},

		{"/", "/debug/pprof/foo", 404},
		{"/foo", "/bar/debug/pprof/goroutine", 404},
	} {
		opts := &Options{
			RoutePrefix:   tc.prefix,
			ListenAddress: "somehost:9090",
			ExternalURL: &url.URL{
				Host:   "localhost.localdomain:9090",
				Scheme: "http",
			},
		}
		handler := New(nil, opts)
		handler.Ready()

		w := httptest.NewRecorder()

		req, err := http.NewRequest("GET", tc.url, nil)

		require.NoError(t, err)

		handler.router.ServeHTTP(w, req)

		require.Equal(t, tc.code, w.Code)
	}
}

func TestHTTPMetrics(t *testing.T) {
	t.Parallel()
	handler := New(nil, &Options{
		RoutePrefix:   "/",
		ListenAddress: "somehost:9090",
		ExternalURL: &url.URL{
			Host:   "localhost.localdomain:9090",
			Scheme: "http",
		},
	})
	getReady := func() int {
		t.Helper()
		w := httptest.NewRecorder()

		req, err := http.NewRequest("GET", "/-/ready", nil)
		require.NoError(t, err)

		handler.router.ServeHTTP(w, req)
		return w.Code
	}

	code := getReady()
	require.Equal(t, http.StatusServiceUnavailable, code)
	counter := handler.metrics.requestCounter
	require.Equal(t, 1, int(prom_testutil.ToFloat64(counter.WithLabelValues("/-/ready", strconv.Itoa(http.StatusServiceUnavailable)))))

	handler.Ready()
	for range [2]int{} {
		code = getReady()
		require.Equal(t, http.StatusOK, code)
	}
	require.Equal(t, 2, int(prom_testutil.ToFloat64(counter.WithLabelValues("/-/ready", strconv.Itoa(http.StatusOK)))))
	require.Equal(t, 1, int(prom_testutil.ToFloat64(counter.WithLabelValues("/-/ready", strconv.Itoa(http.StatusServiceUnavailable)))))
}

func TestShutdownWithStaleConnection(t *testing.T) {
	dbDir, err := ioutil.TempDir("", "tsdb-ready")
	require.NoError(t, err)
	defer func() { require.NoError(t, os.RemoveAll(dbDir)) }()

	db, err := tsdb.Open(dbDir, nil, nil, nil, nil)
	require.NoError(t, err)

	timeout := 10 * time.Second

	opts := &Options{
		ListenAddress:  ":9090",
		ReadTimeout:    timeout,
		MaxConnections: 512,
		Context:        nil,
		Storage:        nil,
		LocalStorage:   &dbAdapter{db},
		TSDBDir:        dbDir,
		QueryEngine:    nil,
		ScrapeManager:  &scrape.Manager{},
		RuleManager:    &rules.Manager{},
		Notifier:       nil,
		RoutePrefix:    "/",
		ExternalURL: &url.URL{
			Scheme: "http",
			Host:   "localhost:9090",
			Path:   "/",
		},
		Version:  &PrometheusVersion{},
		Gatherer: prometheus.DefaultGatherer,
	}

	opts.Flags = map[string]string{}

	webHandler := New(nil, opts)

	webHandler.config = &config.Config{}
	webHandler.notifier = &notifier.Manager{}
	l, err := webHandler.Listener()
	if err != nil {
		panic(fmt.Sprintf("Unable to start web listener: %s", err))
	}

	closed := make(chan struct{})

	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		err := webHandler.Run(ctx, l, "")
		if err != nil {
			panic(fmt.Sprintf("Can't start web handler:%s", err))
		}
		close(closed)
	}()

	// Give some time for the web goroutine to run since we need the server
	// to be up before starting tests.
	time.Sleep(5 * time.Second)

	// Open a socket, and don't use it. This connection should then be closed
	// after the ReadTimeout.
	c, err := net.Dial("tcp", "localhost:9090")
	require.NoError(t, err)
	t.Cleanup(func() { require.NoError(t, c.Close()) })

	// Stop the web handler.
	cancel()

	select {
	case <-closed:
	case <-time.After(timeout + 5*time.Second):
		t.Fatalf("Server still running after read timeout.")
	}
}

func TestHandleMultipleQuitRequests(t *testing.T) {
	opts := &Options{
		ListenAddress:   ":9090",
		MaxConnections:  512,
		EnableLifecycle: true,
		RoutePrefix:     "/",
		ExternalURL: &url.URL{
			Scheme: "http",
			Host:   "localhost:9090",
			Path:   "/",
		},
	}
	webHandler := New(nil, opts)
	webHandler.config = &config.Config{}
	webHandler.notifier = &notifier.Manager{}
	l, err := webHandler.Listener()
	if err != nil {
		panic(fmt.Sprintf("Unable to start web listener: %s", err))
	}
	ctx, cancel := context.WithCancel(context.Background())
	closed := make(chan struct{})
	go func() {
		err := webHandler.Run(ctx, l, "")
		if err != nil {
			panic(fmt.Sprintf("Can't start web handler:%s", err))
		}
		close(closed)
	}()

	// Give some time for the web goroutine to run since we need the server
	// to be up before starting tests.
	time.Sleep(5 * time.Second)

	start := make(chan struct{})
	var wg sync.WaitGroup
	for i := 0; i < 3; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			<-start
			resp, err := http.Post("http://localhost:9090/-/quit", "", strings.NewReader(""))
			require.NoError(t, err)
			require.Equal(t, http.StatusOK, resp.StatusCode)
		}()
	}
	close(start)
	wg.Wait()

	// Stop the web handler.
	cancel()

	select {
	case <-closed:
	case <-time.After(5 * time.Second):
		t.Fatalf("Server still running after 5 seconds.")
	}
}

func cleanupTestResponse(t *testing.T, resp *http.Response) {
	_, err := io.Copy(ioutil.Discard, resp.Body)
	require.NoError(t, err)
	require.NoError(t, resp.Body.Close())
}

func cleanupSnapshot(t *testing.T, dbDir string, resp *http.Response) {
	snapshot := &struct {
		Data struct {
			Name string `json:"name"`
		} `json:"data"`
	}{}
	b, err := ioutil.ReadAll(resp.Body)
	require.NoError(t, err)
	require.NoError(t, json.Unmarshal(b, snapshot))
	require.NotZero(t, snapshot.Data.Name, "snapshot directory not returned")
	require.NoError(t, os.Remove(filepath.Join(dbDir, "snapshots", snapshot.Data.Name)))
	require.NoError(t, os.Remove(filepath.Join(dbDir, "snapshots")))
}


text:
"""Utility functions for processing images for delivery to Tesseract"""

import os

def image_to_scratch(im, scratch_image_name):
    """Saves image in memory to scratch file.  .bmp format will be read correctly by Tesseract"""
    im.save(scratch_image_name, dpi=(200,200))

def retrieve_text(scratch_text_name_root):
    inf = file(scratch_text_name_root + '.txt')
    text = inf.read()
    inf.close()
    return text

def perform_cleanup(scratch_image_name, scratch_text_name_root):
    """Clean up temporary files from disk"""
    for name in (scratch_image_name, scratch_text_name_root + '.txt', "tesseract.log"):
        try:
            os.remove(name)
        except OSError:
            pass


text:
require 'spec_helper'

describe "python support" do
  let(:filename) { 'test.py' }

  specify "two blank lines in the global scope" do
    set_file_contents <<-EOF
      def one():
          pass

      def two():
          pass
    EOF

    vim.search 'def one'
    vim.normal 'Vjjd'
    vim.search 'pass'
    vim.whitespaste_after

    assert_file_contents <<-EOF
      def two():
          pass

      def one():
          pass
    EOF
  end
end


text:
import { PluginShape } from '@seleniumhq/side-runtime'

const plugin: PluginShape = {
  commands: {
    customClick: {
      name: 'custom click',
      description:
        'This command should replace the standard click command when recording',
      target: {
        name: 'locator',
        description: 'The target of the original recorded click',
      },
      execute: async (command, driver) => {
        await driver.doClick(command.target as string, command.value || '')
      },
    },
  },
  hooks: {
    onAfterCommand: (input) => {
      console.log('After command', input)
    },
    onBeforeCommand: (input) => {
      console.log('Before command', input)
    },
    onMessage: (...args) => {
      console.log('Received message!', ...args)
    },
  },
}

export default plugin


text:
/ instanceStartDate;
@property (readonly) NSString* sourcePackageFamilyName;
- (void)reportCompleted:(NSString*)itemId;
- (void)reportCanceled;
- (void)reportError:(NSString*)value;
- (void)dismissUI;
@end

#endif // __WAAAReplaceAppointmentOperation_DEFINED__

// Windows.ApplicationModel.Appointments.AppointmentsProvider.RemoveAppointmentOperation
#ifndef __WAAARemoveAppointmentOperation_DEFINED__
#define __WAAARemoveAppointmentOperation_DEFINED__

WINRT_EXPORT
@interface WAAARemoveAppointmentOperation : RTObject
@property (readonly) NSString* appointmentId;
@property (readonly) id /* WFDateTime* */ instanceStartDate;
@property (readonly) NSString* sourcePackageFamilyName;
- (void)reportCompleted;
- (void)reportCanceled;
- (void)reportError:(NSString*)value;
- (void)dismissUI;
@end

#endif // __WAAARemoveAppointmentOperation_DEFINED__


text:
module Tick

  class Task < Tick::Base
    attr_accessor :billable, :budget, :closed_on, :name, :opened_on,
                  :position, :project, :project_id, :sum_hours, :user_count

    XML_PROPERTIES = %w( id billable budget closed_on name
                         opened_on position project_id sum_hours user_count )
  end

end


text:
<?php

namespace Scopefragger\Mappy\Commands;

use App\User;
use App\DripEmailer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * Class PurgeCommand
 *
 * Truncates the entire `mappy_urls` table when
 * `php artisan mappy:purge` is ran via command line
 *
 * @package Scopefragger\Mappy\Commands
 */
class PurgeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mappy:purge';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Purges the mappy_urls Table';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::table('mappy_urls')->truncate();
    }
}


text:
package main

import (
	"log"
	"os"

	"github.com/codegangsta/cli"
)

var Log *log.Logger

func main() {
	app := cli.NewApp()
	app.Name = "Intuition"
	app.Version = Version
	app.Usage = "Intuition API client"

	app.Flags = []cli.Flag{
		// TODO Impact log setup
		cli.BoolFlag{Name: "verbose", Usage: "Extends log output to debug level"},
		cli.StringFlag{Name: "addr", Value: "http://localhost:5000", Usage: "Telepathy HTTP API address"},
	}

	app.Action = func(c *cli.Context) {
		Log = log.New(os.Stdout, "[intuition] ", log.Ldate|log.Ltime|log.Lshortfile)

		api := NewIntuitionAPI(c.String("addr"))

		health, err := api.Health()
		Log.Printf("Error: %v\n", err)
		Log.Printf("State: %v\n", health.State)
		Log.Printf("Versions: %v\n", health.Version)
	}

	app.RunAndExitOnError()
}


text:
module AtomName(testAtomName) where

import Control.Monad
import Data.List(sort,nub)
import Data.Monoid
import Name.Names
import PackedString
import StringTable.Atom
import System.IO.Unsafe
import Test.QuickCheck
import qualified Data.ByteString as BS

instance Arbitrary NameType where
    arbitrary = oneof $ map return [ minBound .. ]

deriving instance Bounded NameType

instance Arbitrary Module where
    arbitrary = g `fmap` arbitrary where
        g xs = f (filter (';' /=) xs)
        f "" = f "X"
        f s = toModule s

-- test things dealing with atoms, names, and efficient strings.
qc s p = quickCheck $ label s p

testAtomName = do
    testAtom
    testName
    testPackedString

testAtom = do
    let atomraw = unsafePerformIO $ addrToAtom_ "hello"# 5#
    print atomraw
    when (show atomraw /= "hello") $
        fail "atomRaw"
    when (show (mempty :: Atom) /= "") $
        fail "atomEmpty"
    when (mempty /= toAtom "") $
        fail "atomEmpty2"

    let prop_atomneq xs ys = (xs /= ys) == (a1 /= a2) where
            a1 = toAtom xs
            a2 = toAtom (ys :: String)
        prop_atomcompare xs ys = (xs `compare` ys) == (a1 `atomCompare` a2) where
            a1 = toAtom xs
            a2 = toAtom (ys :: String)
        -- prop_atomIndex (xs :: String) = intToAtom (fromAtom a) == Just a where
        --     a = toAtom xs
        prop_atomneq' xs ys = (xs `compare` ys) == (fromAtom a1 `compare` (fromAtom a2 :: BS.ByteString)) where
            a1 = toAtom xs
            a2 = toAtom (ys :: String)
        prop_atomint xs = null xs || an > 0  where
            an = fromAtom $ toAtom (xs :: String) :: Int
        -- prop_atomii xs = Just xs == fromAtom `fmap` (intToAtom an) where
        --     an = fromAtom $ toAtom (xs :: String) :: Int
        prop_aappend (xs,ys) = (toAtom xs `mappend` toAtom ys) == toAtom ((xs::String) ++ ys)
        prop_aappend' (xs,ys) = fromAtom (toAtom xs `mappend` toAtom ys) == ((xs::String) ++ ys)
    qc "atom.id" $ \xs -> fromAtom (toAtom xs) == (xs::String)
    qc "atom.eq" $ \xs -> (toAtom xs) == toAtom (xs::String)
--    qc "atom.index" prop_atomIndex
    qc "atom.neq" prop_atomneq
    qc "atom.compare" prop_atomcompare
    qc "atom.eq'" prop_atomneq'
    qc "atom.int" prop_atomint
 --   qc "atom.ii" prop_atomii
    qc "atom.aapend" prop_aappend

--strings = [ "foo", "foobar", "baz", "", "bob"]
strings =  ["h","n\206^um\198(","\186","yOw\246$\187x#",";\221x<n","\201\209\236\213J\244\233","\189eW\176v\175\209"]

appendPS :: PackedString -> PackedString -> PackedString
appendPS = mappend

testPackedString = do
    let prop_psid xs = unpackPS (packString xs) == (xs::String)
--        prop_pslen xs = lengthPS (packString xs) == length (xs::String)
        prop_psappend (xs,ys) = (packString xs `appendPS` packString ys) == packString ((xs::String) ++ ys)
        prop_psappend' (xs,ys) = unpackPS (packString xs `appendPS` packString ys) == ((xs::String) ++ ys)
        prop_sort xs = sort (map packString xs) == map packString (sort xs)
    qc "PackedString.psid" prop_psid
    qc "PackedString.sort"  prop_sort
    qc "PackedString.psappend"  prop_psappend
    qc "PackedString.psappend'"  prop_psappend'
--    quickCheck prop_pslen
--    print $ map packString strings
--    print $ sort $ map packString strings
--    print $ sort strings
 --   pshash "Hello"
--    pshash "Foo"
--    pshash "Bar"
--    pshash "Baz"
--    pshash ""
--    pshash "\2321\3221x.y\3421\2222"

--pshash xs = putStrLn $ xs ++ ": " ++ show (hashPS (packString xs ))

testName = do
    let nn x = (not (null x)) && ';' `notElem` x
        prop_acc t a b = nn a && nn b ==> let
            n = toName t (a::String,b::String)
            un = toUnqualified n
            in  nameType n == t && getModule n == Just (toModule a) && getModule un == Nothing && show un == b && show n == (a ++ "." ++ b)
    qc "name.tofrom" $ \t a b -> nn a && nn b ==> fromName (toName t (a::String,b::String)) == (t,(a,b))
    qc "name.nameparts" $ \t a b -> nn b ==> nameParts (toName t (a,b)) == (t,a,b)
    qc "name.nameparts2" $ \t a b ->  nn b ==> nameParts (toName t (a,b)) == (t,Just a,b)
    qc "name.toUnqualified" $ \t a b -> nn a && nn b ==> toUnqualified (toName t (a,b)) == toName t b
    qc "name.getModule" $ \ t a b -> nn a && nn b ==> getModule (toName t (a,b)) == Just (toModule a)
    qc "name.getModule2" $ \ t b -> nn b ==> getModule (toName t b) == Nothing
    qc "name.getIdent" $ \t a b ->  nn b ==> getIdent (toName t (a :: Maybe Module,b)) == b
    qc "name.setModule" $ \t a b c ->  nn b && nn c ==> setModule (toModule c) (toName t (a :: Maybe Module,b)) == toName t (c,b)
    qc "name.show" $ \ t a b -> nn a && nn b ==> show (toName t (a,b)) == a ++ "." ++ b
    qc "name.quote" $ \ t a b -> nn a && nn b ==> let n = toName t (a,b) in fromQuotedName (quoteName n) == Just n
    qc "name.noquote" $ \ t a b -> t /= QuotedName && nn b ==> collect t (fromQuotedName (toName t (a :: Maybe Module,b)) == Nothing)
    qc "name.acc" prop_acc
    qc "name.tup" $ \n -> n >= 0 ==> fromUnboxedNameTuple (unboxedNameTuple RawType n) == Just n
    qc "name.overlap" $ \t -> (isTypeNamespace t,isValNamespace t) /= (True,True)


text:
package org.ovirt.engine.ui.common.widget.form;

import org.ovirt.engine.ui.common.CommonApplicationConstants;
import org.ovirt.engine.ui.common.gin.AssetProvider;
import org.ovirt.engine.ui.common.widget.label.StringValueLabel;
import org.ovirt.engine.ui.uicompat.external.StringUtils;

import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;

/**
 * Represents a name/value item rendered within an {@link AbstractFormPanel}.
 */
public class FormItem {

    /**
     * If {@link #showDefaultValue} returns {@code true}, show the default value, otherwise show the actual value.
     */
    public interface DefaultValueCondition {

        boolean showDefaultValue();

    }

    private static final CommonApplicationConstants constants = AssetProvider.getConstants();

    private static final int UNASSIGNED_ROW = -1;

    private AbstractFormPanel formPanel;

    private int row;
    private final int column;

    private final String isAvailablePropertyName;
    private boolean isAvailable = true;

    private String name;
    private Widget valueWidget;

    /**
     * Replaces provided value widget if {@code defaultValueCondition} holds {@code true}.
     */
    private StringValueLabel defaultValueLabel;
    private DefaultValueCondition defaultValueCondition;

    /**
     * Replaces resolved value widget if the widget's text is {@code null} or empty string.
     */
    private final StringValueLabel emptyValueLabel = new StringValueLabel(constants.unAvailablePropertyLabel());

    private boolean autoPlacement = false;
    private int autoPlacementRow = UNASSIGNED_ROW;

    public FormItem(int row, int column) {
        this("", new StringValueLabel(), row, column); //$NON-NLS-1$
    }

    public FormItem(String name, Widget valueWidget, int column) {
        this(name, valueWidget, 0 , column, null, true);
        withAutoPlacement();
    }

    public FormItem(String name, Widget valueWidget, int column, boolean isAvailable) {
        this(name, valueWidget, 0 , column, null, isAvailable);
        withAutoPlacement();
    }

    public FormItem(String name, Widget valueWidget, int row, int column) {
        this(name, valueWidget, row, column, null);
    }

    public FormItem(String name, Widget valueWidget, int row, int column, boolean isAvailable) {
        this(name, valueWidget, row, column, null, isAvailable);
    }

    public FormItem(String name, Widget valueWidget, int row, int column, String isAvailablePropertyName) {
        this(name, valueWidget, row, column, isAvailablePropertyName, true);
    }

    public FormItem(String name,
            Widget valueWidget,
            int row,
            int column,
            String isAvailablePropertyName,
            boolean isAvailable) {
        this.row = row;
        this.column = column;
        this.isAvailablePropertyName = isAvailablePropertyName;
        this.valueWidget = valueWidget;
        this.isAvailable = isAvailable;

        // Add trailing ':' to the item name, if necessary
        if (name != null && !name.trim().isEmpty() && !name.endsWith(":")) { //$NON-NLS-1$
            this.name = name + ":"; //$NON-NLS-1$
        } else {
            this.name = name;
        }
    }

    /**
     * Use {@code defaultValue} based on dynamic {@code defaultValueCondition}.
     */
    public FormItem withDefaultValue(String defaultValue, DefaultValueCondition defaultValueCondition) {
        this.defaultValueLabel = new StringValueLabel(defaultValue);
        this.defaultValueCondition = defaultValueCondition;
        return this;
    }

    /**
     * Set custom "empty" value shown when the resolved value widget's text is {@code null} or empty string.
     */
    public FormItem withEmptyValue(String emptyValue) {
        emptyValueLabel.setValue(emptyValue);
        return this;
    }

    /**
     * Automatically place this form item into next available row for the given column.
     * <p>
     * This works only when the form item is {@linkplain #getIsAvailable available} when being added to the
     * {@link AbstractFormPanel}. Otherwise, the form item is marked as dead and will be discarded by the form panel.
     *
     * @see #setFormPanel(AbstractFormPanel)
     */
    public FormItem withAutoPlacement() {
        this.autoPlacement = true;
        return this;
    }

    public void setFormPanel(AbstractFormPanel formPanel) {
        this.formPanel = formPanel;

        // Compute autoPlacementRow if this item is available
        if (autoPlacement && getIsAvailable()) {
            this.autoPlacementRow = formPanel.getNextAvailableRow(column);
        }
    }

    /**
     * If {@code false}, this form item shouldn't be processed by the {@link AbstractFormPanel}.
     */
    public boolean isValid() {
        if (autoPlacement && autoPlacementRow == UNASSIGNED_ROW) {
            // Failed to assign autoPlacementRow
            return false;
        }
        return true;
    }

    public void update() {
        assert formPanel != null : "FormItem must be adopted by FormPanel"; //$NON-NLS-1$
        formPanel.updateFormItem(this);
    }

    public int getRow() {
        return (autoPlacement && autoPlacementRow != UNASSIGNED_ROW) ? autoPlacementRow : row;
    }

    public int getColumn() {
        return column;
    }

    public String getIsAvailablePropertyName() {
        return isAvailablePropertyName;
    }

    public boolean getIsAvailable() {
        return isAvailable;
    }

    public void setIsAvailable(boolean isAvailable) {
        this.isAvailable = isAvailable;
        update();
    }

    public String getName() {
        return name;
    }

    /**
     * Resolves the appropriate value widget for this form item based on {@link DefaultValueCondition} (if any).
     */
    public Widget resolveValueWidget() {
        boolean showDefaultValue = defaultValueCondition != null && defaultValueCondition.showDefaultValue();
        Widget resolvedValueWidget = showDefaultValue ? defaultValueLabel : valueWidget;

        boolean showEmptyValue = (resolvedValueWidget instanceof HasText)
                && StringUtils.isEmpty(((HasText) resolvedValueWidget).getText());
        return showEmptyValue ? emptyValueLabel : resolvedValueWidget;
    }

}


text:
#ifndef _LIVE_JOB_COUNTERS_H
#define _LIVE_JOB_COUNTERS_H

// The schedd will have one of these structures per owner, and one for the schedd as a whole
// these counters are new for 8.7, and used with the code that keeps live counts of jobs
// by tracking state transitions
//
struct LiveJobCounters {
  int JobsSuspended;
  int JobsIdle;             // does not count Local or Scheduler universe jobs, or Grid jobs that are externally managed.
  int JobsRunning;
  int JobsRemoved;
  int JobsCompleted;
  int JobsHeld;
  int SchedulerJobsIdle;
  int SchedulerJobsRunning;
  int SchedulerJobsRemoved;
  int SchedulerJobsCompleted;
  int SchedulerJobsHeld;
  void clear_counters() { memset(this, 0, sizeof(*this)); }
  void publish(ClassAd & ad, const char * prefix) const;
  LiveJobCounters()
	: JobsSuspended(0)
	, JobsIdle(0)
	, JobsRunning(0)
	, JobsRemoved(0)
	, JobsCompleted(0)
	, JobsHeld(0)
	, SchedulerJobsIdle(0)
	, SchedulerJobsRunning(0)
	, SchedulerJobsRemoved(0)
	, SchedulerJobsCompleted(0)
	, SchedulerJobsHeld(0)
  {}
};

void IncrementLiveJobCounter(LiveJobCounters & num, int universe, int status, int increment /*, JobQueueJob * job*/);

#endif


text:
package com.example.orm.repository;

import com.example.orm.model.LunchMenu;
import com.example.orm.model.Order;
import com.example.orm.model.Restaurant;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.List;

@Repository
public interface OrderRepository extends CrudRepository<Order, Long> {

    public List<Order> findByLunchMenuRestaurant(Restaurant restaurant);

    public List<Order> findByLunchMenuRestaurantAndUpdatedBetween(Restaurant restaurant, Timestamp start, Timestamp end);

    public Order findByCustomerLoginAndUpdatedBetween(String login, Timestamp start, Timestamp end);

    public void deleteByCustomerLoginAndUpdatedBetween(String login, Timestamp start, Timestamp end);

}


text:
package de.slgdev.leoapp.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLiteConnectorITProblem extends SQLiteOpenHelper {

    public static final  String TABLE_DECISIONS   = "Entscheidungen";
    public static final  String DECISION_SUBJECT  = "titel";
    public static final  String DECISIONS_CONTENT = "adressat";

    private static final String DATABASE_NAME     = "problems.db";

    public SQLiteConnectorITProblem(Context c) {
        super(c, DATABASE_NAME, null, 5);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_DECISIONS
                + " (" +
                DECISION_SUBJECT + " VARCHAR(255) NOT NULL, " +
                DECISIONS_CONTENT + " TEXT NOT NULL," +
                " CONSTRAINT unique_subj UNIQUE ("+DECISION_SUBJECT+") " +
                ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_DECISIONS);
        onCreate(db);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }

    public ContentValues getContentValues(String subject, String content) {
        ContentValues values = new ContentValues();
        values.put(DECISION_SUBJECT, subject);
        values.put(DECISIONS_CONTENT, content);
        return values;
    }

}


text:
This game was created Doug McInnes. His code can be found
[here](https://github.com/dmcinnes/HTML5-Asteroids), and you can play his
version of the game online at his website
[here](http://dougmcinnes.com/2010/05/12/html-5-asteroids/).

Caroline Buckey and Sarah Spikes modified the repository to create exercises for
the Udacity course [Version Control Using Git and Github](TODO). These
modifications included introducing bugs and other changes into Doug's commits he
did not in fact create! The bugs are intended to give learners experience using
Git to find the commit where a bug was introduced. To play the modified version
of the game, simply open the index.html file in your web browser.

Many thanks to Doug for creating this awesome game.

merge it


text:
<?php

require_once( '../../../../bootstrap.php' );
require_once( 'Light/Database/Object/Cache/Factory.php' );
require_once( 'CTM/Site.php' );
require_once( 'CTM/Test/Suite/Selector.php' );
require_once( 'CTM/Test/Selector.php' );
require_once( 'CTM/Test/Suite/Plan.php' );
require_once( 'CTM/Test/Suite/Plan/Selector.php' );

class CTM_Site_Test_Suite_Plan extends CTM_Site {

    public function setupPage() {
        $this->setPageTitle('Edit Test Suite Plan');
        return true;
    }

    public function handleRequest() {

        $this->requiresAuth();

        $id                     = $this->getOrPost( 'id', '' );
        $action                 = $this->getOrPost( 'action', '' );
        $suite_id               = $this->getOrPost( 'suite_id', '' );
        $testId                = $this->getOrPost( 'testId', '' );
        $testSuiteId          = $this->getOrPost( 'testSuiteId', '' );
        $test_suite_plan_id     = $this->getOrPost( 'test_suite_plan_id', '' );

        // echo "id: $id action: $action suite_id: $suite_id\n";
        try {
            $sel = new CTM_Test_Suite_Selector();
            $and_params = array( new Light_Database_Selector_Criteria( 'id', '=', $id ) );
            $test_suites = $sel->find( $and_params );
        } catch ( Exception $e ) {
        }

        $test_suite = null;
        if ( count( $test_suites ) == 1 ) {
            $test_suite = $test_suites[0];
        } else {
            // did not find the test suite in question.
            return true;
        }

        if ( $action == 'remove_from_plan' ) {
            $target_test = null;
            try {

                // remove the target...
                $sel = new CTM_Test_Suite_Plan_Selector();

                $and_params = array( new Light_Database_Selector_Criteria( 'id', '=', $test_suite_plan_id ) );
                $test_plans = $sel->find( $and_params );

                if ( count( $test_plans ) == 1 ) {
                    $target_test = $test_plans[0];
                    $target_test->remove();
                } else {
                    return true;
                }

                // resequence the testOrder
                $and_params = array( new Light_Database_Selector_Criteria( 'testSuiteId', '=', $testSuiteId ) );
                $or_params = array();
                $field_order = array( 'testOrder' );

                $test_plans = $sel->find( $and_params, $or_params, $field_order );

                $testOrderId = 0;
                foreach ( $test_plans as $test_plan ) {
                    $testOrderId++;
                    $test_plan->testOrder = $testOrderId;
                    $test_plan->save();
                }

            } catch ( Exception $e ) {
            }
            $test_suite->saveRevision();
            return true;
        }

        // Do updates if needed.
        if ( $action == 'move_item_down' || $action == 'move_item_up' ) {
            // lookup the test plan id in question.
            $test_plans = null;
            try {
                $sel = new CTM_Test_Suite_Plan_Selector();
                $and_params = array( new Light_Database_Selector_Criteria( 'testSuiteId', '=', $testSuiteId ) );
                $or_params = array();
                $field_order = array( 'testOrder' );
                $test_plans = $sel->find( $and_params, $or_params, $field_order );
            } catch ( Exception $e ) {
            }

            if ( count( $test_plans ) > 0 ) {

                // find the target item first.
                $target_item = null;
                $high_id = 0;

                foreach ( $test_plans as $test_plan ) {
                    if ( $test_plan->id == $test_suite_plan_id ) {
                        $target_item = $test_plan;
                    }
                    if ( $high_id < $test_plan->testOrder ) {
                        $high_id = $test_plan->testOrder;
                    }
                }

                if ( ! isset( $target_item ) ) {
                    return true;
                }

                $current_order_id = $target_item->testOrder;

                if ( $action == 'move_item_down' ) {

                    // this item is already at the max
                    if ( $target_item->testOrder == $high_id ) {
                        return true;
                    }

                    foreach ( $test_plans as $test_plan ) {
                        // find the next item and drop it by one
                        if ( $test_plan->testOrder == ( $current_order_id + 1) ) {
                            $test_plan->testOrder = $current_order_id;
                            $test_plan->save();
                        }
                    }

                    $target_item->testOrder = $target_item->testOrder + 1;
                    $target_item->save();

                } // move_item_down

                if ( $action == 'move_item_up' ) {

                    if ( $target_item->testOrder == 1 ) {
                        return true;
                    }

                    foreach ( $test_plans as $test_plan ) {
                        // find the previous item and bump it up by one
                        if ( $test_plan->testOrder == ( $current_order_id - 1 ) ) {
                            $test_plan->testOrder = $current_order_id;
                            $test_plan->save();
                        }
                    }

                    $target_item->testOrder = $target_item->testOrder - 1;
                    $target_item->save();

                } // move_item_up

            }

            $test_suite->saveRevision();
            return true;
        }

        // Determine the high id
        $high_id = 0;

        $test_plans = null;
        try {
            $sel = new CTM_Test_Suite_Plan_Selector();
            $and_params = array( new Light_Database_Selector_Criteria( 'testSuiteId', '=', $id ) );
            $test_plans = $sel->find( $and_params );
        } catch ( Exception $e ) {
        }

        if ( count( $test_plans ) > 0 ) {
            foreach ( $test_plans as $test_plan ) {
                if ( $high_id < $test_plan->testOrder ) {
                    $high_id = $test_plan->testOrder;
                }
            }
        }

        if ( $action == 'add_suite_to_plan' && isset( $suite_id ) && $suite_id > 0 ) {
            $test_plan = new CTM_Test_Suite_Plan();
            $test_plan->testSuiteId = $id;
            $test_plan->linkedId = $suite_id;
            $test_plan->testOrder = ( $high_id + 1 );
            $test_plan->testSuitePlanTypeId = 1; // this is a suite
            $test_plan->save();
            $test_suite->saveRevision();
            return true;
        }

        if ( $action == 'add_test_to_plan' && isset( $testId ) && $testId > 0 ) {
            $test_plan = new CTM_Test_Suite_Plan();
            $test_plan->testSuiteId = $id;
            $test_plan->linkedId = $testId;
            $test_plan->testOrder = ( $high_id + 1 );
            $test_plan->testSuitePlanTypeId = 2; // this is a test
            $test_plan->save();
            $test_suite->saveRevision();
            return true;
        }

        return true;

    }

    public function displayBody() {
        $id                   = $this->getOrPost( 'id', '' );
        $testSuiteFolderId    = $this->getOrPost( 'testSuiteFolderId', '' );
        $testFolderId         = $this->getOrPost( 'testFolderId', '' );

        $rows = null;
        $test_suite = null;
        $test_suite_plans = null;
        $test_suite_plan_type_cache = null;
        try {
            $sel = new CTM_Test_Suite_Selector();

            $and_params = array( new Light_Database_Selector_Criteria( 'id', '=', $id ) );

            $rows = $sel->find( $and_params );

            if ( isset( $rows[0] ) ) {
                $test_suite = $rows[0];

                // pull up the plan
                $test_suite_plan_type_cache = Light_Database_Object_Cache_Factory::factory( 'CTM_Test_Suite_Plan_Type_Cache' );

                $sel = new CTM_Test_Suite_Plan_Selector();
                $and_params = array( new Light_Database_Selector_Criteria( 'testSuiteId', '=', $id ) );
                $or_params = array();
                $field_order = array( 'testOrder' );
                $test_suite_plans = $sel->find( $and_params, $or_params, $field_order );

            }
        } catch ( Exception $e ) {
        }

        if ( isset( $test_suite ) ) {

            if ( $testSuiteFolderId == '' ) {
                $testSuiteFolderId = $test_suite->testSuiteFolderId;
            }

            if ( $testFolderId == '' ) {
                $testFolderId = 1;
            }

            $this->printHtml( '
' );
            $this->printHtml( '
' );

            $this->printHtml( '
' );
            $this->printHtml( 'Plan Test Suite	' );
            $this->printHtml( '
' );

            $this->printHtml( '
' );
            $this->printHtml( 'Name: ' . $this->escapeVariable( $test_suite->name ) . '	' );
            $this->printHtml( '
' );

            $this->oddEvenReset();

            $this->printHtml( '
' );
            $this->printHtml( 'Current Test Plan	' );
            $this->printHtml( '
' );

            $this->printHtml( '
' );
            $this->printHtml( 'Order	' );
            $this->printHtml( 'Type	' );
            $this->printHtml( 'Name	' );
            $this->printHtml( 'Action	' );
            $this->printHtml( '
' );

            if ( count( $test_suite_plans ) > 0 ) {

                $plan_type_cache = Light_Database_Object_Cache_Factory::factory( 'CTM_Test_Suite_Plan_Type_Cache' );
                $test_suite_cache = Light_Database_Object_Cache_Factory::factory( 'CTM_Test_Suite_Cache' );
                $test_cache = Light_Database_Object_Cache_Factory::factory( 'CTM_Test_Cache' );

                $high_id = 0;

                foreach ( $test_suite_plans as $test_suite_plan ) {
                    if ( $high_id < $test_suite_plan->testOrder ) {
                        $high_id = $test_suite_plan->testOrder;
                    }
                }

                foreach ( $test_suite_plans as $test_suite_plan ) {

                    $class = $this->oddEvenClass();

                    $plan_type = $plan_type_cache->getById( $test_suite_plan->testSuitePlanTypeId );

                    $test_suite = null;
                    if ( $plan_type->name == 'suite' ) {
                        $test_suite = $test_suite_cache->getById( $test_suite_plan->linkedId );
                    }

                    $test = null;
                    if ( $plan_type->name == 'test' ) {
                        $test = $test_cache->getById( $test_suite_plan->linkedId );
                    }

                    $this->printHtml('
');
                    $this->printHtml('' );
                    if ( $test_suite_plan->testOrder != 0 && $test_suite_plan->testOrder != $high_id ) {
                        $this->printHtml( 'getBaseUrl() . '/test/suite/plan/?id=' . $id . '&action=move_item_down&test_suite_plan_id=' . $test_suite_plan->id . '&testSuiteId=' . $test_suite_plan->testSuiteId . '">↓' );
                    } else {
                        $this->printHtml( ' ' );
                    }
                    $this->printHtml( $test_suite_plan->testOrder );
                    if ( $test_suite_plan->testOrder != 0 && $test_suite_plan->testOrder > 1 ) {
                        $this->printHtml( 'getBaseUrl() . '/test/suite/plan/?id=' . $id . '&action=move_item_up&test_suite_plan_id=' . $test_suite_plan->id . '&testSuiteId=' . $test_suite_plan->testSuiteId . '">↑' );
                    } else {
                        $this->printHtml( ' ' );
                    }
                    $this->printHtml( '	' );
                    $this->printHtml('' . $plan_type->name . '	' );
                    if ( isset( $test_suite ) ) {
                        $this->printHtml('' . $this->escapeVariable( $test_suite->name ) . '	' );
                    } else if ( isset( $test ) ) {
                        $this->printHtml('' . $this->escapeVariable( $test->name ) . '	' );
                    } else {
                        $this->printHtml('Could not find suite or test associated.	' );
                    }
                    $this->printHtml( 'getBaseUrl() . '/test/suite/plan/?id=' . $id . '&test_suite_plan_id=' . $test_suite_plan->id . '&testSuiteId=' . $test_suite_plan->testSuiteId . '&action=remove_from_plan" class="ctmButton">Remove from plan	' );
                    $this->printHtml('
');
                }
            } else {
                $this->printHtml( '
' );
                $this->printHtml( '- There is no test plan for this suite -	' );
                $this->printHtml( '
' );
            }

            $this->printHtml( '
' );
            $this->printHtml( '
' );

            $this->printHtml( '
' );

            $this->printHtml( '
' );

            $this->printHtml( '
' );
            $this->printHtml( 'Add Items to Plan	' );
            $this->printHtml( '
' );

            // --------------------------------------------------------------------------------
            // Look up the chain as needed.

            // --------------------------------------------------------------------------------

            $this->oddEvenReset();

            $this->printHtml( '
' );
            $this->printHtml( 'Test Suites	' );
            $this->printHtml( '
' );

            $this->_localDisplayBreadCrumb($id, $testSuiteFolderId, true);

            $this->printHtml( '
' );
            $this->printHtml( 'ID	' );
            $this->printHtml( 'Name	' );
            $this->printHtml( 'Action	' );
            $this->printHtml( '
' );

            $suite_rows = null;
            try {
                $sel = new CTM_Test_Suite_Selector();
                $and_params = array(
                        new Light_Database_Selector_Criteria( 'testSuiteFolderId', '=', $testSuiteFolderId ),
                        // we exclude ourselves from suites.
                        new Light_Database_Selector_Criteria( 'id', '!=', $id )
                        );
                $suite_rows = $sel->find( $and_params );
            } catch ( Exception $e ) {
            }

            if ( count( $suite_rows ) > 0 ) {
                foreach ( $suite_rows as $suite_row ) {
                    $class = $this->oddEvenClass();

                    $this->printHtml( '
' );
                    $this->printHtml( '' . $suite_row->id . '	' );
                    $this->printHtml( '' . $this->escapeVariable( $suite_row->name ) . '	' );
                    $this->printHtml( 'getBaseUrl() . '/test/suite/plan/?id=' . $id . '&testFolderId=' . $testFolderId . '&action=add_suite_to_plan&suite_id=' . $suite_row->id . '" class="ctmButton">Add to plan	' );
                    $this->printHtml( '
' );

                }
            } else {
                $this->printHtml( '
' );
                $this->printHtml( '- No suites defined -	' );
                $this->printHtml( '
' );
            }

            // pull all the tests in for this folder.
            $test_rows = null;
            try {
                $sel = new CTM_Test_Selector();
                $and_params = array( new Light_Database_Selector_Criteria( 'testFolderId', '=', $testFolderId ) );
                $test_rows = $sel->find( $and_params );
            } catch ( Exception $e ) {
            }

            $this->oddEvenReset();

            $this->printHtml( '
' );
            $this->printHtml( 'Tests	' );
            $this->printHtml( '
' );

            $this->_localDisplayBreadCrumb($id, $testFolderId, false );

            $this->printHtml( '
' );
            $this->printHtml( 'ID	' );
            $this->printHtml( 'Name	' );
            $this->printHtml( 'Action	' );
            $this->printHtml( '
' );

            if ( count( $test_rows ) > 0 ) {
                foreach ( $test_rows as $test_row ) {
                    $class = $this->oddEvenClass();
                    $this->printHtml( '
' );
                    $this->printHtml( '' . $test_row->id . '	' );
                    $this->printHtml( '' . $this->escapeVariable( $test_row->name ) . '	' );
                    $this->printHtml( 'getBaseUrl() . '/test/suite/plan/?id=' . $id . '&testFolderId=' . $testFolderId . '&action=add_test_to_plan&testId=' . $test_row->id . '" class="ctmButton">Add to plan	' );
                    $this->printHtml( '
' );
                }
            } else {
                $this->printHtml( '
' );
                $this->printHtml( '- No tests defined -	' );
                $this->printHtml( '
' );
            }

            $this->printHtml( '
' );
            $this->printHtml( '
' );

        }

        return true;
    }

    private function _localDisplayBreadCrumb($id, $testFolderId, $isSuite ) {

        $folderCache = null;
        if ($isSuite == true ) {
            $folderCache = Light_Database_Object_Cache_Factory::factory( 'CTM_Test_Suite_Folder_Cache' );
        } else {
            $folderCache = Light_Database_Object_Cache_Factory::factory( 'CTM_Test_Folder_Cache' );
        }

        $parents = array();
        $folderCache->getFolderParents( $testFolderId, $parents );
        $parents = array_reverse( $parents );
        $parents_cnt = count( $parents );

        $children = array();
        if ( $parents_cnt > 0 ) {
            $children = $folderCache->getFolderChildren( $parents[ ($parents_cnt-1) ]->id );
        }

        $folder_path = '';
        $current_parent = 0;
        foreach ( $parents as $parent ) {
            $current_parent++;
            $folder_path .= '/';
            $folder_path .= 'getBaseUrl() . '/test/suite/plan/?id=' . $id;
            if ( $isSuite == true ) {
                $folder_path .= '&testSuiteFolderId=' . $parent->id;
            } else {
                $folder_path .= '&testFolderId=' . $parent->id;
            }
            $folder_path .= '">' . $parent->name . '';
        }

        $this->printHtml( '
' );
        $this->printHtml( '<form action="' . $this->getBaseUrl() . '/test/suite/plan/" method="POST">' );
        $this->printHtml( 'Current folder path: ' .  $folder_path );
        if ( count( $children ) > 0 ) {
            $this->printHtml( '<input type="hidden" name="id" value="' . $id . '">' );
            if ( $isSuite == true ) {
                $this->printHtml( 'Switch to Suite Folder: ' );
                $this->printHtml( '<select name="testSuiteFolderId">' );
            } else {
                $this->printHtml( 'Switch to Test Folder: ' );
                $this->printHtml( '<select name="testFolderId">' );
            }
            $this->printHtml( '<option value="0">Pick a sub-folder</option>' );
            foreach ( $children as $child ) {
                $this->printHtml( '<option value="' . $child->id . '">' . $this->escapeVariable( $child->name ) . '</option>' );
            }
            $this->printHtml( '</select>' );
            $this->printHtml( '<input type="submit" value="Go!">' );
        }
        $this->printHtml( '	' );
        $this->printHtml( '</form>' );
        $this->printHtml('
');
    }

}

$test_suite_plan_obj = new CTM_Site_Test_Suite_Plan();
$test_suite_plan_obj->displayPage();


text:
using System;
using Android.App;
using Android.Content;
using Android.Support.V7.App;

namespace TechTalk.Droid
{
    public interface IServiceConnectionBinder
    {
        event EventHandler<ServiceEventArgs> ConnectionChanged;

        void Bind(Context context);

        void Undbind(Context context);

        void Register<T, G>() where T : AppCompatActivity where G : Service;
    }
}


text:
package test.com.moss.apidoc.controller;

public class HomeControllerTests {

}


text:
<?php
namespace Rxnet\Dns;

class RemoteNotFoundException extends \Exception
{

}


text:
    {%- if site.footer_show_references -%}
       - {{ site.references_title | default: "References on request" }}
    {%- endif -%}


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

/**
 * @author Alexey Kudravtsev
 */
public class MakeMethodConstructorFix implements IntentionAction {
  private final PsiMethod myMethod;

  public MakeMethodConstructorFix(PsiMethod method) {
    myMethod = method;
  }

  @Override
  @NotNull
  public String getText() {
    return QuickFixBundle.message("convert.method.to.constructor");
  }

  @Override
  @NotNull
  public String getFamilyName() {
    return getText();
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    return myMethod.isValid() && myMethod.getReturnTypeElement() != null && myMethod.getManager().isInProject(myMethod);
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    if (!FileModificationService.getInstance().preparePsiElementForWrite(myMethod)) return;
    myMethod.getReturnTypeElement().delete();
  }

  @Override
  public boolean startInWriteAction() {
    return true;
  }
}


text:
<?php
if(count(@$direction)==0) {
    ?>

            Мутахассислик коди

                <input type="text" class="form-control" name="mutax_kodi" id="mutax_kodi" maxlength="8" required/>

        Мутахассислик номи

            <input type="text" class="form-control" name="mutax_kodi_name" id="mutax_kodi_name" maxlength="250" required/>

    <?php
} else
{

    foreach($direction as $directionn) {?>

            <input type="hidden" name="direction" value="<?php echo $directionn['mutax_kodi_id'];?>" />

                Мутахассислик коди

                    <input type="text" class="form-control" name="mutax_kodi" id="mutax_kodi" maxlength="8"  value="<?php echo $directionn['mutax_kodi'];?> " required/>

                Мутахассислик номи

                    <input type="text" class="form-control" name="mutax_kodi_name" id="mutax_kodi_name" maxlength="250" value="<?php echo $directionn['mutax_kodi_name'];?>" required/>

    <?php } }?>


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_RegionInstanceGroupManagers_Get_async]
    using Google.Cloud.Compute.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedRegionInstanceGroupManagersClientSnippets
    {
        /// <summary>Snippet for GetAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetRequestObjectAsync()
        {
            // Create client
            RegionInstanceGroupManagersClient regionInstanceGroupManagersClient = await RegionInstanceGroupManagersClient.CreateAsync();
            // Initialize request argument(s)
            GetRegionInstanceGroupManagerRequest request = new GetRegionInstanceGroupManagerRequest
            {
                Region = "",
                Project = "",
                InstanceGroupManager = "",
            };
            // Make the request
            InstanceGroupManager response = await regionInstanceGroupManagersClient.GetAsync(request);
        }
    }
    // [END compute_v1_generated_RegionInstanceGroupManagers_Get_async]
}


text:
FROM biocontainers/biocontainers:vdebian-buster-backports_cv1
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL    software="sspace" \
    base_image="biocontainers/biocontainers:vdebian-buster-backports_cv1" \
    container="sspace" \
    about.summary="scaffolding pre-assembled contigs after extension" \
    about.home="https://github.com/nsoranzo/sspace_basic" \
    software.version="2.1.1dfsg-4-deb" \
    upstream.version="2.1.1" \
    version="1" \
    extra.identifiers.biotools="sspace" \
    about.copyright="2010 Marten Boetzer and Walter Pirovano <walter.pirovano@baseclear.com>" \
    about.license="GPL-2+" \
    about.license_file="/usr/share/doc/sspace/copyright" \
    extra.binaries="/usr/bin/sspace" \
    about.tags=""

USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && (apt-get install -t buster-backports -y sspace || apt-get install -y sspace) && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker


text:
import sys
import os

import #APPNAME.lib.powlib
from #APPNAME.lib.pow_objects import Migration
from #APPNAME.models.copow_log import Copow_log

migration = Migration()

def up():
    """ up method will be executed when running do_migrate -d up"""
    copow_log = Copow_log( schema  = {
           "time"       :      { "type" : "date" },
           "logstr"     :      { "type" : "string" },
           "user  "     :      { "type" : "string" }
           #"a_more_complex_one"    :       { "type" : "Text" , "index" : True, "default" : "something"}
      }
    )

    # creates the tabke (collection) and the schema in migrations/schemas/
    # creates a collection named log with a maximum size of 5 megabytes and a maximum of 5000 documents.
    # See: http://docs.mongodb.org/manual/reference/method/db.createCollection/
    #migration.create_table(copow_log, capped=True, size=5242880, max=5000, postfix="_#APPNAME"  )
    migration.create_table(copow_log, capped=True, size=5242880, max=5000 )

    print("  Successfully migrated copow_log -> mehtod: up()")

def down():
    """ down method will be executed when running do_migrate -d down"""
    # drops the table (collection) and removes the schema from migrations/schemas/
    copow_log = Copow_log()
    migration.drop_table(copow_log)
    print("  Successfully migrated copow_log -> mehtod: down()")


text:
mysqldump -h SOURCE_HOST  -uUSERNAME -pPASSWORD --all-databases | gzip > /PATH_TO_DIR/YOUR_FILE_NAME.gz --verbose

#e.g.
#mysqldump -h prod1-rds1-master.servers.com -uroot -proot --all-databases | gzip > /Users/nikunj/projects/picasso/db/rds1.gz --verbose


text:
package org.apache.felix.dm.lambda.callbacks;

import java.io.Serializable;

/**
 * Base interface for serializable lambdas. Some lambda must be serializable in order to allow to introspect their type and method signatures.
 */
public interface SerializableLambda extends Serializable {
}


text:
from creer.utilities import extend, copy_dict, sort_dict_keys
import creer.default as default
import creer.validate

def _inherit_into(obj, parent_class, game_objects):
    parent = game_objects[parent_class]
    for parm_type in ["attributes", "functions"]:
        for parm_key, parm_parms in parent[parm_type].items():
            obj['inherited' + parm_type.capitalize()][parm_key] = copy_dict(parm_parms, {
                'inheritedFrom': parent_class
            })

    for parent_parent_class in parent['parentClasses']:
        _inherit_into(obj, parent_parent_class, game_objects)

def build(datas):
    parent_keys = ['main']
    parent_datas = []
    while len(parent_keys) > 0:
        parent_key = parent_keys.pop()
        parent_data = datas[parent_key]
        parent_datas.append(parent_data)

        # now look if that data had parent data to continue investigating
        if not '_parentDatas' in parent_data:
            parent_data['_parentDatas'] = []

        for new_parent_key in parent_data['_parentDatas']:
            parent_keys.append(new_parent_key)

    parent_datas.append(datas['base']) # all games get the base data

    # merge all the prototypes inherited into one prototype
    prototype = {}
    for parent_data in reversed(parent_datas):
        extend(prototype, parent_data)

    # extend won't do this correctly. multiple data may pre-define parent classes and will get overwritten via extend. this appends each additional class name
    for proto_key, proto in prototype.items():
        if proto_key[0] == "_":
            continue

        newServerParentClasses = []
        if 'serverParentClasses' in proto:
            for parent_data in reversed(parent_datas):
                if proto_key in parent_data and 'serverParentClasses' in parent_data[proto_key]:
                    for parent_class_name in parent_data[proto_key]['serverParentClasses']:
                        newServerParentClasses.append(parent_class_name)
        proto['serverParentClasses'] = newServerParentClasses

    game_objects = {}
    game = prototype['Game']
    if not 'name' in game:
        raise Exception("Error: no name given for the main game data. Name your Game!!!")
    default.game_obj(game, "Game")

    ai = prototype['AI']
    del prototype['AI']
    default.functions_for(ai, "AI")

    if len(game['serverParentClasses']) == 0:
        game['serverParentClasses'].append("BaseGame")

    for obj_key, obj in prototype.items():
        if obj_key == "Game" or obj_key[0] == "_":
            continue

        if obj_key == "GameObject" and len(obj['serverParentClasses']) == 0:
            obj['serverParentClasses'] = [ 'BaseGameObject' ]

        default.game_obj(obj, obj_key)

        if obj_key != "GameObject" and len(obj['parentClasses']) == 0:
            obj['parentClasses'].append("GameObject")

        game_objects[obj_key] = obj

    for obj_key, obj in (copy_dict(game_objects, {'Game': game}).items()):
        obj['inheritedAttributes'] = {}
        obj['inheritedFunctions'] = {}

        for parent_class in obj['parentClasses']:
            _inherit_into(obj, parent_class, game_objects)

    # now all the prototypes should be built, so sort the attribute/function keys
    for proto_key, proto in prototype.items():
        if proto_key[0] == '_':
            continue

        proto['function_names'] = sort_dict_keys(proto['functions'])
        proto['attribute_names'] = sort_dict_keys(proto['attributes'])
        proto['inheritedFunction_names'] = sort_dict_keys(proto['inheritedFunctions'])
        proto['inheritedAttribute_names'] = sort_dict_keys(proto['inheritedAttributes'])
    ai['function_names'] = sort_dict_keys(ai['functions'])

    creer.validate.validate(prototype)

    return {
        'game_objects': game_objects,
        'game': game,
        'ai': ai
    }


text:
package com.netsteadfast.pine.sys;

import org.apache.shiro.authc.UsernamePasswordToken;

public class GreenStepBaseUsernamePasswordToken extends UsernamePasswordToken {
	private static final long serialVersionUID = 8559334178952902253L;
	private String captcha;

	public GreenStepBaseUsernamePasswordToken() {
		super();
	}

	public GreenStepBaseUsernamePasswordToken(String username, char[] password,
			boolean rememberMe, String host,String captcha) {

		super(username, password, rememberMe, host);
		this.captcha = captcha;
	}

	public String getCaptcha() {
		return captcha;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

}


text:
'use strict';

mldsApp.factory('DomainBlacklistService', ['$http', '$log', function($http, $log){
		return {
			getDomainBlacklist: function() {
				return $http.get('/api/domain-blacklist');
			},

			addDomain: function addDomain(domainName) {
				$log.log('addDomain', domainName);
				return $http({
					method: 'POST',
					url: 'api/domain-blacklist/create',
					params: {domain: domainName}
				});
			},

			removeDomain: function removeDomain(domainName) {
				$log.log('removeDomain', domainName);
				return $http({
					method: 'POST',
					url: 'api/domain-blacklist/remove',
					params: {domain: domainName}
				});
			}
		};

	}]);


text:
A journal plugin for akka-persistence using the pure java bdb library.

## Requirements
At least Akka 2.3.4

## Why BDB over LevelDB?
If your application requires a very high message rate its very possible you will run into the situation where
your LevelDB database can grow unbounded due to old keys not being considered for compaction.

For more details see [this thread](https://groups.google.com/forum/#!msg/leveldb/yL6h1mAOc20/vLU64RylIdMJ).

## Installation
Add the following lines to your build.sbt:

    resolvers += "bseibel at bintray" at "http://dl.bintray.com/bseibel/release"

    libraryDependencies += "com.github.bseibel" %% "akka-persistence-bdb" % "1.0.1"

This version of the plugin is cross compiled with Scala 2.10.4 and 2.11.1

## Configuration

Add to your application.conf

    akka.persistence.journal.plugin = "bdb-journal"

### Additional Settings

```
bdb-journal {
    dir = "journal" ; The directory to store the database environment
    sync = true ; true = Durability.COMMIT_SYNC, false = Durability.COMMIT_WRITE_NO_SYNC
    cache-size-percent = 15 ; size of the heap to use for the bdb cache
    cleaner-threads = 2 ; Number of threads used for journal compaction
    stats-collect = false ; Log usage stats to journal directory
}
```

## TODO

- Optimization pass
- Expose other bdb features (replication, etc)


text:
package org.softlang.operations;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Compute the total all salaries of a company
 */
public class Total extends DefaultHandler
{

	private static String ns = "http://www.softlang.org/company.xsd";
	private boolean isSalary = false;
	private double total = 0;

	/**
	 * Return the final result of query for totaling salaries.
	 */
	public double getTotal() {
		return total;
	}

	/**
	 * Handle "start element"
	 */
    public void startElement(
    		String uri,
    		String name,
			String qName,
			Attributes atts) {
    	isSalary = (uri.equals(ns) && name.equals("salary"));
    }

    /**
     * Handle "end element"
     */
    public void endElement(
    		String uri,
    		String name,
    		String qName) {
    	isSalary = false;
    }

	/**
	 * Handle "characters"
	 */
    public void characters(
    		char ch[],
    		int start,
    		int length) {
    	if (isSalary) {
    		String str = String.valueOf(ch, start, length);
    		double salary = Double.parseDouble(str);
    		total += salary;
	    }
    }
}


text:
package timeseries

import (
	"sync"
	"time"
)

type Instance struct {
	data  Data
	times times
	mutex sync.Mutex
}

func (ts *Instance) AddObservation(val float64, t time.Time) {
	ts.mutex.Lock()
	defer ts.mutex.Unlock()
	ts.data = append(ts.data, val)
	ts.times = append(ts.times, t)
}

func (ts *Instance) AddAll(o *Instance) {
	ts.mutex.Lock()
	defer ts.mutex.Unlock()

	oData, oTimes := o.Series()
	ts.data = append(ts.data, oData...)
	ts.times = append(ts.times, oTimes...)
}

func (ts *Instance) Data() Data {
	ts.mutex.Lock()
	defer ts.mutex.Unlock()
	return ts.data.Copy()
}

func (ts *Instance) Series() (Data, []time.Time) {
	ts.mutex.Lock()
	defer ts.mutex.Unlock()
	return ts.data.Copy(), ts.times.copy()
}

func (ts *Instance) SeriesAsDurationSinceEpoch(epoch time.Time) (Data, []time.Duration) {
	ts.mutex.Lock()
	defer ts.mutex.Unlock()
	return ts.data.Copy(), ts.times.asDurationSinceEpoch(epoch)
}

type times []time.Time

func (t times) copy() times {
	out := make(times, 0, len(t))
	out = append(out, t...)
	return out
}

func (t times) asDurationSinceEpoch(epoch time.Time) []time.Duration {
	out := make([]time.Duration, 0, len(t))
	for _, tm := range t {
		out = append(out, tm.Sub(epoch))
	}
	return out
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
	"http://www.w3.org/TR/html4/strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Queued Photo Uploader - Standalone Showcase from digitarald.de</title>

	<meta name="author" content="Harald Kirschner, digitarald.de" />
	<meta name="copyright" content="Copyright 2009 Harald Kirschner" />

	<link rel="stylesheet" href="http://github.com/joshuaclayton/blueprint-css/raw/master/blueprint/screen.css" type="text/css" media="screen, projection">
	<link rel="stylesheet" href="http://github.com/joshuaclayton/blueprint-css/raw/master/blueprint/print.css" type="text/css" media="print">

FancyUpload Standalone Showcase from digitarald.de

Queued Photo Uploader

<form action="./server/script.php" method="post" enctype="multipart/form-data" id="form-demo">

	<fieldset id="demo-fallback">
		<legend>File Upload</legend>

			This form is just an example fallback for the unobtrusive behaviour of FancyUpload.
			If this part is not changed, something must be wrong with your code.

			Upload a Photo:
			<input type="file" name="Filedata" />

	</fieldset>

			Browse Files |
			Clear List |
			Start Upload

</form>

		© 2008-2009 by Harald Kirschner and available under The MIT License