text:
package org.axonframework.test;

import org.axonframework.domain.DomainEventMessage;
import org.axonframework.domain.EventMessage;
import org.hamcrest.Description;
import org.hamcrest.StringDescription;

import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * The reporter generates extensive human readable reports of what the expected outcome of a test was, and what the
 * actual results were.
 *
 * @author Allard Buijze
 * @since 0.6
 */
public class Reporter {

    private static final String NEWLINE = System.getProperty("line.separator");

    /**
     * Report a failed assertion due to a difference in the stored versus the published events.
     *
     * @param storedEvents    The events that were stored
     * @param publishedEvents The events that were published
     * @param probableCause   An exception that might be the cause of the failure
     */
    public void reportDifferenceInStoredVsPublished(Collection<DomainEventMessage> storedEvents,
                                                    Collection<EventMessage> publishedEvents, Throwable probableCause) {
        StringBuilder sb = new StringBuilder(
                "The stored events do not match the published events.");
        appendEventOverview(sb, storedEvents, publishedEvents, "Stored events", "Published events");
        appendProbableCause(probableCause, sb);
        throw new AxonAssertionError(sb.toString());
    }

    /**
     * Report an error in the ordering or count of events. This is typically a difference that can be shown to the user
     * by enumerating the expected and actual events
     *
     * @param actualEvents   The events that were found
     * @param expectedEvents The events that were expected
     * @param probableCause  An optional exception that might be the reason for wrong events
     */
    public void reportWrongEvent(Collection<?> actualEvents, Collection<?> expectedEvents,
                                 Throwable probableCause) {
        StringBuilder sb = new StringBuilder(
                "The published events do not match the expected events");
        appendEventOverview(sb, expectedEvents, actualEvents, "Expected", "Actual");
        appendProbableCause(probableCause, sb);

        throw new AxonAssertionError(sb.toString());
    }

    /**
     * Report an error in the ordering or count of events. This is typically a difference that can be shown to the user
     * by enumerating the expected and actual events
     *
     * @param actualEvents  The events that were found
     * @param expectation   A Description of what was expected
     * @param probableCause An optional exception that might be the reason for wrong events
     */
    public void reportWrongEvent(Collection<?> actualEvents, StringDescription expectation, Throwable probableCause) {
        StringBuilder sb = new StringBuilder(
                "The published events do not match the expected events.");
        sb.append("Expected :");
        sb.append(NEWLINE);
        sb.append(expectation);
        sb.append(NEWLINE);
        sb.append("But got");
        if (actualEvents.isEmpty()) {
            sb.append(" none");
        } else {
            sb.append(":");
        }
        for (Object publishedEvent : actualEvents) {
            sb.append(NEWLINE);
            sb.append(publishedEvent.getClass().getSimpleName());
            sb.append(": ");
            sb.append(publishedEvent.toString());
        }
        appendProbableCause(probableCause, sb);

        throw new AxonAssertionError(sb.toString());
    }

    /**
     * Reports an error due to an unexpected exception. This means a return value was expected, but an exception was
     * thrown by the command handler
     *
     * @param actualException The actual exception
     * @param expectation     A text describing what was expected
     */
    public void reportUnexpectedException(Throwable actualException, Description expectation) {
        StringBuilder sb = new StringBuilder("The command handler threw an unexpected exception");
        sb.append(NEWLINE)
          .append(NEWLINE)
                .append("Expected <") //NOSONAR
                .append(expectation.toString())
                .append("> but got <exception of type [")
                .append(actualException.getClass().getSimpleName())
                .append("]>. Stack trace follows:")
                .append(NEWLINE);
        writeStackTrace(actualException, sb);
        sb.append(NEWLINE);
        throw new AxonAssertionError(sb.toString());
    }

    /**
     * Reports an error due to a wrong return value.
     *
     * @param actualReturnValue The actual return value
     * @param expectation       A description of the expected value
     */
    public void reportWrongResult(Object actualReturnValue, Description expectation) {
        StringBuilder sb = new StringBuilder("The command handler returned an unexpected value");
        sb.append(NEWLINE)
          .append(NEWLINE)
          .append("Expected <"); //NOSONAR
        sb.append(expectation.toString());
        sb.append("> but got <");
        describe(actualReturnValue, sb);
        sb.append(">")
          .append(NEWLINE);
        throw new AxonAssertionError(sb.toString());
    }

    /**
     * Report an error due to an unexpected return value, while an exception was expected.
     *
     * @param actualReturnValue The actual return value
     * @param description       A description describing the expected value
     */
    public void reportUnexpectedReturnValue(Object actualReturnValue, Description description) {
        StringBuilder sb = new StringBuilder("The command handler returned normally, but an exception was expected");
        sb.append(NEWLINE)
          .append(NEWLINE)
          .append("Expected <"); //NOSONAR
        sb.append(description.toString());
        sb.append("> but returned with <");
        describe(actualReturnValue, sb);
        sb.append(">")
          .append(NEWLINE);
        throw new AxonAssertionError(sb.toString());
    }

    /**
     * Report an error due to a an exception of an unexpected type.
     *
     * @param actualException The actual exception
     * @param description     A description describing the expected value
     */
    public void reportWrongException(Throwable actualException, Description description) {
        StringBuilder sb = new StringBuilder("The command handler threw an exception, but not of the expected type");
        sb.append(NEWLINE)
          .append(NEWLINE)
                .append("Expected <") //NOSONAR
                .append(description.toString())
                .append("> but got <exception of type [")
                .append(actualException.getClass().getSimpleName())
                .append("]>. Stacktrace follows: ")
                .append(NEWLINE);
        writeStackTrace(actualException, sb);
        sb.append(NEWLINE);
        throw new AxonAssertionError(sb.toString());
    }

    /**
     * Report an error due to a difference in on of the fields of an event.
     *
     * @param eventType The (runtime) type of event the difference was found in
     * @param field     The field that contains the difference
     * @param actual    The actual value of the field
     * @param expected  The expected value of the field
     */
    public void reportDifferentEventContents(Class<?> eventType, Field field, Object actual,
                                             Object expected) {
        StringBuilder sb = new StringBuilder("One of the events contained different values than expected");
        sb.append(NEWLINE)
          .append(NEWLINE)
          .append("In an event of type [")
          .append(eventType.getSimpleName())
          .append("], the property [")
          .append(field.getName())
          .append("] ");
        if (!eventType.equals(field.getDeclaringClass())) {
            sb.append("(declared in [")
              .append(field.getDeclaringClass().getSimpleName())
              .append("]) ");
        }

        sb.append("was not as expected.")
          .append(NEWLINE)
                .append("Expected <") //NOSONAR
                .append(nullSafeToString(expected))
                .append("> but got <")
                .append(nullSafeToString(actual))
                .append(">")
                .append(NEWLINE);
        throw new AxonAssertionError(sb.toString());
    }

    private void appendProbableCause(Throwable probableCause, StringBuilder sb) {
        if (probableCause != null) {
            sb.append(NEWLINE);
            sb.append("A probable cause for the wrong chain of events is an "
                              + "exception that occurred while handling the command.");
            sb.append(NEWLINE);
            CharArrayWriter charArrayWriter = new CharArrayWriter();
            probableCause.printStackTrace(new PrintWriter(charArrayWriter));
            sb.append(charArrayWriter.toCharArray());
        }
    }

    private void writeStackTrace(Throwable actualException, StringBuilder sb) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(baos);
        actualException.printStackTrace(pw);
        pw.flush();
        sb.append(new String(baos.toByteArray()));
    }

    private String nullSafeToString(final Object value) {
        if (value == null) {
            return "<null>";
        }
        return value.toString();
    }

    private void describe(Object value, StringBuilder sb) {
        if (value == null) {
            sb.append("null");
        } else {
            sb.append(value.toString());
        }
    }

    private void appendEventOverview(StringBuilder sb, Collection<?> leftColumnEvents,
                                     Collection<?> rightColumnEvents,
                                     String leftColumnName,
                                     String rightColumnName) {
        List<String> actualTypes = new ArrayList<String>(rightColumnEvents.size());
        List<String> expectedTypes = new ArrayList<String>(leftColumnEvents.size());
        int largestExpectedSize = leftColumnName.length();
        for (Object event : rightColumnEvents) {
            actualTypes.add(payloadContentType(event));
        }
        for (Object event : leftColumnEvents) {
            String simpleName = payloadContentType(event);
            if (simpleName.length() > largestExpectedSize) {
                largestExpectedSize = simpleName.length();
            }
            expectedTypes.add(simpleName);
        }
        sb.append(NEWLINE);
        sb.append(NEWLINE);
        sb.append(leftColumnName);
        pad(sb, leftColumnName.length(), largestExpectedSize, " ");
        sb.append("  |  ")
          .append(rightColumnName)
          .append(NEWLINE);
        pad(sb, 0, largestExpectedSize, "-");
        sb.append("--|--");
        pad(sb, 0, largestExpectedSize, "-");
        sb.append(NEWLINE);
        Iterator<String> actualIterator = actualTypes.iterator();
        Iterator<String> expectedIterator = expectedTypes.iterator();
        while (actualIterator.hasNext() || expectedIterator.hasNext()) {
            boolean difference;
            String expected = "";
            if (expectedIterator.hasNext()) {
                expected = expectedIterator.next();
                sb.append(expected);
                pad(sb, expected.length(), largestExpectedSize, " ");
                difference = !actualIterator.hasNext();
            } else {
                pad(sb, 0, largestExpectedSize, " ");
                difference = true;
            }
            if (actualIterator.hasNext()) {
                String actual = actualIterator.next();
                difference = difference || !actual.equals(expected);
                if (difference) {
                    sb.append(" <|> ");
                } else {
                    sb.append("  |  ");
                }
                sb.append(actual);
            } else {
                sb.append(" <|> ");
            }

            sb.append(NEWLINE);
        }
    }

    private String payloadContentType(Object event) {
        String simpleName;
        if (EventMessage.class.isInstance(event)) {
            simpleName = ((EventMessage) event).getPayload().getClass().getName();
        } else {
            simpleName = event.getClass().getName();
        }
        return simpleName;
    }

    private void pad(StringBuilder sb, int currentLength, int targetLength, String character) {
        for (int t = currentLength; t < targetLength; t++) {
            sb.append(character);
        }
    }
}


text:
import winston from 'winston';
import mongoose from 'mongoose';

// Overwrite mongoose promise module
mongoose.Promise = Promise;

/**
 * Project Schema
 */
const ProjectSchema = new mongoose.Schema({
  name: {
    type: String,
    lowercase: false,
    uppercase: false,
    trim: null,
    match: null,
    enum: null,
    minlength: null,
    maxlength: null,
    required: false,
    default: false,
    select: false,
    validate: null,
    get: null,
    set: null,
    unique: false,
    sparse: false
},
  companyId: {
    type: Schema.Types.ObjectId,
    ref: 'Company'
}
}, {
  collection: 'projects',
  autoIndex: true,
  minimize: false,
  timestamps: true
});

/**
 * Methods
 */
/**
*Uncomment if needed

ProjectSchema.methods.findSimilarParam = () => new Promise((resolve, reject) => {
  this.model('Project').find({ param: this.param }, (err, res) => {
    if (err) {
      reject(err);
    }
    resolve(res);
  });
});
*/

/**
 * Statics
 */
/**
*Uncomment if needed

ProjectSchema.statics.findByParam = param => new Promise((resolve, reject) => {
  this.find({ param: new RegExp(param, 'ig') }, (err, res) => {
    if (err) {
      reject(err);
    }
    resolve(res);
  });
});
*/

/**
 * Query Helpers
 */
/**
*Uncomment if needed

ProjectSchema.query.byParam = param => this.find({ param: new RegExp(param, 'ig') });
*/

/**
 * Indexes
 */
 /**
*Uncomment if needed

ProjectSchema.index({ param: 1, type: -1 });
*/

/**
 * Virtuals
 *//**
*Uncomment if needed

ProjectSchema.virtual('fullName')
  .get(() => `${this.name.first} ${this.name.last}`)
  .set((fullName) => {
    this.name.first = fullName.substr(0, fullName.indexOf(' '));
    this.name.last = fullName.substr(fullName.indexOf(' ') + 1);
  });
*/

/**
 * Pre Middleware
 *//**
*Uncomment if needed

ProjectSchema.pre('init', (next) => {
  // do something before a document is returned from mongodb
  next(); // if no errors, else call next(err)
});

ProjectSchema.pre('validate', (next) => {
  // do something before executing registered validation rules for this document
  next(); // if no errors, else call next(err)
});

ProjectSchema.pre('save', (next) => {
  // do something before saving this document
  next(); // if no errors, else call next(err)
});

ProjectSchema.pre('remove', (next) => {
  // do something before removing this document
  next(); // if no errors, else call next(err)
});
*/

/**
 * Post Middleware
 */
 /**
*Uncomment if needed

ProjectSchema.post('init', (doc) => {
  // do something after
  winston.log('info', 'Document with _id %s initiated', doc._id);
});

ProjectSchema.post('validate', (doc) => {
  // do something after
  winston.log('info', 'Document with _id %s validated', doc._id);
});

ProjectSchema.post('save', (doc) => {
  // do something after
  winston.log('info', 'Document with _id %s saved', doc._id);
});

ProjectSchema.post('remove', (doc) => {
  // do something after
  winston.log('info', 'Document with _id %s removed', doc._id);
});
*/

/**
 * @typedef Project
 */
export default mongoose.model('Project', ProjectSchema);

redpajama_set_name: RedPajamaGithub


text:
import keys from 'lodash/keys';
import { underscore } from 'inflection';

export default function setAttributes(options = {}) {
	let { model, modelJson } = options;

  keys(model.constructor.attributes).forEach(attributeName => {
  	model[attributeName] = modelJson[attributeName] ? modelJson[attributeName] : modelJson[underscore(attributeName)];
  });
}


text:
/**
 * The wrapper for the whole game
 */

define( [ "lodash", "dom", "events", "app/Board", "app/Score", "app/Menu",
          "app/Tetromino", "app/shapeTemplates" ], function(
        _, dom, ev, Board, Score, Menu, Tetromino, shapeTemplates ) {

    var NUMPREVIEW = 3;
    var MAXSHAPEH  = 4;
    var MAXSHAPEW  = 4;
    var COUNTFROM  = 1; //FIXME make bigger
    // ms - the amount of time before a lock is committed
    var LOCKDELAY  = 500;
    var DROPSPEED  = 25;
    var SPEEDLIMIT = 25;
    var STARTSPEED = 250;

    // game state lookup, make global so that everyone can see...
    PREGAME  = 0x1;
    COUNTING = 0x2;
    PLAYING  = 0x3;
    CLEARING = 0x4;
    PAUSED   = 0x5;

    /*
     * Constructor for the game.
     */
    function TetrisGame( args ) {
        this.dom       = dom.create("div");

        this.state     = PREGAME;

        this.score     = new Score();
        this.playBoard = new Board( { game : this, height : 20 } ); // FIXME
        this.menu      = new Menu ( this );

        // need to keep track of the setInterval so that pause and end game can stop it.
        this.moveInterval = null;
        this.moveStep     = null;

        // various things need to know the currently moving object
        this.shape     = null;

        // the ghost is a shadow down of the shape showing where it would be.
        this.useGhost  = true;
        this.ghost     = null;

        // keep track of the next N shapes that will be dropped in.
        this.preview   = _.range(NUMPREVIEW).map(__prepPreview, this);

        // place holder for the keyboard handler.
        this.kbdDnHandler = null;

        this.dom.appendChild( this.makeHTML() );

        return;
    }

    // to cut down on the typing.
    var thisP = TetrisGame.prototype;

    // create a preview board.
    // one for each preview.
    // the first (exit of queue) will be grey.
    function __prepPreview (idx) {
        var init = {
            game      : this,
            padTop    : 0,
            padBottom : 0,
            padLeft   : 0,
            padRight  : 0,
            height    : ( MAXSHAPEH + 2 ),
            width     : ( MAXSHAPEW + 2 ),
            cellSize  : "5px",
        };

        idx === 0 ? init.color = [128,128,128] : null;
        var brd = new Board(init);
        return { board : brd, shape : null };
    }

    // Creates the DOM objects to put in the browser.
    thisP.makeHTML = function () {
        // Create a div to contain the
        this.msgText = dom.create("string", "");
        var msgColor  = this.playBoard.color == [255,255,255] ? [0, 0, 0] : [255, 255, 255];
        var msgDiv    = dom.create("div",
                {style : "color : "+rgb2str(msgColor)+" ; background-color : "+rgb2str(this.playBoard.color)+" ; position : absolute ; top : 40% ; width : 100% ; text-align: center;"},
                this.msgText
        );

        var layout  = dom.create("div", null,
                dom.create("TBODY", null,
                    dom.create("TR", null,
                            dom.create("TD", null, this.score.dom),
                            dom.create("TD")
                    ),
                    dom.create("TR", null,
                            dom.create("TD", null,
                                    dom.create("div", { style : "position : relative" },
                                            msgDiv,
                                            this.playBoard.dom)
                            ),
                            dom.create("TD",
                                    {style : "padding-left : 10px; vertical-align:top ;" },
                                    dom.create("string", "Preview"),
                                    _.map(this.preview, function ( obj ) { return obj.board.dom; })
                            )
                    )
                ),
                this.menu.dom
        );
        return layout;
    };

    /*
     * Start the game.
     * Reset the score, remove the shape, clear the board and the previews.
     * Fill up the preview queue.
     * Then count down before actually playing.
     */
    thisP.start = function() {
        this.state = COUNTING;

        this.score.reset();

        if ( this.shape ) {
            this.shape.clear();
            this.shape = null;
        }

        this.playBoard.resetGrid();

        for (var i=0; i<NUMPREVIEW; i++) {
            if ( this.preview[i].shape ) {
                this.preview[i].shape.clear();
                this.preview[i].shape = null;
            }
        }

        // fill in the preview queue
        while ( ! this.preview[0].shape ) {
            this.addNewShape();
        }

        // count down this number of seconds before playing.
        var lclMsg = COUNTFROM;
        this.msgText.nodeValue = COUNTFROM;

        var startCnt = setInterval(function ( self ) {

            // if we've gotten to the end of the count down start actually playing.
            if ( lclMsg <= 0 ) {
                    self.msgText.nodeValue = "";
                    clearInterval(startCnt);
                    self.state = PLAYING;
                    self.startKbdHandler();
                    self.addNewShape();
                    self.calcMoveStep();
                    self.moveShapeIter();
                }
                lclMsg--;
                self.msgText.nodeValue = lclMsg ? ( lclMsg < 0 ? "" : lclMsg ) : "Go";
            },
            1000,
            this
        );

    };

    // Handle key presses.
    // Arrow keys don't register as keypress's so use key down.
    thisP.startKbdHandler = function () {
        var self = this;
        this.kbdDnHandle = ev.addHandler(document, "keydown", function ( event ) {

            // can only move if there is a shape
            if ( !self.shape ) {
                return;
            }

            // If there is a lock queued up, cancel that.
            // it will be restarted, if appropriate, later.
            self.stopLock();

            // stop moving down while figuring out kbd pushes.
            self.stopMove();

            // turn off the kbdHandler while things are being processed.
            self.stopKbdHandler();

            // dropShape just changes the drop speed, check for lock in normal flow.
            // everything else should check for lock after the action.
            if ( event.keyCode == 40 ) { self.dropShape(); } // down
            else {
                if      ( event.keyCode == 37 ) { self.shape.moveLeft();    } // left
                else if ( event.keyCode == 39 ) { self.shape.moveRight();   } // right
                else if ( event.keyCode == 38 ) { self.shape.rotateLeft();  } // up
                else if ( event.keyCode == 90 ) { self.shape.rotateLeft();  } // z
                else if ( event.keyCode == 88 ) { self.shape.rotateRight(); } // x
                // redraw the ghost, if approriate.
                self.drawGhost();
                // this starts either lock or move
                self.checkForLock();
            }

            // restart the keyboard handler
            self.startKbdHandler();
        });
    };

    // wrapper to stop the keyboard handler
    thisP.stopKbdHandler = function () {
        if ( this.kbdDnHandle !== null ) {
            ev.removeHandler(this.kbdDnHandle);
        }
    };

    /*
     * calculate the number of ms it takes to drop one row.
     * not sure how this is supposed to be done...
     * do linear from (level, step) of (1,STARTSPEED) to (10,SPEEDLIMIT)
     * then cap at the SPEEDLIMT (25) and STARTSPEED(250)
     */
    thisP.calcMoveStep = function () {
        this.moveStep = Math.floor(( SPEEDLIMIT - STARTSPEED )/(10 - 1) *
            ( this.score.level - 1 ) + STARTSPEED);
        if ( this.moveStep > STARTSPEED ) {
            this.moveStep = STARTSPEED;
        }
        if ( this.moveStep < SPEEDLIMIT ) {
            this.moveStep = SPEEDLIMIT;
        }
    };

    /*
     * This is what moves the shape down automatically.
     * Using a timeout here instead of interval for reasons that don't, in hindsight,
     * make sense. But it doesn't matter much... so keep it.
     * The next drop is started by the checkForLock call.
     */
    thisP.moveShapeIter = function () {

        // if already moving, don't start a new chain.
        if ( this.moveInterval ) {
            return;
        }
        this.moveInterval = setTimeout(function ( self ) {
                self.moveInterval = null;
                self.shape.moveDown();
                self.checkForLock();
            },
            this.moveStep,
            this // pass this to timeout function as self
        );
    };

    // clears the timeout that will, soon, move the shape down one.
    thisP.stopMove = function () {
        if (this.moveInterval) {
            clearTimeout(this.moveInterval);
            this.moveInterval = null;
        }
    };

    /*
     * Looks to see if a lock should be started for this shape.
     * A lock is started as soon as the next row down has locked cells lining up.
     * The lock itself is delayed so that the player can keep moving.
     * Each move resets the lock delay.
     * If the moves make it so that the shape shouldn't be locked, start the move timer.
     */
    thisP.checkForLock = function () {
        // can try for locks in multiple ways, so cancel any existing ones
        // before starting the next.
        this.stopLock();

        // this means that the shape can't move down one, so start the lock.
        if ( this.shape.conflictsWithBoard( {y:1} ) ) {
            this.lockTimeout = setTimeout(function ( self ) {
                    self.lockTimeout = null;
                    self.lockShape( this.lockTimeout );
                },
                LOCKDELAY,
                this
            );
            return true;
        }
        this.moveShapeIter();
        return false;
    };

    // clear the timeout that will soon lock the shape to the board.
    thisP.stopLock = function () {
        if (this.lockTimeout) {
            clearTimeout(this.lockTimeout);
            this.lockTimeout = null;
        }
    };

    /*
     * Tell the board to lock the shape down.
     * Board does the real work here.
     * If any of the locked cells are in the padTop then the game is over.
     * Otherwise, remove an filled rows.
     */
    thisP.lockShape = function ( par ) {
        var plc = this.shape.y + this.shape.minY;
        this.playBoard.lockShape(this.shape);
        this.shape = null;
        if ( plc < this.playBoard.padTop ) {
            this.msgText.nodeValue = "Game Over";
            this.menu.gameOver();
        }
        else {
            var numrows = this.playBoard.clearFullRows();
            this.score.update(numrows);
            var wait4clear = setInterval( function (self) {
                    if ( self.state === PLAYING ) {
                        clearInterval(wait4clear);
                        self.addNewShape();
                        self.calcMoveStep();
                        self.moveShapeIter();
                    }
                },
                1,
                this
            );
        }
    };

    // end the game.
    // this is only used for debugging from the console.
    thisP.stop = function() {
        this.state = PREGAME;
        this.stopLock();
        this.stopMove();
        this.stopKbdHandler();
    };

    /*
     * Pause/Unpause the game.
     * If pausing, stop the move, lock iterators and the kbd handler.
     * If unpausing, start those up again...
     */
    thisP.togglePause = function () {
        if ( this.state === PAUSED ) {
            this.state = PLAYING;
            this.checkForLock();
            this.startKbdHandler();
        }
        else if ( this.state === PLAYING ) {
            this.state = PAUSED;
            this.stopKbdHandler();
            this.stopLock();
            this.stopMove();
        }
    };

    /*
     * This is a 'hard drop'.
     * Increase the speed of the drop to the maximum
     */
    thisP.dropShape = function () {
        this.stopMove();
        this.moveStep = DROPSPEED;
        this.moveShapeIter();
    };

    /*
     * The ghost is a shadow of the shape, showing where it will go if dropped.
     * The ghost is the same as the shape, but it's color is that of the board.
     * Just the border is visible.
     */
    thisP.drawGhost = function () {

        // if there is no ghost don't draw.
        // if the shape is trying to lock, don't draw.
        if ( !this.shape || !this.ghost || this.lockTimeout ) {
            return;
        }

        this.ghost.clear();
        this.ghost.x = this.shape.x;
        this.ghost.y = this.shape.y;
        this.ghost.version = this.shape.version;

        while ( !this.ghost.conflictsWithBoard( {y:1} ) ) {
            this.ghost.y++;
        }

        //FIXME - maybe don't draw the ghost if it overlaps with the shape
        //FIXME - maybe don't draw the ghost if it overlaps with the shape
        // simple work around is to draw the shape again...
        this.ghost.draw();
        this.shape.draw();
    };

    // Need a list of potential shape names.
    var shapeNames = _.keys(shapeTemplates);

    /*
     * Takes the top of the preview and adds it to the board.
     * Creates a new shape and adds to the end of the preview list.
     */
    thisP.addNewShape = function () {
        // clear all the existing previews.
        for (var i=0; i<NUMPREVIEW; i++) {
            if ( this.preview[i].shape ) {
                this.preview[i].shape.clear();
            }
        }

        // shouldn't be necassiry under normal operation, but helps in debug mode.
        if ( this.shape ) {
            this.shape.clear();
        }

        // move the the next shape to the play board.
        this.shape = this.preview[0].shape;

        if ( this.shape ) {
            this.shape.board = this.playBoard;
            this.shape.x     = this.playBoard.padLeft + Math.ceil( (this.playBoard.width - this.shape.width ) /2 );
            this.shape.y     = 0;

            this.shape.draw();

            if ( this.useGhost ) {
                this.ghost =  new Tetromino( {
                    name  : this.shape.name,
                    board : this.shape.board,
                    x     : this.shape.x,
                    y     : this.shape.y,
                    isGhost : true
                });
                this.drawGhost();
            }
        }

        // shift the shapes up one.
        for (var i=0; i<NUMPREVIEW-1; i++) {

            this.preview[i].shape = this.preview[i+1].shape;
            if ( this.preview[i].shape ) {
                this.preview[i].shape.board = this.preview[i].board;
            }

            if ( this.preview[i].shape ) {
                this.preview[i].shape.draw();
            }
        }

        // add a new shape to the end.
        var j = NUMPREVIEW-1;
        this.preview[j].shape =  new Tetromino( {
            name  : shapeNames[Math.floor( Math.random()*shapeNames.length )],
            board : this.preview[j].board,
            x     : 1,
            y     : 2,
        });
        this.preview[NUMPREVIEW-1].shape.draw();
    };

    return TetrisGame;
} );


text:
using System;
using System.Drawing;
using Newtonsoft.Json;

namespace WTManager.Converters
{
    public class FontConverter : JsonConverter
    {
        private readonly System.Drawing.FontConverter _converter;

        public FontConverter()
        {
            this._converter = new System.Drawing.FontConverter();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var fontObject = value as Font;

            if (fontObject == null)
                return;

            writer.WriteValue(this._converter.ConvertToString(fontObject));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string serializedData = reader.Value as string;

            if (serializedData == null)
                return null;

            return this._converter.ConvertFromString(serializedData);
        }

        public override bool CanConvert(Type objectType)
            => objectType == typeof(Font);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Modern Business - Start Bootstrap Template</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

        Start Bootstrap
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              About

              Services

              Contact

                Portfolio

                1 Column Portfolio
                2 Column Portfolio
                3 Column Portfolio
                4 Column Portfolio
                Single Portfolio Item

                Blog

                Blog Home 1
                Blog Home 2
                Blog Post

                Other Pages

                Full Width Page
                Sidebar Page
                FAQ
                404
                Pricing Table

404
        Page Not Found

          Home

404

404

The page you're looking for could not be found. Here are some helpful links to get you back on track:

            Home

            About

            Services

            Contact

            Portfolio

                1 Column Portfolio

                2 Column Portfolio

                3 Column Portfolio

                4 Column Portfolio

            Blog

                Blog Home 1

                Blog Home 2

                Blog Post

            Other Pages

                Full Width Page

                Sidebar Page

                FAQ

                404 Page

                Pricing Table

Copyright © Your Website 2017


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var core_2 = require("@angular-mdl/core");
var platform_browser_1 = require("@angular/platform-browser");
var forms_1 = require("@angular/forms");
var http_1 = require("@angular/http");
var app_routing_module_1 = require("./app-routing.module");
var app_component_1 = require("./app.component");
var dashboard_component_1 = require("./dashboard.component");
var reservelist_component_1 = require("./reservelist.component");
var shucedule_component_1 = require("./shucedule.component");
var shuceduledetail_component_1 = require("./shuceduledetail.component");
var programdetail_component_1 = require("./programdetail.component");
var carousel_component_1 = require("./carousel.component");
var reserve_service_1 = require("./reserve.service");
var shucedule_service_1 = require("./shucedule.service");
var socketio_service_1 = require("./socketio.service");
var AppModule = (function () {
    function AppModule() {
    }
    return AppModule;
}());
AppModule.decorators = [
    { type: core_1.NgModule, args: [{
                imports: [
                    platform_browser_1.BrowserModule,
                    forms_1.FormsModule,
                    http_1.HttpModule,
                    core_2.MdlModule,
                    app_routing_module_1.AppRoutingModule
                ],
                declarations: [
                    app_component_1.AppComponent,
                    dashboard_component_1.DashboardComponent,
                    reservelist_component_1.ReserveListComponent,
                    programdetail_component_1.ProgramDetailComponent,
                    shucedule_component_1.ShuceduleComponent,
                    shuceduledetail_component_1.ShuceduleDetailComponent,
                    carousel_component_1.Carousel
                ],
                providers: [shucedule_service_1.ShuceduleService, reserve_service_1.ReserveService, socketio_service_1.SocketIOService],
                bootstrap: [app_component_1.AppComponent]
            },] },
];
/** @nocollapse */
AppModule.ctorParameters = function () { return []; };
exports.AppModule = AppModule;
//# sourceMappingURL=app.module.js.map


text:
<?php
/**
 * @author Tom Sartain <toms@kindlingapp.com>
 */
return array();


text: Java version of Indic language compression


text: {{item.heading}}


text:
// key: compiler.misc.bad.source.file.header
// key: compiler.misc.file.doesnt.contain.class
// key: compiler.err.cant.access

class BadSourceFileHeader {
    p.A a;
}


text:
<?php

namespace Symfony\Component\Cache\Tests\Adapter;

use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

/**
 * @group time-sensitive
 */
class FilesystemAdapterTest extends AdapterTestCase
{
    public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface
    {
        return new FilesystemAdapter('', $defaultLifetime);
    }

    public static function tearDownAfterClass(): void
    {
        self::rmdir(sys_get_temp_dir().'/symfony-cache');
    }

    public static function rmdir(string $dir)
    {
        if (!file_exists($dir)) {
            return;
        }
        if (!$dir || !str_starts_with(\dirname($dir), sys_get_temp_dir())) {
            throw new \Exception(__METHOD__."() operates only on subdirs of system's temp dir");
        }
        $children = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($children as $child) {
            if ($child->isDir()) {
                rmdir($child);
            } else {
                unlink($child);
            }
        }
        rmdir($dir);
    }

    protected function isPruned(CacheItemPoolInterface $cache, string $name): bool
    {
        $getFileMethod = (new \ReflectionObject($cache))->getMethod('getFile');
        $getFileMethod->setAccessible(true);

        return !file_exists($getFileMethod->invoke($cache, $name));
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Test Content · MatinGholami</title>
        <meta name="description" content="to try functionality and appearance.">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="generator" content="Hugo 0.88.1" />
        <meta name="robots" content="index,follow">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta property="og:title" content="Test Content">
<meta property="og:description" content="to try functionality and appearance.">
<meta property="og:type" content="article">
<meta property="og:url" content="https://matingholami.github.io/2021/hugo-self-tutorial/">
        <link rel="stylesheet" href="https://matingholami.github.io/dist/site.css">
        <link rel="stylesheet" href="https://matingholami.github.io/dist/syntax.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,400,600,700,300&subset=latin,cyrillic-ext,latin-ext,cyrillic">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

                                Matin Gholami

        My website

        Blog

        About Me

Test Content

to try functionality and appearance.

        Published <time datetime="2021-06-11" itemprop="datePublished">2021-June-11</time>
        by

                MatinGholami

            This post could be read in  2 min

why Don’t I just lorem them Ipsums?

Many people do this, and it seems quite reasonable to put some Lorem ipsum at place as for test content
to fill out blanks and show pros and cons of a design, right? I’m not sure about that! I just don’t like the idea of publishing something
that is not but ctrl+c => ctrl+v, especially because I have somehow convinced myself to commit to not removing anything of this blog after publishing.

I am some kind of a programmer myself

I have a history of messing around codes and stuff, from C++ to PHP (well it doesn’t make much sense
cause C++ and PHP are not two separate points on a scale to form a range, but I meant that I started with C++ and ended up loving PHP).
I do not consider myself a professional programmer but a proud member of programmers' societies.

Here is a random PHP script:

echo Hello();

function Hello($anon=false){
  if($anon==true) return 'Greeting Citizens of the World';
  else return 'Hello World!';
}

MatinGholami owns this personal blog

If you look up the term “MatinGholami” in this page, you will find more than a few Matingholamis in the text!
That’s cause Matin Gholami owns this blog meaning this blog belongs to Matin Gholami and no one but MatinGholami shall write here.
Just kidding! anyone weather MatinGholami or anyone else with proper access to the github repository responsible for this blog may
write in or edit the blog, who am I to morally evaluate such actions?
But if you make an edit to this blog, do it in your own name <3

                        Matin Gholami

                    Powered by Ghostwriter theme on Hugo


text:
DESTDIR=/
PYTHON=python

prefix=/usr
bindir=$(prefix)/bin

all:
	$(PYTHON) setup.py build

install:
	$(PYTHON) setup.py install \
		--root=$(DESTDIR) \
		--prefix=$(prefix) \
		--install-scripts=$(bindir)

dist:
	$(PYTHON) setup.py sdist

rpm:
	$(PYTHON) setup.py bdist_rpm


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.7.6.1">
  <compounddef id="direction__code_8hpp" kind="file">
    <compoundname>direction_code.hpp</compoundname>
    <includes refid="access_8hpp" local="no">boost/geometry/core/access.hpp</includes>
    <includes refid="math_8hpp" local="no">boost/geometry/util/math.hpp</includes>
    <includedby refid="point__is__spike__or__equal_8hpp" local="no">/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/point_is_spike_or_equal.hpp</includedby>
    <includedby refid="sort__by__side_8hpp" local="no">/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/sort_by_side.hpp</includedby>
    <incdepgraph>
      <node id="10963">
        boost/geometry/util/math.hpp
        <link refid="math_8hpp"/>
        <childnode refid="10964" relation="include">
        </childnode>
        <childnode refid="10965" relation="include">
        </childnode>
        <childnode refid="10946" relation="include">
        </childnode>
        <childnode refid="10966" relation="include">
        </childnode>
        <childnode refid="10967" relation="include">
        </childnode>
        <childnode refid="10968" relation="include">
        </childnode>
        <childnode refid="10969" relation="include">
        </childnode>
        <childnode refid="10962" relation="include">
        </childnode>
        <childnode refid="10970" relation="include">
        </childnode>
        <childnode refid="10973" relation="include">
        </childnode>
      </node>
      <node id="10953">
        boost/type_traits/remove_const.hpp
      </node>
      <node id="10965">
        limits
      </node>
      <node id="10966">
        boost/math/constants/constants.hpp
      </node>
      <node id="10956">
        boost/type_traits/is_const.hpp
      </node>
      <node id="10944">
        boost/geometry/core/access.hpp
        <link refid="access_8hpp"/>
        <childnode refid="10945" relation="include">
        </childnode>
        <childnode refid="10946" relation="include">
        </childnode>
        <childnode refid="10947" relation="include">
        </childnode>
        <childnode refid="10948" relation="include">
        </childnode>
        <childnode refid="10949" relation="include">
        </childnode>
        <childnode refid="10950" relation="include">
        </childnode>
        <childnode refid="10951" relation="include">
        </childnode>
        <childnode refid="10958" relation="include">
        </childnode>
        <childnode refid="10960" relation="include">
        </childnode>
      </node>
      <node id="10964">
        cmath
      </node>
      <node id="10955">
        boost/mpl/if.hpp
      </node>
      <node id="10948">
        boost/type_traits/is_pointer.hpp
      </node>
      <node id="10967">
        boost/math/special_functions/fpclassify.hpp
      </node>
      <node id="10950">
        boost/geometry/core/coordinate_type.hpp
        <link refid="coordinate__type_8hpp"/>
        <childnode refid="10947" relation="include">
        </childnode>
        <childnode refid="10951" relation="include">
        </childnode>
        <childnode refid="10958" relation="include">
        </childnode>
        <childnode refid="10960" relation="include">
        </childnode>
        <childnode refid="10961" relation="include">
        </childnode>
      </node>
      <node id="10947">
        boost/mpl/assert.hpp
      </node>
      <node id="10943">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/direction_code.hpp
        <link refid="direction_code.hpp"/>
        <childnode refid="10944" relation="include">
        </childnode>
        <childnode refid="10963" relation="include">
        </childnode>
      </node>
      <node id="10957">
        boost/type_traits/remove_reference.hpp
      </node>
      <node id="10972">
        boost/geometry/core/coordinate_system.hpp
        <link refid="coordinate__system_8hpp"/>
        <childnode refid="10947" relation="include">
        </childnode>
        <childnode refid="10951" relation="include">
        </childnode>
        <childnode refid="10960" relation="include">
        </childnode>
      </node>
      <node id="10946">
        boost/core/ignore_unused.hpp
      </node>
      <node id="10961">
        boost/geometry/util/promote_floating_point.hpp
        <link refid="promote__floating__point_8hpp"/>
        <childnode refid="10955" relation="include">
        </childnode>
        <childnode refid="10962" relation="include">
        </childnode>
      </node>
      <node id="10959">
        boost/geometry/core/tags.hpp
        <link refid="core_2tags_8hpp"/>
      </node>
      <node id="10971">
        boost/type_traits/integral_constant.hpp
      </node>
      <node id="10969">
        boost/type_traits/is_fundamental.hpp
      </node>
      <node id="10951">
        boost/geometry/core/point_type.hpp
        <link refid="point__type_8hpp"/>
        <childnode refid="10947" relation="include">
        </childnode>
        <childnode refid="10952" relation="include">
        </childnode>
        <childnode refid="10953" relation="include">
        </childnode>
        <childnode refid="10954" relation="include">
        </childnode>
        <childnode refid="10958" relation="include">
        </childnode>
        <childnode refid="10959" relation="include">
        </childnode>
        <childnode refid="10960" relation="include">
        </childnode>
      </node>
      <node id="10952">
        boost/range/value_type.hpp
      </node>
      <node id="10945">
        cstddef
      </node>
      <node id="10954">
        boost/geometry/core/ring_type.hpp
        <link refid="ring__type_8hpp"/>
        <childnode refid="10947" relation="include">
        </childnode>
        <childnode refid="10955" relation="include">
        </childnode>
        <childnode refid="10952" relation="include">
        </childnode>
        <childnode refid="10956" relation="include">
        </childnode>
        <childnode refid="10953" relation="include">
        </childnode>
        <childnode refid="10957" relation="include">
        </childnode>
        <childnode refid="10958" relation="include">
        </childnode>
        <childnode refid="10959" relation="include">
        </childnode>
      </node>
      <node id="10962">
        boost/type_traits/is_integral.hpp
      </node>
      <node id="10974">
        boost/type_traits/is_floating_point.hpp
      </node>
      <node id="10958">
        boost/geometry/core/tag.hpp
        <link refid="tag_8hpp"/>
        <childnode refid="10959" relation="include">
        </childnode>
        <childnode refid="10960" relation="include">
        </childnode>
      </node>
      <node id="10970">
        boost/geometry/core/cs.hpp
        <link refid="cs_8hpp"/>
        <childnode refid="10945" relation="include">
        </childnode>
        <childnode refid="10947" relation="include">
        </childnode>
        <childnode refid="10971" relation="include">
        </childnode>
        <childnode refid="10972" relation="include">
        </childnode>
        <childnode refid="10959" relation="include">
        </childnode>
      </node>
      <node id="10960">
        boost/geometry/util/bare_type.hpp
        <link refid="bare__type_8hpp"/>
        <childnode refid="10953" relation="include">
        </childnode>
        <childnode refid="10949" relation="include">
        </childnode>
        <childnode refid="10957" relation="include">
        </childnode>
      </node>
      <node id="10949">
        boost/type_traits/remove_pointer.hpp
      </node>
      <node id="10973">
        boost/geometry/util/select_most_precise.hpp
        <link refid="select__most__precise_8hpp"/>
        <childnode refid="10955" relation="include">
        </childnode>
        <childnode refid="10974" relation="include">
        </childnode>
        <childnode refid="10969" relation="include">
        </childnode>
      </node>
      <node id="10968">
        boost/numeric/conversion/cast.hpp
      </node>
    </incdepgraph>
    <invincdepgraph>
      <node id="11004">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/interface.hpp
        <link refid="intersection_2interface_8hpp"/>
        <childnode refid="10996" relation="include">
        </childnode>
        <childnode refid="11005" relation="include">
        </childnode>
        <childnode refid="10994" relation="include">
        </childnode>
      </node>
      <node id="10978">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/has_spikes.hpp
        <link refid="has__spikes_8hpp"/>
        <childnode refid="10979" relation="include">
        </childnode>
        <childnode refid="10982" relation="include">
        </childnode>
        <childnode refid="10985" relation="include">
        </childnode>
      </node>
      <node id="10998">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/follow.hpp
        <link refid="follow_8hpp"/>
        <childnode refid="10999" relation="include">
        </childnode>
        <childnode refid="11002" relation="include">
        </childnode>
      </node>
      <node id="10983">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/implementation.hpp
        <link refid="is__valid_2implementation_8hpp"/>
        <childnode refid="10984" relation="include">
        </childnode>
      </node>
      <node id="10995">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/implementation.hpp
        <link refid="intersection_2implementation_8hpp"/>
        <childnode refid="10996" relation="include">
        </childnode>
      </node>
      <node id="11007">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/overlay.hpp
        <link refid="overlay_8hpp"/>
        <childnode refid="11008" relation="include">
        </childnode>
        <childnode refid="11001" relation="include">
        </childnode>
        <childnode refid="11002" relation="include">
        </childnode>
      </node>
      <node id="10996">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/intersection.hpp
        <link refid="algorithms_2intersection_8hpp"/>
        <childnode refid="10997" relation="include">
        </childnode>
      </node>
      <node id="11000">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/linear_linear.hpp
        <link refid="overlay_2linear__linear_8hpp"/>
        <childnode refid="11001" relation="include">
        </childnode>
        <childnode refid="11002" relation="include">
        </childnode>
      </node>
      <node id="10989">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/copy_segments.hpp
        <link refid="copy__segments_8hpp"/>
        <childnode refid="10990" relation="include">
        </childnode>
        <childnode refid="10994" relation="include">
        </childnode>
        <childnode refid="10998" relation="include">
        </childnode>
        <childnode refid="10999" relation="include">
        </childnode>
        <childnode refid="11006" relation="include">
        </childnode>
      </node>
      <node id="11011">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/handle_colocations.hpp
        <link refid="handle__colocations_8hpp"/>
        <childnode refid="11010" relation="include">
        </childnode>
      </node>
      <node id="10976">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/point_is_spike_or_equal.hpp
        <link refid="point__is__spike__or__equal_8hpp"/>
        <childnode refid="10977" relation="include">
        </childnode>
        <childnode refid="10978" relation="include">
        </childnode>
        <childnode refid="10988" relation="include">
        </childnode>
      </node>
      <node id="10982">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/linear.hpp
        <link refid="is__valid_2linear_8hpp"/>
        <childnode refid="10983" relation="include">
        </childnode>
      </node>
      <node id="10975">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/direction_code.hpp
        <link refid="direction_code.hpp"/>
        <childnode refid="10976" relation="include">
        </childnode>
        <childnode refid="11009" relation="include">
        </childnode>
      </node>
      <node id="10980">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_simple/implementation.hpp
        <link refid="is__simple_2implementation_8hpp"/>
        <childnode refid="10981" relation="include">
        </childnode>
      </node>
      <node id="11001">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/union.hpp
        <link refid="union_8hpp"/>
        <childnode refid="10997" relation="include">
        </childnode>
      </node>
      <node id="11006">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/traverse.hpp
        <link refid="traverse_8hpp"/>
        <childnode refid="10991" relation="include">
        </childnode>
        <childnode refid="11007" relation="include">
        </childnode>
      </node>
      <node id="11002">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/intersection_insert.hpp
        <link refid="intersection__insert_8hpp"/>
        <childnode refid="11003" relation="include">
        </childnode>
        <childnode refid="11004" relation="include">
        </childnode>
      </node>
      <node id="10987">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/multipolygon.hpp
        <link refid="multipolygon_8hpp"/>
        <childnode refid="10983" relation="include">
        </childnode>
      </node>
      <node id="10991">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/buffer/buffered_piece_collection.hpp
        <link refid="buffered__piece__collection_8hpp"/>
        <childnode refid="10992" relation="include">
        </childnode>
      </node>
      <node id="10986">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/polygon.hpp
        <link refid="algorithms_2detail_2is__valid_2polygon_8hpp"/>
        <childnode refid="10983" relation="include">
        </childnode>
        <childnode refid="10987" relation="include">
        </childnode>
      </node>
      <node id="10985">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_valid/ring.hpp
        <link refid="algorithms_2detail_2is__valid_2ring_8hpp"/>
        <childnode refid="10983" relation="include">
        </childnode>
        <childnode refid="10986" relation="include">
        </childnode>
      </node>
      <node id="10990">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/buffer/buffered_ring.hpp
        <link refid="buffered__ring_8hpp"/>
        <childnode refid="10991" relation="include">
        </childnode>
      </node>
      <node id="10988">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/append_no_dups_or_spikes.hpp
        <link refid="append__no__dups__or__spikes_8hpp"/>
        <childnode refid="10989" relation="include">
        </childnode>
      </node>
      <node id="11003">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/difference.hpp
        <link refid="difference_8hpp"/>
      </node>
      <node id="10994">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/multi.hpp
        <link refid="multi_8hpp"/>
        <childnode refid="10995" relation="include">
        </childnode>
      </node>
      <node id="10997">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/sym_difference.hpp
        <link refid="sym__difference_8hpp"/>
      </node>
      <node id="10992">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp
        <link refid="buffer__inserter_8hpp"/>
        <childnode refid="10993" relation="include">
        </childnode>
      </node>
      <node id="10993">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/buffer.hpp
        <link refid="algorithms_2buffer_8hpp"/>
      </node>
      <node id="11012">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/less_by_segment_ratio.hpp
        <link refid="less__by__segment__ratio_8hpp"/>
        <childnode refid="11010" relation="include">
        </childnode>
      </node>
      <node id="11008">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/touches.hpp
        <link refid="touches_8hpp"/>
      </node>
      <node id="11009">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/sort_by_side.hpp
        <link refid="sort__by__side_8hpp"/>
        <childnode refid="11010" relation="include">
        </childnode>
        <childnode refid="11011" relation="include">
        </childnode>
        <childnode refid="11012" relation="include">
        </childnode>
        <childnode refid="11006" relation="include">
        </childnode>
      </node>
      <node id="10984">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/is_valid.hpp
        <link refid="is__valid_8hpp"/>
      </node>
      <node id="10979">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/is_simple/linear.hpp
        <link refid="is__simple_2linear_8hpp"/>
        <childnode refid="10980" relation="include">
        </childnode>
      </node>
      <node id="10999">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/follow_linear_linear.hpp
        <link refid="follow__linear__linear_8hpp"/>
        <childnode refid="11000" relation="include">
        </childnode>
      </node>
      <node id="11010">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/overlay/enrich_intersection_points.hpp
        <link refid="enrich__intersection__points_8hpp"/>
        <childnode refid="10991" relation="include">
        </childnode>
        <childnode refid="11007" relation="include">
        </childnode>
      </node>
      <node id="10981">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/is_simple.hpp
        <link refid="is__simple_8hpp"/>
      </node>
      <node id="11005">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/intersection/box_box.hpp
        <link refid="intersection_2box__box_8hpp"/>
        <childnode refid="10995" relation="include">
        </childnode>
      </node>
      <node id="10977">
        /home/travis/build/boostorg/boost/boost/geometry/algorithms/remove_spikes.hpp
        <link refid="remove__spikes_8hpp"/>
      </node>
    </invincdepgraph>
    <innernamespace refid="namespaceboost">boost</innernamespace>
    <innernamespace refid="namespaceboost_1_1geometry">boost::geometry</innernamespace>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="/home/travis/build/boostorg/boost/boost/geometry/algorithms/detail/direction_code.hpp"/>
  </compounddef>
</doxygen>


text:
using UnityEngine;
using System.Collections;

public class MagicUILabel : MonoBehaviour
{
	protected UILabel _label;

	protected bool _isButton;
	protected NGUIText.Alignment _horizontal;
	// _vertical
	protected bool _isMultiline;
	protected float _fontSize;

	protected bool _isTextBox;
	public UILabel SetForTextBox()
	{
		_isTextBox = true;
		_label.overflowMethod = UILabel.Overflow.ClampContent;
		return _label;
	}

	public Color Color
	{
		get { return _label.color; }
		set { _label.color = value; }
	}

	public void Initialize(string text, bool isButton, JSONObject markup)
	{
		_isTextBox = false;

		_label.text = text;
		_label.trueTypeFont = MagicUIManager.Instance.Skin.FontParameters.Font;
		_label.color = Color.black;
		_label.keepCrispWhenShrunk = UILabel.Crispness.Always;

		if (isButton)
		{
			_isButton = true;
			_isMultiline = false;
			_horizontal = NGUIText.Alignment.Center;
			// _vertical
			_fontSize = 999;
		}
		else
		{
			_isButton = false;

			bool? multiline = markup.GetBoolSafely("multiline", false);
			if (multiline.HasValue)
				_isMultiline = multiline.Value;

			switch (markup.GetStringSafely("halign", "center").ToLower()[0])
			{
				case 'l':
					_horizontal = NGUIText.Alignment.Left;
					break;

				case 'r':
					_horizontal = NGUIText.Alignment.Right;
					break;

				case 'c':
				default:
					_horizontal = NGUIText.Alignment.Center;
					break;
			}
			_label.alignment = _horizontal;

			//control.AddField("valign", valign);

			_fontSize = markup.GetFloatSafely("fontsize", 25);
		}
	}

	public void SetExtents(Rect extents)
	{
		if (!_isTextBox)
		{
			_label.overflowMethod = UILabel.Overflow.ShrinkContent;
		}

		_label.width = Mathf.RoundToInt(extents.width);
		_label.height = Mathf.RoundToInt(extents.height);
		_label.maxLineCount = (_isMultiline && !_isTextBox) ? 0 : 1;

		// TODO Scale font
		_label.fontSize = Mathf.RoundToInt(_fontSize);
	}

	public void SetZOrder(int z)
	{
		_label.depth = z;
	}

	public static MagicUILabel CreateAsChild(GameObject parent)
	{
		GameObject child = new GameObject();
		child.name = "Label";
		child.layer = parent.layer;
		child.transform.parent = parent.transform;
		child.transform.localPosition = Vector3.zero;
		child.transform.localScale = Vector3.one;

		return CreateAsComponent(child);
	}

	public static MagicUILabel CreateAsComponent(GameObject me)
	{
		MagicUILabel result = me.AddComponent<MagicUILabel>();
		result._label = me.AddComponent<UILabel>();
		return result;
	}
}


text:
import re

import pytest
from django.urls import reverse

from rdmo.views.models import View

from ..models import Project

users = (
    ('owner', 'owner'),
    ('manager', 'manager'),
    ('author', 'author'),
    ('guest', 'guest'),
    ('user', 'user'),
    ('site', 'site'),
    ('anonymous', None),
)

view_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'manager': [1, 3, 5, 7],
    'author': [1, 3, 5, 8],
    'guest': [1, 3, 5, 9],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

change_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'manager': [1, 3, 5, 7],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

delete_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

export_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'manager': [1, 3, 5, 7],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

projects = [1, 2, 3, 4, 5, 6, 7, 8, 9]

export_formats = ('rtf', 'odt', 'docx', 'html', 'markdown', 'tex', 'pdf')

site_id = 1
parent_project_id = 1
catalog_id = 1

@pytest.mark.parametrize('username,password', users)
def test_list(db, client, username, password):
    client.login(username=username, password=password)

    url = reverse('projects')
    response = client.get(url)

    projects = re.findall(r'/projects/(\d+)/', response.content.decode())

    if password:
        assert response.status_code == 200

        if username == 'site':
            assert projects == []
        else:
            assert sorted(list(set([int(project_id) for project_id in projects]))) \
                == view_project_permission_map.get(username, [])
    else:
        assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
def test_site(db, client, username, password):
    client.login(username=username, password=password)

    url = reverse('site_projects')
    response = client.get(url)

    projects = re.findall(r'/projects/(\d+)/update/', response.content.decode())

    if username == 'site':
        assert sorted([int(project_id) for project_id in projects]) \
            == view_project_permission_map.get(username, [])
    elif password:
        assert response.status_code == 403
    else:
        assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_detail(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project', args=[project_id])
    response = client.get(url)

    if project_id in view_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
def test_project_create_get(db, client, username, password):
    client.login(username=username, password=password)

    url = reverse('project_create')
    response = client.get(url)

    if password:
        assert response.status_code == 200

        # check the parent select dropdown
        for project_id in re.findall(r'<option value="(\d+)"', response.content.decode()):
            assert int(project_id) in view_project_permission_map.get(username, [])
    else:
        assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
def test_project_create_post(db, client, username, password):
    client.login(username=username, password=password)
    project_count = Project.objects.count()

    url = reverse('project_create')
    data = {
        'title': 'A new project',
        'description': 'Some description',
        'catalog': catalog_id
    }
    response = client.post(url, data)

    if password:
        assert response.status_code == 302
        assert Project.objects.count() == project_count + 1
    else:
        assert response.status_code == 302
        assert Project.objects.count() == project_count

@pytest.mark.parametrize('username,password', users)
def test_project_create_parent_post(db, client, username, password):
    client.login(username=username, password=password)
    project_count = Project.objects.count()

    url = reverse('project_create')
    data = {
        'title': 'A new project',
        'description': 'Some description',
        'catalog': catalog_id,
        'parent': parent_project_id
    }
    response = client.post(url, data)

    if username == 'user':
        assert response.status_code == 200
        assert Project.objects.count() == project_count
    elif password:
        assert response.status_code == 302
        assert Project.objects.count() == project_count + 1
    else:
        assert response.status_code == 302
        assert Project.objects.count() == project_count

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_get(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_update', args=[project_id])
    response = client.get(url)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_post(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project = Project.objects.get(pk=project_id)

    url = reverse('project_update', args=[project_id])
    data = {
        'title': 'New title',
        'description': project.description,
        'catalog': project.catalog.pk
    }
    response = client.post(url, data)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 302
        assert Project.objects.get(pk=project_id).title == 'New title'
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert Project.objects.get(pk=project_id).title == project.title

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_post_parent(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project = Project.objects.get(pk=project_id)

    url = reverse('project_update', args=[project_id])
    data = {
        'title': project.title,
        'description': project.description,
        'catalog': project.catalog.pk,
        'parent': parent_project_id
    }
    response = client.post(url, data)

    if project_id in change_project_permission_map.get(username, []):
        if project_id == parent_project_id:
            assert response.status_code == 200
            assert Project.objects.get(pk=project_id).parent == project.parent
        else:
            assert response.status_code == 302
            assert Project.objects.get(pk=project_id).parent_id == parent_project_id
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert Project.objects.get(pk=project_id).parent == project.parent

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_information_get(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_update_information', args=[project_id])
    response = client.get(url)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_information_post(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project = Project.objects.get(pk=project_id)

    url = reverse('project_update_information', args=[project_id])
    data = {
        'title': 'Lorem ipsum dolor sit amet',
        'description': 'At vero eos et accusam et justo duo dolores et ea rebum.'
    }
    response = client.post(url, data)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 302
        assert Project.objects.get(pk=project_id).title == 'Lorem ipsum dolor sit amet'
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert Project.objects.get(pk=project_id).title == project.title

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_catalog_get(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_update_catalog', args=[project_id])
    response = client.get(url)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_catalog_post(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project = Project.objects.get(pk=project_id)

    url = reverse('project_update_catalog', args=[project_id])
    data = {
        'catalog': catalog_id
    }
    response = client.post(url, data)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 302
        assert Project.objects.get(pk=project_id).catalog_id == catalog_id
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert Project.objects.get(pk=project_id).catalog == project.catalog

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_tasks_get(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_update_tasks', args=[project_id])
    response = client.get(url)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_tasks_post(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project = Project.objects.get(pk=project_id)

    url = reverse('project_update_tasks', args=[project_id])
    data = {
        'tasks': []
    }
    response = client.post(url, data)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 302
        assert list(Project.objects.get(pk=project_id).tasks.values('id')) == []
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert list(Project.objects.get(pk=project_id).tasks.values('id')) == list(project.tasks.values('id'))

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_views_get(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_update_views', args=[project_id])
    response = client.get(url)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_views_post(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project = Project.objects.get(pk=project_id)

    url = reverse('project_update_views', args=[project_id])
    data = {
        'views': []
    }
    response = client.post(url, data)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 302
        assert list(Project.objects.get(pk=project_id).views.values('id')) == []
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert list(Project.objects.get(pk=project_id).views.values('id')) == list(project.views.values('id'))

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_parent_get(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_update_parent', args=[project_id])
    response = client.get(url)

    if project_id in change_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_update_parent_post(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project = Project.objects.get(pk=project_id)

    url = reverse('project_update_parent', args=[project_id])
    data = {
        'parent': parent_project_id
    }
    response = client.post(url, data)

    if project_id in change_project_permission_map.get(username, []):
        if project_id == parent_project_id:
            assert response.status_code == 200
            assert Project.objects.get(pk=project_id).parent == project.parent
        else:
            assert response.status_code == 302
            assert Project.objects.get(pk=project_id).parent_id == parent_project_id
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert Project.objects.get(pk=project_id).parent == project.parent

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_delete_get(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_delete', args=[project_id])
    response = client.get(url)

    if project_id in delete_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_delete_post(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_delete', args=[project_id])
    response = client.post(url)

    if project_id in delete_project_permission_map.get(username, []):
        assert response.status_code == 302
        assert not Project.objects.filter(pk=project_id).first()
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

        assert Project.objects.filter(pk=project_id).first()

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_export_xml(db, client, files, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_export', args=[project_id, 'xml'])
    response = client.get(url)

    if project_id in export_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_export_csv(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_export', args=[project_id, 'csvcomma'])
    response = client.get(url)

    if project_id in export_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_export_csvsemicolon(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_export', args=[project_id, 'csvsemicolon'])
    response = client.get(url)

    if project_id in export_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_answers(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_answers', args=[project_id])
    response = client.get(url)

    if project_id in view_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
@pytest.mark.parametrize('export_format', export_formats)
def test_project_answers_export(db, client, username, password, project_id, export_format):
    client.login(username=username, password=password)

    url = reverse('project_answers_export', args=[project_id, export_format])
    response = client.get(url)

    if project_id in view_project_permission_map.get(username, []):
        assert response.status_code == 200
    else:
        if password:
            assert response.status_code == 403
        else:
            assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_view(db, client, username, password, project_id):
    client.login(username=username, password=password)
    project_views = Project.objects.get(pk=project_id).views.all()

    for view in View.objects.all():
        url = reverse('project_view', args=[project_id, view.id])
        response = client.get(url)

        if project_id in view_project_permission_map.get(username, []):
            if view in project_views:
                assert response.status_code == 200
            else:
                assert response.status_code == 404
        else:
            if password:
                assert response.status_code == 403
            else:
                assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
@pytest.mark.parametrize('export_format', export_formats)
def test_project_view_export(db, client, username, password, project_id, export_format):
    client.login(username=username, password=password)
    project_views = Project.objects.get(pk=project_id).views.all()

    for view in View.objects.all():
        url = reverse('project_view_export', args=[project_id, view.pk, export_format])
        response = client.get(url)

        if project_id in view_project_permission_map.get(username, []):
            if view in project_views:
                assert response.status_code == 200
            else:
                assert response.status_code == 404
        else:
            if password:
                assert response.status_code == 403
            else:
                assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_questions(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_questions', args=[project_id])
    response = client.get(url)

    if project_id in view_project_permission_map.get(username, []):
        assert response.status_code == 200
    elif password:
        assert response.status_code == 403
    else:
        assert response.status_code == 302

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_project_error(db, client, username, password, project_id):
    client.login(username=username, password=password)

    url = reverse('project_questions', args=[project_id])
    response = client.get(url)

    if project_id in view_project_permission_map.get(username, []):
        assert response.status_code == 200
    elif password:
        assert response.status_code == 403
    else:
        assert response.status_code == 302


text:
package org.ml4j.nn.components.builders;

import org.ml4j.nn.components.NeuralComponent;
import org.ml4j.nn.components.NeuralComponentType;
import org.ml4j.nn.components.NeuralComponentVisitor;
import org.ml4j.nn.neurons.Neurons;

/**
 * An example of using a custom NeuralComponent as an alternative to one of the default ml4j NeuralComponents
 * such as DefaultChainableDirectedComponent.
 *
 * Such custom components can be created in InceptionV4 graphs by a InceptionV4Definition in the same way as the default components
 *
 * @author Michael Lavelle
 */
public class ComponentMetadata implements NeuralComponent<ComponentMetadata> {

	/**
	 * Default serialization id.
	 */
	private static final long serialVersionUID = 1L;
	private Neurons inputNeurons;
	private Neurons outputNeurons;
	private String description;

	public ComponentMetadata(String name, Neurons inputNeurons, Neurons outputNeurons, String description) {
		this.description = description;
		this.inputNeurons = inputNeurons;
		this.outputNeurons = outputNeurons;
	}

	public String getDescription() {
		return description;
	}

	@Override
	public String toString() {
		return "ComponentMetadata [inputNeurons=" + inputNeurons + ", outputNeurons=" + outputNeurons + ", description="
				+ description + "]";
	}

	@Override
	public NeuralComponentType getComponentType() {
		return NeuralComponentType.createCustomBaseType(ComponentMetadata.class.getName());
	}

	@Override
	public Neurons getInputNeurons() {
		return inputNeurons;
	}

	@Override
	public Neurons getOutputNeurons() {
		return outputNeurons;
	}

	@Override
	public String getName() {
		return description;
	}

	@Override
	public String accept(NeuralComponentVisitor<ComponentMetadata> visitor) {
		return null;
	}
}


text:
import {REQUEST_API} from '../constants';
import {dispatchAction} from './helpers';

export default store => next => action => {
  const {request, type} = action;

  if (type === REQUEST_API) {
    const rest = sessionStorage.getItem(getKey(request));
    const {success} = request.actions;

    if (rest) {
      action.interrupt = ()=>true;
      dispatchAction(store.dispatch, success, ...JSON.parse(rest));
    } else {
      if (success !== null && request.cache) {
        request.actions.success = proxyDispatch.bind(this, request, store.dispatch, success);
      }
    }
  }

  return next(action);
};

function getKey(request) {
  const {url, method, params} = request;
  return JSON.stringify({url, method, params});
}

function proxyDispatch(request, dispatch, action, ...rest) {
  sessionStorage.setItem(getKey(request), JSON.stringify(rest));
  dispatchAction(dispatch, action, ...rest);
}


text:
/*
 * Copyright 2017 ScyllaDB
 */

#pragma once

#include <limits>
#include <cstdint>
#include <functional>
#include <seastar/util/noncopyable_function.hh>
#include <seastar/util/critical_alloc_section.hh>

namespace seastar {
namespace memory {

///
/// Allocation failure injection framework. Allows testing for exception safety.
///
/// To exhaustively inject failure at every allocation point:
///
///     uint64_t i = 0;
///     while (true) {
///         try {
///             local_failure_injector().fail_after(i++);
///             code_under_test();
///             local_failure_injector().cancel();
///             break;
///         } catch (const std::bad_alloc&) {
///             // expected
///         }
///     }
class alloc_failure_injector {
    uint64_t _alloc_count = 0;
    uint64_t _fail_at = std::numeric_limits<uint64_t>::max();
    noncopyable_function<void()> _on_alloc_failure = [] { throw std::bad_alloc(); };
    bool _failed = false;
private:
    void fail();
public:
    /// \brief Marks a point in code which should be considered for failure injection.
    void on_alloc_point() {
        if (is_critical_alloc_section()) {
            return;
        }
        if (_alloc_count >= _fail_at) {
            fail();
        }
        ++_alloc_count;
    }

    /// Counts encountered allocation points which didn't fail and didn't have failure suppressed.
    uint64_t alloc_count() const {
        return _alloc_count;
    }

    /// Will cause count-th allocation point from now to fail, counting from 0.
    void fail_after(uint64_t count) {
        _fail_at = _alloc_count + count;
        _failed = false;
    }

    /// Cancels the failure scheduled by fail_after().
    void cancel() {
        _fail_at = std::numeric_limits<uint64_t>::max();
    }

    /// Returns true iff allocation was failed since last fail_after().
    bool failed() const {
        return _failed;
    }

    /// Runs given function with a custom failure action instead of the default std::bad_alloc throw.
    void run_with_callback(noncopyable_function<void()> callback, noncopyable_function<void()> to_run);
};

/// \cond internal
extern thread_local alloc_failure_injector the_alloc_failure_injector;
/// \endcond

/// \brief Return the shard-local \ref alloc_failure_injector instance.
inline
alloc_failure_injector& local_failure_injector() {
    return the_alloc_failure_injector;
}

#ifdef SEASTAR_ENABLE_ALLOC_FAILURE_INJECTION

#ifdef SEASTAR_DEFAULT_ALLOCATOR
#error SEASTAR_ENABLE_ALLOC_FAILURE_INJECTION is not supported when using SEASTAR_DEFAULT_ALLOCATOR
#endif

#endif

struct [[deprecated("Use scoped_critical_section instead")]] disable_failure_guard {
    scoped_critical_alloc_section cs;
};

/// \brief Marks a point in code which should be considered for failure injection.
inline
void on_alloc_point() {
#ifdef SEASTAR_ENABLE_ALLOC_FAILURE_INJECTION
    local_failure_injector().on_alloc_point();
#endif
}

/// Repeatedly run func with allocation failures
///
/// Initially, allocations start to fail immediately. In each
/// subsequent run the failures start one allocation later. This
/// returns when func is run and no allocation failures are detected.
void with_allocation_failures(noncopyable_function<void()> func);

}
}


text:
layout:     post
category:   iOS
title:      "Runtime应用(一):Json转Model"
subtitle:   "简易版的JSon转模型"
date:       2017-05-09 12:00:00
author:     "Ted"
header-img: "img/default.jpg"
---

完整版代码可以在[GitHub-JsonToModel](https://github.com/helloted/JsonToModel)下载

### 一、前言

与后台交互,后台返回的数据一般是Json类型的,然而我们的定义的模型一般是继承自NSObject,Json与Model之间的转换,第三方工具也有很多,比如YYModel,JSONModel,MJExtention.

这三个第三方框架的测试效率为YYModel>MJExtention>JsonModel

其中JSon转Model的核心知识点就在于利用Runtime的特点来获取属性以及KVC进行赋值,尝试了一下,封装了一个简易版的工具,一行代码即可完成转换

```
User *user = [User ht_modelFromJson:jsonStr];
```

### 二、流程

首先要引入runtime

```
#import <objc/runtime.h>
```

拿到Model里的所有属性

```
//获取当前类中的所有属性
 unsigned int propertyCount;
 objc_property_t *allPropertys = class_copyPropertyList([self class], &propertyCount);
```

获取属性的name

```
  //拿到属性名称
 NSString *property_name = [NSString stringWithUTF8String:property_getName(property)];
```

以name为key从Json字典里获取值

```
// 从Json字典里获取值
id value = [dict objectForKey:key];
if (value == nil) {
continue;
}
```

KVC赋值

```
[self setValue:value forKey:key];
```

### 三、补充

> 1、拿到的可能不是Json字典,而是Json字符串或者是二进制类型NSData,那么首先要对将Json字符串转成Json字典

```
- (NSDictionary *)dictionaryWithJSON:(id)json
{
    if (!json) {
        return nil;
    }
    // 若是NSDictionary类型,直接返回
    if ([json isKindOfClass:[NSDictionary class]]) {
        return json;
    }

    NSDictionary *dict = nil;
    NSData *jsonData = nil;

    // 如果是NSString,就先转化为NSData
    if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding:NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }

    // 如果时NSData类型,使用NSJSONSerialization
    if (jsonData && [jsonData isKindOfClass:[NSData class]]) {
        NSError *error = nil;
        dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        if (error) {
            NSLog(@"dictionaryWithJSON error:%@", error);
            return nil;
        }
        if (![dict isKindOfClass:[NSDictionary class]]) {
            return nil;
        }
    }

    return dict;
}
```

> 2、如果字典属性与模型属性不完全相同,则需要匹配一下

解决方案是定义一个Protocol

```
@protocol JSONModelSpecialAttributesProtocol <NSObject>

@optional
// 属性匹配
+ (NSDictionary *)attributesMapperDictionary;

// 嵌套模型
+ (NSDictionary *)attributesNestDictionary;

@end
```

如果某个Model与字典不一一匹配,则遵循这个协议,将需要配套的属性返回即可,在赋值的时候,将key现行转换一下

```
    // 某些属性需要重新映射===
    NSDictionary *mapperDict;
    if ([self conformsToProtocol:@protocol(JSONModelSpecialAttributesProtocol)] && [[self class] respondsToSelector:@selector(attributesMapperDictionary)]) {
        mapperDict = [[self class] attributesMapperDictionary];
    }

    // 如果有属性需要重新映射===
    NSString *key = property_name;
    if (mapperDict && [mapperDict objectForKey:property_name]) {
    key = [mapperDict objectForKey:property_name];
    }
```

> 3、如果模型里面嵌套了模型,也是需要先自定义下,在赋值时做个区分

```
      // 如果有属性嵌套其他Model
        if (nestDict && [nestDict objectForKey:property_name]) {
            NSString *className = [nestDict objectForKey:property_name];
            Class class = NSClassFromString(className);
            id obj = [[class alloc]init];
            [obj modelWithJsonDictionary:value];
            [self setValue:obj forKey:key];
        }else{
            [self setValue:value forKey:key];
        }
```

完整版代码可以在[GitHub-JsonToModel](https://github.com/helloted/JsonToModel)下载