text:
/* global describe, it, beforeEach */
'use strict'

process.env.TZ = 'America/Los_Angeles'

var tmp = require('../')
var date = tmp.date
var gmdate = tmp.gmdate
var assert = require('assert')

describe('date', function () {
  var testDate
  beforeEach(function () {
    testDate = new Date(2016, 1, 4, 3, 24, 5, 34)
  })
  describe('d', function () {
    it('should properly format date with padded zero', function () {
      assert.strictEqual(date('d', testDate), '04')
    })
  })
  describe('j', function () {
    it('should properly format date without padded zero', function () {
      assert.strictEqual(date('j', testDate), '4')
    })
  })
  describe('D', function () {
    it('should format date to short day name', function () {
      assert.strictEqual(date('D', testDate), 'Thu')
      testDate.setMonth(0, 31)
      assert.strictEqual(date('D', testDate), 'Sun')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('D', testDate), 'Mon')
      testDate.setDate(2)
      assert.strictEqual(date('D', testDate), 'Tue')
      testDate.setDate(3)
      assert.strictEqual(date('D', testDate), 'Wed')
      testDate.setDate(5)
      assert.strictEqual(date('D', testDate), 'Fri')
      testDate.setDate(6)
      assert.strictEqual(date('D', testDate), 'Sat')
    })
  })
  describe('l', function () {
    it('should format date to long day name', function () {
      assert.strictEqual(date('l', testDate), 'Thursday')
      testDate.setMonth(0, 31)
      assert.strictEqual(date('l', testDate), 'Sunday')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('l', testDate), 'Monday')
      testDate.setDate(2)
      assert.strictEqual(date('l', testDate), 'Tuesday')
      testDate.setDate(3)
      assert.strictEqual(date('l', testDate), 'Wednesday')
      testDate.setDate(5)
      assert.strictEqual(date('l', testDate), 'Friday')
      testDate.setDate(6)
      assert.strictEqual(date('l', testDate), 'Saturday')
    })
  })
  describe('N', function () {
    it('should format date to iso-8601 day number (monday = 1, sunday = 7)', function () {
      assert.strictEqual(date('N', testDate), '4')
      testDate.setMonth(0, 31)
      assert.strictEqual(date('N', testDate), '7')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('N', testDate), '1')
      testDate.setDate(2)
      assert.strictEqual(date('N', testDate), '2')
      testDate.setDate(3)
      assert.strictEqual(date('N', testDate), '3')
      testDate.setDate(5)
      assert.strictEqual(date('N', testDate), '5')
      testDate.setDate(6)
      assert.strictEqual(date('N', testDate), '6')
    })
  })
  describe('S', function () {
    it('should properly determine ordinality of the date', function () {
      assert.strictEqual(date('jS', testDate), '4th')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('jS', testDate), '1st')
      testDate.setDate(2)
      assert.strictEqual(date('jS', testDate), '2nd')
      testDate.setDate(3)
      assert.strictEqual(date('jS', testDate), '3rd')
    })
  })
  describe('w', function () {
    it('should properly format the day of the week to just a number', function () {
      assert.strictEqual(date('w', testDate), '4')
      testDate.setMonth(0, 31)
      assert.strictEqual(date('w', testDate), '0')
      testDate.setMonth(1, 6)
      assert.strictEqual(date('w', testDate), '6')
    })
  })
  describe('z', function () {
    it('should return the number of days into the year', function () {
      assert.strictEqual(date('z', testDate), '34')
    })
  })
  describe('F', function () {
    it('should return the long month name of the date', function () {
      testDate.setMonth(0, 31)
      assert.strictEqual(date('F', testDate), 'January')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('F', testDate), 'February')
      testDate.setMonth(2, 1)
      assert.strictEqual(date('F', testDate), 'March')
      testDate.setMonth(3, 1)
      assert.strictEqual(date('F', testDate), 'April')
      testDate.setMonth(4, 1)
      assert.strictEqual(date('F', testDate), 'May')
      testDate.setMonth(5, 1)
      assert.strictEqual(date('F', testDate), 'June')
      testDate.setMonth(6, 1)
      assert.strictEqual(date('F', testDate), 'July')
      testDate.setMonth(7, 1)
      assert.strictEqual(date('F', testDate), 'August')
      testDate.setMonth(8, 1)
      assert.strictEqual(date('F', testDate), 'September')
      testDate.setMonth(9, 1)
      assert.strictEqual(date('F', testDate), 'October')
      testDate.setMonth(10, 1)
      assert.strictEqual(date('F', testDate), 'November')
      testDate.setMonth(11, 1)
      assert.strictEqual(date('F', testDate), 'December')
    })
  })
  describe('m', function () {
    it('should return the month number with a padded zero (non-zero indexed)', function () {
      testDate.setMonth(0, 31)
      assert.strictEqual(date('m', testDate), '01')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('m', testDate), '02')
      testDate.setMonth(2, 1)
      assert.strictEqual(date('m', testDate), '03')
      testDate.setMonth(3, 1)
      assert.strictEqual(date('m', testDate), '04')
      testDate.setMonth(4, 1)
      assert.strictEqual(date('m', testDate), '05')
      testDate.setMonth(5, 1)
      assert.strictEqual(date('m', testDate), '06')
      testDate.setMonth(6, 1)
      assert.strictEqual(date('m', testDate), '07')
      testDate.setMonth(7, 1)
      assert.strictEqual(date('m', testDate), '08')
      testDate.setMonth(8, 1)
      assert.strictEqual(date('m', testDate), '09')
      testDate.setMonth(9, 1)
      assert.strictEqual(date('m', testDate), '10')
      testDate.setMonth(10, 1)
      assert.strictEqual(date('m', testDate), '11')
      testDate.setMonth(11, 1)
      assert.strictEqual(date('m', testDate), '12')
    })
  })
  describe('M', function () {
    it('should return the short month name of the date', function () {
      testDate.setMonth(0, 31)
      assert.strictEqual(date('M', testDate), 'Jan')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('M', testDate), 'Feb')
      testDate.setMonth(2, 1)
      assert.strictEqual(date('M', testDate), 'Mar')
      testDate.setMonth(3, 1)
      assert.strictEqual(date('M', testDate), 'Apr')
      testDate.setMonth(4, 1)
      assert.strictEqual(date('M', testDate), 'May')
      testDate.setMonth(5, 1)
      assert.strictEqual(date('M', testDate), 'Jun')
      testDate.setMonth(6, 1)
      assert.strictEqual(date('M', testDate), 'Jul')
      testDate.setMonth(7, 1)
      assert.strictEqual(date('M', testDate), 'Aug')
      testDate.setMonth(8, 1)
      assert.strictEqual(date('M', testDate), 'Sep')
      testDate.setMonth(9, 1)
      assert.strictEqual(date('M', testDate), 'Oct')
      testDate.setMonth(10, 1)
      assert.strictEqual(date('M', testDate), 'Nov')
      testDate.setMonth(11, 1)
      assert.strictEqual(date('M', testDate), 'Dec')
    })
  })
  describe('n', function () {
    it('should return the month number without a padded zero (non-zero indexed)', function () {
      testDate.setMonth(0, 31)
      assert.strictEqual(date('n', testDate), '1')
      testDate.setMonth(1, 1)
      assert.strictEqual(date('n', testDate), '2')
      testDate.setMonth(2, 1)
      assert.strictEqual(date('n', testDate), '3')
      testDate.setMonth(3, 1)
      assert.strictEqual(date('n', testDate), '4')
      testDate.setMonth(4, 1)
      assert.strictEqual(date('n', testDate), '5')
      testDate.setMonth(5, 1)
      assert.strictEqual(date('n', testDate), '6')
      testDate.setMonth(6, 1)
      assert.strictEqual(date('n', testDate), '7')
      testDate.setMonth(7, 1)
      assert.strictEqual(date('n', testDate), '8')
      testDate.setMonth(8, 1)
      assert.strictEqual(date('n', testDate), '9')
      testDate.setMonth(9, 1)
      assert.strictEqual(date('n', testDate), '10')
      testDate.setMonth(10, 1)
      assert.strictEqual(date('n', testDate), '11')
      testDate.setMonth(11, 1)
      assert.strictEqual(date('n', testDate), '12')
    })
  })
  describe('L', function () {
    it('should return 0 for non-leap-years', function () {
      [2015, 2013, 2011, 2003, 1997, 1998, 1986].forEach(function (y) {
        testDate.setYear(y)
        assert.strictEqual(date('L', testDate), '0')
      })
    })
    it('should return 1 for leap-years', function () {
      [2016, 2012, 2008, 2004, 2000, 1996, 1992, 1988].forEach(function (y) {
        testDate.setYear(y)
        assert.strictEqual(date('L', testDate), '1')
      })
    })
  })
  describe('t', function () {
    it('should return the number of calendar days for the set month', function () {
      assert.strictEqual(date('t', testDate), '29')
      testDate.setYear(2015)
      assert.strictEqual(date('t', testDate), '28')
      testDate.setMonth(0, 4)
      assert.strictEqual(date('t', testDate), '31')
      testDate.setMonth(3, 1)
      assert.strictEqual(date('t', testDate), '30')
    })
  })
  describe('Y', function () {
    it('should return the full year', function () {
      assert.strictEqual(date('Y', testDate), '2016')
      testDate.setYear(2012)
      assert.strictEqual(date('Y', testDate), '2012')
    })
  })
  describe('y', function () {
    it('should return the truncated year (1998 -> 98)', function () {
      assert.strictEqual(date('y', testDate), '16')
      testDate.setYear(2012)
      assert.strictEqual(date('y', testDate), '12')
      testDate.setYear(2000)
      assert.strictEqual(date('y', testDate), '00')
    })
  })
  describe('a', function () {
    it('should return am or pm depending on the hour of day', function () {
      assert.strictEqual(date('a', testDate), 'am')
      testDate.setHours(0)
      assert.strictEqual(date('a', testDate), 'am')
      testDate.setHours(23)
      assert.strictEqual(date('a', testDate), 'pm')
      testDate.setHours(12)
      assert.strictEqual(date('a', testDate), 'pm')
    })
  })
  describe('A', function () {
    it('should return AM or PM depending on the hour of the day', function () {
      assert.strictEqual(date('A', testDate), 'AM')
      testDate.setHours(0)
      assert.strictEqual(date('A', testDate), 'AM')
      testDate.setHours(23)
      assert.strictEqual(date('A', testDate), 'PM')
      testDate.setHours(12)
      assert.strictEqual(date('A', testDate), 'PM')
    })
  })
  describe('g', function () {
    it('should return non-military hour without a leading zero', function () {
      assert.strictEqual(date('g', testDate), '3')
      testDate.setHours(15)
      assert.strictEqual(date('g', testDate), '3')
      testDate.setHours(0)
      assert.strictEqual(date('g', testDate), '12')
      testDate.setHours(12)
      assert.strictEqual(date('g', testDate), '12')
    })
  })
  describe('G', function () {
    it('should return military hour without a leading zero', function () {
      assert.strictEqual(date('G', testDate), '3')
      testDate.setHours(15)
      assert.strictEqual(date('G', testDate), '15')
      testDate.setHours(0)
      assert.strictEqual(date('G', testDate), '0')
      testDate.setHours(12)
      assert.strictEqual(date('G', testDate), '12')
    })
  })
  describe('h', function () {
    it('should return non-military hour with a leading zero', function () {
      assert.strictEqual(date('h', testDate), '03')
      testDate.setHours(15)
      assert.strictEqual(date('h', testDate), '03')
      testDate.setHours(0)
      assert.strictEqual(date('h', testDate), '12')
      testDate.setHours(12)
      assert.strictEqual(date('h', testDate), '12')
    })
  })
  describe('H', function () {
    it('should return military hour with a leading zero', function () {
      assert.strictEqual(date('H', testDate), '03')
      testDate.setHours(15)
      assert.strictEqual(date('H', testDate), '15')
      testDate.setHours(0)
      assert.strictEqual(date('H', testDate), '00')
      testDate.setHours(12)
      assert.strictEqual(date('H', testDate), '12')
    })
  })
  describe('i', function () {
    it('should return the minutes with a leading zero', function () {
      assert.strictEqual(date('i', testDate), '24')
      testDate.setMinutes(3)
      assert.strictEqual(date('i', testDate), '03')
    })
  })
  describe('s', function () {
    it('should return the seconds with a leading zero', function () {
      assert.strictEqual(date('s', testDate), '05')
      testDate.setSeconds(45)
      assert.strictEqual(date('s', testDate), '45')
    })
  })
  describe('u', function () {
    it('should return the milliseconds with a leading zero', function () {
      assert.strictEqual(date('s.u', testDate), '05.034')
    })
  })
  describe('U', function () {
    it('should return the seconds since the unix epoch', function () {
      assert.strictEqual(date('U', testDate), '1454585045')
    })
  })
  describe('P', function () {
    it('should return the timezone offset seperated by a colon', function () {
      assert.strictEqual(date('P', testDate), '+08:00')
    })
  })
  describe('O', function () {
    it('should return the timezone offset not seperated by a colon', function () {
      assert.strictEqual(date('O', testDate), '+0800')
    })
  })
  describe('c', function () {
    it('should return the date formatted in iso 8601 format', function () {
      assert.strictEqual(date('c', testDate), '2016-02-04T03:24:05+08:00')
    })
  })
  describe('r', function () {
    it('should return the date formatted rfc2822 format', function () {
      assert.strictEqual(date('r', testDate), 'Thu, 04 Feb 2016 03:24:05 +0800')
    })
  })
  describe('letter escaping', function () {
    it('should skip over letters that are prefixed with a slash (\\)', function () {
      assert.strictEqual(date('\\rc', testDate), 'r2016-02-04T03:24:05+08:00')
      assert.strictEqual(date('Y-\\m-d H:\\i:s', testDate), '2016-m-04 03:i:05')
    })
  })
})

describe('gmdate', function () {
  /** @type {Date} */
  var testDate
  beforeEach(function () {
    testDate = new Date(2016, 1, 4, 3, 24, 5, 34)
  })
  describe('d', function () {
    it('should properly format date with padded zero', function () {
      assert.strictEqual(gmdate('d', testDate), '04')
    })
  })
  describe('j', function () {
    it('should properly format date without padded zero', function () {
      assert.strictEqual(gmdate('j', testDate), '4')
    })
  })
  describe('D', function () {
    it('should format date to short day name', function () {
      assert.strictEqual(gmdate('D', testDate), 'Thu')
      testDate.setMonth(0, 31)
      assert.strictEqual(gmdate('D', testDate), 'Sun')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('D', testDate), 'Mon')
      testDate.setDate(2)
      assert.strictEqual(gmdate('D', testDate), 'Tue')
      testDate.setDate(3)
      assert.strictEqual(gmdate('D', testDate), 'Wed')
      testDate.setDate(5)
      assert.strictEqual(gmdate('D', testDate), 'Fri')
      testDate.setDate(6)
      assert.strictEqual(gmdate('D', testDate), 'Sat')
    })
  })
  describe('l', function () {
    it('should format date to long day name', function () {
      assert.strictEqual(gmdate('l', testDate), 'Thursday')
      testDate.setMonth(0, 31)
      assert.strictEqual(gmdate('l', testDate), 'Sunday')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('l', testDate), 'Monday')
      testDate.setDate(2)
      assert.strictEqual(gmdate('l', testDate), 'Tuesday')
      testDate.setDate(3)
      assert.strictEqual(gmdate('l', testDate), 'Wednesday')
      testDate.setDate(5)
      assert.strictEqual(gmdate('l', testDate), 'Friday')
      testDate.setDate(6)
      assert.strictEqual(gmdate('l', testDate), 'Saturday')
    })
  })
  describe('N', function () {
    it('should format date to iso-8601 day number (monday = 1, sunday = 7)', function () {
      assert.strictEqual(gmdate('N', testDate), '4')
      testDate.setMonth(0, 31)
      assert.strictEqual(gmdate('N', testDate), '7')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('N', testDate), '1')
      testDate.setDate(2)
      assert.strictEqual(gmdate('N', testDate), '2')
      testDate.setDate(3)
      assert.strictEqual(gmdate('N', testDate), '3')
      testDate.setDate(5)
      assert.strictEqual(gmdate('N', testDate), '5')
      testDate.setDate(6)
      assert.strictEqual(gmdate('N', testDate), '6')
    })
  })
  describe('S', function () {
    it('should properly determine ordinality of the date', function () {
      assert.strictEqual(gmdate('jS', testDate), '4th')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('jS', testDate), '1st')
      testDate.setDate(2)
      assert.strictEqual(gmdate('jS', testDate), '2nd')
      testDate.setDate(3)
      assert.strictEqual(gmdate('jS', testDate), '3rd')
    })
  })
  describe('w', function () {
    it('should properly format the day of the week to just a number', function () {
      assert.strictEqual(gmdate('w', testDate), '4')
      testDate.setMonth(0, 31)
      assert.strictEqual(gmdate('w', testDate), '0')
      testDate.setMonth(1, 6)
      assert.strictEqual(gmdate('w', testDate), '6')
    })
  })
  describe('z', function () {
    it('should return the number of days into the year', function () {
      assert.strictEqual(gmdate('z', testDate), '34')
    })
  })
  describe('F', function () {
    it('should return the long month name of the date', function () {
      testDate.setMonth(0, 31)
      assert.strictEqual(gmdate('F', testDate), 'January')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('F', testDate), 'February')
      testDate.setMonth(2, 1)
      assert.strictEqual(gmdate('F', testDate), 'March')
      testDate.setMonth(3, 1)
      assert.strictEqual(gmdate('F', testDate), 'April')
      testDate.setMonth(4, 1)
      assert.strictEqual(gmdate('F', testDate), 'May')
      testDate.setMonth(5, 1)
      assert.strictEqual(gmdate('F', testDate), 'June')
      testDate.setMonth(6, 1)
      assert.strictEqual(gmdate('F', testDate), 'July')
      testDate.setMonth(7, 1)
      assert.strictEqual(gmdate('F', testDate), 'August')
      testDate.setMonth(8, 1)
      assert.strictEqual(gmdate('F', testDate), 'September')
      testDate.setMonth(9, 1)
      assert.strictEqual(gmdate('F', testDate), 'October')
      testDate.setMonth(10, 1)
      assert.strictEqual(gmdate('F', testDate), 'November')
      testDate.setMonth(11, 1)
      assert.strictEqual(gmdate('F', testDate), 'December')
    })
  })
  describe('m', function () {
    it('should return the month number with a padded zero (non-zero indexed)', function () {
      testDate.setMonth(0, 31)
      assert.strictEqual(gmdate('m', testDate), '01')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('m', testDate), '02')
      testDate.setMonth(2, 1)
      assert.strictEqual(gmdate('m', testDate), '03')
      testDate.setMonth(3, 1)
      assert.strictEqual(gmdate('m', testDate), '04')
      testDate.setMonth(4, 1)
      assert.strictEqual(gmdate('m', testDate), '05')
      testDate.setMonth(5, 1)
      assert.strictEqual(gmdate('m', testDate), '06')
      testDate.setMonth(6, 1)
      assert.strictEqual(gmdate('m', testDate), '07')
      testDate.setMonth(7, 1)
      assert.strictEqual(gmdate('m', testDate), '08')
      testDate.setMonth(8, 1)
      assert.strictEqual(gmdate('m', testDate), '09')
      testDate.setMonth(9, 1)
      assert.strictEqual(gmdate('m', testDate), '10')
      testDate.setMonth(10, 1)
      assert.strictEqual(gmdate('m', testDate), '11')
      testDate.setMonth(11, 1)
      assert.strictEqual(gmdate('m', testDate), '12')
    })
  })
  describe('M', function () {
    it('should return the short month name of the date', function () {
      testDate.setMonth(0, 31)
      assert.strictEqual(gmdate('M', testDate), 'Jan')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('M', testDate), 'Feb')
      testDate.setMonth(2, 1)
      assert.strictEqual(gmdate('M', testDate), 'Mar')
      testDate.setMonth(3, 1)
      assert.strictEqual(gmdate('M', testDate), 'Apr')
      testDate.setMonth(4, 1)
      assert.strictEqual(gmdate('M', testDate), 'May')
      testDate.setMonth(5, 1)
      assert.strictEqual(gmdate('M', testDate), 'Jun')
      testDate.setMonth(6, 1)
      assert.strictEqual(gmdate('M', testDate), 'Jul')
      testDate.setMonth(7, 1)
      assert.strictEqual(gmdate('M', testDate), 'Aug')
      testDate.setMonth(8, 1)
      assert.strictEqual(gmdate('M', testDate), 'Sep')
      testDate.setMonth(9, 1)
      assert.strictEqual(gmdate('M', testDate), 'Oct')
      testDate.setMonth(10, 1)
      assert.strictEqual(gmdate('M', testDate), 'Nov')
      testDate.setMonth(11, 1)
      assert.strictEqual(gmdate('M', testDate), 'Dec')
    })
  })
  describe('n', function () {
    it('should return the month number without a padded zero (non-zero indexed)', function () {
      testDate.setMonth(0)
      assert.strictEqual(gmdate('n', testDate), '1')
      testDate.setMonth(1, 1)
      assert.strictEqual(gmdate('n', testDate), '2')
      testDate.setMonth(2, 1)
      assert.strictEqual(gmdate('n', testDate), '3')
      testDate.setMonth(3, 1)
      assert.strictEqual(gmdate('n', testDate), '4')
      testDate.setMonth(4, 1)
      assert.strictEqual(gmdate('n', testDate), '5')
      testDate.setMonth(5, 1)
      assert.strictEqual(gmdate('n', testDate), '6')
      testDate.setMonth(6, 1)
      assert.strictEqual(gmdate('n', testDate), '7')
      testDate.setMonth(7, 1)
      assert.strictEqual(gmdate('n', testDate), '8')
      testDate.setMonth(8, 1)
      assert.strictEqual(gmdate('n', testDate), '9')
      testDate.setMonth(9, 1)
      assert.strictEqual(gmdate('n', testDate), '10')
      testDate.setMonth(10, 1)
      assert.strictEqual(gmdate('n', testDate), '11')
      testDate.setMonth(11, 1)
      assert.strictEqual(gmdate('n', testDate), '12')
    })
  })
  describe('L', function () {
    it('should return 0 for non-leap-years', function () {
      [2015, 2013, 2011, 2003, 1997, 1998, 1986].forEach(function (y) {
        testDate.setYear(y)
        assert.strictEqual(gmdate('L', testDate), '0')
      })
    })
    it('should return 1 for leap-years', function () {
      [2016, 2012, 2008, 2004, 2000, 1996, 1992, 1988].forEach(function (y) {
        testDate.setYear(y)
        assert.strictEqual(gmdate('L', testDate), '1')
      })
    })
  })
  describe('t', function () {
    it('should return the number of calendar days for the set month', function () {
      assert.strictEqual(gmdate('t', testDate), '29')
      testDate.setYear(2015)
      assert.strictEqual(gmdate('t', testDate), '28')
      testDate.setMonth(0, 4)
      assert.strictEqual(gmdate('t', testDate), '31')
      testDate.setMonth(3, 1)
      assert.strictEqual(gmdate('t', testDate), '30')
    })
  })
  describe('Y', function () {
    it('should return the full year', function () {
      assert.strictEqual(gmdate('Y', testDate), '2016')
      testDate.setYear(2012)
      assert.strictEqual(gmdate('Y', testDate), '2012')
    })
  })
  describe('y', function () {
    it('should return the truncated year (1998 -> 98)', function () {
      assert.strictEqual(gmdate('y', testDate), '16')
      testDate.setYear(2012)
      assert.strictEqual(gmdate('y', testDate), '12')
      testDate.setYear(2000)
      assert.strictEqual(gmdate('y', testDate), '00')
    })
  })
  describe('a', function () {
    it('should return am or pm depending on the hour of day', function () {
      assert.strictEqual(gmdate('a', testDate), 'am')
      testDate.setHours(0)
      assert.strictEqual(gmdate('a', testDate), 'am')
      testDate.setHours(23) // remember: this is 23 hours at America/Los_Angeles, not UTC, so yes, 'am' is correct
      assert.strictEqual(gmdate('a', testDate), 'am')
      testDate.setHours(12)
      assert.strictEqual(gmdate('a', testDate), 'pm')
    })
  })
  describe('A', function () {
    it('should return AM or PM depending on the hour of the day', function () {
      assert.strictEqual(gmdate('A', testDate), 'AM')
      testDate.setHours(0)
      assert.strictEqual(gmdate('A', testDate), 'AM')
      testDate.setHours(23)
      assert.strictEqual(gmdate('A', testDate), 'AM')
      testDate.setHours(12)
      assert.strictEqual(gmdate('A', testDate), 'PM')
    })
  })
  describe('g', function () {
    it('should return non-military hour without a leading zero', function () {
      assert.strictEqual(gmdate('g', testDate), '11')
      testDate.setHours(15)
      assert.strictEqual(gmdate('g', testDate), '11')
      testDate.setHours(0)
      assert.strictEqual(gmdate('g', testDate), '8')
      testDate.setHours(12)
      assert.strictEqual(gmdate('g', testDate), '8')
    })
  })
  describe('G', function () {
    it('should return military hour without a leading zero', function () {
      assert.strictEqual(gmdate('G', testDate), '11')
      testDate.setHours(15)
      assert.strictEqual(gmdate('G', testDate), '23')
      testDate.setHours(0)
      assert.strictEqual(gmdate('G', testDate), '8')
      testDate.setHours(12)
      assert.strictEqual(gmdate('G', testDate), '20')
    })
  })
  describe('h', function () {
    it('should return non-military hour with a leading zero', function () {
      assert.strictEqual(gmdate('h', testDate), '11')
      testDate.setHours(15)
      assert.strictEqual(gmdate('h', testDate), '11')
      testDate.setHours(0)
      assert.strictEqual(gmdate('h', testDate), '08')
      testDate.setHours(12)
      assert.strictEqual(gmdate('h', testDate), '08')
    })
  })
  describe('H', function () {
    it('should return military hour with a leading zero', function () {
      assert.strictEqual(gmdate('H', testDate), '11')
      testDate.setHours(15)
      assert.strictEqual(gmdate('H', testDate), '23')
      testDate.setHours(0)
      assert.strictEqual(gmdate('H', testDate), '08')
      testDate.setHours(12)
      assert.strictEqual(gmdate('H', testDate), '20')
    })
  })
  describe('i', function () {
    it('should return the minutes with a leading zero', function () {
      assert.strictEqual(gmdate('i', testDate), '24')
      testDate.setMinutes(3)
      assert.strictEqual(gmdate('i', testDate), '03')
    })
  })
  describe('s', function () {
    it('should return the seconds with a leading zero', function () {
      assert.strictEqual(gmdate('s', testDate), '05')
      testDate.setSeconds(45)
      assert.strictEqual(gmdate('s', testDate), '45')
    })
  })
  describe('u', function () {
    it('should return the milliseconds with a leading zero', function () {
      assert.strictEqual(gmdate('s.u', testDate), '05.034')
    })
  })
  describe('U', function () {
    it('should return the seconds since the unix epoch', function () {
      assert.strictEqual(gmdate('U', testDate), '1454585045')
    })
  })
  describe('P', function () {
    it('should return the timezone offset seperated by a colon', function () {
      assert.strictEqual(gmdate('P', testDate), '+00:00')
    })
  })
  describe('O', function () {
    it('should return the timezone offset not seperated by a colon', function () {
      assert.strictEqual(gmdate('O', testDate), '+0000')
    })
  })
  describe('c', function () {
    it('should return the date formatted in iso 8601 format', function () {
      assert.strictEqual(gmdate('c', testDate), '2016-02-04T11:24:05+00:00')
    })
  })
  describe('r', function () {
    it('should return the date formatted rfc2822 format', function () {
      assert.strictEqual(gmdate('r', testDate), 'Thu, 04 Feb 2016 11:24:05 +0000')
    })
  })
  describe('letter escaping', function () {
    it('should skip over letters that are prefixed with a slash (\\)', function () {
      assert.strictEqual(gmdate('\\rc', testDate), 'r2016-02-04T11:24:05+00:00')
      assert.strictEqual(gmdate('Y-\\m-d H:\\i:s', testDate), '2016-m-04 11:i:05')
    })
  })
})

redpajama_set_name: RedPajamaGithub


text:
'''
Created on 2016年1月11日

@author: xxw
'''

import time

import client
from common import baseclientfactory

class ClientFactory(baseclientfactory.BaseClientFactory):

    def __init__(self):
        baseclientfactory.BaseClientFactory.__init__(self)

    def createClient(self, pid, addr):
        return client.Client(pid, addr)

    def getClient(self, pid):
        return self.getProtocol(pid)

    def checkClients(self, clients):
        curtime = time.time()

        for c in clients:
            if c.getState()== client.CLIENT_STATE_TO_CLOSE and curtime-c.toclosetime > 10:
                c.abort()
            elif curtime-c.getLastActiveTime() > 60:
                c.sendKeepAlive()

instance = ClientFactory()


text:
require 'rack/head'
require 'rack/mock'

describe Rack::Head do

  def test_response(headers = {})
    body = StringIO.new "foo"
    app = lambda do |env|
      [200, {"Content-type" => "test/plain", "Content-length" => "3"}, body]
    end
    request = Rack::MockRequest.env_for("/", headers)
    response = Rack::Head.new(app).call(request)

    return response, body
  end

  should "pass GET, POST, PUT, DELETE, OPTIONS, TRACE requests" do
    %w[GET POST PUT DELETE OPTIONS TRACE].each do |type|
      resp, _ = test_response("REQUEST_METHOD" => type)

      resp[0].should.equal(200)
      resp[1].should.equal({"Content-type" => "test/plain", "Content-length" => "3"})
      resp[2].each { |b| b.should.equal("foo") }
    end
  end

  should "remove body from HEAD requests" do
    resp, _ = test_response("REQUEST_METHOD" => "HEAD")

    resp[0].should.equal(200)
    resp[1].should.equal({"Content-type" => "test/plain", "Content-length" => "3"})
    resp[2].each { |b| flunk "body should be empty" }
  end

  should "close the body when it is removed" do
    resp, body = test_response("REQUEST_METHOD" => "HEAD")
    resp[0].should.equal(200)
    resp[1].should.equal({"Content-type" => "test/plain", "Content-length" => "3"})
    resp[2].each { |b| flunk "body should be empty" }
    body.should.be.closed
  end
end


text:
Events
======

An event mechanism is available to add an extra entry point to extend Admin instance.

ConfigureEvent
~~~~~~~~~~~~~~

This event is generated when a form, list, show, datagrid is configured. The event names are:

 - sonata.admin.event.configure.form
 - sonata.admin.event.configure.list
 - sonata.admin.event.configure.datagrid
 - sonata.admin.event.configure.show

PersistenceEvent
~~~~~~~~~~~~~~~~

This event is generated when a persistency layer update, save or delete an object. The event names are:

 - sonata.admin.event.persistence.pre_update
 - sonata.admin.event.persistence.post_update
 - sonata.admin.event.persistence.pre_persist
 - sonata.admin.event.persistence.post_persist
 - sonata.admin.event.persistence.pre_remove
 - sonata.admin.event.persistence.post_remove

ConfigureQueryEvent
~~~~~~~~~~~~~~~~~~~

This event is generated when a list query is defined. The event name is: ``sonata.admin.event.configure.query``

BlockEvent
~~~~~~~~~~

Block events help you customize your templates. Available events are :

 - sonata.admin.dashboard.top
 - sonata.admin.dashboard.bottom
 - sonata.admin.list.table.top
 - sonata.admin.list.table.bottom
 - sonata.admin.edit.form.top
 - sonata.admin.edit.form.bottom
 - sonata.admin.show.top
 - sonata.admin.show.bottom

If you want more information about block events, you should check the
`"Event" section of block bundle documentation <http://sonata-project.org/bundles/block/master/doc/reference/events.html>`_.


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

package org.chromium.chrome.browser.translate;

import android.test.suitebuilder.annotation.MediumTest;

import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.Restriction;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.infobar.InfoBar;
import org.chromium.chrome.browser.infobar.InfoBarContainer;
import org.chromium.chrome.test.ChromeActivityTestCaseBase;
import org.chromium.chrome.test.util.ChromeRestriction;
import org.chromium.chrome.test.util.InfoBarTestAnimationListener;
import org.chromium.chrome.test.util.InfoBarUtil;
import org.chromium.chrome.test.util.TranslateUtil;
import org.chromium.net.test.EmbeddedTestServer;

import java.util.concurrent.TimeoutException;

/**
 * Tests for the translate infobar, assumes it runs on a system with language
 * preferences set to English.
 *
 * Note: these tests all currently fail because they depend on a newer version of Google Play
 * Services than is installed on the test devices. See http://crbug.com/514449
 */
public class TranslateInfoBarTest extends ChromeActivityTestCaseBase<ChromeActivity> {

    private static final String TRANSLATE_PAGE = "/chrome/test/data/translate/fr_test.html";
    private static final String NEVER_TRANSLATE_MESSAGE =
            "Would you like Google Chrome to offer to translate French pages from this"
                    + " site next time?";

    private InfoBarContainer mInfoBarContainer;
    private InfoBarTestAnimationListener mListener;
    private EmbeddedTestServer mTestServer;

    public TranslateInfoBarTest() {
        super(ChromeActivity.class);
    }

    @Override
    public void startMainActivity() throws InterruptedException {
        startMainActivityOnBlankPage();
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mInfoBarContainer = getActivity().getActivityTab().getInfoBarContainer();
        mListener =  new InfoBarTestAnimationListener();
        mInfoBarContainer.setAnimationListener(mListener);
        mTestServer = EmbeddedTestServer.createAndStartServer(getInstrumentation().getContext());
    }

    @Override
    protected void tearDown() throws Exception {
        mTestServer.stopAndDestroyServer();
        super.tearDown();
    }

    /**
     * Test the translate language panel.
     */
    @MediumTest
    @Feature({"Browser", "Main"})
    @Restriction(ChromeRestriction.RESTRICTION_TYPE_GOOGLE_PLAY_SERVICES)
    public void testTranslateLanguagePanel() throws InterruptedException, TimeoutException {
        loadUrl(mTestServer.getURL(TRANSLATE_PAGE));
        mListener.addInfoBarAnimationFinished("InfoBar not opened.");
        InfoBar infoBar = mInfoBarContainer.getInfoBarsForTesting().get(0);
        assertTrue(InfoBarUtil.hasPrimaryButton(infoBar));
        assertTrue(InfoBarUtil.hasSecondaryButton(infoBar));
        TranslateUtil.openLanguagePanel(this, infoBar);
    }

    /**
     * Test the "never translate" panel.
     */
    @MediumTest
    @Feature({"Browser", "Main"})
    @Restriction(ChromeRestriction.RESTRICTION_TYPE_GOOGLE_PLAY_SERVICES)
    public void testTranslateNeverPanel() throws InterruptedException, TimeoutException {
        loadUrl(mTestServer.getURL(TRANSLATE_PAGE));
        mListener.addInfoBarAnimationFinished("InfoBar not opened.");
        InfoBar infoBar = mInfoBarContainer.getInfoBarsForTesting().get(0);

        assertTrue(InfoBarUtil.clickCloseButton(infoBar));
        mListener.removeInfoBarAnimationFinished("Infobar not removed.");

        // Reload the page so the infobar shows again
        loadUrl(mTestServer.getURL(TRANSLATE_PAGE));
        mListener.addInfoBarAnimationFinished("InfoBar not opened");
        infoBar = mInfoBarContainer.getInfoBarsForTesting().get(0);
        assertTrue(InfoBarUtil.clickCloseButton(infoBar));
        mListener.swapInfoBarAnimationFinished("InfoBar not swapped");

        TranslateUtil.assertInfoBarText(infoBar, NEVER_TRANSLATE_MESSAGE);
    }

    /**
     * Test infobar transitions.
     *
     * @MediumTest
     * @Feature({"Browser", "Main"})
     */
    @DisabledTest(message = "crbug.com/514449")
    public void testTranslateTransitions() throws InterruptedException, TimeoutException {
        loadUrl(mTestServer.getURL(TRANSLATE_PAGE));
        mListener.addInfoBarAnimationFinished("InfoBar not Added");
        InfoBar infoBar = getInfoBars().get(0);
        assertTrue(InfoBarUtil.hasPrimaryButton(infoBar));
        assertTrue(InfoBarUtil.hasSecondaryButton(infoBar));
        assertTrue(InfoBarUtil.clickPrimaryButton(infoBar));
        mListener.swapInfoBarAnimationFinished("BEFORE -> TRANSLATING transition not Swapped.");
        mListener.swapInfoBarAnimationFinished("TRANSLATING -> ERROR transition not Swapped.");
    }
}


text:
#import <Foundation/Foundation.h>

/**
 * The `CPReachDataPushDelegate` protocol defines methods a delegate of <CPReachModule> should implement to receive data
 * pushes.
 *
 * To process data push, you must implement method <onDataPushBase64ReceivedWithDecodedBody:andEncodedBody:>
 * if it's a file upload or a base64 data, otherwise you implement <onDataPushStringReceived:>.<br>
 * To use it in your application just call the method <[CPReachModule dataPushDelegate]> after module
 * initialization.
 */
@protocol CPReachDataPushDelegate <UIAlertViewDelegate>

@optional

/**
 * This function is called when a datapush of type text has been received.
 * @param category short string describing your data to push
 * @param body Your content.
 * @result YES to acknowledge the content, NO to cancel.
 **/
- (BOOL)didReceiveStringDataPushWithCategory:(NSString*)category body:(NSString*)body;

/**
 * This function is called when a datapush of type base64 has been received.
 * @param category short string describing your data to push
 * @param decodedBody Your base64 content decoded.
 * @param encodedBody Your base64 content encoded.
 * @result YES to acknowledge the content, NO to cancel.
 **/
- (BOOL)didReceiveBase64DataPushWithCategory:(NSString*)category decodedBody:(NSData*)decodedBody encodedBody:(NSString*)
  encodedBody;

@end


text:
#include <node.h>
#include <node_buffer.h>
#include "ffi.h"
#include "fficonfig.h"

/*
 * Called when the wrapped pointer is garbage collected.
 * We never have to do anything here...
 */

void wrap_pointer_cb(char *data, void *hint) {
  //fprintf(stderr, "wrap_pointer_cb\n");
}

int node_ffi_errno() {
    return errno;
}

///////////////

NAN_MODULE_INIT(FFI::InitializeStaticFunctions) {
  Local<Object> o = Nan::New<Object>();

  // dl functions used by the DynamicLibrary JS class
  o->Set(Nan::New<String>("dlopen").ToLocalChecked(),  WrapPointer((char *)dlopen));
  o->Set(Nan::New<String>("dlclose").ToLocalChecked(), WrapPointer((char *)dlclose));
  o->Set(Nan::New<String>("dlsym").ToLocalChecked(),   WrapPointer((char *)dlsym));
  o->Set(Nan::New<String>("dlerror").ToLocalChecked(), WrapPointer((char *)dlerror));

  o->Set(Nan::New<String>("_errno").ToLocalChecked(), WrapPointer((char *)node_ffi_errno));

  target->Set(Nan::New<String>("StaticFunctions").ToLocalChecked(), o);
}

///////////////

#define SET_ENUM_VALUE(_value) \
  Nan::ForceSet(target, Nan::New<String>(#_value).ToLocalChecked(), \
  Nan::New<Integer>((uint32_t)_value), \
  static_cast<PropertyAttribute>(ReadOnly|DontDelete))

NAN_MODULE_INIT(FFI::InitializeBindings) {

  Nan::Set(target, Nan::New<String>("version").ToLocalChecked(),
    Nan::New<String>(PACKAGE_VERSION).ToLocalChecked());

  // main function exports
  Nan::Set(target, Nan::New<String>("ffi_prep_cif").ToLocalChecked(),
    Nan::New<FunctionTemplate>(FFIPrepCif)->GetFunction());
  Nan::Set(target, Nan::New<String>("ffi_prep_cif_var").ToLocalChecked(),
    Nan::New<FunctionTemplate>(FFIPrepCifVar)->GetFunction());
  Nan::Set(target, Nan::New<String>("ffi_call").ToLocalChecked(),
    Nan::New<FunctionTemplate>(FFICall)->GetFunction());
  Nan::Set(target, Nan::New<String>("ffi_call_async").ToLocalChecked(),
    Nan::New<FunctionTemplate>(FFICallAsync)->GetFunction());

  // `ffi_status` enum values
  SET_ENUM_VALUE(FFI_OK);
  SET_ENUM_VALUE(FFI_BAD_TYPEDEF);
  SET_ENUM_VALUE(FFI_BAD_ABI);

  // `ffi_abi` enum values
  SET_ENUM_VALUE(FFI_DEFAULT_ABI);
  SET_ENUM_VALUE(FFI_FIRST_ABI);
  SET_ENUM_VALUE(FFI_LAST_ABI);
  /* ---- ARM processors ---------- */
#ifdef __arm__
  SET_ENUM_VALUE(FFI_SYSV);
  SET_ENUM_VALUE(FFI_VFP);
  /* ---- Intel x86 Win32 ---------- */
#elif defined(X86_WIN32)
  SET_ENUM_VALUE(FFI_SYSV);
  SET_ENUM_VALUE(FFI_STDCALL);
  SET_ENUM_VALUE(FFI_THISCALL);
  SET_ENUM_VALUE(FFI_FASTCALL);
  SET_ENUM_VALUE(FFI_MS_CDECL);
#elif defined(X86_WIN64)
  SET_ENUM_VALUE(FFI_WIN64);
#else
  /* ---- Intel x86 and AMD x86-64 - */
  SET_ENUM_VALUE(FFI_SYSV);
  /* Unix variants all use the same ABI for x86-64  */
  SET_ENUM_VALUE(FFI_UNIX64);
#endif

  /* flags for dlopen() */
#ifdef RTLD_LAZY
  SET_ENUM_VALUE(RTLD_LAZY);
#endif
#ifdef RTLD_NOW
  SET_ENUM_VALUE(RTLD_NOW);
#endif
#ifdef RTLD_LOCAL
  SET_ENUM_VALUE(RTLD_LOCAL);
#endif
#ifdef RTLD_GLOBAL
  SET_ENUM_VALUE(RTLD_GLOBAL);
#endif
#ifdef RTLD_NOLOAD
  SET_ENUM_VALUE(RTLD_NOLOAD);
#endif
#ifdef RTLD_NODELETE
  SET_ENUM_VALUE(RTLD_NODELETE);
#endif
#ifdef RTLD_FIRST
  SET_ENUM_VALUE(RTLD_FIRST);
#endif

  /* flags for dlsym() */
#ifdef RTLD_NEXT
  Nan::ForceSet(target,Nan::New<String>("RTLD_NEXT").ToLocalChecked(), WrapPointer((char *)RTLD_NEXT), static_cast<PropertyAttribute>(ReadOnly | DontDelete));
#endif
#ifdef RTLD_DEFAULT
  Nan::ForceSet(target,Nan::New<String>("RTLD_DEFAULT").ToLocalChecked(), WrapPointer((char *)RTLD_DEFAULT), static_cast<PropertyAttribute>(ReadOnly | DontDelete));
#endif
#ifdef RTLD_SELF
  Nan::ForceSet(target,Nan::New<String>("RTLD_SELF").ToLocalChecked(), WrapPointer((char *)RTLD_SELF), static_cast<PropertyAttribute>(ReadOnly|DontDelete));
#endif
#ifdef RTLD_MAIN_ONLY
  Nan::ForceSet(target,Nan::New<String>("RTLD_MAIN_ONLY").ToLocalChecked(), WrapPointer((char *)RTLD_MAIN_ONLY), static_cast<PropertyAttribute>(ReadOnly|DontDelete));
#endif

  Nan::ForceSet(target,Nan::New<String>("FFI_ARG_SIZE").ToLocalChecked(), Nan::New<Uint32>((uint32_t)sizeof(ffi_arg)), static_cast<PropertyAttribute>(ReadOnly|DontDelete));
  Nan::ForceSet(target,Nan::New<String>("FFI_SARG_SIZE").ToLocalChecked(), Nan::New<Uint32>((uint32_t)sizeof(ffi_sarg)), static_cast<PropertyAttribute>(ReadOnly | DontDelete));
  Nan::ForceSet(target,Nan::New<String>("FFI_TYPE_SIZE").ToLocalChecked(), Nan::New<Uint32>((uint32_t)sizeof(ffi_type)), static_cast<PropertyAttribute>(ReadOnly | DontDelete));
  Nan::ForceSet(target,Nan::New<String>("FFI_CIF_SIZE").ToLocalChecked(), Nan::New<Uint32>((uint32_t)sizeof(ffi_cif)), static_cast<PropertyAttribute>(ReadOnly | DontDelete));

  bool hasObjc = false;
#if __OBJC__ || __OBJC2__
  hasObjc = true;
#endif
  Nan::ForceSet(target,Nan::New<String>("HAS_OBJC").ToLocalChecked(), Nan::New<Boolean>(hasObjc), static_cast<PropertyAttribute>(ReadOnly | DontDelete));

  Local<Object> ftmap = Nan::New<Object>();
  ftmap->Set(Nan::New<String>("void").ToLocalChecked(), WrapPointer((char *)&ffi_type_void));
  ftmap->Set(Nan::New<String>("uint8").ToLocalChecked(), WrapPointer((char *)&ffi_type_uint8));
  ftmap->Set(Nan::New<String>("int8").ToLocalChecked(), WrapPointer((char *)&ffi_type_sint8));
  ftmap->Set(Nan::New<String>("uint16").ToLocalChecked(), WrapPointer((char *)&ffi_type_uint16));
  ftmap->Set(Nan::New<String>("int16").ToLocalChecked(), WrapPointer((char *)&ffi_type_sint16));
  ftmap->Set(Nan::New<String>("uint32").ToLocalChecked(), WrapPointer((char *)&ffi_type_uint32));
  ftmap->Set(Nan::New<String>("int32").ToLocalChecked(), WrapPointer((char *)&ffi_type_sint32));
  ftmap->Set(Nan::New<String>("uint64").ToLocalChecked(), WrapPointer((char *)&ffi_type_uint64));
  ftmap->Set(Nan::New<String>("int64").ToLocalChecked(), WrapPointer((char *)&ffi_type_sint64));
  ftmap->Set(Nan::New<String>("uchar").ToLocalChecked(), WrapPointer((char *)&ffi_type_uchar));
  ftmap->Set(Nan::New<String>("char").ToLocalChecked(), WrapPointer((char *)&ffi_type_schar));
  ftmap->Set(Nan::New<String>("ushort").ToLocalChecked(), WrapPointer((char *)&ffi_type_ushort));
  ftmap->Set(Nan::New<String>("short").ToLocalChecked(), WrapPointer((char *)&ffi_type_sshort));
  ftmap->Set(Nan::New<String>("uint").ToLocalChecked(), WrapPointer((char *)&ffi_type_uint));
  ftmap->Set(Nan::New<String>("int").ToLocalChecked(), WrapPointer((char *)&ffi_type_sint));
  ftmap->Set(Nan::New<String>("float").ToLocalChecked(), WrapPointer((char *)&ffi_type_float));
  ftmap->Set(Nan::New<String>("double").ToLocalChecked(), WrapPointer((char *)&ffi_type_double));
  ftmap->Set(Nan::New<String>("pointer").ToLocalChecked(), WrapPointer((char *)&ffi_type_pointer));
  // NOTE: "long" and "ulong" get handled in JS-land
  // Let libffi handle "long long"
  ftmap->Set(Nan::New<String>("ulonglong").ToLocalChecked(), WrapPointer((char *)&ffi_type_ulong));
  ftmap->Set(Nan::New<String>("longlong").ToLocalChecked(), WrapPointer((char *)&ffi_type_slong));

  target->Set(Nan::New<String>("FFI_TYPES").ToLocalChecked(), ftmap);
}

/*
 * Function that creates and returns an `ffi_cif` pointer from the given return
 * value type and argument types.
 *
 * args[0] - the CIF buffer
 * args[1] - the number of args
 * args[2] - the "return type" pointer
 * args[3] - the "arguments types array" pointer
 * args[4] - the ABI to use
 *
 * returns the ffi_status result from ffi_prep_cif()
 */

NAN_METHOD(FFI::FFIPrepCif) {
  unsigned int nargs;
  char *rtype, *atypes, *cif;
  ffi_status status;
  ffi_abi abi;

  if (info.Length() != 5) {
    return THROW_ERROR_EXCEPTION("ffi_prep_cif() requires 5 arguments!");
  }

  Handle<Value> cif_buf = info[0];
  if (!Buffer::HasInstance(cif_buf)) {
    return THROW_ERROR_EXCEPTION("prepCif(): Buffer required as first arg");
  }

  cif = Buffer::Data(cif_buf.As<Object>());
  nargs = info[1]->Uint32Value();
  rtype = Buffer::Data(info[2]->ToObject());
  atypes = Buffer::Data(info[3]->ToObject());
  abi = (ffi_abi)info[4]->Uint32Value();

  status = ffi_prep_cif(
      (ffi_cif *)cif,
      abi,
      nargs,
      (ffi_type *)rtype,
      (ffi_type **)atypes);

  info.GetReturnValue().Set(Nan::New<Integer>(status));
}

/*
 * Function that creates and returns an `ffi_cif` pointer from the given return
 * value type and argument types.
 *
 * args[0] - the CIF buffer
 * args[1] - the number of fixed args
 * args[2] - the number of total args
 * args[3] - the "return type" pointer
 * args[4] - the "arguments types array" pointer
 * args[5] - the ABI to use
 *
 * returns the ffi_status result from ffi_prep_cif_var()
 */
NAN_METHOD(FFI::FFIPrepCifVar) {
  unsigned int fargs, targs;
  char *rtype, *atypes, *cif;
  ffi_status status;
  ffi_abi abi;

  if (info.Length() != 6) {
    return THROW_ERROR_EXCEPTION("ffi_prep_cif() requires 5 arguments!");
  }

  Handle<Value> cif_buf = info[0];
  if (!Buffer::HasInstance(cif_buf)) {
    return THROW_ERROR_EXCEPTION("prepCifVar(): Buffer required as first arg");
  }

  cif = Buffer::Data(cif_buf.As<Object>());
  fargs = info[1]->Uint32Value();
  targs = info[2]->Uint32Value();
  rtype = Buffer::Data(info[3]->ToObject());
  atypes = Buffer::Data(info[4]->ToObject());
  abi = (ffi_abi)info[5]->Uint32Value();

  status = ffi_prep_cif_var(
      (ffi_cif *)cif,
      abi,
      fargs,
      targs,
      (ffi_type *)rtype,
      (ffi_type **)atypes);

  info.GetReturnValue().Set(Nan::New<Integer>(status));
}

/*
 * JS wrapper around `ffi_call()`.
 *
 * args[0] - Buffer - the `ffi_cif *`
 * args[1] - Buffer - the C function pointer to invoke
 * args[2] - Buffer - the `void *` buffer big enough to hold the return value
 * args[3] - Buffer - the `void **` array of pointers containing the arguments
 */

NAN_METHOD(FFI::FFICall) {
  if (info.Length() != 4) {
    return THROW_ERROR_EXCEPTION("ffi_call() requires 4 arguments!");
  }

  char *cif = Buffer::Data(info[0]->ToObject());
  char *fn = Buffer::Data(info[1]->ToObject());
  char *res = Buffer::Data(info[2]->ToObject());
  char *fnargs = Buffer::Data(info[3]->ToObject());

#if __OBJC__ || __OBJC2__
    @try {
#endif
      ffi_call(
          (ffi_cif *)cif,
          FFI_FN(fn),
          (void *)res,
          (void **)fnargs
        );
#if __OBJC__ || __OBJC2__
    } @catch (id ex) {
      return THROW_ERROR_EXCEPTION(WrapPointer((char *)ex));
    }
#endif

  info.GetReturnValue().SetUndefined();
}

/*
 * Asynchronous JS wrapper around `ffi_call()`.
 *
 * args[0] - Buffer - the `ffi_cif *`
 * args[1] - Buffer - the C function pointer to invoke
 * args[2] - Buffer - the `void *` buffer big enough to hold the return value
 * args[3] - Buffer - the `void **` array of pointers containing the arguments
 * args[4] - Function - the callback function to invoke when complete
 */

NAN_METHOD(FFI::FFICallAsync) {
  if (info.Length() != 5) {
    return THROW_ERROR_EXCEPTION("ffi_call_async() requires 5 arguments!");
  }

  AsyncCallParams *p = new AsyncCallParams();
  p->result = FFI_OK;

  // store a persistent references to all the Buffers and the callback function
  p->cif = Buffer::Data(info[0]->ToObject());
  p->fn = Buffer::Data(info[1]->ToObject());
  p->res = Buffer::Data(info[2]->ToObject());
  p->argv = Buffer::Data(info[3]->ToObject());

  Local<Function> callback = Local<Function>::Cast(info[4]);
  p->callback = new Nan::Callback(callback);

  uv_work_t *req = new uv_work_t;
  req->data = p;

  uv_queue_work(uv_default_loop(), req,
      FFI::AsyncFFICall,
      (uv_after_work_cb)FFI::FinishAsyncFFICall);

  info.GetReturnValue().SetUndefined();
}

/*
 * Called on the thread pool.
 */
void FFI::AsyncFFICall(uv_work_t *req) {
  AsyncCallParams *p = (AsyncCallParams *)req->data;

#if __OBJC__ || __OBJC2__
  @try {
#endif
    ffi_call(
      (ffi_cif *)p->cif,
      FFI_FN(p->fn),
      (void *)p->res,
      (void **)p->argv
    );
#if __OBJC__ || __OBJC2__
  } @catch (id ex) {
    p->result = FFI_ASYNC_ERROR;
    p->err = (char *)ex;
  }
#endif
}

/*
 * Called after the AsyncFFICall function completes on the thread pool.
 * This gets run on the main loop thread.
 */

void FFI::FinishAsyncFFICall(uv_work_t *req) {
  Nan::HandleScope scope;

  AsyncCallParams *p = (AsyncCallParams *)req->data;

  Local<Value> argv[] = { Nan::Null() };
  if (p->result != FFI_OK) {
    // an Objective-C error was thrown
    argv[0] = WrapPointer(p->err);
  }

  Nan::TryCatch try_catch;

  // invoke the registered callback function
  p->callback->Call(1, argv);

  // dispose of our persistent handle to the callback function
  delete p->callback;

  // free up our memory (allocated in FFICallAsync)
  delete p;
  delete req;

  if (try_catch.HasCaught()) {
#if NODE_VERSION_AT_LEAST(0, 12, 0)
    Nan::FatalException(try_catch);
#else
    FatalException(try_catch);
#endif
  }
}

NAN_MODULE_INIT(init) {
  Nan::HandleScope scope;

  FFI::InitializeBindings(target);
  FFI::InitializeStaticFunctions(target);
  CallbackInfo::Initialize(target);
}

NODE_MODULE(ffi_bindings, init)


text:
from flask import request, g
from flask_restplus import abort
from .request_wants_json import request_wants_json

valid_versions = ['1', '2', '3']
def check_version(sender, **extra):
    if request.method == 'OPTIONS':
        return
    if not request_wants_json():
        return
    if request.url_rule is None:
        return
    endpoint = request.url_rule.endpoint
    if endpoint == 'api.specs' or endpoint == 'static' or endpoint.startswith('js_bo'):
        return
    version = request.headers.get('X-VERSION', None)
    if version not in valid_versions:
        abort(404, message="Invalid version, valid versions are: {}".format(valid_versions))
    g.version = int(version)

def add_version_header(sender, response, **extra):
    response.headers['X-VERSION'] = request.headers.get('X-VERSION')


text:
require 'spec_helper'

describe "gws_schedule_list_plans", type: :feature, dbscope: :example do
  let(:site) { gws_site }
  let(:item) { create :gws_schedule_plan }
  let(:index_path) { gws_schedule_list_plans_path site }
  let(:new_path) { new_gws_schedule_list_plan_path site }
  let(:show_path) { gws_schedule_list_plan_path site, item }
  let(:edit_path) { edit_gws_schedule_list_plan_path site, item }
  let(:delete_path) { delete_gws_schedule_list_plan_path site, item }

  it "without login" do
    visit index_path
    expect(current_path).to eq sns_login_path
  end

  it "without auth" do
    login_ss_user
    visit index_path
    expect(status_code).to eq 403
  end

  context "with auth" do
    before { login_gws_user }

    it "#index" do
      visit index_path
      expect(status_code).to eq 200
      expect(current_path).not_to eq sns_login_path
    end

    it "#new" do
      visit new_path
      within "form#item-form" do
        fill_in "item[name]", with: "name"
        click_button "保存"
      end
      expect(status_code).to eq 200
      expect(current_path).not_to eq new_path
      expect(page).to have_no_css("form#item-form")
    end

    it "#show" do
      visit show_path
      expect(status_code).to eq 200
      expect(current_path).not_to eq sns_login_path
    end

    it "#edit" do
      visit edit_path
      within "form#item-form" do
        fill_in "item[name]", with: "modify"
        click_button "保存"
      end
      expect(current_path).not_to eq sns_login_path
      expect(page).to have_no_css("form#item-form")
    end

    it "#delete" do
      visit delete_path
      within "form" do
        click_button "削除"
      end
      expect(current_path).to eq index_path
    end
  end
end


text:
"""MSSQL backend, thru either pymssq, adodbapi or pyodbc interfaces.

* ``IDENTITY`` columns are supported by using SA ``schema.Sequence()``
  objects. In other words::

    Table('test', mss_engine,
           Column('id',   Integer, Sequence('blah',100,10), primary_key=True),
           Column('name', String(20))
         ).create()

  would yield::

   CREATE TABLE test (
     id INTEGER NOT NULL IDENTITY(100,10) PRIMARY KEY,
     name VARCHAR(20)
     )

  Note that the start & increment values for sequences are optional
  and will default to 1,1.

* Support for ``SET IDENTITY_INSERT ON`` mode (automagic on / off for
  ``INSERT`` s)

* Support for auto-fetching of ``@@IDENTITY/@@SCOPE_IDENTITY()`` on ``INSERT``

* ``select._limit`` implemented as ``SELECT TOP n``

Known issues / TODO:

* No support for more than one ``IDENTITY`` column per table

* pymssql has problems with binary and unicode data that this module
  does **not** work around

"""

import datetime, random, warnings, re, sys, operator

from sqlalchemy import sql, schema, exceptions
from sqlalchemy.sql import compiler, expression
from sqlalchemy.engine import default, base
from sqlalchemy import types as sqltypes

class MSNumeric(sqltypes.Numeric):
    def result_processor(self, dialect):
        return None

    def bind_processor(self, dialect):
        def process(value):
            if value is None:
                # Not sure that this exception is needed
                return value
            else:
                return str(value)
        return process

    def get_col_spec(self):
        if self.precision is None:
            return "NUMERIC"
        else:
            return "NUMERIC(%(precision)s, %(length)s)" % {'precision': self.precision, 'length' : self.length}

class MSFloat(sqltypes.Float):
    def get_col_spec(self):
        return "FLOAT(%(precision)s)" % {'precision': self.precision}

    def bind_processor(self, dialect):
        def process(value):
            """By converting to string, we can use Decimal types round-trip."""
            if not value is None:
                return str(value)
            return None
        return process

class MSInteger(sqltypes.Integer):
    def get_col_spec(self):
        return "INTEGER"

class MSBigInteger(MSInteger):
    def get_col_spec(self):
        return "BIGINT"

class MSTinyInteger(MSInteger):
    def get_col_spec(self):
        return "TINYINT"

class MSSmallInteger(MSInteger):
    def get_col_spec(self):
        return "SMALLINT"

class MSDateTime(sqltypes.DateTime):
    def __init__(self, *a, **kw):
        super(MSDateTime, self).__init__(False)

    def get_col_spec(self):
        return "DATETIME"

class MSDate(sqltypes.Date):
    def __init__(self, *a, **kw):
        super(MSDate, self).__init__(False)

    def get_col_spec(self):
        return "SMALLDATETIME"

class MSTime(sqltypes.Time):
    __zero_date = datetime.date(1900, 1, 1)

    def __init__(self, *a, **kw):
        super(MSTime, self).__init__(False)

    def get_col_spec(self):
        return "DATETIME"

    def bind_processor(self, dialect):
        def process(value):
            if isinstance(value, datetime.datetime):
                value = datetime.datetime.combine(self.__zero_date, value.time())
            elif isinstance(value, datetime.time):
                value = datetime.datetime.combine(self.__zero_date, value)
            return value
        return process

    def result_processor(self, dialect):
        def process(value):
            if isinstance(value, datetime.datetime):
                return value.time()
            elif isinstance(value, datetime.date):
                return datetime.time(0, 0, 0)
            return value
        return process

class MSDateTime_adodbapi(MSDateTime):
    def result_processor(self, dialect):
        def process(value):
            # adodbapi will return datetimes with empty time values as datetime.date() objects.
            # Promote them back to full datetime.datetime()
            if value and not hasattr(value, 'second'):
                return datetime.datetime(value.year, value.month, value.day)
            return value
        return process

class MSDateTime_pyodbc(MSDateTime):
    def bind_processor(self, dialect):
        def process(value):
            if value and not hasattr(value, 'second'):
                return datetime.datetime(value.year, value.month, value.day)
            else:
                return value
        return process

class MSDate_pyodbc(MSDate):
    def bind_processor(self, dialect):
        def process(value):
            if value and not hasattr(value, 'second'):
                return datetime.datetime(value.year, value.month, value.day)
            else:
                return value
        return process

    def result_processor(self, dialect):
        def process(value):
            # pyodbc returns SMALLDATETIME values as datetime.datetime(). truncate it back to datetime.date()
            if value and hasattr(value, 'second'):
                return value.date()
            else:
                return value
        return process

class MSDate_pymssql(MSDate):
    def result_processor(self, dialect):
        def process(value):
            # pymssql will return SMALLDATETIME values as datetime.datetime(), truncate it back to datetime.date()
            if value and hasattr(value, 'second'):
                return value.date()
            else:
                return value
        return process

class MSText(sqltypes.TEXT):
    def get_col_spec(self):
        if self.dialect.text_as_varchar:
            return "VARCHAR(max)"
        else:
            return "TEXT"

class MSString(sqltypes.String):
    def get_col_spec(self):
        return "VARCHAR(%(length)s)" % {'length' : self.length}

class MSNVarchar(sqltypes.Unicode):
    def get_col_spec(self):
        if self.length:
            return "NVARCHAR(%(length)s)" % {'length' : self.length}
        elif self.dialect.text_as_varchar:
            return "NVARCHAR(max)"
        else:
            return "NTEXT"

class AdoMSNVarchar(MSNVarchar):
    """overrides bindparam/result processing to not convert any unicode strings"""
    def bind_processor(self, dialect):
        return None

    def result_processor(self, dialect):
        return None

class MSChar(sqltypes.CHAR):
    def get_col_spec(self):
        return "CHAR(%(length)s)" % {'length' : self.length}

class MSNChar(sqltypes.NCHAR):
    def get_col_spec(self):
        return "NCHAR(%(length)s)" % {'length' : self.length}

class MSBinary(sqltypes.Binary):
    def get_col_spec(self):
        return "IMAGE"

class MSBoolean(sqltypes.Boolean):
    def get_col_spec(self):
        return "BIT"

    def result_processor(self, dialect):
        def process(value):
            if value is None:
                return None
            return value and True or False
        return process

    def bind_processor(self, dialect):
        def process(value):
            if value is True:
                return 1
            elif value is False:
                return 0
            elif value is None:
                return None
            else:
                return value and True or False
        return process

class MSTimeStamp(sqltypes.TIMESTAMP):
    def get_col_spec(self):
        return "TIMESTAMP"

class MSMoney(sqltypes.TypeEngine):
    def get_col_spec(self):
        return "MONEY"

class MSSmallMoney(MSMoney):
    def get_col_spec(self):
        return "SMALLMONEY"

class MSUniqueIdentifier(sqltypes.TypeEngine):
    def get_col_spec(self):
        return "UNIQUEIDENTIFIER"

class MSVariant(sqltypes.TypeEngine):
    def get_col_spec(self):
        return "SQL_VARIANT"

def descriptor():
    return {'name':'mssql',
    'description':'MSSQL',
    'arguments':[
        ('user',"Database Username",None),
        ('password',"Database Password",None),
        ('db',"Database Name",None),
        ('host',"Hostname", None),
    ]}

class MSSQLExecutionContext(default.DefaultExecutionContext):
    def __init__(self, *args, **kwargs):
        self.IINSERT = self.HASIDENT = False
        super(MSSQLExecutionContext, self).__init__(*args, **kwargs)

    def _has_implicit_sequence(self, column):
        if column.primary_key and column.autoincrement:
            if isinstance(column.type, sqltypes.Integer) and not column.foreign_key:
                if column.default is None or (isinstance(column.default, schema.Sequence) and \
                                              column.default.optional):
                    return True
        return False

    def pre_exec(self):
        """MS-SQL has a special mode for inserting non-NULL values
        into IDENTITY columns.

        Activate it if the feature is turned on and needed.
        """
        if self.compiled.isinsert:
            tbl = self.compiled.statement.table
            if not hasattr(tbl, 'has_sequence'):
                tbl.has_sequence = None
                for column in tbl.c:
                    if getattr(column, 'sequence', False) or self._has_implicit_sequence(column):
                        tbl.has_sequence = column
                        break

            self.HASIDENT = bool(tbl.has_sequence)
            if self.dialect.auto_identity_insert and self.HASIDENT:
                if isinstance(self.compiled_parameters, list):
                    self.IINSERT = tbl.has_sequence.key in self.compiled_parameters[0]
                else:
                    self.IINSERT = tbl.has_sequence.key in self.compiled_parameters
            else:
                self.IINSERT = False

            if self.IINSERT:
                self.cursor.execute("SET IDENTITY_INSERT %s ON" % self.dialect.identifier_preparer.format_table(self.compiled.statement.table))

        super(MSSQLExecutionContext, self).pre_exec()

    def post_exec(self):
        """Turn off the INDENTITY_INSERT mode if it's been activated,
        and fetch recently inserted IDENTIFY values (works only for
        one column).
        """

        if self.compiled.isinsert:
            if self.IINSERT:
                self.cursor.execute("SET IDENTITY_INSERT %s OFF" % self.dialect.identifier_preparer.format_table(self.compiled.statement.table))
                self.IINSERT = False
            elif self.HASIDENT:
                if not len(self._last_inserted_ids) or self._last_inserted_ids[0] is None:
                    if self.dialect.use_scope_identity:
                        self.cursor.execute("SELECT scope_identity() AS lastrowid")
                    else:
                        self.cursor.execute("SELECT @@identity AS lastrowid")
                    row = self.cursor.fetchone()
                    self._last_inserted_ids = [int(row[0])] + self._last_inserted_ids[1:]
                    # print "LAST ROW ID", self._last_inserted_ids
            self.HASIDENT = False
        super(MSSQLExecutionContext, self).post_exec()

    _ms_is_select = re.compile(r'\s*(?:SELECT|sp_columns)',
                               re.I | re.UNICODE)

    def is_select(self):
        return self._ms_is_select.match(self.statement) is not None

class MSSQLExecutionContext_pyodbc (MSSQLExecutionContext):
    def pre_exec(self):
        """execute "set nocount on" on all connections, as a partial
        workaround for multiple result set issues."""

        if not getattr(self.connection, 'pyodbc_done_nocount', False):
            self.connection.execute('SET nocount ON')
            self.connection.pyodbc_done_nocount = True

        super(MSSQLExecutionContext_pyodbc, self).pre_exec()

        # where appropriate, issue "select scope_identity()" in the same statement
        if self.compiled.isinsert and self.HASIDENT and (not self.IINSERT) and self.dialect.use_scope_identity:
            self.statement += "; select scope_identity()"

    def post_exec(self):
        if self.compiled.isinsert and self.HASIDENT and (not self.IINSERT) and self.dialect.use_scope_identity:
            # do nothing - id was fetched in dialect.do_execute()
            self.HASIDENT = False
        else:
            super(MSSQLExecutionContext_pyodbc, self).post_exec()

class MSSQLDialect(default.DefaultDialect):
    colspecs = {
        sqltypes.Unicode : MSNVarchar,
        sqltypes.Integer : MSInteger,
        sqltypes.Smallinteger: MSSmallInteger,
        sqltypes.Numeric : MSNumeric,
        sqltypes.Float : MSFloat,
        sqltypes.DateTime : MSDateTime,
        sqltypes.Date : MSDate,
        sqltypes.Time : MSTime,
        sqltypes.String : MSString,
        sqltypes.Binary : MSBinary,
        sqltypes.Boolean : MSBoolean,
        sqltypes.TEXT : MSText,
        sqltypes.CHAR: MSChar,
        sqltypes.NCHAR: MSNChar,
        sqltypes.TIMESTAMP: MSTimeStamp,
    }

    ischema_names = {
        'int' : MSInteger,
        'bigint': MSBigInteger,
        'smallint' : MSSmallInteger,
        'tinyint' : MSTinyInteger,
        'varchar' : MSString,
        'nvarchar' : MSNVarchar,
        'char' : MSChar,
        'nchar' : MSNChar,
        'text' : MSText,
        'ntext' : MSText,
        'decimal' : MSNumeric,
        'numeric' : MSNumeric,
        'float' : MSFloat,
        'datetime' : MSDateTime,
        'smalldatetime' : MSDate,
        'binary' : MSBinary,
        'varbinary' : MSBinary,
        'bit': MSBoolean,
        'real' : MSFloat,
        'image' : MSBinary,
        'timestamp': MSTimeStamp,
        'money': MSMoney,
        'smallmoney': MSSmallMoney,
        'uniqueidentifier': MSUniqueIdentifier,
        'sql_variant': MSVariant,
    }

    def __new__(cls, dbapi=None, *args, **kwargs):
        if cls != MSSQLDialect:
            return super(MSSQLDialect, cls).__new__(cls, *args, **kwargs)
        if dbapi:
            dialect = dialect_mapping.get(dbapi.__name__)
            return dialect(*args, **kwargs)
        else:
            return object.__new__(cls, *args, **kwargs)

    def __init__(self, auto_identity_insert=True, **params):
        super(MSSQLDialect, self).__init__(**params)
        self.auto_identity_insert = auto_identity_insert
        self.text_as_varchar = False
        self.use_scope_identity = False
        self.set_default_schema_name("dbo")

    def dbapi(cls, module_name=None):
        if module_name:
            try:
                dialect_cls = dialect_mapping[module_name]
                return dialect_cls.import_dbapi()
            except KeyError:
                raise exceptions.InvalidRequestError("Unsupported MSSQL module '%s' requested (must be adodbpi, pymssql or pyodbc)" % module_name)
        else:
            for dialect_cls in [MSSQLDialect_pyodbc, MSSQLDialect_pymssql, MSSQLDialect_adodbapi]:
                try:
                    return dialect_cls.import_dbapi()
                except ImportError, e:
                    pass
            else:
                raise ImportError('No DBAPI module detected for MSSQL - please install pyodbc, pymssql, or adodbapi')
    dbapi = classmethod(dbapi)

    def create_connect_args(self, url):
        opts = url.translate_connect_args(username='user')
        opts.update(url.query)
        if 'auto_identity_insert' in opts:
            self.auto_identity_insert = bool(int(opts.pop('auto_identity_insert')))
        if 'query_timeout' in opts:
            self.query_timeout = int(opts.pop('query_timeout'))
        if 'text_as_varchar' in opts:
            self.text_as_varchar = bool(int(opts.pop('text_as_varchar')))
        if 'use_scope_identity' in opts:
            self.use_scope_identity = bool(int(opts.pop('use_scope_identity')))
        return self.make_connect_string(opts)

    def create_execution_context(self, *args, **kwargs):
        return MSSQLExecutionContext(self, *args, **kwargs)

    def type_descriptor(self, typeobj):
        newobj = sqltypes.adapt_type(typeobj, self.colspecs)
        # Some types need to know about the dialect
        if isinstance(newobj, (MSText, MSNVarchar)):
            newobj.dialect = self
        return newobj

    def last_inserted_ids(self):
        return self.context.last_inserted_ids

    def get_default_schema_name(self, connection):
        return self.schema_name

    def set_default_schema_name(self, schema_name):
        self.schema_name = schema_name

    def last_inserted_ids(self):
        return self.context.last_inserted_ids

    def do_execute(self, cursor, statement, params, **kwargs):
        if params == {}:
            params = ()
        super(MSSQLDialect, self).do_execute(cursor, statement, params, **kwargs)

    def _execute(self, c, statement, parameters):
        try:
            if parameters == {}:
                parameters = ()
            c.execute(statement, parameters)
            self.context.rowcount = c.rowcount
            c.DBPROP_COMMITPRESERVE = "Y"
        except Exception, e:
            raise exceptions.DBAPIError.instance(statement, parameters, e)

    def table_names(self, connection, schema):
        from sqlalchemy.databases import information_schema as ischema
        return ischema.table_names(connection, schema)

    def raw_connection(self, connection):
        """Pull the raw pymmsql connection out--sensative to "pool.ConnectionFairy" and pymssql.pymssqlCnx Classes"""
        try:
            # TODO: probably want to move this to individual dialect subclasses to
            # save on the exception throw + simplify
            return connection.connection.__dict__['_pymssqlCnx__cnx']
        except:
            return connection.connection.adoConn

    def uppercase_table(self, t):
        # convert all names to uppercase -- fixes refs to INFORMATION_SCHEMA for case-senstive DBs, and won't matter for case-insensitive
        t.name = t.name.upper()
        if t.schema:
            t.schema = t.schema.upper()
        for c in t.columns:
            c.name = c.name.upper()
        return t

    def has_table(self, connection, tablename, schema=None):
        import sqlalchemy.databases.information_schema as ischema

        current_schema = schema or self.get_default_schema_name(connection)
        columns = self.uppercase_table(ischema.columns)
        s = sql.select([columns],
                   current_schema
                       and sql.and_(columns.c.table_name==tablename, columns.c.table_schema==current_schema)
                       or columns.c.table_name==tablename,
                   )

        c = connection.execute(s)
        row  = c.fetchone()
        return row is not None

    def reflecttable(self, connection, table, include_columns):
        import sqlalchemy.databases.information_schema as ischema

        # Get base columns
        if table.schema is not None:
            current_schema = table.schema
        else:
            current_schema = self.get_default_schema_name(connection)

        columns = self.uppercase_table(ischema.columns)
        s = sql.select([columns],
                   current_schema
                       and sql.and_(columns.c.table_name==table.name, columns.c.table_schema==current_schema)
                       or columns.c.table_name==table.name,
                   order_by=[columns.c.ordinal_position])

        c = connection.execute(s)
        found_table = False
        while True:
            row = c.fetchone()
            if row is None:
                break
            found_table = True
            (name, type, nullable, charlen, numericprec, numericscale, default) = (
                row[columns.c.column_name],
                row[columns.c.data_type],
                row[columns.c.is_nullable] == 'YES',
                row[columns.c.character_maximum_length],
                row[columns.c.numeric_precision],
                row[columns.c.numeric_scale],
                row[columns.c.column_default]
            )
            if include_columns and name not in include_columns:
                continue

            args = []
            for a in (charlen, numericprec, numericscale):
                if a is not None:
                    args.append(a)
            coltype = self.ischema_names.get(type, None)
            if coltype == MSString and charlen == -1:
                coltype = MSText()
            else:
                if coltype is None:
                    warnings.warn(RuntimeWarning("Did not recognize type '%s' of column '%s'" % (type, name)))
                    coltype = sqltypes.NULLTYPE

                elif coltype in (MSNVarchar, AdoMSNVarchar) and charlen == -1:
                    args[0] = None
                coltype = coltype(*args)
            colargs= []
            if default is not None:
                colargs.append(schema.PassiveDefault(sql.text(default)))

            table.append_column(schema.Column(name, coltype, nullable=nullable, *colargs))

        if not found_table:
            raise exceptions.NoSuchTableError(table.name)

        # We also run an sp_columns to check for identity columns:
        cursor = connection.execute("sp_columns %s" % self.identifier_preparer.format_table(table))
        ic = None
        while True:
            row = cursor.fetchone()
            if row is None:
                break
            col_name, type_name = row[3], row[5]
            if type_name.endswith("identity"):
                ic = table.c[col_name]
                # setup a psuedo-sequence to represent the identity attribute - we interpret this at table.create() time as the identity attribute
                ic.sequence = schema.Sequence(ic.name + '_identity')
                # MSSQL: only one identity per table allowed
                cursor.close()
                break
        if not ic is None:
            try:
                cursor = connection.execute("select ident_seed(?), ident_incr(?)", table.fullname, table.fullname)
                row = cursor.fetchone()
                cursor.close()
                if not row is None:
                    ic.sequence.start=int(row[0])
                    ic.sequence.increment=int(row[1])
            except:
                # ignoring it, works just like before
                pass

        # Add constraints
        RR = self.uppercase_table(ischema.ref_constraints)    #information_schema.referential_constraints
        TC = self.uppercase_table(ischema.constraints)        #information_schema.table_constraints
        C  = self.uppercase_table(ischema.pg_key_constraints).alias('C') #information_schema.constraint_column_usage: the constrained column
        R  = self.uppercase_table(ischema.pg_key_constraints).alias('R') #information_schema.constraint_column_usage: the referenced column

        # Primary key constraints
        s = sql.select([C.c.column_name, TC.c.constraint_type], sql.and_(TC.c.constraint_name == C.c.constraint_name,
                                                                         C.c.table_name == table.name))
        c = connection.execute(s)
        for row in c:
            if 'PRIMARY' in row[TC.c.constraint_type.name]:
                table.primary_key.add(table.c[row[0]])

        # Foreign key constraints
        s = sql.select([C.c.column_name,
                        R.c.table_schema, R.c.table_name, R.c.column_name,
                        RR.c.constraint_name, RR.c.match_option, RR.c.update_rule, RR.c.delete_rule],
                       sql.and_(C.c.table_name == table.name,
                                C.c.table_schema == current_schema,
                                C.c.constraint_name == RR.c.constraint_name,
                                R.c.constraint_name == RR.c.unique_constraint_name,
                                C.c.ordinal_position == R.c.ordinal_position
                                ),
                       order_by = [RR.c.constraint_name, R.c.ordinal_position])
        rows = connection.execute(s).fetchall()

        # group rows by constraint ID, to handle multi-column FKs
        fknm, scols, rcols = (None, [], [])
        for r in rows:
            scol, rschema, rtbl, rcol, rfknm, fkmatch, fkuprule, fkdelrule = r
            if rfknm != fknm:
                if fknm:
                    table.append_constraint(schema.ForeignKeyConstraint(scols, ['%s.%s' % (t,c) for (s,t,c) in rcols], fknm))
                fknm, scols, rcols = (rfknm, [], [])
            if (not scol in scols): scols.append(scol)
            if (not (rschema, rtbl, rcol) in rcols): rcols.append((rschema, rtbl, rcol))

        if fknm and scols:
            table.append_constraint(schema.ForeignKeyConstraint(scols, ['%s.%s' % (t,c) for (s,t,c) in rcols], fknm))

class MSSQLDialect_pymssql(MSSQLDialect):
    supports_sane_rowcount = False
    max_identifier_length = 30

    def import_dbapi(cls):
        import pymssql as module
        # pymmsql doesn't have a Binary method.  we use string
        # TODO: monkeypatching here is less than ideal
        module.Binary = lambda st: str(st)
        return module
    import_dbapi = classmethod(import_dbapi)

    colspecs = MSSQLDialect.colspecs.copy()
    colspecs[sqltypes.Date] = MSDate_pymssql

    ischema_names = MSSQLDialect.ischema_names.copy()
    ischema_names['smalldatetime'] = MSDate_pymssql

    def __init__(self, **params):
        super(MSSQLDialect_pymssql, self).__init__(**params)
        self.use_scope_identity = True

    def do_rollback(self, connection):
        # pymssql throws an error on repeated rollbacks. Ignore it.
        # TODO: this is normal behavior for most DBs.  are we sure we want to ignore it ?
        try:
            connection.rollback()
        except:
            pass

    def create_connect_args(self, url):
        r = super(MSSQLDialect_pymssql, self).create_connect_args(url)
        if hasattr(self, 'query_timeout'):
            self.dbapi._mssql.set_query_timeout(self.query_timeout)
        return r

    def make_connect_string(self, keys):
        if keys.get('port'):
            # pymssql expects port as host:port, not a separate arg
            keys['host'] = ''.join([keys.get('host', ''), ':', str(keys['port'])])
            del keys['port']
        return [[], keys]

    def is_disconnect(self, e):
        return isinstance(e, self.dbapi.DatabaseError) and "Error 10054" in str(e)

##    This code is leftover from the initial implementation, for reference
##    def do_begin(self, connection):
##        """implementations might want to put logic here for turning autocommit on/off, etc."""
##        pass

##    def do_rollback(self, connection):
##        """implementations might want to put logic here for turning autocommit on/off, etc."""
##        try:
##            # connection.rollback() for pymmsql failed sometimes--the begin tran doesn't show up
##            # this is a workaround that seems to be handle it.
##            r = self.raw_connection(connection)
##            r.query("if @@trancount > 0 rollback tran")
##            r.fetch_array()
##            r.query("begin tran")
##            r.fetch_array()
##        except:
##            pass

##    def do_commit(self, connection):
##        """implementations might want to put logic here for turning autocommit on/off, etc.
##            do_commit is set for pymmsql connections--ADO seems to handle transactions without any issue
##        """
##        # ADO Uses Implicit Transactions.
##        # This is very pymssql specific.  We use this instead of its commit, because it hangs on failed rollbacks.
##        # By using the "if" we don't assume an open transaction--much better.
##        r = self.raw_connection(connection)
##        r.query("if @@trancount > 0 commit tran")
##        r.fetch_array()
##        r.query("begin tran")
##        r.fetch_array()

class MSSQLDialect_pyodbc(MSSQLDialect):
    supports_sane_rowcount = False
    supports_sane_multi_rowcount = False
    # PyODBC unicode is broken on UCS-4 builds
    supports_unicode = sys.maxunicode == 65535
    supports_unicode_statements = supports_unicode

    def __init__(self, **params):
        super(MSSQLDialect_pyodbc, self).__init__(**params)
        # whether use_scope_identity will work depends on the version of pyodbc
        try:
            import pyodbc
            self.use_scope_identity = hasattr(pyodbc.Cursor, 'nextset')
        except:
            pass

    def import_dbapi(cls):
        import pyodbc as module
        return module
    import_dbapi = classmethod(import_dbapi)

    colspecs = MSSQLDialect.colspecs.copy()
    if supports_unicode:
        colspecs[sqltypes.Unicode] = AdoMSNVarchar
    colspecs[sqltypes.Date] = MSDate_pyodbc
    colspecs[sqltypes.DateTime] = MSDateTime_pyodbc

    ischema_names = MSSQLDialect.ischema_names.copy()
    if supports_unicode:
        ischema_names['nvarchar'] = AdoMSNVarchar
    ischema_names['smalldatetime'] = MSDate_pyodbc
    ischema_names['datetime'] = MSDateTime_pyodbc

    def make_connect_string(self, keys):
        if 'dsn' in keys:
            connectors = ['dsn=%s' % keys['dsn']]
        else:
            connectors = ["Driver={SQL Server}"]
            if 'port' in keys:
                connectors.append('Server=%s,%d' % (keys.get('host'), keys.get('port')))
            else:
                connectors.append('Server=%s' % keys.get('host'))
            connectors.append("Database=%s" % keys.get("database"))
        user = keys.get("user")
        if user:
            connectors.append("UID=%s" % user)
            connectors.append("PWD=%s" % keys.get("password", ""))
        else:
            connectors.append ("TrustedConnection=Yes")
        return [[";".join (connectors)], {}]

    def is_disconnect(self, e):
        return isinstance(e, self.dbapi.Error) and '[08S01]' in str(e)

    def create_execution_context(self, *args, **kwargs):
        return MSSQLExecutionContext_pyodbc(self, *args, **kwargs)

    def do_execute(self, cursor, statement, parameters, context=None, **kwargs):
        super(MSSQLDialect_pyodbc, self).do_execute(cursor, statement, parameters, context=context, **kwargs)
        if context and context.HASIDENT and (not context.IINSERT) and context.dialect.use_scope_identity:
            import pyodbc
            # fetch the last inserted id from the manipulated statement (pre_exec).
            try:
                row = cursor.fetchone()
            except pyodbc.Error, e:
                # if nocount OFF fetchone throws an exception and we have to jump over
                # the rowcount to the resultset
                cursor.nextset()
                row = cursor.fetchone()
            context._last_inserted_ids = [int(row[0])]

class MSSQLDialect_adodbapi(MSSQLDialect):
    supports_sane_rowcount = True
    supports_sane_multi_rowcount = True
    supports_unicode_statements = True

    def import_dbapi(cls):
        import adodbapi as module
        return module
    import_dbapi = classmethod(import_dbapi)

    colspecs = MSSQLDialect.colspecs.copy()
    colspecs[sqltypes.Unicode] = AdoMSNVarchar
    colspecs[sqltypes.DateTime] = MSDateTime_adodbapi

    ischema_names = MSSQLDialect.ischema_names.copy()
    ischema_names['nvarchar'] = AdoMSNVarchar
    ischema_names['datetime'] = MSDateTime_adodbapi

    def make_connect_string(self, keys):
        connectors = ["Provider=SQLOLEDB"]
        if 'port' in keys:
            connectors.append ("Data Source=%s, %s" % (keys.get("host"), keys.get("port")))
        else:
            connectors.append ("Data Source=%s" % keys.get("host"))
        connectors.append ("Initial Catalog=%s" % keys.get("database"))
        user = keys.get("user")
        if user:
            connectors.append("User Id=%s" % user)
            connectors.append("Password=%s" % keys.get("password", ""))
        else:
            connectors.append("Integrated Security=SSPI")
        return [[";".join (connectors)], {}]

    def is_disconnect(self, e):
        return isinstance(e, self.dbapi.adodbapi.DatabaseError) and "'connection failure'" in str(e)

dialect_mapping = {
    'pymssql':  MSSQLDialect_pymssql,
    'pyodbc':   MSSQLDialect_pyodbc,
    'adodbapi': MSSQLDialect_adodbapi
    }

class MSSQLCompiler(compiler.DefaultCompiler):
    def __init__(self, *args, **kwargs):
        super(MSSQLCompiler, self).__init__(*args, **kwargs)
        self.tablealiases = {}

    def get_select_precolumns(self, select):
        """ MS-SQL puts TOP, it's version of LIMIT here """
        s = select._distinct and "DISTINCT " or ""
        if select._limit:
            s += "TOP %s " % (select._limit,)
        if select._offset:
            raise exceptions.InvalidRequestError('MSSQL does not support LIMIT with an offset')
        return s

    def limit_clause(self, select):
        # Limit in mssql is after the select keyword
        return ""

    def _schema_aliased_table(self, table):
        if getattr(table, 'schema', None) is not None:
            if table not in self.tablealiases:
                self.tablealiases[table] = table.alias()
            return self.tablealiases[table]
        else:
            return None

    def visit_table(self, table, mssql_aliased=False, **kwargs):
        if mssql_aliased:
            return super(MSSQLCompiler, self).visit_table(table, **kwargs)

        # alias schema-qualified tables
        alias = self._schema_aliased_table(table)
        if alias is not None:
            return self.process(alias, mssql_aliased=True, **kwargs)
        else:
            return super(MSSQLCompiler, self).visit_table(table, **kwargs)

    def visit_alias(self, alias, **kwargs):
        # translate for schema-qualified table aliases
        self.tablealiases[alias.original] = alias
        kwargs['mssql_aliased'] = True
        return super(MSSQLCompiler, self).visit_alias(alias, **kwargs)

    def visit_column(self, column):
        if column.table is not None and not self.isupdate and not self.isdelete:
            # translate for schema-qualified table aliases
            t = self._schema_aliased_table(column.table)
            if t is not None:
                return self.process(t.corresponding_column(column))
        return super(MSSQLCompiler, self).visit_column(column)

    def visit_binary(self, binary):
        """Move bind parameters to the right-hand side of an operator, where possible."""
        if isinstance(binary.left, expression._BindParamClause) and binary.operator == operator.eq:
            return self.process(expression._BinaryExpression(binary.right, binary.left, binary.operator))
        else:
            return super(MSSQLCompiler, self).visit_binary(binary)

    def label_select_column(self, select, column):
        if isinstance(column, expression._Function):
            return column.label(column.name + "_" + hex(random.randint(0, 65535))[2:])
        else:
            return super(MSSQLCompiler, self).label_select_column(select, column)

    function_rewrites =  {'current_date': 'getdate',
                          'length':     'len',
                          }
    def visit_function(self, func):
        func.name = self.function_rewrites.get(func.name, func.name)
        return super(MSSQLCompiler, self).visit_function(func)

    def for_update_clause(self, select):
        # "FOR UPDATE" is only allowed on "DECLARE CURSOR" which SQLAlchemy doesn't use
        return ''

    def order_by_clause(self, select):
        order_by = self.process(select._order_by_clause)

        # MSSQL only allows ORDER BY in subqueries if there is a LIMIT
        if order_by and (not self.is_subquery(select) or select._limit):
            return " ORDER BY " + order_by
        else:
            return ""

class MSSQLSchemaGenerator(compiler.SchemaGenerator):
    def get_column_specification(self, column, **kwargs):
        colspec = self.preparer.format_column(column) + " " + column.type.dialect_impl(self.dialect).get_col_spec()

        # install a IDENTITY Sequence if we have an implicit IDENTITY column
        if (not getattr(column.table, 'has_sequence', False)) and column.primary_key and \
                column.autoincrement and isinstance(column.type, sqltypes.Integer) and not column.foreign_key:
            if column.default is None or (isinstance(column.default, schema.Sequence) and column.default.optional):
                column.sequence = schema.Sequence(column.name + '_seq')

        if not column.nullable:
            colspec += " NOT NULL"

        if hasattr(column, 'sequence'):
            column.table.has_sequence = column
            colspec += " IDENTITY(%s,%s)" % (column.sequence.start or 1, column.sequence.increment or 1)
        else:
            default = self.get_column_default_string(column)
            if default is not None:
                colspec += " DEFAULT " + default

        return colspec

class MSSQLSchemaDropper(compiler.SchemaDropper):
    def visit_index(self, index):
        self.append("\nDROP INDEX %s.%s" % (
            self.preparer.quote_identifier(index.table.name),
            self.preparer.quote_identifier(index.name)
            ))
        self.execute()

class MSSQLDefaultRunner(base.DefaultRunner):
    # TODO: does ms-sql have standalone sequences ?
    pass

class MSSQLIdentifierPreparer(compiler.IdentifierPreparer):
    def __init__(self, dialect):
        super(MSSQLIdentifierPreparer, self).__init__(dialect, initial_quote='[', final_quote=']')

    def _escape_identifier(self, value):
        #TODO: determin MSSQL's escapeing rules
        return value

dialect = MSSQLDialect
dialect.statement_compiler = MSSQLCompiler
dialect.schemagenerator = MSSQLSchemaGenerator
dialect.schemadropper = MSSQLSchemaDropper
dialect.preparer = MSSQLIdentifierPreparer
dialect.defaultrunner = MSSQLDefaultRunner


text:
<?php

/**
 * TestCase class for like subs.
 *
 * WARNING. These tests work directly with the local database. Don't run
 * them if you need to keep your data untouched!
 */
class TestLikes extends PHPUnit_Framework_TestCase
{
	/**
	 * Prepare some test data, to use in these tests.
	 *
	 * setUp() is run automatically by the testing framework before each test method.
	 */
	public function setUp()
	{
		// Lets make sure a topic exists by creating one
		require_once(SUBSDIR . '/Likes.subs.php');
		require_once(SUBSDIR . '/Post.subs.php');

		// post variables
		$msgOptions = array(
			'id' => 0,
			'subject' => 'A New Topic',
			'smileys_enabled' => true,
			'body' => 'Something for us to like, like bacon on a burger',
			'attachments' => array(),
			'approved' => 1
		);

		$topicOptions = array(
			'id' => 0,
			'board' => 1,
			'mark_as_read' => false
		);

		$posterOptions = array(
			'id' => 1,
			'name' => 'test',
			'email' => 'noemail@test.tes',
			'update_post_count' => false,
			'ip' => '127.0.0.1'
		);

		// Attempt to make the new topic.
		createPost($msgOptions, $topicOptions, $posterOptions);

		// Keep id of the new topic.
		$this->id_topic = $topicOptions['id'];
	}

	/**
	 * Cleanup data we no longer need at the end of the tests in this class.
	 *
	 * tearDown() is run automatically by the testing framework after each test method.
	 */
	public function tearDown()
	{
		// remove temporary test data
		require_once(SUBSDIR . '/Topic.subs.php');
		removeTopics($this->id_topic); // it should remove the likes too
	}

	/**
	 * Like the topic
	 */
	public function testLikeTopic()
	{
		global $modSettings;

		$liked_message = basicMessageInfo($this->id_topic, true, true);

		// Lets like the topic
		$modSettings['likeAllowSelf'] = 1;
		likePost(1, $liked_message, '+');

		// Get the number of likes, better be one
		$likescount = messageLikeCount($this->id_topic);
		$this->assertEquals($likescount, 1);

		// Load it in, should be able to find this as well
		$likes = loadLikes($this->id_topic, false);
		$this->assertEquals($likes[$this->id_topic]['count'], 1);
	}

	/**
	 * Remove the like that was given
	 */
	public function testRemoveLikeTopic()
	{
		$liked_message = basicMessageInfo($this->id_topic, true, true);

		// Lets remove the like from the topic
		likePost(1, $liked_message, '-');

		// get the number of likes, better be none now
		$likescount = messageLikeCount($this->id_topic);
		$this->assertEquals($likescount, 0);
	}
}


text:
#include <Inventor/C/threads/sync.h>
#include "coindefs.h"

#include <stddef.h>

#include <Inventor/C/threads/mutex.h>

#include "tidbitsp.h"
#include "base/dict.h"
#include "threads/syncp.h"
#include "threads/mutexp.h"

/* ********************************************************************** */

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

static cc_dict * sync_hash_table = NULL;

static void
sync_hash_cb(uintptr_t COIN_UNUSED_ARG(key), void * val, void * COIN_UNUSED_ARG(closure))
{
  cc_mutex_destruct((cc_mutex*) val);
}

static void
sync_cleanup(void)
{
  cc_dict_apply(sync_hash_table, sync_hash_cb, NULL);
  cc_dict_destruct(sync_hash_table);
  sync_hash_table = NULL;
}

/*
  Initialize synchronizer. Should only be called once, from SoDB::init()
*/
void
cc_sync_init(void)
{
  if (sync_hash_table == NULL) {
    /* the priority is set so to make this callback trigger late,
       after normal cleanup function which might still use a cc_sync
       instance */
    coin_atexit((coin_atexit_f*) sync_cleanup, CC_ATEXIT_THREADING_SUBSYSTEM);
    sync_hash_table = cc_dict_construct(256, 0.75f);
  }
}

/*!

  Begin synchronizing \a id. After returning from this call, other
  threads trying to synchronize \a id will be blocked until the first
  thread calls cc_sync_end() with the key returned from this function.

*/
void *
cc_sync_begin(void * id)
{
  void * mutex;

  cc_mutex_global_lock();
  if (sync_hash_table == NULL) {
    cc_sync_init();
  }
  if (!cc_dict_get(sync_hash_table, (uintptr_t)id, &mutex)) {
    mutex = (void*) cc_mutex_construct();
    (void) cc_dict_put(sync_hash_table, (uintptr_t)id, mutex);
  }

  cc_mutex_global_unlock();
  cc_mutex_lock((cc_mutex*) mutex);

  return mutex;
}

/*!
  End synchronize. \a key should be the key returned from cc_sync_begin().
*/
void
cc_sync_end(void * key)
{
  cc_mutex_unlock((cc_mutex*) key);
}

/*!
  Free sync item. This can be called from the destructor of objects
  that use a sync item so that the sync-mutex is freed when the object
  is destructed.

  \since Coin 2.3
*/
void
cc_sync_free(void * id)
{
  void * mutex;

  cc_mutex_global_lock();
  if (sync_hash_table == NULL) {
    cc_sync_init();
  }
  if (cc_dict_get(sync_hash_table, (uintptr_t)id, &mutex)) {
    cc_mutex_destruct((cc_mutex*) mutex);
    cc_dict_remove(sync_hash_table, (uintptr_t)id);
  }
  cc_mutex_global_unlock();
}

#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */


text:
"""
==========================================================
Decoding sensor space data with Generalization Across Time
==========================================================

This example runs the analysis computed in:

Jean-Remi King, Alexandre Gramfort, Aaron Schurger, Lionel Naccache
and Stanislas Dehaene, "Two distinct dynamic modes subtend the detection of
unexpected sounds", PLOS ONE, 2013,
http://www.ncbi.nlm.nih.gov/pubmed/24475052

The idea is to learn at one time instant and assess if the decoder
can predict accurately over time.
"""
# Authors: Jean-Remi King <jeanremi.king@gmail.com>
#          Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)

import mne
from mne.datasets import spm_face
from mne.decoding import GeneralizationAcrossTime

print(__doc__)

# Preprocess data
data_path = spm_face.data_path()
# Load and filter data, set up epochs
raw_fname = data_path + '/MEG/spm/SPM_CTF_MEG_example_faces%d_3D_raw.fif'

raw = mne.io.Raw(raw_fname % 1, preload=True)  # Take first run

picks = mne.pick_types(raw.info, meg=True, exclude='bads')
raw.filter(1, 45, method='iir')

events = mne.find_events(raw, stim_channel='UPPT001')
event_id = {"faces": 1, "scrambled": 2}
tmin, tmax = -0.1, 0.5

decim = 4  # decimate to make the example faster to run
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                    picks=picks, baseline=None, preload=True,
                    reject=dict(mag=1.5e-12), decim=decim, verbose=False)

# Define decoder. The decision function is employed to use cross-validation
gat = GeneralizationAcrossTime(predict_mode='cross-validation', n_jobs=1)

# fit and score
gat.fit(epochs)
gat.score(epochs)
gat.plot(vmin=0.1, vmax=0.9,
         title="Generalization Across Time (faces vs. scrambled)")
gat.plot_diagonal()  # plot decoding across time (correspond to GAT diagonal)