text:
var gulp = require("gulp"),
  clean = require("gulp-clean"),
  uglify = require("gulp-uglify"),
  rename = require("gulp-rename"),
  minifyCss = require("gulp-minify-css")
  markdown = require("gulp-markdown")
  gfi = require("gulp-file-insert");

gulp.task("default", ["watch"]);

gulp.task("watch", function () {
  gulp.watch(["src/**/*.{css,js}", "page-src/index.html", "README.md"], ["minify-js", "minify-css", "compileFrontPage"]);
});

gulp.task("clean", function() {
  return gulp.src(["dist"], { read: false })
    .pipe(clean());
});

gulp.task("minify-js", ["clean"], function () {
  gulp.src("./src/spiral-button.js")
    .pipe(rename("spiral-button.min.js"))
    .pipe(uglify())
    .pipe(gulp.dest("./dist"));
});

gulp.task("minify-css", ["clean"], function () {
  gulp.src("./src/spiral-button.css") // path to your file
    .pipe(rename("spiral-button.min.css"))
    .pipe(minifyCss())
    .pipe(gulp.dest("./dist"));
});

gulp.task("convertReadmeToHtml", function () {
  return gulp.src("README.md")
    .pipe(markdown())
    .pipe(gulp.dest("./page-src"));
});

gulp.task("compileFrontPage", ["convertReadmeToHtml"], function () {
  return gulp.src("page-src/index.html")
    .pipe(gfi({
      "<!-- readme -->": "page-src/README.html"
    }))
    .pipe(gulp.dest("./"));
});


text:
<bill session="110" type="s" number="2269" updated="2009-01-09T16:34:47-05:00">
	<status><introduced date="1193803200" datetime="2007-10-31"/></status>

	<introduced date="1193803200" datetime="2007-10-31"/>
	<titles>
		<title type="official" as="introduced">A bill to reauthorize the Mni Wiconi Rural Water Supply Project.</title>
	</titles>
	<sponsor id="300058"/>
	<cosponsors>
		<cosponsor id="400546" joined="2007-10-31"/>
	</cosponsors>
	<actions>
		<action date="1193803200" datetime="2007-10-31"><text>Read twice and referred to the Committee on Energy and Natural Resources.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	10/31/2007--Introduced.
Amends the Mni Wiconi Project Act of 1988 to authorize appropriations for the Mni Wiconi Rural Water Supply Project, South Dakota, through 2013.

</bill>

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>OCBinaryStream: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

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

OCBinaryStream 1.0.0-dev

Objective-C Binary Stream

Main Page

Classes

Files

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

Class List

Class Index

Class Hierarchy

Class Members

InputStream Member List

This is the complete list of members for InputStream, including all inherited members.

	_buffer	BaseStream	 [protected]

	_currentOffset	BaseStream	 [protected]

	_file	BaseStream	 [protected]

	_fileLen	BaseStream	 [protected]

	_path	BaseStream	 [protected]

	_stringEncoding	BaseStream	 [protected]

- 	checkSizeToRead:	BaseStream

- 	closeStream	InputStream

	isOpen	BaseStream

	len	BaseStream

	offset	BaseStream

- 	openStream	InputStream

	path	BaseStream

- 	readBytesOfLen:to:	InputStream(PrivateMethods)

- 	readChar	InputStream

- 	readDouble	InputStream

- 	readFloat	InputStream

- 	readInt	InputStream

- 	readLong	InputStream

- 	readShort	InputStream

- 	readString	InputStream

- 	readStringOfLen:	InputStream

- 	readUnsignedChar	InputStream

- 	readUnsignedInt	InputStream

- 	readUnsignedLong	InputStream

- 	readUnsignedShort	InputStream

	stringEncoding	BaseStream

 All Classes Files Functions Variables Properties

<address class="footer">Generated on Thu Jul 21 2011 20:51:58 for OCBinaryStream by

 1.7.4 </address>


text:
  Saint-Jean-d'Heurs est
       un village
       géographiquement positionné dans le département de Puy-de-Dôme en Auvergne. On dénombrait 564 habitants en 2008.

À Saint-Jean-d'Heurs, la valorisation moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 097 € du m². À la location la valeur moyenne se situe à 0 € du m² mensuel.

À coté de Saint-Jean-d'Heurs sont localisées les villes de
Ravel à 5 km, 692 habitants,
Bort-l'Étang à 4 km, 521 habitants,
Peschadoires à 3 km, 2 011 habitants,
Lezoux à 5 km, 5 434 habitants,
Thiers située à 8 km, 12 194 habitants,
Lempty située à 8 km, 317 habitants,
 entre autres. De plus, Saint-Jean-d'Heurs est située à seulement 28 km de Clermont-Ferrand.

Le parc d'habitations, à Saint-Jean-d'Heurs, se décomposait en 2011 en un appartements et 220 maisons soit
 un marché relativement équilibré.

Si vous envisagez de venir habiter à Saint-Jean-d'Heurs, vous pourrez aisément trouver une maison à acheter.


text:
yii2-date-range
=================

[![Latest Stable Version](https://img.shields.io/packagist/v/kartik-v/yii2-date-range.svg)](https://packagist.org/packages/kartik-v/yii2-date-range)
[![License](https://poser.pugx.org/kartik-v/yii2-date-range/license)](https://packagist.org/packages/kartik-v/yii2-date-range)
[![Total Downloads](https://poser.pugx.org/kartik-v/yii2-date-range/downloads)](https://packagist.org/packages/kartik-v/yii2-date-range)
[![Monthly Downloads](https://poser.pugx.org/kartik-v/yii2-date-range/d/monthly)](https://packagist.org/packages/kartik-v/yii2-date-range)
[![Daily Downloads](https://poser.pugx.org/kartik-v/yii2-date-range/d/daily)](https://packagist.org/packages/kartik-v/yii2-date-range)

An advanced date range picker input for Yii Framework 2 based on [dangrossman/bootstrap-daterangepicker plugin](https://github.com/dangrossman/bootstrap-daterangepicker).
The date range picker widget is styled for Bootstrap 3.x and creates a dropdown menu from which a user can select a range of dates. If the plugin is invoked with no options,
it will present two calendars to choose a start and end date from. Optionally, you can provide a list of date ranges the user can select from instead of
choosing dates from the calendars. If attached to a text input, the selected dates will be inserted into the text box. Otherwise, you can provide a custom callback
function to receive the selection.

Additional enhancements added for this widget (by Krajee):

- allows ability to work with Bootstrap input group addons and set the picker position to point at the input-group-addon icon.
- enhanced translation features using yii i18n message files.
- automatically convert format from PHP Date/time format to Moment.js Date/time format.
- automatically trigger change of base field to enforce Yii ActiveField validation
- ability to set the widget to display a preset dropdown of date options within a container (and hidden input).
- style the container options as per your need using templates
- automatically disable date-range based on disabled/readonly options.

### Demo
You can see detailed [documentation](http://demos.krajee.com/date-range) on usage of the extension.

### Latest Release
The latest version of the extension is release v1.6.6. Refer the [CHANGE LOG](https://github.com/kartik-v/yii2-date-range/blob/master/CHANGE.md) for details of various releases.

## Installation

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

> Note: Check the [composer.json](https://github.com/kartik-v/yii2-date-range/blob/master/composer.json) for this extension's requirements and dependencies.
Read this [web tip /wiki](http://webtips.krajee.com/setting-composer-minimum-stability-application/) on setting the `minimum-stability` settings for your application's composer.json.

Either run

```
$ php composer.phar require kartik-v/yii2-date-range "dev-master"
```

or add

```
"kartik-v/yii2-date-range": "dev-master"
```

to the ```require``` section of your `composer.json` file.

## Usage

### DateRangePicker

```php
use kartik\daterange\DateRangePicker;
echo DateRangePicker::widget([
    'model'=>$model,
    'attribute'=>'datetime_range',
    'convertFormat'=>true,
    'pluginOptions'=>[
        'timePicker'=>true,
        'timePickerIncrement'=>30,
        'locale'=>[
            'format'=>'Y-m-d h:i A'
        ]
    ]
]);
```

## License

**yii2-date-range** is released under the BSD 3-Clause License. See the bundled `LICENSE.md` for details.


text:
// Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build libsqlite3

package sqlite3

/*
#cgo CFLAGS: -DUSE_LIBSQLITE3
#cgo LDFLAGS: -lsqlite3
*/
import "C"


text:
class ApplicationController < ActionController::Base
  protect_from_forgery

  helper :async
  after_filter do
    Thread.new { AsyncCache.instance.build }
  end
end


text:
package spot.scripts;

import org.testng.Assert;
import org.testng.annotations.*;

import spot.BaseSelenium;
import spot.SeleniumTestSuite;
import spot.pages.HelpPage;
import spot.pages.StartPage;

public class ContactSupportTest extends BaseSelenium {

	@BeforeClass
	public void beforeClass() {
		navigateToStartPage();
	}

	@BeforeMethod
	public void beforeMethod() {
		navigateToStartPage();
	}

	@Test(dependsOnGroups = "helpTest")
	public void contactSupportTest() {

		/* instead of navigateToHelpPage using beforeClass is possible in theory;
		 * but beforeClass annotated methods will still run even though the group failed.
		 * -> beforeClass doesn't work with dependsOnGroups
		*/
		String windowHandleBeforeHelp = driver.getWindowHandle();

		HelpPage helpPage = new StartPage(driver).goToHelpPage();

		String supportMailAddress = helpPage.contactSupport();

		if (SeleniumTestSuite.testEnvironmentURL.equals(SeleniumTestSuite.qaImeji))
			Assert.assertEquals(supportMailAddress, "spot-support@gwdg.de");
		else if (SeleniumTestSuite.testEnvironmentURL.equals(SeleniumTestSuite.qaEdmond))
			Assert.assertEquals(supportMailAddress, "edmond-support@gwdg.de");
		else
			Assert.assertEquals(false, true, "Not known test environment url");

		// closing the (help page) window; since that window's no more required
		driver.close();

		// switching back to original browser (start page)
		driver.switchTo().window(windowHandleBeforeHelp);

	}

	@Test
	public void contactEdmondsupportFromStartPage() {
		String edmondSupportMailAddress = new StartPage(driver).contactEdmondSupport();

		Assert.assertEquals(edmondSupportMailAddress, "edmond-support@gwdg.de");

	}

}


text:
<!DOCTYPE html>

  <title>RSpec results</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Expires" content="-1" />
  <meta http-equiv="Pragma" content="no-cache" />

RSpec Code Examples

    <input id="passed_checkbox"  name="passed_checkbox"  type="checkbox" checked="checked" onchange="apply_filters()" value="1" /> Passed
    <input id="failed_checkbox"  name="failed_checkbox"  type="checkbox" checked="checked" onchange="apply_filters()" value="2" /> Failed
    <input id="pending_checkbox" name="pending_checkbox" type="checkbox" checked="checked" onchange="apply_filters()" value="3" /> Pending

DiamondLang::Errors::InvalidAxis

with the invalid axis being i

should eq "A cordinate was created with an axis of i, which isn't in: [x, y, z]"0.00243s

with the invalid axis being w

should eq "A cordinate was created with an axis of w, which isn't in: [x, y, z]"0.00020s

with the invalid axis being a

should eq "A cordinate was created with an axis of a, which isn't in: [x, y, z]"0.00013s

DiamondLang::Errors::InvalidCoordinateValue

with the invalid value being 5f

should eq "5f isn't a valid coordinate."0.00015s

with the invalid value being ~!2!

should eq "~!2! isn't a valid coordinate."0.00012s

DiamondLang::Errors::RelativeCordinateConvertedToArgument

with the default message

should eq "A relative cordinate was converted to an argument."0.00016s

DiamondLang::Errors::TooSmall

with the default message

should eq "Could not fit all commands in the area you selected."0.00014s

DiamondLang::Helpers::Block

with no nbt data

with a data value of 0

with an id of stone

is stone0.00010s

has a data value of 00.00009s

converts to a string0.00012s

converts to a string with a replace method0.00010s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00158s

is a FallingSand entity0.00016s

has a block id of stone0.00010s

has a time of 10.00013s

with an id of sand

is sand0.00010s

has a data value of 00.00009s

converts to a string0.00011s

converts to a string with a replace method0.00010s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00017s

is a FallingSand entity0.00009s

has a block id of stone0.00012s

has a time of 10.00009s

with an id of wood

is wood0.00011s

has a data value of 00.00009s

converts to a string0.00010s

converts to a string with a replace method0.00018s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00016s

is a FallingSand entity0.00015s

has a block id of stone0.00009s

has a time of 10.00009s

with a data value of 1

with an id of stone

is stone0.00009s

has a data value of 10.00011s

converts to a string0.00010s

converts to a string with a replace method0.00010s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00013s

is a FallingSand entity0.00012s

has a block id of stone0.00009s

has a time of 10.00013s

with an id of sand

is sand0.00009s

has a data value of 10.00011s

converts to a string0.00009s

converts to a string with a replace method0.00009s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00013s

is a FallingSand entity0.00009s

has a block id of stone0.00013s

has a time of 10.00009s

with an id of wood

is wood0.00011s

has a data value of 10.00008s

converts to a string0.00010s

converts to a string with a replace method0.00009s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00012s

is a FallingSand entity0.00011s

has a block id of stone0.00009s

has a time of 10.00010s

with a data value of 2

with an id of stone

is stone0.00008s

has a data value of 20.00011s

converts to a string0.00010s

converts to a string with a replace method0.00010s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00012s

is a FallingSand entity0.00009s

has a block id of stone0.00012s

has a time of 10.00017s

with an id of sand

is sand0.00008s

has a data value of 20.00008s

converts to a string0.00011s

converts to a string with a replace method0.00010s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00013s

is a FallingSand entity0.00009s

has a block id of stone0.00015s

has a time of 10.00009s

with an id of wood

is wood0.00012s

has a data value of 20.00008s

converts to a string0.00010s

converts to a string with a replace method0.00012s

when converted to falling sand

should be a kind of DiamondLang::Helpers::FallingSand0.00016s

is a FallingSand entity0.00012s

has a block id of stone0.00009s

has a time of 10.00009s


text:
<?php

namespace Skl\BlogBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * ProduitsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ProduitsRepository extends EntityRepository
{
     public function recherche($chaine)
    {
        // création d'un objet

        $qb = $this->createQueryBuilder('u')
                   ->select('u')
                   ->where('u.nom like :chaine')
                   ->andWhere('u.disponible = 1')
                   ->orderBy('u.id ')
                   ->setParameter('chaine', $chaine);

        return $qb->getQuery()->getResult();

    }
}


text:
"""
The tray classes are providing the graphical interface to the wells and
drops of the crystallization experiment.

"""

import wx
from buffered_window import BufferedWindow
import logging
import sys
from util.trayErrors import NoObservationError, BurnInBackgroundError

log = logging.getLogger("tray")
log.setLevel(logging.WARN)

# constants for movement direction
MV_FORWARDS = 0
MV_BACKWARDS = 1
MV_UP = 2
MV_DOWN = 3

class Tray(BufferedWindow):
    def __init__(self, parent, data, screen = False, id = -1, style = wx.WANTS_CHARS):
        ## Any data the Draw() function needs must be initialized before
        ## calling BufferedWindow.__init__, as it will call the Draw
        ## function.

        self.data = data
        self.data.AddEventListener("front",self)
        self.data.AddEventListener("tray",self)
        self.keyListeners = []
        self.wells = {}
        self.drops = []
        self.noCols = data.noCols
        self.noRows = data.noRows
        self.noWells = self.noCols * self.noRows
        self.isScreen = screen
        self.activeDrop = None
        self.init()
        self.collectDrops()
        self.alphabet = {1:"A", 2:"B", 3:"C", 4:"D", 5:"E", 6:"F", 7:"G",\
                         8:"H", 9:"I", 10:"J", 11:"K", 12:"L", 13:"M", 14:"N",\
                         15:"O", 16:"P", 17:"Q", 18:"R", 19:"S", 20:"T", 21:"U",\
                         22:"V", 23:"W", 24:"X", 25:"Y", 26:"Z"}
        self.printInfo = 0
        if wx.Platform == '__WXGTK__':
            self.font = wx.Font(12, wx.MODERN, wx.NORMAL, wx.NORMAL)
        else:
            self.font = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL)

        BufferedWindow.__init__(self, parent, id)
        self.Bind(wx.EVT_LEFT_UP, self.OnClick)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
        self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)

    def AddKeyListener(self, newKeyListener):
        self.keyListeners.append(newKeyListener)

    def init(self):
        color = "grey"
        for i in range(self.noWells):
            self.wells[i] = Well(self.data, i,1,1,1,1, self.isScreen)

    def RefreshWells(self):
        for well in self.wells.values():
            well.Init()
            for drop in well.drops.values():
                drop.Init()

    def calcWells(self):
        """calculates well size"""
        (x,y) = self.GetSizeTuple()
        self.xoffset = 0

        if x/(self.noCols + 2) > y/(self.noRows + 2):
            self.boxwidth = y/(self.noRows + 2)
            self.xoffset = (x - ((self.noCols + 2) * self.boxwidth)) / 2
        else:
            self.boxwidth = x/(self.noCols + 2)

        self.boxpitch = self.boxwidth + 2

        self.border = self.boxwidth
        newFont = 10
        if self.boxwidth < 20:
            newFont = self.boxwidth / 2.
        self.font = wx.Font(newFont, wx.MODERN, wx.NORMAL, wx.NORMAL)

        for i in range(self.noWells):
            rect = self.wells[i]
            c = i % self.noCols
            r = int(i/self.noCols)
            rect.SetX(c * self.boxpitch + self.border + self.xoffset)
            rect.SetY(r * self.boxpitch + self.border)
            rect.SetWidth(self.boxwidth)
            rect.SetHeight(self.boxwidth)

    def collectDrops(self):
        del self.drops[:]
        for i in range(self.noWells):
            drops = self.wells[i].drops
            for drop in drops.values():
                self.drops.append(drop)

    def OnSize(self, event):
        self.Width, self.Height = self.GetClientSizeTuple()
        self._Buffer = wx.EmptyBitmap(self.Width, self.Height)
        dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
        self.DrawBackground(dc)
        self._Buffer = wx.EmptyBitmap(self.Width, self.Height)
        self.UpdateDrawing()

    def Draw(self, dc):
        dc.BeginDrawing()
        dc.Clear() # make sure you clear the bitmap!
        dc.DrawBitmap(self.bgImage.ConvertToBitmap(), 0,0,)
        for well in self.wells.values():
            try:
                well.Draw(dc)
            except BurnInBackgroundError, e:
                #dc.EndDrawing()
                self.BurnIntoBackground([e.caller.dropNr])
                well.Draw(dc)
                #self.Draw(dc)
        dc.EndDrawing()

    def DrawBackground(self, dc):
        self.calcWells()
        dc.BeginDrawing()
        dc.SetBackground( wx.Brush("White"))
        dc.SetFont(self.font)
        dc.Clear() # make sure you clear the bitmap!

        # Here's the actual drawing code.
        colNrY = 0.5 * self.border
        rowNrX = self.xoffset + int(round(0.5 * self.boxpitch))
        for pos in self.wells.keys():
            c = pos % self.noCols
            r = int(pos/self.noCols)
            colNrX = self.xoffset + self.border + int(round((c + 0.3) * self.boxpitch))
            dc.DrawText(str(c + 1), colNrX, colNrY)
            rowNrY = self.border + int(round((r + 0.25) * self.boxpitch))
            dc.DrawText(self.alphabet[r + 1], rowNrX, rowNrY)

        for well in self.wells.values():
                #dc.SetBrush(wx.Brush(well.GetColor(),wx.SOLID))
                #dc.DrawRectangle(well.GetX(), well.GetY(), \
                #                 well.GetWidth(), well.GetHeight())
            try:
                well.Draw(dc, True)
            except BurnInBackgroundError, e:
                well.Draw(dc, True)

        if self.printInfo:
            font = wx.Font(self.boxwidth/5, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,\
                           wx.FONTWEIGHT_NORMAL)
            dc.SetFont(font)
            filename = self.data.GetFilename()
            date = self.data.observationDate
            dc.DrawText("File: " + filename, self.border,\
                        self.boxpitch * self.noRows + 1.0 * self.border)
            if date:
                dc.DrawText("Observation: " + date, self.border,\
                           self.boxpitch * self.noRows + 1.3 * self.border)

        dc.EndDrawing()
        self.bgImage = self._Buffer.ConvertToImage()

    def GetImage(self, size):
        # use a new dc to print tray and date and filename
        self.printInfo = 1
        oldSize = self.GetSizeTuple()
        newSize = size
        self.SetSize(newSize)
        dc = wx.MemoryDC()
        buffer = wx.EmptyBitmap(self.Width, self.Height)
        dc.SelectObject(buffer)
        self.DrawBackground(dc)
        self.printInfo = 0
        self.SetSize(oldSize)
        return buffer

    def OnCopy(self, event):
        # copy buffer to clipboard
        clipdata = wx.BitmapDataObject()
        clipdata.SetBitmap(self.GetImage(self.GetSize()))
        wx.TheClipboard.Open()
        wx.TheClipboard.SetData(clipdata)
        wx.TheClipboard.Close()

    def OnMultiply(self, event):
        try:
            factor = float(wx.GetTextFromUser("Please enter multipllication factor",\
                                   "Multiplication factor"))
        except ValueError:
            log.debug("Could not convert to float.")
            factor = 0
        if self.isScreen and factor:
            self.data.MultiplyScreenSolutions(factor)
            self.data.UpdateEventListeners(["screen"],self)
        elif not self.isScreen and factor:
            self.data.MultiplyReservoirSolutions(factor)
            self.data.UpdateEventListeners(["front"],self)

    def OnRightClick(self, event):
        # only do this part the first time so the events are only bound once
        #
        # Yet another anternate way to do IDs. Some prefer them up top to
        # avoid clutter, some prefer them close to the object of interest
        # for clarity.
        if not hasattr(self, "popupID1"):
            self.popupID1 = wx.NewId()
            self.Bind(wx.EVT_MENU, self.OnCopy, id=self.popupID1)
            self.popupID2 = wx.NewId()
            self.Bind(wx.EVT_MENU, self.OnMultiply, id=self.popupID2)

        # make a menu
        menu = wx.Menu()
        menu.Append(self.popupID1, "Copy Graphics")
        menu.Append(self.popupID2, "Multiply Well Concentrations")
        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu(menu, event.GetPosition())
        menu.Destroy()

    def ClearWells(self):
        for well in self.wells.values():
            well.Toggle(-1)
            well.ClearDrops()

    def OnClick(self, event):
        if not event.m_controlDown:
            self.ClearWells()

        mp = event.GetPosition()
        (x,y) = event.GetPosition()
        dx = x - self.border -  self.xoffset
        dy = y - self.border
        col = dx / self.boxpitch
        row = dy / self.boxpitch
        position = row * self.noCols + col
        self.activeWell = (position)

        if dx < 0 and  dy < 0:
            for well in self.wells.values():
                if event.m_shiftDown or self.isScreen:
                    well.Toggle()
                else:
                    well.ToggleDrop(well.GetPosition())
            self.data.UpdateEventListeners(["front","screen"],self)
            return

        if dx < 0:
            for key,well in self.wells.items():
                if int(key/self.noCols) == row:
                    if event.m_shiftDown or self.isScreen:
                        well.Toggle()
                    else:
                        well.ToggleDrop(well.GetPosition())
            self.data.UpdateEventListeners(["front","screen"],self)
            return

        if dy < 0:
            if event.m_shiftDown or self.isScreen:
                for key,well in self.wells.items():
                    if key % self.noCols == col:
                        well.Toggle()
            else:
                counter = 0
                for drop in self.drops:
                    dropy = drop.GetY()
                    if drop.Inside((x,dropy)):
                        drop.Toggle()
            self.data.UpdateEventListeners(["front","screen"],self)
            return

        if col < self.noCols and row < self.noRows:
            self.wells[position].ToggleDrop(mp)
        self.data.UpdateEventListeners(["front","screen"],self)

    def Move(self, direction):

        # get active drops or reservoir
        try:
            activeDrop = self.data.GetActiveDrops()[0]
        except IndexError:
            activeDrop = None
        try:
            activeReservoir = self.data.GetActiveReservoirs()[0]
        except IndexError:
            activeReservoir = None

        # initialize parameters for calculation of next position
        if activeDrop:
            id = self.data.noDrops * activeDrop[0] + activeDrop[1]
            containers = self.drops
            total = len(self.drops)
            nrDrops = self.data.GetNrDrops()
            drop = True
        elif activeReservoir is not None:
            id = activeReservoir
            total = self.noWells
            containers = self.wells
            nrDrops = 1
            drop = False
        else:
            return

        # calculate next position depending on direction
        if direction == MV_FORWARDS:
            next = (id + 1) % total
        elif direction == MV_BACKWARDS:
            next = (id + total - 1) % total
        elif direction == MV_UP:
            next = (id - (self.noCols * nrDrops) + \
                        total )  % total
        elif direction == MV_DOWN:
            next = (id + (self.noCols * nrDrops))\
                       % total

        # set selection on next position
        self.ClearWells()
        containers[next].Toggle(1)
        self.data.UpdateEventListeners(["front","screen"],self)

    def OnKey(self, event):
        # Send key event to listeners, register successful change
        update = False
        for keyListener in self.keyListeners:
            if keyListener.OnKey(event):
                update = True
        if update:
            self.data.UpdateEventListeners(["front","screen"],self)
        drops = self.data.GetActiveDrops()
        if len(drops):
            self.activeDrop = drops[0]

        forwardKeys = [wx.WXK_RIGHT, wx.WXK_TAB, wx.WXK_NUMPAD_ENTER,
                       wx.WXK_RETURN]
        if forwardKeys.count(event.GetKeyCode()):
            self.Move(MV_FORWARDS)

        if event.GetKeyCode() == wx.WXK_LEFT:
            self.Move(MV_BACKWARDS)

        if event.GetKeyCode() == wx.WXK_UP:
            self.Move(MV_UP)

        if event.GetKeyCode() == wx.WXK_DOWN:
            self.Move(MV_DOWN)

        try:
            keyEvents = {wx.WXK_NUMPAD0:0,wx.WXK_NUMPAD1:1,wx.WXK_NUMPAD2:2,wx.WXK_NUMPAD3:3,wx.WXK_NUMPAD4:4,
                         wx.WXK_NUMPAD5:5,wx.WXK_NUMPAD6:6,wx.WXK_NUMPAD7:7,wx.WXK_NUMPAD8:8,wx.WXK_NUMPAD9:9,
                         48:0, 49:1, 50:2, 51:3, 52:4, 53:5, 54:6, 55:7, 56:8, 57:9, wx.WXK_NUMPAD_SUBTRACT:-1,
                         wx.WXK_SUBTRACT:-1, 45:-1}
            keyCode = event.GetKeyCode()
            if keyEvents.has_key(keyCode):
                self.data.SetScore(keyEvents[keyCode])
                self.BurnIntoBackground(drops)
            if len(drops) == 1 and keyEvents.has_key(keyCode):
                self.Move(MV_FORWARDS)
        except NoObservationError, e:
            d = wx.MessageBox("Please enter observation date first.",\
                         "Error", wx.OK, self)

    def BurnIntoBackground(self, drops):
        buffer = wx.EmptyBitmap(self.Width, self.Height)
        dc = wx.BufferedDC(wx.ClientDC(self), buffer)
        dc.BeginDrawing()
        dc.Clear() # make sure you clear the bitmap!
        dc.DrawBitmap(self.bgImage.ConvertToBitmap(), 0,0,)
        for drop in drops:
            id = self.data.noDrops * drop[0] + drop[1]
            self.drops[id].Draw(dc, True)
        dc.EndDrawing()
        self.bgImage = buffer.ConvertToImage()

    def OnDataChange(self):
        self.UpdateDrawing()

class Well(wx.Rect):
    """ Class handling the properties of the well in a graphics tray"""
    border = 2
    onColor = 'yellow'
    offColor = 'grey'

    def __init__(self, data, wellNr, x=0, y=0, width=0, height=0, screen = False):
        wx.Rect.__init__(self, x, y, width, height)
        self.wellNr = wellNr
        self.data = data
        self.nrDrops = self.data.GetNrDrops()
        self.drops = {}
        self.color = self.offColor
        self.isScreen = screen
        #self.needsUpdate = True
        for i in range(self.nrDrops):
            pos = (wellNr, i)
            self.drops[i] = Drop(data, pos)
        self.Init()

    def Init(self):
        self.container = self.data.GetReservoir(self.wellNr)

    def calcDrops(self):
        """calculates drop size"""
        height = (self.height - 2 * self.border) / 2
        width = int((self.width - 2 * self.border) * 1.0 / self.nrDrops)
        for i, drop in self.drops.items():
            drop.SetX(self.x + width * (i) + self.border)
            drop.SetY(self.y +  self.border)
            drop.SetWidth(width)
            drop.SetHeight(height)

    def Draw(self, dc, background = False):
        if self.container.selected or background:
            if background:
                dc.SetBrush(wx.Brush(self.offColor,wx.SOLID))
            else:
                dc.SetBrush(wx.Brush(self.GetColor(),wx.SOLID))
            dc.DrawRectangle(self.GetX(), self.GetY(), \
                             self.GetWidth(), self.GetHeight())
        if self.nrDrops and not self.isScreen:
            if background:
                self.calcDrops()
            for drop in self.drops.values():
                if self.container.selected and not drop.container.selected:
                    try:
                        drop.Draw(dc, True)
                    except BurnInBackgroundError, e:
                        raise
                        #raise BurnInBackgroundError(e.caller)
                else:
                    try:
                        drop.Draw(dc, background)
                    except BurnInBackgroundError:
                        raise
        #if not self.container.selected:
        #    self.isChanged = False

    def GetColor(self):
        """ returns well color """
        dropSelected = False
        if type(self) == Well and self.isScreen:
            for drop in self.drops.values():
                if drop.container.selected:
                    dropSelected = True
        if self.container.selected or dropSelected:
            return wx.NamedColor(self.onColor)
        else:
            return wx.NamedColor(self.offColor)

    def SetColor(self, color):
        """ sets Well color """
        self.color = color

    def ClearDrops(self):
        for drop in self.drops.values():
            drop.Toggle(-1)

    def ToggleDrop(self, point, state = 0):
        if point.x == self.x and point.y == self.y:
            for drop in self.drops.values():
                drop.Toggle(state)
            return

        found = 0
        if self.nrDrops:
            for drop in self.drops.values():
                if drop.Inside(point):
                    drop.Toggle(state)
                    found = 1
            if not found:
                self.Toggle(state)
        else:
            self.Toggle(state)

    def Toggle(self, state = 0):
        #oldSelection = self.container.selected
        if state == 0:
##            if self.color == self.offColor:
##                self.color = self.onColor
##            else:
##                self.color = self.offColor
            #self.Init()
            self.container.selected = not self.container.selected
        elif state == 1:
##            self.color = self.onColor
            #self.Init()
            self.container.selected = True
        else:
##            self.color = self.offColor
            self.container.selected = False
        #if oldSelection != self.container.selected:
        #    self.isChanged = True

class Drop(Well):
    def __init__(self, data, dropNr, x=0, y=0, width=0, height=0):
        """ data is a TrayData object and dropNr is a tuple (wellposition, dropNr)"""
        wx.Rect.__init__(self, x, y, width, height)
        self.color = self.offColor
        self.data = data
        self.dropNr = dropNr
        self.hasImage = False
        #self.isChanged = True
        self.Init()

    def Draw(self, dc, background = False):
        if self.container.selected or background:
            if background:
                dc.SetBrush(wx.Brush(self.GetColor(True),wx.SOLID))
            else:
                dc.SetBrush(wx.Brush(self.GetColor(),wx.SOLID))
            dc.DrawRectangle(self.GetX(), self.GetY(), self.GetWidth(),\
                                     self.GetHeight())
            if self.HasImages():
                if not self.hasImage:
                    self.hasImage = True
                    #raise BurnInBackgroundError("New image update detected", self)
                dc.SetBrush(wx.Brush(wx.NamedColor("white"),wx.SOLID))
                boxsize = 0
                if self.GetWidth() > self.GetHeight():
                    boxsize =  round(self.GetHeight()/3)
                else:
                    boxsize =  round(self.GetWidth()/3)
                dc.DrawRectangle(self.GetX(), self.GetY(), boxsize,\
                                 boxsize)
            #if not self.container.selected:
            #    self.isChanged = False

    def Init(self):
        self.container = self.data.GetDrop(self.dropNr)

    def HasImages(self):
        images = self.data.GetImages(0, self.dropNr)
        return len(images)

    def GetColor(self, background = False):
        if (self.data.GetObservation(0, self.dropNr) and not self.container.selected) \
            or ( self.data.GetObservation(0, self.dropNr) and background):
            try:
                score = self.data.GetObservation(0, self.dropNr).GetProperty("ScoreValue")
                log.debug("Score: %s", score)
                return "#" + self.data.GetScoreColor(score)
            except ValueError:
                return wx.NamedColor(self.offColor)
            except KeyError:
                log.debug("ScoreColor %s not found", score)
                return wx.NamedColor(self.offColor)
        else:
            return Well.GetColor(self)

"""
Testing code
###################################3
"""

import controller

class GuiApp(wx.App):

    def OnInit(self):
        self.controller = controller.Controller(["U:/Personal/Programming/pyTray/src/","\\\\xtend\\biopshare/Thomas/Screens/pyTray_Files/test.exp"], self)
        frame = wx.Frame(None)
        data = self.controller.GetTrayData(frame, "\\\\xtend\\biopshare/Thomas/Screens/pyTray_Files/test.exp")
        tray = Tray(frame,data)
        frame.Show()
        return True

if __name__ == "__main__":
#if True:
    app = GuiApp(0)
    profiling = False
    if profiling:
        import profile
        profile.run('app.MainLoop()', 'gui_profile')
    else:
        app.MainLoop()


text:
"""Runs all the buildbot steps for ChromeDriver except for update/compile."""

import optparse
import os
import subprocess
import shutil
import sys
import tempfile
import urllib2
import zipfile

_THIS_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(_THIS_DIR, os.pardir, 'pylib'))

from common import chrome_paths
from common import util

GS_BUCKET = 'gs://chromedriver-prebuilts'
GS_ZIP_PREFIX = 'chromedriver2_prebuilts'
SLAVE_SCRIPT_DIR = os.path.join(_THIS_DIR, os.pardir, os.pardir, os.pardir,
                                os.pardir, os.pardir, os.pardir, os.pardir,
                                'scripts', 'slave')
UPLOAD_SCRIPT = os.path.join(SLAVE_SCRIPT_DIR, 'skia', 'upload_to_bucket.py')
DOWNLOAD_SCRIPT = os.path.join(SLAVE_SCRIPT_DIR, 'gsutil_download.py')

def Archive(revision):
  print '@@@BUILD_STEP archive@@@'
  prebuilts = ['libchromedriver2.so', 'chromedriver2_server',
               'chromedriver2_unittests', 'chromedriver2_tests']
  build_dir = chrome_paths.GetBuildDir(prebuilts[0:1])
  zip_name = '%s_r%s.zip' % (GS_ZIP_PREFIX, revision)
  temp_dir = util.MakeTempDir()
  zip_path = os.path.join(temp_dir, zip_name)
  print 'Zipping prebuilts %s' % zip_path
  f = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
  for prebuilt in prebuilts:
    f.write(os.path.join(build_dir, prebuilt), prebuilt)
  f.close()

  cmd = [
    sys.executable,
    UPLOAD_SCRIPT,
    '--source_filepath=%s' % zip_path,
    '--dest_gsbase=%s' % GS_BUCKET
  ]
  if util.RunCommand(cmd):
    print '@@@STEP_FAILURE@@@'

def Download():
  print '@@@BUILD_STEP Download chromedriver prebuilts@@@'

  temp_dir = util.MakeTempDir()
  zip_path = os.path.join(temp_dir, 'chromedriver2_prebuilts.zip')
  cmd = [
    sys.executable,
    DOWNLOAD_SCRIPT,
    '--url=%s' % GS_BUCKET,
    '--partial-name=%s' % GS_ZIP_PREFIX,
    '--dst=%s' % zip_path
  ]
  if util.RunCommand(cmd):
    print '@@@STEP_FAILURE@@@'

  build_dir = chrome_paths.GetBuildDir(['host_forwarder'])
  print 'Unzipping prebuilts %s to %s' % (zip_path, build_dir)
  f = zipfile.ZipFile(zip_path, 'r')
  f.extractall(build_dir)
  f.close()
  # Workaround for Python bug: http://bugs.python.org/issue15795
  os.chmod(os.path.join(build_dir, 'chromedriver2_server'), 0700)

def MaybeRelease(revision):
  # Version is embedded as: const char kChromeDriverVersion[] = "0.1";
  with open(os.path.join(_THIS_DIR, 'chrome', 'version.cc'), 'r') as f:
    version_line = filter(lambda x: 'kChromeDriverVersion' in x, f.readlines())
  version = version_line[0].split('"')[1]

  bitness = '32'
  if util.IsLinux():
    bitness = '64'
  zip_name = 'chromedriver2_%s%s_%s.zip' % (
      util.GetPlatformName(), bitness, version)

  site = 'https://code.google.com/p/chromedriver/downloads/list'
  s = urllib2.urlopen(site)
  downloads = s.read()
  s.close()

  if zip_name in downloads:
    return 0

  print '@@@BUILD_STEP releasing %s@@@' % zip_name
  if util.IsWindows():
    server_orig_name = 'chromedriver2_server.exe'
    server_name = 'chromedriver.exe'
  else:
    server_orig_name = 'chromedriver2_server'
    server_name = 'chromedriver'
  server = os.path.join(chrome_paths.GetBuildDir([server_orig_name]),
                        server_orig_name)

  print 'Zipping ChromeDriver server', server
  temp_dir = util.MakeTempDir()
  zip_path = os.path.join(temp_dir, zip_name)
  f = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
  f.write(server, server_name)
  if util.IsLinux() or util.IsMac():
    adb_commands = os.path.join(_THIS_DIR, 'chrome', 'adb_commands.py')
    f.write(adb_commands, 'adb_commands.py')
  f.close()

  cmd = [
    sys.executable,
    os.path.join(_THIS_DIR, 'third_party', 'googlecode',
                 'googlecode_upload.py'),
    '--summary', 'version of ChromeDriver2 r%s' % revision,
    '--project', 'chromedriver',
    '--user', 'chromedriver.bot@gmail.com',
    '--label', 'Release',
    zip_path
  ]
  with open(os.devnull, 'wb') as no_output:
    if subprocess.Popen(cmd, stdout=no_output, stderr=no_output).wait():
      print '@@@STEP_FAILURE@@@'

def KillChromes():
  chrome_map = {
      'win': 'chrome.exe',
      'mac': 'Chromium',
      'linux': 'chrome',
  }
  if util.IsWindows():
    cmd = ['taskkill', '/F', '/IM']
  else:
    cmd = ['pkill', '-9']
  cmd.append(chrome_map[util.GetPlatformName()])
  util.RunCommand(cmd)

def CleanTmpDir():
  tmp_dir = tempfile.gettempdir()
  print 'cleaning temp directory:', tmp_dir
  for file_name in os.listdir(tmp_dir):
    if os.path.isdir(os.path.join(tmp_dir, file_name)):
      print 'deleting sub-directory', file_name
      shutil.rmtree(os.path.join(tmp_dir, file_name), True)

def main():
  parser = optparse.OptionParser()
  parser.add_option(
      '', '--android-package',
      help='Application package name, if running tests on Android.')
  parser.add_option(
      '-r', '--revision', type='string', default=None,
      help='Chromium revision')
  options, _ = parser.parse_args()

  if not options.android_package:
    KillChromes()
  CleanTmpDir()

  if options.android_package:
    Download()
  else:
    if options.revision is None:
      parser.error('Must supply a --revision')

    platform = util.GetPlatformName()
    if 'linux' in platform:
      Archive(options.revision)

  cmd = [
    sys.executable,
    os.path.join(_THIS_DIR, 'run_all_tests.py'),
  ]
  if options.android_package:
    cmd.append('--android-package=' + options.android_package)

  passed = (util.RunCommand(cmd) == 0)

  if not options.android_package and passed:
    MaybeRelease(options.revision)

if __name__ == '__main__':
  main()


text:
#ifndef _NPT_UTILS_H_
#define _NPT_UTILS_H_

/*----------------------------------------------------------------------
|   includes
+---------------------------------------------------------------------*/
#include "NptConfig.h"
#include "NptTypes.h"
#include "NptStrings.h"
#include "NptMap.h"
#include "NptDataBuffer.h"
#include "NptHash.h"

#if defined (NPT_CONFIG_HAVE_STDIO_H)
#include <stdio.h>
#endif

#if defined (NPT_CONFIG_HAVE_STRING_H)
#include <string.h>
#endif

#if defined(NPT_CONFIG_HAVE_STDARG_H)
#include <stdarg.h>
#endif

/*----------------------------------------------------------------------
|   macros
+---------------------------------------------------------------------*/
#define NPT_ARRAY_SIZE(_a) (sizeof(_a)/sizeof((_a)[0]))

/*----------------------------------------------------------------------
|   byte I/O
+---------------------------------------------------------------------*/
extern void NPT_BytesFromInt64Be(unsigned char* buffer, NPT_UInt64 value);
extern void NPT_BytesFromInt32Be(unsigned char* buffer, NPT_UInt32 value);
extern void NPT_BytesFromInt24Be(unsigned char* buffer, NPT_UInt32 value);
extern void NPT_BytesFromInt16Be(unsigned char* buffer, NPT_UInt16 value);
extern NPT_UInt64 NPT_BytesToInt64Be(const unsigned char* buffer);
extern NPT_UInt32 NPT_BytesToInt32Be(const unsigned char* buffer);
extern NPT_UInt32 NPT_BytesToInt24Be(const unsigned char* buffer);
extern NPT_UInt16 NPT_BytesToInt16Be(const unsigned char* buffer);

extern void NPT_BytesFromInt64Le(unsigned char* buffer, NPT_UInt64 value);
extern void NPT_BytesFromInt32Le(unsigned char* buffer, NPT_UInt32 value);
extern void NPT_BytesFromInt24Le(unsigned char* buffer, NPT_UInt32 value);
extern void NPT_BytesFromInt16Le(unsigned char* buffer, NPT_UInt16 value);
extern NPT_UInt64 NPT_BytesToInt64Le(const unsigned char* buffer);
extern NPT_UInt32 NPT_BytesToInt32Le(const unsigned char* buffer);
extern NPT_UInt32 NPT_BytesToInt24Le(const unsigned char* buffer);
extern NPT_UInt16 NPT_BytesToInt16Le(const unsigned char* buffer);

/*----------------------------------------------------------------------
|    conversion utilities
+---------------------------------------------------------------------*/
extern NPT_Result
NPT_ParseFloat(const char* str, float& result, bool relaxed = true);

extern NPT_Result
NPT_ParseInteger(const char* str, long& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

extern NPT_Result
NPT_ParseInteger(const char* str, unsigned long& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

extern NPT_Result
NPT_ParseInteger(const char* str, int& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

extern NPT_Result
NPT_ParseInteger(const char* str, unsigned int& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

extern NPT_Result
NPT_ParseInteger32(const char* str, NPT_Int32& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

extern NPT_Result
NPT_ParseInteger32(const char* str, NPT_UInt32& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

extern NPT_Result
NPT_ParseInteger64(const char* str, NPT_Int64& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

extern NPT_Result
NPT_ParseInteger64(const char* str, NPT_UInt64& result, bool relaxed = true, NPT_Cardinal* chars_used = 0);

/*----------------------------------------------------------------------
|    formatting
+---------------------------------------------------------------------*/
void
NPT_FormatOutput(void        (*function)(void* parameter, const char* message),
                 void*       function_parameter,
                 const char* format,
                 va_list     args);

void NPT_ByteToHex(NPT_Byte b, char* buffer, bool uppercase=false);
NPT_Result NPT_HexToByte(const char* buffer, NPT_Byte& b);
NPT_Result NPT_HexToBytes(const char* hex, NPT_DataBuffer& bytes);
NPT_String NPT_HexString(const unsigned char* data,
                         NPT_Size             data_size,
                         const char*          separator = NULL,
                         bool                 uppercase=false);
char NPT_NibbleToHex(unsigned int nibble, bool uppercase = true);
int NPT_HexToNibble(char hex);

/*----------------------------------------------------------------------
|    parsing
+---------------------------------------------------------------------*/
NPT_Result
NPT_ParseMimeParameters(const char*                      encoded,
                        NPT_Map<NPT_String, NPT_String>& parameters);

/*----------------------------------------------------------------------
|    environment variables
+---------------------------------------------------------------------*/
class NPT_Environment {
public:
    static NPT_Result Get(const char* name, NPT_String& value);
    static NPT_Result Set(const char* name, const char* value);
};
// compat for older APIs
#define NPT_GetEnvironment(_x,_y) NPT_Environment::Get(_x,_y)

/*----------------------------------------------------------------------
|   string utils
+---------------------------------------------------------------------*/
#if defined (NPT_CONFIG_HAVE_STDIO_H)
#include <stdio.h>
#endif

#if defined (NPT_CONFIG_HAVE_STRING_H)
#include <string.h>
#endif

#if defined (NPT_CONFIG_HAVE_SNPRINTF)
#define NPT_FormatString NPT_snprintf
#else
int NPT_FormatString(char* str, NPT_Size size, const char* format, ...);
#endif

#if defined(NPT_CONFIG_HAVE_VSNPRINTF)
#define NPT_FormatStringVN(s,c,f,a) NPT_vsnprintf(s,c,f,a)
#else
extern int NPT_FormatStringVN(char *buffer, size_t count, const char *format, va_list argptr);
#endif

#if defined(NPT_CONFIG_HAVE_MEMCPY)
#define NPT_CopyMemory memcpy
#else
extern void NPT_CopyMemory(void* dest, void* src, NPT_Size size);
#endif

#if defined(NPT_CONFIG_HAVE_STRCMP)
#define NPT_StringsEqual(s1, s2) (strcmp((s1), (s2)) == 0)
#else
extern int NPT_StringsEqual(const char* s1, const char* s2);
#endif

#if defined(NPT_CONFIG_HAVE_STRNCMP)
#define NPT_StringsEqualN(s1, s2, n) (strncmp((s1), (s2), (n)) == 0)
#else
extern int NPT_StringsEqualN(const char* s1, const char* s2, unsigned long size);
#endif

#if defined(NPT_CONFIG_HAVE_STRLEN)
#define NPT_StringLength(s) (NPT_Size)(strlen(s))
#else
extern unsigned long NPT_StringLength(const char* s);
#endif

#if defined(NPT_CONFIG_HAVE_STRCPY)
#define NPT_CopyString(dst, src) ((void)NPT_strcpy((dst), (src)))
#else
extern void NPT_CopyString(char* dst, const char* src);
#endif

/**
 * Copy up to n characters from src to dst.
 * The destination buffer will be null-terminated, so it must
 * have enough space for n+1 characters (n from the source plus
 * the null terminator).
 */
#if defined(NPT_CONFIG_HAVE_STRNCPY)
#define NPT_CopyStringN(dst, src, n) \
do { ((void)NPT_strncpy((dst), (src), n)); (dst)[(n)] = '\0'; } while(0)
#else
extern int NPT_CopyStringN(char* dst, const char* src, unsigned long n);
#endif

#if defined(NPT_CONFIG_HAVE_MEMSET)
#define NPT_SetMemory memset
#else
extern void NPT_SetMemory(void* dest, int c, NPT_Size size);
#endif

#if defined(NPT_CONFIG_HAVE_MEMCMP)
#define NPT_MemoryEqual(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
#else
extern int NPT_MemoryEqual(const void* s1, const void* s2, unsigned long n);
#endif

#endif // _NPT_UTILS_H_


text:
'use strict';

var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');

var Strategy = require('./../../../src/strategies/strategy.js');
var WorldConstraints = require('./../../../src/world-constraints/');
var Block = require('./../../../src/block/');

chai.use(require('sinon-chai'));

describe('world/index.js', function () {
    var Victim;
    var consoleErrorStub;

    var noop = function () {};
    var validStrategy = new Strategy({
        getSidesTemplate: function () {
            return ['UP', 'RIGHT', 'BOTTOM', 'LEFT'];
        },
        init: noop,
        getAtPosition: noop,
        getPartialMap: noop,
        getMap: noop
    });
    var validWorldConstraints = new WorldConstraints(10, null, null);
    var validBlock = new Block(validStrategy, 'some block id');

    before(function () {
        consoleErrorStub = sinon.stub(console, 'error');
        Victim = require('./../../../src/world/index.js');
    });

    after(function () {
        consoleErrorStub.restore();
    });

    describe('constructor', function () {

        describe('assertions', function () {

            describe('strategy', function () {
                it('should fail when strategy is not an instance of Strategy', function () {
                    expect(function () {
                        new Victim();
                    }).to.throw('is required');
                    expect(function () {
                        new Victim({});
                    }).to.throw('must be an instance of "Strategy"');
                });
            });

            describe('constraints', function () {
                it('should fail when constraints is not an instance of WorldConstraints', function () {
                    expect(function () {
                        new Victim(validStrategy);
                    }).to.throw('is required');
                    expect(function () {
                        new Victim(validStrategy, {});
                    }).to.throw('must be an instance of "WorldConstraints"');
                });
            });

            describe('blocks', function () {
                it('should fail when blocks is not an array of Block instances', function () {
                    expect(function () {
                        new Victim(validStrategy, validWorldConstraints);
                    }).to.throw('is required');
                    expect(function () {
                        new Victim(validStrategy, validWorldConstraints, {});
                    }).to.throw('must be an array');
                    expect(function () {
                        new Victim(validStrategy, validWorldConstraints, []);
                    }).to.throw('must contain at least 2 items');
                    expect(function () {
                        new Victim(validStrategy, validWorldConstraints, [{}, {}]);
                    }).to.throw('must be an instance of "Block"');
                });
            });

        });

        describe('methods', function () {
            var world;
            var strategy;
            var setOfBlocks = [validBlock, validBlock];

            beforeEach(function () {
                strategy = new Strategy({
                    getSidesTemplate: sinon.stub(),
                    init: sinon.stub(),
                    getAtPosition: sinon.stub(),
                    getPartialMap: sinon.stub().returns('strategy.getPartialMap response'),
                    getMap: sinon.stub().returns('strategy.getMap response')
                });
                world = new Victim(strategy, validWorldConstraints, setOfBlocks);
            });

            describe('start', function () {
                it('should init strategy', function () {
                    world.start();
                    expect(strategy.init).to.have.been.called.once;
                    expect(strategy.init).to.have.been.calledWithExactly(validWorldConstraints, setOfBlocks);
                });

                it('should set hasStarted flag as true', function () {
                    world.start();
                    expect(world.hasStarted()).to.be.true;
                });

                it('should throw an error when instance has already started', function () {
                    expect(function () {
                        world.start();
                    }).to.not.throw(Error);
                    expect(function () {
                        world.start();
                    }).to.throw('World instance already started');
                });
            });

            describe('hasStarted', function () {
                it('should be false before start()', function () {
                    expect(world.hasStarted()).to.be.false;
                });
            });

            describe('getPartialMap', function () {

                describe('coordinates assertions', function () {
                    it('should throw when invalid minX is passed', function () {
                        expect(function () { world.getPartialMap(); }).to.throw('is required');
                        expect(function () { world.getPartialMap({}); }).to.throw('must be a number');
                    });
                    it('should throw when invalid minY is passed', function () {
                        expect(function () { world.getPartialMap(0); }).to.throw('is required');
                        expect(function () { world.getPartialMap(0, {}); }).to.throw('must be a number');
                    });
                    it('should throw when invalid maxX is passed', function () {
                        expect(function () { world.getPartialMap(0, 0); }).to.throw('is required');
                        expect(function () { world.getPartialMap(0, 0, {}); }).to.throw('must be a number');
                    });
                    it('should throw when invalid maxY is passed', function () {
                        expect(function () { world.getPartialMap(0, 0, 2); }).to.throw('is required');
                        expect(function () { world.getPartialMap(0, 0, 2, {}); }).to.throw('must be a number');
                    });
                });

                it('should throw an error when instance has not started', function () {
                    expect(function () {
                        world.getPartialMap(0, 0, 2, 2);
                    }).to.throw('World instance not started');
                });

                it('should return the strategy.getPartialMap call result', function () {
                    var partialMap;

                    world.start();
                    partialMap = world.getPartialMap(0, 0, 2, 2);
                    expect(strategy.getPartialMap).to.have.been.called.once;
                    expect(partialMap).to.be.equal('strategy.getPartialMap response');
                });

            });

            describe('getMap', function () {
                it('should throw an error when instance has not started', function () {
                    expect(function () {
                        world.getMap();
                    }).to.throw('World instance not started');
                });

                it('should return the strategy.getMap call result', function () {
                    var map;

                    world.start();
                    map = world.getMap();
                    expect(strategy.getMap).to.have.been.called.once;
                    expect(map).to.be.equal('strategy.getMap response');
                });
            });

        });

    });
});


text: google.com


text:
name: Trader Joe's
address_1: 10850 National Blvd
address_2: ''
city: Los Angeles
state: CA
zip: '90064'
phone: (310) 470-1917
latitude: '34.030053'
longitude: '-118.421502'
category: Supermarket
website: 'http://www.traderjoes.com/'
active: ''
daycode1: Mon
day1_open: '800'
day1_close: '2200'
daycode2: Tue
day2_open: '800'
day2_close: '2200'
daycode3: Wed
day3_open: '800'
day3_close: '2200'
daycode4: Thu
day4_open: '800'
day4_close: '2200'
daycode5: Fri
day5_open: '800'
day5_close: '2200'
daycode6: Sat
day6_open: '800'
day6_close: '2200'
daycode7: Sun
day7_open: '800'
day7_close: '2200'
title: 'Trader Joe''s, Food Oasis Los Angeles'
uri: /supermarket/trader-joes-10850-national-blvd/
formatted_daycode1: Monday
formatted_day1_open: 8am
formatted_day1_close: 10pm
formatted_daycode2: Tuesday
formatted_day2_open: 8am
formatted_day2_close: 10pm
formatted_daycode3: Wednesday
formatted_day3_open: 8am
formatted_day3_close: 10pm
formatted_daycode4: Thursday
formatted_day4_open: 8am
formatted_day4_close: 10pm
formatted_daycode5: Friday
formatted_day5_open: 8am
formatted_day5_close: 10pm
formatted_daycode6: Saturday
formatted_day6_open: 8am
formatted_day6_close: 10pm
formatted_daycode7: Sunday
formatted_day7_open: 8am
formatted_day7_close: 10pm

---


text:
<?php
	defined('BASEPATH') OR exit('No direct script access allowed');
	class DisplayProducts extends CI_Controller {
		public function Index (){
			$this->load->model('Search');
			$products = $this->Search->display_products();
			$view_data = array();
			$view_data['products'] = $products;
			$this->load->view('DisplayProducts/index', $view_data);

		}

		// public function Index (){
		// 	$this->load->model('Search');
		// 	$products = $this->Search->fetch_all_products();
		// 	$this->load->library('table');
		// 	$table_template = array(
		// 		'heading_row_start'   => "
",
		//         'heading_row_end'     => '
',
		// 		'row_start'           => "
",
		//         'row_end'             => '
',
		// 		);
		// 	$this->table->set_heading('Product ID', 'Category ID', 'Product Name', 'Product Description', 'Price', 'Inventory',
		// 							  'Main Image', 'Image 1', 'Image 2', 'Image 3', 'Created At', 'Updated At');
		// 	$this->table->set_template($table_template);
		// 	$data = [];
		// 	$data['products'] = $this->table->generate($products);
		// 	$this->load->view('DisplayProducts/index', $data);
		// 	// var_dump($data['products']);
		// }
	}
?>


text:
<?php
namespace whitemerry\phpkin;

/**
 * Class TracerProxy
 *
 * @author Piotr Bugaj <whitemerry@outlook.com>
 * @package whitemerry\phpkin
 */
class TracerProxy
{
    /**
     * @var Tracer
     */
    protected static $instance;

    /**
     * Set instance for proxy
     *
     * @param $instance Tracer
     *
     * @throws \InvalidArgumentException
     */
    public static function init($instance)
    {
        static::setInstance($instance);
    }

    /**
     * @see Tracer::addSpan($span)
     */
    public static function addSpan($span)
    {
        static::checkInstance();
        static::$instance->addSpan($span);
    }

    /**
     * @see Tracer::trace()
     */
    public static function trace()
    {
        static::checkInstance();
        static::$instance->trace();
    }

    /**
     * Valid and set instance
     *
     * @param $instance
     */
    protected static function setInstance($instance)
    {
        if (!($instance instanceof Tracer)) {
            throw new \InvalidArgumentException('$instance must be instance of Tracer');
        }

        static::$instance = $instance;
    }

    /**
     * Checks Tracer instance
     */
    protected static function checkInstance()
    {
        if (static::$instance === null) {
            throw new \BadMethodCallException('TracerProxy needs to be initialized first');
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.yaadafy" >

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher_2"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
        </activity>
        <activity
            android:name=".ReminderAddActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".users.Registration"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name=".users.Login"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ReminderEditActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".fragments.AddFriendActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".ShareListActivity"
            android:label="@string/app_name" >
        </activity>

        <receiver android:name=".alarm.AlarmReceiver" />
        <receiver android:name=".alarm.BootReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".appIntro.OnBoardScreenActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
        </activity>
        <activity android:name=".AboutActivity"
            android:label="@string/app_name">
        </activity>
        <service android:name=".StandardNotification">
        </service>
    </application>

</manifest>


text:
import tweepy, json
from tweepy import OAuthHandler

tw_api = None

def Auth():
	print 'Authenticating on Twitter...'
	global tw_api
	# Cuenta para App TheEventCalendar (JF)
	consumer_key = 'NDrER3txtbIHWCHlCLE9M7i7j'
	consumer_secret = 'fcfk4q9ppJ5Xh7hjOqnjVl1n8zES4DUWoi0xYXNp6KApJRBHa3'
	access_token = '230478664-nJVVHchEyomMbB4FVNDsD7gUwbLFokOFVGZZ3ZTc'
	access_secret = 'hdUwdY92LvrkVxkzmslXEOptY7x1vhJlDzUnNzbQfg4DC'

	auth = OAuthHandler(consumer_key, consumer_secret)
	auth.set_access_token(access_token, access_secret)

	tw_api = tweepy.API(auth)

def GetTweets(_user, _count=3):
	print '...Retrieving ' + _user + ' tweets'
	global tw_api
	twits = []

	# user_timeline extrae twits de una cuenta
	content = tw_api.user_timeline(screen_name = _user, count=_count, include_rts = False)

	for twit in content:
		twit_json = json.dumps(twit._json)
		twits.append(ParseTweet(twit_json))

	print '..... (' + str(len(twits)) + ')'
	return twits

def ParseTweet(_tw_json):
	tw_json = json.loads(_tw_json)
	tw = {
		'username' : tw_json['user']['name'],
		'text' : tw_json['text']
	}
	return tw


text:
package servlets;

import affichage.StylePage;
import exceptions.ExceptionConnexion;
import exceptions.ExceptionUtilisateur;
import modele.Utilisateur;
import utils.Utilitaires;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * NouvelleRepresentation Servlet.
 *
 * This servlet dynamically adds a new date a show.
 *
 * @author Sara Bouchenak
 * @version 1.0, 31/10/2007
 */

public class ConsulterRepresentationServlet extends HttpServlet {

   /**
    * HTTP GET request entry point.
    *
    * @param req	an HttpServletRequest object that contains the request
    *			the client has made of the servlet
    * @param res	an HttpServletResponse object that contains the response
    *			the servlet sends to the client
    *
    * @throws javax.servlet.ServletException   if the request for the GET could not be handled
    * @throws java.io.IOException	 if an input or output error is detected
    *				 when the servlet handles the GET request
    */
    public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException
    {
    	String numS;
        ServletOutputStream out = res.getOutputStream();

	  res.setContentType("text/html");

	 StylePage.Header(out);

	  numS= req.getParameter("numS");

	  if (numS == null) {
          	out.println("Veuillez saisir les informations relatives à la nouvelle représentation :");
          	out.println("
");
          	out.print("<form action=\"");
          	out.print("ConsulterRepresentationServlet\" ");
          	out.println("method=POST>");
          	out.println("Numéro de spectacle :");
          	out.println("<input type=text size=20 name=numS>");
          	out.println("
");
          	out.println("<input type=submit>");
          	out.println("</form>");
	  } else {
          Utilisateur user = null;
          try {
              user = Utilitaires.Identification();
          } catch (ExceptionConnexion exceptionConnexion) {
              out.println(" Message " + exceptionConnexion.getMessage());
          } catch (ExceptionUtilisateur exceptionUtilisateur) {
              out.println(" Message " + exceptionUtilisateur.getMessage());
          }
          if(user!=null){
              try {
                  Utilitaires.AfficherRepresentations(user,out,numS);
              } catch (ExceptionConnexion exceptionConnexion) {
                  out.println(" Message " + exceptionConnexion.getMessage());
              } catch (ExceptionUtilisateur exceptionUtilisateur) {
                  out.println(" Message " + exceptionUtilisateur.getMessage());
              }
          }else{
              out.println(" reseau indisponible - veuillez reessayer plus tard");
          }
      }
        StylePage.Footer(out);
    }

   /**
    * HTTP POST request entry point.
    *
    * @param req	an HttpServletRequest object that contains the request
    *			the client has made of the servlet
    * @param res	an HttpServletResponse object that contains the response
    *			the servlet sends to the client
    *
    * @throws ServletException   if the request for the POST could not be handled
    * @throws IOException	   if an input or output error is detected
    *					   when the servlet handles the POST request
    */
    public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException
    {
	  doGet(req, res);
    }

   /**
    * Returns information about this servlet.
    *
    * @return String information about this servlet
    */

    public String getServletInfo() {
        return "Ajoute une reprentation �une date donn閑 pour un spectacle existant";
    }

}


text:
/**
 * @title AopClass.java
 * @description TODO(这里用一句话描述这个文件的作用)
 * @package lm.pro.aop
 * @author mrluo735
 * @since JDK1.7
 * @date 2017年5月2日上午11:34:03
 * @version v1.0.0
 */
package lm.com.aop.model;

import java.io.Serializable;

/**
 * @ClassName: AopClass
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author mrluo735
 * @date 2017年5月2日 上午11:34:03
 *
 */
public class AopClass implements Serializable {
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 532730544830479526L;

	/**
	 * 类类型
	 */
	private EnumClassType classType = EnumClassType.Common;

	private Class<?> type;

	/**
	 * 包名
	 */
	private String packageName = "";

	/**
	 * 类名
	 */
	private String className = "";

	/**
	 * 类描述
	 */
	private String classDescription = "";

	/**
	 * 方法全名
	 */
	private String methodFullName = "";

	/**
	 * 方法名
	 */
	private String methodName = "";

	/**
	 * 方法参数
	 */
	private String methodParameter = "";

	/**
	 * 方法描述
	 */
	private String methodDescription = "";

	/**
	 * 获取类类型
	 *
	 * @return the classType
	 */
	public EnumClassType getClassType() {
		return classType;
	}

	/**
	 * 设置类类型
	 *
	 * @param classType
	 *            the classType to set
	 */
	public void setClassType(EnumClassType classType) {
		this.classType = classType;
	}

	/**
	 * @return the type
	 */
	public Class<?> getType() {
		return type;
	}

	/**
	 * @param type the type to set
	 */
	public void setType(Class<?> type) {
		this.type = type;
	}

	/**
	 * 获取包名
	 *
	 * @return the packageName
	 */
	public String getPackageName() {
		return packageName;
	}

	/**
	 * 设置包名
	 *
	 * @param packageName
	 *            the packageName to set
	 */
	public void setPackageName(String packageName) {
		this.packageName = packageName;
	}

	/**
	 * 获取类名
	 *
	 * @return the className
	 */
	public String getClassName() {
		return className;
	}

	/**
	 * 设置类名
	 *
	 * @param className
	 *            the className to set
	 */
	public void setClassName(String className) {
		this.className = className;
	}

	/**
	 * 获取类描述
	 *
	 * @return the classDescription
	 */
	public String getClassDescription() {
		return classDescription;
	}

	/**
	 * 设置类描述
	 *
	 * @param classDescription
	 *            the classDescription to set
	 */
	public void setClassDescription(String classDescription) {
		this.classDescription = classDescription;
	}

	/**
	 * 获取方法全名
	 *
	 * @return the methodFullName
	 */
	public String getMethodFullName() {
		return methodFullName;
	}

	/**
	 * 设置方法全名
	 *
	 * @param methodFullName
	 *            the methodFullName to set
	 */
	public void setMethodFullName(String methodFullName) {
		this.methodFullName = methodFullName;
	}

	/**
	 * 获取方法名
	 *
	 * @return the methodName
	 */
	public String getMethodName() {
		return methodName;
	}

	/**
	 * 设置方法名
	 *
	 * @param methodName
	 *            the methodName to set
	 */
	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	/**
	 * 获取方法参数
	 *
	 * @return the methodParameter
	 */
	public String getMethodParameter() {
		return methodParameter;
	}

	/**
	 * 设置方法参数
	 *
	 * @param methodParameter
	 *            the methodParameter to set
	 */
	public void setMethodParameter(String methodParameter) {
		this.methodParameter = methodParameter;
	}

	/**
	 * 获取方法描述
	 *
	 * @return the methodDescription
	 */
	public String getMethodDescription() {
		return methodDescription;
	}

	/**
	 * 设置方法描述
	 *
	 * @param methodDescription
	 *            the methodDescription to set
	 */
	public void setMethodDescription(String methodDescription) {
		this.methodDescription = methodDescription;
	}
}


text:
module("luci.controller.admin.system", package.seeall)

function index()
	local fs = require "nixio.fs"

	entry({"admin", "system"}, alias("admin", "system", "system"), _("System"), 30).index = true
	entry({"admin", "system", "system"}, cbi("admin_system/system"), _("System"), 1)
	entry({"admin", "system", "clock_status"}, post_on({ set = true }, "action_clock_status"))

	entry({"admin", "system", "admin"}, cbi("admin_system/admin"), _("Administration"), 2)

	if fs.access("/bin/opkg") then
		entry({"admin", "system", "packages"}, post_on({ exec = "1" }, "action_packages"), _("Software"), 10)
		entry({"admin", "system", "packages", "ipkg"}, form("admin_system/ipkg"))
	end

	entry({"admin", "system", "startup"}, form("admin_system/startup"), _("Startup"), 45)
	entry({"admin", "system", "crontab"}, form("admin_system/crontab"), _("Scheduled Tasks"), 46)

	if fs.access("/sbin/block") and fs.access("/etc/config/fstab") then
		entry({"admin", "system", "fstab"}, cbi("admin_system/fstab"), _("Mount Points"), 50)
		entry({"admin", "system", "fstab", "mount"}, cbi("admin_system/fstab/mount"), nil).leaf = true
		entry({"admin", "system", "fstab", "swap"},  cbi("admin_system/fstab/swap"),  nil).leaf = true
	end

	if fs.access("/sys/class/leds") then
		entry({"admin", "system", "leds"}, cbi("admin_system/leds"), _("LED Configuration"), 60)
	end

	entry({"admin", "system", "flashops"}, call("action_flashops"), _("Backup / Flash Firmware"), 70)
	entry({"admin", "system", "flashops", "reset"}, post("action_reset"))
	entry({"admin", "system", "flashops", "backup"}, post("action_backup"))
	entry({"admin", "system", "flashops", "backupfiles"}, form("admin_system/backupfiles"))

	-- call() instead of post() due to upload handling!
	entry({"admin", "system", "flashops", "restore"}, call("action_restore"))
	entry({"admin", "system", "flashops", "sysupgrade"}, call("action_sysupgrade"))

	entry({"admin", "system", "reboot"}, template("admin_system/reboot"), _("Reboot"), 90)
	entry({"admin", "system", "reboot", "call"}, post("action_reboot"))
end

function action_clock_status()
	local set = tonumber(luci.http.formvalue("set"))
	if set ~= nil and set > 0 then
		local date = os.date("*t", set)
		if date then
			luci.sys.call("date -s '%04d-%02d-%02d %02d:%02d:%02d'" %{
				date.year, date.month, date.day, date.hour, date.min, date.sec
			})
		end
	end

	luci.http.prepare_content("application/json")
	luci.http.write_json({ timestring = os.date("%c") })
end

function action_packages()
	local fs = require "nixio.fs"
	local ipkg = require "luci.model.ipkg"
	local submit = (luci.http.formvalue("exec") == "1")
	local update, upgrade
	local changes = false
	local install = { }
	local remove  = { }
	local stdout  = { "" }
	local stderr  = { "" }
	local out, err

	-- Display
	local display = luci.http.formvalue("display") or "installed"

	-- Letter
	local letter = string.byte(luci.http.formvalue("letter") or "A", 1)
	letter = (letter == 35 or (letter >= 65 and letter <= 90)) and letter or 65

	-- Search query
	local query = luci.http.formvalue("query")
	query = (query ~= '') and query or nil

	-- Modifying actions
	if submit then
		-- Packets to be installed
		local ninst = luci.http.formvalue("install")
		local uinst = nil

		-- Install from URL
		local url = luci.http.formvalue("url")
		if url and url ~= '' then
			uinst = url
		end

		-- Do install
		if ninst then
			install[ninst], out, err = ipkg.install(ninst)
			stdout[#stdout+1] = out
			stderr[#stderr+1] = err
			changes = true
		end

		if uinst then
			local pkg
			for pkg in luci.util.imatch(uinst) do
				install[uinst], out, err = ipkg.install(pkg)
				stdout[#stdout+1] = out
				stderr[#stderr+1] = err
				changes = true
			end
		end

		-- Remove packets
		local rem = luci.http.formvalue("remove")
		if rem then
			remove[rem], out, err = ipkg.remove(rem)
			stdout[#stdout+1] = out
			stderr[#stderr+1] = err
			changes = true
		end

		-- Update all packets
		update = luci.http.formvalue("update")
		if update then
			update, out, err = ipkg.update()
			stdout[#stdout+1] = out
			stderr[#stderr+1] = err
		end

		-- Upgrade all packets
		upgrade = luci.http.formvalue("upgrade")
		if upgrade then
			upgrade, out, err = ipkg.upgrade()
			stdout[#stdout+1] = out
			stderr[#stderr+1] = err
		end
	end

	-- List state
	local no_lists = true
	local old_lists = false
	if fs.access("/var/opkg-lists/") then
		local list
		for list in fs.dir("/var/opkg-lists/") do
			no_lists = false
			if (fs.stat("/var/opkg-lists/"..list, "mtime") or 0) < (os.time() - (24 * 60 * 60)) then
				old_lists = true
				break
			end
		end
	end

	luci.template.render("admin_system/packages", {
		display   = display,
		letter    = letter,
		query     = query,
		install   = install,
		remove    = remove,
		update    = update,
		upgrade   = upgrade,
		no_lists  = no_lists,
		old_lists = old_lists,
		stdout    = table.concat(stdout, ""),
		stderr    = table.concat(stderr, "")
	})

	-- Remove index cache
	if changes then
		fs.unlink("/tmp/luci-indexcache")
	end
end

local function image_supported(image)
	return (os.execute("sysupgrade -T %q >/dev/null" % image) == 0)
end

local function image_checksum(image)
	return (luci.sys.exec("md5sum %q" % image):match("^([^%s]+)"))
end

local function image_sha256_checksum(image)
	return (luci.sys.exec("sha256sum %q" % image):match("^([^%s]+)"))
end

local function supports_sysupgrade()
	return nixio.fs.access("/lib/upgrade/platform.sh")
end

local function supports_reset()
	return (os.execute([[grep -sqE '"rootfs_data"|"ubi"' /proc/mtd]]) == 0)
end

local function storage_size()
	local size = 0
	if nixio.fs.access("/proc/mtd") then
		for l in io.lines("/proc/mtd") do
			local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"')
			if n == "linux" or n == "firmware" then
				size = tonumber(s, 16)
				break
			end
		end
	elseif nixio.fs.access("/proc/partitions") then
		for l in io.lines("/proc/partitions") do
			local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)')
			if b and n and not n:match('[0-9]') then
				size = tonumber(b) * 1024
				break
			end
		end
	end
	return size
end

function action_flashops()
	--
	-- Overview
	--
	luci.template.render("admin_system/flashops", {
		reset_avail   = supports_reset(),
		upgrade_avail = supports_sysupgrade()
	})
end

function action_sysupgrade()
	local fs = require "nixio.fs"
	local http = require "luci.http"
	local image_tmp = "/tmp/firmware.img"

	local fp
	http.setfilehandler(
		function(meta, chunk, eof)
			if not fp and meta and meta.name == "image" then
				fp = io.open(image_tmp, "w")
			end
			if fp and chunk then
				fp:write(chunk)
			end
			if fp and eof then
				fp:close()
			end
		end
	)

	if not luci.dispatcher.test_post_security() then
		fs.unlink(image_tmp)
		return
	end

	--
	-- Cancel firmware flash
	--
	if http.formvalue("cancel") then
		fs.unlink(image_tmp)
		http.redirect(luci.dispatcher.build_url('admin/system/flashops'))
		return
	end

	--
	-- Initiate firmware flash
	--
	local step = tonumber(http.formvalue("step") or 1)
	if step == 1 then
		if image_supported(image_tmp) then
			luci.template.render("admin_system/upgrade", {
				checksum = image_checksum(image_tmp),
				sha256ch = image_sha256_checksum(image_tmp),
				storage  = storage_size(),
				size     = (fs.stat(image_tmp, "size") or 0),
				keep     = (not not http.formvalue("keep"))
			})
		else
			fs.unlink(image_tmp)
			luci.template.render("admin_system/flashops", {
				reset_avail   = supports_reset(),
				upgrade_avail = supports_sysupgrade(),
				image_invalid = true
			})
		end
	--
	-- Start sysupgrade flash
	--
	elseif step == 2 then
		local keep = (http.formvalue("keep") == "1") and "" or "-n"
		luci.template.render("admin_system/applyreboot", {
			title = luci.i18n.translate("Flashing..."),
			msg   = luci.i18n.translate("The system is flashing now.
 DO NOT POWER OFF THE DEVICE!
 Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings."),
			addr  = (#keep > 0) and "192.168.1.1" or nil
		})
		fork_exec("sleep 1; killall dropbear uhttpd; sleep 1; /sbin/sysupgrade %s %q" %{ keep, image_tmp })
	end
end

function action_backup()
	local reader = ltn12_popen("sysupgrade --create-backup - 2>/dev/null")

	luci.http.header(
		'Content-Disposition', 'attachment; filename="backup-%s-%s.tar.gz"' %{
			luci.sys.hostname(),
			os.date("%Y-%m-%d")
		})

	luci.http.prepare_content("application/x-targz")
	luci.ltn12.pump.all(reader, luci.http.write)
end

function action_restore()
	local fs = require "nixio.fs"
	local http = require "luci.http"
	local archive_tmp = "/tmp/restore.tar.gz"

	local fp
	http.setfilehandler(
		function(meta, chunk, eof)
			if not fp and meta and meta.name == "archive" then
				fp = io.open(archive_tmp, "w")
			end
			if fp and chunk then
				fp:write(chunk)
			end
			if fp and eof then
				fp:close()
			end
		end
	)

	if not luci.dispatcher.test_post_security() then
		fs.unlink(archive_tmp)
		return
	end

	local upload = http.formvalue("archive")
	if upload and #upload > 0 then
		luci.template.render("admin_system/applyreboot")
		os.execute("tar -C / -xzf %q >/dev/null 2>&1" % archive_tmp)
		luci.sys.reboot()
		return
	end

	http.redirect(luci.dispatcher.build_url('admin/system/flashops'))
end

function action_reset()
	if supports_reset() then
		luci.template.render("admin_system/applyreboot", {
			title = luci.i18n.translate("Erasing..."),
			msg   = luci.i18n.translate("The system is erasing the configuration partition now and will reboot itself when finished."),
			addr  = "192.168.1.1"
		})

		fork_exec("sleep 1; killall dropbear uhttpd; sleep 1; jffs2reset -y && reboot")
		return
	end

	http.redirect(luci.dispatcher.build_url('admin/system/flashops'))
end

function action_passwd()
	local p1 = luci.http.formvalue("pwd1")
	local p2 = luci.http.formvalue("pwd2")
	local stat = nil

	if p1 or p2 then
		if p1 == p2 then
			stat = luci.sys.user.setpasswd("root", p1)
		else
			stat = 10
		end
	end

	luci.template.render("admin_system/passwd", {stat=stat})
end

function action_reboot()
	luci.sys.reboot()
end

function fork_exec(command)
	local pid = nixio.fork()
	if pid > 0 then
		return
	elseif pid == 0 then
		-- change to root dir
		nixio.chdir("/")

		-- patch stdin, out, err to /dev/null
		local null = nixio.open("/dev/null", "w+")
		if null then
			nixio.dup(null, nixio.stderr)
			nixio.dup(null, nixio.stdout)
			nixio.dup(null, nixio.stdin)
			if null:fileno() > 2 then
				null:close()
			end
		end

		-- replace with target command
		nixio.exec("/bin/sh", "-c", command)
	end
end

function ltn12_popen(command)

	local fdi, fdo = nixio.pipe()
	local pid = nixio.fork()

	if pid > 0 then
		fdo:close()
		local close
		return function()
			local buffer = fdi:read(2048)
			local wpid, stat = nixio.waitpid(pid, "nohang")
			if not close and wpid and stat == "exited" then
				close = true
			end

			if buffer and #buffer > 0 then
				return buffer
			elseif close then
				fdi:close()
				return nil
			end
		end
	elseif pid == 0 then
		nixio.dup(fdo, nixio.stdout)
		fdi:close()
		fdo:close()
		nixio.exec("/bin/sh", "-c", command)
	end
end


text:
define([
  'underscore',
  'paper',
  'backbone',
  'models/data/PaperUI',
], function(_, paper, Backbone, PaperUI) {

  var Arrow = PaperUI.extend({

    initialize: function(data) {
      PaperUI.prototype.initialize.apply(this, arguments);
       targetLayer = paper.project.layers.filter(function(layer) {
        return layer.name === 'ui_layer';
      })[0];
    },

    draw: function() {
      var constraint = this.get('constraint');
      if ( !constraint.get('references') || !constraint.get('relatives') ) {
        console.log('[ERROR] Cannot draw arrow without constraint references and relatives existing.');
        return;
      }

      var references = constraint.get('references');
      var relatives = constraint.get('relatives');
      this.set('tail', relatives.get('geom').bounds.center);
      this.set('head', references.get('geom').bounds.center);

      var vector = this.get('head').subtract(this.get('tail')).normalize(10);
      var arrowPath = new paper.Group([
        new paper.Path([this.get('tail'), this.get('head')]),
        new paper.Path([
          this.get('head').add(vector.rotate(135)),
          this.get('head'),
          this.get('head').add(vector.rotate(-135))
        ])
      ]);
      arrowPath.strokeColor = '#A5FF00';
      arrowPath.fillColor = null;

      this.set('geometry', arrowPath);
      targetLayer.addChild(arrowPath);
    },

    hide: function() {
      var geometry = this.get('geometry');
      geometry.remove();
      geometry = null;
    },

    show: function() {
      if ( this.get('geometry') ) {
        return;
      }
      this.draw();
    },

    redraw: function() {
      var geometry = this.get('geometry');
      if ( !geometry ) {
        console.log('[ERROR] Arrow is not drawn, so redraw() does nothing.');
        return;
      }
      geometry.remove();
      geometry = null;
      this.draw();
    },

    redrawTail: function(geom) {
      var arrow = this.get('geometry');
      var newTail = geom.position;
      var currentAngle = this.get('tail').subtract(this.get('head')).angle;
      var newAngle = geom.position.subtract(this.get('head')).angle;
      this.set('tail', newTail);
      arrow.rotate(newAngle - currentAngle, this.get('head'));
      arrow.children[0].removeSegment(0);
      arrow.children[0].insert(0, newTail);
    },

    //********* DEFAULT LISTENERS **********//
    onMouseEnter: function( event ) {

    },

    onMouseLeave: function( event ) {

    },

    onClick: function( event ) {

    },

    onMouseDown: function( event ) {

    },

    onMouseUp: function( event ) {

    },

    remove: function( event ) {
      var geometry = this.get('geometry');
      if ( geometry ) {
        geometry.remove();
        geometry = null;
      }
    }
  });

  return Arrow;

});


text:
require 'pdf-reader'
require 'ndr_support/safe_file'
require_relative 'registry'

module NdrImport
  # This is one of a collection of file handlers that deal with individual formats of data.
  # They can be instantiated directly or via the factory method Registry.tables
  module File
    # This class is an AcroForm PDF file handler that returns a single table
    class AcroForm < Base
      private

      def rows(&block)
        return enum_for(:rows) unless block

        [reader.fields_hash].each(&block)
      rescue NoMethodError
        raise "Failed to read #{SafeFile.basename(@filename)} as an AcroForm PDF"
      end

      def reader
        @reader ||= AcroFormReader.new(SafeFile.safepath_to_string(@filename))
      end
    end

    Registry.register(AcroForm, 'acroform')
  end
end


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;

/**
 *
 */
public class PurchaseReservedInstancesOfferingResult implements Serializable, Cloneable {

    /**
     * The IDs of the purchased Reserved instances.
     */
    private String reservedInstancesId;

    /**
     * The IDs of the purchased Reserved instances.
     *
     * @return The IDs of the purchased Reserved instances.
     */
    public String getReservedInstancesId() {
        return reservedInstancesId;
    }

    /**
     * The IDs of the purchased Reserved instances.
     *
     * @param reservedInstancesId The IDs of the purchased Reserved instances.
     */
    public void setReservedInstancesId(String reservedInstancesId) {
        this.reservedInstancesId = reservedInstancesId;
    }

    /**
     * The IDs of the purchased Reserved instances.
     * <p>
     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param reservedInstancesId The IDs of the purchased Reserved instances.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public PurchaseReservedInstancesOfferingResult withReservedInstancesId(String reservedInstancesId) {
        this.reservedInstancesId = reservedInstancesId;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getReservedInstancesId() != null) sb.append("ReservedInstancesId: " + getReservedInstancesId() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getReservedInstancesId() == null) ? 0 : getReservedInstancesId().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof PurchaseReservedInstancesOfferingResult == false) return false;
        PurchaseReservedInstancesOfferingResult other = (PurchaseReservedInstancesOfferingResult)obj;

        if (other.getReservedInstancesId() == null ^ this.getReservedInstancesId() == null) return false;
        if (other.getReservedInstancesId() != null && other.getReservedInstancesId().equals(this.getReservedInstancesId()) == false) return false;
        return true;
    }

    @Override
    public PurchaseReservedInstancesOfferingResult clone() {
        try {
            return (PurchaseReservedInstancesOfferingResult) super.clone();

        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                    + "even though we're Cloneable!",
                    e);
        }

    }

}


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// AlipayOverseasTaxOrderQueryModel Data Structure.
    /// </summary>
    [Serializable]
    public class AlipayOverseasTaxOrderQueryModel : AopObject
    {
        /// <summary>
        /// 退税机构业务流水号,唯一,由退税机构生成,只能包含英字母、数字,长度不能小于3且不能大于64
        /// </summary>
        [XmlElement("out_order_no")]
        public string OutOrderNo { get; set; }
    }
}


text:
public class User {

  public static void test(A a) {

    a.genericFunctionWithOverloads(null, null);

  }

}


text:
package mfi.riseandshinepi.listeners;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.TimerTask;
import mfi.riseandshinepi.logic.Processor;

public abstract class AbstractLongClickMouseListener extends MouseAdapter {

	private java.util.Timer t;
	private boolean eventFired;
	private Processor processor;
	private int timespan;

	public AbstractLongClickMouseListener(Processor processor, int timespanInMillies) {
		this.processor = processor;
		timespan = timespanInMillies;
	}

	@Override
	public final void mousePressed(MouseEvent e) {

		eventFired = false;
		if (timespan > 0) {
			if (t == null) {
				t = new java.util.Timer();
			}
			t.schedule(new TimerTask() {
				@Override
				public void run() {
					eventFired = true;
					clickEvents();
					longClick();
				}
			}, timespan);
		}
	}

	@Override
	public final void mouseReleased(MouseEvent e) {
		if (t != null) {
			t.cancel();
			t.purge();
			t = null;
			if (!eventFired) {
				eventFired = true;
				clickEvents();
				shortClick();
			}
		} else {
			eventFired = true;
			clickEvents();
			shortClick();
		}
	}

	private void clickEvents() {
		getProcessor().getDisplayOffController().newActivity();
	}

	public abstract void shortClick();

	public abstract void longClick();

	Processor getProcessor() {
		return processor;
	}

}


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<title>'Sitemap & Wireframes'</title>
	<meta name="project_pf_button_text" content="'InVision Prototype'"/>
	<meta name="project_pf_button_link" content="'http://invision.michaelfangman.com/caliper-desktop'"/>
	<meta name="project_pf_iframe" content="'http://invision.michaelfangman.com/caliper-mobile'"/>
	<meta name="project_pf_phoneimg" content="caliper-homepage-mobile-wire-v1.png"/>
	<meta name="project_pf_background_image" content="business-3-min.jpg"/>
	<meta name="date" content="'03-09-2016 00:00'"/>

With the project’s goals in mind, I set out to design a better content structure and navigation system for the new site. My intention during this process was to improve the ease of navigation from page to page. After the sitemap and content structure had been locked in, I shifted my focus to building a clear content hierarchy for each page with strategically placed call to actions throughout.


text:
package com.mercury.chat.client.protocol;

import static com.mercury.chat.common.util.Preconditions.checkAllNotNull;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.mercury.chat.client.Connection;
import com.mercury.chat.client.impl.ConnectionImpl;
import com.mercury.chat.common.ConnectionListener;
import com.mercury.chat.common.exception.ChatException;

public final class SecureChatClient{

	static final Logger logger = LogManager.getLogger(SecureChatClient.class);

	private EventLoopGroup group = new NioEventLoopGroup();

	private ConnectionListener connectionListener;

	//default value for client side.
	static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));

	public static void main(String[] args) throws Exception {
        connect(HOST, PORT);
    }

    public static Connection connect(String host, int port) {
		return new ConnectionImpl().channel(new SecureChatClient().connectInner(host, port));
	}

	public Channel connectInner(String host, int port) {
		checkAllNotNull(host, port);
		// Configure SSL.
        SslContext sslCtx;
		try {
			sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
			Bootstrap b = new Bootstrap();
	        b.group(group)
	         .option(ChannelOption.TCP_NODELAY, true)
	         .channel(NioSocketChannel.class)
	         .handler(new SecureChatClientInitializer(sslCtx));
	         ChannelFuture channelFuture = b.connect(host, port);

	         channelFuture.addListener(new ChannelFutureListener(){
	 			@Override
				public void operationComplete(ChannelFuture future) throws Exception {
	 				ConnectionListener listener = getConnectionListener();
					if (listener != null) {
						listener.onConnection();
					}
				}
			});

			Channel channel = channelFuture.sync().channel();
			channel.closeFuture().addListener(new ChannelFutureListener(){
	 			@Override
				public void operationComplete(ChannelFuture future) throws Exception {
	 				ConnectionListener listener = getConnectionListener();
					if (listener != null) {
						listener.onClose();
					}
				}
			});
			return channel;
		} catch (Exception e) {
			//handler the exception
			if (connectionListener != null) {
				connectionListener.onError(e);
			}
			group.shutdownGracefully();
			throw new ChatException(e);
		}
	}

	public ConnectionListener getConnectionListener() {
		return connectionListener;
	}

	public void setConnectionListener(ConnectionListener connectionListener) {
		this.connectionListener = connectionListener;
	}

}


text:
module ZeroJobs
  class Job < ActiveRecord::Base
    set_table_name :zero_jobs

    class DumpError < StandardError
    end

    def self.enqueue(obj, mess)
      job = self.create(:object => obj, :message => mess)
      if job.new_record?
        raise ArgumentError.new("Can't save job : #{job.errors.full_message}")
      else
        JobSender.send_job(job)
      end
      job
    end

    def perfom
      self.object.send(self.message)
    end

    def terminate!
      self.destroy
    end

    def log_error(e)
      self.update_attributes(:failed_at => Time.now, :last_error =>  e.message + "\n" + e.backtrace.join("\n"))
    end

    def object
      @object ||= load(self.raw_object)
    end

    def object=(value)
      self.raw_object = self.dump(value)
    end

    def dump(obj)
      case obj
      when Class              then class_to_string(obj)
      when ActiveRecord::Base then active_record_instance_to_string(obj)
      else obj
      end
    end

    def load(str)
      begin
        hash = JSON.parse(str.to_s)
      rescue JSON::ParserError => e
        return nil
      end
      case hash['type']
      when 'class'                  then hash['class_name'].constantize
      when 'active_record_instance' then hash['class_name'].constantize.find(hash['id'].to_i)
      else nil
      end
    end

    def active_record_instance_to_string(obj)
      raise DumpError.new("Can't dump unsaved instance. Need an id to retreive it later") if obj.new_record?
      {:type => :active_record_instance, :class_name => obj.class.name, :id => obj.id}.to_json
    end

    def class_to_string(obj)
      {:type => :class, :class_name => obj.name}.to_json
    end
  end
end


text:
module Bulldog
  class MissingFile
    def initialize(options={})
      @attachment_type = attachment_type
      @file_name = options[:file_name] || 'missing-file'
      @content_type = options[:content_type]
      @path = options[:path] || '/dev/null'
    end

    attr_reader :attachment_type, :file_name, :content_type, :path
  end
end


text:
var Event = require('./Event');

function WindowEvent(type, data){
    Event.call(this, type, data);
}

WindowEvent.prototype = Object.create(Event.prototype);
WindowEvent.prototype.constructor = WindowEvent;

WindowEvent.WINDOW_RESIZE = 'windowresize';
WindowEvent.WINDOW_READY = 'windowready';

module.exports = WindowEvent;