text:
package at.illecker.classification.commons;

import java.util.Map;

public class Item extends FeatureVector {

  private Long m_id;
  private Integer m_actualClass = null;
  private Integer m_predictedClass = null;
  private Map<Integer, Double> m_predictedClassProbabilities = null;

  public Item(Long id, Map<Integer, Double> featureVector, Integer actualClass) {
    super(featureVector);
    this.m_id = id;
    this.m_actualClass = actualClass;
  }

  public Long getId() {
    return m_id;
  }

  public Integer getActualClass() {
    return m_actualClass;
  }

  public Integer getPredictedClass() {
    return m_predictedClass;
  }

  public void setPredictedClass(Integer predictedClass) {
    this.m_predictedClass = predictedClass;
  }

  public Map<Integer, Double> getPredictedClassProbabilities() {
    return m_predictedClassProbabilities;
  }

  public void setPredictedClassProbabilities(
      Map<Integer, Double> predictedClassProbabilities) {
    this.m_predictedClassProbabilities = predictedClassProbabilities;
  }

  @Override
  public String toString() {
    return "Item [id=" + m_id + ", actualClass=" + m_actualClass
        + ", predictedClass=" + m_predictedClass + ", featureVector: "
        + this.getFeatureVector() + "]";
  }

}


text:
package org.apache.spark.ml.classification

object ClassifierSuite {

  /**
   * Mapping from all Params to valid settings which differ from the defaults.
   * This is useful for tests which need to exercise all Params, such as save/load.
   * This excludes input columns to simplify some tests.
   */
  val allParamSettings: Map[String, Any] = Map(
    "predictionCol" -> "myPrediction",
    "rawPredictionCol" -> "myRawPrediction"
  )

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Guardtime.KSI.Exceptions;
using Org.BouncyCastle.X509;

namespace Guardtime.KSI.Crypto.BouncyCastle.Crypto
{
    /// <summary>
    /// Class for verifying that a certificate was valid on given time
    /// </summary>
    public class CertificateTimeVerifier
    {
        /// <summary>
        /// Verify that given certificate was valid on given time
        /// </summary>
        /// <param name="certificate">certificate</param>
        /// <param name="time">time to check certificate validity against</param>
        public static void Verify(X509Certificate certificate, ulong? time)
        {
            if (time.HasValue)
            {
                DateTime signTime = Utils.Util.ConvertUnixTimeToDateTime(time.Value);
                if (certificate.NotBefore.ToUniversalTime() > signTime || certificate.NotAfter.ToUniversalTime() < signTime)
                {
                    throw new PkiVerificationFailedCertNotValidException(string.Format("Certificate not valid at {0}.", signTime));
                }
            }
        }
    }
}


text:
/**
 *
 */
package com.github.zhou6ang.statemachine.pojo;

/**
 * @author ganzhou
 *
 */
public class Transition {

	private State from;
	private State to;
	private Condition condition;
	private Action action;
	public State getFrom() {
		return from;
	}
	public void setFrom(State from) {
		this.from = from;
	}
	public State getTo() {
		return to;
	}
	public void setTo(State to) {
		this.to = to;
	}
	public Condition getCondition() {
		return condition;
	}
	public void setCondition(Condition condtion) {
		this.condition = condtion;
	}
	public Action getAction() {
		return action;
	}
	public void setAction(Action action) {
		this.action = action;
	}

}


text:
import {Messaging} from '../messaging/messaging';
import {TouchHandler} from '../touch-handler';
import * as sinon from 'sinon';

class WindowPortEmulator {
  constructor(win, origin) {
    /** @const {!Window} */
    this.win = win;
    /** @private {string} */
    this.origin_ = origin;
  }

  addEventListener(eventType, handler) {
    console/*OK*/.log(eventType, handler);
  }

  postMessage(data) {
    console/*OK*/.log(data);
  }
  start() {
  }
}

function fakeTouchEvent(type) {
  return {
    type,
    'pageX': 10,
    'pageY': 20,
    'thisshouldnotgetcopied': 'bla',
    touches:
    [{'clientX': 20, 'clientY': 30, 'screenX': 10, 'screenY': 20,
      'dontcopythis': 234}],
    changedTouches:
        [{'clientX': 20, 'clientY': 30, 'screenX': 10, 'screenY': 20}],
    preventDefault() {},
  };
}

describes.fakeWin('TouchHandler', {}, env => {
  describe('TouchHandler Unit Tests', function() {
    let win;
    let sandbox;
    let touchHandler;
    let messaging;

    beforeEach(() => {
      win = env.win;
      sandbox = sinon.sandbox;
      const port =
        new WindowPortEmulator(this.messageHandlers_, 'origin doesnt matter');
      messaging = new Messaging(win, port);
      touchHandler = new TouchHandler(win, messaging);
    });

    afterEach(() => {
      touchHandler = null;
    });

    it('should only forward supported events', () => {
      const forwardEventStub = sandbox.stub(touchHandler, 'forwardEvent_');

      touchHandler.handleEvent_(fakeTouchEvent('notasupportedevent'));
      expect(forwardEventStub).to.not.be.called;

      touchHandler.handleEvent_(fakeTouchEvent('touchstart'));
      touchHandler.handleEvent_(fakeTouchEvent('touchmove'));
      touchHandler.handleEvent_(fakeTouchEvent('touchend'));
      expect(forwardEventStub).to.be.calledThrice;
    });

    it('should behave correctly when forwarding events', () => {
      const fakeEvent = fakeTouchEvent('touchstart');
      const preventDefaultStub = sandbox.stub(fakeEvent, 'preventDefault');
      const copyTouchEventStub = sandbox.stub(touchHandler, 'copyTouchEvent_');
      const sendRequestStub = sandbox.stub(messaging, 'sendRequest');

      touchHandler.forwardEvent_(fakeEvent);
      expect(copyTouchEventStub).to.have.been.called;
      expect(sendRequestStub).to.have.been.called;
      expect(preventDefaultStub).to.not.have.been.called;

      touchHandler.scrollLockHandler_('some type', true, false);
      touchHandler.forwardEvent_(fakeEvent);
      expect(preventDefaultStub).to.have.been.called;

    });

    it('should copy events correctly', () => {
      const eventType = 'touchstart';
      const fakeEvent = fakeTouchEvent(eventType);
      const copiedEvent = touchHandler.copyTouchEvent_(fakeEvent);
      expect(copiedEvent).to.deep.equal({
        'pageX': 10,
        'pageY': 20,
        'type': eventType,
        touches:
            [{'clientX': 20, 'clientY': 30, 'screenX': 10, 'screenY': 20}],
        changedTouches:
            [{'clientX': 20, 'clientY': 30, 'screenX': 10, 'screenY': 20}],
      });
    });
  });
});


text:
"""docstring
"""

__revision__ = '0.1'

import time

from django.http import HttpResponse

from annotations import to_url, get, strlist
from utils import time_table_data_source
from utils import ical_data_bridge

@to_url("^$")
def index(request):
    return HttpResponse('Welcome to 美剧时间表')

@to_url('^fetch_yyets_data')
def fetch_yyets_data(request):
    i_year = int(time.strftime('%Y'))
    i_this_month = int(time.strftime('%m'))
    time_table = time_table_data_source.read_time_table(i_year, i_this_month)
    ical_data = ical_data_bridge.ical_data(i_year, i_this_month, time_table)
    return HttpResponse(ical_data)

@to_url('^time_table.ics$')
@get(c_type=(str, ""), show_ids=(strlist, []))
def fetch_yyets_data(request, c_type, show_ids):
    i_year = int(time.strftime('%Y'))
    i_this_month = int(time.strftime('%m'))
    time_table = time_table_data_source.read_time_table(i_year, i_this_month)
    ical_data = ical_data_bridge.ical_data(i_year, i_this_month, time_table, show_ids)
    if (c_type == 'file'):
        #Content-Type:text/calendar; charset=UTF-8
        return HttpResponse(content=ical_data, content_type='Content-Type:text/calendar; charset=UTF-8')
    else:
        return HttpResponse(content=ical_data)


text:
@interface LolayBaseTracker : NSObject <LolayTracker>

@end


text:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Xml;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using static System.Console;
using static System.ConsoleKey;

namespace OpenDataApplication.Core
{
    public class NsData
    {
        public int RitNummer;
        public string VertrekTijd;
        public string EindBestemming;
        public string TreinSoort;
        public string Vervoerder;
        public string VertrekSpoor;

        public override string ToString()
        {
            return $"{{{RitNummer}, {VertrekTijd ?? "NULL"}, {EindBestemming ?? "NULL"}, {TreinSoort ?? "NULL"}, {Vervoerder ?? "NULL"}, {VertrekSpoor ?? "NULL"}}}";
        }
    }

    [XmlRoot("ActueleVertrekTijden")]
    public class ActueleVertrekTijden
    {
        [XmlElement("VertrekkendeTrein")]
        public List<NsData> data { get; set; }

        public ActueleVertrekTijden()
        {
            data = new List<NsData>();
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{Count=");
            sb.Append(data.Count);
            sb.Append(", Data=");
            for (int i = 0; i < data.Count; i++)
            {
                sb.Append(data[i]);
            }
            sb.Append("}");
            return sb.ToString();
        }
    }

    public class HttpHeader
    {
        const string username = "0916827@hr.nl";
        const string password = "6qmg-XC7AH61Wz53i89ZC-bVSyab7QYTD6nS_Dx6wlLoMM_cFzzSXA";

        public static object getActueleVertrektijden(string URL)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.Method = WebRequestMethods.Http.Get;
            request.Credentials = new NetworkCredential(username, password);
            request.ContentType = "text/xml; encoding='utf-8'";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            XmlDocument xmlDocu = new XmlDocument();

            XmlSerializer serial = new XmlSerializer(typeof(ActueleVertrekTijden));
            ActueleVertrekTijden resp = (ActueleVertrekTijden)serial.Deserialize(response.GetResponseStream());

            Console.WriteLine(resp);

            return (resp);
        }
    }
}


text:
using System;

namespace Wpf.Home
{
    public class SampleVm
    {
        private static int _idCount;

        public SampleVm()
        {
            Id = _idCount++;
            Tags = string.Empty;
        }

        public SampleVm(string title, Type content, string tags = "")
        {
            Id = _idCount++;
            Title = title;
            Content = content;
            Tags = tags;
        }

        public int Id { get; private set; }
        public string Title { get; set; }
        public Type Content { get; set; }
        public string Tags { get; set; }
    }
}


text:
namespace MetaMorpheusGUI
{
    public class CollectionForTreeView : ForTreeView
    {
        #region Public Constructors

        public CollectionForTreeView(string id, string displayName) : base(id, displayName)
        {
        }

        #endregion Public Constructors
    }
}


text:
<?php

namespace Mesd\FilterBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * FilterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FilterRepository extends EntityRepository
{
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// more...
using System.ComponentModel.DataAnnotations;

// This source code file is used to define your model classes

namespace LinkRelations.Models
{
    // Music web service
    // Artist - Album - Song

    public class Artist
    {
        public Artist()
        {
            this.BirthOrStartDate = DateTime.Now.AddYears(-10);
            this.Albums = new List<Album>();
        }

        public int Id { get; set; }
        [Required, StringLength(50)]
        public string Name { get; set; }
        public string BirthName { get; set; }
        // For a person, the birth date
        // For a duo/band/group, the date the band started working together
        public DateTime BirthOrStartDate { get; set; }
        [Required, StringLength(50)]
        public string Genre { get; set; }

        public ICollection<Album> Albums { get; set; }

    }

    public class Album
    {
        public Album()
        {
            this.ReleaseDate = DateTime.Now.AddYears(-1);
            this.Songs = new List<Song>();
        }

        public int Id { get; set; }
        [Required, StringLength(50)]
        public string Name { get; set; }
        public DateTime ReleaseDate { get; set; }
        [Required, StringLength(50)]
        public string Genre { get; set; }

        public ICollection<Song> Songs { get; set; }
        public Artist Artist { get; set; }
    }

    public class Song
    {
        public Song()
        {
            this.SingleReleaseDate = DateTime.Now.AddYears(-1);
            this.TrackNumber = 1;
            this.LengthInSeconds = 240;
        }

        public int Id { get; set; }
        [Required, StringLength(50)]
        public string Name { get; set; }
        public DateTime SingleReleaseDate { get; set; }
        [Required, StringLength(50)]
        public string Composer { get; set; }
        public int TrackNumber { get; set; }
        public int LengthInSeconds { get; set; }
        [Required, StringLength(50)]
        public string Genre { get; set; }

        public Album Album { get; set; }
    }

}


text:
import {Component} from '@angular/core';

@Component({
	moduleId: module.id,
	selector: 'slider',
	templateUrl: 'slider.component.html',
	styleUrls: ['slider.component.css']
})

export class SliderComponent { }


text:
package com.gamerecorder.db.model;

import java.util.Date;

import com.gamerecorder.interfaces.Identity;
import com.gamerecorder.util.Constants;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = GameResultStatistic.TABLE_NAME)
public class GameResultStatistic implements Identity{

	public static final String TABLE_NAME = "game_result_statistic";
	public static final String COLUMN_ID = "id";
	public static final String COLUMN_MARK = "special_mark";
	public static final String COLUMN_DESC = "desc";

	@DatabaseField(generatedId = true)
	private int id;

	@DatabaseField
	private String desc;

	@DatabaseField(columnName = COLUMN_MARK)
	private int specialMark;

	@DatabaseField(foreign = true, canBeNull = false,columnDefinition = "integer references " + GameResult.TABLE_NAME + "(" + GameResult.COLUMN_ID + ") on delete cascade")
	private GameResult result;

	@DatabaseField(foreign = true, canBeNull = false,foreignAutoRefresh = true,maxForeignAutoRefreshLevel = 2)
	public GameTeammember teammember;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public int getSpecialMark() {
		return specialMark;
	}

	public void setSpecialMark(int specialMark) {
		this.specialMark = specialMark;
	}

	public GameResult getResult() {
		return result;
	}

	public void setResult(GameResult result) {
		this.result = result;
	}

	private void setDesc(Integer score,String type){
		String record = teammember.getName();
		if(score != null){
			record += "$"+score;
		}
		else{
			record += "$" + Constants.NOT_PTS;
		}
		record += "$"+type + "$" + new Date().getTime();
		setDesc(record);
	}

	public GameResultStatistic(GameResult result,GameTeammember teammember,Integer score,String type){
		this();
		this.result = result;
		this.teammember = teammember;
		setDesc(score, type);
	}

	public GameResultStatistic(){}

	public GameTeammember getTeammember() {
		return teammember;
	}

	public String getTeammemeberName(){
		return teammember.getName();
	}

	public String getStatisticType(){
		return this.desc.split("\\$")[2];
	}

	public int getScore(){
		return Integer.valueOf(this.desc.split("\\$")[1]);
	}

	public Date getTime(){
		return new Date(Long.valueOf(this.desc.split("\\$")[3]));
	}

}


text:
<?php
/**
 * Description of ValidationHelper
 *
 * @author ypra
 */
class ValidationHelper
{

    public static function validateNotNull($field, $value)
    {
        return is_null($value)?
            new ValidationFailed($field, __('validate.null')): null;
    }

    public static function validateNotBlank($field, $value)
    {
        return is_string($value) && trim($value)===''?
            new ValidationFailed($field, __('validate.blank')): null;
    }

    public static function validateRange($field, $value, $min, $max)
    {
        return ($value<$min || $value>$max)?
            new ValidationFailed($field, __('validate.range',
                    array('min' => $min, 'max' => $max))): null;
    }

    public static function validateMinValue($field, $value, $min)
    {
        return $value<$min? new ValidationFailed($field,
                __('validate.min.value', array('min' => $min))): null;
    }

    public static function validateMaxValue($field, $value, $max)
    {
        return $value>$max? new ValidationFailed($field,
                __('validate.max.value', array('max' => $max))): null;
    }

    public static function validateSize($field, $value, $min, $max)
    {
        return (mb_strlen($value)<$min || mb_strlen($value)>$max)?
            new ValidationFailed($field, __('validate.size',
                    array('min' => $min, 'max' => $max))): null;
    }

    public static function validateMinSize($field, $value, $min)
    {
        return mb_strlen($value)<$min? new ValidationFailed($field,
                __('validate.min.size', array('min' => $min))): null;
    }

    public static function validateMaxSize($field, $value, $max)
    {
        return mb_strlen($value)>$max? new ValidationFailed($field,
                __('validate.max.size', array('max' => $max))): null;
    }

    public static function validateNotEqual($field, $value, $val)
    {
        return $value!=$val? new ValidationFailed($field,
                __('validate.not.equal', array('val' => $val))): null;
    }

    public static function validateNotEmail($field, $value)
    {
        return !Validation::isEmail($value)? new ValidationFailed($field,
                __('validate.email')): null;
    }

    public static function validateNotInlist($field, $value, $list)
    {
        return !in_array($value, $list)? new ValidationFailed($field,
                __('validate.not.inlist', array('val' => $val))): null;
    }

    public static function validateField($field, $value, $validations)
    {
        $keys = array_keys($validations);
        foreach($validations as $type => $option){
            $validateResult = null;
            switch ($type){
                case 'null':
                    $validateResult = !$option?
                        self::validateNotNull($field, $value): null;
                    break;
                case 'blank':
                    $validateResult = !$option?
                        self::validateNotBlank($field, $value): null;
                    break;
                case 'value':
                    $min = $option['min'];
                    $max = $option['max'];
                    if(self::isInteger($min) && self::isInteger($max)){
                        $validateResult = self::validateRange($field, $value,
                                $min, $max);
                    }elseif(self::isInteger($min)){
                        $validateResult = self::validateMinValue($field,
                                $value, $min);
                    }elseif(self::isInteger($max)){
                        $validateResult = self::validateMaxValue($field,
                                $value, $max);
                    }else{
                        throw new ChocalaException('INVALID VALUE VALIDATION DATA');
                    }
                case 'size':
                    $min = $option['min'];
                    $max = $option['max'];
                    if(self::isInteger($min) && self::isInteger($max)){
                        $validateResult = self::validateSize($field,  $value,
                                $min, $max);
                    }elseif(is_integer($min)){
                        $validateResult = self::validateMinSize($field, $value,
                                $min);
                    }elseif(is_integer($max)){
                        $validateResult = self::validateMaxSize($field, $value,
                                $max);
                    }else{
                        throw new ChocalaException('INVALID SIZE VALIDATION DATA');
                    }
                    break;
                case 'equal':
                    $validateResult = self::validateNotEqual($field, $value,
                            $option);
                    break;
                case 'email':
                    $validateResult = $option? self::validateNotEmail($field,
                            $value): null;
                    break;
                case 'inlist':
                    if(is_array($option)){
                        $validateResult = self::validateNotInlist($field,
                                $value, $option);
                    }else{
                        throw new ChocalaException('INVALID LIST VALIDATION DATA');
                    }
                    break;
            }
            if(!is_null($validateResult)){
                return $validateResult;
            }
        }
        return null;
    }

    public static function validateObject($obj, $validations)
    {
        $failures = array();
        foreach ($validations as $kVal => $vVal){
            $getter = 'get'.ucfirst($kVal);
            $fails = self::validateField($kVal, $obj->$getter(), $vVal);
            if($fails != ''){
                $failures[] = $fails;
            }
        }
        return $failures;
    }

    public static function mergeFailures($parentErrors, $validationErrors)
    {
        if(is_array($parentErrors)){
            if(!empty($validationErrors)){
                $validationErrors = array_merge($parentErrors,
                        $validationErrors);
            }else{
                $validationErrors = $parentErrors;
            }
            return $validationErrors;
        }elseif($parentErrors === true){
            if(empty($validationErrors)){
                return true;
            }else{
                return $validationErrors;
            }
        }else{
            throw UnexpectedValueException('Unexpected validation state.');
        }
    }

    public static function failuresMap($failures)
    {
        return array_map( function($obj){
                    return array(   'field' => $obj->getColumn(),
                                    'message' => $obj->getMessage());
                }, $failures);
    }

    /**
     *
     * @param mixed $var
     * @return boolean
     */
    public static function isInteger($var)
    {
        return is_numeric($var) && is_integer($var*1);
    }

    /**
     *
     * @param mixed $var
     * @return boolean
     */
    public static function isNotEmpty($var)
    {
        return (trim($var) != '');
    }

    /**
     *
     * @param string $var
     * @param int $min
     * @return bool
     */
    public static function isMinLength($var, $min)
    {
        return (strlen(trim($var))>=$min);
    }

    /**
     *
     * @param string $var
     * @return bool
     */
    public static function isEmail($var)
    {
        return  preg_match('#^(((([a-z\d][\.\-\+_]?)*)[a-z0-9])+)\@'.
                '(((([a-z\d][\.\-_]?){0,62})[a-z\d])+)\.([a-z\d]{2,6})$#i',
                trim($var));
    }

    /**
     *
     * @param string $var
     * @return bool
     */
    public static function isDate($var)
    {
        return preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/', trim($var));
    }

    /**
     *
     * @param string $var
     * @return bool
     */
    public static function isIP($var)
    {
        return preg_match('^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)'.
                '(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$', trim($var));
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isFile($key)
    {
        return (isset($_FILES[$key]) && $_FILES[$key]['error']==0);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isGet($key)
    {
        return isset($_GET[$key]);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isGetInteger($key)
    {
        return self::isGet($key) && self::isInteger($_GET[$key]);
    }

    /**
     *
     * @param string $key
     * @param int $min
     * @return bool
     */
    public static function isGetMinLength($key, $min)
    {
        return self::isGet($key) && self::isMinLength($_GET[$key], $min);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isGetNotEmpty($key)
    {
        return self::isGet($key) && self::isNotEmpty($_GET[$key]);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isGetEmail($key)
    {
        return self::isGet($key) && self::isEmail($_GET[$key]);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isPost($key)
    {
        return isset($_POST[$key]);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isPostInteger($key)
    {
        return self::isPost($key) && self::isInteger($_POST[$key]);
    }

    /**
     *
     * @param string $key
     * @param int $min
     * @return bool
     */
    public static function isPostMinLength($key, $min)
    {
        return self::isPost($key) && self::isMinLength($_POST[$key], $min);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isPostNotEmpty($key)
    {
        return self::isPost($key) && self::isNotEmpty($_POST[$key]);
    }

    /**
     *
     * @param string $key
     * @return bool
     */
    public static function isPostEmail($key)
    {
        return self::isPost($key) && self::isEmail($_POST[$key]);
    }

}


text:
'use strict';

describe('Filter: weight', function () {

  // load the filter's module
  beforeEach(module('newCodexApp'));

  // initialize a new instance of the filter before each test
  var weight;
  beforeEach(inject(function ($filter) {
    weight = $filter('weight');
  }));

  it('should return the input prefixed with "weight filter:"', function () {
    var text = 'angularjs';
    expect(weight(text)).toBe('weight filter: ' + text);
  });

});


text:
from flask import abort, g
from flask.ext.login import current_user

from access_levels import access

## Admin Table
# pk(user_id), level
# user_id - fk, int(11)
# level, unsigned int(4)

def test_access (uid, access):
	db = getattr(g, 'db', None)

	with db as cursor:
		query = "select level from tbl_admin where user_id = %s;"

		if cursor.execute(query, (uid,)) <= 0:
			#That user has no clearance.
			return False;
		elif cursor.fetchone()[0] > access:
			#That user has insufficient clearance.
			return False;
		else:
			#That user has sufficient clearance.
			return True

#check if current_user actually has access
def perimeter_check (access_str):
	if not test_access(current_user.uid, access[access_str]):
		abort(403)

def admin_config (uid, newaccess):
	db = getattr(g, 'db', None)

	with db as cursor:
		query = "insert into tbl_admin (user_id, level) values (\
			(select id from tbl_user where id = %s), %s) on\
			duplicate key update level=values(level);"
		cursor.execute(query, (uid, newaccess))


text:
'use strict';

/**
 * Expected Lighthouse audit values for sites with various errors.
 */
module.exports = [
  {
    errorCode: 'PAGE_HUNG',
    lhr: {
      requestedUrl: 'http://localhost:10200/infinite-loop.html',
      finalUrl: 'http://localhost:10200/infinite-loop.html',
      audits: {},
    },
  },
  {
    errorCode: 'INSECURE_DOCUMENT_REQUEST',
    lhr: {
      requestedUrl: 'https://expired.badssl.com',
      finalUrl: 'https://expired.badssl.com',
      audits: {},
    },
  },
];


text:
package org.yugzan.aop;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringAopApplicationTests {

	@Autowired
	private SomeService service;

	@Test
	public void contextLoads() {
	}

    @Test
    public void testAspect() {
    	System.out.println( service.doService("John"));
    }
}


text:
<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} %-5level %-20.20logger %message%n%xException{5}</pattern>
    </encoder>
  </appender>

  <logger name="org.apache" level="warn" />

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>

</configuration>


text:
* [maven](https://maven.apache.org/download.cgi)
* [java 8](https://java.com/download/)
* [adb](http://forum.xda-developers.com/showthread.php?t=2588979)
* [minicap](https://github.com/openstf/minicap) & [minitouch](https://github.com/openstf/minitouch)
* android device with adb enabled

### running
build minicap & minitouch,
push binaries (minicap, minicap.so, minitouch) to android device /data/local/tmp,
make them executable with chmod 0755

    mvn clean install
    java -jar mzdlink-{version}.jar
    open http://jsfiddle.net/serezhka/x6j1zcde/ (not https to make websockets work)

### dev notes

##### evtest arm cross compile
    sudo apt-get install gcc-arm-linux-gnueabi
    sudo apt-get install lib6c-dev-i386 lib6c-arm64-cross libc6-dev-armel-cross
    arm-linux-gnueabi-gcc evtest.c -o evtest


text:
**KBContactsSelection** is a standalone UI and logic component that allows you to easily search and select contacts in your Address Book and redirect to Mail or Messages with results.

##Showcase
Notice elegant solution with phone number, emails and final redirect difference.

![KBContactsSelection screen 1](https://raw.githubusercontent.com/burczyk/KBContactsSelection/master/assets/KBContactsSelection.png)

![KBContactsSelection gif](https://raw.githubusercontent.com/burczyk/KBContactsSelection/master/assets/KBContactsSelection.gif)

##Installation
**KBContactsSelection** is available via [CocoaPods](http://cocoapods.org). To use it simply add one line to your Podfile:

```
pod 'KBContactsSelection'
```

and then add required `import`:

```objective-c
#import "KBContactsSelectionViewController.h"
```

##Configuration
The public element of library is `KBContactsSelectionViewController` class. It contains one convenient method to create instance of itself with proper configuration:

```objective-c
+ (KBContactsSelectionViewController*)contactsSelectionViewControllerWithConfiguration:(void (^)(KBContactsSelectionConfiguration* configuration))configurationBlock;
```

**The simplest possible usage** looks like this:

```objective-c
KBContactsSelectionViewController *vc = [KBContactsSelectionViewController contactsSelectionViewControllerWithConfiguration:nil];

[self presentViewController:vc animated:YES completion:nil];
```

It uses objective-c [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern) adopted in elegant way with blocks usage. Inpiration for such solution was found [here](http://joris.kluivers.nl/blog/2014/04/08/the-builder-pattern-in-objective-c-foundation/).

`KBContactsSelectionViewController` is fullscreen view controller and it can be either pushed on navigation stack or presented.

`KBContactsSelectionConfiguration` class is responsinble for setting basic properties:

```objective-c
UIColor *tintColor;
enum KBContactsSelectionMode mode;
BOOL shouldShowNavigationBar;
```

**tintColor** is responsible for setting navigation bar `tintColor`, table view `sectionIndexColor` and search bar `tintColor`.

**mode** can be set to one of two enum values: `KBContactsSelectionModeMessages` or `KBContactsSelectionModeEmail`. They have impact on data displayed (emails or phone numbers) and final navigation (Messages or Mail app) for selected contacts.

**shouldShowNavigationBar** hides navigation bar from `KBContactsSelectionViewController` and should set when you push this view controller instead of presenting it.

##Usage
###Pushing KBContactsSelectionViewController with phone numbers

```objective-c
KBContactsSelectionViewController *vc = [KBContactsSelectionViewController contactsSelectionViewControllerWithConfiguration:^(KBContactsSelectionConfiguration *configuration) {
    configuration.mode = KBContactsSelectionModeMessages;
    configuration.shouldShowNavigationBar = NO;
    configuration.tintColor = [UIColor colorWithRed:11.0/255 green:211.0/255 blue:24.0/255 alpha:1];
}];

[self.navigationController pushViewController:vc animated:YES];
```

###Presenting KBContactsSelectionViewController with emails

```objective-c
KBContactsSelectionViewController *vc = [KBContactsSelectionViewController contactsSelectionViewControllerWithConfiguration:^(KBContactsSelectionConfiguration *configuration) {
    configuration.tintColor = [UIColor orangeColor];
    configuration.mode = KBContactsSelectionModeEmail;
}];

[self presentViewController:vc animated:YES completion:nil];
```

Each property of `KBContactsSelectionConfiguration` can be freely modified although it is advised not to hide navigation bar when presented and hide it when pushed.

##Example project
Example project is attached to this repository. Open `KBContactsSelectionExample.xcworkspace`, install all required dependencies by performing `pod install` and run the the same demo as in gif above.

##Known issues
iOS Simulator obviously doesn't support messaging (proper alert) and apparently has some issues with presenting `MFMailComposeViewController`:

```
KBContactsSelectionExample[20027:5171733] _serviceViewControllerReady:error: Error Domain=_UIViewServiceErrorDomain Code=1 "The operation couldn't be completed. (_UIViewServiceErrorDomain error 1.)" UserInfo=0x7f95cae243f0 {Canceled=service continuation}
```

It works fine on real device but fails on Simulator which is probably a bug. Some StackOverflow threads regarding this issue can be found [here](http://stackoverflow.com/questions/25604552/i-have-real-misunderstanding-with-mfmailcomposeviewcontroller-in-swift-ios8-in) and [here](http://stackoverflow.com/questions/25604552/i-have-real-misunderstanding-with-mfmailcomposeviewcontroller-in-swift-ios8-in).

This is why presented email view controller in gif doesn't have recipients entered.

##Components
###KBContactsSelectionViewController
Is a main component of whole library and probably the only one you should explicitly use. For a convenience it has some self-describing public properties to tweak its behavior:

```objective-c
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *buttonItemCancel;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *buttonItemSelect;
@property (weak, nonatomic) IBOutlet UINavigationBar *navigationBarSearchContacts;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navigationBarSearchContactsHeight;
```

It is responsible for most of user interactions: buttons, presenting final view controllers, search.

Despite the fact that `KBContactsSelectionViewController` contains table view it doesn't act as its data source or delegate. It passes all responsibilities regarding table view to `KBContactsTableViewDataSource` component.

###KBContactsTableViewDataSource
Is an object that adopts two protocols: `<UITableViewDataSource, UITableViewDelegate>` and is fully responsible for rendering, filtering and capturing contacts in table view.

It starts with loading all contacts once and storing them in immutable array for performance reasons. Then it groups the contacts in a dictionary where keys are first letters of full name and values are sorted arrays of all contacts whose name starts with this letter.

Search is performed by creating a filtered copy of all contacts and grouping it like before.

All selected contacts are stored in separate array by `recordID` field so they are persisted between searches.

When `Select` button is pushed initial contacts array is filtered using all `recordIds` and proper view controller is displayed.

###KBContactsSelectionConfiguration
Was described in **Configuration** section.

##Localized strings
Library contains `NSLocalizedString` macro in proper places so you can generate `Localizable.strings` file with following literals:

```
"Messaging not supported" = "Messaging not supported";
"Messaging on this device is not supported." = "Messaging on this device is not supported.";
"OK" = "OK";
"Search contacts" = "Search contacts";
"Select" = "Select";
"Sending emails from this device is not supported." = "Sending emails from this device is not supported.";
```

##Dependencies
**KBContactsSelection** uses [APAddressBook](https://github.com/Alterplay/APAddressBook) to easily manage iOS Address Book.

##License
**KBContactsSelection** is under `MIT License`. See [LICENSE](https://github.com/burczyk/KBContactsSelection/blob/master/LICENSE) file for more info.


text:
function [ys,ts,xs] = lsim(varargin)
%LSIM  Simulates time response of LTI systems to arbitrary inputs.
%
%   LSIM(SYS,U,T)  plots the time response of the LTI model SYS to the
%   input signal described by U and T.  The time vector T consists of
%   regularly spaced time samples and U is a matrix with as many columns
%   as inputs and whose i-th row specifies the input value at time T(i).
%   For example,
%           t = 0:0.01:5;   u = sin(t);   lsim(sys,u,t)
%   simulates the response of a single-input model SYS to the input
%   u(t)=sin(t) during 5 seconds.
%
%   In discrete time, U should be sampled at the same rate as the system
%   (T is then redundant and can be omitted or set to the empty matrix).
%   In continuous time, choose the sampling period T(2)-T(1) small enough
%   to accurately describe the input U.  LSIM checks for intersample
%   oscillations and resamples U if necessary.
%
%   LSIM(SYS,U,T,X0)  specifies an additional nonzero initial state X0
%   (for state-space systems only).
%
%   LSIM(SYS1,SYS2,...,U,T,X0)  simulates the response of multiple LTI
%   systems SYS1,SYS2,... on a single plot.  The initial condition X0
%   is optional.  You can also specify a color, line style, and marker
%   for each system, as in  lsim(sys1,'r',sys2,'y--',sys3,'gx',u,t).
%
%   When invoked with left-hand arguments,
%        [YS,TS] = LSIM(SYS,U,T,...)
%   returns the output history YS and time vector TS used for simulation.
%   No plot is drawn on the screen.  The matrix YS has LENGTH(TS) rows
%   and as many columns as outputs in SYS.
%   WARNING: TS contains more points than T when U is resampled to reveal
%   intersample oscillations.  To get the response at the samples T only,
%   extract YS(1:d:end,:) where d=round(length(TS)/length(T)).
%
%   For state-space systems,
%        [YS,TS,XS] = LSIM(SYS,U,T,...)
%   also returns the state trajectory XS, a matrix with LENGTH(TS) rows
%   and as many columns as states.
%
%   See also  GENSIG, STEP, IMPULSE, INITIAL.

%   To compute the time response of continuous-time systems, LSIM uses linear
%   interpolation of the input between samples for smooth signals, and
%   zero-order hold for rapidly changing signals like steps or square waves.
%   When the system dynamics are likely to cause intersample oscillations,
%   LSIM first resamples the input using linear interpolation where the signal
%   is smooth and zero-order hold near pulses or steps. Since poorly sampled
%   periodic signals may look discontinuous, the sampling rate should always
%   be high enough to reflect the nature of the signal.

%   Author(s): S. Almy
%   Copyright (c) 1986-98 by The MathWorks, Inc.
%   $Revision: 1.2 $  $Date: 1998/08/26 21:48:34 $

error('LSIM unsupported for FRD systems.  Remove FRDs from system list.');


text:
How to configure a classic single-ball trough without shooter lane
==================================================================

+------------------------------------------------------------------------------+
| Related Config File Sections                                                 |
+==============================================================================+
| :doc:`/config/ball_devices`                                                  |
+------------------------------------------------------------------------------+
| :doc:`/config/playfields`                                                    |
+------------------------------------------------------------------------------+

This guide will show you how to configure MPF to use an older-style single
ball drain without shooter lane. This is the type of configuration that some single-ball
machines use, from EM machines of the 1950s through electronic single ball
machines of the early 1980s.

Here's an example from a Gottlieb Playball (1971 EM):

.. image:: /mechs/images/classic_single_ball_trough_without_shooter_lane_photo.png

1. Add the drain switch
-----------------------

The first step is to add the drain switch to the ``switches:``
section of your machine config file.

.. code-block:: mpf-config

    switches:
      s_drain:
        number: 01

Note that we configured this switches with number ``01``, but you should use the
actual switch number for your control system that the switch is connected to.
(See :doc:`/hardware/numbers` for instructions for each type of control system.)

2. Add the eject coil
---------------------

Next, create the entry in your ``coils:`` section for the drain eject
coil. Again, the name doesn't matter. We'll call it *c_drain_eject* and enter it
like this:

.. code-block:: mpf-config

    coils:
      c_drain_eject:
        number: 03
        default_pulse_ms: 20

Again, the ``number:`` entry in your config will vary depending on your actual
hardware, and again, you can pick whatever name you want for your coil.

You'll also note that we went ahead and entered a ``default_pulse_ms:`` value of 20
which will override the default pulse times of 10ms. It's hard to say
at this point what values you'll actually need. You can always adjust
this at any time. You can play with the exact values in a bit once we
finish getting everything set up.

3. Add your "drain" ball device
-------------------------------

In MPF, anything that holds and releases a ball is a
:doc:`ball device </mechs/ball_devices/index>`. So in your ``ball_devices:``
section, create an entry called ``bd_drain:`` like this: (If you don't have that
section add it now.)

::

    ball_devices:
        bd_drain:

This means that you're creating a ball device called ``bd_drain``.
We use the preface ``bd_`` to indicate that this is a ball device
which makes it easier when we're referencing them later. Then under
your ``bd_drain:`` entry, you'll start entering the
configuration settings for your drain ball device.

* Add ``ball_switches: s_drain`` which means this device will use the *s_drain*
  switch to know whether or not this device has a ball.
* Add ``eject_coil: c_drain_eject`` which is the name of the coil that will
  eject the ball from the drain.
* Add ``tags: drain, home, trough`` which tells MPF that balls entering this
  device mean that a ball has drained from the playfield, that it's ok to start
  a game with a ball here, and that this device is used to store unused balls.
* Set ``eject_timeouts`` to the maximum time the ball can take to return if the
  eject fails.

Your drain device configuration should look now look like this:

.. code-block:: mpf-config

    #! switches:
    #!   s_drain:
    #!     number: 01
    #! coils:
    #!   c_drain_eject:
    #!     number: 03
    #!     default_pulse_ms: 20
    ball_devices:
      bd_drain:
        ball_switches: s_drain
        eject_coil: c_drain_eject
        tags: drain, home, trough
        eject_timeouts: 3s

4. Add the trough as default_source_device
------------------------------------------

Normally you would use your plunger device as source device for your playfield.
But since there is no plunger lane, that means
we have to go back to the trough ball device and use it as source device.
Therefore, you need to add your trough ball device as ``default_source_device`` to
your playfield to tell MPF that this ball device is used to add a new ball
into play.

To do that, add your trough device as ``default_source_device`` in
the default ``playfield``, like this:

.. code-block:: mpf-config

    #! switches:
    #!   s_drain:
    #!     number: 01
    #! coils:
    #!   c_drain_eject:
    #!     number: 03
    #!     default_pulse_ms: 20
    #! ball_devices:
    #!   bd_drain:
    #!     ball_switches: s_drain
    #!     eject_coil: c_drain_eject
    #!     tags: drain, home, trough
    #!     eject_timeouts: 3s
    playfields:
      playfield:
        default_source_device: bd_drain
        tags: default

Then when MPF needs to add a live ball into play, it will eject a ball
from the trough and you're all set!

5. Configure your virtual hardware to start with balls in the trough
--------------------------------------------------------------------

While we're talking about the trough, it's probably a good idea to configure
MPF so that when you start it in virtual mode (with no physical hardware) that
it starts with the trough full of balls. To do this, add a new section to your
config file called ``virtual_platform_start_active_switches:``. (Sorry this
entry name is hilariously long.) As its name implies,
*virtual_platform_start_active_switches:* lets you list the names of
switches that you want to start in the "active" state when you're
running MPF with the virtual platform interfaces.

The reason these only work with the virtual platforms is because if you're
running MPF while connected to a physical pinball machine, it doesn't
really make sense to tell MPF which switches are active since MPF can
read the actual switches from the physical machine. So you can add
this section to your config file, but MPF only reads this section when
you're running with one of the virtual hardware interfaces. To use it,
simply add the section along with a list of the switches you want to
start active. For example:

.. code-block:: mpf-config

    #! switches:
    #!   s_drain:
    #!     number: 01
    virtual_platform_start_active_switches: s_drain

Here's the complete config
--------------------------

.. code-block:: mpf-config

    #config_version=5
    switches:
      s_drain:
        number: 01
    coils:
      c_drain_eject:
        number: 03
        default_pulse_ms: 20
    ball_devices:
      bd_drain:
        ball_switches: s_drain
        eject_coil: c_drain_eject
        tags: drain, home, trough
        eject_timeouts: 3s
    playfields:
      playfield:
        default_source_device: bd_drain
        tags: default
    virtual_platform_start_active_switches: s_drain

What if it did not work?
------------------------

Have a look at our
:doc:`troubleshooting guide for ball_devices </mechs/ball_devices/troubleshooting>`.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    AET

    Copyright (C) 2013 Cognifide Limited

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<suite name="TS1" company="cognifide" project="project">
    <test name="test1" useProxy="true">
        <collect>
            <open/>
            <sleep duration="1500"/>
            <resolution width="640" height="1136" />
            <screen name="iphone5"/>
            <source/>
            <status-codes/>
            <js-errors/>
        </collect>
        <compare>
            <!-- executed for fullScreen/iphone5 -->
            <screen comparator="layout"/>
            <!-- executed only for pageSource -->
            <source comparator="w3c"/>
            <status-codes filterRange="400,999" name="errors"/>
            <status-codes filterCodes="302" name="redirects"/>
            <source comparator="source" compareType="all"/>
            <js-errors/>
        </compare>
        <urls>
            <url href=""/>
            <url href="/test0"/>
            <url href="/test0"/>
            <url href="/test1" name="name-1"/>
            <url href="/test1" name="name-1"/>
            <url href="/test2" name="name-2"/>
            <url href="/test2" name="name-3"/>
            <url href="/test3" description="description-1"/>
            <url href="/test3" description="description-1"/>
            <url href="/test4" description="description-2"/>
            <url href="/test4" description="description-3"/>
        </urls>
    </test>
    <test name="test2" useProxy="false">
        <collect>
            <open/>
            <sleep duration="1500"/>
            <screen/>
            <source/>
        </collect>
        <compare>
            <screen/>
            <source comparator="w3c"/>
        </compare>
        <urls>
            <url href=""/>
            <url href="/test0"/>
            <url href="/test0"/>
            <url href="/test1" name="name-1"/>
            <url href="/test1" name="name-1"/>
            <url href="/test2" name="name-2"/>
            <url href="/test2" name="name-3"/>
            <url href="/test3" description="description-1"/>
            <url href="/test3" description="description-1"/>
            <url href="/test4" description="description-2"/>
            <url href="/test4" description="description-3"/>
        </urls>
    </test>
</suite>


text:
layout: post
date: 2016-11-03
title: "The Dessy Group Dessy - Dessy Collection Style 2896 Sleeveless Floor-Length Sheath/Column"
category: The Dessy Group
tags: [The Dessy Group,Sheath/Column,Sweetheart,Floor-Length,Sleeveless]
---
### The Dessy Group Dessy - Dessy Collection Style 2896
Just **$269.99**
###   Sleeveless Floor-Length Sheath/Column

BRANDS	The Dessy Group

Silhouette	Sheath/Column

Neckline	Sweetheart

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/the-dessy-group/13048-the-dessy-group-dessy-collection-style-2896.html](https://www.readybrides.com/en/the-dessy-group/13048-the-dessy-group-dessy-collection-style-2896.html)


text:
# moar Implementation Details

The Regular Expressions (Regexes) used in Java, C++, etc. are mostly based on Perl Regexes. They are more powerful than the ones known in language theory and describe a superset of the regular languages. Perl Regexes, however are non deterministic by design, and have therefore to be handled with care in user-facing applications (so that a specific user input can not crash the complete program/website). In this case specific deterministic Regex engines are used, which however don't  support backreferences - a feature that can be useful in some applications. Dominik and Markus proposed the notion of deterministic Regexes with backreferences that work with deterministic Memory Occurence Automata (or MOA, these can be thought of as regular automata with variables).

Moar is the first implementation of Regular Expressions based on deterministica MOAs. It aims to support all features provided in Dominik & Markus' paper while also shipping with an API that is inspired by Java's Pattern class. However, we only support a subset of Regexes compared to Java Patterns, in order to simplify the Grammar.

## Utility classes/interfaces

### CharSeq

![CharSeq interface](img/CharSeq.png)

The CharSeq interface is an abstraction from the CharSequence interface that is generally used in Java programs and enables us to support other inputs as well (for example input from a byte sequence like in the Lucene module which can be found in the git repository). Moar only works with codePoints instead of chars. This means that we can support UTF-32 and helps us with unicode character duplicates.

## How are MOAs represented in Code?

In moar, a MOA (Java class: com.github.s4ke.moar.Moa) consists of a set of Variables (basic placeholders for the Variables used in the MOA, nothing fancy) and a Graph representation of the automaton (com.github.s4ke.moar.moa.edgegraph.EdgeGraph).

### Basic classes

In order to get into how the Graph representation is implemented, we first have to explain two basic data classes: Variable and MatchInfo.

##### Variable

![The Variable class](img/Variable.png)

Objects of this type just holds the current contents of the Variables and is implemented as basic as it gets.

##### MatchInfo

![The MatchInfo class](img/MatchInfo.png)

MatchInfo objects are used to hold information about where in the input string the matching process is currently at. The fields are:

- string: what character (or in some cases characters) are currently supposed to be matched. The EfficientString wrapper around character sequences allows us to represent subsequences in an efficient manner by only storing the start and end index together with a reference to the original sequence.

- wholeString: the whole input. The CharSeq interface is used so we can wrap away details of what we are matching. This way we can also support for example Byte-Wise character sequences instead of the default Java Strings.

- pos: the current position in the input string

- lastMatch: the index in the string where the last match ended (otherwise this is set to -1)

### The Graph representation

#### States

We shall now take a look at the nodes of our MOA Graph, the states:

![The State interface](img/state_interface.png)

(Note: getIdx() is the equivalent of the markings in a marked alphabet. This is not really necessary for the implementation, but helps us to identify states faster)

As we can see, the State interface has three different methods that look like they are related to identifying what has to be read in order to go to them during evaluation. However not every method can be used for every type of state. But to explain this we have to go over the different State implementations. After that we give the reasoning behind the three different methods.

##### Static (Basic) States

A static State is the code representation of basic character only states. These states can only contain singular characters.

##### Set States

The theoretical model has no need for these states as it doesn't support character classes. But we want to support these in our Regexes and without creating unnecessarily big numbers of basic states to represent them, which would also mean a high memory footpring. We give a short explanation of character classes in Regexes later, but for now, we just think of them as a Set/range of allowed characters.

In our implementation we represent basic Sets (not often needed, mainly for internal things) via the Java Collection Set and Ranges (like [a-ce-z]) by a Google Guava TreeRangeSet which is space efficient as it only stores the ranges of allowed characters instead of all of them. It also already comes with a negation implementation which helps us with negative sets (e.g.: to allow everything but a's).

In our implementation we use `canConsume(EfficientString string) : boolean` for Static and Set states to check whether the current character can be consumed. The implementation for this is just a basic equality (or containment for the Set state) check.

##### Variable States

Variable States are the code representation of backreferences and only need to have the variable name as a member. As the variables can contain input longer than one character we don't have a separate "canConsume" method. In our matching algorithm we first get the character sequence we have to match in order to traverse into a variable state via `getEdgeString(Map<String, Variable>) : EfficientString` and then check for equality in the remaining input.

##### Bound States

Bound states are used to represent boundary checks in Regexes. We can think of them as basic checks like "am I at the beginning of the input?" or "am I at the end of the input?" (the ^ and the $ anchor in typical regex implementations, respectively). For these we use the `canConsume(MatchInfo matchInfo) : boolean` method during matching.

#### Edges

The edges of the MOAs are represented by a simple Edge object in the EdgeGraph:

![EdgeGraph](img/Edges.png)

Every Edge has a set of MemoryActions that determine just like in the theoretical model how the variable state(s) should change if the edge is used.

#### EdgeGraph

The EdgeGraph is the basic in-code representation of the MOA Graph:

![EdgeGraph](img/EdgeGraph.png)

It stores all the states (field: states) with their corresponding Edges (field: edges) which are duplicated into the other *Edges fields for more convenient and faster access during evaluation.

Note: CurStepHolder is an abstraction enables the EdgeGraph to be reused as it doesn't need to store the current state.

It's most prominent methods are:

- `maximalNextTokenLength(CurStateHolder stateHolder, Map<String, Variable> vars) : int`

  This method is used to compute the length of the next character sequence ("token") to be read. This is primarily needed because of the fact that Variable States can have tokens of any length and because we can have epsilon edges to the sink (just like in the theoretical model, the MOA always has a source and a sink, these are special unique State objects which we talk about in the Regex chapter that also explains how the MOAs are meant to be created). If there are only transitions to Basic or SetStates this returns 1.

- `step(CurStateHolder stateHolder, MatchInfo mi, Map<String, Variable> vars) : StepResult`

  The EdgeGraph tries to perform a step with the current step represented in the stateHolder object with the given info of the MatchInfo object (position, current "token", see above) and the current variable state. Its possible return values are CONSUMED (success), NOT_CONSUMED (the current token was not consumed, this is used for boundary checks which do not consume anything) and REJECTED (no valid transition could be found).

### The Moa class

![Moa class](img/Moa.png)

The Moa class serves as an intermediary entry point for matching. Essentially it could be directly used, but is a bit rough on the edges (therefore it is wrapped into the MoaPattern class, which is explained in the Regexes & Pattern API chapter). Its two most prominent methods are `matcher(CharSeq charSeq) : MoaMatcher` which creates a MoaMatcher object on the given input and the `check(CharSeq charSeq) : boolean` method which immediately checks the input for a complete match.

###  The Matcher

![MoaMatcher interface](img/MoaMatcher.png)

The MoaMatcher interface grants the user more detailed control over how the matching is done. With this interface the user can:

- check for a full-string match with `matches() : boolean`
- check for the next match with `nextMatch() : boolean` (this tries to find the longest sequence in the input that is in the language of the MOA)
- replace the first match of the MOA in the input with `replaceFirst(String replacement) : String` (or all matches with `replaceAll(String replacement) : String`)
- retrieve the variable content via the `getVariableContent(...) : String` methods
- retrieve the start (`getStart() : int`) and the end (`getEnd() : int`) of the last match

It is also meant to be reused (see `reuse(CharSeq charSeq) : MoaMatcher`).

### The MoaPattern

![MoaPattern](img/MoaPattern.png)

This is the main entry class for users and has the same purpose as Java's Pattern class. It doesn't add new functionality over the Moa class, but wraps it into a more beautiful API. It has two separate compile methods that allow for creation from a DSL and from a Regex String. The `build(Moa moa, String regex) : MoaPattern` method is mostly meant for integrators like the JSON export/import module.

## Regexes & Pattern API

Our deterministic Regexes can be translated into code in two separate ways:

### With a Java DSL:

```Java
MoaPattern moa = MoaPattern.compile(
  					// DSL style generation of the Regex
  					Regex.reference( "x" )
                        .bind( "y" )
                        .and( Regex.reference( "y" ).and( "a" ).bind( "x" ) )
                        .plus()
                 );
```

This chaining DSL was initially created to be able to create Regexes without any additional Parser. It is an in code representation of a super set of deterministic Regexes (this means for this to be useful in the deterministic context, we have to check for determinism during compilation). Internally it produces a direct representation of the abstract syntax tree of the regex. For a complete list of the supported methods, take a look at the `com.github.s4ke.moar.regex.Regex` class.

Later, we shall explain how this is translated into a MOA.

### With a Java Pattern-like Regex string:

```Java
// building a Regex from a String
MoaPattern moa = MoaPattern.compile("((?<y>\k<x>)(?<x>\k<y>a))+");
```

The parsing of this Regex string is done via ANTLR v4 and internally uses the DSL API (above). The Grammar is the following:

```java
grammar Regex;

/**
 * Grammar for parsing Perl/Java-style Regexes
 * after: http://www.cs.sfu.ca/~cameron/Teaching/384/99-3/regexp-plg.html
 * but with left recursion eliminated
 */

regex:
    EOF
    | startBoundary? union endBoundary? EOF;

startBoundary :
    START
    | prevMatch;
prevMatch : ESC 'G';

endBoundary :
    EOS
    | endOfInput;
endOfInput : ESC 'z';

union :
    concatenation
    | union '|' concatenation;

concatenation :
    basicRegex
    | basicRegex concatenation;

basicRegex :
    star
    | plus
    | orEpsilon
    | elementaryRegex;

star :
    elementaryRegex '*';
plus :
    elementaryRegex '+';
orEpsilon:
    elementaryRegex '?';

elementaryRegex :
    backRef
    | group
    | set
    | charOrEscaped
    | stockSets
    | ANY;

group :
    '(' (capturingGroup | nonCapturingGroup) ')';
capturingGroup : ('?' '<' groupName '>')? union?;
nonCapturingGroup: '?' ':' union?;
groupName : character+;

backRef :
    ESC number
    | ESC 'k' '<' groupName '>';

set :
    positiveSet
    | negativeSet;
positiveSet	: '[' setItems ']';
negativeSet	: '[^' setItems ']';
setItems :
    setItem
    | setItem setItems;
setItem :
    range
    | charOrEscaped;
range :
    charOrEscaped '-' charOrEscaped;

//should these be handled in the TreeListener?
//if so, we could patch stuff easily without changing
//the grammar
stockSets:
    whiteSpace
    | nonWhiteSpace
    | digit
    | nonDigit
    | wordCharacter
    | nonWordCharacter;
whiteSpace : ESC 's';
nonWhiteSpace : ESC 'S';
digit : ESC 'd';
nonDigit : ESC 'D';
wordCharacter : ESC 'w';
nonWordCharacter : ESC 'W';

charOrEscaped :
    character
    | escapeSeq
    | UTF_32_MARKER utf32 UTF_32_MARKER;
// this odd separation of unused chars and "used chars" is due to ANTLR
// processing in two phases. At first, only the token rules (in CAPS) are
// and then the rules are used. For normal grammars (for programming languages)
// this is fine, but in our case this means this extra (and ugly) work.
// Due to this, every single char that is to be matched must be tokenized
// (the ones that are not part of a NAMED token rule are just implicitly made
// into their own token rule). Every "non special" char
// (the ones that are not explicitly mentioned) is therefore tokenized
// into UNUSED_CHAR.
// This approach is by far easier than a hand written parser, though.
character : (UNUSED_CHARS | ZERO | ONE_TO_NINE | 's' | 'S' | 'd' | 'D' | 'w' | 'W' | 'k' | 'z' | 'G' | ':' | '<' | '>' );
escapeSeq : ESC escapee;
escapee : '[' | ']' | '(' | ')'
    | ESC | ANY | EOS | START | UTF_32_MARKER
    | '*' | '+' | '?'
    | '-' ;
utf32 : (character | escapeSeq)+;

number :  ONE_TO_NINE (ZERO | ONE_TO_NINE)*;

ZERO : '0';
ONE_TO_NINE : [1-9];
ESC : '\\';
ANY : '.';
EOS : '$';
START : '^';
UTF_32_MARKER : '~';

UNUSED_CHARS :
    ~('0' .. '9'
    | '[' | ']' | '(' | ')'
    | '\\' | '.' | '$' | '^'
    | '*' | '+' | '?'
    | ':'
    | 's' | 'S' | 'd' | 'D' | 'w' | 'W' | 'k' | 'z' | 'G'
    | '~');
```

The MoaPattern class behaves in this context similar to Java's native Pattern class and wraps the internal MOA logic for the user. It serves as the entry point to build MoaMatcher objects (similar to Java's Matcher) which encapsulate all the matching logic so that the Pattern itself can be reused as its construction can be expensive.

### From Regex to MOA

![Regex Interface](img/Regex_Interface.png)

Now that we know how the Regexes are represented (as an AST), we shall talk about the process that is used to create a MOA from a Regex. This process is internally used by the MoaPattern class to compile the Regex it is given in the `compile(...)` method into a usable Moa.

#### Accumulate States

In the first phase of the Building process we start at the top of our AST representation of the Regex and let every Regex object contribute the states it has via `contributeStates(Map<String, Variable> variables, Set<State> states, Map<Regex, Map<String, State>> selfRelevant, Supplier<Integer> idxSupplier) : void`.

###### Trivial Sub-Regexes

For trivial sub Regexes (Primitive, SetRegex,  BoundaryRegex, Epsilon) and also for Reference this means that the object has to create a new State with the index supplied by the idxSupplier object (in our case this is a method reference to the getAndIncrement function of a AtomicInteger object, but this can be changed ;)) and add it to the states set (The Reference Regex also creates the Variable it is referring to if it does not exist - this is needed due to the fact that references can occur before the variable is declared) .

In this method the Regex object also has to store the states that it needs later on in the creation in the selfRelevant Map (currently that's all the states that the object created).

###### Non Trivial Sub-Regexes

For the other non trivial Regexes (Plus, Concat and Choice, Binding) the implementation is quite basic as they don't require their own states. These just delegate to their own Sub-Regexes.

#### Accumulate Edges

In the second phase, now that all states are properly known, the edges are added to the moa via `contributeEdges( EdgeGraph edgeGraph, Map<String, Variable> variables, Set<State> states, Map<Regex, Map<String, State>> selfRelevant) : void`. The passed `edgeGraph` already has all the states properly added, so the Regex objects can directly work with the states passed in the `states` set (this is also due to us wanting seperation of concerns during the process of creating the MOA).

In a similar fashion to the accumulation of states the behaviours of the different Regex types differ (by nature of the creation). This is done more straight forward than the accumulation of the states (but uses some of the principles of the delegation to the Sub Regexes for non trivial parents) and every Regex contributes at least one edge in the process (but can be removed by an ancestor Regex).

One important thing is how the sources and sinks of the MOAs are handled, though: If an edge that includes at least one of them is needed, the Regex implementations are required to use the static fields `SRC` and `SNK`of the Moa class (or the EdgeGraph class, they are equivalent) as equality for SRC and SNK is generally checked by equivalence.

Note that the only part of the accumulation of the edges that differs greatly to the one in the paper is how Concat and Plus are built. In Moar this still relies on a older version of the paper that included a special function (see `com.github.s4ke.moar.moa.Moa#f(Set<MemoryAction> a1, Set<MemoryAction> a2) : Set<MemoryAction>`) that recomputed the memory actions. This approach is equivalent to the way this is done in the paper (the paper version should be more easy to understand), but has not been changed in Moar (,yet ?).

##### Determinism

As the Regex DSL can produce non deterministic Regexes as well, we have to make sure that we don't produce a MOA which is non deterministic while adding edges. These checks are implicitly done during compilation and a `NotDeterministicException` is thrown if non determinism is detected. Moar tries to help the user by providing the exact position in the MOA where the non determinism was detected (what Edges were tried to be added for which State).

#### Number variables

For the third phase, as we support References and data retrieval by index of the Binding in our Regexes as well, we have to number all variables. The algorithm is similar to the accumulation of states and edges but is only relevant for the Binding Regex (Plus, Concat and Choice just delegate to their children while all other Sub-Regexes - except for Bindings - have a no-op implementation of their respective `calculateVariableOccurences(Map<String, Variable> variables, Supplier<Integer> varIdxSupplier) : void` method).

## Using MoaPatterns

![MoaPattern](img/MoaPattern.png)

Now that we know how the internals of MoaPatterns work, we can take a quick look into how they are meant to be used.

### MoaPattern Creation

This was already discussed when we described how Regexes are represented in code: We use one of the two static compilation methods `MoaPattern#compile(String Regex) : MoaPattern` / `MoaPattern#compile(Regex regex) : MoaPattern` and then usually **cache the returned object** as the compilation is quite costly.

### Accessing the MoaMatcher

The MoaMatcher is easily accessed via the instance methods `MoaPattern#matcher(...)` which either take a CharSequence or an instance of the CharSeq abstraction we talked about earlier in this draft. How the MoaMatcher works is explained in the introductory chapter.

## JSON Serialization

MoaPatterns can be serialized into a human readable format:

```json
{
  "regex":"^(?<toast>[a-z]b[^b]\\w)\\k<toast>.$",
  "vars":["toast"],
  "states":[
    		{"bound":"^","idx":2},
    		{"set":"[a-z]","idx":3},
    		{"name":"b","idx":4},
    		{"set":"[^b]","idx":5},
    		{"set":"\\w","idx":6},
    		{"ref":"toast","idx":7},
    		{"set":".","idx":8},
    		{"bound":"$","idx":9}
  ],
  "edges":[
    		{"from":0,"to":2},
    		{"from":2,"to":3,"memoryActions":["o(toast)"]},
    		{"from":3,"to":4},
    		{"from":4,"to":5},
    		{"from":5,"to":6},
    		{"from":6,"to":7,"memoryActions":["c(toast)"]},
    		{"from":7,"to":8},
    		{"from":8,"to":9},
    		{"from":9,"to":1}
  ]
}
```

Explanation for the JSON fields:

- regex

  This is for documentation purposes only and couldn't be anything else as the Regexes do not have the same expressive power as hand written MOAs.

- vars

  In this field all used vars of the MOA are listed as simple strings.

- states

  In this field the states are listed. "name" represents Basic states, "set" represents Set states, "ref" represents Variable states and "bound" represents boundary states (the list of supported bounds can be found in com.github.s4ke.moar.regex.BoundConstants). The "idx" must be unique and in the range and >= 2 as SRC and SNK are 0 and 1, respectively.

- edges

  In this field we can specify the edges and possible memoryActions (o = open, c = close, r = reset, used like in the example: r(x) - reset the variable x)

Serialization is done via `com.github.s4ke.moar.json.MoarJSONSerializer#toJSON(MoaPattern pattern) : String` and deserialization via `com.github.s4ke.moar.json.MoarJSONSerializer#fromJSON(String json) : MoaPattern`.

This feature is particularly useful as this allows users to not only hand-write MOAs but also enables them to transmit generic MoaPatterns between applications even if no Regex is available. One can also think of an extra application that allows users to create their own MOAs with a GUI which then are exported to this format for later usage.

## Trying it out

The moar project also has a separate command line tool to try out the functionality (the cli module). Already compiled binaries of it can be found in the realease section on GitHub (https://github.com/s4ke/moar/releases).

Its usage is as follows:

```
C:\Users\Martin\Downloads>java -jar moar-cli-2016-08-23.jar
usage: moar-cli
 -d          only do determinism check
 -help       prints this dialog
 -ls         treat every line of the input string file as one string
 -m          multiline matching mode (search in string for regex)
 -mf <arg>   file/folder to read the MOA from
 -mo <arg>   folder to export the MOAs to (overwrites if existent)
 -r <arg>    regex to test against
 -rf <arg>   file containint the regexes to test against (multiple regexes
             are separated by one empty line)
 -s <arg>    string to test the MOA/Regex against
 -sf <arg>   file to read the input string(s) from
 -t          trim lines if -ls is set
```

## The Lucene Module

Regexes are quite useful if we want to search for data. This is the reason we implemented a proof of concept for a MoaPattern Query for the popular fulltext search engine Lucene in the 'lucene' module. It is currently not as fast as Lucene's own Regex Query type because it does not do optimizations like stopping traversal of the search-tree if it encounters words that will never match. For example all remaining words start with a 'b' if the Regex expects an 'a'. This would require more specific tuning of the moar API for this specific use-case.

It can be used like this:

```
IndexSearcher is = ...
MoaPattern pattern = MoaPattern.compile( "(a*)b\\1" );
MoarQuery tq = new MoarQuery( "tag", pattern );
TopDocs td = searcher.search( query, 10 );
```

Just like with normal Lucene Queries we could now extract the Lucene documents from the TopDocs object. This however, can be looked up in any basic Lucene tutorial.


text:
/*
 * File Layout for: SA.SA_SALCUST on 21-May-01
 *
 * Customer Sales File
 */

#pragma member_alignment save
#pragma nomember_alignment

struct sa_salcust_cdd
{
/* Element = CUSTOMER
   Description = Customer Number */
	char cusnum[10];
/* Element = ACCOUNT
   Description = General Ledger Account Number */
	char account[18];
/* Element = PERIOD
   Description = Fiscal year (YYYY) and Cycle (PP) */
	char period[6];
/* Element =
   Description = Amount */
	double amount;
/* Element = DATE
   Description = PostDate (YYYYMMDD) */
	char postdate[8];
/* Element = TIME
   Description = Post Time (HHMMSS) */
	char posttime[6];
/* Element = BATCH
   Description = Batch number used for process (post,clos */
	char batch[6];
};
#pragma member_alignment restore


text:
package org.keycloak.testsuite.broker;

import static org.keycloak.testsuite.broker.BrokerTestConstants.CLIENT_SECRET;
import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS;
import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_PROVIDER_ID;
import static org.keycloak.testsuite.broker.BrokerTestTools.createIdentityProvider;

import java.util.List;
import java.util.Map;

import org.keycloak.authentication.authenticators.client.JWTClientSecretAuthenticator;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.testsuite.arquillian.SuiteContext;

public class KcOidcBrokerClientSecretJwtTest extends AbstractBrokerTest {

    @Override
    protected BrokerConfiguration getBrokerConfiguration() {
        return new KcOidcBrokerConfigurationWithJWTAuthentication();
    }

    private class KcOidcBrokerConfigurationWithJWTAuthentication extends KcOidcBrokerConfiguration {

        @Override
        public List<ClientRepresentation> createProviderClients(SuiteContext suiteContext) {
            List<ClientRepresentation> clientsRepList = super.createProviderClients(suiteContext);
            log.info("Update provider clients to accept JWT authentication");
            for (ClientRepresentation client: clientsRepList) {
                client.setClientAuthenticatorType(JWTClientSecretAuthenticator.PROVIDER_ID);
                client.setSecret(CLIENT_SECRET);
            }
            return clientsRepList;
        }

        @Override
        public IdentityProviderRepresentation setUpIdentityProvider(SuiteContext suiteContext) {
            IdentityProviderRepresentation idp = createIdentityProvider(IDP_OIDC_ALIAS, IDP_OIDC_PROVIDER_ID);
            Map<String, String> config = idp.getConfig();
            applyDefaultConfiguration(suiteContext, config);
            config.put("clientAuthMethod", OIDCLoginProtocol.CLIENT_SECRET_JWT);
            return idp;
        }

    }
}


text:
package org.springframework.social.facebook.api;

import static org.junit.Assert.*;
import static org.springframework.http.HttpMethod.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;

import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.social.DuplicateStatusException;
import org.springframework.social.ExpiredAuthorizationException;
import org.springframework.social.InsufficientPermissionException;
import org.springframework.social.InvalidAuthorizationException;
import org.springframework.social.ResourceNotFoundException;
import org.springframework.social.RevokedAuthorizationException;
import org.springframework.social.ServerException;
import org.springframework.social.UncategorizedApiException;

public class ErrorHandlingTest extends AbstractFacebookApiTest {

	@Test(expected=UncategorizedApiException.class)
	public void code1HttpsRequired() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-1-httpsRequired")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=ServerException.class)
	public void code2Service() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-2-serviceUnavailable")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=org.springframework.social.InsufficientPermissionException.class)
	public void code10PermissionDenied() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-10-permissionDenied")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=UncategorizedApiException.class)
	public void code100BadRequestUri() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-100-badRequestUrl")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=UncategorizedApiException.class)
	public void code100NonExistingFields() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-100-nonExistingFields")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=InvalidAuthorizationException.class)
	public void code104NoAccessToken() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-104-noAccessToken")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=InvalidAuthorizationException.class)
	public void code190BogusAccessToken() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-190-bogusAccessToken")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=ExpiredAuthorizationException.class)
	public void code190TokenExpired() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-190-tokenExpired")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=RevokedAuthorizationException.class)
	public void code190UserRevokedToken() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-190-userRevokedToken")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=RevokedAuthorizationException.class)
	public void code190UserLoggedOut() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-190-userLoggedOut")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=InsufficientPermissionException.class)
	public void code200NotAuthorizedForAction() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-200-notAuthorizedForAction")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=UncategorizedApiException.class)
	public void code368Blocked() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-368-blocked")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=DuplicateStatusException.class)
	public void code506DuplicatePost() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-506-duplicate")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=ResourceNotFoundException.class)
	public void code803UnknownAlias() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-803-unknownAlias")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

	@Test(expected=ResourceNotFoundException.class)
	public void code803UnknownPath() throws Exception {
		mockServer.expect(requestTo(fbUrl("me")))
			.andExpect(method(GET))
			.andExpect(header("Authorization", "OAuth someAccessToken"))
			.andRespond(withStatus(HttpStatus.BAD_REQUEST).body(jsonResource("error-2500-bogusPath")).contentType(MediaType.APPLICATION_JSON));
		facebook.fetchObject("me", User.class);
		fail();
	}

}