text:
/*jslint nomen:true*/
/*global define*/
define(function (require) {
    'use strict';

    var ActivityListView,
        $ = require('jquery'),
        _ = require('underscore'),
        __ = require('orotranslation/js/translator'),
        routing = require('routing'),
        mediator = require('oroui/js/mediator'),
        DialogWidget = require('oro/dialog-widget'),
        DeleteConfirmation = require('oroui/js/delete-confirmation'),
        BaseCollectionView = require('oroui/js/app/views/base/collection-view');

    ActivityListView = BaseCollectionView.extend({
        options: {
            configuration: {},
            template: null,
            itemTemplate: null,
            itemViewIdPrefix: 'activity-',
            listSelector: '.items.list-box',
            fallbackSelector: '.no-data',
            loadingSelector: '.loading-mask',
            collection: null,
            urls: {
                viewItem: null,
                updateItem: null,
                deleteItem: null
            },
            messages: {},
            ignoreHead: false,
            doNotFetch: false
        },
        listen: {
            'toView collection': '_viewItem',
            'toViewGroup collection': '_viewGroup',
            'toEdit collection': '_editItem',
            'toDelete collection': '_deleteItem'
        },

        initialize: function (options) {
            this.options = _.defaults(options || {}, this.options);

            _.defaults(this.options.messages, {
                editDialogTitle: __('oro.activitylist.edit_title'),
                itemSaved: __('oro.activitylist.item_saved'),
                itemRemoved: __('oro.activitylist.item_removed'),

                deleteConfirmation: __('oro.activitylist.delete_confirmation'),
                deleteItemError: __('oro.activitylist.delete_error'),

                loadItemsError: __('oro.activitylist.load_error'),
                forbiddenError: __('oro.activitylist.forbidden_error'),
                forbiddenActivityDataError: __('oro.activitylist.forbidden_activity_data_view_error')
            });

            this.template = _.template($(this.options.template).html());

            /**
             * on adding activity item listen to "widget:doRefresh:activity-list-widget"
             */
            mediator.on('widget:doRefresh:activity-list-widget', this._reload, this);

            /**
             * on editing activity item listen to "widget_success:activity_list:item:update"
             */
            mediator.on('widget_success:activity_list:item:update', this._reload, this);

            ActivityListView.__super__.initialize.call(this, options);

            if (!this.doNotFetch) {
                this._initPager();
            }
        },

        /**
         * @inheritDoc
         */
        dispose: function () {
            if (this.disposed) {
                return;
            }

            delete this.itemEditDialog;

            mediator.off('widget:doRefresh:activity-list-widget', this._reload, this );
            mediator.off('widget_success:activity_list:item:update', this._reload, this);

            ActivityListView.__super__.dispose.call(this);
        },

        initItemView: function (model) {
            var className = model.getRelatedActivityClass(),
                configuration = this.options.configuration[className];
            if (this.itemView) {
                return new this.itemView({
                    autoRender: false,
                    model: model,
                    configuration: configuration,
                    ignoreHead: this.options.ignoreHead
                });
            } else {
                ActivityListView.__super__.render.apply(this, arguments);
            }
        },

        refresh: function () {
            this.collection.setPage(1);
            this._setPageNumber();
            this._reload();

            mediator.trigger('widget_success:activity_list:refresh');
        },

        _initPager: function () {
            if (this.collection.getPageSize() < this.collection.getCount()) {
                this._toggleNext(true);
            } else {
                this._toggleNext();
            }
            $('.activity-list-widget .pagination-total-num').html(this.collection.pager.total);
            $('.activity-list-widget .pagination-total-count').html(this.collection.getCount());
        },

        /**
         * Fetches loading container element
         *
         *  - returns loading container passed over options,
         *    or the view element as default loading container
         *
         * @returns {HTMLElement|undefined}
         * @protected
         * @override
         */
        _getLoadingContainer: function () {
            var loadingContainer = this.options.loadingContainer;
            if (loadingContainer instanceof $) {
                // fetches loading container from options
                loadingContainer = loadingContainer.get(0);
            }
            if (!loadingContainer) {
                // uses the element as default loading container
                loadingContainer = this.$el.get(0);
            }
            return loadingContainer;
        },

        goto_previous: function () {
            var currentPage = this.collection.getPage();
            if (currentPage > 1) {
                var nextPage = currentPage - 1;
                this.collection.setPage(nextPage);
                if (nextPage == 1) {
                    this._togglePrevious();
                }

                if (this.collection.pager.total > 1) {
                    this._toggleNext(true);
                } else {
                    this._toggleNext();
                }

                this._setPageNumber(nextPage);
                this._reload();
            }
        },

        goto_page: function (e) {
            var that = this.list,
                currentPage = that.collection.getPage(),
                maxPage = that.collection.pager.total,
                nextPage = parseInt($(e.target).val());

            if (_.isNaN(nextPage) || nextPage <= 0 || nextPage > maxPage || nextPage == currentPage) {
                $(e.target).val(currentPage);
                return;
            }

            that._togglePrevious(true);
            that._toggleNext(true);

            if (nextPage == 1) {
                that._togglePrevious();
            }
            if (nextPage == maxPage) {
                that._toggleNext();
            }

            that.collection.setPage(nextPage);
            that._setPageNumber(nextPage);
            that._reload();
        },

        goto_next: function () {
            var currentPage = this.collection.getPage();
            if (currentPage < this.collection.pager.total) {
                var nextPage = currentPage + 1;
                this.collection.setPage(nextPage);
                if (nextPage == this.collection.pager.total) {
                    this._toggleNext();
                } else {
                    this._toggleNext(true);
                }
                this._togglePrevious(true);

                this._setPageNumber(nextPage);
                this._reload();
            }
        },

        _setPageNumber: function (pageNumber) {
            if (_.isUndefined(pageNumber)) {
                pageNumber = 1;
            }
            $('.activity-list-widget .pagination-current').val(pageNumber);
        },

        _togglePrevious: function (enable) {
            if (_.isUndefined(enable)) {
                $('.activity-list-widget .pagination-previous').addClass('disabled');
            } else {
                $('.activity-list-widget .pagination-previous').removeClass('disabled');
            }
        },

        _toggleNext: function (enable) {
            if (_.isUndefined(enable)) {
                $('.activity-list-widget .pagination-next').addClass('disabled');
            } else {
                $('.activity-list-widget .pagination-next').removeClass('disabled');
            }
        },

        _reload: function () {
            var itemViews;
            // please note that _hideLoading will be called in renderAllItems() function
            this._showLoading();
            if (this.options.doNotFetch) {
                this._hideLoading();
                return;
            }
            try {
                // store views state
                this.oldViewStates = {};
                itemViews = this.getItemViews();
                this.oldViewStates = _.map(itemViews, function (view) {
                    return {
                        attrs: view.model.toJSON(),
                        collapsed: view.isCollapsed(),
                        height: view.$el.height()
                    };
                });

                this.collection.fetch({
                    reset: true,
                    success: _.bind(this._initPager, this),
                    error: _.bind(function (collection, response) {
                        this._showLoadItemsError(response.responseJSON || {});
                    }, this)
                });
            } catch (err) {
                this._showLoadItemsError(err);
            }
        },

        renderAllItems: function () {
            var result, i, view, model, oldViewState, contentLoadedPromises, deferredContentLoading;

            result = ActivityListView.__super__.renderAllItems.apply(this, arguments);

            contentLoadedPromises = [];

            if (this.oldViewStates) {
                // restore state
                for (i = 0; i < this.oldViewStates.length; i++) {
                    oldViewState = this.oldViewStates[i];
                    model = this.collection.findSameActivity(oldViewState.attrs);
                    if (model) {
                        view = this.getItemView(model);
                        if (view && !oldViewState.collapsed && view.isCollapsed()) {
                            view.toggle();
                            view.getAccorditionBody().addClass('in');
                            view.getAccorditionToggle().removeClass('collapsed');
                            if (view.model.get('isContentLoading')) {
                                // if model is loading - need to wait until content will be loaded before _hideLoading()
                                // also preserve height during loading
                                view.$el.height(oldViewState.height);
                                deferredContentLoading = $.Deferred();
                                contentLoadedPromises.push(deferredContentLoading);
                                view.model.once(
                                    'change:isContentLoading',
                                    _.bind(function (view, deferredContentLoading) {
                                        // reset height
                                        view.$el.height('');
                                        deferredContentLoading.resolve();
                                    }, this, view, deferredContentLoading)
                                );
                            }
                        }
                    }
                }
                delete this.oldViewStates;
            }

            $.when.apply($, contentLoadedPromises).done(_.bind(function () {
                this._hideLoading();
            }, this));

            return result;
        },

        _viewItem: function (model) {
            this._loadModelContentHTML(model, 'itemView');
        },

        _viewGroup: function (model) {
            this._loadModelContentHTML(model, 'groupView');
        },

        _loadModelContentHTML: function (model, actionKey) {
            var url = this._getUrl(actionKey, model);
            if (model.get('is_loaded') === true) {
                return;
            }
            model.loadContentHTML(url)
                .fail(_.bind(function (response) {
                    if (response.status === 403) {
                        this._showForbiddenActivityDataError(response.responseJSON || {});
                    } else {
                        this._showLoadItemsError(response.responseJSON || {});
                    }
                }, this));
        },

        _editItem: function (model) {
            if (!this.itemEditDialog) {
                var unescapeHTML = function unescapeHtml(unsafe) {
                    return unsafe
                        .replace(/ /g, " ")
                        .replace(/&/g, "&")
                        .replace(/</g, "<")
                        .replace(/>/g, ">")
                        .replace(/"/g, "\"")
                        .replace(/'/g, "'");
                };

                this.itemEditDialog = new DialogWidget({
                    'url': this._getUrl('itemEdit', model),
                    'title': unescapeHTML(model.get('subject')),
                    'regionEnabled': false,
                    'incrementalPosition': false,
                    'alias': 'activity_list:item:update',
                    'dialogOptions': {
                        'modal': true,
                        'resizable': false,
                        'width': 675,
                        'autoResize': true,
                        'close': _.bind(function () {
                            delete this.itemEditDialog;
                        }, this)
                    }
                });

                this.itemEditDialog.render();
            }
        },

        _deleteItem: function (model) {
            var confirm = new DeleteConfirmation({
                content: this._getMessage('deleteConfirmation')
            });
            confirm.on('ok', _.bind(function () {
                this._onItemDelete(model);
            }, this));
            confirm.open();
        },

        _onItemDelete: function (model) {
            this._showLoading();
            try {
                model.destroy({
                    wait: true,
                    url: this._getUrl('itemDelete', model),
                    success: _.bind(function () {
                        mediator.execute('showFlashMessage', 'success', this._getMessage('itemRemoved'));
                        mediator.trigger('widget_success:activity_list:item:delete');

                        this._reload();
                    }, this),
                    error: _.bind(function (model, response) {
                        if (!_.isUndefined(response.status) && response.status === 403) {
                            this._showForbiddenError(response.responseJSON || {});
                        } else {
                            this._showDeleteItemError(response.responseJSON || {});
                        }
                        this._hideLoading();
                    }, this)
                });
            } catch (err) {
                this._showDeleteItemError(err);
                this._hideLoading();
            }
        },

        /**
         * Fetches url for certain action
         *
         * @param {string} actionKey
         * @param {Backbone.Model=}model
         * @returns {string}
         * @protected
         */
        _getUrl: function (actionKey, model) {
            var className = model.getRelatedActivityClass();
            var route = this.options.configuration[className].routes[actionKey];
            return routing.generate(route, {'id': model.get('relatedActivityId')});
        },

        _getMessage: function (labelKey) {
            return this.options.messages[labelKey];
        },

        _showLoading: function () {
            this.subview('loading').show();
        },

        _hideLoading: function () {
            this.subview('loading').hide();
        },

        _showLoadItemsError: function (err) {
            this._showError(this.options.messages.loadItemsError, err);
        },

        _showDeleteItemError: function (err) {
            this._showError(this.options.messages.deleteItemError, err);
        },

        _showForbiddenActivityDataError: function (err) {
            this._showError(this.options.messages.forbiddenActivityDataError, err);
        },

        _showForbiddenError: function (err) {
            this._showError(this.options.messages.forbiddenError, err);
        },

        _showError: function (message, err) {
            this._hideLoading();
            mediator.execute('showErrorMessage', message, err);
        }
    });

    return ActivityListView;
});


text:
<?php

namespace JPI\SoluxBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JPI\CoreBundle\Entity\Entity as BaseEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\ExecutionContextInterface;
use JPI\SoluxBundle\Validator\Constraints as JPIAssert;

/**
 * Famille
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="JPI\SoluxBundle\Entity\FamilleRepository")
 * @JPIAssert\FamilleTauxParticipationExiste
 */
class Famille extends BaseEntity
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(min = "0",max = "255")
     */
    protected $nom;

    /**
     * @var string
     *
     * @ORM\Column(name="prenomChef", type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(min = "0",max = "255")
     */
    protected $prenomChef;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateEntree", type="date")
     * @Assert\Date()
     */
    protected $dateEntree;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateSortie", type="date", nullable=true)
     * @Assert\Date()
     */
    protected $dateSortie;

    /**
     * @var integer
     *
     * @ORM\Column(name="numeroCompte", type="integer", nullable=true)
     * @Assert\Type(type="int")
     * @Assert\Range(min = 0, max = 100000000)
     */
    protected $numeroCompte;

    /**
     * @var string
     *
     * @ORM\Column(name="recettes", type="decimal", precision=12, scale=2)
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     * @Assert\Range(min = -100000, max = 100000000)
     */
    protected $recettes;

    /**
     * @var string
     *
     * @ORM\Column(name="depenses", type="decimal", precision=12, scale=2)
     * @Assert\NotBlank()
     * @Assert\Type(type="float")
     * @Assert\Range(min = -100000, max = 100000000)
     */
    protected $depenses;

    /**
     * @ORM\ManyToOne(targetEntity="JPI\SoluxBundle\Entity\StatutProfessionnel")
     * @ORM\JoinColumn(nullable=false)
     */
    protected $statutProfessionnel;

    /**
     * @ORM\OneToMany(targetEntity="JPI\SoluxBundle\Entity\MembreFamille", mappedBy="famille", cascade={"persist", "remove"}, orphanRemoval=true)
     * @Assert\Valid
     */
    protected $membres;

    public function __construct()
    {
    	$this->membres = new ArrayCollection();
    }

    public function addMembre(MembreFamille $membres)
    {
    	$this->membres[] = $membres;
    	$membres->setFamille($this);
    	return $this;
    }

    public function removeMembre(MembreFamille $membres)
    {
    	$this->membres->removeElement($membres);
    }

    public function getMembres()
    {
    	return $this->membres;
    }

    public function countMembres()
    {
    	return count($this->membres);
    }

    public function sumPourcentageACharge()
    {
    	$lSum = 0;
    	foreach($this->membres as $membre)
    	{
    		$lSum += $membre->getPourcentageACharge();
    	}
    	return $lSum;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nom
     *
     * @param string $nom
     * @return Famille
     */
    public function setNom($nom)
    {
        $this->nom = ucfirst(strtolower($nom));

        return $this;
    }

    /**
     * Get nom
     *
     * @return string
     */
    public function getNom()
    {
        return $this->nom;
    }

    /**
     * Set prenomChef
     *
     * @param string $prenomChef
     * @return Famille
     */
    public function setPrenomChef($prenomChef)
    {
        $this->prenomChef = ucfirst(strtolower($prenomChef));

        return $this;
    }

    /**
     * Get prenomChef
     *
     * @return string
     */
    public function getPrenomChef()
    {
        return $this->prenomChef;
    }

    /**
     * Set dateEntree
     *
     * @param \DateTime $dateEntree
     * @return Famille
     */
    public function setDateEntree($dateEntree)
    {
        $this->dateEntree = $dateEntree;

        return $this;
    }

    /**
     * Get dateEntree
     *
     * @return \DateTime
     */
    public function getDateEntree()
    {
        return $this->dateEntree;
    }

    /**
     * Set dateSortie
     *
     * @param \DateTime $dateSortie
     * @return Famille
     */
    public function setDateSortie($dateSortie)
    {
        $this->dateSortie = $dateSortie;

        return $this;
    }

    /**
     * Get dateSortie
     *
     * @return \DateTime
     */
    public function getDateSortie()
    {
        return $this->dateSortie;
    }

    /**
     * Set numeroCompte
     *
     * @param integer $numeroCompte
     * @return Famille
     */
    public function setNumeroCompte($numeroCompte)
    {
        $this->numeroCompte = $numeroCompte;

        return $this;
    }

    /**
     * Get numeroCompte
     *
     * @return integer
     */
    public function getNumeroCompte()
    {
        return $this->numeroCompte;
    }

    /**
     * Set recettes
     *
     * @param string $recettes
     * @return Famille
     */
    public function setRecettes($recettes)
    {
        $this->recettes = $recettes;

        return $this;
    }

    /**
     * Get recettes
     *
     * @return string
     */
    public function getRecettes()
    {
        return $this->recettes;
    }

    /**
     * Set depenses
     *
     * @param string $depenses
     * @return Famille
     */
    public function setDepenses($depenses)
    {
        $this->depenses = $depenses;

        return $this;
    }

    /**
     * Get depenses
     *
     * @return string
     */
    public function getDepenses()
    {
        return $this->depenses;
    }

    /**
     * Set statutProfessionnel
     *
     * @param \JPI\SoluxBundle\Entity\StatutProfessionnel $statutProfessionnel
     * @return Famille
     */
    public function setStatutProfessionnel(\JPI\SoluxBundle\Entity\StatutProfessionnel $statutProfessionnel)
    {
        $this->statutProfessionnel = $statutProfessionnel;

        return $this;
    }

    /**
     * Get statutProfessionnel
     *
     * @return \JPI\SoluxBundle\Entity\StatutProfessionnel
     */
    public function getStatutProfessionnel()
    {
        return $this->statutProfessionnel;
    }

    /**
     * @Assert\Callback
     */
    public function validateDateDebutFin(ExecutionContextInterface $context)
    {
    	$dF=$this->getDateSortie();

    	if( !is_null($dF)) {
	    	$dO=$this->getDateEntree();

	    	if($dF->format("dd/mm/yy") < $dO->format("dd/mm/yy")){
	    		$context->addViolationAt(
	    				'dateEntree',
	    				'Erreur! la date de sortie est supérieure à la date d\'entrée',
	    				array(),
	    				null
	    		);
	    	}
    	}
    }

    /**
     * @Assert\Callback
     */
    public function isPourcentageAChargeValid(ExecutionContextInterface $context)
    {
    	if($this->sumPourcentageACharge() <= 0)
    	{
    		$context->addViolationAt(
    				'membres',
    				'Il faut au minimum un membre dans la famille',
    				array(),
    				null
    		);
    	}
    }
}

redpajama_set_name: RedPajamaGithub


text:
var expect = chai.expect;

describe('a fully functional JS implementation of the Little Schemer', function () {

  describe('in chapter 3', function() {
    it('should feature a working implementation of isLat', function() {
      expect(isLat(List())).to.be.ok;
      expect(isLat(List('a','b'))).to.be.ok;
      expect(isLat(ArrayToList([['a'],'b']))).to.be.not.ok;
    })
    it('should handle tuples', function() {
      var myTuple = build('a','b');
      expect(size(myTuple)).to.be.equal(2);
      expect(first(myTuple)).to.be.equal('a');
      expect(second(myTuple)).to.be.equal('b');
      safeThrow(function(){first(cons('c', myTuple));}, 'Not a tuple!');
      safeThrow(function(){second(cons('c', myTuple));}, 'Not a tuple!');
    });
  });

  describe('in chapter 4', function() {
    it('should feature a working implementation of pick', function() {
      var myList = ArrayToList([['a'],'b',['c','d']])
      expect(pick(2, myList)).to.be.equal('b');
      expect(pick(2, pick(3, myList))).to.be.equal('d');
      expect(isEmpty(pick(212, myList))).to.be.ok;
    });
  });

  describe('in chapter 5', function() {
    it('should feature a working implementation of eqlist', function() {
      expect(eqlist(ArrayToList([]), ArrayToList([]))).to.be.ok;
      expect(eqlist(ArrayToList(['a']), ArrayToList(['a']))).to.be.ok;
      expect(eqlist(ArrayToList(['a']), ArrayToList(['b']))).to.be.not.ok;
      expect(eqlist(ArrayToList(['a']), ArrayToList(['b','c']))).to.be.not.ok;
      expect(eqlist(ArrayToList([]), ArrayToList(['a']))).to.be.not.ok;
      expect(eqlist(ArrayToList(['a',['b','c']]), ArrayToList(['a',['b','c']]))).to.be.ok;
      expect(eqlist(ArrayToList(['a',['b','c'],'d']), ArrayToList(['a',['b','c']]))).to.be.not.ok;
    });
    it('should feature a working implementation of rember', function() {
      // rember 'a' (a) -> ( )
      expect(eqlist(ArrayToList([]),rember('a', ArrayToList(['a'])))).to.be.ok;
      // rember 'b' (a,(b),b) -> (a,( b))  that's to say it DOES NOT recur inside sublists
      expect(eqlist(ArrayToList(['a',['b']]),rember('b', ArrayToList(['a',['b'],'b'])))).to.be.ok;
      // rember (a,b) ((a,b,(a,b)) -> (a,b)  that's to say it removes only S-list COMPLETELY matched
      expect(eqlist(ArrayToList(['a','b']),rember(ArrayToList(['a','b']), ArrayToList(['a','b',['a','b']])))).to.be.ok;
    });
    it('should feature a working implementation of remberStar', function() {
      // rember* 'a' (a) -> ( )
      expect(eqlist(ArrayToList([]), remberStar('a', ArrayToList(['a'])))).to.be.ok;
      // rember* 'b' (a,(b),b) -> (a,( ))  that's to say it DOES recur inside sublists
      expect(eqlist(ArrayToList(['a',[]]), remberStar('b', ArrayToList(['a',['b'],'b'])))).to.be.ok;
    });
  });

  describe('in chapter 7', function() {
    it('should feature a working implementation of isIntersection', function() {
      expect(isIntersection(List('a'),List('a'))).to.be.ok;
      expect(isIntersection(List(),List())).to.be.not.ok;
      expect(isIntersection(List('a'),List('b'))).to.be.not.ok;
      expect(isIntersection(List('a'),List())).to.be.not.ok;
      expect(isIntersection(List(),List('c'))).to.be.not.ok;
      expect(isIntersection(List('a','b','c'),List('b','a'))).to.be.ok;
      expect(isIntersection(List('a','b','c'),List('z','y','z'))).to.be.not.ok;
      expect(isIntersection(List('a','b','c'),List('z','c','z'))).to.be.ok;
    });
    it('should feature a working implementation of intersection', function() {
      expect(consToString(intersection(List('a'),List('a')))).to.be.equal('[a]');
      expect(consToString(intersection(List(),List()))).to.be.equal('[]');
      expect(consToString(intersection(List('a'),List('b')))).to.be.equal('[]');
      expect(consToString(intersection(List('a'),List()))).to.be.equal('[]');
      expect(consToString(intersection(List(),List('a')))).to.be.equal('[]');
      expect(consToString(intersection(List('a','b','c'),List('b','a')))).to.be.equal('[a,b]');
      expect(consToString(intersection(List('a','b','c'),List('x','y','z')))).to.be.equal('[]');
      expect(consToString(intersection(List('a','b','c'),List('x','c','z')))).to.be.equal('[c]');
    });
    it('should feature a working implementation of intersectall', function() {
      expect(eqlist(EMPTY,intersectall(EMPTY)),'empty set').to.be.ok;  // added after reading Seasoned Schemer, page 38
      var input = ArrayToList([['a','b','c'],['c','a','d','e'],['e','f','g','h','a','b']]);
      expect(eqlist(ArrayToList(['a']),intersectall(input)),'input').to.be.ok;
      var input2 = ArrayToList([[6,'pears','and'],[3,'peaches','and',6,'peppers'],[8,'pears','and',6,'plums'],['and',6,'prunes','with','some','apples']]);
      expect(eqlist(ArrayToList([6,'and']),intersectall(input2)),'input2').to.be.ok;
    });
    it('should feature a working implementation of union', function() {
      expect(consToString(union(List('a'),List('a')))).to.be.equal('[a]');
      expect(consToString(union(List(),List()))).to.be.equal('[]');
      expect(consToString(union(List('a'),List('b')))).to.be.equal('[a,b]');
      expect(consToString(union(List('a'),List()))).to.be.equal('[a]');
      expect(consToString(union(List(),List('a')))).to.be.equal('[a]');
      expect(consToString(union(List('a','b','c'),List('b','a')))).to.be.equal('[c,b,a]');
      expect(consToString(union(List('a','b','c'),List('x','y','z')))).to.be.equal('[a,b,c,x,y,z]');
      expect(consToString(union(List('a','b','c'),List('x','c','z')))).to.be.equal('[a,b,x,c,z]');
    });
    it('should feature a working implementation of isSet', function() {
      expect(isSet(List('a'))).to.be.ok;
      expect(isSet(List())).to.be.ok;
      expect(isSet(List('a','a'))).to.be.not.ok;
      expect(isSet(List('a','b','c'))).to.be.ok;
    });
    it('should feature a working implementation of makeset', function() {
      var madeset = makeset(List('a','b','a'));
      expect(isMember('a',madeset)).to.be.ok;
      expect(isMember('b',madeset)).to.be.ok;
      expect(size(madeset)).to.be.equal(2);
      expect(consToString(madeset)).to.be.equal('[b,a]');
    });
    it('should feature a working implementation of isSubset', function() {
      expect(isSubset(List(), List('a'))).to.be.ok;
      expect(isSubset(List('a'), List())).to.be.not.ok;
      expect(isSubset(List('a'), List('a'))).to.be.ok;
      expect(isSubset(List('a'), List('a','b'))).to.be.ok;
      expect(isSubset(List('b'), List('a','b'))).to.be.ok;
      expect(isSubset(List('b','a'), List('a','b'))).to.be.ok;
    });
    it('should feature a working implementation of equalSet', function() {
      expect(equalSet(List(), List())).to.be.ok;
      expect(equalSet(List(), List('a'))).to.be.not.ok;
      expect(equalSet(List('a'),List())).to.be.not.ok;
      expect(equalSet(List('a','b'),List('b'))).to.be.not.ok;
      expect(equalSet(List('a'), List('a'))).to.be.ok;
      expect(equalSet(List('a','b'), List('b','a'))).to.be.ok;
    });
    it('should feature a working implementation of isMember', function() {
      expect(isMember('a', List('a'))).to.be.ok;
      expect(isMember(List(), List('a'))).to.be.not.ok;
      expect(isMember(List('a'), Nil)).to.be.not.ok;
      expect(isMember('a', List('b','a'))).to.be.ok;
      expect(isMember('a', List('b'))).to.be.not.ok;
    });
  });

  describe('in chapter 8', function() {
    it('should feature a working implementation of multiRember&Co', function() {
      //  make list without, list with and cons their lengths
      var lengthsCollector = function(removed,left) {return cons(size(removed),cons(size(left),EMPTY));}
      var input = List('a',true,123,'b','a')
      var output = multiremberAndCo('a', input, lengthsCollector)
      expect(eqlist(ArrayToList([3,2]), output)).to.be.ok;
    });
    it('should feature a working implementation of multiInsertLr&Co', function() {
      var myCollector = function(insertionResult, numLeftInsertions, numRightInsertions) {
        return pick(numLeftInsertions+numRightInsertions, insertionResult)
      }
      var input = List('chips','and','fish','or','fish','and','chips')
      expect(multiinsertLrAndCo('salty', 'fish', 'chips', input, myCollector)).to.be.equal('salty');
    });
    it('should feature a working implementation of evensOnly', function() {
      expect(eqlist(ArrayToList([2,4,6,8,10]), evensOnly(ArrayToList([1,2,3,4,5,6,7,8,9,10])))).to.be.ok;
    });
    it('should feature a working implementation of evensOnly*', function() {
      var input = ArrayToList([[1],2,3,[4,[7,8,[]],5,6,[9,[10]]]]);
      var output = evensOnlyStar(input);
      expect(equal(ArrayToList([[],2,[4,[8,[]],6,[[10]]]]), output)).to.be.ok;
    });
    it('should feature a working implementation of evensOnly*&Co', function() {
      //var input = ArrayToList([[1],2,3,[4,[7,8,[]],5,6,[9,[10]]]]);
      var input = ArrayToList([[1],2,3,[4,[7,8,[]],5,6,[9,[10]]]]);
      var oddAdder = function (listOfNumbers, productOfEvens, sumOfOdds) {
        return cons(listOfNumbers, cons(productOfEvens, cons(sumOfOdds, EMPTY)));
      }
      var output = evensOnlyStarAndCo(input, oddAdder)
      //expect(equal(ArrayToList([[[],2],2,1]), output)).to.be.ok; // fix me
      expect(equal(ArrayToList([[[],2,[4,[8,[]],6,[[10]]]],3840,25]), output)).to.be.ok;
    });
  });

  describe('in chapter 9', function() {
    describe('it should start by refreshing refactorings in functional programming style:', function() {
      beforeEach(function() {
        /* here is the fixture */
        this.gi = function(x) {return 'gi-' + x}
        expect(this.gi('pippo')).to.be.equal('gi-pippo');
      });

      /* 1) Tennent Correspondence Principle - wrapping a function and immediately invoking the wrapper returns the original function */
      it('Tennent Correspondence Principle', function(){
        var gi = this.gi;
        var teCoPrGi = function(){return gi}
        expect(teCoPrGi()('pippo')).to.be.equal(gi('pippo'));
      });

      /* 2) Introduce Binding -  I may introduce a new variable as long as it's not bound elsewhere */
      it('Introduce Binding', function(){
        var gi = this.gi;
        var inBiGi = function(toBeBound){return gi}
        expect(inBiGi('value given to the variable to be bound but blatantly ignored')('pippo')).to.be.equal(gi('pippo'));
      });

      /* 3) [Invisible] Wrapper Function - wraps and returns the application to itself of the original function */
      it('[Invisible] Wrapper Function', function(){
        var gi = this.gi;
        var wrapperGi = function(v){return (gi)(v)}
        expect(wrapperGi('pippo')).to.be.equal(gi('pippo'));
      });

      /* 4) Inline Function - anonymous bonanza */
      it('Inline Function', function(){
        var gi = this.gi;
        var teCoPrGiInline = function(){return function(x) {return 'gi-' + x}}
        expect(teCoPrGiInline()('pippo')).to.be.equal(gi('pippo'));
        var inBiGiInline = function(toBeBound){return function(x) {return 'gi-' + x}}
        expect(inBiGiInline('value given to the variable to be bound but blatantly ignored')('pippo')).to.be.equal(gi('pippo'));
        var wrapperGiInline = function(v){return (function(x) {return 'gi-' + x})(v)}
        expect(wrapperGiInline('pippo')).to.be.equal(gi('pippo'));
      });
    });

    it('should tread carefully while approaching the Y-combinator - testProtoCombinator', function() {
      var apples = ArrayToList(['a','p','p','l','e','s','a','p','p','l','e','s']);
      expect(MAma(apples)).to.be.equal(12);
    });

    /* NB - the following function is the attempt at page 168 to extract
    make-length(make-length) from the innermost loop. This function is shown to generate an infinite loop
    Instead of "lenght" (which is what the book does) I am calling male(male) a "composite", shortened in "comp".*/
    it.skip('should tread carefully while approaching the Y-combinator - testProtoCombinatorComp', function() {
    var apples = ArrayToList(['a','p','p','l','e','s','a','p','p','l','e','s']);
    /* see lines around 170 in littleFunkyJavascripter.js */
    var MAmaComp = function(MALE) { return (MALE(MALE))}
      (function(male){return function(comp){ return function(list){return isEmpty(list)?0:1+comp(cdr(list))}}(male(male))});
    try{
      var result = MAmaComp(apples);
      expect(true).to.be.not.ok;
      //Assert.isTrue(false, 'MAmaComp should be either not-a-function or be causing too much recursion')
    } catch (err) {
      expect(true).to.be.ok;
    }
   });
    it('should tread carefully while approaching the Y-combinator - testProtoCombinatorOfun', function() {
      var apples = ArrayToList(['a','p','p','l','e','s','a','p','p','l','e','s']);
      // See notes at the definition of MAmaOfun inside littleFunkyJavascripter.js
      var MAmaOfunLocal = function(MALE) { return MALE(MALE)}  // definition inside this test will work
        (function(male){return function(oFun) { return function(list){return isEmpty(list)?0:1+oFun(cdr(list))}}(function(x){return male(male)(x)})});  // male = make-length in inner loop
      expect(MAmaOfunLocal(apples)).to.be.equal(12);
      try{  // using the definition in the library file
        var result = MAmaOfun(apples)   // definition outside this test will NOT work!
        expect(true).to.be.not.ok;
        //Assert.isTrue(false, 'MAmaOfun should be not-a-function')
      } catch (err) {
        expect(true).to.be.ok;
      }
    });
    it('should verify the helper functions that plug into the Y-combinator, in clean TDD-style', function() {
      /* 1) a plain factorial does its job (obviously) */
      var plainFactorial = function(n) {
        return (n==0) ? 1 : n*plainFactorial(n-1)
      }
      expect(plainFactorial(5)).to.be.equal(120);

      /* 2) a factorialWorker was born to be given as argument to a Y combinator */
      var factorialWorker = function (partial) {
        return function(n){
          return (n==0) ? 1 : n*partial(n-1)
        }
      }
      var MyY = function(worker) { return function(MALE) { return MALE(MALE) }
        (function (male) {
          return worker(function(x){return male(male)(x)})
        })
      }
      expect(MyY(factorialWorker)(5)).to.be.equal(120);

      /* 3) assigning a plain factorial to a factorialWorker you get back ... a factorial function!! */
      expect(factorialWorker(plainFactorial)(5)).to.be.equal(120);

      /* as Jim Weirich (http://www.infoq.com/presentations/Y-Combinator) says:
        - a recursive function is the fixed point of its own worker(*)
        - the Y combinator calculates the fixed points of a worker function
        - the Y combinator is the fixpoint combinator
       (*) Jim Weirich calls it an "improver"
      */
    });
    it('...and eventually it should feature a Y-COMBINATOR worth its name!', function() {
      var MyY = function(worker) { return function(MALE) { return MALE(MALE) }  // MALE = make-length in combinator function
        (function (male) {  // male = make-length in argument function
          return worker(function(x){return male(male)(x)})
        })
      }
      var apples = ArrayToList(['a','p','p','l','e','s','a','p','p','l','e','s']);
      var lengthWorker = function(oFun) {
        return function(list){
          return isEmpty(list)?0:1+oFun(cdr(list));
        }
      }
      var myLength = MyY(lengthWorker)
      expect(myLength(apples)).to.be.equal(12);

      var factorialWorker = function(oFun) {
        return function(n) {
          return (n === 0) ? 1 : n * oFun(n - 1);
        }
      }
      var myFactorial = MyY(factorialWorker)
      expect(myFactorial(4)).to.be.equal(24);
    });
  });

  describe('in chapter 10', function() {
    it('should XXX - to be continued', function() {
      var alal = function(xxx){alert(xxx)}
      var myTuple = new_entry('a','b')
      expect(size(myTuple)).to.be.equal(2);
      expect(keys(myTuple)).to.be.equal('a');
      expect(values(myTuple)).to.be.equal('b');

      var myEntry = new_entry(atl(['key1','key2','key3']),atl(['val1','val2','val2']))
      expect(lookup_in_entry('key2',myEntry,alal)).to.be.equal('val2');
      expect(lookup_in_entry('key3',car(extend_table(myEntry,EMPTY)),alal)).to.be.equal('val2');
      var myEntry2 = new_entry(atl(['key11','key2']),atl(['val11','will_be_found']))
      var myTable = extend_table(myEntry2,extend_table(myEntry,EMPTY))
      expect(lookup_in_table('key11',myTable,alal)).to.be.equal('val11');
      expect(lookup_in_table('key2',myTable,alal)).to.be.equal('will_be_found');
    });
  });

  function safeThrow(command, string) {
    try {
      command();
    } catch(err) {
      expect(err).to.be.equal(string);
    }
  }
});


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

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".view.adapter.BlackWordCursorListViewAdapter">

    <data>

        <variable
            name="model"
            type="me.ykrank.s1next.viewmodel.BlackWordViewModel" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?android:attr/activatedBackgroundIndicator"
        android:descendantFocusability="blocksDescendants"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="@dimen/single_line_height"
            android:layout_weight="5"
            android:ellipsize="marquee"
            android:gravity="center"
            android:singleLine="true"
            android:text="@{model.blackword.word}"
            android:textAppearance="@style/TextAppearance.AppCompat.Subhead" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="@dimen/single_line_height"
            android:layout_weight="2"
            android:ellipsize="marquee"
            android:gravity="center"
            android:singleLine="true"
            android:text="@{model.blackword.statRes}"
            android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
            tools:text="@string/blacklist_flag_normal" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="@dimen/single_line_height"
            android:layout_weight="4"
            android:ellipsize="marquee"
            android:gravity="center"
            android:singleLine="true"
            android:text="@{model.blackword.time}"
            android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
            tools:text="2018-12-08 16:38" />

    </LinearLayout>

</layout>


text:
using UnityEngine;

namespace FMODUnity
{
    public abstract class EventHandler : MonoBehaviour
    {
        public string CollisionTag = "";

        protected virtual void Start()
        {
            HandleGameEvent(EmitterGameEvent.ObjectStart);
        }

        protected virtual void OnDestroy()
        {
            HandleGameEvent(EmitterGameEvent.ObjectDestroy);
        }

        private void OnEnable()
        {
            HandleGameEvent(EmitterGameEvent.ObjectEnable);
        }

        private void OnDisable()
        {
            HandleGameEvent(EmitterGameEvent.ObjectDisable);
        }

        #if UNITY_PHYSICS_EXIST
        private void OnTriggerEnter(Collider other)
        {
            if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag) || (other.attachedRigidbody && other.attachedRigidbody.CompareTag(CollisionTag)))
            {
                HandleGameEvent(EmitterGameEvent.TriggerEnter);
            }
        }

        private void OnTriggerExit(Collider other)
        {
            if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag) || (other.attachedRigidbody && other.attachedRigidbody.CompareTag(CollisionTag)))
            {
                HandleGameEvent(EmitterGameEvent.TriggerExit);
            }
        }
        #endif

        #if UNITY_PHYSICS2D_EXIST
        private void OnTriggerEnter2D(Collider2D other)
        {
            if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag))
            {
                HandleGameEvent(EmitterGameEvent.TriggerEnter2D);
            }
        }

        private void OnTriggerExit2D(Collider2D other)
        {
            if (string.IsNullOrEmpty(CollisionTag) || other.CompareTag(CollisionTag))
            {
                HandleGameEvent(EmitterGameEvent.TriggerExit2D);
            }
        }
        #endif

        private void OnCollisionEnter()
        {
            HandleGameEvent(EmitterGameEvent.CollisionEnter);
        }

        private void OnCollisionExit()
        {
            HandleGameEvent(EmitterGameEvent.CollisionExit);
        }

        private void OnCollisionEnter2D()
        {
            HandleGameEvent(EmitterGameEvent.CollisionEnter2D);
        }

        private void OnCollisionExit2D()
        {
            HandleGameEvent(EmitterGameEvent.CollisionExit2D);
        }

        private void OnMouseEnter()
        {
            HandleGameEvent(EmitterGameEvent.MouseEnter);
        }

        private void OnMouseExit()
        {
            HandleGameEvent(EmitterGameEvent.MouseExit);
        }

        private void OnMouseDown()
        {
            HandleGameEvent(EmitterGameEvent.MouseDown);
        }

        private void OnMouseUp()
        {
            HandleGameEvent(EmitterGameEvent.MouseUp);
        }

        protected abstract void HandleGameEvent(EmitterGameEvent gameEvent);
    }
}


text:
from veros import logger, veros_kernel, veros_routine, KernelOutput
from veros.variables import allocate
from veros.distributed import global_max
from veros.core import utilities as mainutils
from veros.core.operators import numpy as npx, for_loop, update, at
from veros.core.streamfunction import island, line_integrals
from veros.core.streamfunction.solvers import get_linear_solver

@veros_routine
def get_isleperim(state):
    """
    preprocess land map using MOMs algorithm for B-grid to determine number of islands
    """
    from veros.state import resize_dimension

    vs = state.variables

    island.isleperim(state)

    # now that we know the number of islands we can resize
    # all arrays depending on that
    nisle = int(global_max(npx.max(vs.land_map)))
    resize_dimension(state, "isle", nisle)
    vs.isle = npx.arange(nisle)

@veros_routine
def streamfunction_init(state):
    """
    prepare for island integrals
    """
    vs = state.variables
    settings = state.settings

    logger.info("Initializing streamfunction method")

    get_isleperim(state)

    boundary_masks_out = boundary_masks(state)
    vs.update(boundary_masks_out)

    # populate linear solver cache
    linear_solver = get_linear_solver(state)

    """
    precalculate time independent boundary components of streamfunction
    """
    forc = allocate(state.dimensions, ("xt", "yt"))

    vs.psin = update(vs.psin, at[...], vs.maskZ[..., -1, npx.newaxis])

    for isle in range(state.dimensions["isle"]):
        logger.info(f" Solving for boundary contribution by island {isle:d}")
        isle_sol = linear_solver.solve(state, forc, vs.psin[:, :, isle], boundary_val=vs.boundary_mask[:, :, isle])
        vs.psin = update(vs.psin, at[:, :, isle], isle_sol)

    vs.psin = mainutils.enforce_boundaries(vs.psin, settings.enable_cyclic_x)

    line_psin_out = island_integrals(state)
    vs.update(line_psin_out)

@veros_kernel
def island_integrals(state):
    """
    precalculate time independent island integrals
    """
    vs = state.variables

    uloc = allocate(state.dimensions, ("xt", "yt", "isle"))
    vloc = allocate(state.dimensions, ("xt", "yt", "isle"))

    uloc = update(
        uloc,
        at[1:, 1:, :],
        -(vs.psin[1:, 1:, :] - vs.psin[1:, :-1, :])
        * vs.maskU[1:, 1:, -1, npx.newaxis]
        / vs.dyt[npx.newaxis, 1:, npx.newaxis]
        * vs.hur[1:, 1:, npx.newaxis],
    )

    vloc = update(
        vloc,
        at[1:, 1:, ...],
        (vs.psin[1:, 1:, :] - vs.psin[:-1, 1:, :])
        * vs.maskV[1:, 1:, -1, npx.newaxis]
        / (vs.cosu[npx.newaxis, 1:, npx.newaxis] * vs.dxt[1:, npx.newaxis, npx.newaxis])
        * vs.hvr[1:, 1:, npx.newaxis],
    )

    vs.line_psin = line_integrals.line_integrals(state, uloc=uloc, vloc=vloc, kind="full")
    return KernelOutput(line_psin=vs.line_psin)

@veros_kernel
def boundary_masks(state):
    """
    now that the number of islands is known we can allocate the rest of the variables
    """
    vs = state.variables
    settings = state.settings

    def loop_body(isle, masks):
        (east_mask, west_mask, south_mask, north_mask, boundary_mask) = masks
        boundary_map = vs.land_map == (isle + 1)

        if settings.enable_cyclic_x:
            east_mask = update(east_mask, at[2:-2, 1:-1, isle], boundary_map[3:-1, 1:-1] & ~boundary_map[3:-1, 2:])
            west_mask = update(west_mask, at[2:-2, 1:-1, isle], boundary_map[2:-2, 2:] & ~boundary_map[2:-2, 1:-1])
            south_mask = update(south_mask, at[2:-2, 1:-1, isle], boundary_map[2:-2, 1:-1] & ~boundary_map[3:-1, 1:-1])
            north_mask = update(north_mask, at[2:-2, 1:-1, isle], boundary_map[3:-1, 2:] & ~boundary_map[2:-2, 2:])
        else:
            east_mask = update(east_mask, at[1:-1, 1:-1, isle], boundary_map[2:, 1:-1] & ~boundary_map[2:, 2:])
            west_mask = update(west_mask, at[1:-1, 1:-1, isle], boundary_map[1:-1, 2:] & ~boundary_map[1:-1, 1:-1])
            south_mask = update(south_mask, at[1:-1, 1:-1, isle], boundary_map[1:-1, 1:-1] & ~boundary_map[2:, 1:-1])
            north_mask = update(north_mask, at[1:-1, 1:-1, isle], boundary_map[2:, 2:] & ~boundary_map[1:-1, 2:])

        boundary_mask = update(
            boundary_mask,
            at[..., isle],
            (east_mask[..., isle] | west_mask[..., isle] | north_mask[..., isle] | south_mask[..., isle]),
        )
        return (east_mask, west_mask, south_mask, north_mask, boundary_mask)

    (
        vs.line_dir_east_mask,
        vs.line_dir_west_mask,
        vs.line_dir_south_mask,
        vs.line_dir_north_mask,
        vs.boundary_mask,
    ) = for_loop(
        0,
        state.dimensions["isle"],
        loop_body,
        (
            vs.line_dir_east_mask,
            vs.line_dir_west_mask,
            vs.line_dir_south_mask,
            vs.line_dir_north_mask,
            vs.boundary_mask,
        ),
    )

    return KernelOutput(
        boundary_mask=vs.boundary_mask,
        line_dir_east_mask=vs.line_dir_east_mask,
        line_dir_west_mask=vs.line_dir_west_mask,
        line_dir_south_mask=vs.line_dir_south_mask,
        line_dir_north_mask=vs.line_dir_north_mask,
    )


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Base extends Controller_Template {

    public $template = 'template';

    public function before() {
        parent::before();

        if (Auth::instance()->logged_in()) {
            $this->template->header = View::factory('templates/logged_in');
        } else {
            $this->template->header = View::factory('templates/header');
        }

        $this->template->content = '';
        $this->template->table = '';
    }
}


text:
"""
Copyright (c) 2004-Present Pivotal Software, Inc.

This program and the accompanying materials are made available under
the terms of the 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.
"""

from unittest2.main import USAGE_AS_MAIN
import tinctest

tinctest.TINCTestProgram.USAGE = USAGE_AS_MAIN
tinctest.TINCTestProgram(module = None,
                testLoader = tinctest.default_test_loader,
                testRunner = tinctest.TINCTestRunner)


text:
<?php

if (class_exists('PHP_CodeSniffer_Standards_AbstractVariableSniff', true) === false) {
    throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_Standards_AbstractVariableSniff not found');
}

/**
 * Parses and verifies the variable doc comment.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

class Squiz_Sniffs_Commenting_VariableCommentSniff extends PHP_CodeSniffer_Standards_AbstractVariableSniff
{

    /**
     * Called to process class member vars.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
     * @param int                  $stackPtr  The position of the current token
     *                                        in the stack passed in $tokens.
     *
     * @return void
     */
    public function processMemberVar(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $ignore = array(
                   T_PUBLIC,
                   T_PRIVATE,
                   T_PROTECTED,
                   T_VAR,
                   T_STATIC,
                   T_WHITESPACE,
                  );

        $commentEnd = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true);
        if ($commentEnd === false
            || ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
            && $tokens[$commentEnd]['code'] !== T_COMMENT)
        ) {
            $phpcsFile->addError('Missing member variable doc comment', $stackPtr, 'Missing');
            return;
        }

        if ($tokens[$commentEnd]['code'] === T_COMMENT) {
            $phpcsFile->addError('You must use "/**" style comments for a member variable comment', $stackPtr, 'WrongStyle');
            return;
        }

        $commentStart = $tokens[$commentEnd]['comment_opener'];

        $foundVar = null;
        foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
            if ($tokens[$tag]['content'] === '@var') {
                if ($foundVar !== null) {
                    $error = 'Only one @var tag is allowed in a member variable comment';
                    $phpcsFile->addError($error, $tag, 'DuplicateVar');
                } else {
                    $foundVar = $tag;
                }
            } else if ($tokens[$tag]['content'] === '@see') {
                // Make sure the tag isn't empty.
                $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd);
                if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) {
                    $error = 'Content missing for @see tag in member variable comment';
                    $phpcsFile->addError($error, $tag, 'EmptySees');
                }
            } else {
                $error = '%s tag is not allowed in member variable comment';
                $data  = array($tokens[$tag]['content']);
                $phpcsFile->addWarning($error, $tag, 'TagNotAllowed', $data);
            }//end if
        }//end foreach

        // The @var tag is the only one we require.
        if ($foundVar === null) {
            $error = 'Missing @var tag in member variable comment';
            $phpcsFile->addError($error, $commentEnd, 'MissingVar');
            return;
        }

        $firstTag = $tokens[$commentStart]['comment_tags'][0];
        if ($foundVar !== null && $tokens[$firstTag]['content'] !== '@var') {
            $error = 'The @var tag must be the first tag in a member variable comment';
            $phpcsFile->addError($error, $foundVar, 'VarOrder');
        }

        // Make sure the tag isn't empty and has the correct padding.
        $string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $foundVar, $commentEnd);
        if ($string === false || $tokens[$string]['line'] !== $tokens[$foundVar]['line']) {
            $error = 'Content missing for @var tag in member variable comment';
            $phpcsFile->addError($error, $foundVar, 'EmptyVar');
            return;
        }

        $varType       = $tokens[($foundVar + 2)]['content'];
        $suggestedType = PHP_CodeSniffer::suggestType($varType);
        if ($varType !== $suggestedType) {
            $error = 'Expected "%s" but found "%s" for @var tag in member variable comment';
            $data  = array(
                      $suggestedType,
                      $varType,
                     );

            $fix = $phpcsFile->addFixableError($error, ($foundVar + 2), 'IncorrectVarType', $data);
            if ($fix === true) {
                $phpcsFile->fixer->replaceToken(($foundVar + 2), $suggestedType);
            }
        }

    }//end processMemberVar()

    /**
     * Called to process a normal variable.
     *
     * Not required for this sniff.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where this token was found.
     * @param int                  $stackPtr  The position where the double quoted
     *                                        string was found.
     *
     * @return void
     */
    protected function processVariable(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {

    }//end processVariable()

    /**
     * Called to process variables found in double quoted strings.
     *
     * Not required for this sniff.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The PHP_CodeSniffer file where this token was found.
     * @param int                  $stackPtr  The position where the double quoted
     *                                        string was found.
     *
     * @return void
     */
    protected function processVariableInString(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {

    }//end processVariableInString()

}//end class


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace WGS
{
    public class soundfm
    {
        public int id;

        #region Define Controls
        Label lblnm = new Label();
        WindowsFormsAero.TextBox nmtxtbx = new WindowsFormsAero.TextBox();
        WindowsFormsAero.Button okbtn = new WindowsFormsAero.Button();
        WindowsFormsAero.Button loadsprbtn = new WindowsFormsAero.Button();
        WindowsFormsAero.Button editsprbtn = new WindowsFormsAero.Button();
        #endregion

        public soundfm(int i)
        {
            id = i;
        }

        public List<Control> soundform(Control tbpg)
        {
            List<Control> ctrls = new List<Control>();

            lblnm.Location = new Point(DPI.CorrectDPIvalues(12,Main.dx),DPI.CorrectDPIvalues(9,Main.dx));
            lblnm.Size = new Size(DPI.CorrectDPIvalues(55, Main.dx), DPI.CorrectDPIvalues(20, Main.dx));
            lblnm.Text = "&Name:";

            nmtxtbx.Location = new Point(DPI.CorrectDPIvalues(73,Main.dx), DPI.CorrectDPIvalues(6,Main.dx));
            nmtxtbx.Size = new Size(DPI.CorrectDPIvalues(136,Main.dx), DPI.CorrectDPIvalues(26,Main.dx));
            nmtxtbx.Text = Main.sounds[id].name;

            okbtn.Text = "&OK";
            okbtn.Dock = DockStyle.Bottom;
            okbtn.Click += okbtn_Click;

            loadsprbtn.Text = "&Load Sound";
            loadsprbtn.Location = new Point(DPI.CorrectDPIvalues(45, Main.dx), DPI.CorrectDPIvalues(51, Main.dx));
            loadsprbtn.Size = new Size(DPI.CorrectDPIvalues(164,Main.dx), DPI.CorrectDPIvalues(28,Main.dx));

            editsprbtn.Text = "&Edit Sound";
            editsprbtn.Location = new Point(DPI.CorrectDPIvalues(45, Main.dx), DPI.CorrectDPIvalues(85, Main.dx));
            editsprbtn.Size = new Size(DPI.CorrectDPIvalues(164, Main.dx), DPI.CorrectDPIvalues(28, Main.dx));

            ctrls.Add(lblnm);
            ctrls.Add(nmtxtbx);
            ctrls.Add(okbtn);
            ctrls.Add(loadsprbtn);
            ctrls.Add(editsprbtn);

            return ctrls;
        }

        private void okbtn_Click(object sender, EventArgs e)
        {
            if (Main.RenameResource(Main.sounds[id], nmtxtbx.Text))
            {
                Program.mn.maintbctrl.TabPages[Program.mn.maintbctrl.SelectedIndex].Dispose();

                if (Program.mn.maintbctrl.TabPages.Count < 1)
                {
                    Program.mn.maintbctrl.Visible = false;
                }
                Program.mn.UpdateResourceList();
            }
        }
    }
}


text:
require 'rails_helper'

RSpec.describe Reference, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
{-# OPTIONS -O2 -Wall #-}

module Drool.Types (
   RotationVector(..),
   Signal(..),
-- SignalBuffer(..),
   SignalList(..),
   SignalSource(..),
   RenderPerspective(..),
   rvector_x, rvector_y, rvector_z,
   newSignal,
-- newSignalBuffer,
   newSignalList,
   getSignal,
   getRecentSignal,
   getLastSignal,
   getBufferSample,
   getSignalSample
) where

import Data.Array.IO
import Graphics.Rendering.OpenGL
import Drool.Utils.SigGen ( SValue )

-- A signal is an array of samples (sample type is GLfloat):
newtype Signal = CSignal { signalArray :: IOUArray Int Float }

-- A signal buffer is an array of signals, signal[t] = signal_t
-- In effect, a two-dimensional matrix over samples.
-- newtype SignalBuffer = CSignalBuffer { signalBufferArray :: IOArray Int Signal }

-- Would perform better in case a list of Signal is too slow:
-- newtype SignalQueue = CSignalQueue { signalQueueArray :: MFifoQOf IO Signal }

newtype SignalList = CSignalList { signalList :: [Signal] }

data SignalSource = Microphone | TestSignal | File
  deriving ( Eq, Show, Read )

-- Type for translation vector
-- newtype TVector = TVector (Vector3 GLfloat GLfloat GLfloat)
-- Type for rotation vector
data RotationVector = CRotationVector { rotX :: GLfloat, rotY :: GLfloat, rotZ :: GLfloat }
  deriving ( Show, Read )

data RenderPerspective = Top | Side | Front | Isometric
  deriving ( Show, Read )

rvector_x :: (a,a,a) -> a
rvector_x (x,_,_) = x

rvector_y :: (a,a,a) -> a
rvector_y (_,y,_) = y

rvector_z :: (a,a,a) -> a
rvector_z (_,_,z) = z

newSignal :: IO Signal
newSignal = fmap CSignal $ newArray(0,10) (0::Float) :: IO Signal

{-
newSignalBuffer :: Int -> IO SignalBuffer
newSignalBuffer size = do
  blankSignal <- newSignal
  fmap CSignalBuffer $ newArray(0,size) (blankSignal) :: IO SignalBuffer
-}

newSignalList :: Int -> Signal -> [Signal]
newSignalList size el = if size > 0 then (el::Signal) : (newSignalList (size-1) el) else []

-- getSignal signalBuf time_idx = readArray (signalBufferArray signalBuf) time_idx
getSignal :: SignalList -> Int -> Signal
getSignal signals time_idx = (signalList signals) !! time_idx

-- Using !! here is okay as signal buffer passed is supposed to be really short (<= 3 signals).
getRecentSignal :: SignalList -> Maybe Signal
getRecentSignal signals@(CSignalList (_:_)) = Just $ sigList !! 0
  where sigList = signalList signals
getRecentSignal (CSignalList []) = Nothing

getLastSignal :: SignalList -> Maybe Signal
getLastSignal signals@(CSignalList (_:_)) = Just $ last sigList
  where sigList = signalList signals
getLastSignal (CSignalList []) = Nothing

{-
getBufferSample signalBuf time_idx sample_idx = do
  signal <- getSignal signalBuf time_idx
  sample <- readArray (signalArray signal) sample_idx
  return sample
-}

getBufferSample :: SignalList -> Int -> Int -> IO Float
getBufferSample signals time_idx sample_idx = do
  let signal = getSignal signals time_idx
  sample <- readArray (signalArray signal) sample_idx
  return sample

getSignalSample :: Signal -> Int -> IO SValue
getSignalSample signal sample_idx = do
  sample <- readArray (signalArray signal) sample_idx
  return sample


text:
'use strict';
var Discovery = require('../index.js').Discovery;
var discover = new Discovery();

discover.on('available', function(name, data, reason) {
  console.log('available ',name);
  console.log('data',data);
  console.log('reason',reason);
  var obj = {a: 1, b: '2', c: true, d: {e: 333}};
  discover.sendEvent('Hello', obj);

  console.log(name,':','available:',reason);
  console.log(data);
});

discover.on('unavailable', function(name, data, reason) {
  console.log(name,':','unavailable:',reason);
  console.log(data);
});


text:
<?php

require('components/class.post.php');

get_header(); ?>

 <?php
            if (have_posts()) {
                the_post();

                $options = new Post_Options();
                $options->Get_Footer_Options()->Disable_Navigation();

                Post::Render($options);
            }
            else {
                Post::Render_Content_Not_Found();
            }

            ?>

            <?php get_sidebar(Sidebars::Right); ?>

<?php get_footer(); ?>


text:
"""
Configuration additions for TiddlyWebWiki.

base_tiddlywiki: the file location of the tiddlywiki file into which
Tiddlers are pushed when creating outgoing TiddlyWiki representations
from TiddlyWeb. This can be an absolute path or relative to the startup
directory of the server.
"""

try:
    from pkg_resources import resource_filename
except ImportError:
    from tiddlywebplugins.utils import resource_filename

PACKAGE_NAME = 'tiddlywebwiki'
BASE_TIDDLYWIKI = resource_filename(PACKAGE_NAME, 'resources/empty.html')

config = {
    'instance_pkgstores': ['tiddlywebplugins.console', PACKAGE_NAME],
    'base_tiddlywiki': BASE_TIDDLYWIKI,
    'extension_types': {
        'wiki': 'text/x-tiddlywiki',
    },
    'serializers': {
        'text/x-tiddlywiki': ['tiddlywebwiki.serialization',
            'text/html; charset=UTF-8'],
    },
    'tiddlywebwiki.friendlywiki': True,
    'wsgi_server': 'tiddlywebplugins.cherrypy'
}


text:
#import "UIView.h"

@class NSString, PTIconSettings, UIImage, UIImageView, _UILegibilityLabel, _UILegibilityView;

@interface PTIcon : UIView
{
    UIImage *_image;
    NSString *_title;
    _UILegibilityLabel *_label;
    _UILegibilityView *_iconLegibilityView;
    UIImageView *_imageView;
    PTIconSettings *_iconSettings;
    struct __CFRunLoopObserver *_runLoopObserver;
    CDStruct_7d841a06 _imageStatistics;
}

+ (id)iconWithImageName:(id)arg1 title:(id)arg2;
+ (id)iconWithImage:(id)arg1 title:(id)arg2;
@property(nonatomic) struct __CFRunLoopObserver *runLoopObserver; // @synthesize runLoopObserver=_runLoopObserver;
@property(nonatomic) CDStruct_7d841a06 imageStatistics; // @synthesize imageStatistics=_imageStatistics;
@property(retain, nonatomic) PTIconSettings *iconSettings; // @synthesize iconSettings=_iconSettings;
@property(retain, nonatomic) UIImageView *imageView; // @synthesize imageView=_imageView;
@property(retain, nonatomic) _UILegibilityView *iconLegibilityView; // @synthesize iconLegibilityView=_iconLegibilityView;
@property(retain, nonatomic) _UILegibilityLabel *label; // @synthesize label=_label;
@property(copy, nonatomic) NSString *title; // @synthesize title=_title;
@property(retain, nonatomic) UIImage *image; // @synthesize image=_image;
- (void).cxx_destruct;
- (void)layoutSubviews;
- (struct CGRect)labelFrame;
- (id)init;

@end


text:
package com.temple.util.net.http;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;

import com.temple.util.net.HttpDomain;

public final class HTTPFileGetter extends AbstractHTTPGetter<File> {

	private static final long serialVersionUID = 1L;

	public static final int BUFFER_SIZE = 8192; // in bytes

	private final File downloadFolder;

	public HTTPFileGetter(HttpDomain<?> domain, File downloadFolder) {
		super(domain);
		this.downloadFolder = downloadFolder;
	}

	@Override
	protected File getFile0(HttpURLConnection con, String path) throws IOException {
		final byte[] cbuf = new byte[HTTPFileGetter.BUFFER_SIZE];
		File f = null;
		final String hf = con.getHeaderField("Content-Disposition");
		if (hf != null) {
			final int offset = hf.indexOf('=');
			if (offset > 0) {
				f = new File(this.downloadFolder, hf.substring(offset + 1));
			}
		}
		if (f == null) {
			f = File.createTempFile("temple_", "_download", this.downloadFolder);
		}
		try (DataInputStream is = new DataInputStream(con.getInputStream()); DataOutputStream os = new DataOutputStream(new FileOutputStream(f))) {
			int l = 0;
			while (l != -1) {
				l = is.read(cbuf);
				if (l > 0) {
					os.write(cbuf, 0, l);
				}
			}
		}
		return f;
	}
}


text:
/*
 * Tests of API
 *
 * How to run the tests:
 * > npx cross-env TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true npx mocha test/api.ts --require ts-node/register
 *
 * To specify test:
 * > npx cross-env TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true npx mocha test/api.ts --require ts-node/register -g 'test name'
 */
/*
process.env.NODE_ENV = 'test';

import * as assert from 'assert';
import * as childProcess from 'child_process';
import { async, signup, request, post, react, uploadFile } from './utils';

describe('API', () => {
	let p: childProcess.ChildProcess;

	beforeEach(done => {
		p = childProcess.spawn('node', [__dirname + '/../index.js'], {
			stdio: ['inherit', 'inherit', 'ipc'],
			env: { NODE_ENV: 'test' }
		});
		p.on('message', message => {
			if (message === 'ok') {
				done();
			}
		});
	});

	afterEach(() => {
		p.kill();
	});

	describe('signup', () => {
		it('不正なユーザー名でアカウントが作成できない', async(async () => {
			const res = await request('/signup', {
				username: 'test.',
				password: 'test'
			});
			assert.strictEqual(res.status, 400);
		}));

		it('空のパスワードでアカウントが作成できない', async(async () => {
			const res = await request('/signup', {
				username: 'test',
				password: ''
			});
			assert.strictEqual(res.status, 400);
		}));

		it('正しくアカウントが作成できる', async(async () => {
			const me = {
				username: 'test',
				password: 'test'
			};

			const res = await request('/signup', me);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.username, me.username);
		}));

		it('同じユーザー名のアカウントは作成できない', async(async () => {
			await signup({
				username: 'test'
			});

			const res = await request('/signup', {
				username: 'test',
				password: 'test'
			});

			assert.strictEqual(res.status, 400);
		}));
	});

	describe('signin', () => {
		it('間違ったパスワードでサインインできない', async(async () => {
			await signup({
				username: 'test',
				password: 'foo'
			});

			const res = await request('/signin', {
				username: 'test',
				password: 'bar'
			});

			assert.strictEqual(res.status, 403);
		}));

		it('クエリをインジェクションできない', async(async () => {
			await signup({
				username: 'test'
			});

			const res = await request('/signin', {
				username: 'test',
				password: {
					$gt: ''
				}
			});

			assert.strictEqual(res.status, 400);
		}));

		it('正しい情報でサインインできる', async(async () => {
			await signup({
				username: 'test',
				password: 'foo'
			});

			const res = await request('/signin', {
				username: 'test',
				password: 'foo'
			});

			assert.strictEqual(res.status, 200);
		}));
	});

	describe('i/update', () => {
		it('アカウント設定を更新できる', async(async () => {
			const me = await signup();

			const myName = '大室櫻子';
			const myLocation = '七森中';
			const myBirthday = '2000-09-07';

			const res = await request('/i/update', {
				name: myName,
				location: myLocation,
				birthday: myBirthday
			}, me);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.name, myName);
			assert.strictEqual(res.body.location, myLocation);
			assert.strictEqual(res.body.birthday, myBirthday);
		}));

		it('名前を空白にできない', async(async () => {
			const me = await signup();
			const res = await request('/i/update', {
				name: ' '
			}, me);
			assert.strictEqual(res.status, 400);
		}));

		it('誕生日の設定を削除できる', async(async () => {
			const me = await signup();
			await request('/i/update', {
				birthday: '2000-09-07'
			}, me);

			const res = await request('/i/update', {
				birthday: null
			}, me);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.birthday, null);
		}));

		it('不正な誕生日の形式で怒られる', async(async () => {
			const me = await signup();
			const res = await request('/i/update', {
				birthday: '2000/09/07'
			}, me);
			assert.strictEqual(res.status, 400);
		}));
	});

	describe('users/show', () => {
		it('ユーザーが取得できる', async(async () => {
			const me = await signup();

			const res = await request('/users/show', {
				userId: me.id
			}, me);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.id, me.id);
		}));

		it('ユーザーが存在しなかったら怒る', async(async () => {
			const res = await request('/users/show', {
				userId: '000000000000000000000000'
			});
			assert.strictEqual(res.status, 400);
		}));

		it('間違ったIDで怒られる', async(async () => {
			const res = await request('/users/show', {
				userId: 'kyoppie'
			});
			assert.strictEqual(res.status, 400);
		}));
	});

	describe('notes/show', () => {
		it('投稿が取得できる', async(async () => {
			const me = await signup();
			const myPost = await post(me, {
				text: 'test'
			});

			const res = await request('/notes/show', {
				noteId: myPost.id
			}, me);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.id, myPost.id);
			assert.strictEqual(res.body.text, myPost.text);
		}));

		it('投稿が存在しなかったら怒る', async(async () => {
			const res = await request('/notes/show', {
				noteId: '000000000000000000000000'
			});
			assert.strictEqual(res.status, 400);
		}));

		it('間違ったIDで怒られる', async(async () => {
			const res = await request('/notes/show', {
				noteId: 'kyoppie'
			});
			assert.strictEqual(res.status, 400);
		}));
	});

	describe('notes/reactions/create', () => {
		it('リアクションできる', async(async () => {
			const bob = await signup({ username: 'bob' });
			const bobPost = await post(bob);

			const alice = await signup({ username: 'alice' });
			const res = await request('/notes/reactions/create', {
				noteId: bobPost.id,
				reaction: 'like'
			}, alice);

			assert.strictEqual(res.status, 204);
		}));

		it('自分の投稿にはリアクションできない', async(async () => {
			const me = await signup();
			const myPost = await post(me);

			const res = await request('/notes/reactions/create', {
				noteId: myPost.id,
				reaction: 'like'
			}, me);

			assert.strictEqual(res.status, 400);
		}));

		it('二重にリアクションできない', async(async () => {
			const bob = await signup({ username: 'bob' });
			const bobPost = await post(bob);

			const alice = await signup({ username: 'alice' });
			await react(alice, bobPost, 'like');

			const res = await request('/notes/reactions/create', {
				noteId: bobPost.id,
				reaction: 'like'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('存在しない投稿にはリアクションできない', async(async () => {
			const me = await signup();

			const res = await request('/notes/reactions/create', {
				noteId: '000000000000000000000000',
				reaction: 'like'
			}, me);

			assert.strictEqual(res.status, 400);
		}));

		it('空のパラメータで怒られる', async(async () => {
			const me = await signup();

			const res = await request('/notes/reactions/create', {}, me);

			assert.strictEqual(res.status, 400);
		}));

		it('間違ったIDで怒られる', async(async () => {
			const me = await signup();

			const res = await request('/notes/reactions/create', {
				noteId: 'kyoppie',
				reaction: 'like'
			}, me);

			assert.strictEqual(res.status, 400);
		}));
	});

	describe('following/create', () => {
		it('フォローできる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });

			const res = await request('/following/create', {
				userId: alice.id
			}, bob);

			assert.strictEqual(res.status, 200);
		}));

		it('既にフォローしている場合は怒る', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });
			await request('/following/create', {
				userId: alice.id
			}, bob);

			const res = await request('/following/create', {
				userId: alice.id
			}, bob);

			assert.strictEqual(res.status, 400);
		}));

		it('存在しないユーザーはフォローできない', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/create', {
				userId: '000000000000000000000000'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('自分自身はフォローできない', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/create', {
				userId: alice.id
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('空のパラメータで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/create', {}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('間違ったIDで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/create', {
				userId: 'foo'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));
	});

	describe('following/delete', () => {
		it('フォロー解除できる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });
			await request('/following/create', {
				userId: alice.id
			}, bob);

			const res = await request('/following/delete', {
				userId: alice.id
			}, bob);

			assert.strictEqual(res.status, 200);
		}));

		it('フォローしていない場合は怒る', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });

			const res = await request('/following/delete', {
				userId: alice.id
			}, bob);

			assert.strictEqual(res.status, 400);
		}));

		it('存在しないユーザーはフォロー解除できない', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/delete', {
				userId: '000000000000000000000000'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('自分自身はフォロー解除できない', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/delete', {
				userId: alice.id
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('空のパラメータで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/delete', {}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('間違ったIDで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/following/delete', {
				userId: 'kyoppie'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));
	});

	describe('drive', () => {
		it('ドライブ情報を取得できる', async(async () => {
			const bob = await signup({ username: 'bob' });
			await uploadFile({
				userId: me.id,
				size: 256
			});
			await uploadFile({
				userId: me.id,
				size: 512
			});
			await uploadFile({
				userId: me.id,
				size: 1024
			});
			const res = await request('/drive', {}, me);
			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			expect(res.body).have.property('usage').eql(1792);
		}));
	});

	describe('drive/files/create', () => {
		it('ファイルを作成できる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await uploadFile(alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.name, 'Lenna.png');
		}));

		it('ファイルに名前を付けられる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await assert.request(server)
				.post('/drive/files/create')
				.field('i', alice.token)
				.field('name', 'Belmond.png')
				.attach('file', fs.readFileSync(__dirname + '/resources/Lenna.png'), 'Lenna.png');

			expect(res).have.status(200);
			expect(res.body).be.a('object');
			expect(res.body).have.property('name').eql('Belmond.png');
		}));

		it('ファイル無しで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/drive/files/create', {}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('SVGファイルを作成できる', async(async () => {
			const izumi = await signup({ username: 'izumi' });

			const res = await uploadFile(izumi, __dirname + '/resources/image.svg');

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.name, 'image.svg');
			assert.strictEqual(res.body.type, 'image/svg+xml');
		}));
	});

	describe('drive/files/update', () => {
		it('名前を更新できる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const file = await uploadFile(alice);
			const newName = 'いちごパスタ.png';

			const res = await request('/drive/files/update', {
				fileId: file.id,
				name: newName
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.name, newName);
		}));

		it('他人のファイルは更新できない', async(async () => {
			const bob = await signup({ username: 'bob' });
			const alice = await signup({ username: 'alice' });
			const file = await uploadFile(bob);

			const res = await request('/drive/files/update', {
				fileId: file.id,
				name: 'いちごパスタ.png'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('親フォルダを更新できる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const file = await uploadFile(alice);
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;

			const res = await request('/drive/files/update', {
				fileId: file.id,
				folderId: folder.id
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.folderId, folder.id);
		}));

		it('親フォルダを無しにできる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const file = await uploadFile(alice);

			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;

			await request('/drive/files/update', {
				fileId: file.id,
				folderId: folder.id
			}, alice);

			const res = await request('/drive/files/update', {
				fileId: file.id,
				folderId: null
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.folderId, null);
		}));

		it('他人のフォルダには入れられない', async(async () => {
			const bob = await signup({ username: 'bob' });
			const alice = await signup({ username: 'alice' });
			const file = await uploadFile(alice);
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, bob)).body;

			const res = await request('/drive/files/update', {
				fileId: file.id,
				folderId: folder.id
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('存在しないフォルダで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const file = await uploadFile(alice);

			const res = await request('/drive/files/update', {
				fileId: file.id,
				folderId: '000000000000000000000000'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('不正なフォルダIDで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const file = await uploadFile(alice);

			const res = await request('/drive/files/update', {
				fileId: file.id,
				folderId: 'foo'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('ファイルが存在しなかったら怒る', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/drive/files/update', {
				fileId: '000000000000000000000000',
				name: 'いちごパスタ.png'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('間違ったIDで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/drive/files/update', {
				fileId: 'kyoppie',
				name: 'いちごパスタ.png'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));
	});

	describe('drive/folders/create', () => {
		it('フォルダを作成できる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/drive/folders/create', {
				name: 'test'
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.name, 'test');
		}));
	});

	describe('drive/folders/update', () => {
		it('名前を更新できる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				name: 'new name'
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.name, 'new name');
		}));

		it('他人のフォルダを更新できない', async(async () => {
			const bob = await signup({ username: 'bob' });
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, bob)).body;

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				name: 'new name'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('親フォルダを更新できる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;
			const parentFolder = (await request('/drive/folders/create', {
				name: 'parent'
			}, alice)).body;

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				parentId: parentFolder.id
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.parentId, parentFolder.id);
		}));

		it('親フォルダを無しに更新できる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;
			const parentFolder = (await request('/drive/folders/create', {
				name: 'parent'
			}, alice)).body;
			await request('/drive/folders/update', {
				folderId: folder.id,
				parentId: parentFolder.id
			}, alice);

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				parentId: null
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.parentId, null);
		}));

		it('他人のフォルダを親フォルダに設定できない', async(async () => {
			const bob = await signup({ username: 'bob' });
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;
			const parentFolder = (await request('/drive/folders/create', {
				name: 'parent'
			}, bob)).body;

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				parentId: parentFolder.id
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('フォルダが循環するような構造にできない', async(async () => {
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;
			const parentFolder = (await request('/drive/folders/create', {
				name: 'parent'
			}, alice)).body;
			await request('/drive/folders/update', {
				folderId: parentFolder.id,
				parentId: folder.id
			}, alice);

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				parentId: parentFolder.id
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('フォルダが循環するような構造にできない(再帰的)', async(async () => {
			const alice = await signup({ username: 'alice' });
			const folderA = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;
			const folderB = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;
			const folderC = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;
			await request('/drive/folders/update', {
				folderId: folderB.id,
				parentId: folderA.id
			}, alice);
			await request('/drive/folders/update', {
				folderId: folderC.id,
				parentId: folderB.id
			}, alice);

			const res = await request('/drive/folders/update', {
				folderId: folderA.id,
				parentId: folderC.id
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('フォルダが循環するような構造にできない(自身)', async(async () => {
			const arisugawa = await signup({ username: 'arisugawa' });
			const folderA = (await request('/drive/folders/create', {
				name: 'test'
			}, arisugawa)).body;

			const res = await request('/drive/folders/update', {
				folderId: folderA.id,
				parentId: folderA.id
			}, arisugawa);

			assert.strictEqual(res.status, 400);
		}));

		it('存在しない親フォルダを設定できない', async(async () => {
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				parentId: '000000000000000000000000'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('不正な親フォルダIDで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const folder = (await request('/drive/folders/create', {
				name: 'test'
			}, alice)).body;

			const res = await request('/drive/folders/update', {
				folderId: folder.id,
				parentId: 'foo'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('存在しないフォルダを更新できない', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/drive/folders/update', {
				folderId: '000000000000000000000000'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('不正なフォルダIDで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/drive/folders/update', {
				folderId: 'foo'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));
	});

	describe('messaging/messages/create', () => {
		it('メッセージを送信できる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });

			const res = await request('/messaging/messages/create', {
				userId: bob.id,
				text: 'test'
			}, alice);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true);
			assert.strictEqual(res.body.text, 'test');
		}));

		it('自分自身にはメッセージを送信できない', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/messaging/messages/create', {
				userId: alice.id,
				text: 'Yo'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('存在しないユーザーにはメッセージを送信できない', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/messaging/messages/create', {
				userId: '000000000000000000000000',
				text: 'test'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('不正なユーザーIDで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });

			const res = await request('/messaging/messages/create', {
				userId: 'foo',
				text: 'test'
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('テキストが無くて怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });

			const res = await request('/messaging/messages/create', {
				userId: bob.id
			}, alice);

			assert.strictEqual(res.status, 400);
		}));

		it('文字数オーバーで怒られる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });

			const res = await request('/messaging/messages/create', {
				userId: bob.id,
				text: '!'.repeat(1001)
			}, alice);

			assert.strictEqual(res.status, 400);
		}));
	});

	describe('notes/replies', () => {
		it('自分に閲覧権限のない投稿は含まれない', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });
			const carol = await signup({ username: 'carol' });

			const alicePost = await post(alice, {
				text: 'foo'
			});

			await post(bob, {
				replyId: alicePost.id,
				text: 'bar',
				visibility: 'specified',
				visibleUserIds: [alice.id]
			});

			const res = await request('/notes/replies', {
				noteId: alicePost.id
			}, carol);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(Array.isArray(res.body), true);
			assert.strictEqual(res.body.length, 0);
		}));
	});

	describe('notes/timeline', () => {
		it('フォロワー限定投稿が含まれる', async(async () => {
			const alice = await signup({ username: 'alice' });
			const bob = await signup({ username: 'bob' });

			await request('/following/create', {
				userId: alice.id
			}, bob);

			const alicePost = await post(alice, {
				text: 'foo',
				visibility: 'followers'
			});

			const res = await request('/notes/timeline', {}, bob);

			assert.strictEqual(res.status, 200);
			assert.strictEqual(Array.isArray(res.body), true);
			assert.strictEqual(res.body.length, 1);
			assert.strictEqual(res.body[0].id, alicePost.id);
		}));
	});
});
*/


text:
---

# Angular 2 Hot Module Replacement
> Angular2-HMR

`npm install @angularclass/hmr @angularclass/hmr-loader`

Please see repository [AngularClass/angular2-seed](https://github.com/AngularClass/angular2-seed) for a working example.
Also download [AngularClass/angular2-hmr-loader](https://github.com/AngularClass/angular2-hmr-loader)

![hmr-state-dom](https://cloud.githubusercontent.com/assets/1016365/18380378/e573320e-762b-11e6-99e0-cc110ffacc6a.gif)

`main.browser.ts`
```typescript
import { removeNgStyles, createNewHosts, bootloader } from '@angularclass/hmr';

@NgModule({
  bootstrap: [ App ],
  declarations: [ App ],
  imports: [
    // Angular 2
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot([], {
      useHash: true
    }),
    // app
    appModule
    // vendors
  ],
  providers: []
})
class MainModule {
  constructor(public appRef: ApplicationRef) {}
  hmrOnInit(store) {
    if (!store || !store.state) return;
    console.log('HMR store', store);
    console.log('store.state.data:', store.state.data)
    // inject AppStore here and update it
    // this.AppStore.update(store.state)
    if ('restoreInputValues' in store) {
      store.restoreInputValues();
    }
    // change detection
    this.appRef.tick();
    delete store.state;
    delete store.restoreInputValues;
  }
  hmrOnDestroy(store) {
    var cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
    // recreate elements
    store.disposeOldHosts = createNewHosts(cmpLocation)
    // inject your AppStore and grab state then set it on store
    // var appState = this.AppStore.get()
    store.state = {data: 'yolo'};
    // store.state = Object.assign({}, appState)
    // save input values
    store.restoreInputValues  = createInputTransfer();
    // remove styles
    removeNgStyles();
  }
  hmrAfterDestroy(store) {
    // display new elements
    store.disposeOldHosts()
    delete store.disposeOldHosts;
    // anything you need done the component is removed
  }
}

export function main() {
  return platformBrowserDynamic().bootstrapModule(MainModule);
}

// boot on document ready
bootloader(main);

```
`bootloader` is only needed to detech that the dom is ready before bootstraping otherwise bootstrap. This is needed because that dom is already ready during reloading

## Important Helpers
* **removeNgStyles**: remove angular styles
* **createNewHosts and disposeOldHosts**: recreate root elements for bootstrapping
* **bootloader**: boot on document ready or boot if it's already ready
* **createInputTransfer** and **restoreInputValues**: transfer input DOM state during replacement

## Production
In production you only need bootloader which just does this
```typescript
export function bootloader(main) {
  if (document.readyState === 'complete') {
    main()
  } else {
    document.addEventListener('DOMContentLoaded', main);
  }
}
```
you would bootstrap your app the normal way, in production, afer dom is ready. Also, in production, you should remove the loader
```es6
        {
          test: /\.ts$/,
          loaders: [
            'awesome-typescript-loader',
          ].concat(prod ? [] : '@angularclass/hmr-loader')
        },
```

___

enjoy — **AngularClass**

[![AngularClass](https://cloud.githubusercontent.com/assets/1016365/9863770/cb0620fc-5af7-11e5-89df-d4b0b2cdfc43.png  "Angular Class")](https://angularclass.com)
##[AngularClass](https://angularclass.com)
> Learn AngularJS, Angular 2, and Modern Web Development from the best.
> Looking for corporate Angular training, want to host us, or Angular consulting? patrick@angularclass.com