text:
window.MinnPost = window.MinnPost || {};

(function(window, $, undefined) {
  var MapView = window.MinnPost.MapView = Backbone.View.extend({
    // Easy place for options
    options: {
      'dataPath': './data/',
      'proxyPrefix': 'https://mp-jsonproxy.herokuapp.com/proxy?callback=?&url=',
      'mapOptions': {
        'minZoom': 3,
        'maxZoom': 11
      },
      'mapID': 'map',
      'mapDefaultCenter': new L.LatLng(46.49839225859763, -93.6474609375),
      'mapDefaultZoom': 6,
      'mapDefaultLayer': 'Minnesota State House Districts',
      'mapMNBounds': [43.499356, -97.239209, 49.384358, -89.489226],
      'mapGeocodeURL': 'https://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=?&countrycodes=us&limit=1&q=',
      'applicationSelector': '#minnpost-election-map-2012-application',
      'boundaryURL': 'https://boundaries.minnpost.com/1.0/boundary/?sets=state-house-districts-2012,state-senate-districts-2012&callback=?&contains=',
      'translateLayerToBoundary': {
        'Minnesota State House Districts': 'Minnesota State House district',
        'Minnesota State Senate Districts': 'Minnesota State Senate district'
      },
      'translateLayerToDistrict': {
        'Minnesota State House Districts': 'State Representative District ',
        'Minnesota State Senate Districts': 'State Senator District '
      }
    },

    // Some placeholders
    candidates: {},
    mapLayers: {},
    mapOverlays: {},

    // Default marker
    marker: new L.CircleMarker(new L.LatLng(0, 0), {
      'color': '#4A9666',
      'weight': 1,
      'opacity': 0.9,
      'fillColor': '#63B2A7',
      'fillOpacity': 0.6,
      'radius': 8,
      'clickable': false
    }),

    // Init funciton
    initialize: function(options) {
      this.options = _.extend(this.options, options);

      if (this.isIE7()) {
        this.options.mapOptions.doubleClickZoom = false;
      }

      this.loadCandidates();
      this.drawMap();
      this.drawSide();
      this.drawLayerSwitcher();
      this.initAddressSearch();

    },

    // IE7 test.  Ran into some serious issues with IE7 so
    // need to turn off things.  :(
    isIE7: function() {
      return ($.browser.msie && $.browser.version == 7);
    },

    // Clear marker off map
    clearMarker: function() {
      if (this.marker !== undefined && this.map !== undefined) {
        this.map.removeLayer(this.marker);
      }
    },

    // Address found
    renderAddressFound: function() {
      if (this.addressFound === undefined || _.isEmpty(this.addressFound)) {
        return this;
      }
      var point = new L.LatLng(this.addressFound.lat, this.addressFound.lon);
      var b;
      var boundary;
      var district;
      var template;
      var $popup = $('.map-popup-container');

      // Place marker
      this.lastFound = 'address';
      this.marker.setLatLng(point);
      this.map.setView(point, 10);
      this.map.addLayer(this.marker);

      // Determine district
      boundary = this.options.translateLayerToBoundary[this.currentLayer];
      district = this.options.translateLayerToDistrict[this.currentLayer];
      for (b in this.addressFound.boundaries.objects) {
        if (this.addressFound.boundaries.objects[b].kind == boundary) {
          template = _.template($("#template-popup-contents").html(), {
            tileData: {},
            cands: this.getCandidates(district + this.addressFound.boundaries.objects[b].name),
            title: district + this.addressFound.boundaries.objects[b].name
          });

          $popup.html(template);
          $popup.fadeIn('fast');
        }
      }

      return this;
    },

    // Load candidates
    initAddressSearch: function() {
      var thisView = this;

      $('form#search-address-form').submit(function(e) {
        e.preventDefault();
        var address = $('input#search-address-input').val();
        if (address === '') {
          return;
        }

        $('.search-status').removeClass('error').html('Searching...');

        // Geocode address using Mapquest becuase its terms of service are more open,
        // though its geocoding is not the best.
        $.getJSON(thisView.options.mapGeocodeURL + encodeURI(address), function(value) {
          var mnBounds = thisView.options.mapMNBounds;
          value = value[0];
          if (value === undefined) {
            thisView.showAddressStatus('error', 'We were unable turn your search terms, ' + address +
              ', into a geographical location.  Please be more specific, such as including ZIP code.');
          }
          // Check we are still mostly in Minnesota
          else if (value.lat < mnBounds[0] || value.lat > mnBounds[2] ||
            value.lon < mnBounds[1] || value.lon > mnBounds[3]) {
            thisView.showAddressStatus('error', 'Sorry, but what you are looking for is outside of Minnesota.');
          }
          else {
            // Use boundary service
            $.getJSON(thisView.options.boundaryURL + encodeURI(value.lat) + ',' + encodeURI(value.lon), function(data) {
              if (data.meta.total_count === undefined || data.meta.total_count === 0) {
                thisView.showAddressStatus('error', 'Sorry, we were unable to determine the district from that address.');
              }
              else {
                $('.search-status').fadeOut('fast');
                thisView.addressFound = {
                  lat: value.lat,
                  lon: value.lon,
                  boundaries: data
                };
                thisView.clearMarker();
                thisView.renderAddressFound();
              }
            });
          }
        });

        return this;
      });
    },

    // Status and erros for address search
    showAddressStatus: function(type, status) {
      $('.search-status').html(status);
      $('.search-status').fadeIn('fast');
      if (type == 'error') {
        $('.search-status').addClass('error');
      }
      else {
        $('.search-status').removeClass('error');
      }
      return this;
    },

    // Load candidates
    loadCandidates: function() {
      var thisView = this;
      var dataSource = this.options.dataPath + 'minnesota_registered_candidates.json';

      // If the data path is not relative, then use JSONP
      if (dataSource.indexOf('http') === 0) {
        dataSource = this.options.proxyPrefix + encodeURI(dataSource);
      }

      $.getJSON(dataSource, function(candData) {
        thisView.candidates = candData;
      });

      return this;
    },

    // Get Candidates
    getCandidates: function(office) {
      var found = [];

      if (!_.isEmpty(this.candidates)) {
        found = _.filter(this.candidates, function(cand) {
          return (cand.office == office) ? true : false;
        });
      }
      return found;
    },

    // Handles drawing layer switcher content.  Note that Wax does not really
    // support multiple interactions on the map, so we have to rebuild it
    // each time (mostly it was IE7 that did not like this)
    drawLayerSwitcher: function() {
      var thisView = this;
      var s;

      // For each data layer, add link
      var template = _.template($("#template-layer-switcher").html(), {
        layers: this.mapOverlays,
        defaultLayer: this.options.mapDefaultLayer
      });

      $('.layer-switcher-container').append(template);

      // Click events
      $('.layer-switcher-container li a').click(function(e) {
        e.preventDefault();
        var thisLayer = $(this).attr('data-id');
        var l;

        if (thisLayer == thisView.currentLayer) {
          return;
        }
        thisView.currentLayer = thisLayer;

        // Hide popup
        $('.map-popup-container').fadeOut('fast');

        // Handle list classes
        $('.layer-switcher-container li a').removeClass('active');
        $(this).addClass('active');

        // Go through layers and hide others and remove interactions
        for (l in thisView.mapOverlays) {
          if (l != thisLayer) {
            thisView.map.removeLayer(thisView.mapOverlays[l]);
          }
        }

        // Show the one we want;
        thisView.map.addLayer(thisView.mapOverlays[thisLayer]);

        // If last found is address, re-render address, otherwise
        // remove marker
        if (thisView.lastFound !== undefined && thisView.lastFound == 'address') {
          thisView.renderAddressFound();
        }
        else {
          thisView.clearMarker();
        }
      });

      return this;
    },

    // Create interaction object
    createInteraction: function(layer, name) {
      var thisView = this;

      layer
        .on('mousemove', function(e) {
          // Remove leading zero
          if (e.data.DISTRICT.indexOf('0') === 0) {
            e.data.DISTRICT = e.data.DISTRICT.slice(1);
          }

          var prefx = thisView.options.translateLayerToDistrict[name];
          var $popup = $('.map-popup-container');
          var template = _.template($("#template-popup-contents").html(), {
            tileData: e.data,
            cands: thisView.getCandidates(prefx + e.data.DISTRICT),
            title: prefx + e.data.DISTRICT
          });

          $popup.html(template);
          $popup.fadeIn('fast');
        })
        .on('mouseout', function(e) {
          thisView.map._container.style.cursor = 'default';
        });
    },

    // Handles drawing side view
    drawSide: function() {
      var data = (this.isIE7()) ? { 'isIE7': true } : { 'isIE7': false };
      var template = _.template($("#template-side-column").html(), data);
      $(this.options.applicationSelector).append(template);

      // Move map over, and append
      $('#map').css({ width: '60%' });
      $('.side-column').css({ width: '40%', float: 'left' });
      this.map.invalidateSize();

      return this;
    },

    // Handles drawing map
    drawMap: function() {
      var thisView = this;
      this.clickCount = 0;

      this.map = new L.Map(this.options.mapID, this.options.mapOptions);
      this.addMapLayers();
      this.map.setView(this.options.mapDefaultCenter, this.options.mapDefaultZoom);
      //this.map.addControl(new L.Control.Fullscreen());

      // Move attributioin to footnotes
      this.map.attributionControl.setPrefix('');
      $('.footnote').eq(0).html($('.footnote').html() + ' ' + this.map.attributionControl._container.innerHTML);
      this.map.removeControl(this.map.attributionControl);

      // Add a marker on click.  Hack around double click
      if (!this.isIE7()) {
        this.map.on('click', function(e) {
          thisView.clickCount += 1;
          if (thisView.clickCount <= 1) {
            _.delay(function() {
              if (thisView.clickCount <= 1) {
                thisView.lastFound = 'click';
                thisView.clearMarker();
                thisView.marker.setLatLng(e.latlng);
                thisView.map.addLayer(thisView.marker);
              }
              thisView.clickCount = 0;
            }, 500);
          }
        });
      }

      return this;
    },

    // Map layers
    addMapLayers: function() {
      var thisView = this;
      var baselayers = {};
      var overlays = {};

      // Mapbox base layer
      this.mapLayers.mapboxBase = L.mapbox.tileLayer('minnpost.map-wi88b700', {
        attribution: 'Some map imagery from Mapbox'
      });
      this.map.addLayer(this.mapLayers.mapboxBase);

      this.mapOverlays['Minnesota State House Districts'] = L.mapbox.tileLayer('minnpost.mn-2012-state-leg-leaning');
      this.mapOverlays['Minnesota State Senate Districts'] = L.mapbox.tileLayer('minnpost.mn-2012-state-sen-leaning');

      // Activate the default interactions
      thisView.createInteraction(this.mapOverlays['Minnesota State House Districts'], 'Minnesota State House Districts');
      thisView.createInteraction(this.mapOverlays['Minnesota State Senate Districts'], 'Minnesota State Senate Districts');

      this.map.addLayer(this.mapOverlays['Minnesota State House Districts']);
      this.currentLayer = this.mapOverlays['Minnesota State House Districts'];

      return this;
    }
  });
})(window, jQuery);


text:
package org.wso2.siddhi.core.query.output.ratelimit.snapshot;

import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.stream.StreamEventPool;
import org.wso2.siddhi.core.util.Scheduler;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PerSnapshotOutputRateLimiter extends SnapshotOutputRateLimiter {
    private String id;
    private final Long value;
    private ScheduledExecutorService scheduledExecutorService;
    private ComplexEventChunk<ComplexEvent> eventChunk = new ComplexEventChunk<ComplexEvent>();
    private boolean endOfChunk = false;
    private Scheduler scheduler;
    private long scheduledTime;
    private Lock lock;

    public PerSnapshotOutputRateLimiter(String id, Long value, ScheduledExecutorService scheduledExecutorService, WrappedSnapshotOutputRateLimiter wrappedSnapshotOutputRateLimiter) {
        super(wrappedSnapshotOutputRateLimiter);
        this.id = id;
        this.value = value;
        this.scheduledExecutorService = scheduledExecutorService;
        lock = new ReentrantLock();
    }

    @Override
    public void process(ComplexEventChunk complexEventChunk) {
        ComplexEvent firstEvent = complexEventChunk.getFirst();
        try {
            lock.lock();
            if(firstEvent != null && firstEvent.getType() == ComplexEvent.Type.TIMER) {
                if (firstEvent.getTimestamp() >= scheduledTime) {
                    sendEvents();
                    scheduledTime = scheduledTime + value;
                    scheduler.notifyAt(scheduledTime);
                }
            } else {
                endOfChunk = true;
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void add(ComplexEvent complexEvent) {
        try {
            lock.lock();
            if (endOfChunk) {
                eventChunk.clear();
                endOfChunk = false;
            }
            if (complexEvent.getType() == ComplexEvent.Type.CURRENT) {
                eventChunk.add(complexEvent);
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public SnapshotOutputRateLimiter clone(String key, WrappedSnapshotOutputRateLimiter wrappedSnapshotOutputRateLimiter) {
        return new PerSnapshotOutputRateLimiter(id + key, value, scheduledExecutorService, wrappedSnapshotOutputRateLimiter);
    }

    @Override
    public void start() {
        scheduler = new Scheduler(scheduledExecutorService, this);
        scheduler.setStreamEventPool(new StreamEventPool(0,0,0, 5));
        long currentTime = System.currentTimeMillis();
        scheduler.notifyAt(currentTime);
        scheduledTime = currentTime;
    }

    @Override
    public void stop() {
        //Nothing to stop
    }

    @Override
    public Object[] currentState() {
        return new Object[]{eventChunk, endOfChunk};
    }

    @Override
    public void restoreState(Object[] state) {
        eventChunk = (ComplexEventChunk<ComplexEvent>) state[0];
        endOfChunk = (Boolean) state[1];
    }

    public synchronized void sendEvents() {
        eventChunk.reset();
        sendToCallBacks(eventChunk);
    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef FMUCOMM_H_
#define	FMUCOMM_H_

// *****************************************************************************
// ************************** System Include Files *****************************
// *****************************************************************************

#include <xc.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

// *****************************************************************************
// ************************** User Include Files *******************************
// *****************************************************************************

#include "sbus.h"

// *****************************************************************************
// ************************** Defines ******************************************
// *****************************************************************************

// Received (Host -> FMU) messages.
typedef enum
{
    FMUCOMM_TYPE_HOST_HEARTBEAT,
    FMUCOMM_TYPE_CTRL_SURFACE_CMD,
    FMUCOMM_TYPE_GPS_CMD,
    FMUCOMM_TYPE_HOST_EXCEPTION,

    FMUCOMM_RX_TYPE_MAX,

} FMUCOMM_RX_TYPE_E;

// Transmitted (FMU -> Host) messages.
typedef enum
{
    FMUCOMM_TYPE_FMU_HEARTBEAT,
    FMUCOMM_TYPE_IMU_DATA,
    FMUCOMM_TYPE_GPS_DATA,
    FMUCOMM_TYPE_CTRL_SURFACE_DATA,
    FMUCOMM_TYPE_RC_DATA,
    FMUCOMM_TYPE_FMU_EXCEPTION,

    FMUCOMM_TX_TYPE_MAX,

} FMUCOMM_TX_TYPE_E;

// Communication protocol wrapper content.  Messages are wrapped with a
// header (header0, header1, header2, type, and length) and footer (CRC) field.
typedef struct
{
    uint8_t   header0;
    uint8_t   header1;
    uint8_t   header2;
    uint8_t   type;

    union
    {
        struct
        {
            uint8_t lengthLsb;
            uint8_t lengthMsb;
        };

        uint16_t length;
    };

    union
    {
        struct
        {
            uint8_t crcLsb;
            uint8_t crcMsb;
        };

        uint16_t crc;
    };

} FMUCOMM_PKT_WRAP;

// Definition of received packet.
typedef struct
{
    // Flag identifying if the received packet is valid.
    //  true  = packet is valid
    //  false = packet is invalid; no received for the execution cycle
    bool valid;

    FMUCOMM_PKT_WRAP wrap;

    uint8_t* pl_p;

} FMUCOMM_RX_PKT;

//
// Received (HOST -> FMU) Message Payload Definition ---------------------------
//

typedef struct __attribute__ ((packed))
{
    union
    {
        struct __attribute__ ((packed))
        {
            uint8_t	 fwVersionRev;  // Firmware revision version ID.
            uint8_t	 fwVersionMin;  // Firmware minor version ID.
            uint8_t	 fwVersionMaj;  // Firmware major version ID.
            uint8_t	 hwVersionRev;  // Hardware revision version ID.
            uint8_t	 hwVersionMin;  // Hardware minor version ID.
            uint8_t	 hwVersionMaj;  // Hardware major version ID.
            uint32_t serialNum;     // Serial number.
            uint32_t msUptime;      // System uptime in milliseconds.
        };

        uint8_t pl_u8[ 14 ];
    };

} FMUCOMM_HOST_HEARTBEAT_PL;

typedef struct __attribute__ ((packed))
{
    uint8_t  surfaceID;
    uint8_t  cmdType;
    uint16_t cmdPwm;
    uint16_t cmdPos;

} FMUCOMM_CTRL_SURFACE_CMD_PL_FIELD;

typedef struct __attribute__ ((packed))
{
    union
    {
        FMUCOMM_CTRL_SURFACE_CMD_PL_FIELD ctrlSurface[ 10 ];

        uint8_t pl_u8[ 60 ];
    };

} FMUCOMM_CTRL_SURFACE_CMD_PL;

typedef struct __attribute__ ((packed))
{
    union
    {
        uint8_t GPSData[ 1024 ];

        uint8_t pl_u8[ 1024 ];
    };

} FMUCOMM_HOST_GPS_CMD_PL;

typedef struct __attribute__ ((packed))
{
    union
    {
        uint8_t debugData[ 1024 ];

        uint8_t pl_u8[ 1024 ];
    };

} FMUCOMM_HOST_EXCEPTION_PL;

//
// Transmitted (FMU -> HOST) Message Payload Definition ------------------------
//

typedef struct __attribute__ ((packed))
{
    uint8_t	 fwVersionRev;  // Firmware revision version ID.
    uint8_t	 fwVersionMin;  // Firmware minor version ID.
    uint8_t	 fwVersionMaj;  // Firmware major version ID.
    uint8_t	 hwVersionRev;  // Hardware revision version ID.
    uint8_t	 hwVersionMin;  // Hardware minor version ID.
    uint8_t	 hwVersionMaj;  // Hardware major version ID.
    uint32_t serialNum;     // Serial number.
    uint32_t msUptime;      // System uptime in milliseconds.
    uint16_t inputVoltage;  // Input voltage in millivolts.
    int16_t  boardTemp;     // Board temperature in 1e2 degrees Celsius.
} FMUCOMM_FMU_HEARTBEAT_PL;

typedef struct __attribute__ ((packed))
{
    uint64_t fmuTime;       // FMU timestamp in microseconds.
    uint16_t imuType;       // IMU type: 0 = VN-100, 1 = MPU-9150

    struct __attribute__ ((packed))
    {
        uint16_t mag    :  1;   // bits       0
        uint16_t accel  :  1;   // bits       1
        uint16_t gyro   :  1;   // bits       2
        uint16_t temp   :  1;   // bits       3
        uint16_t press  :  1;   // bits       4
        uint16_t att    :  1;   // bits       5
        uint16_t        : 10;   // bits  6 - 15 (reserved)

    } imuValid;             // Set as 1 if data is valid, 0 otherwise.

    uint32_t imuTimeSyncIn; // Elapsed time between last IMU sync pulse trigger
                            // and sampling of IMU measurements.
    float    magX;          // Uncompensated magnetic X-axis in Gauss.
    float    magY;          // Uncompensated magnetic Y-axis in Gauss.
    float    magZ;          // Uncompensated magnetic Z-axis in Gauss.
    float    accelX;        // Uncompensated acceleration X-axis in m/s/s.
    float    accelY;        // Uncompensated acceleration Y-axis in m/s/s.
    float    accelZ;        // Uncompensated acceleration Z-axis in m/s/s.
    float    gyroX;         // Uncompensated angular rate X-axis in rad/s.
    float    gyroY;         // Uncompensated angular rate Y-axis in rad/s.
    float    gyroZ;         // Uncompensated angular rate Z-axis in rad/s.
    float    temp;          // IMU temperature in degrees Celsius.
    float    pressure;      // Barometric pressure in kPa.

    uint32_t attTimeSyncIn; // Elapsed time between last IMU sync pulse trigger
                            // and sampling of attitude measurements.
    float    yaw;           // Estimated yaw attitude in degrees.
    float    pitch;         // Estimated pitch attitude in degrees.
    float    roll;          // Estimated roll attitude in degrees.
} FMUCOMM_IMU_DATA_PL;

typedef struct __attribute__ ((packed))
{
    uint64_t fmuTime;       // FMU timestamp in nanosecones.
    uint16_t gpsType;       // GPS type: 0 = Novatel OEMStar, 1 = U-blox
    uint8_t  gpsData[1500]; // GPS receiver data.
} FMUCOMM_GPS_DATA_PL;

typedef struct __attribute__ ((packed))
{
    uint8_t  surfaceID;     // Control surface ID.
    uint16_t cmdTypeEcho;   // Echo of the command type used.
    uint16_t actPwm;        // Actual surface position.
    uint16_t inputVoltage;  // Input voltage in millivolts.
    uint16_t inputCurrent;  // Input current in milliamps.
    int16_t  vsense1Cor;    // The calibration corrected value of V_SENSE1.
    int16_t  vsense2Cor;    // The calibration corrected value of V_SENSE2.
} FMUCOMM_CTRL_SURFACE_DATA_PL_FIELD;

typedef struct __attribute__ ((packed))
{
    FMUCOMM_CTRL_SURFACE_DATA_PL_FIELD ctrlSurface[ 10 ];

} FMUCOMM_CTRL_SURFACE_DATA_PL;

typedef struct __attribute__ ((packed))
{
    uint16_t chVal[ SBUS_CH_MAX ];

} FMUCOMM_CH_DATA_PL;

typedef struct __attribute__ ((packed))
{
    uint8_t debugData[1024];
} FMUCOMM_FMU_EXCEPTION_PL;

// *****************************************************************************
// ************************** Declarations *************************************
// *****************************************************************************

// *****************************************************************************
// ************************** Function Prototypes ******************************
// *****************************************************************************

// Service the FMUComm module.  Communication channels are setup, and received
// Ethernet data is processed.
void FMUCommTask();

// Queue Ethernet data for transmission.
bool FMUCommSet( FMUCOMM_TX_TYPE_E pktType, uint8_t* pl_p, uint16_t plLen );

// Get received Ethernet data.
const FMUCOMM_RX_PKT* FMUCommGet( FMUCOMM_RX_TYPE_E pktType );

#endif	// FMUCOMM_H_


text:
var constants = {};

constants.GITHUB_URL = 'https://github.com/'

constants.GITHUB_ISSUE_URL = '/issues/new'

constants.CALENDAR_EVENTS_API_URL_ =
    "https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events"

constants.CALENDAR_LIST_API_URL_ =
    'https://www.googleapis.com/calendar/v3/users/me/calendarList'

constants.PARSE_PER_CHARACTERS = 5


text:
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

$DIR/preversion.sh
$DIR/../frigging-bootstrap/scripts/preversion.sh


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
	"http://java.sun.com/dtd/application_1_3.dtd">
<application>
    <display-name></display-name>
    <module>
        <connector></connector>
    </module>
</application>


text:
package org.jsecurity.crypto.hash;

import org.jsecurity.codec.Base64;
import org.jsecurity.codec.Hex;

/**
 * Generates an SHA-256 Hash from a given input <tt>source</tt> with an optional <tt>salt</tt> and hash iterations.
 *
 *
See the {@link AbstractHash AbstractHash} parent class JavaDoc for a detailed explanation of Hashing
 * techniques and how the overloaded constructors function.
 *
 *
JDK Version Note - Attempting to instantiate this class on JREs prior to version 1.4.0 will throw
 * an {@link IllegalStateException IllegalStateException}
 *
 * @author Les Hazlewood
 * @since 0.9
 */
public class Sha256Hash extends AbstractHash {

    public static final String ALGORITHM_NAME = "SHA-256";

    public Sha256Hash() {
    }

    public Sha256Hash(Object source) {
        super(source);
    }

    public Sha256Hash(Object source, Object salt) {
        super(source, salt);
    }

    public Sha256Hash(Object source, Object salt, int hashIterations) {
        super(source, salt, hashIterations);
    }

    protected String getAlgorithmName() {
        return ALGORITHM_NAME;
    }

    public static Sha256Hash fromHexString(String hex) {
        Sha256Hash hash = new Sha256Hash();
        hash.setBytes(Hex.decode(hex));
        return hash;
    }

    public static Sha256Hash fromBase64String(String base64) {
        Sha256Hash hash = new Sha256Hash();
        hash.setBytes(Base64.decode(base64));
        return hash;
    }

}


text:
export { build } from './core/builder'

// export all interface
export { IToolbox, IRunContext, IParameters } from './core/toolbox'
export { ICommandLine } from './core/command'

// export the toolbox
export { fs, IFilesystem } from './toolbox/fs-tools'
export { strings, IStrings } from './toolbox/string-tools'
export { logger, ILOGGER } from './toolbox/logger-tools'
export { system, ISystem } from './toolbox/system-tools'
export { semver, ISemver } from './toolbox/semver-tools'
export { http, IHttp } from './toolbox/http-tools'
export { patching, IPatching, IPatchingPatchOptions } from './toolbox/patching-tools'
export { inquirer, IInquirer } from './toolbox/inquirer-tools'
export { open } from './toolbox/open-tools'
export { install, InstallerOption } from './toolbox/installer-tools'

// TODO: can't export these tools directly as they require context to run
// need ideas on how to handle this
export { IMeta } from './extensions/meta-extension'

// this adds the node_modules path to the "search path"
// it's hacky, but it works well!
require('app-module-path').addPath(`${__dirname}/../node_modules`)
require('app-module-path').addPath(process.cwd())


text:
def extractSunShowerFields(item):
	"""

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	return False


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecanora crenulatissima Mereschk.

### Remarks
null


text:
"""
* Experimental *

Like the map function, but can use a pool of threads.

Really easy to use threads.  eg.  tmap(f, alist)

If you know how to use the map function, you can use threads.
"""

__author__ = "Rene Dudfield"
__version__ = "0.3.0"
__license__ = 'Python license'

import traceback, sys

from pygame.compat import geterror

if sys.version_info[0] == 3:
    from multiprocessing import JoinableQueue as Queue
    from queue import Empty
elif (sys.version_info[0] == 2 and sys.version_info[1] < 5):
    from Py25Queue import Queue
    from Py25Queue import Empty
else:
    # use up to date version
    from Queue import Queue
    from Queue import Empty

import threading
Thread = threading.Thread

STOP = object()
FINISH = object()

# DONE_ONE = object()
# DONE_TWO = object()

# a default worker queue.
_wq = None

# if we are using threads or not.  This is the number of workers.
_use_workers = 0

# Set this to the maximum for the amount of Cores/CPUs
#    Note, that the tests early out.
#    So it should only test the best number of workers +2
MAX_WORKERS_TO_TEST = 64

def init(number_of_workers = 0):
    """ Does a little test to see if threading is worth it.
          Sets up a global worker queue if it's worth it.

        Calling init() is not required, but is generally better to do.
    """
    global _wq, _use_workers

    if number_of_workers:
        _use_workers = number_of_workers
    else:
        _use_workers = benchmark_workers()

    # if it is best to use zero workers, then use that.
    _wq = WorkerQueue(_use_workers)

def quit():
    """ cleans up everything.
    """
    global _wq, _use_workers
    _wq.stop()
    _wq = None
    _use_workers = False

def benchmark_workers(a_bench_func = None, the_data = None):
    """ does a little test to see if workers are at all faster.
        Returns the number of workers which works best.
        Takes a little bit of time to run, so you should only really call
          it once.
        You can pass in benchmark data, and functions if you want.
        a_bench_func - f(data)
        the_data - data to work on.
    """
    global _use_workers

    #TODO: try and make this scale better with slower/faster cpus.
    #  first find some variables so that using 0 workers takes about 1.0 seconds.
    #  then go from there.

    # note, this will only work with pygame 1.8rc3+
    # replace the doit() and the_data with something that releases the GIL

    import pygame
    import pygame.transform
    import time

    if not a_bench_func:
        def doit(x):
            return pygame.transform.scale(x, (544, 576))
    else:
        doit = a_bench_func

    if not the_data:
        thedata = []
        for x in range(10):
            thedata.append(pygame.Surface((155,155), 0, 32))
    else:
        thedata = the_data

    best = time.time() + 100000000
    best_number = 0
    last_best = -1

    for num_workers in range(0, MAX_WORKERS_TO_TEST):

        wq = WorkerQueue(num_workers)
        t1 = time.time()
        for xx in range(20):
            print ("active count:%s" % threading.activeCount())
            results = tmap(doit, thedata, worker_queue = wq)
        t2 = time.time()

        wq.stop()

        total_time = t2 - t1
        print ("total time num_workers:%s: time:%s:" % (num_workers, total_time))

        if total_time < best:
            last_best = best_number
            best_number =num_workers
            best = total_time

        if num_workers - best_number > 1:
            # We tried to add more, but it didn't like it.
            #   so we stop with testing at this number.
            break

    return best_number

class WorkerQueue(object):

    def __init__(self, num_workers = 20):
        self.queue = Queue()
        self.pool = []
        self._setup_workers(num_workers)

    def _setup_workers(self, num_workers):
        """ Sets up the worker threads
              NOTE: undefined behaviour if you call this again.
        """
        self.pool = []

        for _ in range(num_workers):
            self.pool.append(Thread(target=self.threadloop))

        for a_thread in self.pool:
            a_thread.setDaemon(True)
            a_thread.start()

    def do(self, f, *args, **kwArgs):
        """ puts a function on a queue for running later.
        """
        self.queue.put((f, args, kwArgs))

    def stop(self):
        """ Stops the WorkerQueue, waits for all of the threads to finish up.
        """
        self.queue.put(STOP)
        for thread in self.pool:
            thread.join()

    def threadloop(self): #, finish = False):
        """ Loops until all of the tasks are finished.
        """
        while True:
            args = self.queue.get()
            if args is STOP:
                self.queue.put(STOP)
                self.queue.task_done()
                break
            else:
                try:
                    args[0](*args[1], **args[2])
                finally:
                    # clean up the queue, raise the exception.
                    self.queue.task_done()
                    #raise

    def wait(self):
        """ waits until all tasks are complete.
        """
        self.queue.join()

class FuncResult:
    """ Used for wrapping up a function call so that the results are stored
         inside the instances result attribute.
    """
    def __init__(self, f, callback = None, errback = None):
        """ f - is the function we that we call
            callback(result) - this is called when the function(f) returns
            errback(exception) - this is called when the function(f) raises
                                   an exception.
        """
        self.f = f
        self.exception = None
        self.callback = callback
        self.errback = errback

    def __call__(self, *args, **kwargs):

        #we try to call the function here.  If it fails we store the exception.
        try:
            self.result = self.f(*args, **kwargs)
            if self.callback:
                self.callback(self.result)
        except Exception:
            self.exception = geterror()
            if self.errback:
                self.errback(self.exception)

def tmap(f, seq_args, num_workers = 20, worker_queue = None, wait = True, stop_on_error = True):
    """ like map, but uses a thread pool to execute.
        num_workers - the number of worker threads that will be used.  If pool
                        is passed in, then the num_workers arg is ignored.
        worker_queue - you can optionally pass in an existing WorkerQueue.
        wait - True means that the results are returned when everything is finished.
               False means that we return the [worker_queue, results] right away instead.
               results, is returned as a list of FuncResult instances.
        stop_on_error -
    """

    if worker_queue:
        wq = worker_queue
    else:
        # see if we have a global queue to work with.
        if _wq:
            wq = _wq
        else:
            if num_workers == 0:
                return map(f, seq_args)

            wq = WorkerQueue(num_workers)

    # we short cut it here if the number of workers is 0.
    # normal map should be faster in this case.
    if len(wq.pool) == 0:
        return map(f, seq_args)

    #print ("queue size:%s" % wq.queue.qsize())

    #TODO: divide the data (seq_args) into even chunks and
    #       then pass each thread a map(f, equal_part(seq_args))
    #      That way there should be less locking, and overhead.

    results = []
    for sa in seq_args:
        results.append(FuncResult(f))
        wq.do(results[-1], sa)

    #wq.stop()

    if wait:
        #print ("wait")
        wq.wait()
        #print ("after wait")
        #print ("queue size:%s" % wq.queue.qsize())
        if wq.queue.qsize():
            raise Exception("buggy threadmap")
        # if we created a worker queue, we need to stop it.
        if not worker_queue and not _wq:
            #print ("stoping")
            wq.stop()
            if wq.queue.qsize():
                um = wq.queue.get()
                if not um is STOP:
                    raise Exception("buggy threadmap")

        # see if there were any errors.  If so raise the first one.  This matches map behaviour.
        # TODO: the traceback doesn't show up nicely.
        # NOTE: TODO: we might want to return the results anyway?  This should be an option.
        if stop_on_error:
            error_ones = filter(lambda x:x.exception, results)
            if error_ones:
                raise error_ones[0].exception

        return map(lambda x:x.result, results)
    else:
        return [wq, results]


text:
<?xml version="1.0" encoding="UTF-8"?>
<module codename="org.netbeans.modules.keyring">
    <module_version install_time="1358413891520" last="true" origin="installer" specification_version="1.11.1">
        <file crc="3581559990" name="config/Modules/org-netbeans-modules-keyring.xml"/>
        <file crc="2109115772" name="modules/org-netbeans-modules-keyring.jar"/>
    </module_version>
</module>


text:
angular.module('licenseService', [])
	// each function returns a promise object
	.factory('Licenses', ['$http','$rootScope',function($http,$rootScope) {
		return {
			view : function() {
				console.log('view Licenses called');
				return $http.get('/api/viewLicense/'+$rootScope.loggedUser);
			},

			viewIssuedLicense : function() {
				console.log('viewIssuedLicense called');
				return $http.get('/api/viewIssuedLicense/');
			},

			getSoftwareList : function() {
				console.log('view Licenses called');
				return $http.get('/api/getSoftwareList/');
			},

			issueLicense : function(userData){
				console.log('issue license called');
				return  $http({ // Accessing the Angular $http Service to send data via REST Communication to Node Server.
					method: 'POST',
					url: '/api/issueLicense',
					data:  userData ,
					headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				})
			},

			addLicenseToMaster : function(userData){
				console.log('addLicenseToMaster called');
				return  $http({ // Accessing the Angular $http Service to send data via REST Communication to Node Server.
					method: 'POST',
					url: '/api/addLicenseToMaster',
					data:  userData ,
					headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				})
			},

			requestLicense : function(userData){
				console.log('request license called');
				console.log('DATA: '+userData);
				return  $http({ // Accessing the Angular $http Service to send data via REST Communication to Node Server.
					method: 'POST',
					url: '/api/requestLicense',
					data:  userData ,
					headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				})
			},

			viewRequestList : function() {
				console.log('view RequestList called');
				return $http.get('/api/viewMyRequests/' + $rootScope.loggedUser);
			},

			viewpendingRequestList : function() {
				console.log('view Penidng RequestList called');
				return $http.get('/api/viewMyPendingRequests/' + $rootScope.loggedUser);
			},
			transfer : function(userData){
				console.log('Transferring Asset');
				//return $http.post('/api/signup', userData);
				return  $http({ // Accessing the Angular $http Service to send data via REST Communication to Node Server.
					method: 'POST',
					url: '/api/transfer',
					data:  userData ,
					headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				})

			},
			rejectLicenseRequest : function(requestId){
				console.log('rejectLicenseRequest angular '+ requestId);
				$http.post('/api/transfer/reject/'+requestId);
			}
		}
	}]);


text:
<?php
namespace Concrete\Core\File\Event;

use Concrete\Core\File\Set\Set;

class FileSet
{
    protected $fs;

    public function __construct(Set $fs)
    {
        $this->fs = $fs;
    }

    public function getFileSetObject()
    {
        return $this->fs;
    }
}


text:
<?php

namespace Bureaupieper\StoreeClient\Client\Result;

/**
 * Class ContentResult
 * @package Bureaupieper\StoreeClient\Client\Result
 */
class ProfileResult extends AbstractResult
{
}


text:
package org.apache.axis2;

import org.apache.axis2.i18n.Messages;

/**
 * Little utility to get the version and build date of the axis2.jar.
 *

 * The messages referenced here are automatically kept up-to-date by the
 * build.xml.
 */
public class Version {
    /**
     * Get the version of this AXIS.
     *
     * @return the version of this axis2
     */
    public static String getVersion() {
        return Messages.getMessage("axisVersion") + "\n" +
                Messages.getMessage("builtOn");
    }

    /**
     * Returns the Axis Version number and build date.
     *

     * Example output: 1.1 Jul 08, 2003 (09:00:12 EDT)
     *
     * @return the full version of this axis2
     */
    public static String getVersionText() {
        return Messages.getMessage("axisVersionRaw");
    }

    /**
     * Entry point.
     *

     * Calling this with no arguments returns the version of the client-side
     * axis2.jar.
     */
    public static void main(String[] args) {
        System.out.println(getVersion());
    }
}


text:
package com.microsoft.azure.management.resources.fluentcore.collection;

import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.apigeneration.LangDefinition.MethodConversion;

/**
 * Provides access to listing Azure resources of a specific type based on their tag.
 * <p>
 * (Note: this interface is not intended to be implemented by user code)
 *
 * @param <T> the fluent type of the resource
 */
@LangDefinition(ContainerName = "CollectionActions", MethodConversionType = MethodConversion.OnlyMethod)
public interface SupportsListingByTag<T> {
    /**
     * Lists all the resources with the specified tag.
     *
     * @param tagName tag's name as the key
     * @param tagValue tag's value
     * @return list of resources
     */
    PagedList<T> listByTag(String tagName, String tagValue);
}


text:
namespace Gearset.Components.Profiler
{
    /// <summary>
    /// A facade for Profiler settings.
    /// </summary>
    /// <remarks>
    /// Ideally utilised by the Inspector to hide lots of property noise - I still wanted to be able to throw a Profiler into the
    /// inspector though so didn't want to tag the properties with [InspectorIgnore]
    /// </remarks>
    public class ProfilerInpectorSettings
    {
        readonly ProfilerManager _profiler;

        public ProfilerInpectorSettings(ProfilerManager profiler)
        {
            _profiler = profiler;
        }

        public bool Sleep
        {
            get { return _profiler.Sleep; }
            set { _profiler.Sleep = value; }
        }

        public bool SkipUpdate
        {
            get { return _profiler.SkipUpdate; }
            set { _profiler.SkipUpdate = value; }
        }

        public uint MaxFrameCount
        {
            get { return PerformanceGraph.MaxFrames; }
        }

        public uint DisplayedFrameCount
        {
            get { return _profiler.PerformanceGraph.DisplayedFrameCount; }
            set { _profiler.PerformanceGraph.DisplayedFrameCount = value; }
        }

        public uint SkipFrames
        {
            get { return _profiler.PerformanceGraph.SkipFrames; }
            set { _profiler.PerformanceGraph.SkipFrames = value; }
        }

        public void ResetProfileWindows()
        {
            _profiler.TimeRuler.TopLeft = _profiler.Config.TimeRulerConfig.DefaultPosition;
            _profiler.TimeRuler.Size = _profiler.Config.TimeRulerConfig.DefaultSize;
            _profiler.PerformanceGraph.TopLeft = _profiler.Config.PerformanceGraphConfig.DefaultPosition;
            _profiler.PerformanceGraph.Size = _profiler.Config.PerformanceGraphConfig.DefaultSize;
            _profiler.ProfilerSummary.TopLeft = _profiler.Config.ProfilerSummaryConfig.DefaultPosition;
            _profiler.ProfilerSummary.Size = _profiler.Config.ProfilerSummaryConfig.DefaultSize;
        }
    }
}


text:
var profile_win = Ti.UI.currentWindow;
var Cloud = require('ti.cloud');
Cloud.debug = true;

// Create a Label.
var userLabel = Ti.UI.createLabel({
	text: 'User',
	color: '#fff',
	font: {fontSize:20},
	height: 'auto',
	width: 'auto',
	top: 45,
	left: 10,
	textAlign: 'center'
});

// Add to the parent view.
profile_win.add(userLabel);

// Create a Label.
var passLabel = Ti.UI.createLabel({
	text: 'Pass',
	color: '#fff',
	font: {fontSize:20},
	height: 'auto',
	width: 'auto',
	top: 125,
	left: 10,
	textAlign: 'center'
});

// Add to the parent view.
profile_win.add(passLabel);
// ----------------
// profile form
// ----------------

// Create a TextField.
var userNameField = Ti.UI.createTextField({
    height : 35,
    top : 40,
    left : 80,
    width : 200,
    hintText : '',
    keyboardType : Ti.UI.KEYBOARD_DEFAULT,
    returnKeyType : Ti.UI.RETURNKEY_DEFAULT,
    borderStyle : Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});

// Listen for return events.
userNameField.addEventListener('return', function(e) {
    userNameField.blur();
    //alert('Input was: ' + userNameField.value);
});

// Add to the parent view.
profile_win.add(userNameField);

// Create a TextField.
var passwordField = Ti.UI.createTextField({
    height: 35,
    top: 120,
    left: 80,
    width: 200,
    hintText: '',
    passwordMask: true,
    keyboardType: Ti.UI.KEYBOARD_DEFAULT,
    returnKeyType: Ti.UI.RETURNKEY_DEFAULT,
    borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});

// Listen for return events.
passwordField.addEventListener('return', function(e) {
    passwordField.blur();
    //alert('Input was: ' + passwordField.value);
});

// Add to the parent view.
profile_win.add(passwordField);

 // Create a Button.
var loginButton = Ti.UI.createButton({
    title: 'Login',
    top: 190,
    left: 110,
    width: 150
});

// Listen for click events.
loginButton.addEventListener('click', function() {
    //alert('\'loginButton\' was clicked!');
});

// Add to the parent view.
profile_win.add(loginButton);

var registerButton = Ti.UI.createButton({
	top: 250,
  left: 110,
  width: 150,
  title:'Register'
});

profile_win.add(registerButton);

registerButton.addEventListener('click', function() {
	//containingTab attribute must be set by parent tab group on
	//the window for this work
	profile_win.containingTab.open(Ti.UI.createWindow({
		title: 'Register',
		backgroundColor: 'white',
		url: 'register.js'
	}));
});

 // Listen for click events.
loginButton.addEventListener('click', function() {
	//burr
	Cloud.Users.login ({
		login: userNameField.value,
		password: passwordField.value
	}, function (e) {
		if (e.success) {
			var user = e.users[0];
      alert('Welcome back:\n' +
            	user.username);
		} else {
			alert('Error:\n' +
            ((e.error && e.message) || JSON.stringify(e)));
		}
	});
});


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit4193d4fd3ac2434e484b3dc4e32f7545::getLoader();


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>

  <link href="../../dist/modular/css/core.css" rel="stylesheet" type="text/css">
  <link href="../../dist/modular/css/grid.css" rel="stylesheet" type="text/css">
  <link href="../../dist/modular/css/dropdown.css" rel="stylesheet" type="text/css">


text:
package test.wsdd;

import junit.framework.TestCase;
import org.apache.axis.Handler;
import org.apache.axis.configuration.XMLStringProvider;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.server.AxisServer;

public class TestOptions extends TestCase
{
    static final String HANDLER_NAME = "logger";
    static final String PARAM_NAME = "testParam";
    static final String PARAM_VAL  = "testValue";

    // Two-part WSDD, with a space for scope option in the middle
    static final String doc =
            "<deployment xmlns=\"http://xml.apache.org/axis/wsdd/\" " +
                  "xmlns:java=\"" + WSDDConstants.URI_WSDD_JAVA + "\">\n" +
            " <handler type=\"java:org.apache.axis.handlers.LogHandler\" " +
                      "name=\"" + HANDLER_NAME + "\">\n" +
            "  <parameter name=\"" + PARAM_NAME +
                          "\" value=\"" + PARAM_VAL + "\"/>\n" +
            " </handler>\n" +
            " <handler type=\"logger\" name=\"other\"/>\n" +
            "</deployment>";

    /**
     * Initialize an engine with a single handler with a parameter set, and
     * another reference to that same handler with a different name.
     *
     * Make sure the param is set for both the original and the reference
     * handler.
     *
     */
    public void testOptions() throws Exception
    {
        XMLStringProvider provider = new XMLStringProvider(doc);
        AxisServer server = new AxisServer(provider);

        Handler h1 = server.getHandler(HANDLER_NAME);
        assertNotNull("Couldn't get logger handler from engine!", h1);

        Object optVal = h1.getOption(PARAM_NAME);
        assertNotNull("Option value was null!", optVal);
        assertEquals("Option was not expected value", optVal, PARAM_VAL);

        optVal = server.getOption("someOptionWhichIsntSet");
        assertNull("Got value for bad option!", optVal);

        Handler h2 = server.getHandler("other");
        assertNotNull("Couldn't get second handler", h2);

        optVal = h1.getOption(PARAM_NAME);
        assertNotNull("Option value was null for 2nd handler!", optVal);
        assertEquals("Option was not expected value for 2nd handler",
                     optVal, PARAM_VAL);

        optVal = server.getOption("someOptionWhichIsntSet");
        assertNull("Got value for bad option on 2nd handler!", optVal);
    }
}


text:
package org.javalite.activeweb;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.javalite.common.Convert;
import org.javalite.json.JSONHelper;
import org.javalite.common.Util;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.javalite.common.Collections.map;

/**
 * @author Igor Polevoy
 */
public class HttpSupport implements RequestAccess {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private static Pattern hashPattern = Pattern.compile("\\[.*\\]");

    protected void logInfo(String info){
        logger.info(info);
    }

    protected void logDebug(String info){
        logger.debug(info);
    }

    protected void logWarning(String info){
        logger.warn(info);
    }

    protected void logWarning(String info, Throwable e){
        logger.warn(info, e);
    }

    protected void logError(String info){
        logger.error(info);
    }

    protected void logError(Throwable e){
        logger.error("", e);
    }

    protected void logError(String info, Throwable e){
        logger.error(info, e);
    }

    /**
     * Assigns a value for a view.
     *
     * @param name name of value
     * @param value value.
     */
    protected void assign(String name, Object value) {
        KeyWords.check(name);
        RequestContext.getValues().put(name, value);
    }

    /**
     * Alias to {@link #assign(String, Object)}.
     *
     * @param name name of object to be passed to view
     * @param value object to be passed to view
     */
    protected void view(String name, Object value) {
        assign(name, value);
    }

    /**
     * Returns status code from current response.
     *
     * @return status code  or -1 if controller response was not generated (error)
     */
    protected int status() {
        ControllerResponse response = RequestContext.getControllerResponse();
        return response != null ? response.getStatus() : -1;
    }
    /**
     * Convenience method, calls {@link #assign(String, Object)} internally.
     * The keys in teh map are converted to String values.
     *
     * @param values map with values to pass to view.
     */
    protected void view(Map values){
        for(Object key:values.keySet() ){
            assign(key.toString(), values.get(key));
        }
    }

    /**
     * Convenience method to pass multiple names and corresponding values to a view.
     *
     * @param values - pairs of names and values. such as: name1, value1, name2, value2, etc. Number of arguments must be even.
     */
    protected void view(Object ... values){
        view(map(values));
    }

    /**
     * Flash method to display multiple flash messages.
     * Takes in a map of names and values for a flash.
     * Keys act like names, and values act like... ehr.. values.
     *
     * @see #flash(String, Object)
     *
     * @param values values to flash.
     */
    protected void flash(Map values){
        checkFlasher();
        for(Object key:values.keySet() ){
            flash(key.toString(), values.get(key));
        }
    }

    /**
     * Flash method to display multiple flash messages.
     * Takes in a vararg of values for flash. Number of arguments must be even.
     * Format: name, value, name, value, etc.
     *
     * @see #flash(String, Object)
     * @param values values to flash.
     */
    protected void flash(Object ... values){
        flash(map(values));
    }

    /**
     * Sets a flash name for a flash with  a body.
     * Here is a how to use a tag with a body:
     *
     *

     * <@flash name="warning">
         <div class="warning">${message}</div>
       </@flash>
     *

     *
     * If body refers to variables (as in this example), then such variables need to be passed in to the template as usual using
     * the {@link #view(String, Object)} method.
     *
     * @param name name of a flash
     */
    @SuppressWarnings("unchecked")
    protected void flash(String name){
        flash(name, null);
    }

    /**
     * Sends value to flash. Flash survives one more request.  Using flash is typical
     * for POST/GET pattern,
     *
     * @param name name of value to flash
     * @param value value to live for one more request in current session.
     */
    @SuppressWarnings("unchecked")
    protected void flash(String name, Object value) {
        checkFlasher();
        ((Map) session().get("flasher")).put(name, value);
    }

    private void checkFlasher(){
        if (session().get("flasher") == null) {
            session().put("flasher", new HashMap());
        }
    }

    public class HttpBuilder {
        private ControllerResponse controllerResponse;
        private HttpBuilder(ControllerResponse controllerResponse){
            this.controllerResponse = controllerResponse;
        }

        protected ControllerResponse getControllerResponse() {
            return controllerResponse;
        }

        /**
         * Sets content type of response.
         * These can be "text/html". Value "text/html" is set by default.
         *
         * @param contentType content type value.
         * @return instance of RenderBuilder
         */
        public HttpBuilder contentType(String contentType) {
            controllerResponse.setContentType(contentType);
            return this;
        }

        /**
         * Sets a HTTP header on response.
         *
         * @param name name of header.
         * @param value value of header.
         * @return instance of RenderBuilder
         */
        public HttpBuilder header(String name, String value){
            RequestContext.getHttpResponse().setHeader(name, value);
            return this;
        }

        /**
         * Overrides HTTP status with a different value.
         * For values and more information, look here:
         * HTTP Status Codes.
         *
         * By default, the status is set to 200, OK.
         *
         * @param status HTTP status code.
         */
        public void status(int status){
            controllerResponse.setStatus(status);
        }

        /**
         * Alias to {@link #status(int)}.
         *
         * @param status response code.
         */
        public void statusCode(int status){
            status(status);
        }
    }

    public class RenderBuilder extends HttpBuilder {

        private RenderBuilder(RenderTemplateResponse response){
            super(response);
        }

        /**
         * Use this method to override a default layout configured.
         *
         * @param layout name of another layout.
         * @return instance of RenderBuilder
         */
        public RenderBuilder layout(String layout){
            getRenderTemplateResponse().setLayout(layout);
            return this;
        }

        protected RenderTemplateResponse getRenderTemplateResponse(){
            return (RenderTemplateResponse)getControllerResponse();
        }

        /**
         * Call this method to turn off all layouts. The view will be rendered raw - no layouts.
         * @return instance of RenderBuilder
         */
        public RenderBuilder noLayout(){
            getRenderTemplateResponse().setLayout(null);
            return this;
        }

        /**
         * Sets a format for the current request. This is a intermediate extension for the template file. For instance,
         * if the name of template file is document.xml.ftl, then the "xml" part is set with this method, the
         * "document" is a template name, and "ftl" extension is assumed in case you use FreeMarker template manager.
         *
         * @param format template format
         * @return instance of RenderBuilder
         */
        public RenderBuilder format(String format){
            ControllerResponse response = RequestContext.getControllerResponse();
            if(response instanceof RenderTemplateResponse){
                ((RenderTemplateResponse)response).setFormat(format);
            }
            return this;
        }
    }

    /**
     * Renders results with a template.
     *
     * This call must be the last call in the action.
     *
     * @param template - template name, must be "absolute", starting with slash,
     * such as: "/controller_dir/action_template".
     * @param values map with values to pass to view.
     * @return instance of {@link RenderBuilder}, which is used to provide additional parameters.
     */
    protected RenderBuilder render(String template, Map values) {
        RenderTemplateResponse resp = new RenderTemplateResponse(values, template, RequestContext.getFormat());
        RequestContext.setControllerResponse(resp);
        return new RenderBuilder(resp);
    }

    /**
     * Redirects to a an action of this controller, or an action of a different controller.
     * This method does not expect a full URL.
     *
     * @param path - expected to be a path within the application.
     * @return instance of {@link HttpSupport.HttpBuilder} to accept additional information.
     */
    protected HttpBuilder redirect(String path) {
        RedirectResponse resp = new RedirectResponse(path);
        RequestContext.setControllerResponse(resp);
        return new HttpBuilder(resp);
    }

    /**
     * Redirects to another URL (usually another site).
     *
     * @param url absolute URL: http://domain/path....
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected HttpBuilder redirect(URL url) {
        RedirectResponse resp = new RedirectResponse(url);
        RequestContext.setControllerResponse(resp);
        return new HttpBuilder(resp);
    }

    /**
     * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to
     * the defaultReference.
     *
     * @param defaultReference where to redirect - can be absolute or relative; this will be used in case
     * the request does not provide a "Referrer" header.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected HttpBuilder redirectToReferrer(String defaultReference) {
        String referrer = RequestContext.getHttpRequest().getHeader("Referer");
        referrer = referrer == null? defaultReference: referrer;
        RedirectResponse resp = new RedirectResponse(referrer);
        RequestContext.setControllerResponse(resp);
        return new HttpBuilder(resp);
    }

    /**
     * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to
     * the root of the application.
     *
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected HttpBuilder redirectToReferrer() {
        String referrer = RequestContext.getHttpRequest().getHeader("Referer");
        referrer = referrer == null? RequestContext.getHttpRequest().getContextPath(): referrer;
        RedirectResponse resp = new RedirectResponse(referrer);
        RequestContext.setControllerResponse(resp);
        return new HttpBuilder(resp);
    }

    /**
     * Convenience method for {@link #redirect(Class, java.util.Map)}.
     *
     * @param controllerClass controller class where to send redirect.
     * @param action action to redirect to.
     * @param id id to redirect to.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action, Object id){
        return redirect(controllerClass, map("action", action, "id", id));
    }

    /**
     * Convenience method for {@link #redirect(Class, java.util.Map)}.
     *
     * @param controllerClass controller class where to send redirect.
     * @param id id to redirect to.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Object id){
        return redirect(controllerClass, map("id", id));
    }

    /**
     * Convenience method for {@link #redirect(Class, java.util.Map)}.
     *
     * @param controllerClass controller class where to send redirect.
     * @param action action to redirect to.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action){
        return redirect(controllerClass, map("action", action));
    }

    /**
     * Redirects to the same controller, and action "index". This is equivalent to
     *

     *     redirect(BooksController.class);
     *

     * given that the current controller is BooksController.
     *
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected HttpBuilder redirect() {
        return redirect(getRoute().getController().getClass());
    }

    /**
     * Redirects to given controller, action "index" without any parameters.
     *
     * @param controllerClass controller class where to send redirect.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass){
        return redirect(controllerClass, new HashMap());

    }

    /**
     * Redirects to a controller, generates appropriate redirect path. There are two keyword keys expected in
     * the params map: "action" and "id". Both are optional. This method will generate appropriate URLs for regular as
     * well as RESTful controllers. The "action" and "id" values in the map will be treated as parts of URI such as:
     *

     *
     * /controller/action/id
     *
     *

     * for regular controllers, and:
     *

     *
     * /controller/id/action
     *
     *

     * for RESTful controllers. For RESTful controllers, the action names are limited to those described in
     * {@link org.javalite.activeweb.annotations.RESTful} and allowed on a GET URLs, which are: "edit_form" and "new_form".
     *
     *

     * The map may contain any number of other key/value pairs, which will be converted to a query string for
     * the redirect URI. Example:
     *

     * Method:
     *

     *
     * redirect(app.controllers.PersonController.class,  org.javalite.common.Collections.map("action", "show", "id", 123, "format", "json", "restrict", "true"));
     *
     *

     * will generate the following URI:
     *

     *
     * /person/show/123?format=json&restrict=true
     *
     *

     *
     * This method will also perform URL - encoding of special characters if necessary.
     *
     *
     * @param controllerClass controller class
     * @param params map with request parameters.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Map params){
        String controllerPath = Router.getControllerPath(controllerClass);
        String contextPath = RequestContext.getHttpRequest().getContextPath();
        String action = params.get("action") != null? params.get("action").toString() : null;
        String id = params.get("id") != null? params.get("id").toString() : null;
        boolean restful= AppController.restful(controllerClass);
        params.remove("action");
        params.remove("id");

        String uri = contextPath + Router.generate(controllerPath, action, id, restful, params);

        RedirectResponse resp = new RedirectResponse(uri);
        RequestContext.setControllerResponse(resp);
        return new HttpBuilder(resp);
    }

    /**
     * This method will send the text to a client verbatim. It will not use any layouts. Use it to build app.services
     * and to support AJAX.
     *
     * @param text text of response.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected HttpBuilder respond(String text){
        if(text == null){
            text = "null";
        }
        DirectResponse resp = new DirectResponse(text);
        RequestContext.setControllerResponse(resp);
        return new HttpBuilder(resp);
    }

    /**
     * Convenience method for downloading files. This method will force the browser to find a handler(external program)
     *  for  this file (content type) and will provide a name of file to the browser. This method sets an HTTP header
     * "Content-Disposition" based on a file name.
     *
     * @param file file to download.
     * @param delete true to delete the file after processing
     * @return builder instance.
     */
    protected HttpBuilder sendFile(File file, boolean delete)  {
        try{
            FileResponse resp = new FileResponse(file, delete);
            RequestContext.setControllerResponse(resp);
            HttpBuilder builder = new HttpBuilder(resp);
            builder.header("Content-Disposition", "attachment; filename=" + file.getName());
            return builder;
        }catch(Exception e){
            throw new ControllerException(e);
        }
    }

    /**
     * Convenience method for downloading files. This method will force the browser to find a handler(external program)
     *  for  this file (content type) and will provide a name of file to the browser. This method sets an HTTP header
     * "Content-Disposition" based on a file name.
     *
     * @param file file to download.
     * @return builder instance.
     */
    protected HttpBuilder sendFile(File file) {
       return sendFile(file, false);
    }

    /**
     * Convenience method to get file content from multipart/form-data request. If more than one files with the same
     * name are submitted, only one is returned.
     *
     * @param fieldName name of form field from the  multipart/form-data request corresponding to the uploaded file.
     * @param formItems form items retrieved from multipart/form-data request.
     * @return InputStream from which to read content of uploaded file or null if FileItem with this name is not found.
     */
    protected org.javalite.activeweb.FileItem getFile(String fieldName, List<FormItem> formItems){
        for (FormItem formItem : formItems) {
            if(formItem instanceof org.javalite.activeweb.FileItem && formItem.getFieldName().equals(fieldName)){
                return (org.javalite.activeweb.FileItem)formItem;
            }
        }
        return null;
    }

    /**
     * Direct access to current HttpServletRequest for low level operations.
     *
     * @return instance of current HttpServletRequest.
     */
    protected HttpServletRequest getHttpServletRequest(){
        return RequestContext.getHttpRequest();
    }

    /**
     * Direct access to current HttpServletResponse for low level operations.
     *
     * @return instance of current HttpServletResponse.
     */
    protected HttpServletResponse getHttpServletResponse(){
        return RequestContext.getHttpResponse();
    }

    /**
     * Returns a collection of uploaded files from a multi-part port request.
     * Uses request encoding if one provided, and sets no limit on the size of upload.
     *
     * @return a collection of uploaded files from a multi-part port request.
     */
    protected Iterator<FormItem> uploadedFiles() {
        return uploadedFiles(null, -1);
    }

    /**
     * Returns a collection of uploaded files from a multi-part port request.
     * Sets no limit on the size of upload.
     *
     * @param encoding specifies the character encoding to be used when reading the headers of individual part.
     * When not specified, or null, the request encoding is used. If that is also not specified, or null,
     * the platform default encoding is used.
     *
     * @return a collection of uploaded files from a multi-part port request.
     */
    protected Iterator<FormItem> uploadedFiles(String encoding) {
        return uploadedFiles(encoding, -1);
    }

    /**
     * Returns a collection of uploaded files from a multi-part port request.
     *
     * @param encoding specifies the character encoding to be used when reading the headers of individual part.
     * When not specified, or null, the request encoding is used. If that is also not specified, or null,
     * the platform default encoding is used.
     * @param maxFileSize maximum file size in the upload in bytes. -1 indicates no limit.
     *
     * @return a collection of uploaded files from a multi-part port request.
     */
    protected Iterator<FormItem> uploadedFiles(String encoding, long maxFileSize) {
        List<FormItem> fileItems = new ArrayList<>();
        for(FormItem item : multipartFormItems(encoding, maxFileSize)) {
            if (item.isFile()) {
                fileItems.add(item);
            }
        }
        return fileItems.iterator();
    }

    /**
     * Convenience method, calls {@link #multipartFormItems(String)}. Does not set encoding before reading request.
     * @see #multipartFormItems(String)
     * @return a collection of uploaded files/fields from a multi-part request.
     */
    protected List<FormItem> multipartFormItems() {
        return multipartFormItems(null);
    }

    /**
     * Returns a collection of uploaded files and form fields from a multi-part request.
     * This method uses DiskFileItemFactory.
     * As a result, it is recommended to add the following to your web.xml file:
     *
     *

     *   <listener>
     *      <listener-class>
     *         org.apache.commons.fileupload.servlet.FileCleanerCleanup
     *      </listener-class>
     *   </listener>
     *

     *
     * For more information, see: Using FileUpload
     *
     * The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept larger files, create a file called activeweb.properties,
     * add it to your classpath and place this property to the file:
     *
     *

     * #max upload size
     * maxUploadSize = 20000000
     *

     *
     * Alternatively, just call this method and pass a per-request parameter for the size: {@link #multipartFormItems(String, long)}.
     *
     *
     * @param encoding specifies the character encoding to be used when reading the headers of individual part.
     * When not specified, or null, the request encoding is used. If that is also not specified, or null,
     * the platform default encoding is used.
     *
     * @return a collection of uploaded files from a multi-part request.
     */
    protected List<FormItem> multipartFormItems(String encoding) {
        return multipartFormItems(encoding, Configuration.getMaxUploadSize());
    }

    /**
     * @return {@link MultipartForm} object for convenience.
     */
    protected MultipartForm multipartForm(){
        return multipartForm("UTF-8", Configuration.getMaxUploadSize());
    }

    /**
     * @param encoding encoding to use to read values from request
     * @param maxUploadSize set max upload size
     *
     * @return {@link MultipartForm} object for convenience.
     */
    protected MultipartForm multipartForm(String encoding, long maxUploadSize){
        MultipartForm multipartForm = new MultipartForm();
        List<FormItem> formItems = multipartFormItems(encoding, maxUploadSize);
        for (FormItem formItem : formItems) {
            if(formItem instanceof org.javalite.activeweb.FileItem){
                multipartForm.addFileItem((org.javalite.activeweb.FileItem) formItem);
            }else {
                multipartForm.addFormItem(formItem);
            }
        }
        return multipartForm;
    }

    /**
     * Returns a collection of uploaded files and form fields from a multi-part request.
     * This method uses DiskFileItemFactory.
     * As a result, it is recommended to add the following to your web.xml file:
     *
     *

     *   <listener>
     *      <listener-class>
     *         org.apache.commons.fileupload.servlet.FileCleanerCleanup
     *      </listener-class>
     *   </listener>
     *

     *
     * For more information, see: Using FileUpload
     *
     * @param encoding specifies the character encoding to be used when reading the headers of individual part.
     * When not specified, or null, the request encoding is used. If that is also not specified, or null,
     * the platform default encoding is used.
     *
     * @param maxUploadSize maximum size of the upload in bytes. A value of -1 indicates no maximum.
     *
     * @return a collection of uploaded files from a multi-part request.
     */
    protected List<FormItem> multipartFormItems(String encoding, long maxUploadSize) {
        //we are thread safe, because controllers are pinned to a thread and discarded after each request.
        if(RequestContext.getFormItems() != null ){
            return RequestContext.getFormItems();
        }

        HttpServletRequest req = RequestContext.getHttpRequest();

        if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload.
            RequestContext.setFormItems(((AWMockMultipartHttpServletRequest) req).getFormItems());
        } else {

            if (!ServletFileUpload.isMultipartContent(req))
                throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ...");

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(Configuration.getMaxUploadSize());
            factory.setRepository(Configuration.getTmpDir());

            ServletFileUpload upload = new ServletFileUpload(factory);
            if(encoding != null)
                upload.setHeaderEncoding(encoding);
            upload.setFileSizeMax(maxUploadSize);
            try {
                List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload.parseRequest(RequestContext.getHttpRequest());
                ArrayList items = new ArrayList<>();
                for (FileItem apacheItem : apacheFileItems) {
                    ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem);
                    if(f.isFormField()){
                        items.add(new FormItem(f));
                    }else{
                        items.add(new org.javalite.activeweb.FileItem(f));
                    }
                }
                RequestContext.setFormItems(items);
            } catch (Exception e) {
                throw new ControllerException(e);
            }
        }
        return RequestContext.getFormItems();
    }

    /**
     * Returns a map parsed from a request if parameter names have a "hash" syntax:
     *
     *

     *  <input type="text" name="account[name]" />
        <input type="text" name="account[number]" />
     *

     *
     * will result in a map where keys are names of hash elements, and values are values of these elements from request.
     * For the example above, the map will have these values:
     *
     *

     *     { "name":"John", "number": "123" }
     *

     *
     * @param hashName - name of a hash. In the example above, it will be "account".
     * @return map with name/value pairs parsed from request.
     */
    protected Map<String, String> getMap(String hashName) {
        Map<String, String[]>  params = params();
        Map<String, String>  hash = new HashMap<>();
        for(String key:params.keySet()){
            if(key.startsWith(hashName)){
                String name = parseHashName(key);
                if(name != null){
                    hash.put(name, param(key));
                }
            }
        }
        return hash;
    }

    /**
     * Convenience method to get parameter map in case multipart/form-data request was used.
     * This method will skip files, and will only return form fields that are not files.
     *
     * Returns a map parsed from a request if parameter names have a "hash" syntax:
     *
     *

     *  <input type="text" name="account[name]" />
     *  <input type="text" name="account[number]" />
     *

     *
     * will result in a map where keys are names of hash elements, and values are values of these elements from request.
     * For the example above, the map will have these values:
     *
     *

     *     { "name":"John", "number": "123" }
     *

     *
     * @param hashName - name of a hash. In the example above, it will be "account".
     * @param formItems form items retrieved from multipart/form-data request.
     * @return map with name/value pairs parsed from request.
     */
    protected Map<String, String> getMap(String hashName, List<FormItem> formItems) {
        Map<String, String>  hash = new HashMap<>();
        for(FormItem item:formItems){
            if(item.getFieldName().startsWith(hashName) && !item.isFile()){
                String name = parseHashName(item.getFieldName());
                if(name != null){
                    hash.put(name, item.getStreamAsString());
                }
            }
        }
        return hash;
    }

    /**
     * Parses name from hash syntax.
     *
     * @param param something like this: person[account]
     * @return name of hash key:account
     */
    private static String parseHashName(String param) {
        Matcher matcher = hashPattern.matcher(param);
        String name = null;
        while (matcher.find()){
            name = matcher.group(0);
        }
        return name == null? null : name.substring(1, name.length() - 1);
    }

    /**
     * Sets character encoding for request. Has to be called before reading any parameters of getting input
     * stream.
     * @param encoding encoding to be set.
     */
    protected void setRequestEncoding(String encoding) {

        try{
            RequestContext.getHttpRequest().setCharacterEncoding(encoding);
        }catch(Exception e){
            throw new WebException(e);
        }
    }

    /**
     * Sets character encoding for response.
     *
     * @param encoding encoding to be set.
     */
    protected void setResponseEncoding(String encoding) {
        RequestContext.getHttpResponse().setCharacterEncoding(encoding);
    }

    /**
     * Sets character encoding on the response.
     *
     * @param encoding character encoding for response.
     */
    protected void setEncoding(String encoding){
        RequestContext.setEncoding(encoding);
    }

    /**
     * Synonym for {@link #setEncoding(String)}
     *
     * @param encoding encoding of response to client
     */
    protected void encoding(String encoding){
        setEncoding(encoding);
    }

    /**
     * Controllers can override this method to return encoding they require. Encoding set in method {@link #setEncoding(String)}
     * trumps this setting.
     *
     * @return null. If this method is not overridden and encoding is not set from an action or filter,
     * encoding will be set according to container implementation.
     */
    protected String getEncoding(){
        return null;
    }

    /**
     * Sets content length of response.
     *
     * @param length content length of response.
     */
    protected void setContentLength(int length){
        RequestContext.getHttpResponse().setContentLength(length);
    }
    /**
     * Sets locale on response.
     *
     * @param locale locale for response.
     */
    protected void setLocale(Locale locale){
        RequestContext.getHttpResponse().setLocale(locale);
    }

    /**
     * Same as {@link #setLocale(java.util.Locale)}
     *
     * @param locale locale for response
     */
    protected void locale(Locale locale){
        RequestContext.getHttpResponse().setLocale(locale);
    }

    /**
     * Returns reference to a current session. Creates a new session of one does not exist.
     * @return reference to a current session.
     */
    protected SessionFacade session(){
        return new SessionFacade();
    }
    /**
     * Convenience method, sets an object on a session. Equivalent of:
     *

     *
     *     session().put(name, value)
     *
     *

     *
     * @param name name of object
     * @param value object itself.
     */
    protected void session(String name, Serializable value){
        session().put(name, value);
    }

    /**
     * Convenience method, returns object from session, equivalent of:
     *

     *
     *     session().get(name)
     *
     *

     *
     * @param name name of object,
     * @return session object.
     */
    protected Object sessionObject(String name){
        return session(name);
    }

    /**
     * Convenience method, returns object from session, equivalent of:
     *

     *
     *     String val = (String)session().get(name)
     *
     *

     *
     * @param name name of object
     * @return value
     */
    protected String sessionString(String name){
        return Convert.toString(session(name));
    }

    /**
     * Convenience method, returns object from session, equivalent of:
     *

     *
     *     Integer val = (Integer)session().get(name)
     *
     *

     *
     * @param name name of object
     * @return value
     */
    protected Integer sessionInteger(String name){
        return Convert.toInteger(session(name));
    }

    /**
     * Convenience method, returns object from session, equivalent of:
     *

     *
     *     Boolean val = (Boolean)session().get(name)
     *
     *

     *
     * @param name name of object
     * @return value
     */
    protected Boolean sessionBoolean(String name){
        return Convert.toBoolean(session(name));
    }

    /**
     * Convenience method, returns object from session, equivalent of:
     *

     *
     *     Double val = (Double)session().get(name)
     *
     *

     *
     * @param name name of object
     * @return value
     */
    protected Double sessionDouble(String name){
        return Convert.toDouble(session(name));
    }

    /**
     * Convenience method, returns object from session, equivalent of:
     *

     *
     *     Float val = (Float)session().get(name)
     *
     *

     *
     * @param name name of object
     * @return value
     */
    protected Float sessionFloat(String name){
        return Convert.toFloat(session(name));
    }

    /**
     * Convenience method, returns object from session, equivalent of:
     *

     *
     *     Long val = (Long)session().get(name)
     *
     *

     *
     * @param name name of object
     * @return value
     */
    protected Long sessionLong(String name){
        return Convert.toLong(session(name));
    }

    /**
     * Returns true if session has named object, false if not.
     *
     * @param name name of object.
     * @return true if session has named object, false if not.
     */
    protected boolean sessionHas(String name){
        return session().get(name) != null;
    }

    /**
     * Sends cookie to browse with response.
     *
     * @param cookie cookie to send.
     */
    protected void sendCookie(Cookie cookie){
        RequestContext.getHttpResponse().addCookie(Cookie.toServletCookie(cookie));
    }

    /**
     * Sends cookie to browse with response.
     *
     * @param name name of cookie
     * @param value value of cookie.
     */
    protected void sendCookie(String name, String value) {
        RequestContext.getHttpResponse().addCookie(Cookie.toServletCookie(new Cookie(name, value)));
    }

    /**
     * Sends long to live cookie to browse with response. This cookie will be asked to live for 20 years.
     *
     * @param name name of cookie
     * @param value value of cookie.
     */
    protected void sendPermanentCookie(String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(60*60*24*365*20);
        RequestContext.getHttpResponse().addCookie(Cookie.toServletCookie(cookie));
    }

    /**
     * Adds a header to response.
     *
     * @param name name of header.
     * @param value value of header.
     */
    protected void header(String name, String value){
        RequestContext.getHttpResponse().addHeader(name, value);
    }

    /**
     * Adds a header to response.
     *
     * @param name name of header.
     * @param value value of header.
     */
    protected void header(String name, Object value){
        if(value == null) throw new NullPointerException("value cannot be null");

        header(name, value.toString());
    }

    /**
     * Streams content of the reader to the HTTP client.
     *
     * @param in input stream to read bytes from.
     * @return {@link HttpSupport.HttpBuilder}, to accept additional information.
     */
    protected HttpBuilder streamOut(InputStream in) {
        StreamResponse resp = new StreamResponse(in);
        RequestContext.setControllerResponse(resp);
        return new HttpBuilder(resp);
    }

    /**
     * Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns
     * the absolute file path on the server's filesystem would be served by a request for
     * "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext..
     *

     * The real path returned will be in a form appropriate to the computer and operating system on which the servlet
     *

     * container is running, including the proper path separators. This method returns null if the servlet container
     * cannot translate the virtual path to a real path for any reason (such as when the content is being made
     * available from a .war archive).
     *
     *

     * JavaDoc copied from:
     * http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29
     *
     * @param path a String specifying a virtual path
     * @return a String specifying the real path, or null if the translation cannot be performed
     */
    protected String getRealPath(String path) {
        return RequestContext.getFilterConfig().getServletContext().getRealPath(path);
    }

    /**
     * Use to send raw data to HTTP client. Content type and headers will not be set.
     * Response code will be set to 200.
     *
     * @return instance of output stream to send raw data directly to HTTP client.
     */
    protected OutputStream outputStream(){
        return outputStream(null, null, 200);
    }

    /**
     * Use to send raw data to HTTP client. Status will be set to 200.
     *
     * @param contentType content type
     * @return instance of output stream to send raw data directly to HTTP client.
     */
    protected OutputStream outputStream(String contentType) {
        return outputStream(contentType, null, 200);
    }

    /**
     * Use to send raw data to HTTP client.
     *
     * @param contentType content type
     * @param headers set of headers.
     * @param status status.
     * @return instance of output stream to send raw data directly to HTTP client.
     */
    protected OutputStream outputStream(String contentType, Map headers, int status) {
        try {
            addHeaders(contentType, headers, status);
            return RequestContext.getHttpResponse().getOutputStream();
        }catch(Exception e){
            throw new ControllerException(e);
        }
    }

    private void addHeaders(String contentType, Map headers, int status){
        RequestContext.setControllerResponse(new NopResponse(contentType, status));

        if (headers != null) {
            for (Object key : headers.keySet()) {
                if (headers.get(key) != null)
                    RequestContext.getHttpResponse().addHeader(key.toString(), headers.get(key).toString());
            }
        }
    }

    /**
     * Produces a writer for sending raw data to HTTP clients.
     *
     * Content type content type not be set on the response. Headers will not be send to client. Status will be
     * set to 200.
     * @return instance of a writer for writing content to HTTP client.
     */
    protected PrintWriter writer(){
        return writer(null, null, 200);
    }

    /**
     * Produces a writer for sending raw data to HTTP clients.
     *
     * @param contentType content type. If null - will not be set on the response
     * @param headers headers. If null - will not be set on the response
     * @param status will be sent to browser.
     * @return instance of a writer for writing content to HTTP client.
     */
    protected PrintWriter writer(String contentType, Map headers, int status){
        try{
            addHeaders(contentType, headers, status);
            return RequestContext.getHttpResponse().getWriter();
        }catch(Exception e){
            throw new ControllerException(e);
        }
    }

    /**
     * Returns true if any named request parameter is blank.
     *
     * @param names names of request parameters.
     * @return true if any request parameter is blank.
     */
    protected boolean blank(String ... names){
        for(String name:names){
            if(Util.blank(param(name))){
                return true;
            }
        }
        return false;
    }

    /**
     * Will merge a template and return resulting string. This method is used for just merging some text with dynamic values.
     * Once you have the result, you can send it by email, external web service, save it to a database, etc.
     *
     * @param template name of template - same as in regular templates. Example: "/email-templates/welcome".
     * @param values values to be merged into template.
     * @return merged string
     */
    protected String merge(String template, Map values){
        StringWriter stringWriter = new StringWriter();
        Configuration.getTemplateManager().merge(values, template, stringWriter);
        return stringWriter.toString();
    }

    /**
     * Returns response headers
     *
     * @return map with response headers.
     */
    protected Map<String, String> getResponseHeaders(){
        Collection<String> names  = RequestContext.getHttpResponse().getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        for (String name : names) {
            headers.put(name, RequestContext.getHttpResponse().getHeader(name));
        }
        return headers;
    }

    /**
     * Cleans HTML from harmful tags, making XSS impossible.
     *
For example, input like this:

     *
     *

     *      <html><script> alert('hello');</script><div>this is a clean part</div></html>
     *

     *
     * Will produce output like this:
     *
     *

     *     this is a clean part
     *

     *
     * @param unsafeContent unsafe content. Something that an end user typed into a text area, or input that may include
     *                      a script tag or other garbage.
     * @return sanitized version of input
     */
    protected String sanitize(String unsafeContent){
        return Jsoup.clean(unsafeContent, Whitelist.basic());
    }

    /**
     * Returns InputStream of the request.
     *
     * @return InputStream of the request
     */
    protected InputStream getRequestInputStream() {
        try {
            return RequestContext.getHttpRequest().getInputStream();
        } catch (IOException e) {
            throw new WebException(e);
        }
    }

    /**
     * Alias to {@link #getRequestInputStream()}.
     * @return input stream to read data sent by client.
     *
     */
    protected InputStream getRequestStream() {
        try {
            return RequestContext.getHttpRequest().getInputStream();
        } catch (IOException e) {
            throw new WebException(e);
        }
    }

    /**
     * Reads entire request data as String. Do not use for large data sets to avoid
     * memory issues, instead use {@link #getRequestInputStream()}.
     *
     * @return data sent by client as string.
     */
    protected String getRequestString() {
        try {
            return Util.read(RequestContext.getHttpRequest().getInputStream());
        } catch (IOException e) {
            throw new WebException(e);
        }
    }

    /**
     * Reads entire request data as byte array. Do not use for large data sets to avoid
     * memory issues.
     *
     * @return data sent by client as string.
     */
    protected byte[] getRequestBytes() {

        try {
            return Util.bytes(RequestContext.getHttpRequest().getInputStream());
        } catch (IOException e) {
            throw new WebException(e);
        }
    }

    /**
     * Converts posted JSON array to a Java List. Example of a JSON array: [1, 2, 3].
     *
     * @return Java List converted from posted JSON string.
     */
    protected List jsonList() {
        checkJsonContentType();
        return JSONHelper.toList(getRequestString());
    }

    private void checkJsonContentType(){
        if(!(header("Content-Type") != null && header("Content-Type").toLowerCase().contains("application/json")) ){
            throw new WebException("Trying to convert JSON to object, but Content-Type is " + header("Content-Type") + ", not 'application/json'");
        }
    }

    /**
     * Converts posted JSON map to a Java Map. Example JSON map: {"name":"John", "age":21}.
     *
     * @return Java Map converted from posted JSON string map.
     */
    protected Map jsonMap() {
        checkJsonContentType();
        return JSONHelper.toMap(getRequestString());

    }

    /**
     * Converts posted JSON maps to a Java Maps array. Example JSON map: [{"name":"John", "age":21}, {"name":"Jane", "age":20}].
     *
     * @return Java Maps converted from posted JSON string maps.
     */
    protected Map[] jsonMaps() {
        checkJsonContentType();
        return JSONHelper.toMaps(getRequestString());
    }

    /**
     * Returns a mutable Map with all the values from the current request context. Use this to get/put/modify values from
     * current place on the stack down stream (from filters to controllers, to views).
     *
     * @return a mutable Map with all values from/for current request context.
     */
    protected Map values() {
        return RequestContext.getValues();
    }
}


text:
{% extends "../view.html" %}

{% block page_title %}
  Add your contact information - GOV.UK
{% endblock %}

{% block content %}

  {% include "../partials/feedback-banner.html" %}

  {% include "../partials/nav-admin-manage.html" %}

        Add your contact information

        This is the information that will be available to your public contacts.

      <form method="POST" action="hof-notice-search">

            Contact email

          <input class="form-control" id="contact_email" type="text" name="contact_email" value="">

            Contact phone number

          <input class="form-control" id="contact_phone" type="text" name="contact_phone" value="">

            Contact postal address

          <textarea maxlength="8000" class="form-control form-control-3-4" name="sender_address" id="sender_address" rows="7" value=""></textarea>

        <button type="submit" class="button big-space">Continue</button>

      </form>

{% endblock %}


text:
package com.mvp4g.rebind.config.element;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class EventFiltersElementTest
  extends AbstractMvp4gElementTest<EventFiltersElement> {

  protected static final String[] properties = { "afterHistory",
                                                 "filterForward",
                                                 "filterStart",
                                                 "forceFilters" };

  @Test
  public void testAfterHistory() {
    EventFiltersElement element = newElement();
    assertFalse(element.isAfterHistory());
    element.setAfterHistory("true");
    assertTrue(element.isAfterHistory());

    element = newElement();
    element.setAfterHistory("false");
    assertFalse(element.isAfterHistory());
  }

  @Override
  protected EventFiltersElement newElement() {
    return new EventFiltersElement();
  }

  @Override
  protected String getTag() {
    return "eventFilters";
  }

  @Override
  protected String getUniqueIdentifierName() {
    return EventFiltersElement.class.getName();
  }

  @Override
  protected String[] getProperties() {
    return properties;
  }

  @Test
  public void testFilterStart() {
    EventFiltersElement element = newElement();
    assertTrue(element.isFilterStart());
    element.setFilterStart("false");
    assertFalse(element.isFilterStart());

    element = newElement();
    element.setFilterStart("true");
    assertTrue(element.isFilterStart());
  }

  @Test
  public void testFilterFoward() {
    EventFiltersElement element = newElement();
    assertTrue(element.isFilterForward());
    element.setFilterForward("false");
    assertFalse(element.isFilterForward());

    element = newElement();
    element.setFilterForward("true");
    assertTrue(element.isFilterForward());
  }

  @Test
  public void testForceFilters() {
    EventFiltersElement element = newElement();
    assertFalse(element.isForceFilters());
    element.setForceFilters("true");
    assertTrue(element.isForceFilters());

    element = newElement();
    element.setForceFilters("false");
    assertFalse(element.isForceFilters());
  }

}