text:
const IS_DEV = process.env.NODE_ENV === "development";

class EntityRef {
  constructor(entity) {
    this.entity = entity;
  }

  get alive() {
    return this.entity ? this.entity.alive : false;
  }

  kill() {
    if (this.entity) this.entity.kill();
  }
}

export default class Entity {
  constructor(entityManager) {
    this._alive = false;
    this._enabled = true;
    this._entityManager = entityManager;
    this.system = null;
    this.name = null;
    this.Tags = new Map();
    this._queuedEvents = 0;
    this._refs = null;
    this._removeTagInstance = (instance, Tag) => {
      if (Tag.isData || Tag.isValue) {
        this._entityManager.releaseTag(Tag, instance);
      }
    };
  }

  ref() {
    const ref = new EntityRef(this);
    if (!this._refs) this._refs = [];
    this._refs.push(ref);
    return ref;
  }

  reset() {
    this.removeAll();
    this.system = null;
    this._alive = false;
    this._enabled = true;
    this.name = undefined;
    this._queuedEvents = 0;
  }

  add(Tag, values) {
    if (!Tag) throw new Error(`Must specify a Tag`);
    if (typeof Tag !== "function") {
      throw new Error(`Tags must be functions or classes`);
    }
    // if we already have this tag, clean up the old one
    if (this.has(Tag)) {
      this._directRemoveTag(Tag);
    }
    let tag;
    if (Tag.isData) {
      tag = this._entityManager.createTag(Tag);
      for (let k in values) {
        if (values.hasOwnProperty(k)) {
          if (Tag.data.hasOwnProperty(k)) {
            const prop = Tag.data[k];
            tag[k] = prop.copy(values[k], tag[k]);
          } else if (IS_DEV) {
            console.warn(
              `No property "${k}" found on the Data tag ${Tag.name}`
            );
          }
        }
      }
    } else if (Tag.isValue) {
      tag = this._entityManager.createTag(Tag);
      if (typeof values !== "undefined") {
        const prop = Tag.value;
        tag.value = prop.copy(values, tag.value);
      }
    } else {
      tag = Tag;
    }
    this.Tags.set(Tag, tag);
    this._tagAdded(Tag);
    return this;
  }

  set(Tag, values) {
    if (!this.has(Tag)) {
      this.add(Tag, values);
    } else if (Tag.isData) {
      const tag = this.getTag(Tag);
      for (let k in values) {
        if (values.hasOwnProperty(k)) {
          if (Tag.data.hasOwnProperty(k)) {
            const prop = Tag.data[k];
            tag[k] = prop.copy(values[k], tag[k]);
          } else if (IS_DEV) {
            console.warn(
              `No property "${k}" found on the Data tag ${Tag.name}`
            );
          }
        }
      }
    } else if (Tag.isValue && typeof values !== "undefined") {
      const tag = this.getTag(Tag);
      const prop = Tag.value;
      tag.value = prop.copy(values, tag.value);
    }
    return this;
  }

  _directRemoveTag(Tag) {
    if (Tag.isData || Tag.isValue) {
      const instance = this.Tags.get(Tag);
      this._entityManager.releaseTag(Tag, instance);
    }
    this.Tags.delete(Tag);
  }

  remove(Tag) {
    if (this.has(Tag)) {
      this._directRemoveTag(Tag);
      this._tagRemoved(Tag);
    }
    return this;
  }

  removeAll(Tags) {
    if (this.Tags.size > 0) {
      this.Tags.forEach(this._removeTagInstance);
      this.Tags.clear();
      this._update();
    }
    return this;
  }

  get(Tag) {
    const t = this.getTag(Tag);
    if (Tag.isValue) return t.value;
    return t;
  }

  getTag(Tag) {
    if (!this.has(Tag)) {
      throw new Error(`The Tag ${Tag.name} is not part of this Entity`);
    }
    return this.Tags.get(Tag);
  }

  getTagEntries() {
    return Array.from(this.Tags.entries());
  }

  has(Tag) {
    return this.Tags.has(Tag);
  }

  hasAll(Tags) {
    for (let i = 0; i < Tags.length; i++) {
      const Tag = Tags[i];
      if (!this.has(Tag)) return false;
    }
    return true;
  }

  hasAny(Tags) {
    for (let i = 0; i < Tags.length; i++) {
      const Tag = Tags[i];
      if (this.has(Tag)) return true;
    }
    return false;
  }

  get alive() {
    return this._alive;
  }

  get enabled() {
    return this._enabled;
  }

  get processed() {
    return this._queuedEvents === 0;
  }

  // alias to add only if tag doesn't exist
  tagOn(Tag, values) {
    if (!this.has(Tag)) this.add(Tag, values);
    return this;
  }

  // alias to disable only if tag exists
  tagOff(Tag) {
    this.remove(Tag);
    return this;
  }

  enable() {
    if (!this._enabled) {
      this._enabled = true;
      this._update();
    }
    return this;
  }

  disable() {
    if (this._enabled) {
      this._enabled = false;
      this._update();
    }
    return this;
  }

  unmanage() {
    if (this.system) {
      this.system._unmanage(this);
      this.system = null;
    }
  }

  kill() {
    if (this.system) this.unmanage();
    if (this._alive) {
      this._alive = false;
      this._entityManager._markEntityForRemoval(this);
    }
    if (this._refs) {
      // clear refs
      for (let i = 0; i < this._refs.length; i++) {
        this._refs[i].entity = null;
      }
      // de-reference the array
      this._refs = null;
    }
    return this;
  }

  _tagAdded(Tag) {
    // TODO: optimization here for add-only case
    this._update();
  }

  _tagRemoved(Tag) {
    // TODO: optimization here for remove-only case
    this._update();
  }

  _update() {
    this._entityManager._onEntityUpdated(this);
  }
}


text:
<meta>
	<info author="UAG Crew" type="misc" name="The Hub"/>
	<min_mta_version client="1.3.0-9.03931" server="1.3.0-9.03772" />

	<script src="s_connect.lua"/>
	<script src="c_connect.lua" type="client"/>
	<script src="s_elements.lua"/>

	<file src="images/bgcolor.png" type="client"/>
	<file src="images/white.png" type="client"/>
	<file src="images/play.png" type="client" />
	<file src="images/parachute.png" type="client" />
	<file src="images/arrow.png" type="client" />

	<file src="images/screens/infoSpawn/frame1.jpg" type="client" />

	<file src="shader/window.fx" type="client" />
	<file src="shader/texreptransform.fx" type="client" />

	<export function="getModeName" type="client"/>
	<export function="loadGamemode" type="client"/>
	<export function="unloadGamemode" type="client"/>
	<export function="onClientMapStop" type="client"/>
	<export function="setRoomID" type="server"/>
	<export function="onPlayerTableUpdate" type="server"/>
	<export function="onPlayerLeaveRoom" type="server"/>
	<export function="sendMapElement" type="client"/>
	<export function="onMapLoaded" type="client"/>
</meta>

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var autoprefixer = require('autoprefixer-core');

var paths = {
    scripts: ['assets/js/*.js'],
    styles: ['assets/css/styles.scss']
};

//Minify all CSS files
gulp.task('minify-css', function() {
  return gulp.src(paths.styles)
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.sass())
    .pipe($.postcss([ autoprefixer({ browsers: ['last 2 version'] }) ]))
    .pipe($.minifyCss())
    .pipe($.rename({
      suffix: '.min'
    }))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('./assets/css'))
    .pipe($.filesize());
});

// Minify and copy all JavaScript (except vendor scripts)
gulp.task('minify-js', function() {
    return gulp.src(paths.scripts)
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.uglify())
    .pipe($.concat('main.min.js'))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('assets/js'))
    .pipe($.filesize());
});

//Watch the SCSS folder
gulp.task('watch', function () {
    gulp.watch(paths.styles, ['minify-css']);
    gulp.watch(paths.scripts, ['minify-js']);
});

//Default task
gulp.task('default', ['minify-css', 'minify-js']);


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

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="markdown.css" rel="stylesheet"></link>
<title></title>

Introduction

Main purpose of jbehaviour-tools is to simplify common developpment tools for
simple users in "natural" langage.

behaviour-tools is not a fork, but it's based on the great idea of dan north : http://dannorth.net/introducing-bdd
all is rewritten, and based on a antlr grammar.

This framework permit to parse and execute story with a jbehave/cumcumber approach but with some extention :

json object on the fly creation and manipulation in the story (with jackson)

velocity templating integration to manipulating all object created on the fly in the story

storage during the story on object in session

include other story

registering annoted class at the begining of the story

the purpose of this framework is to simplify, and make readable all story manipulated by a business analyst
and avoid to consider so much technical method for using testing tools :

soapui

ssh/scp/sftp/svn/git manipulation

remote host manipulation (unix system)

selenium suite

and so on ...

Default usage

Extention

System core included ...

Sikuli

Remote

Jdbc

Fluentlenium

Soapui


text:
/**
 * Created by bmf on 10/31/13.
 */
"use strict";

var assert = require('assert');
var crypto = require('crypto');
var sodium = require('../build/Release/sodium');

describe('Sign', function() {
    it('crypto_sign_keypair should return a pair of keys', function(done) {
        var keys = sodium.crypto_sign_keypair();
        assert.equal(typeof keys, 'object');
        assert.notEqual(typeof keys.publicKey, 'undefined');
        assert.notEqual(typeof keys.secretKey, 'undefined');
        assert.equal(keys.publicKey.length, sodium.crypto_sign_PUBLICKEYBYTES);
        assert.equal(keys.secretKey.length, sodium.crypto_sign_SECRETKEYBYTES);
        done();
    });

    it('a signed message should verify correctly', function(done) {
        var keys = sodium.crypto_sign_keypair();
        var message = Buffer.from("Libsodium is cool", 'utf8');
        var signedMsg = sodium.crypto_sign(message, keys.secretKey);

        var message2 = sodium.crypto_sign_open(signedMsg, keys.publicKey);
        assert.equal(message2.toString('utf8'), message.toString('utf8'));
        done();
    });

    it('should accept a zero length message', function(done) {
        var keys = sodium.crypto_sign_ed25519_keypair();
        var signedMsg = sodium.crypto_sign_ed25519_detached(Buffer.allocUnsafe(0), keys.secretKey)
        done();
    });

    it('a detached message signature should verify correctly', function(done) {
        var keys = sodium.crypto_sign_keypair();
        var message = Buffer.from("Libsodium is cool", 'utf8');
        var signature = sodium.crypto_sign_detached(message, keys.secretKey);

        var verified = sodium.crypto_sign_verify_detached(signature, message, keys.publicKey);
        assert.strictEqual(verified, true);
        done();
    });

    it('a modified detached message signature should not verify correctly', function(done) {
        var keys = sodium.crypto_sign_keypair();
        var message = Buffer.from("Libsodium is cool", 'utf8');
        var signature = sodium.crypto_sign_detached(message, keys.secretKey);
        signature.writeFloatLE(Math.random(), 0);
        var verified = sodium.crypto_sign_verify_detached(signature, message, keys.publicKey);
        assert.strictEqual(verified, false);
        done();
    });

    it('should throw with less than 2 arguments', function(done) {
        var keys = sodium.crypto_sign_keypair();
        var message = Buffer.from("Libsodium is cool", 'utf8');

         assert.throws(function() {
            var signedMsg = sodium.crypto_sign(message);
        });
        done();
    });

    it('should throw with no params', function(done) {
        var keys = sodium.crypto_sign_keypair();
        var message = Buffer.from("Libsodium is cool", 'utf8');

         assert.throws(function() {
            var signedMsg = sodium.crypto_sign();
        });
        done();
    });

    it('should throw with a small key', function(done) {
        var message = Buffer.from("Libsodium is cool", 'utf8');

         assert.throws(function() {
            var signedMsg = sodium.crypto_sign(message, Buffer.allocUnsafe(12));
        });
        done();
    });

    it('should test bad arg 1', function(done) {
        var message = Buffer.from("Libsodium is cool", 'utf8');
        var keys = sodium.crypto_sign_keypair();
         assert.throws(function() {
            var signedMsg = sodium.crypto_sign(1, keys.secretKey);
        });
        done();
    });

    it('should test bad arg 2', function(done) {
        var message = Buffer.from("Libsodium is cool", 'utf8');
        var keys = sodium.crypto_sign_keypair();
         assert.throws(function() {
            var signedMsg = sodium.crypto_sign(message, 1);
        });
        done();
    });

    it('should test bad arg 2', function(done) {
        var message = Buffer.from("Libsodium is cool", 'utf8');
        var keys = sodium.crypto_sign_keypair();
         assert.throws(function() {
            var signedMsg = sodium.crypto_sign(message, "123");
        });
        done();
    });
});


text:
package jsystem.extensions.analyzers.tabletext;

import java.util.HashSet;
import java.util.Set;

/**
 * @author guy.arieli
 *
 */
public abstract class TableBasic implements TTable {
	protected String stringTable = null;

	protected String[] lines = null;

	protected int[] fieldsOffset = null;

	protected int numberOfFields = -1;

	protected String[] header1 = null;

	protected String[] header2 = null;

	protected String[][] cells = null;

	/**
	 * Create a table instance from a cli string input.
	 *
	 * @param stringTable
	 *            the string to be analyze into table structure
	 * @throws Exception
	 */
	public TableBasic(String stringTable) throws Exception {
		this.stringTable = stringTable;
		initTable(stringTable);
	}

	public TableBasic() {

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getNumberOfRows()
	 */
	public int getNumberOfRows() {
		return cells.length;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getNumberOfColumns()
	 */
	public int getNumberOfColumns() {
		return numberOfFields;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getCell(int, int)
	 */
	public String getCell(int row, int col) {
		if (col >= numberOfFields || row >= getNumberOfRows()) {
			return null;
		}
		return cells[row][col];
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getRow(int)
	 */
	public String[] getRow(int row) {
		if (row >= getNumberOfRows()) {
			return null;
		}
		return cells[row];
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getColumn(int)
	 */
	public String[] getColumn(int col) {
		int numberOfRows = getNumberOfRows();
		String[] returnArray = new String[numberOfRows];
		for (int i = 0; i < numberOfRows; i++) {
			returnArray[i] = getCell(i, col);
		}
		return returnArray;
	}

	protected void initLines() {
		lines = stringTable.split("[\\r\\n]+");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#findFieldInRow(java.lang.String,
	 *      int)
	 */
	public int findFieldInRow(String fieldName, int lineIndex) {
		String[] rowArray = getRow(lineIndex);
		for (int i = 0; i < rowArray.length; i++) {
			if (rowArray[i].equals(fieldName)) {
				return i;
			}
		}
		return -1;
	}

	protected abstract void initHeaders() throws Exception;

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getHeaders()
	 */
	public String[] getHeaders() throws Exception {

		return header1;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getHeaderFieldIndex(java.lang.String)
	 */
	public abstract int getHeaderFieldIndex(String fieldName) throws Exception;

	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < getNumberOfRows(); i++) {
			for (int j = 0; j < getNumberOfColumns(); j++) {
				sb.append(getCell(i, j));
				if (j != getNumberOfColumns() - 1) {
					sb.append(",");
				}
			}
			sb.append("\n");
		}
		return sb.toString();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getTableString()
	 */
	public String getTableString() {
		return stringTable;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getFirstRowIndex(java.lang.String,
	 *      java.lang.String)
	 */
	public int getFirstRowIndex(String headerField, String cellValue) throws Exception {
		int colIndex = getHeaderFieldIndex(headerField);
		String[] col = getColumn(colIndex);
		for (int i = 0; i < col.length; i++) {
			if (cellValue.equals(col[i])) {
				// if(cellValue.compareToIgnoreCase(col[i])==0){
				return i;
			}
		}
		throw new Exception("Row: " + headerField + " doesn't contain field: " + cellValue);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see jsystem.extensions.analyzers.tabletext.TTable#getFirstRowIndex(int,
	 *      java.lang.String)
	 */
	public int getFirstRowIndex(int colIndex, String cellValue) throws Exception {
		String[] col = getColumn(colIndex);
		for (int i = 0; i < col.length; i++) {
			if (cellValue.equals(col[i])) {
				// if(cellValue.compareToIgnoreCase(col[i])==0){
				return i;
			}
		}
		throw new Exception("Row index: " + colIndex + " doesn't contain field: " + cellValue);
	}

	public boolean isRealKeyHeader(String keyHeader, Object testAgainst) {

		 // to find it out we put the first column in a hashset.
		 // If all the values in our table's first column are different,
	     //  then the size of the hashset will be the same as the size of our table's first column.
	     //  If the size is equal than it is a table with keyheader, otherwise it is without keyheader.

		boolean isRealKeyHeader;
		GetTableColumn gtc = null;
		try {
			gtc = new GetTableColumn(keyHeader);
		} catch (Exception e) {
			// throwable = e;
			isRealKeyHeader = false;
			return isRealKeyHeader;
		}
		gtc.setTestAgainst(testAgainst);
		gtc.analyze();
		String[] keyHeaders = gtc.getColumn();
		Set<String> myHashSet = new HashSet<String>();
		for (int i = 0; i < keyHeaders.length; i++) {
			myHashSet.add(keyHeaders[i]);
		}
		if (myHashSet.size() == keyHeaders.length)
			isRealKeyHeader = true;
		else
			isRealKeyHeader = false;

		return isRealKeyHeader;
	}

}


text:
layout: page
navigation_title: Blog
title: Blog
permalink: /blog/
published: true
description: >-
  How much should we worry about Trump and Republican majority government? We
  will suggest strategic and tactical actions to help, including supporting
  efforts, organizations or politicians local or national.
---

{% assign posts = site.posts | where:'type', 'blog' %}
{% for post in posts %}

{{ post.title }}

Posted on <time class="published" datetime="{{ post.datetime | date_to_xmlschema }}">{{ post.datetime}}</time>

      	{{post.content}}

{% endfor %}


text:
<?php

namespace Iyzipay\Tests\Model\Mapper;

use Iyzipay\Model\BasicThreedsInitialize;
use Iyzipay\Model\Locale;
use Iyzipay\Model\Mapper\BasicThreedsInitializeMapper;
use Iyzipay\Model\Status;
use Iyzipay\Tests\TestCase;

class BasicBasicThreedsInitializeMapperTest extends TestCase
{
    public function test_should_map_basic_threeds_initialize()
    {
        $json = $this->retrieveJsonFile("initialize-basic-threeds-payment.json");

        $basicThreedsInitialize = BasicThreedsInitializeMapper::create($json)->jsonDecode()->mapBasicThreedsInitialize(new BasicThreedsInitialize());

        $this->assertNotEmpty($basicThreedsInitialize);
        $this->assertEquals(Status::FAILURE, $basicThreedsInitialize->getStatus());
        $this->assertEquals("10000", $basicThreedsInitialize->getErrorCode());
        $this->assertEquals("error message", $basicThreedsInitialize->getErrorMessage());
        $this->assertEquals("ERROR_GROUP", $basicThreedsInitialize->getErrorGroup());
        $this->assertEquals(Locale::TR, $basicThreedsInitialize->getLocale());
        $this->assertEquals("1458545234852", $basicThreedsInitialize->getSystemTime());
        $this->assertEquals("123456", $basicThreedsInitialize->getConversationId());
        $this->assertEquals("htmlContent", $basicThreedsInitialize->getHtmlContent());
        $this->assertJson($basicThreedsInitialize->getRawResult());
        $this->assertJsonStringEqualsJsonString($json, $basicThreedsInitialize->getRawResult());
    }
}


text:
import base
import unittest
import formish
import schemaish
from BeautifulSoup import BeautifulSoup
from datetime import date
import validatish

class TestFormExamples(base.TestCase):

    def test_string_form(self):
        """
        Form with a couple of string fields
        """
        schema = schemaish.Structure()
        schema.add('fieldOne',schemaish.String())
        schema.add('fieldTwo',schemaish.String())

        form_name = 'form_name'
        form = formish.Form(schema, form_name)

        request_data = {'fieldOne':'a','fieldTwo':'b'}
        expected_data = {'fieldOne':'a','fieldTwo':'b'}

        request = self.Request(form_name,request_data)
        data = form.validate(request)
        assert data == expected_data

        form.defaults = request_data
        htmlsoup = BeautifulSoup(form())
        assert htmlsoup.findAll(id='form_name-fieldOne--field')[0]['class'] == 'field form_name-fieldOne type-string widget-input'
        assert htmlsoup.findAll(id='form_name-fieldTwo--field')[0]['class'] == 'field form_name-fieldTwo type-string widget-input'
        assert htmlsoup.findAll(id='form_name-fieldOne')[0]['value'] == 'a'
        assert htmlsoup.findAll(id='form_name-fieldTwo')[0]['value'] == 'b'

    def test_integer_form(self):
        """
        Form with a couple of integer fields
        """
        schema = schemaish.Structure()
        schema.add('fieldOne',schemaish.Integer())
        schema.add('fieldTwo',schemaish.Integer())

        form_name = 'form_name'
        form = formish.Form(schema, form_name)

        request_data = {'fieldOne':'1','fieldTwo':'2'}
        expected_data = {'fieldOne':1,'fieldTwo':2}

        request = self.Request(form_name,request_data)

        data = form.validate(request)
        assert data == expected_data

        form.defaults = expected_data
        htmlsoup = BeautifulSoup(form())
        assert htmlsoup.findAll(id='form_name-fieldOne--field')[0]['class'] == 'field form_name-fieldOne type-integer widget-input'
        assert htmlsoup.findAll(id='form_name-fieldTwo--field')[0]['class'] == 'field form_name-fieldTwo type-integer widget-input'
        assert htmlsoup.findAll(id='form_name-fieldOne')[0]['value'] == '1'
        assert htmlsoup.findAll(id='form_name-fieldTwo')[0]['value'] == '2'

    def test_date_form(self):
        """
        Form with a date
        """
        schema = schemaish.Structure()
        schema.add('a',schemaish.Date())

        form_name = 'form_name'
        form = formish.Form(schema, form_name)

        request_data = {'a':'1966-12-18'}
        expected_data = {'a': date(1966,12,18)}

        request = self.Request(form_name,request_data)

        try:
            data = form.validate(request)
        except:
            pass
        assert data == expected_data

        form.defaults = expected_data
        htmlsoup = BeautifulSoup(form())
        assert htmlsoup.findAll(id='form_name-a--field')[0]['class'] == 'field form_name-a type-date widget-input'
        assert htmlsoup.findAll(id='form_name-a')[0]['value'] == '1966-12-18'

    def test_date_dateparts_form(self):
        """
        Form with a date
        """
        schema = schemaish.Structure()
        schema.add('a',schemaish.Date())

        form_name = 'form_name'
        form = formish.Form(schema, form_name)
        form['a'].widget = formish.DateParts()

        request = self.Request(form_name,{'a.year': '', 'a.month': '', 'a.day': ''})
        data = form.validate(request)
        assert data == {'a': None}

        request_data = {'a.day':'18', 'a.month':'12','a.year':'1966'}
        expected_data = {'a': date(1966,12,18)}

        request = self.Request(form_name,request_data)
        data = form.validate(request)
        assert data == expected_data

        form.defaults = expected_data
        htmlsoup = BeautifulSoup(form())
        assert htmlsoup.findAll(id='form_name-a--field')[0]['class'] == 'field form_name-a type-date widget-dateparts'
        assert htmlsoup.findAll(id='form_name-a')[0]['value'] == '18'

class TestErrorRendering(base.TestCase):

    def test_simple(self):
        """
        Check simple field templates emit errors correctly.
        """
        self._test(
                schemaish.Structure([
                    ('simple', schemaish.String()),
                    ]),
                'simple')

    def test_structure_error(self):
        """
        Check structure field templates emit errors correctly.
        """
        self._test(
                schemaish.Structure([
                    ('structure', schemaish.Structure([
                        ('string', schemaish.String())]
                        ))
                    ]),
                'structure')

    def test_sequence_error(self):
        self._test(
                schemaish.Structure([
                    ('sequence', schemaish.Sequence(schemaish.String()))
                    ]),
                'sequence')

    def _test(self, schema, attr):
        ERROR_TEXT = '!!!WOOP!!!WOOP!!!WOOP!!!'
        form = formish.Form(schema, errors={attr: validatish.Invalid(ERROR_TEXT)})
        html = form()
        element = BeautifulSoup(html).find(id='%s--field'%(attr.replace('.', '-'),))
        div_error = element.find('div',{'class': 'error'})
        span_error = element.find('span',{'class': 'error'})
        assert div_error or span_error
        if div_error:
            assert div_error.string == ERROR_TEXT
        if span_error:
            assert span_error.string == ERROR_TEXT

class TestSequenceDefault(base.TestCase):

    def test_empty_checker(self):
        form = formish.Form(self._schema(),'form')
        form['seq'].widget = formish.SequenceDefault()
        # Structure should be in form ...
        self.assertTrue('seq.0.foo' in form())
        # ... but not in data
        self.assertEquals(form.validate(self.Request('form', {})), {'seq': []})

    def test_min_start_fields_default(self):
        form = formish.Form(self._schema(),'form')
        form['seq'].widget = formish.SequenceDefault()
        html = form()
        self.assertTrue('seq.0.foo' in html)
        self.assertTrue('seq.1.foo' not in html)

    def test_min_start_fields(self):
        for i in range(1, 5):
            form = formish.Form(self._schema(),'form')
            form['seq'].widget = formish.SequenceDefault(min_start_fields=i)
            html = form()
            for num in range(i):
                self.assertTrue('seq.%d.foo'%num in html)
            self.assertEquals(form.validate(self.Request('form', {})), {'seq': []})

    def test_min_start_with_data(self):
        form = formish.Form(self._schema(),'form')
        form['seq'].widget = formish.SequenceDefault()
        form.defaults = {'seq': [{'foo': 'bar'}]}
        html = form()
        self.assertTrue('seq.0.foo' in html)
        self.assertTrue('value="bar"' in html)
        self.assertTrue('seq.1.foo' not in html)

    def test_min_start_min_empty(self):
        form = formish.Form(self._schema(),'form')
        form['seq'].widget = formish.SequenceDefault(min_start_fields=1, min_empty_start_fields=1)
        html = form()
        self.assertTrue('seq.0.foo' in html)
        self.assertTrue('seq.1.foo' not in html)
        form.defaults = {'seq': [{'foo': 'bar'}]}
        html = form()
        self.assertTrue('seq.0.foo' in html)
        self.assertTrue('value="bar"' in html)
        self.assertTrue('seq.1.foo' in html)

    def test_first_entry(self):
        form = formish.Form(self._schema(),'form')
        form['seq'].widget = formish.SequenceDefault(min_start_fields=2)
        self.assertEquals(form.validate(self.Request('form', [('seq.0.foo', 'bar'), ('seq.1.foo', '')])), {'seq': [{'foo': 'bar'}]})

    def test_empty_first_entry(self):
        form = formish.Form(self._schema(),'form')
        form['seq'].widget = formish.SequenceDefault(min_start_fields=2)
        self.assertRaises(formish.FormError, form.validate, self.Request('form', [('seq.0.foo', ''), ('seq.1.foo', 'bar')]))

    def test_unicode_in_template(self):
        # Check that new item template encoding is ok with unicode characters.
        schema = schemaish.Structure([('seq', schemaish.Sequence(schemaish.String()))])
        form = formish.Form(schema)
        form['seq.*'].widget = formish.SelectChoice(options=[('GBP', '£'.decode('utf-8'))])
        form()

    def _schema(self):
        return schemaish.Structure([
                ('seq', schemaish.Sequence(
                    schemaish.Structure([
                        ('foo', schemaish.String(validator=validatish.Required()))
                    ])
                )),
            ])

class TestSelectChoice(base.TestCase):

    def test_default(self):
        form = formish.Form(
            schemaish.Structure([
                ('foo', schemaish.String()),
            ])
        )
        form['foo'].widget = formish.SelectChoice(['a', 'b'])
        self.assertTrue('selected="selected"' not in form())
        form.defaults = {'foo': 'a'}
        self.assertTrue('value="a"  selected="selected"' in form())

    def test_none_option(self):
        form = formish.Form(
            schemaish.Structure([
                ('foo', schemaish.String()),
            ])
        )
        form['foo'].widget = formish.SelectChoice(options=['a', 'b'])
        self.assertTrue('value=""' in form())
        form['foo'].widget = formish.SelectChoice(options=['a', 'b'], none_option=None)
        self.assertTrue('value=""' not in form())

class TestSelectWithOther(base.TestCase):

    def test_default(self):
        form = formish.Form(
            schemaish.Structure([
                ('foo', schemaish.String()),
            ])
        )
        form['foo'].widget = formish.SelectWithOtherChoice(['a', 'b'])
        self.assertTrue('selected="selected"' not in form())
        form.defaults = {'foo': 'b'}
        self.assertTrue('value="b" selected="selected"' in form())
        form.defaults = {'foo': 'c'}
        self.assertTrue('value="..." selected="selected"' in form())

class TestCheckboxMultiChoice(base.TestCase):

    def test_renders_with_options(self):
        schema = schemaish.Structure()
        schema.add('foo', schemaish.Sequence(schemaish.String()))
        form = formish.Form(schema)
        form['foo'].widget = formish.CheckboxMultiChoice(options=[('opt1', 'Opt #1')])
        html = form()
        assert 'foo' in html
        assert 'opt1' in html
        assert 'Opt #1' in html

class TestFileUpload(base.TestCase):

    def test_thumbnail_sizing(self):
        schema = schemaish.Structure()
        schema.add('foo', schemaish.File())
        basic_form = formish.Form(schema)
        basic_form['foo'].widget = formish.FileUpload(
            image_thumbnail_default='/images/blank.png',
            show_image_thumbnail=True)
        advanced_form = formish.Form(schema)
        advanced_form['foo'].widget = formish.FileUpload(
            thumbnail_size="40x40",
            image_thumbnail_default='/images/blank.png',
            show_image_thumbnail=True)
        html = basic_form()
        assert 'foo' in html
        assert '/images/blank.png?size=20x20' in html
        html = advanced_form()
        assert 'foo' in html
        assert '/images/blank.png?size=40x40' in html

if __name__ == '__main__':
    unittest.main()


text:
<?php

include_once "buffer.php";
include_once "error.php";
include_once "curl.php";

/**
* Builds a transportAPI JSON answer for locations
* @query - The query string
* @returns a transport-API conform location answer
*/
function getlocationjson($query) {
	$res=getlocation($query);
	$r2value = array();
	$r2value['stations']=$res;
	return json_encode($r2value);
}

/**
* Builds a transportAPI JSON answer for locations searched by coordinates
* @query - The query string
* @returns a transport-API conform location answer
*/
function getlocationjsoncoord($x,$y) {
	$res=getlocationcoord($x,$y);
	$r2value = array();
	$r2value['stations']=$res;
	return json_encode($r2value);
}

/**
* Builds a transportAPI answer for locations
* @query - the query string
* @returns rough result for locations
*/
function getlocation($query){

	if (inbuffer('getlocation',$query)){
		return getbuffer('getlocation',$query);
	}
	$data = docurl("https://opentransportdata.swiss/api/action/package_show?id=bhlist");
	$myArr = $data->result->resources;

	$id=-1;
	if (strcmp($myArr[0]->{'identifier'},"Station list")==0){
		$id=$myArr[0]->{'id'};
	} else {
		$id=$myArr[1]->{'id'};
	}
	$geoid=-1;
	if (strcmp($myArr[0]->{'identifier'},"Station geographic")==0){
		$geoid=$myArr[0]->{'id'};
	} else {
		$geoid=$myArr[1]->{'id'};
	}
	$qstr="https://opentransportdata.swiss/api/action/datastore_search?resource_id=%%%id%%%&q=%%%name%%%";
	$qstr=str_replace("%%%id%%%",$id,$qstr);
	$qstr=str_replace("%%%name%%%",$query,$qstr);

	$data = docurl($qstr);

	$rvalue= array();

	foreach ($data->result->records as $val){
		$station = array();
		$station['id'] = $val->StationID;
		$station['name']= $val->Station;
		$station['score'] = null;
		$station['coordinate'] = getcoordinates($val->StationID,$geoid);
		$station['distance'] = null;
		$rvalue[]=$station;
	}
	setbuffer('getlocation',$query,$rvalue); //buffering
	return $rvalue;

};

/**
* Gets the coordinates in json format
* @param $bpuic - The bpuic code
* @param $id - the id of the ressource
* @returns the coordinates in json format
*/
function getcoordinatesjson($bpuic,$id){
	$r2value['stations']=getcoordinates($bpuic,$id);
	return $r2value;
}

/**
* Gets the coordinates in format
* @param $bpuic - The bpuic code
* @param $id - the id of the ressource
* @returns the coordinates
*/
function getcoordinates($bpuic,$id){
	if (inbuffer('getcoordinates',$query)){
		return getbuffer('getcoordinates',$query);
	}

	$data = docurl("https://opentransportdata.swiss/api/action/package_show?id=bhlist");
	$myArr = $data->result->resources;
	$qstr="https://opentransportdata.swiss/api/action/datastore_search?resource_id=%%%id%%%&q=%%%name%%%";
	$qstr=str_replace("%%%id%%%",$id,$qstr);
	$qstr=str_replace("%%%name%%%",$bpuic,$qstr);
	$data = docurl($qstr);
	$data= $data->result->records;
	//var_dump($data);
    $x=$data[0]->Longitude;
    $y=$data[0]->Latitude;
	$station = array();
	$station['type'] = "WGS84";
	$station['x']= $x;
	$station['y']= $y;

	setbuffer('getlocation',$query,$station); //buffering
	return $station;
}

/**
* Searches the locations by coordinates
* @param $x - The longitude
* @param $y - The latitude
* @returns an array of locations
*/
function getlocationcoord($x,$y){

	if (inbuffer('getlocationcoord',$x."---".$y)){
		return getbuffer('getlocationcoord',$query);
	}
	$data = docurl("https://opentransportdata.swiss/api/action/package_show?id=bhlist");
	$myArr = $data->result->resources;

	$id=-1;
	if (strcmp($myArr[0]->{'identifier'},"Station list")==0){
		$id=$myArr[0]->{'id'};
	} else {
		$id=$myArr[1]->{'id'};
	}
	$geoid=-1;
	if (strcmp($myArr[0]->{'identifier'},"Station geographic")==0){
		$geoid=$myArr[0]->{'id'};
	} else {
		$geoid=$myArr[1]->{'id'};
	}
	$qstr='SELECT * from "%%%id%%%" where (abs("Longitude" - %%%x%%%) <0.03) AND (abs("Latitude" - %%%y%%%) <0.03)';
	$qstr=str_replace("%%%id%%%",$geoid,$qstr);
	$qstr=str_replace("%%%x%%%",$x,$qstr);
	$qstr=str_replace("%%%y%%%",$y,$qstr);

    $qstr="https://opentransportdata.swiss/api/action/datastore_search_sql?sql=".urlencode($qstr);
	$data = docurl($qstr);

	$rvalue= array();
	//var_dump_file("query.res",$qstr);

	foreach ($data->result->records as $val){
		$station = array();
		$station['id'] = $val->StationID;
		$station['name']= $val->Remark; //@TODO we take it from the remark, which is not really well done
		$station['score'] = null;
		$station['coordinate'] = getcoordinates($val->StationID,$geoid); //@TODO his is also not very smooth
		$station['distance'] = haversineGreatCircleDistance($x,$y,$station['coordinate']['x'],$station['coordinate']['y']);
		$t=$station['id'];
		//file_put_contents("php://stdout", "\n>$t<");
		$rvalue[]=$station;
	}
	setbuffer('getlocationcoord',$x."---".$y,$rvalue); //buffering

	return $rvalue;

}

/**
* Gets the first location in the list. Be aware, that no special sorting is implemented
* @param $name - the name of the station
* @returns the first location or null
* @TODO better sorting
*/
function getfirstlocationFull($name){
	$loc_struct=getlocation($name);
	$n=count($loc_struct);
	//file_put_contents("php://stdout", "\n num results>$n<");
	$log=json_encode($loc_struct);
	//file_put_contents("php://stdout", "\n>$log<");
	if (count($loc_struct)>0){

      return $loc_struct[0];
	  }
	return null;
}

/**
* Gets the first location
* @param $name - the name of the station
* @returns the first location or null
* @TODO better sorting
*/
function getfirstlocation($name){
	$loc_struct=getlocation($name);
	$n=count($loc_struct);
	//file_put_contents("php://stdout", "\n num results>$n<");
	$log=json_encode($loc_struct);
	//file_put_contents("php://stdout", "\n>$log<");
	if (count($loc_struct)>0){
	  $id =$loc_struct[0]['id'];
	  file_put_contents("php://stdout", "\nid: >$id<");
      return $id;
	  }
	return null;
}

/**
 * Calculates the great-circle distance between two points, with
 * the Haversine formula.
 * @param float $latitudeFrom Latitude of start point in [deg decimal]
 * @param float $longitudeFrom Longitude of start point in [deg decimal]
 * @param float $latitudeTo Latitude of target point in [deg decimal]
 * @param float $longitudeTo Longitude of target point in [deg decimal]
 * @param float $earthRadius Mean earth radius in [m]
 * @return float Distance between points in [m] (same as earthRadius)
 * @see http://stackoverflow.com/questions/10053358/measuring-the-distance-between-two-coordinates-in-php
 */
function haversineGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
  // convert from degrees to radians
  $latFrom = deg2rad($latitudeFrom);
  $lonFrom = deg2rad($longitudeFrom);
  $latTo = deg2rad($latitudeTo);
  $lonTo = deg2rad($longitudeTo);

  $latDelta = $latTo - $latFrom;
  $lonDelta = $lonTo - $lonFrom;

  $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
    cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
  return $angle * $earthRadius;
}
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/white"/>

    <corners
        android:bottomRightRadius="3dp"
        android:topRightRadius="3dp"/>

</shape>


text:
using System.Globalization;
using System.Runtime.CompilerServices;
using Jint.Collections;
using Jint.Native.Function;
using Jint.Native.Object;
using Jint.Runtime;
using Jint.Runtime.Descriptors;
using Jint.Runtime.Interop;

namespace Jint.Native.Date
{
    /// <summary>
    /// https://tc39.es/ecma262/#sec-date-constructor
    /// </summary>
    internal sealed class DateConstructor : FunctionInstance, IConstructor
    {
        internal static readonly DateTime Epoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        private static readonly string[] DefaultFormats = {
            "yyyy-MM-dd",
            "yyyy-MM",
            "yyyy"
        };

        private static readonly string[] SecondaryFormats = {
            "yyyy-MM-ddTHH:mm:ss.FFF",
            "yyyy-MM-ddTHH:mm:ss",
            "yyyy-MM-ddTHH:mm",

            // Formats used in DatePrototype toString methods
            "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
            "ddd MMM dd yyyy",
            "HH:mm:ss 'GMT'K",

            // standard formats
            "yyyy-M-dTH:m:s.FFFK",
            "yyyy/M/dTH:m:s.FFFK",
            "yyyy-M-dTH:m:sK",
            "yyyy/M/dTH:m:sK",
            "yyyy-M-dTH:mK",
            "yyyy/M/dTH:mK",
            "yyyy-M-d H:m:s.FFFK",
            "yyyy/M/d H:m:s.FFFK",
            "yyyy-M-d H:m:sK",
            "yyyy/M/d H:m:sK",
            "yyyy-M-d H:mK",
            "yyyy/M/d H:mK",
            "yyyy-M-dK",
            "yyyy/M/dK",
            "yyyy-MK",
            "yyyy/MK",
            "yyyyK",
            "THH:mm:ss.FFFK",
            "THH:mm:ssK",
            "THH:mmK",
            "THHK"
        };

        private static readonly JsString _functionName = new JsString("Date");

        internal DateConstructor(
            Engine engine,
            Realm realm,
            FunctionPrototype functionPrototype,
            ObjectPrototype objectPrototype)
            : base(engine, realm, _functionName)
        {
            _prototype = functionPrototype;
            PrototypeObject = new DatePrototype(engine, this, objectPrototype);
            _length = new PropertyDescriptor(7, PropertyFlag.Configurable);
            _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
        }

        internal DatePrototype PrototypeObject { get; }

        protected override void Initialize()
        {
            const PropertyFlag LengthFlags = PropertyFlag.Configurable;
            const PropertyFlag PropertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable;

            var properties = new PropertyDictionary(3, checkExistingKeys: false)
            {
                ["parse"] = new(new ClrFunctionInstance(Engine, "parse", Parse, 1, LengthFlags), PropertyFlags),
                ["UTC"] = new(new ClrFunctionInstance(Engine, "UTC", Utc, 7, LengthFlags), PropertyFlags),
                ["now"] = new(new ClrFunctionInstance(Engine, "now", Now, 0, LengthFlags), PropertyFlags)
            };
            SetProperties(properties);
        }

        /// <summary>
        /// https://tc39.es/ecma262/#sec-date.parse
        /// </summary>
        private JsValue Parse(JsValue thisObj, JsValue[] arguments)
        {
            var date = TypeConverter.ToString(arguments.At(0));
            var negative = date.StartsWith("-");
            if (negative)
            {
                date = date.Substring(1);
            }

            var startParen = date.IndexOf('(');
            if (startParen != -1)
            {
                // informative text
                date = date.Substring(0, startParen);
            }

            date = date.Trim();

            if (!DateTime.TryParseExact(date, DefaultFormats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var result))
            {
                if (!DateTime.TryParseExact(date, SecondaryFormats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result))
                {
                    if (!DateTime.TryParse(date, Engine.Options.Culture, DateTimeStyles.AdjustToUniversal, out result))
                    {
                        if (!DateTime.TryParse(date, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result))
                        {
                            // unrecognized dates should return NaN (15.9.4.2)
                            return JsNumber.DoubleNaN;
                        }
                    }
                }
            }

            return FromDateTime(result, negative);
        }

        private static JsValue Utc(JsValue thisObj, JsValue[] arguments)
        {
            var y = TypeConverter.ToNumber(arguments.At(0));
            var m = TypeConverter.ToNumber(arguments.At(1, JsNumber.PositiveZero));
            var dt = TypeConverter.ToNumber(arguments.At(2, JsNumber.PositiveOne));
            var h = TypeConverter.ToNumber(arguments.At(3, JsNumber.PositiveZero));
            var min = TypeConverter.ToNumber(arguments.At(4, JsNumber.PositiveZero));
            var s = TypeConverter.ToNumber(arguments.At(5, JsNumber.PositiveZero));
            var milli = TypeConverter.ToNumber(arguments.At(6, JsNumber.PositiveZero));

            var yInteger = TypeConverter.ToInteger(y);
            if (!double.IsNaN(y) && 0 <= yInteger && yInteger <= 99)
            {
                y  = yInteger + 1900;
            }

            var finalDate = DatePrototype.MakeDate(
                DatePrototype.MakeDay(y, m, dt),
                DatePrototype.MakeTime(h, min, s, milli));

            return finalDate.TimeClip();
        }

        private static JsValue Now(JsValue thisObj, JsValue[] arguments)
        {
            return System.Math.Floor((DateTime.UtcNow - Epoch).TotalMilliseconds);
        }

        protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
        {
            return PrototypeObject.ToString(Construct(Arguments.Empty, thisObject), Arguments.Empty);
        }

        ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) => Construct(arguments, newTarget);

        /// <summary>
        /// https://tc39.es/ecma262/#sec-date
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
        {
            // fast path is building default, new Date()
            if (arguments.Length == 0 || newTarget.IsUndefined())
            {
                return OrdinaryCreateFromConstructor(
                    newTarget,
                    static intrinsics => intrinsics.Date.PrototypeObject,
                    static (engine, _, dateValue) => new JsDate(engine, dateValue),
                    (DateTime.UtcNow - Epoch).TotalMilliseconds);
            }

            return ConstructUnlikely(arguments, newTarget);
        }

        private JsDate ConstructUnlikely(JsValue[] arguments, JsValue newTarget)
        {
            double dv;
            if (arguments.Length == 1)
            {
                if (arguments[0] is JsDate date)
                {
                    return Construct(date.DateValue);
                }

                var v = TypeConverter.ToPrimitive(arguments[0]);
                if (v.IsString())
                {
                    return Construct(((JsNumber) Parse(Undefined, Arguments.From(v)))._value);
                }

                dv = TypeConverter.ToNumber(v);
            }
            else
            {
                var y = TypeConverter.ToNumber(arguments.At(0));
                var m = TypeConverter.ToNumber(arguments.At(1));
                var dt = TypeConverter.ToNumber(arguments.At(2, JsNumber.PositiveOne));
                var h = TypeConverter.ToNumber(arguments.At(3, JsNumber.PositiveZero));
                var min = TypeConverter.ToNumber(arguments.At(4, JsNumber.PositiveZero));
                var s = TypeConverter.ToNumber(arguments.At(5, JsNumber.PositiveZero));
                var milli = TypeConverter.ToNumber(arguments.At(6, JsNumber.PositiveZero));

                var yInteger = TypeConverter.ToInteger(y);
                if (!double.IsNaN(y) && 0 <= yInteger && yInteger <= 99)
                {
                    y += 1900;
                }

                var finalDate = DatePrototype.MakeDate(
                    DatePrototype.MakeDay(y, m, dt),
                    DatePrototype.MakeTime(h, min, s, milli));

                dv = PrototypeObject.Utc(finalDate);
            }

            return OrdinaryCreateFromConstructor(
                newTarget,
                static intrinsics => intrinsics.Date.PrototypeObject,
                static (engine, _, dateValue) => new JsDate(engine, dateValue), dv);
        }

        public JsDate Construct(DateTimeOffset value) => Construct(value.UtcDateTime);

        public JsDate Construct(DateTime value) => Construct(FromDateTime(value));

        public JsDate Construct(double time)
        {
            return OrdinaryCreateFromConstructor(
                Undefined,
                static intrinsics => intrinsics.Date.PrototypeObject,
                static (engine, _, dateValue) => new JsDate(engine, dateValue), time);
        }

        internal double FromDateTime(DateTime dt, bool negative = false)
        {
            var convertToUtcAfter = dt.Kind == DateTimeKind.Unspecified;

            var dateAsUtc = dt.Kind == DateTimeKind.Local
                ? dt.ToUniversalTime()
                : DateTime.SpecifyKind(dt, DateTimeKind.Utc);

            double result;
            if (negative)
            {
                var zero = (Epoch - DateTime.MinValue).TotalMilliseconds;
                result = zero - TimeSpan.FromTicks(dateAsUtc.Ticks).TotalMilliseconds;
                result *= -1;
            }
            else
            {
                result = (dateAsUtc - Epoch).TotalMilliseconds;
            }

            if (convertToUtcAfter)
            {
                result = PrototypeObject.Utc(result);
            }

            return System.Math.Floor(result);
        }
    }
}


text:
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
var expect = chai.expect;
chai.use(sinonChai);

var $ = require('jquery');

var Arrow = require('../app/models/arrow');

describe("Arrow", function () {

  var arrow;
  beforeEach(function () {
    arrow = new Arrow();
  });

  describe('attributes', function () {

    it('has attributes', function () {
      expect( Arrow.ATTRS ).not.to.eql(undefined);
    });

    it('responds to getAttrs with all the attributes', function () {
      expect( arrow.getAttrs ).to.be.a('function');
      expect( arrow.getAttrs() ).to.eql(arrow._attributes);
    });

    describe('getters and setters', function () {
      it('has getters and setters', function () {
        expect( arrow.get ).to.be.a('function');
        expect( arrow.set ).to.be.a('function');
      });
    });
  });

  describe('eventing', function () {

    var $arrow;

    beforeEach(function () {
      $arrow = arrow._$self;
    });

    it('has an "on" method', function () {
      expect( arrow.on ).to.be.a('function');
    });

    it('delegates "on" to jQuery.on', function () {
      var spy = sinon.spy($arrow, 'on');

      arrow.on('change', function () {});

      expect(spy).to.have.been.called;
    });

    it('has a "fire" method', function () {
      expect( arrow.fire ).to.be.a('function');
    });

    it('delegates "fire" to jQuery.trigger', function () {
      var spy = sinon.spy($arrow, 'trigger');

      arrow.fire('change');

      expect(spy).to.have.been.called;
    });

    it('fires a "change" event when setting attributes', function () {
      var spy = sinon.spy(arrow, 'fire');

      arrow.set('position', 'bottom');

      expect(spy).to.have.been.calledWith('change');
    });
  });

  describe('inverted position', function () {

    it('inverts "top"', function () {
      arrow.set('position', 'top');
      expect( arrow.invertedPosition() ).to.eql('bottom');
    });

    it('inverts "bottom"', function () {
      arrow.set('position', 'bottom');
      expect( arrow.invertedPosition() ).to.eql('top');
    });

    it('inverts "left"', function () {
      arrow.set('position', 'left');
      expect( arrow.invertedPosition() ).to.eql('right');
    });

    it('inverts "right"', function () {
      arrow.set('position', 'right');
      expect( arrow.invertedPosition() ).to.eql('left');
    });

  });

  describe('convert hex color to rgb color', function () {

    it('converts "#888"', function () {
      expect( arrow.hexToRGB('#888') ).to.eql([136 , 136 , 136]);
    });

    it('converts "#88B7D5"', function () {
      expect( arrow.hexToRGB('#88B7D5') ).to.eql([136, 183, 213]);
    });

    it('converts "#C2E1F5"', function () {
      expect( arrow.hexToRGB('#C2E1F5') ).to.eql([194, 225, 245]);
    });

    it('returns [0, 0, 0] if there is no input color', function () {
      expect( arrow.hexToRGB() ).to.eql([0, 0, 0]);
    });

    it('returns [0, 0, 0] if the input color is invalid', function () {
      expect( arrow.hexToRGB('invalid') ).to.eql([0, 0, 0]);
    });

  });

  describe('toCSS', function () {

    describe('baseCSS', function () {

      it('is position: relative', function () {
        var css = arrow._baseCSS();
        expect( css ).to.contain( 'position: relative' );
      });

      it('has base arrow css', function () {
        var css = arrow._baseCSS(),
            expected;

        expected = '\tbottom: 100%;\n';
        expected = '\tleft: 50%;\n';
        expected += '\tborder: solid transparent;\n';
        expected += '\tcontent: " ";\n';
        expected += '\theight: 0;\n';
        expected += '\twidth: 0;\n';
        expected += '\tposition: absolute;\n';

        expect( css ).to.contain( expected );
      });

      it('sets offset using invertedPosition', function () {
        ['top', 'right', 'bottom', 'left'].forEach(function (pos, i) {
          arrow.set('position', pos);
          expect( arrow._baseCSS() ).to.contain(
            arrow.invertedPosition() + ': 100%'
          );
        });
      });

      describe('width border', function () {
        beforeEach(function () { arrow.set('borderWidth', 2); });

        it('has background and border colors', function () {
          var css                 = arrow._baseCSS(),
              color               = arrow.get('color'),
              borderWidth         = arrow.get('borderWidth'),
              borderColor         = arrow.get('borderColor'),
              expectedBackground  = 'background: ' + color,
              expectedBorder      = 'border: ' + borderWidth + 'px solid ' + borderColor;

          expect( css ).to.contain( expectedBackground );
          expect( css ).to.contain( expectedBorder);
        });

        it("targets both :before and :after", function () {
          var css = arrow._baseCSS();
          expect( css ).to.contain(':before');
          expect( css ).to.contain(':after');
        });
      });

      describe('without border', function () {
        beforeEach(function () { arrow.set('borderWidth', 0); });

        it('only has background', function () {
          var css                 = arrow._baseCSS(),
              color               = arrow.get('color'),
              borderWidth         = arrow.get('borderWidth'),
              borderColor         = arrow.get('borderColor'),
              expectedBackground  = 'background: ' + color,
              expectedBorder      = 'border: ' + borderWidth + 'px solid ' + borderColor;

          expect( css ).to.contain( expectedBackground );
          expect( css ).not.to.contain( expectedBorder );
        });

        it("doesn't have :before", function () {
          var css = arrow._baseCSS();
          expect( css ).not.to.contain(':before');
        });
      });
    });

    describe('_arrowCSS', function () {
      it('it has the correct size', function () {
        var expected = 'border-width: 20px';
        expect( arrow._arrowCSS('red', 20) ).to.contain( expected );
      });

      it('it has the correct color', function () {
        var css = arrow._arrowCSS('#888', 20);
        expect( css ).to.contain( 'border-bottom-color: #888' );
        expect( css ).to.contain( 'border-color: rgba(136, 136, 136, 0)' );
      });

      describe('position top', function () {
        beforeEach(function () { arrow.set('position', 'top'); });

        it('is centered', function () {
          var arrowcss = arrow._arrowCSS('red', 20),
              basecss = arrow._baseCSS();
          expect( basecss ).to.contain( 'left: 50%' );
          expect( arrowcss ).to.contain( 'margin-left: -20px' );
        });
      });

      describe('position bottom', function () {
        beforeEach(function () { arrow.set('position', 'bottom'); });

        it('is centered', function () {
          var arrowcss = arrow._arrowCSS('red', 20),
              basecss = arrow._baseCSS();
          expect( basecss ).to.contain( 'left: 50%' );
          expect( arrowcss ).to.contain( 'margin-left: -20px' );
        });
      });

      describe('position right', function () {
        beforeEach(function () { arrow.set('position', 'right'); });

        it('is centered', function () {
          var arrowcss = arrow._arrowCSS('red', 20),
              basecss = arrow._baseCSS();
          expect( basecss ).to.contain( 'top: 50%' );
          expect( arrowcss ).to.contain( 'margin-top: -20px' );
        });
      });

      describe('position left', function () {
        beforeEach(function () { arrow.set('position', 'left'); });

        it('is centered', function () {
          var arrowcss = arrow._arrowCSS('red', 20),
              basecss = arrow._baseCSS();
          expect( basecss ).to.contain( 'top: 50%' );
          expect( arrowcss ).to.contain( 'margin-top: -20px' );
        });
      });

    });

    describe('_baseArrowCSS', function () {
      it('delegates to _arrowCSS', function () {
        var spy = sinon.spy( arrow, '_arrowCSS' );

        arrow._baseArrowCSS();

        expect( spy ).to.have.been.calledWith(
          arrow.get('color'),
          arrow.get('size'),
          'after'
        );
      });
    });

    describe('_arrowBorderCSS', function () {
      it('delegates to _arrowCSS', function () {
        var spy = sinon.spy( arrow, '_arrowCSS' );

        arrow._arrowBorderCSS();

        expect( spy ).to.have.been.calledWith(
          arrow.get('borderColor'),
          arrow.get('size') + Math.round(arrow.get('borderWidth') * 1.41421356),
          'before'
        );
      });
    });

    it('combines pieces', function () {
      var expected = [
        arrow._baseCSS(),
        arrow._baseArrowCSS(),
        arrow._arrowBorderCSS()
      ].join('\n');

      expect( arrow.toCSS() ).to.eql( expected );
    });

  });

});


text:
.. currentmodule:: climt

===============
Initialisation
===============

.. autosummary::
    :toctree: generated/

    get_default_state
    get_grid


text:
.jumbotron { margin-top: 10px; }
.disp-none { display: none; }
.note { font-size: 0.85em; }

#stage {
  border: 1px solid #5afbea;
}
#loader .spin-animate {
  margin-right: 0.5em;
  -animation: spin 1s infinite linear;
  -ms-animation: spin 1s infinite linear;
  -webkit-animation: spinw 1s infinite linear;
  -moz-animation: spinm 1s infinite linear;
  -o-animation: spin 1s infinite linear;
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg);}
    to { transform: scale(1) rotate(360deg);}
}

@-webkit-keyframes spinw {
    from { -webkit-transform: rotate(0deg);}
    to { -webkit-transform: rotate(360deg);}
}

@-moz-keyframes spinm {
    from { -moz-transform: rotate(0deg);}
    to { -moz-transform: rotate(360deg);}
}

#icons img {
  width: 100%;
}
#icon_thumb_circle {
  border: 2px solid #ffae38;
}

#download_container {
  margin: 20px 0;
}


text:
from datetime import datetime
import re
import unicodedata

def str2bool(string):
    if not string:
        return False
    if isinstance(string, (str, unicode)):
        string = string.lower()
        options = ['none', 'null', 'nil', 'false', 'f', 'no', '0']
        return not (string in options)
    return string

def smart_split(text, comma=','):
    if isinstance(text, (str, unicode)):
        text = text.strip()
        text = text.split(comma)
        text = map(lambda x: x.strip(), text)
        text = filter(str, text)
        text = list(set(text))
    return text

def to_lower_case(text):
    if text:
        if isinstance(text, (str, unicode)):
            text = text.lower()
        elif isinstance(text, (list, set)):
            text = map(lambda x: x.lower(), text)
    return text

def normalize(string):
    if not isinstance(string, unicode):
        string = unicode(string, encoding='utf-8', errors='ignore')
    return unicodedata.normalize('NFKD', string).encode('ascii', 'ignore')

def taggify(text_or_list, comma=','):
    a_list = smart_split(text_or_list, comma=comma)
    a_list = to_lower_case(a_list)
    if a_list and isinstance(a_list, (list, set)):
        a_list = map(lambda x: x.strip(), a_list)
        a_list = filter(str, a_list)
        a_list = map(normalize, a_list)
        a_list = list(set(a_list))
    return a_list

#http://refactormycode.com/codes/675-camelcase-to-camel-case-python-newbie
def space_out_camel_case(str_as_camel_case, join=' '):
    """Adds spaces to a camel case string.  Failure to space out string returns the original string.
    >>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
    'DMLS Services Other BS Text LLC'
    """
    if str_as_camel_case is None:
        return None
    pattern = re.compile('([A-Z][A-Z][a-z])|([a-z][A-Z])')
    return pattern.sub(lambda m: m.group()[:1] + join + m.group()[1:], str_as_camel_case)

STRIP_REGEXP = re.compile(r'[^\w\s-]')
HYPHENATE_REGEXP = re.compile(r'[-\s]+')
def slugify(value):
    if not value:
        return value
    value = space_out_camel_case(value)
    value = normalize(value)
    value = unicode(STRIP_REGEXP.sub('', value).strip().lower())
    value = HYPHENATE_REGEXP.sub('-', value)
    value = re.sub('-{2,}', '-', value)
    return value

def slugify_with_date(value):
    if not value:
        return value
    value = slugify(value)
    return datetime.today().strftime('%Y-%m-%d') + '-' + value

def slugify_with_datetime(value):
    if not value:
        return value
    value = slugify(value)
    return datetime.now().strftime('%Y-%m-%dT%H:%M:%S') + '-' + value


text:
$(document).ready(function () {
    $("input[name=pw], input[name=pw2]").tooltipster({
        animation: 'fade',
        delay: 200,
        theme: 'tooltipster-light',
        trigger: 'custom',
        position: 'right',
        iconCloning: false,
        maxWidth: 400
    });

    $('input[name=pw]').tooltipster('content', 'Password must have between ' + $("input[name=pw]").attr('minlength') + ' and ' + $("input[name=pw]").attr('maxlength') + ' characters');
    $('input[name=pw2]').tooltipster('content', 'Passwords don\'t match');

    $("input[name=pw]").keyup(function() {
      checkPassword($(this));
    });

    $("input[name=pw2]").keyup(function() {
      checkPasswordConfirm($(this), $('input[name=pw]'));
    });

    function checkPassword(elm) {
      elm.tooltipster(!elm[0].checkValidity() ? 'show' : 'hide');
    }

    function checkPasswordConfirm(elm, pelm) {
      elm.tooltipster(elm.val() != pelm.val() ? 'show' : 'hide');
    }
  });


text:
2FactorWallet
=============

The prototype of a bitcoin wallet with two-factor authentication and verification over a seperate channel. This prototype uses a modified version of the two-party DSA signature protocol by MacKenzie and Reiter.

Further information can be found in the article _Two-factor authentication for the bitcoin protocol_ by Christopher Mann and Daniel Loebenberger (https://eprint.iacr.org/2014/629.pdf). For a detailed description refer to the master thesis by Christopher Mann [BitcoinTwoFactorAuth.pdf](https://github.com/ChristopherMann/2FactorWallet/raw/master/BitcoinTwoFactorAuth.pdf).

**This is a prototype. Do NOT use it for storing your real Bitcoins.**


text:
import os
import sys
import time
import codecs
import urllib

if os.name == 'nt':
    #import BTL.likewin32api as win32api
    import win32api
    from win32com.shell import shellcon, shell

is_frozen_exe = getattr(sys, 'frozen', '') == 'windows_exe'

def get_module_filename():
    if is_frozen_exe:
        return os.path.abspath(win32api.GetModuleFileName(0))
    else:
        return os.path.abspath(sys.argv[0])

try:
    from __main__ import app_name
except:
    # ok, I'm sick of this. Everyone gets BTL if they don't
    # specify otherwise.
    app_name = "BTL"

if sys.platform.startswith('win'):
    bttime = time.clock
else:
    bttime = time.time

def urlquote_error(error):
     s = error.object[error.start:error.end]
     s = s.encode('utf8')
     s = urllib.quote(s)
     s = s.decode('ascii')
     return (s, error.end)

codecs.register_error('urlquote', urlquote_error)

def get_filesystem_encoding(errorfunc=None):
    def dummy_log(e):
        print e
        pass
    if not errorfunc:
        errorfunc = dummy_log

    default_encoding = 'utf8'

    if os.path.supports_unicode_filenames:
        encoding = None
    else:
        try:
            encoding = sys.getfilesystemencoding()
        except AttributeError:
            errorfunc("This version of Python cannot detect filesystem encoding.")

        if encoding is None:
            encoding = default_encoding
            errorfunc("Python failed to detect filesystem encoding. "
                      "Assuming '%s' instead." % default_encoding)
        else:
            try:
                'a1'.decode(encoding)
            except:
                errorfunc("Filesystem encoding '%s' is not supported. Using '%s' instead." %
                          (encoding, default_encoding))
                encoding = default_encoding

    return encoding

def encode_for_filesystem(path):
    assert isinstance(path, unicode), "Path should be unicode not %s" % type(path)

    bad = False
    encoding = get_filesystem_encoding()
    if encoding == None:
        encoded_path = path
    else:
        try:
            encoded_path = path.encode(encoding)
        except:
            bad = True
            path.replace(u"%", urllib.quote(u"%"))
            encoded_path = path.encode(encoding, 'urlquote')

    return (encoded_path, bad)

def decode_from_filesystem(path):
    encoding = get_filesystem_encoding()
    if encoding == None:
        assert isinstance(path, unicode), "Path should be unicode not %s" % type(path)
        decoded_path = path
    else:
        assert isinstance(path, str), "Path should be str not %s" % type(path)
        decoded_path = path.decode(encoding)

    return decoded_path

efs = encode_for_filesystem

def efs2(path):
    # same as encode_for_filesystem, but doesn't bother returning "bad"
    return encode_for_filesystem(path)[0]

# this function is the preferred way to get windows' paths
def get_shell_dir(value):
    dir = None
    if os.name == 'nt':
        try:
            dir = shell.SHGetFolderPath(0, value, 0, 0)
        except:
            pass
    return dir

def get_cache_dir():
    dir = None
    if os.name == 'nt':
        dir = get_shell_dir(shellcon.CSIDL_INTERNET_CACHE)
    return dir


text:
require 'spec_helper'

describe SimpleDeploy::AWS::InstanceReader do
  include_context 'double stubbed logger'

  describe 'temporary credentials' do
    include_context 'double stubbed config', :access_key => 'key',
                                             :secret_key => 'XXX',
                                             :security_token => 'the token',
                                             :temporary_credentials? => true,
                                             :region     => 'us-west-1'

    it 'creates a connection with the temporary credentials' do
      args = {
        aws_access_key_id:     'key',
        aws_secret_access_key: 'XXX',
        aws_session_token:     'the token',
        region:                'us-west-1'
      }
      Fog::AWS::AutoScaling.should_receive(:new).with(args)
      Fog::Compute::AWS.should_receive(:new).with(args)
      SimpleDeploy::AWS::InstanceReader.new
    end

  end

  describe 'with long lived credentials' do
    include_context 'double stubbed config', :access_key => 'key',
                                             :secret_key => 'XXX',
                                             :security_token => nil,
                                             :temporary_credentials? => false,
                                             :region     => 'us-west-1'

    before do
      @auto_scaling_groups_mock = mock 'auto scaling'
      @cloud_formation_mock     = mock 'cloud formation'
      @ec2_mock                 = mock 'ec2'
      Fog::AWS::AutoScaling.stub(:new).and_return @auto_scaling_groups_mock
      Fog::Compute::AWS.stub(:new).and_return @ec2_mock
      SimpleDeploy::AWS::CloudFormation.stub(:new).
                                        and_return @cloud_formation_mock
    end

    describe "list_stack_instances" do
      before do
        instances = ['first',{ 'Instances' => [{ 'InstanceId' => 'i-000001' },
                                               { 'InstanceId' => 'i-000002' }] }]
        body =  { 'DescribeAutoScalingGroupsResult' => { 'AutoScalingGroups' => instances } }
        @list_response = stub 'Fog::Response', :body => body, :any? => true

        empty_body =  { 'DescribeAutoScalingGroupsResult' => { 'AutoScalingGroups' => [] } }
        @empty_response = stub 'Fog::Response', :body => empty_body

        @describe_response = stub 'Excon::Response', :body => {
          'reservationSet' => [{
            'instanceSet' => [{'instanceState' => {'name' => 'running'}},
                              {'ipAddress' => '54.10.10.1'},
                              {'instanceId' => 'i-123456'},
                              {'privateIpAddress' => '192.168.1.1'}]}]
        }
      end

      context "with no ASGs" do
        before do
          @cloud_formation_mock.should_receive(:stack_resources).
                                exactly(3).times.
                                with('stack').
                                and_return []
        end

        it "should return an empty array" do
          instance_reader = SimpleDeploy::AWS::InstanceReader.new
          instance_reader.list_stack_instances('stack').should == []
        end
      end

      context "with an ASGs" do
        before do
          stack_resource_results = []
          @asgs = ['asg1', 'asg2'].each do |asg|
            stack_resource_results << { 'StackName'          => 'stack',
                                        'ResourceType'       => 'AWS::AutoScaling::AutoScalingGroup',
                                        'PhysicalResourceId' => asg }
          end

          @cloud_formation_mock.should_receive(:stack_resources).
                                exactly(3).times.
                                with('stack').
                                and_return stack_resource_results
        end

        context "with no running instances" do
          it "should return empty array" do
            @asgs.each do |asg|
              @auto_scaling_groups_mock.should_receive(:describe_auto_scaling_groups).
                                        with('AutoScalingGroupNames' => [asg]).
                                        and_return(@empty_response)
            end

            instance_reader = SimpleDeploy::AWS::InstanceReader.new
            instance_reader.list_stack_instances('stack').should == []
          end
        end

        context "with running instances" do
          it "should return the reservation set for each running instance" do
            @auto_scaling_groups_mock.should_receive(:describe_auto_scaling_groups).
                                      with('AutoScalingGroupNames' => ['asg1']).
                                      and_return(@list_response)
            @auto_scaling_groups_mock.should_receive(:describe_auto_scaling_groups).
                                      with('AutoScalingGroupNames' => ['asg2']).
                                      and_return(@empty_response)
            @ec2_mock.should_receive(:describe_instances).
                      with('instance-state-name' => 'running',
                           'instance-id' => ['i-000001', 'i-000002']).
                      and_return @describe_response

            instance_reader = SimpleDeploy::AWS::InstanceReader.new
            instance_reader.list_stack_instances('stack').should == [{
              'instanceSet' => [{'instanceState' => {'name' => 'running'}},
                                {'ipAddress' => '54.10.10.1'},
                                {'instanceId' => 'i-123456'},
                                {'privateIpAddress' => '192.168.1.1'}]}]
          end
        end
      end

      context "with nested stacks and ASGs and EC2 instances" do
        before do
          stack_resource_results = []
          @nested_stacks = ['nested_stack1', 'nested_stack2'].each do |nested_stack|
            @cloud_formation_mock.should_receive(:stack_status).
              with(nested_stack).
              and_return 'CREATE_COMPLETE'
            stack_resource_results << { 'StackName'          => 'stack',
                                        'ResourceType'       => 'AWS::CloudFormation::Stack',
                                        'PhysicalResourceId' => nested_stack }
          end
          @asgs = ['asg1', 'asg2'].each do |asg|
            stack_resource_results << { 'StackName'          => 'stack',
                                        'ResourceType'       => 'AWS::AutoScaling::AutoScalingGroup',
                                        'PhysicalResourceId' => asg }
          end

          @instances = ['i-instance1', 'i-instance2'].each do |instance|
            stack_resource_results << { 'StackName'          => 'stack',
                                        'ResourceType'       => 'AWS::EC2::Instance',
                                        'PhysicalResourceId' => instance }
          end

          @cloud_formation_mock.should_receive(:stack_resources).
                                exactly(3).times.
                                with('stack').
                                and_return stack_resource_results
        end

        context "with running instances in nested stack and ASG and EC2 instances" do
          it "should return the reservation set for each running instance" do
            @cloud_formation_mock.should_receive(:stack_resources).
                                  exactly(3).times.
                                  with('nested_stack1').
                                  and_return []

            nested_stack2_resource_results = []
            @asgs = ['nested_stack2_asg1', 'nested_stack2_asg2'].each do |nested_stack2_resource_asg|
              nested_stack2_resource_results << { 'StackName'  => 'nested_stack2',
                                                  'ResourceType'       => 'AWS::AutoScaling::AutoScalingGroup',
                                                  'PhysicalResourceId' => nested_stack2_resource_asg }
            end

            @cloud_formation_mock.should_receive(:stack_resources).
                                  exactly(3).times.
                                  with('nested_stack2').
                                  and_return nested_stack2_resource_results
            nested_list_response = stub 'Fog::Response', :body => { 'DescribeAutoScalingGroupsResult' =>
                                                                    { 'AutoScalingGroups' => ['first',
                                                                                { 'Instances' => [{ 'InstanceId' => 'i-stack001' },
                                                                                { 'InstanceId' => 'i-stack002' }] }] } },
                                                         :any? => true
            @auto_scaling_groups_mock.should_receive(:describe_auto_scaling_groups).
                                      with('AutoScalingGroupNames' => ['nested_stack2_asg1']).
                                      and_return(nested_list_response)

            @auto_scaling_groups_mock.should_receive(:describe_auto_scaling_groups).
                                      with('AutoScalingGroupNames' => ['nested_stack2_asg2']).
                                      and_return(@empty_response)

            @auto_scaling_groups_mock.should_receive(:describe_auto_scaling_groups).
                                      with('AutoScalingGroupNames' => ['asg1']).
                                      and_return(@list_response)
            @auto_scaling_groups_mock.should_receive(:describe_auto_scaling_groups).
                                      with('AutoScalingGroupNames' => ['asg2']).
                                      and_return(@empty_response)

            @ec2_mock.should_receive(:describe_instances).
                      with('instance-state-name' => 'running',
                           'instance-id' => ['i-stack001', 'i-stack002']).
                      and_return @describe_response

            @ec2_mock.should_receive(:describe_instances).
                      with('instance-state-name' => 'running',
                           'instance-id' => ['i-000001', 'i-000002','i-instance1', 'i-instance2'] ).
                      and_return @describe_response

            instance_reader = SimpleDeploy::AWS::InstanceReader.new
            instance_reader.list_stack_instances('stack').should == [{
              'instanceSet' => [{'instanceState' => {'name' => 'running'}},
                                {'ipAddress' => '54.10.10.1'},
                                {'instanceId' => 'i-123456'},
                                {'privateIpAddress' => '192.168.1.1'}]}, {
              'instanceSet' => [{'instanceState' => {'name' => 'running'}},
                                {'ipAddress' => '54.10.10.1'},
                                {'instanceId' => 'i-123456'},
                                {'privateIpAddress' => '192.168.1.1'}]}]
          end
        end
      end

    end
  end
end


text:
package model

trait LabelComponent extends TemplateComponent { self: Profile =>
  import profile.simple._

  lazy val Labels = TableQuery[Labels]

  class Labels(tag: Tag) extends Table[Label](tag, "LABEL") with LabelTemplate {
    override val labelId = column[Int]("LABEL_ID", O AutoInc)
    val labelName = column[String]("LABEL_NAME")
    val color = column[String]("COLOR")
    def * = (userName, repositoryName, labelId, labelName, color) <> (Label.tupled, Label.unapply)

    def byPrimaryKey(owner: String, repository: String, labelId: Int) = byLabel(owner, repository, labelId)
    def byPrimaryKey(userName: Column[String], repositoryName: Column[String], labelId: Column[Int]) = byLabel(userName, repositoryName, labelId)
  }
}

case class Label(
  userName: String,
  repositoryName: String,
  labelId: Int = 0,
  labelName: String,
  color: String){

  val fontColor = {
    val r = color.substring(0, 2)
    val g = color.substring(2, 4)
    val b = color.substring(4, 6)

    if(Integer.parseInt(r, 16) + Integer.parseInt(g, 16) + Integer.parseInt(b, 16) > 408){
      "000000"
    } else {
      "FFFFFF"
    }
  }
}


text:
GOFLAGS ?= $(GOFLAGS:)
PACKAGE := github.com/http2d/server

all: install test

install:
ifdef GODEBUG
		godebug build -instrument "${GODEBUG}" ./...
else
	  @go install -x $(GOFLAGS) ./...
endif

build:
	@go build -x -o bin/core.a ./core
	@go build -x -o bin/handlers.a ./handlers
	@go build -x -o bin/QA ./QA

test: install
	@go test $(GOFLAGS) ./...

bench: install
	@go test -run=NONE -bench=. $(GOFLAGS) ./...

clean:
	@go clean $(GOFLAGS) -i ./...

deps:
	# Development tools
	@go get -v -u github.com/cespare/reflex
	@go get -v -u github.com/mailgun/godebug

	# Dependencies
	@go get -v -u golang.org/x/net/http2
	@go get -v -u github.com/gorilla/mux
	@go get -v -u github.com/Sirupsen/logrus
	@go get -v -u github.com/stretchr/testify

	# Code Coverage
	@go get -v -u golang.org/x/tools/cmd/cover
	@go get -v -u github.com/mattn/goveralls
	@go get -v -u github.com/axw/gocov/gocov

run: install
	server

devel: install
	reflex --regex='\.go$$' --start-service -- sh -c 'make run'

PHONY: all test clean install deps run devel


text:
<?php

namespace Test\Pager\Subscriber\Paginate\Doctrine\ORM\QueryTest;

use Test\Tool\BaseTestCaseORM;
use Knp\Component\Pager\Paginator;
use Knp\Component\Pager\Pagination\SlidingPagination;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Knp\Component\Pager\Pagination\PaginationInterface;
use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\QuerySubscriber;
use Knp\Component\Pager\Event\Subscriber\Paginate\PaginationSubscriber;
use Test\Fixture\Entity\Shop\Product;
use Test\Fixture\Entity\Shop\Tag;
use Doctrine\ORM\Query;
use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\QuerySubscriber\UsesPaginator;

class UsesPaginatorTest extends BaseTestCaseORM
{
    /**
     * @test
     */
    function shouldUseOutputWalkersIfAskedTo()
    {
        $this->populate();

        $dql = <<<___SQL
        SELECT p, t
        FROM Test\Fixture\Entity\Shop\Product p
        INNER JOIN p.tags t
        GROUP BY p.id
        HAVING p.numTags = COUNT(t)
___SQL;
        $q = $this->em->createQuery($dql);
        $q->setHydrationMode(Query::HYDRATE_ARRAY);
        $q->setHint(UsesPaginator::HINT_FETCH_JOIN_COLLECTION, true);
        $this->startQueryLog();
        $p = new Paginator;
        $view = $p->paginate($q, 1, 10, array('wrap-queries' => true));
        $this->assertEquals(3, $this->queryAnalyzer->getNumExecutedQueries());
        $this->assertEquals(3, count($view));
    }

    /**
     * @test
     */
    function shouldNotUseOutputWalkersByDefault()
    {
        $this->populate();

        $dql = <<<___SQL
        SELECT p
        FROM Test\Fixture\Entity\Shop\Product p
        GROUP BY p.id
___SQL;
        $q = $this->em->createQuery($dql);
        $q->setHint(UsesPaginator::HINT_FETCH_JOIN_COLLECTION, false);
        $q->setHydrationMode(Query::HYDRATE_ARRAY);
        $this->startQueryLog();
        $p = new Paginator;
        $view = $p->paginate($q, 1, 10, array('wrap-queries' => false));
        $this->assertEquals(2, $this->queryAnalyzer->getNumExecutedQueries());
        $this->assertEquals(3, count($view));
    }

    /**
     * @test
     */
    function shouldFetchJoinCollectionsIfNeeded()
    {
        $this->populate();

        $dql = <<<___SQL
        SELECT p, t
        FROM Test\Fixture\Entity\Shop\Product p
        INNER JOIN p.tags t
        GROUP BY p.id
        HAVING p.numTags = COUNT(t)
___SQL;
        $q = $this->em->createQuery($dql);
        $q->setHydrationMode(Query::HYDRATE_ARRAY);
        $q->setHint(UsesPaginator::HINT_FETCH_JOIN_COLLECTION, true);
        $this->startQueryLog();
        $p = new Paginator;
        $view = $p->paginate($q, 1, 10, array('wrap-queries' => true));
        $this->assertEquals(3, $this->queryAnalyzer->getNumExecutedQueries());
        $this->assertEquals(3, count($view));
    }

    protected function getUsedEntityFixtures()
    {
        return array(
            'Test\Fixture\Entity\Shop\Product',
            'Test\Fixture\Entity\Shop\Tag'
        );
    }

    private function populate()
    {
        $em = $this->getMockSqliteEntityManager();
        $cheep = new Tag;
        $cheep->setName('Cheep');

        $new = new Tag;
        $new->setName('New');

        $special = new Tag;
        $special->setName('Special');

        $starship = new Product;
        $starship->setTitle('Starship');
        $starship->setPrice(277.66);
        $starship->addTag($new);
        $starship->addTag($special);

        $cheese = new Product;
        $cheese->setTitle('Cheese');
        $cheese->setPrice(7.66);
        $cheese->addTag($cheep);

        $shoe = new Product;
        $shoe->setTitle('Shoe');
        $shoe->setPrice(2.66);
        $shoe->addTag($special);

        $em->persist($special);
        $em->persist($cheep);
        $em->persist($new);
        $em->persist($starship);
        $em->persist($cheese);
        $em->persist($shoe);
        $em->flush();
    }
}


text:
CKEDITOR.plugins.setLang( 'codemirror', 'nl', {
	toolbar: 'Broncode',
	searchCode: 'Zoek in broncode',
	autoFormat: 'Formatteer selectie',
	commentSelectedRange: 'Zet selectie in commentaar',
	uncommentSelectedRange: 'Haal selectie uit commentaar',
	autoCompleteToggle: 'Zet automatisch aanvullen van HTML tags aan/uit'
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="headerTextSize">15sp</dimen>
    <dimen name="elementTextTitleSize">14sp</dimen>
    <dimen name="elementTextValueSize">13sp</dimen>
</resources>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessEngine.DataModel
{
    public class Constants
    {
        public static int TYPE_UNITE_KEY = 1;
        public static int TYPE_BLOCK_KEY = 2;

        public static string PRIVILEGE_SU_KEY = "_SU_";
        public static string PRIVILEGE_ADMIN_KEY = "_ADMIN_";
        public static string PRIVILEGE_USTOCK_KEY = "_USTOCK_";
        public static string PRIVILEGE_USER_KEY = "_USER_";

        public static string FOURNISSEUR_RETOUR_FACTURE_CLIENT = "RETOUR_FACTURE_CLIENT";
    }
}


text:
package net.skoumal.forceupdate.example;

import android.app.Activity;
import android.app.Application;
import android.content.SharedPreferences;

import net.skoumal.forceupdate.ForceUpdate;
import net.skoumal.forceupdate.UpdateView;
import net.skoumal.forceupdate.Version;
import net.skoumal.forceupdate.VersionProvider;
import net.skoumal.forceupdate.example.activites.CustomForceUpdateActivity;
import net.skoumal.forceupdate.example.activites.ResetVersionsForceUpdateActivity;
import net.skoumal.forceupdate.example.provider.SharedPreferencesVersionProvider;
import net.skoumal.forceupdate.provider.ApkVersionProvider;
import net.skoumal.forceupdate.util.Versions;
import net.skoumal.forceupdate.view.activity.ActivityUpdateView;
import net.skoumal.forceupdate.view.activity.RecommendedUpdateActivity;

/**
 * Created by Tadeas on 27.09.2016.
 */

public class ExampleApp extends Application {

    private final static boolean SHOW_CUSTOM_FORCED_VIEW = false;

    private static ExampleApp instance;

    private VersionProvider currentVersionProvider;
    private SharedPreferencesVersionProvider minAllowedVersionProvider;
    private SharedPreferencesVersionProvider recommendedVersionProvider;
    private SharedPreferencesVersionProvider excludedVersionProvider;

    private ForceUpdate forceUpdate;

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;

        SharedPreferences preferences = getSharedPreferences(Constants.SHARED_PREFERENCES_VERSIONS,
                MODE_PRIVATE);

        /*
            -- Current version --

            The simples way to provide current version is via ApkVersionProvider, but you can
            implement your own provider of course.
          */
        currentVersionProvider = new ApkVersionProvider(this);

        /*
            -- Min allowed and recommended version --

            For this example purposes we use SharedPreferencesVersionProvider to fake min-allowed
            and recommended version. It is also great example of custom VersionProvider, but for
            real world purposes see use one of ready-to-use VersionProviders, or implement your own:

            https://github.com/skoumalcz/force-update/blob/master/doc/VersionProviders.md
         */
        Version defaultVersion = currentVersionProvider.getVersionResult().getVersion(); // default version when SharedPreferences are empty
        minAllowedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_MIN_ALLOWED_VERSION, defaultVersion);
        recommendedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_RECOMMENDED_VERSION, defaultVersion);

        /*
            -- Excluded version --

            To ban particular version we also use SharedPreferencesVersionProvider to fake it.
         */
        int [] apkVersionParts = currentVersionProvider.getVersionResult().getVersion().getVersionParts();
        Versions.decrementVersion(apkVersionParts);
        excludedVersionProvider = new SharedPreferencesVersionProvider(preferences, Constants.SHARED_PREFERENCES_EXCLUDED_VERSION, new Version(apkVersionParts));

        ForceUpdate.Builder builder = new ForceUpdate.Builder()
                .application(this)
                .debug(true)
                .currentVersionProvider(currentVersionProvider)
                .minAllowedVersionProvider(minAllowedVersionProvider)
                .recommendedVersionProvider(recommendedVersionProvider)
                .excludedVersionListProvider(excludedVersionProvider)
                .minAllowedVersionCheckMinInterval(1)
                .recommendedVersionCheckMinInterval(1)
                .excludedVersionListCheckMinInterval(1)
                .forcedUpdateView(new ActivityUpdateView(ResetVersionsForceUpdateActivity.class))
                .recommendedUpdateView(new ActivityUpdateView(RecommendedUpdateActivity.class));

        if (SHOW_CUSTOM_FORCED_VIEW) {
            //here you can show your custom activity or just exclude forcedUpdateView function to use default activity
            builder.addForceUpdateActivity(CustomForceUpdateActivity.class);
            builder.forcedUpdateView(new UpdateView() {
                @Override
                public void showView(Activity gActivity, Version gCurrentVersion, Version gRequiredVersion, String gUpdateMessage) {
                    CustomForceUpdateActivity.start(gActivity, gCurrentVersion.toString(), gRequiredVersion.toString(), gUpdateMessage);
                }
            });
        }

        forceUpdate = builder.buildAndInit();
    }

    public static ExampleApp getInstance() {
        return instance;
    }

    public VersionProvider getCurrentVersionProvider() {
        return currentVersionProvider;
    }

    public SharedPreferencesVersionProvider getMinAllowedVersionProvider() {
        return minAllowedVersionProvider;
    }

    public SharedPreferencesVersionProvider getRecommendedVersionProvider() {
        return recommendedVersionProvider;
    }

    public SharedPreferencesVersionProvider getExcludedVersionProvider() {
        return excludedVersionProvider;
    }

    public ForceUpdate getForceUpdate() {
        return forceUpdate;
    }
}


text:
/**
 * This class handles RTT event callbacks and passes the data to Objective-C
 * via blocks.
 */

#pragma once

#import <Foundation/Foundation.h>
#import "BrainCloudCompletionBlocks.hh"
#import "braincloud/BrainCloudClient.h"
#import "braincloud/IRTTCallback.h"

class BrainCloudRTTCallback final : public BrainCloud::IRTTCallback
{
public:
    void setEventBlock(BCRTTEventBlock eventBlock, BCCallbackObject cbObject)
    {
        m_eventBlock = eventBlock;
        m_cbObject = cbObject;
    }

protected:
    void rttCallback(const std::string& jsonData) override
    {
        if (m_eventBlock)
        {
            m_eventBlock([NSString stringWithUTF8String:jsonData.c_str()], m_cbObject);
        }
    }

private:
    BCRTTEventBlock m_eventBlock = nil;
    BCCallbackObject m_cbObject = nil;
};


text:
import {Observable} from '@reactivex/rxjs';
import {EOL} from 'os';
import {createWriteStream, truncateSync} from 'fs';
import json2csv from 'json2csv';
import Promise from 'bluebird';
import {property} from 'lodash';
import { closeMsConn } from '../database';

var toCSV = Promise.promisify(json2csv);

export class CsvCoupler {

  constructor() {
    this.defaultName = 'csv';
  }

  /**
   * converts an Observable that emits objects to an Observable that emits csv strings
   *
   * @param config {object}
   * @param srcObservable {Observable}
   * @returns {Observable}
   */
  toCsvObservable(config, srcObservable) {
    return srcObservable.concatMap(function (item, i) {
      if (i === 0) {
        let outputFilename = `output/crt/EOL - ${property(config.groupByProperty)(item)}-${config.prompt.table}.txt`;

        // creates file if it doesn't exist
        var ws = createWriteStream(outputFilename, {
          flags: 'a'
        });

        try {
          ws.on('open', function (fd) {
            truncateSync(outputFilename);
          });
        } catch (e) {
          console.log('couldn\'t truncate file');
          console.log('e == %j', e);
        }
      }
      let csvOutputObj;
      if (!config.outputProperty) {
        csvOutputObj = item;
      } else {
        csvOutputObj = property(config.outputProperty)(item);
      }
      return toCSV({
        data: csvOutputObj,
        del: '\t',
        hasCSVColumnTitle: i === 0 // print columns only if this is the first item emitted
      })
        .then(csvStr => {
          let csvRemQuotes = csvStr.replace(/"/g, '');

          // Add a newline character before every line except the first line
          let csvVal = i === 0 ? csvRemQuotes : EOL + csvRemQuotes;
          if (ws) {
            return {
              csv: csvVal,
              ws: ws
            };
          } else {
            return {
              csv: csvVal
            };
          }
        });

    });
  }

  /**
   *
   * @param observable {Observable}
   * @param channel {string} path to the property of the emitted item object that should be used to group items by
   * @returns {Observable}
   */
  to(channel, observable) {
    return observable
      .groupBy(x => property(channel.groupByProperty)(x))
      .subscribe(groupedObservable => {
        let ws;
        this.toCsvObservable(channel, groupedObservable).subscribe(
          item => {
            if (!ws && item.ws) {
              ws = item.ws;
            }
            ws.write(item.csv);
          },

          error => console.log('error == ', error),

          () => {
            console.log('close writestream');
            closeMsConn();
            ws.end();
          }
        );
      });
  }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="sharpen">
        <note>
            Frames file for 'sharpen' based on sentences in financial subcorpus
            and automatic expansion via verbnet.
        </note>

        <roleset id="sharpen.01" name="cause to become sharp(er)" vncls="45.4">
            <roles>
                <role descr="sharpener" n="0">
                    <vnrole vncls="45.4" vntheta="Agent"/>
                </role>
                <role descr="thing getting sharper" n="1">
                    <vnrole vncls="45.4" vntheta="Patient"/>
                </role>
                <role descr="instrument, if agent is also present" n="2">
                    <vnrole vncls="45.4" vntheta="Instrument"/>
                </role>

            </roles>

            <example name="just transitive">
                <inflection aspect="progressive" form="participle" person="third" tense="present" voice="active"/>
                <text>
                    The government is sharpening its newest weapon against
                    white-collar defendants: the power to prevent them from paying
                    their legal bills.
                </text>
                <arg n="0">The government</arg>
                <rel>sharpening</rel>
                <arg n="1">its newest weapon against white-collar defendants : the power   to prevent them from  paying their legal bills</arg>
            </example>

            <example name="with instrument">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    John sharpened his wits with frequent arguments with Mary.
                </text>
                <arg n="0">John</arg>
                <rel>sharpened</rel>
                <arg n="1">his wits</arg>
                <arg n="2">with frequent arguments with Mary</arg>
            </example>

            <example name="odd locative instrument">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    John sharpened his teeth on the doorstep.
                </text>
                <arg n="0">John</arg>
                <rel>sharpened</rel>
                <arg n="1">his teeth</arg>
                <arg n="2">on the doorstep</arg>
            </example>

        </roleset>
    </predicate>
</frameset>


text:
<?php

namespace Sitecake;

use League\Flysystem\Filesystem;

class FileLock {

	protected $fs;

	protected $tmpdir;

	public function __construct(Filesystem $fs, $tmpdir) {
		$this->fs = $fs;
		$this->tmpdir = $tmpdir;
	}

	public function set($name, $timeout = 0) {
		$t = ($timeout == 0) ? 0 : (string)(round(microtime(true) * 1000) + $timeout);
		$this->fs->put($this->path($name), $t);
	}

	public function remove($name) {
		$path = $this->path($name);
		if ($this->fs->has($path)) {
			$this->fs->delete($path);
		}
	}

	public function exists($name) {
		$file = $this->path($name);
		if ($this->fs->has($file)) {
			if ($this->timedout($file)) {
				$this->fs->delete($file);
				return false;
			} else {
				return true;
			}
		} else {
			return false;
		}
	}

	private function timedout($lock) {
		$timeout = intval($this->fs->read($lock));
		return $timeout == 0 ?
			false : ($timeout - round(microtime(true) * 1000)) < 0;
	}

	private function path($name) {
		return $this->tmpdir . '/' . $name . '.lock';
	}
}


text:
package org.apache.airavata.monitoring;

import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.monitoring.mailbox.MailConfig;

import java.util.Properties;

public class Util {
    /**
     * Fetch mail configurations.
     *
     * @return MailConfig
     */
    public static MailConfig getMailConfig() throws ApplicationSettingsException {
        MailConfig mailConfig = new MailConfig();
//        mailConfig.setHost(ServerSettings.getEmailBasedMonitorHost());
//        mailConfig.setUser(ServerSettings.getEmailBasedMonitorAddress());
//        mailConfig.setPassword(ServerSettings.getEmailBasedMonitorPassword());
//        mailConfig.setStoreProtocol(ServerSettings.getEmailBasedMonitorStoreProtocol());
//        mailConfig.setFolder(ServerSettings.getEmailBasedMonitorFolderName());
//        mailConfig.setPollingInterval(ServerSettings.getEmailMonitorPeriod());
        mailConfig.setHost("smtp.gmail.com");
        mailConfig.setUser("test.airavata@gmail.com");
        mailConfig.setPassword("airavata");
        mailConfig.setStoreProtocol("imaps");
        mailConfig.setFolder("inbox");
        mailConfig.setPollingInterval(1000);
//        Properties props = new Properties();
//        props.setProperty("mail.store.protocol", "imaps");
//        props.setProperty("mail.smtp.host", "smtp.gmail.com");
//        props.setProperty("mail.smtp.socketFactory.port", "993");
//        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.setProperty("mail.smtp.port", "993");
//        props.setProperty("mail.userID", "test.airavata@gmail.com");
//        props.setProperty("mail.password", "airavata");
        return mailConfig;
    }

    /**
     * Fetch Broker Properties. Will be reworked to fetch the properties from properties file.
     *
     * @return
     */
    public static Properties getBrokerProperties() {
        Properties props = new Properties();
        props.setProperty("monitor.email.exchange.name", "monitor");
        props.setProperty("monitor.email.broker.URI", "amqp://localhost:5672");
        props.setProperty("monitor.email.broker.queue1.name", "q1");
        props.setProperty("monitor.email.broker.queue2.name", "q2");
        return props;
    }

}