text:
#include "CCDefines.h"
#include "CCTextureFontPage.h"
#include "CCObjects.h"
#include "CCSceneBase.h"
#include "CCFileManager.h"

#include "CCDeviceControls.h"
#include "CCDeviceRenderer.h"
#include "CCGLView.h"

CCEngine::CCEngine()
{
	renderFlags = render_all;
	fpsLimit = 1/50.0f;

    // Initialise our gameTime lastUpdate value;
    updateTime();
}

CCEngine::~CCEngine()
{
	scenes.deleteObjectsAndList( true );
	cameras.deleteObjectsAndList();

    delete urlManager;
	delete textureManager;
	delete controls;
	delete renderer;
	delete collisionManager;

	gEngine = NULL;

    CCEngineThreadUnlock();
}

void CCEngine::setupNativeThread()
{
	urlManager = new CCURLManager();
}

static int zCompare(const void *a, const void *b)
{
    const CCSceneCollideable *objectA = CCOctreeGetVisibleCollideables( *(int*)a );
    const CCSceneCollideable *objectB = CCOctreeGetVisibleCollideables( *(int*)b );

    if( objectA->drawOrder == 200 || objectB->drawOrder == 200 )
    {
        if( objectA->drawOrder == 200 && objectB->drawOrder == 200 )
        {
            const CCVector3 &cameraPosition = gEngine->currentCamera->getRotatedPosition();
            const CCVector3 *positionA = objectA->positionPtr;
            const CCVector3 *positionB = objectB->positionPtr;
            const float distanceA = CCVector3Distance( *positionA, cameraPosition, true );
            const float distanceB = CCVector3Distance( *positionB, cameraPosition, true );

            // If A is smaller than B, swap
            return distanceB - distanceA;
        }

        // Largest to the back to be drawn last
        return objectA->drawOrder - objectB->drawOrder;
    }

    // Largest to the back to be drawn last
    return objectA->drawOrder - objectB->drawOrder;

    return 0;
}

void CCEngine::setupEngineThread()
{
    renderer = new CCDeviceRenderer();
    renderer->setup( false, true );
    DEBUG_OPENGL();

    textureManager = new CCTextureManager();
    textureManager->load();
    DEBUG_OPENGL();
    textureManager->loadFont( "HelveticaNeueLight" );
    //textureManager->loadFont( "HelveticaNeueBold" );
    DEBUG_OPENGL();

    controls = new CCDeviceControls();

	currentCamera = NULL;

    collisionManager = new CCCollisionManager( 250000.0f );

	CCOctreeSetRenderSortCallback( &zCompare );

    renderer->setupOpenGL();
    DEBUG_OPENGL();

    // Start Game
    start();
}

void CCEngine::addCamera(CCCameraBase *camera, const int index)
{
    camera->setIndex( cameras.length );
    cameras.add( camera );

    if( index != -1 )
    {
        cameras.reinsert( camera, index );
    }
}

const bool CCEngine::removeCamera(CCCameraBase *camera)
{
	if( cameras.remove( camera ) )
	{
		return true;
	}
	return false;
}

void CCEngine::refreshCameras()
{;
    for( int i=0; i<cameras.length; ++i )
    {
        CCCameraBase *camera = cameras.list[i];
        camera->refreshViewport();
    }
}

void CCEngine::addScene(CCSceneBase *scene, const int index)
{
	scenes.add( scene );
	scene->setup();

    if( index != -1 )
    {
        scenes.reinsert( scene, index );
    }
}

void CCEngine::removeScene(CCSceneBase* scene)
{
	if( scenes.remove( scene ) )
	{
		DELETE_OBJECT( scene );
	}
    else
    {
        ASSERT( false );
    }
}

const double getSystemTime()
{
#ifdef IOS

    const NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];

#elif defined( QT )

    const double currentTime = gView->timer.elapsed() * 0.001;

#elif defined( ANDROID )

    struct timespec res;
	clock_gettime( CLOCK_REALTIME, &res );
	const double currentTime = res.tv_sec + (double)( ( res.tv_nsec / 1e6 ) * 0.001 );

#endif

    return currentTime;
}

const bool CCEngine::updateTime()
{
    double currentTime = getSystemTime();
    gameTime.real = (float)( currentTime - gameTime.lastUpdate );

    // If we're too fast, sleep
	while( gameTime.real < fpsLimit )
	{
        const uint difference = roundf( ( fpsLimit - gameTime.real ) * 1000.0f ) + 1;
		usleep( difference );

		currentTime = getSystemTime();
		gameTime.real = (float)( currentTime - gameTime.lastUpdate );
	}

	// Fake 25 fps
	gameTime.delta = MIN( gameTime.real, 0.04f );

    gameTime.lastUpdate = currentTime;

    return true;
}

const bool CCEngine::updateNativeThread()
{
    // Run callbacks
	if( nativeThreadCallbacks.length > 0 )
    {
        CCEngineThreadLock();
        for( int i=0; i<nativeThreadCallbacks.length; ++i )
        {
            nativeThreadCallbacks.list[i]->run();
            delete nativeThreadCallbacks.list[i];
        }
        nativeThreadCallbacks.length = 0;
        CCEngineThreadUnlock();
    }

    urlManager->updateNativeThread();
	return false;
}

void CCEngine::updateEngineThread()
{
    // Update our system time
    if( updateTime() == false )
    {
#ifdef ANDROID
    	// FIXME: Android needs to always redraw the scene
    	// We currently never return false, so perhaps remove this..
    	renderer->clear();
        renderLoop();
#endif
        return;
    }

	gameTime.lifetime += gameTime.real;

#if LOG_FPS
    static uint loggedUpdates = 0;
    static float loggedDelta = 0.0f;
    loggedUpdates++;
    loggedDelta += gameTime.real;
    if( loggedDelta > 1.0f )
    {
        const float averageFPS = 1.0f / ( loggedDelta / loggedUpdates );
        DEBUGLOG( "Average FPS: %f \n", averageFPS );
        loggedUpdates = 0;
        loggedDelta = 0.0f;
    }
#endif

    // Run callbacks
    {
        CCEngineThreadLock();
        for( int i=0; i<engineThreadCallbacks.length; ++i )
        {
            engineThreadCallbacks.list[i]->run();
            delete engineThreadCallbacks.list[i];
        }
        engineThreadCallbacks.length = 0;
        CCEngineThreadUnlock();
    }

    finishJobs();
	updateLoop();

    renderer->update( gameTime.delta );
	renderer->clear();
    renderLoop();
	renderer->render();

#if defined DEBUGON && TARGET_IPHONE_SIMULATOR
	// 66 frames a second in debug
	//usleep( 15000 );
	usleep( 0 );
#endif
}

void CCEngine::updateLoop()
{
#if defined PROFILEON
    CCProfiler profile( "CCEngine::updateGame()" );
#endif

    // Remove any redundant scenes
    for( int i=0; i<scenes.length; ++i )
	{
		CCSceneBase *scene = scenes.list[i];
        if( scene->shouldDelete() )
		{
            removeScene( scene );
			i--;
		}
	}

    CCEngineThreadLock();
    for( int i=0; i<cameras.length; ++i )
    {
        CCCameraBase *camera = cameras.list[i];
        camera->updateControls();
    }
	controls->update( gameTime );
    CCEngineThreadUnlock();

    // Allow scene to handle the controls first
	for( int i=0; i<scenes.length; ++i )
    {
        if( scenes.list[i]->handleControls( gameTime ) )
        {
            break;
        }
	}

    // Run through our controllers first
    for( int i=0; i<updaters.length; ++i )
    {
        // Delete on finish update
        CCUpdater *updater = updaters.list[i];
        if( updater->update( gameTime.delta ) == false )
        {
            updaters.remove( updater );
            DELETE_OBJECT( updater );
        }
    }

    // Update scene logic
	for( int i=0; i<scenes.length; ++i )
    {
        CCSceneBase *scene = scenes.list[i];
        scene->update( gameTime );
	}
}

void CCEngine::renderLoop()
{
#if defined PROFILEON
    CCProfiler profile( "CCEngine::render()" );
#endif

    // Tell the texture manager we're rendering a new frame
    gEngine->textureManager->prepareRender();
    for( int i=0; i<collisionManager->length; ++i )
    {
        collisionManager->objects[i]->visible = false;
    }

	for( int cameraIndex=0; cameraIndex<cameras.length; ++cameraIndex )
    {
		currentCamera = cameras.list[cameraIndex];
		if( currentCamera->enabled == false )
		{
			continue;
		}

#if defined PROFILEON
		CCProfiler profile( "CCEngine::render()::camera" );
#endif

        currentCamera->setViewport();

		// 2D Background
		{
			CCMatrix matrix;
			CCMatrixLoadIdentity( matrix );
			CCMatrixRotate( matrix, renderer->orientation.current, 0.0f, 0.0f, 1.0f );
			CCMatrixOrtho( matrix, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f );
			GLSetPushMatrix( matrix );

			for( int i=0; i<scenes.length; ++i )
			{
				scenes.list[i]->render2DBackground( cameraIndex );
			}
		}

		// 3D Rendering
		glEnable( GL_DEPTH_TEST );
		extern bool gUseProjectionMatrix;
		gUseProjectionMatrix = true;
		{
			currentCamera->update();

			for( uint pass=render_background; pass<render_finished; ++pass )
			{
#if defined PROFILEON
				CCProfiler profile( "CCEngine::render()::pass" );
#endif

				// Render all the non-collideables
				glDisable( GL_BLEND );
				for( int i=0; i<scenes.length; ++i )
				{
					scenes.list[i]->render( currentCamera, pass, false );
				}

				// Render all the visible collideables
				{
#if defined PROFILEON
					CCProfiler profile( "CCOctreeRenderVisibleObjects( false )" );
#endif
					CCOctreeRenderVisibleObjects( currentCamera, pass, false );
				}

				glEnable( GL_BLEND );

				if( pass == render_main )
				{
					if( HasFlag( gEngine->renderFlags, render_collisionTrees ) )
					{
						CCOctreeRender( collisionManager->tree );
					}
				}

				if( pass == render_main )
				{
					// Keep it disabled for the rest of the renders
					glDisable( GL_DEPTH_TEST );
				}

				for( int i=0; i<scenes.length; ++i )
				{
					scenes.list[i]->render( currentCamera, pass, true );
				}

				// Render all the visible collideables
				{

#if defined PROFILEON
					CCProfiler profile( "CCOctreeRenderVisibleObjects( true )" );
#endif
					CCOctreeRenderVisibleObjects( currentCamera, pass, true );
				}
			}
		}
		gUseProjectionMatrix = false;

		// 2D Rendering
		{
			CCMatrix matrix;
			CCMatrixLoadIdentity( matrix );
			CCMatrixRotate( matrix, renderer->orientation.current, 0.0f, 0.0f, 1.0f );
			CCMatrixOrtho( matrix, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f );
			GLSetPushMatrix( matrix );

            for( int i=0; i<scenes.length; ++i )
            {
                scenes.list[i]->render2DForeground( cameraIndex );
            }

#ifdef DEBUGON
			if( HasFlag( gEngine->renderFlags, render_fontPage ) )
			{
				CCSetColour( CCColour() );
				textureManager->fontPages.list[0]->view();
			}
#endif
		}

		currentCamera = NULL;
	}
}

void CCEngine::finishJobs()
{
#if defined PROFILEON
    CCProfiler profile( "CCEngine::finishJobs()" );
#endif

    CCFileManager::readyIO();

    urlManager->updateEngineThread();

	// Prune the octree
	if( collisionManager->pruneTrees > 0.0f )
	{
		collisionManager->pruneTrees -= gameTime.real;
		if( collisionManager->pruneTrees <= 0.0f )
		{
            //DEBUGLOG( "Octree - prune" );
			CCOctreePruneTree( collisionManager->tree );
		}
	}
}

void CCEngine::restart()
{
    urlManager->flushPendingRequests();
    for( int i=scenes.length-1; i>=0; --i )
    {
        removeScene( scenes.list[i] );
    }

    start();
}

void CCEngine::addCollideable(CCSceneCollideable* collideable)
{
	collisionManager->objects[collisionManager->length++] = collideable;
	CCOctreeAddObject( collisionManager->tree, collideable );
}

void CCEngine::removeCollideable(CCSceneCollideable* collideable)
{
	RemoveFromList( collideable, (void**)collisionManager->objects, &collisionManager->length );
	CCOctreeRemoveObject( collideable );
}

const bool CCEngine::serialize(const bool saving)
{
	return false;
}

void CCEngine::runOnNativeThread(CCLambdaCallback *lambdaCallback)
{
    CCEngineThreadLock();
    nativeThreadCallbacks.add( lambdaCallback );
    CCEngineThreadUnlock();
}

void CCEngine::runOnEngineThread(CCLambdaCallback *lambdaCallback)
{
    CCEngineThreadLock();
    engineThreadCallbacks.add( lambdaCallback );
    CCEngineThreadUnlock();
}


text:
<?php

namespace AppBundle\Tests\Domain\ValueObject\ID;

use AppBundle\Domain\ValueObject\ID;
use InvalidArgumentException;

class ConstructorTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructorSetID()
    {
        $idValue = 1234;

        $id = new ID($idValue);
        $this->assertSame($idValue, $id->getId());
        $this->assertSame('1234', (string) $id);
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testConstructorSetNotInt()
    {
        $idValue = 'Bob';
        new ID($idValue);
    }
}

redpajama_set_name: RedPajamaGithub


text:
echo ">>> Installing Symfony"

# Test if PHP is installed
php -v > /dev/null 2>&1 || { printf "!!! PHP is not installed.\n    Installing Symfony aborted!\n"; exit 0; }

# Test if Composer is installed
composer -v > /dev/null 2>&1 || { printf "!!! Composer is not installed.\n    Installing Symfony aborted!\n"; exit 0; }

# Test if Server IP is set in Vagrantfile
[[ -z "$1" ]] && { printf "!!! IP address not set. Check the Vagrantfile.\n    Installing Symfony aborted!\n"; exit 0; }

# Check if Symfony root is set. If not set use default
if [ -z "$2" ]; then
    symfony_root_folder="/vagrant/symfony"
else
    symfony_root_folder="$2"
fi

symfony_public_folder="$symfony_root_folder/web"

# The host ip is same as guest ip with last octet equal to 1
host_ip=`echo $1 | sed 's/\.[0-9]*$/.1/'`

# Test if HHVM is installed
hhvm --version > /dev/null 2>&1
HHVM_IS_INSTALLED=$?

# Test if Apache or Nginx is installed
nginx -v > /dev/null 2>&1
NGINX_IS_INSTALLED=$?

apache2 -v > /dev/null 2>&1
APACHE_IS_INSTALLED=$?

# Create Symfony folder if needed
if [ ! -d $symfony_root_folder ]; then
    mkdir -p $symfony_root_folder
fi

if [ ! -f "$symfony_root_folder/composer.json" ]; then
    # Create Symfony
    if [ $HHVM_IS_INSTALLED -eq 0 ]; then
        hhvm /usr/local/bin/composer create-project --prefer-dist symfony/framework-standard-edition $symfony_root_folder
    else
        composer create-project --prefer-dist symfony/framework-standard-edition $symfony_root_folder
    fi
else
    # Go to vagrant folder
    cd $symfony_root_folder

    # Install Symfony
    if [ $HHVM_IS_INSTALLED -eq 0 ]; then
        hhvm /usr/local/bin/composer install --prefer-dist
    else
        composer install --prefer-dist
    fi

    # Go to the previous folder
    cd -
fi

sudo chmod -R 775 $symfony_root_folder/app/cache
sudo chmod -R 775 $symfony_root_folder/app/logs
sudo chmod -R 775 $symfony_root_folder/app/console

sed -i "s/('127.0.0.1', 'fe80::1'/('127.0.0.1', '$host_ip', 'fe80::1'/" $symfony_public_folder/app_dev.php
sed -i "s/'127.0.0.1',$/'127.0.0.1', '$host_ip',/" $symfony_public_folder/config.php

if [ $NGINX_IS_INSTALLED -eq 0 ]; then
    # Change default vhost created
    sudo sed -i "s@root /vagrant@root $symfony_public_folder@" /etc/nginx/sites-available/vagrant
    sudo service nginx reload
fi

if [ $APACHE_IS_INSTALLED -eq 0 ]; then
    # Find and replace to find public_folder and replace with laravel_public_folder
    # Change DocumentRoot
    # Change ProxyPassMatch fcgi path
    # Change <Directory ...> path
    sudo sed -i "s@$3@$symfony_public_folder@" /etc/apache2/sites-available/$1.xip.io.conf

    sudo service apache2 reload
fi


text:
const newFile = require('../utils/newFile');
const askQuestions = require('../utils/askQuestion');
const configAssets = require('../../assets/configs/config');

module.exports = async (projectPath, projectName, type) => {
  const config = configAssets(type);
  let hasDatabase;

  config.server.connection.host = await askQuestions(`What is your ${type} server host (default: localhost) : `) || 'localhost';
  config.server.auth.secretKey = await askQuestions(`What is your ${type} secret key (default: ChangeThisSecret) : `) || 'ChangeThisSecret';

  if (type !== 'default') {
    hasDatabase = await askQuestions(`Do you want a database for the ${type} env ? (Y/n) : `);
  }

  if (type === 'default' || hasDatabase.toLowerCase() === 'y') {
    config.mongodb = {};
    const host = await askQuestions(`What is your ${type} database host (default: localhost) : `) || 'localhost';
    const name = await askQuestions(`What is your ${type} database name (default: ${projectName} ) : `) || projectName;
    const user = await askQuestions(`What is your ${type} database user (if none, no authentication) : `) || null;
    if (user) {
      const password = await askQuestions(`What is your ${type} database password (default: admin) : `) || 'admin';
      config.mongodb.uri = `mongodb://${user}:${password}@${host}/${name}`;
    } else {
      config.mongodb.uri = `mongodb://${host}/${name}`;
    }
    await newFile({
      projectPath,
      filePath: '/utils/',
      fileName: 'db',
      fileType: 'js',
      hasModel: true,
      outputFilePath: '/services/utils/',
    });
  }

  await newFile({
    projectPath,
    filePath: 'config/',
    fileName: type,
    fileType: 'json',
    fileContent: config,
  });
};


text:
<?php

	require_once("include/session.php");

	$pageTitle = "No Access";

	$phpbms->cssIncludes[] = "pages/search.css";

	include("header.php");
?>

Access Denied

You currently do not have privileges to view this resource.

<?php include("footer.php");?>


text:
shared_examples_for 'a Json authentication error' do
  it_behaves_like(
    'a json object with an error',
    'You need to sign in or sign up before continuing.'
  )
end

shared_examples_for 'a Json authorization error' do
  it_behaves_like(
    'a json object with an error',
    'You are not authorized to access this page.'
  )
end

shared_examples_for 'a blank response' do
  describe 'displays nothing' do
    subject { response.body }
    it { should eq '' }
  end
end

shared_examples_for 'a graphql object '\
                    'showing an item' do |object|
  describe 'displays an item' do
    subject { JSON.parse(response.body)['data'][object.table_name.singularize] }
    it { should be_a Hash }
  end
end

shared_examples_for 'a graphql object '\
                    'listing a collection of items' do |object|
  describe 'displays a collection of items' do
    subject { JSON.parse(response.body)['data'][object.table_name] }
    it { should be_an Array }
  end
end


text:
package org.unitime.timetable.gwt.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.unitime.timetable.gwt.client.widgets.UniTimeFrameDialog;
import org.unitime.timetable.gwt.command.client.GwtRpcException;
import org.unitime.timetable.gwt.resources.GwtConstants;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.PageAccessException;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.shared.UmbrellaException;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Tomas Muller
 */
public class ToolBox {
	public static final GwtConstants CONSTANTS = GWT.create(GwtConstants.class);
	public static final GwtMessages MESSAGES = GWT.create(GwtMessages.class);

	public native static void disableTextSelectInternal(Element e)/*-{
		e.ondrag = function () { return false; };
		e.onselectstart = function () { return false; };
		e.style.MozUserSelect="none"
	}-*/;

	public native static int getScrollBarWidth() /*-{

		var inner = document.createElement("p");
		inner.style.width = "100%";
		inner.style.height = "200px";

		var outer = document.createElement("div");
		outer.style.position = "absolute";
		outer.style.top = "0px";
		outer.style.left = "0px";
		outer.style.visibility = "hidden";
		outer.style.width = "200px";
		outer.style.height = "150px";
		outer.style.overflow = "hidden";
		outer.appendChild (inner);

		document.body.appendChild (outer);
		var w1 = inner.offsetWidth;
		outer.style.overflow = "scroll";
		var w2 = inner.offsetWidth;
		if (w1 == w2) w2 = outer.clientWidth;

		document.body.removeChild (outer);

		return (w1 - w2);
	}-*/;

	public static native void printw(String html) /*-{
		var win = (html ? $wnd.open("about:blank", "__printingWindow") : $wnd);
		var doc = win.document;

		if (html) {
			doc.open();
			doc.write(html);
			doc.write("");
			doc.close();
		}

		win.focus();
	}-*/;

	public static native void printf(String html) /*-{
		if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
			@org.unitime.timetable.gwt.client.ToolBox::printw(Ljava/lang/String;)(html);
			return;
		}

    	var frame = $doc.frames ? $doc.frames['__printingFrame'] : $doc.getElementById('__printingFrame');
        if (!frame) {
			@org.unitime.timetable.gwt.client.ToolBox::printw(Ljava/lang/String;)(html);
            return;
        }

        var doc = null;
        if (frame.contentDocument)
            doc = frame.contentDocument;
        else if (frame.contentWindow)
            doc = frame.contentWindow.document;
        else if (frame.document)
            doc = frame.document;
        if (!doc)  {
			@org.unitime.timetable.gwt.client.ToolBox::printw(Ljava/lang/String;)(html);
            return;
        }

        if (html) {
        	doc.open();
        	doc.write(html);
        	doc.close();
        }

        if (doc.readyState && doc.readyState!='complete') {
        	setTimeout(function() {
        		@org.unitime.timetable.gwt.client.ToolBox::printf(Ljava/lang/String;)(null);
        	}, 50);
        } else if (doc.body && doc.body.innerHTML=='false') {
        	setTimeout(function() {
        		@org.unitime.timetable.gwt.client.ToolBox::printf(Ljava/lang/String;)(null);
        	}, 50);
        } else {
        	if (frame.contentWindow) frame = frame.contentWindow;
        	frame.focus();
        	frame.print();
        }
    }-*/;

    public static void print(String title, String user, String session, Widget... widgets) {
    	String content = "";
    	for (Widget w: widgets)
    		content += "
" + w.getElement().getString() + "
";
    	String html = "" +
    		"<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" +
    		"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + GWT.getHostPageBaseURL() + "unitime/gwt/standard/standard.css\">" +
    		"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + GWT.getHostPageBaseURL() + "styles/unitime.css\">" +
    	    "<link rel=\"shortcut icon\" href=\"" + GWT.getHostPageBaseURL() + "images/timetabling.ico\">" +
    	    "<title>UniTime " + CONSTANTS.version() + "| University Timetabling Application</title>" +
    		"" +
    	    "" +
    			""+
    				"" +
    					""+
    						""+
    						""+
    							"" + title + ""+
    							"" +
    								""+
    									"" +
    										"" + user + "" +
    										"" + session + "" +
    									"" +
    								"" +
    							"" +
    						"" +
    					"" +
    				"" +
    				"" + content + "" +
    			"" +
    			"" +
    				"" +
    					"" +
    						"Printed from UniTime " + CONSTANTS.version() + " | University Timetabling Application" +
    						"" + CONSTANTS.copyright() + "" +
    						"" + DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_MEDIUM).format(new Date()) + "" +
    					"" +
    				"" +
    			"" +
    		"";
    	printf(html);
    }

    public static void print(List<Page> pages) {
    	String html = "" +
        		"<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" +
        		"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + GWT.getHostPageBaseURL() + "unitime/gwt/standard/standard.css\">" +
        		"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + GWT.getHostPageBaseURL() + "styles/unitime.css\">" +
        	    "<link rel=\"shortcut icon\" href=\"" + GWT.getHostPageBaseURL() + "images/timetabling.ico\">" +
        	    "<title>UniTime " + CONSTANTS.version() + "| University Timetabling Application</title>" +
        		"";
    	for (Page p: pages) {
    		html += "" +
    					"" +
    						""+
    							"" +
    								""+
    									""+
    									""+
    										"" + p.getName() + ""+
    										"" +
    											""+
    												"" +
    													"" + p.getUser() + "" +
    													"" + p.getSession() + "" +
    												"" +
    											"" +
    										"" +
    									"" +
    								"" +
    							"" +
    							"" + p.getBody().getString() + "" +
    						"" +
    						"" +
    							"" +
    								"" +
    									"Printed from UniTime " + CONSTANTS.version() + " | University Timetabling Application" +
    									"" + CONSTANTS.copyright() + "" +
    									"" + DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_MEDIUM).format(new Date()) + "" +
    								"" +
    							"" +
    						"" +
    					"" +
    				"";
    	}
    	html += "";
    	printf(html);
    }

    public static void print(Page... pages) {
    	List<Page> list = new ArrayList<Page>();
    	for (Page page: pages) list.add(page);
    	print(list);
    }

	public native static void open(String url) /*-{
		$wnd.location = url;
	}-*/;

	public native static String eval(String script) /*-{
		return eval(script);
	}-*/;

	public static void checkAccess(Throwable t) {
		if (t != null && t instanceof GwtRpcException && t.getCause() != null) t = t.getCause();
		if (t != null && t instanceof PageAccessException) {
			UniTimeFrameDialog.openDialog("UniTime " + CONSTANTS.version() + "| Log In", "login.do?menu=hide&m=" + URL.encodeQueryString(t.getMessage())
					+"&target=" + URL.encodeQueryString(Window.Location.getHref()), "700px", "420px");
		}
	}

	public native static void setWhiteSpace(Style style, String value) /*-{
		style.whiteSpace = value;
	}-*/;

	public native static void setMaxHeight(Style style, String value) /*-{
		style.maxHeight = value;
	}-*/;

	public native static void setMaxWidth(Style style, String value) /*-{
		style.maxWidth = value;
	}-*/;

	public native static void setMinWidth(Style style, String value) /*-{
		style.minWidth = value;
	}-*/;

	public native static String getMinWidth(Style style) /*-{
		return style.minWidth;
	}-*/;

	public native static int getClientWidth() /*-{
		var sideMenu = $doc.getElementById("unitime-SideMenu");
		if (!sideMenu) return $doc.body.clientWidth;
		var sideMenuSpans = sideMenu.getElementsByTagName("span");
    	if (sideMenuSpans.length > 0) {
    		return $doc.body.clientWidth - sideMenuSpans[0].clientWidth;
    	} else {
    		return $doc.body.clientWidth;
    	}
	}-*/;

	public native static void scrollToElement(Element element)/*-{
		element.scrollIntoView();
	}-*/;

	public static Throwable unwrap(Throwable e) {
		if (e == null) return null;
		if (e instanceof UmbrellaException) {
			UmbrellaException ue = (UmbrellaException) e;
			if (ue.getCauses().size() == 1) {
				return unwrap(ue.getCauses().iterator().next());
			}
		}
		return e;
	}

	public static interface Page {
		public String getName();
		public String getUser();
		public String getSession();
		public Element getBody();
	}

	public static String toString(Collection<String> items) {
		if (items == null || items.isEmpty()) return "";
		if (items.size() == 1) return items.iterator().next();
		if (items.size() == 2) {
			Iterator<String> i = items.iterator();
			return MESSAGES.itemSeparatorPair(i.next(), i.next());
		} else {
			Iterator<String> i = items.iterator();
			String list = i.next();
			while (i.hasNext()) {
				String item = i.next();
				if (i.hasNext())
					list = MESSAGES.itemSeparatorMiddle(list, item);
				else
					list = MESSAGES.itemSeparatorLast(list, item);
			}
			return list;
		}
	}
}


text:
package kata.test;

import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.set.primitive.IntSet;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.factory.primitive.IntSets;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
import org.eclipse.collections.impl.test.Verify;
import org.eclipse.collections.impl.tuple.Tuples;
import com.gs.fw.common.mithra.MithraManagerProvider;
import kata.domain.Customer;
import kata.domain.CustomerAccountFinder;
import kata.domain.CustomerAccountList;
import kata.domain.CustomerFinder;
import kata.domain.CustomerList;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExercisesRelationships
        extends AbstractMithraTest
{
    private static final Logger LOGGER = LoggerFactory.getLogger(ExercisesRelationships.class);

    @Override
    protected String[] getTestDataFilenames()
    {
        return new String[]{"testdata/data_CustomersAndAccounts.txt"}; // Look into this file to see the test data being used
    }

// Create a relationship on Customer called "accounts".
// When you regenerate, this should create a getAccounts() method on Customer, and an accounts() relationship in CustomerFinder.
// Use this to answer the following questions.
// Also make this relationship bi-directional so that it also creates a customer() relationship on CustomerAccount.
// Question:
// What is the impact on the footprint of Mithra when you add a new relationship?
// Answer: NONE! Relationships are not intrusive and don't cause any extra objects to be loaded.

//------------------------ Question 1 --------------------------------------------------------
// Get all accounts of a particular customer.

    public CustomerAccountList getAccountsForCustomer(Customer customer)
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ1()
    {
        Customer customer = CustomerFinder.findOne(CustomerFinder.customerId().eq(1));
        CustomerAccountList customerAccounts = this.getAccountsForCustomer(customer);
        Verify.assertSize(3, customerAccounts);

        Assert.assertNotNull(CustomerFinder.getRelatedFinderByName("accounts"));
    }

//------------------------ Question 2 --------------------------------------------------------
// Get all customers that have accounts of a particular type.

    public CustomerList getCustomersThatHaveAccountType(String accountType)
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ2()
    {
        CustomerList customers = this.getCustomersThatHaveAccountType("Savings");
        Verify.assertSetsEqual(UnifiedSet.newSetWith("Yusuke Sato", "John Smith"),
                customers.asEcList().collect(CustomerFinder.name()).toSet());

        Assert.assertNotNull(CustomerAccountFinder.getRelatedFinderByName("customer"));
    }

//--------------------------- Question 3 -------------------------------------------------------
// Create another relationship on Customer that takes one parameter "accountType"
// and returns all the Accounts of the customer that have the particular account type.
// Call this relationship "accountsOfType".

    @Test
    public void testQ3()
    {
        // Implement your solution here.

        // Notes:
        // 1) The test below will not compile until you add the new relationship.
        // 2) You need to enable the test below by uncommenting the commented line
        //    once you have created the new relationship.
        // 3) Don't forget to re-run your build to see the new relationship
        //    get generated.

        Customer john = CustomerFinder.findOne(CustomerFinder.customerId().eq(1));
        CustomerAccountList savingAccounts = null;
        Assert.fail("Uncomment the following line to enable this test");
//        savingAccounts = john.getAccountsOfType("Savings");
        Verify.assertSize(2, savingAccounts);
    }

//--------------------------- Question 4 -------------------------------------------------------
// Add new customer with a list of accounts given as parameter.
// You can assume that the customer does not exist.
// Remember you will need to get Mithra to generate the new accountIds for you.

    public void addCustomerAccounts(String name, String location, MutableList<Pair<String, String>> accountDescriptionAndTypePairs)
    {
        Assert.fail("Implement this functionality to make the test pass");
    }

    @Test
    public void testQ4()
    {
        CustomerAccountList accountsBefore = CustomerAccountFinder.findMany(CustomerAccountFinder.all());
        CustomerList customersBefore = CustomerFinder.findMany(CustomerFinder.all());
        accountsBefore.forceResolve(); //to get this list resolved before we add the new customer.
        customersBefore.forceResolve();

        MutableList<Pair<String, String>> accountDescriptionAndTypePairs = FastList.newListWith(
                Tuples.pair("Tom's saving Account", "Savings"),
                Tuples.pair("Tom's running Account", "Running")
        );

        this.addCustomerAccounts("Tom Jones", "UK", accountDescriptionAndTypePairs);

        CustomerAccountList accountsAfter = CustomerAccountFinder.findMany(CustomerAccountFinder.all());
        CustomerList customersAfter = CustomerFinder.findMany(CustomerFinder.all());

        Assert.assertEquals(1, customersAfter.size() - customersBefore.size());
        Assert.assertEquals(2, accountsAfter.size() - accountsBefore.size());

        Customer tom = CustomerFinder.findOne(CustomerFinder.name().eq("Tom Jones"));
        CustomerAccountList tomsAccounts = new CustomerAccountList(CustomerAccountFinder.customerId().eq(tom.getCustomerId()));
        Verify.assertSize(2, tomsAccounts);
    }

//------------------------- Question 5 -----------------------------------------------------------------------
// Given a list of customerIds, get a list of customers, but also deep fetch all related CustomerAccounts
// so that Mithra will not do single selects on CustomerAccount whenever we try to access an account.
// ie. if we call customers.get(0).getAccounts(); we don't want to go to the database again.
// Quiz1: How can you only deep fetch only Running accounts?
// Quiz2: Can you deep fetch without having the "accounts" relationship defined?
//
// Note: There is no good way to test whether deep fetching has happened as Mithra will perform
// single selects behind the scenes.  Best you can do is turn on sql logging and count the number
// of DB hits.

    public CustomerList getCustomers(IntSet customerIds)
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ5()
    {
        IntSet accountIds = IntSets.immutable.of(1, 2, 999);
        CustomerList customers = getCustomers(accountIds);
        Verify.assertSize(2, customers);

        int dbHitsBefore = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
        // Try un-commenting the following lines, running the test, and then
        // look at the debug messages output.
//        System.out.println("No more SQL SELECT after this point ...");
//        customers.getCustomerAt(0).getAccounts().size();
//        System.out.println("----====----");
//        customers.getCustomerAt(1).getAccounts().size();
//        System.out.println("----====****====----");
        Assert.assertEquals(dbHitsBefore, MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount());
    }

//------------------------- Question 6 -----------------------------------------------------------------------
// Find customers that don't have any accounts.

    public CustomerList getCustomersWithoutAccounts()
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ6()
    {
        CustomerList customers = getCustomersWithoutAccounts();

        Verify.assertSetsEqual(UnifiedSet.newSetWith("Lisbeth Salander", "Mikael Blomkvist"),
                customers.asEcList().collect(CustomerFinder.name()).toSet());
    }
}


text:
package org.elasticsearch.action.admin.indices.cache.clear;

import org.elasticsearch.action.support.DefaultShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.BroadcastResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.xcontent.ConstructingObjectParser;
import org.elasticsearch.xcontent.XContentParser;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * The response of a clear cache action.
 */
public class ClearIndicesCacheResponse extends BroadcastResponse {

    private static final ConstructingObjectParser<ClearIndicesCacheResponse, Void> PARSER = new ConstructingObjectParser<>(
        "clear_cache",
        true,
        arg -> {
            BroadcastResponse response = (BroadcastResponse) arg[0];
            return new ClearIndicesCacheResponse(
                response.getTotalShards(),
                response.getSuccessfulShards(),
                response.getFailedShards(),
                Arrays.asList(response.getShardFailures())
            );
        }
    );

    static {
        declareBroadcastFields(PARSER);
    }

    ClearIndicesCacheResponse(StreamInput in) throws IOException {
        super(in);
    }

    ClearIndicesCacheResponse(
        int totalShards,
        int successfulShards,
        int failedShards,
        List<DefaultShardOperationFailedException> shardFailures
    ) {
        super(totalShards, successfulShards, failedShards, shardFailures);
    }

    public static ClearIndicesCacheResponse fromXContent(XContentParser parser) {
        return PARSER.apply(parser, null);
    }
}


text:
var AuthenticationController = require('./controllers/authentication'),
    TodoController = require('./controllers/todos'),
    express = require('express'),
    passportService = require('../config/passport'),
    passport = require('passport');

var requireAuth = passport.authenticate('jwt', {session: false}),
    requireLogin = passport.authenticate('local', {session: false});

module.exports = function(app){

    var apiRoutes = express.Router(),
        authRoutes = express.Router(),
        todoRoutes = express.Router();

    // Auth Routes
    apiRoutes.use('/auth', authRoutes);

    authRoutes.post('/register', AuthenticationController.register);
    authRoutes.post('/login', requireLogin, AuthenticationController.login);

    authRoutes.get('/protected', requireAuth, function(req, res){
        res.send({ content: 'Success'});
    });

    // Todo Routes
    apiRoutes.use('/todos', todoRoutes);

    todoRoutes.get('/', requireAuth, AuthenticationController.roleAuthorization(['reader','creator','editor']), TodoController.getTodos);
    todoRoutes.post('/', requireAuth, AuthenticationController.roleAuthorization(['creator','editor']), TodoController.createTodo);
    todoRoutes.delete('/:todo_id', requireAuth, AuthenticationController.roleAuthorization(['editor']), TodoController.deleteTodo);

    // Set up routes
    app.use('/api', apiRoutes);

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="android_upgrading_apk">App %1$d ng %2$d.</string>
    <string name="permgrouplab_sensors">Mga Sensor</string>
</resources>


text:
use chrono::{DateTime, Utc};

#[allow(non_snake_case)]
#[derive(Debug, Default, PartialEq, Serialize, FromXmlStream)]
pub struct ShippingAddress {
  pub StateOrRegion: String,
  pub City: String,
  pub CountryCode: String,
  pub PostalCode: String,
  pub Name: String,
  pub AddressLine1: String,
  pub AddressLine2: String,
  pub Phone: Option<String>,
}

#[allow(non_snake_case)]
#[derive(Debug, Default, PartialEq, Serialize, FromXmlStream)]
pub struct CurrencyAmount {
  pub CurrencyCode: String,
  pub Amount: String,
}

#[allow(non_snake_case)]
#[derive(Debug, Default, PartialEq, Serialize, FromXmlStream)]
pub struct Order {
  /// An Amazon-defined order identifier, in 3-7-7 format.
  pub AmazonOrderId: String,
  /// A seller-defined order identifier.
  pub SellerOrderId: String,
  /// The date when the order was created.
  pub PurchaseDate: Option<DateTime<Utc>>,
  /// The date when the order was last updated.
  pub LastUpdateDate: Option<DateTime<Utc>>,
  /// The current order status.
  pub OrderStatus: OrderStatus,
  /// How the order was fulfilled: by Amazon (AFN) or by the seller (MFN).
  pub FulfillmentChannel: FulfillmentChannel,
  /// The sales channel of the first item in the order.
  pub SalesChannel: String,
  /// The order channel of the first item in the order.
  pub OrderChannel: String,
  /// The shipment service level of the order.
  pub ShipServiceLevel: String,
  /// The shipping address for the order.
  pub ShippingAddress: Option<ShippingAddress>,
  /// The total charge for the order.
  pub OrderTotal: Option<CurrencyAmount>,
  /// The number of items shipped.
  pub NumberOfItemsShipped: i32,
  /// The number of items unshipped.
  pub NumberOfItemsUnshipped: i32,

  // pub PaymentExecutionDetail: ?
  /// The payment method for the order.
  /// This response element is limited to Cash On Delivery (COD)
  /// and Convenience Store (CVS) payment methods.
  /// Unless you need the specific COD payment information provided
  /// by the PaymentExecutionDetailItem element, we recommend using
  /// the PaymentMethodDetails response element to get payment
  /// method information.
  pub PaymentMethod: PaymentMethod,

  // pub PaymentMethodDetails: ?
  /// true if this is a replacement order.
  pub IsReplacementOrder: bool,
  /// The AmazonOrderId value for the order that is being replaced.
  pub ReplacedOrderId: String,
  /// The anonymized identifier for the Marketplace where the order was placed.
  pub MarketplaceId: String,
  /// The anonymized e-mail address of the buyer.
  pub BuyerEmail: String,
  /// The name of the buyer.
  pub BuyerName: String,
  /// The county of the buyer.
  /// This element is used only in the Brazil marketplace.
  pub BuyerCounty: String,

  // pub BuyerTaxInfo: ?
  /// The shipment service level category of the order.
  /// ShipmentServiceLevelCategory values: Expedited, FreeEconomy, NextDay, SameDay, SecondDay, Scheduled, Standard
  pub ShipmentServiceLevelCategory: String,
  /// true if the order was shipped by the Amazon Transportation for Merchants (Amazon TFM) service.
  /// Amazon TFM is available only in the China marketplace.
  pub ShippedByAmazonTFM: bool,
  /// The status of the Amazon TFM order. Returned only if
  /// ShippedByAmazonTFM = True. Note that even if ShippedByAmazonTFM = True,
  /// TFMShipmentStatus will not be returned if you have
  /// not yet created the shipment.
  /// TFMShipmentStatus values: PendingPickUp, LabelCanceled, PickedUp,
  /// AtDestinationFC, Delivered, RejectedByBuyer, Undeliverable,
  /// ReturnedToSeller
  /// Amazon TFM is available only in the China marketplace.
  pub TFMShipmentStatus: String,
  /// The status of the Amazon Easy Ship order.
  /// This element is included only for Amazon Easy Ship orders.
  /// EasyShipShipmentStatus values: PendingPickUp, LabelCanceled,
  /// PickedUp, OutForDelivery, Damaged, Delivered, RejectedByBuyer,
  /// Undeliverable, ReturnedToSeller
  /// Amazon Easy Ship is available only in the India marketplace.
  pub EasyShipShipmentStatus: String,
  /// The type of the order.
  pub OrderType: String,
  /// The start of the time period that you have committed to
  /// ship the order. In ISO 8601 date time format.
  pub EarliestShipDate: Option<DateTime<Utc>>,
  /// The end of the time period that you have committed to ship
  /// the order. In ISO 8601 date time format.
  pub LatestShipDate: Option<DateTime<Utc>>,
  /// The start of the time period that you have commited to fulfill
  /// the order. In ISO 8601 date time format.
  pub EarliestDeliveryDate: Option<DateTime<Utc>>,
  /// The end of the time period that you have commited to fulfill the order.
  /// In ISO 8601 date time format.
  pub LatestDeliveryDate: Option<DateTime<Utc>>,
  /// true if the order is an Amazon Business order.
  /// An Amazon Business order is an order where the buyer is a
  /// Verified Business Buyer and the seller is an Amazon Business Seller.
  /// For more information about the Amazon Business Seller Program,
  /// see the Amazon Business website.
  pub IsBusinessOrder: bool,
  /// The purchase order (PO) number entered by the buyer at checkout.
  pub PurchaseOrderNumber: String,
  /// true if the order is a seller-fulfilled Amazon Prime order.
  pub IsPrime: bool,
  /// true if the order has a Premium Shipping Service Level Agreement.
  /// For more information about Premium Shipping orders,
  /// see "Premium Shipping Options" in the Seller Central Help for
  /// your marketplace.
  pub IsPremiumOrder: bool,
  /// Indicates the date by which the seller must respond to the buyer
  /// with an Estimated Ship Date.
  pub PromiseResponseDueDate: Option<DateTime<Utc>>,
  /// true if the Estimated Ship Date is set for the order.
  pub IsEstimatedShipDateSet: bool,
}

str_enum! {
  /// A list of OrderStatus values. Used to select orders with a current status that matches
  /// one of the status values that you specify.
  ///
  /// Unshipped and PartiallyShipped must be used together in this version of the Orders API
  /// section. Using one and not the other returns an error.
  ///
  /// [Reference](http://docs.developer.amazonservices.com/en_CA/orders-2013-09-01/Orders_ListOrders.html)
  pub enum OrderStatus {
    PendingAvailability,
    Pending,
    Unshipped,
    PartiallyShipped,
    Shipped,
    InvoiceUnconfirmed,
    Canceled,
    Unfulfillable,
  }
}

str_enum! {
  ///	A list that indicates how an order was fulfilled.
  ///
  /// [Reference](http://docs.developer.amazonservices.com/en_CA/orders-2013-09-01/Orders_ListOrders.html)
  pub enum FulfillmentChannel {
    AFN,
    MFN,
  }
}

str_enum! {
  /// A list of PaymentMethod values. Used to select orders paid for with the payment methods
  /// that you specify.
  ///
  /// Note: COD and CVS values are valid only in Japan (JP).
  pub enum PaymentMethod {
    COD,
    CVS,
    Other,
  }
}

str_enum! {
  /// A list of TFMShipmentStatus values. Used to select Amazon Transportation for Merchants (TFM)
  /// orders with a current status that matches one of the status values that you specify.
  /// If TFMShipmentStatus is specified, only TFM orders are returned.
  ///
  /// Note: The TFMShipmentStatus request parameter is available only in China (CN).
  pub enum TFMShipmentStatus {
    PendingPickUp,
    LabelCanceled,
    PickedUp,
    AtDestinationFC,
    Delivered,
    RejectedByBuyer,
    Undeliverable,
    ReturnedToSeller,
    Lost,
  }
}

#[allow(non_snake_case)]
#[derive(Debug, Default, PartialEq, Serialize, FromXmlStream)]
pub struct OrderItem {
  pub OrderItemId: String,
  pub QuantityOrdered: i32,
  pub Title: String,
  pub ASIN: String,
  pub SellerSKU: String,
  pub QuantityShipped: i32,
  pub ItemPrice: Option<CurrencyAmount>,
  pub ItemTax: Option<CurrencyAmount>,
  pub GiftWrapPrice: Option<CurrencyAmount>,
  pub GiftWrapTax: Option<CurrencyAmount>,
  pub PromotionDiscount: Option<CurrencyAmount>,
  pub ShippingPrice: Option<CurrencyAmount>,
  pub ShippingDiscount: Option<CurrencyAmount>,
  pub ShippingTax: Option<CurrencyAmount>,
  pub IsTransparency: bool,
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_decode_order() {
    test_decode!(
      Order,
      r#"
        <LatestShipDate>2018-12-18T07:59:59Z</LatestShipDate>
        <OrderType>StandardOrder</OrderType>
        <SellerOrderId>666</SellerOrderId>
        <PurchaseDate>2018-12-16T18:53:45.856Z</PurchaseDate>
        <AmazonOrderId>111-3081581-6666666</AmazonOrderId>
        <BuyerEmail>666@marketplace.amazon.com</BuyerEmail>
        <IsReplacementOrder>false</IsReplacementOrder>
        <LastUpdateDate>2018-12-17T16:50:11.820Z</LastUpdateDate>
        <NumberOfItemsShipped>1</NumberOfItemsShipped>
        <ShipServiceLevel>Std US D2D Dom</ShipServiceLevel>
        <OrderStatus>Shipped</OrderStatus>
        <SalesChannel>Amazon.com</SalesChannel>
        <ShippedByAmazonTFM>false</ShippedByAmazonTFM>
        <IsBusinessOrder>false</IsBusinessOrder>
        <LatestDeliveryDate>2018-12-27T07:59:59Z</LatestDeliveryDate>
        <NumberOfItemsUnshipped>0</NumberOfItemsUnshipped>
        <PaymentMethodDetails>
          <PaymentMethodDetail>Standard</PaymentMethodDetail>
        </PaymentMethodDetails>
        <BuyerName>First Last</BuyerName>
        <EarliestDeliveryDate>2018-12-20T08:00:00Z</EarliestDeliveryDate>
        <OrderTotal>
          <CurrencyCode>USD</CurrencyCode>
          <Amount>666.66</Amount>
        </OrderTotal>
        <IsPremiumOrder>false</IsPremiumOrder>
        <EarliestShipDate>2018-12-17T08:00:00Z</EarliestShipDate>
        <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
        <FulfillmentChannel>MFN</FulfillmentChannel>
        <PaymentMethod>Other</PaymentMethod>
        <ShippingAddress>
          <City>SAN MATEO</City>
          <AddressType>Residential</AddressType>
          <PostalCode>92683-4617</PostalCode>
          <isAddressSharingConfidential>false</isAddressSharingConfidential>
          <StateOrRegion>CA</StateOrRegion>
          <CountryCode>US</CountryCode>
          <Name>First Last</Name>
          <AddressLine1>8888 J AVE</AddressLine1>
        </ShippingAddress>
        <IsPrime>true</IsPrime>
        <ShipmentServiceLevelCategory>Standard</ShipmentServiceLevelCategory>"#,
      Order {
        LatestShipDate: Some(
          "2018-12-18T07:59:59Z"
            .parse()
            .expect("parse LatestShipDate",)
        ),
        OrderType: "StandardOrder".to_string(),
        PurchaseDate: Some(
          "2018-12-16T18:53:45.856Z"
            .parse()
            .expect("parse PurchaseDate")
        ),
        AmazonOrderId: "111-3081581-6666666".to_string(),
        LastUpdateDate: Some(
          "2018-12-17T16:50:11.820Z"
            .parse()
            .expect("parse LastUpdateDate",)
        ),
        ShipServiceLevel: "Std US D2D Dom".to_string(),
        NumberOfItemsShipped: 1,
        OrderStatus: OrderStatus::Shipped,
        SalesChannel: "Amazon.com".to_string(),
        IsBusinessOrder: false,
        NumberOfItemsUnshipped: 0,
        IsPremiumOrder: false,
        EarliestShipDate: Some(
          "2018-12-17T08:00:00Z"
            .parse()
            .expect("parse EarliestShipDate",)
        ),
        MarketplaceId: "ATVPDKIKX0DER".to_string(),
        FulfillmentChannel: FulfillmentChannel::MFN,
        PaymentMethod: PaymentMethod::Other,
        IsPrime: true,
        ShipmentServiceLevelCategory: "Standard".to_string(),
        SellerOrderId: "666".to_string(),
        BuyerEmail: "666@marketplace.amazon.com".to_string(),
        BuyerName: "First Last".to_string(),
        OrderTotal: Some(CurrencyAmount {
          CurrencyCode: "USD".to_string(),
          Amount: "666.66".to_owned(),
        }),
        ShippingAddress: Some(ShippingAddress {
          Phone: None,
          StateOrRegion: "CA".to_string(),
          City: "SAN MATEO".to_string(),
          CountryCode: "US".to_string(),
          PostalCode: "92683-4617".to_string(),
          Name: "First Last".to_string(),
          AddressLine1: "8888 J AVE".to_string(),
          AddressLine2: "".to_string(),
        }),
        BuyerCounty: "".to_string(),
        EarliestDeliveryDate: Some("2018-12-20T08:00:00Z".parse().unwrap()),
        LatestDeliveryDate: Some("2018-12-27T07:59:59Z".parse().unwrap()),
        EasyShipShipmentStatus: "".to_owned(),
        IsEstimatedShipDateSet: false,
        IsReplacementOrder: false,
        ReplacedOrderId: "".to_owned(),
        OrderChannel: "".to_owned(),
        PromiseResponseDueDate: None,
        PurchaseOrderNumber: "".to_owned(),
        ShippedByAmazonTFM: false,
        TFMShipmentStatus: "".to_owned(),
      }
    );
  }

  #[test]
  fn test_decode_orderitem() {
    test_decode!(
      OrderItem,
      r#"<QuantityOrdered>1</QuantityOrdered>
        <Title>Edifier R1280T Powered Bookshelf Speakers - 2.0 Active Near Field Monitors - Studio Monitor Speaker - Wooden Enclosure - 42 Watts RMS</Title>
        <PromotionDiscount>
          <CurrencyCode>USD</CurrencyCode>
          <Amount>0.00</Amount>
        </PromotionDiscount>
        <ASIN>B016P9HJIA</ASIN>
        <SellerSKU>edifier-r1280t-fba</SellerSKU>
        <OrderItemId>46510268396154</OrderItemId>
        <QuantityShipped>1</QuantityShipped>
        <ItemPrice>
          <CurrencyCode>USD</CurrencyCode>
          <Amount>99.99</Amount>
        </ItemPrice>
        <ItemTax>
          <CurrencyCode>USD</CurrencyCode>
          <Amount>0.00</Amount>
        </ItemTax>"#,
      OrderItem {
        OrderItemId: "46510268396154".to_string(),
        QuantityOrdered: 1,
        Title: "Edifier R1280T Powered Bookshelf Speakers - 2.0 Active Near Field Monitors - Studio Monitor Speaker - Wooden Enclosure - 42 Watts RMS".to_string(),
        ASIN: "B016P9HJIA".to_string(),
        SellerSKU: "edifier-r1280t-fba".to_string(),
        QuantityShipped: 1,
        ItemPrice: Some(CurrencyAmount { CurrencyCode: "USD".to_string(), Amount: "99.99".to_owned() }),
        ItemTax: Some(CurrencyAmount { CurrencyCode: "USD".to_string(), Amount: "0.00".to_owned() }),
        GiftWrapPrice: None,
        GiftWrapTax: None,
        PromotionDiscount: Some(CurrencyAmount { CurrencyCode: "USD".to_string(), Amount: "0.00".to_owned() }),
        ShippingPrice: None,
        ShippingDiscount: None,
        ShippingTax: None,
      }
    );
  }
}


text:
using EditorUtils;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;

namespace VsShowChars.Implementation.NewLines
{
    [Export(typeof(IWpfTextViewCreationListener))]
    [ContentType("any")]
    [TextViewRole(PredefinedTextViewRoles.Editable)]
    internal sealed class NewLineDisplayFactory : IWpfTextViewCreationListener
    {
        internal const string AdornmentLayerName = "NewLineDisplayAdornment";

        private readonly IEditorFormatMapService _editorFormatMapService;
        private readonly IVsShowCharsOptions _options;

        /// <summary>
        /// Defines the adornment layer for the adornment. This layer is ordered
        /// after the selection layer in the Z-order
        /// </summary>
        [Export(typeof(AdornmentLayerDefinition))]
        [Name(AdornmentLayerName)]
        [Order(After = PredefinedAdornmentLayers.Selection, Before = PredefinedAdornmentLayers.Text)]
        public AdornmentLayerDefinition NewLineDisplayAdornmentLayerDefinition = null;

        [ImportingConstructor]
        internal NewLineDisplayFactory(IEditorFormatMapService editorFormatMapService, IVsShowCharsOptions options)
        {
            _editorFormatMapService = editorFormatMapService;
            _options = options;
        }

        void IWpfTextViewCreationListener.TextViewCreated(IWpfTextView textView)
        {
            var editorFormatMap = _editorFormatMapService.GetEditorFormatMap(textView);
            new NewLineDisplay(textView, textView.GetAdornmentLayer(AdornmentLayerName), editorFormatMap, _options);
        }
    }
}


text:
/*!
 *************************************************************************************
 * \file annexb.h
 *
 * \brief
 *    Annex B byte stream buffer handling.
 *
 *************************************************************************************
 */

#ifndef _ANNEXB_H_
#define _ANNEXB_H_

#include "nalucommon.h"

extern int IsFirstByteStreamNALU;
extern int LastAccessUnitExists;
extern int NALUCount;

int  GetAnnexbNALU (NALU_t *nalu);
void OpenBitstreamFile (char *fn);
void CloseBitstreamFile();
void CheckZeroByteNonVCL(NALU_t *nalu, int * ret);
void CheckZeroByteVCL(NALU_t *nalu, int * ret);

#endif


text:
package gw2tpapp;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Miki
 */
public class Gw2tpapp {

    /**
     * @param args the command line arguments
     */
    @SuppressWarnings("SleepWhileInLoop")
    public static void main(String[] args) {
        try {
            Database db = new Database();
            RecipeList rl = new RecipeList(db);
            ItemList il = new ItemList(db);
            Generators g = new Generators(db);
            /*FTPUploader fup = new FTPUploader();
            ItemDataWrapper idw = new ItemDataWrapper();
             idw.getItemData(19721, "buy");
             guipanel a = new guipanel(db);
             a.getData();*/
            System.out.println("Start");
            il.getItemList(false);
            //rl.getRecipeList(false);
            System.out.println("End");
            //g.generateDyeList();
            while (true) {
                try {
                    db.connect();
                    Date d = new Date();
                    d.getTime();
                    System.out.println("Start: " + d.toString());
                    il.updateItemTable();
                    //rl.updateRecipeTable();
                    //g.generateFiles();
                    db.conn.close();
                    //fup.ftpconnect();
                    Date e = new Date();
                    e.getTime();
                    System.out.println("End: " + e.toString());
                    Thread.sleep(1800000);
                } catch (Exception e) {
                    Logger.getLogger(Gw2tpapp.class.getName()).log(Level.SEVERE, null, e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
package org.perftester.sbtbot.server

import java.io.OutputStream

import akka.util.ByteString
import play.api.libs.json._

/**
  * A class to write Json RPC messages on an output stream, following the Language Server Protocol.
  * It produces the following format:
  *
  * <Header> '\r\n' <Content>
  *
  * Header := FieldName ':' FieldValue '\r\n'
  *
  * Currently there are two defined header fields:
  * - 'Content-Length' in bytes (required)
  * - 'Content-Type' (string), defaults to 'application/vscode-jsonrpc; charset=utf8'
  *
  * @note The header part is defined to be ASCII encoded, while the content part is UTF8.
  */
class MessageWriter {
  private val ContentLen = "Content-Length"

  /** Lock protecting the output stream, so multiple writes don't mix message chunks. */
  private val lock = new Object

  //  /**
  //   * Write a message to the output stream. This method can be called from multiple threads,
  //   * but it may block waiting for other threads to finish writing.
  //   */
  //  def write[T](msg: T, h: Map[String, String] = Map.empty)(implicit o: Format[T]): Unit = lock.synchronized {
  //    require(h.get(ContentLen).isEmpty)
  //
  //    val str = Json.stringify(o.writes(msg))
  //    val contentBytes = str.getBytes(MessageReader.Utf8Charset)
  //    val headers = (h + (ContentLen -> contentBytes.length))
  //      .map { case (k, v) => s"$k: $v" }
  //      .mkString("", "\r\n", "\r\n\r\n")
  //
  //    println(s"$headers\n\n$str")
  //    println(s"payload: $str")
  //
  //    val headerBytes = headers.getBytes(MessageReader.AsciiCharset)
  //
  //    out.write(headerBytes)
  //    out.write(contentBytes)
  //    out.flush()
  //  }

  /**
    * Write a message to the output stream. This method can be called from multiple threads,
    * but it may block waiting for other threads to finish writing.
    */
  def writeByteString[T](msg: T, h: Map[String, String] = Map.empty)(
      implicit o: Format[T]): ByteString = lock.synchronized {
    require(h.get(ContentLen).isEmpty)

    //    val str = Json.stringify(o.writes(msg)) + "\r\n"
    val str =
      """{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "initializationOptions": { "token": "84046191245433876643612047032303751629" } } }\r\n"""
    //    val str = """{ "jsonrpc": "2.0", "id": 2, "method": "sbt/exec", "params": { "commandLine": "clean" } }\r\n"""
    val contentBytes = str.getBytes(MessageReader.Utf8Charset)
    val headers = (h + (ContentLen -> contentBytes.length))
      .map { case (k, v) => s"$k: $v" }
      .mkString("", "\r\n", "\r\n\r\n")

    //    println(s"$headers\n\n$str")
    println(s"payload: $str")

    //    val headerBytes = headers.getBytes(MessageReader.AsciiCharset)

    /*ByteString(headerBytes) ++ */
    ByteString(contentBytes)
  }

}


text:
@interface ACAccountStore (AsyncResult)

- (id<AsyncResult>)requestAccessToAccountsWithType:(ACAccountType *)accountType;
- (id<AsyncResult>)requestAccessToAccountsWithType:(ACAccountType *)accountType options:(NSDictionary *)options;
- (id<AsyncResult>)renewCredentialsForAccount:(ACAccount *)account;
- (id<AsyncResult>)removeAccount:(ACAccount *)account;

@end


text:
exports.up = function (knex) {
  return knex.schema.createTable('cities', function (t) {
    t.string('country').notNullable();
    t.string('name').notNullable();
    t.integer('count'); // measurements count
    t.integer('locations'); // locations count
    t.unique(['country', 'name']);
  });
};

exports.down = function (knex) {
  return knex.schema.dropTable('cities');
};


text:
namespace Flourish::Memory
{
	//Represents a report of every allocation currently been tracked by a DebugTrackingAllocatorWrapper
	struct AllocationReport
	{
		//When reporting the amount of bytes used by an allocation, we split the value into 3 different parts
		// - Allocation Size: The size (in bytes) of the allocation that are returned to the user. It may be different
		// then the requested amount due to things like alignment, min alloc sizes etc
		//
		// - Metadata Size: This is the amount of bytes that are used internally by the underlying allocator for things like
		// internal memory management as overhead.
		//
		// - Tracking Data Size: This is the amount of bytes that is the overhead for using the DebugTrackingAllocatorWrapper.
		// This is provided separately so you can account for when tracking is disabled
		struct AllocationsSizeData
		{
			//Size of the allocation
			size_t AllocSize;

			//Size of the metadata allocated by the underlying allocator as overhead
			size_t MetadataSize;

			//Size of extra data used by the DebugTrackingAllocatorWrapper for this allocation
			size_t TrackingDataSize;
		};

		//Data for a single allocation
		struct AllocationReportItem
		{
			static const size_t CHAR_BUFFER_SIZE = 512;

			//Size of the allocation
			AllocationsSizeData AllocSizeData { };

			//Address of the allocation returned to the user (might not be the start of the memory block due to alignment, header data etc.)
			intptr_t AllocMemoryAddress = 0;

			//Name of the file this allocation came from
			char FileName[CHAR_BUFFER_SIZE] { };

			//Line number where this allocation came from
			int32_t LineNumber = 0;

			//Name of the function where this allocation was made
			char FunctionName[CHAR_BUFFER_SIZE] { };
		};

		struct AllocationStats
		{
			//The current total size data of all currently open allocations
			AllocationsSizeData CurrentTotalAllocSizeData { };

			//The highest amount of bytes allocated by the allocator during its lifespan (Excluding any memory used by the tracking allocator for internal management)
			size_t BytesAllocatedHighWatermark = 0;
		};

		AllocationReport(FL_SharedPtrArray<AllocationReportItem> &reportItems, size_t numReportItems,
			AllocationStats stats, const char* allocatorName);
		~AllocationReport() = default;

		AllocationReport(const AllocationReport&) = default;
		AllocationReport& operator=(const AllocationReport&) = default;

		AllocationReport(AllocationReport&& other) = default;
		AllocationReport& operator=(AllocationReport&& other) = default;

		size_t GetNumAllocationReportItems() const { return _numReportItems; }
		AllocationStats GetAllocatorStats() const { return _stats; }
		const AllocationReportItem& GetAllocationReportItem(const uint32_t index) const;

		bool DumpCurrentAllocationsStatsReportToString(char* statsReportOut, int statsReportOutLength);

	private:
		char _allocatorNameBuffer[IAllocator::ALLOCATOR_NAME_BUFFER_SIZE] { };
		AllocationStats _stats;
		size_t _numReportItems;
		FL_SharedPtrArray<AllocationReportItem> _reportItems;
	};
};


text:
/*
  Joins/corss products for CnC, provided as a re-usable graph.
*/

#ifndef _CnC_JOIN_H_
#define _CnC_JOIN_H_

#include <cnc/internal/cnc_stddef.h>
#include <tbb/queuing_mutex.h>
#include <set>

namespace CnC
{

    template< typename TagA, typename TunerA, typename TagB, typename TunerB, typename TagC, typename TunerC > class join;

    /// Returns a graph that joins 2 tag-collections into a third one.
    /// Continuously produces the join product of the 2 input tag-collections
    /// and puts it into the output tag-collection.
    ///
    /// Accepts any types; only requires that a an output tag-type
    /// provides a constructor which accepts (taga, tagb) to construct
    /// a joined tag from tag a and b.
    ///
    /// On distributed memory duplicate output tags might be produced.
    /// To avoid duplicate step execution use tag-preservation on the
    /// output tag-collection (CnC::preserve_tuner) and suitable
    /// distribution functions on the prescribed step-collection
    /// (CnC::step_tuner).
    ///
    /// \param ctxt  the context to which the graph belongs
    /// \param name  the name of this join graph instance
    /// \param a     first input collection
    /// \param b     second input collection
    /// \param c     output collection
    template< typename Ctxt, typename TagA, typename TunerA, typename TagB, typename TunerB, typename TagC, typename TunerC >
    graph * make_join_graph( CnC::context< Ctxt > & ctxt, const std::string & name,
                             CnC::tag_collection< TagA, TunerA > & a,
                             CnC::tag_collection< TagB, TunerB > & b,
                             CnC::tag_collection< TagC, TunerC > & c )
    {
        return new join< TagA, TunerA, TagB, TunerB, TagC, TunerC >( ctxt, name, a, b, c );
    }

    // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    // The actual join graph. A complex template construct; use
    // make_join_graph to create a join graph. Only the constructor is
    // public, everything else is private ("hidden").
    //
    // When ever a new tag arrives, it gets joined with all existing
    // tags in the other collection.  The actual join is protected by a
    // mutex. This makes it safe on a single process.
    //
    // We cannot rely on the collection to keep tags because we
    // currently have no thread-safe iteration facility. Hence we use
    // std::set to keep them privately in the graph.
    //
    // We need explicit handling of distributed memory. We keep the
    // tags locally where they are put and just send a bcast message
    // when a new tag arrives. This can produce duplicate output tags.
    template< typename TagA, typename TunerA, typename TagB, typename TunerB, typename TagC, typename TunerC >
    class join : public CnC::graph
    {
        typedef tbb::queuing_mutex mutex_type;
        typedef std::set< TagA > seta_type;
        typedef std::set< TagB > setb_type;
        typedef CnC::tag_collection< TagA, TunerA > colla_type;
        typedef CnC::tag_collection< TagB, TunerB > collb_type;
        typedef CnC::tag_collection< TagC, TunerC > collc_type;
        typedef join< TagA, TunerA, TagB, TunerB, TagC, TunerC > join_type;
        enum { JOINA = 'A', JOINB = 'B' };
        friend struct on_a_put;
        friend struct on_b_put;

    public:
        template< typename Ctxt >
        join( CnC::context< Ctxt > & ctxt, const std::string & name, colla_type & a, collb_type & b, collc_type & c )
            : CnC::graph( ctxt, name ),
              m_a( a ),
              m_b( b ),
              m_c( c ),
              m_seta(),
              m_setb(),
              m_mutex()
        {
            // callback objects must persist the lifetime of collections
            m_a.on_put( new on_a_put( this ) );
            m_b.on_put( new on_b_put( this ) );
        }

        // the implementation is "hidden"
	private:
        // join a given tag with all existing tags in the other set
        template< typename Tag, typename Set, typename joiner >
        void join_one( const Tag & t, const Set & set, const joiner & j )
        {
            // in a more advanced version we can go parallel by using parallel_for or a range
            for( typename Set::iterator i=set.begin(); i!=set.end(); ++i ) {
                m_c.put( j( t, *i ) );
            }
        }

        // join a b-tag with a a-tag
        struct join_ba
        {
            TagC operator()( const TagB & b, const TagA & a ) const {
				return TagC( a, b );
            }
        };
        // join a a-tag with a b-tag
        struct join_ab
        {
            TagC operator()( const TagA & a, const TagB & b ) const {
				return TagC( a, b );
            }
        };
        typedef join_ab join_ab_type;
        typedef join_ba join_ba_type;

        template< typename Tag >
        void send_tag( const Tag & tag, const char op )
        {
#ifdef _DIST_CNC_
            if( Internal::distributor::active() ) {
                if( this->trace_level() > 2 ) {
                    Internal::Speaker oss(std::cout);
                    oss << this->name() << "::send_tag JOIN" << (op==JOINA?"A":"B") << " [";
                    cnc_format( oss, tag );
                    oss << "]";
                }
                CnC::serializer * ser = this->new_serializer();
                (*ser) & op & tag;
                this->bcast_msg( ser );
            }
#endif
        }

        // callback for collection a
        struct on_a_put : public colla_type::callback_type
        {
            on_a_put( join_type * j  ) : m_join( j ) {}

            void on_put( const TagA & tag )
            {
                if( m_join->trace_level() > 0 ) {
                    Internal::Speaker oss(std::cout);
                    oss << m_join->name() << "::on_put_a <";
                    cnc_format( oss, tag );
                    oss << ">";
                }
                m_join->send_tag( tag, JOINA );
                mutex_type::scoped_lock _lock( m_join->m_mutex );
                m_join->join_one( tag, m_join->m_setb, join_ab_type() );
                m_join->m_seta.insert( tag );
            }
        private:
            join_type * m_join;
        };

        // callback for collection b
        struct on_b_put : public collb_type::callback_type
        {
            on_b_put( join_type * j  ) : m_join( j ) {}

            void on_put( const TagB & tag )
            {
                if( m_join->trace_level() > 0 ) {
                    Internal::Speaker oss(std::cout);
                    oss << m_join->name() << "::on_put_b <";
                    cnc_format( oss, tag );
                    oss << ">";
                }
                m_join->send_tag( tag, JOINB );
                mutex_type::scoped_lock _lock( m_join->m_mutex );
                m_join->join_one( tag, m_join->m_seta, join_ba_type() );
                m_join->m_setb.insert( tag );
            }
        private:
            join_type * m_join;
        };

#ifdef _DIST_CNC_
        virtual void recv_msg( serializer * ser )
        {
            char _op;
            (*ser) & _op;
            switch( _op ) {
            case JOINA : {
                TagA _tag;
                (*ser) & _tag;
                if( this->trace_level() > 2 ) {
                    Internal::Speaker oss(std::cout);
                    oss << this->name() << "::recv_msg JOINA <";
                    cnc_format( oss, _tag );
                    oss << ">";
                }
                mutex_type::scoped_lock _lock( m_mutex );
                join_one( _tag, m_setb, join_ab_type() );
                break;
            }
            case JOINB : {
                CNC_ASSERT_MSG( _op == JOINB, "Unexpected message tag" );
                TagB _tag;
                (*ser) & _tag;
                if( this->trace_level() > 2 ) {
                    Internal::Speaker oss(std::cout);
                    oss << this->name() << "::recv_msg JOINB <";
                    cnc_format( oss, _tag );
                    oss << ">";
                }
                mutex_type::scoped_lock _lock( m_mutex );
                join_one( _tag, m_seta, join_ba_type() );
                break;
            }
            default :
                CNC_ASSERT_MSG( false, "Unexpected message tag in JOIN" );
            }
        }
#endif

        colla_type & m_a;
        collb_type & m_b;
        collc_type & m_c;
        mutex_type   m_mutex;
        seta_type    m_seta;
        setb_type    m_setb;
    };

} // namespace CnC

#endif //_CnC_JOIN_H_


text:
namespace mevent {
namespace util {

class HTTPClient {
public:
    HTTPClient() {};
    ~HTTPClient() {};

    bool Request(const std::string &host);

    std::string ResponseData();

private:
    static size_t WriteCallback(char *ptr, size_t size, size_t nmemb, void *userdata);

    std::string    data_;
};

}//namespace util
}//namespace mevent

#endif


text:
#ifndef _SDL_thread_h
#define _SDL_thread_h

/**
 *  \file SDL_thread.h
 *
 *  Header for the SDL thread management routines.
 */

#include "SDL_stdinc.h"
#include "SDL_error.h"

/* Thread synchronization primitives */
#include "SDL_mutex.h"

#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
/* *INDENT-OFF* */
extern "C" {
/* *INDENT-ON* */
#endif

/* The SDL thread structure, defined in SDL_thread.c */
struct SDL_Thread;
typedef struct SDL_Thread SDL_Thread;

/* The SDL thread ID */
typedef unsigned long SDL_threadID;

/* The SDL thread priority
 *
 * Note: On many systems you require special privileges to set high priority.
 */
typedef enum {
    SDL_THREAD_PRIORITY_LOW,
    SDL_THREAD_PRIORITY_NORMAL,
    SDL_THREAD_PRIORITY_HIGH
} SDL_ThreadPriority;

/* The function passed to SDL_CreateThread()
   It is passed a void* user context parameter and returns an int.
 */
typedef int (SDLCALL * SDL_ThreadFunction) (void *data);

#if defined(__WIN32__) && !defined(HAVE_LIBC)
/**
 *  \file SDL_thread.h
 *
 *  We compile SDL into a DLL. This means, that it's the DLL which
 *  creates a new thread for the calling process with the SDL_CreateThread()
 *  API. There is a problem with this, that only the RTL of the SDL.DLL will
 *  be initialized for those threads, and not the RTL of the calling
 *  application!
 *
 *  To solve this, we make a little hack here.
 *
 *  We'll always use the caller's _beginthread() and _endthread() APIs to
 *  start a new thread. This way, if it's the SDL.DLL which uses this API,
 *  then the RTL of SDL.DLL will be used to create the new thread, and if it's
 *  the application, then the RTL of the application will be used.
 *
 *  So, in short:
 *  Always use the _beginthread() and _endthread() of the calling runtime
 *  library!
 */
#define SDL_PASSED_BEGINTHREAD_ENDTHREAD
#ifndef _WIN32_WCE
#include <process.h>            /* This has _beginthread() and _endthread() defined! */
#endif

typedef uintptr_t(__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned,
                                                        unsigned (__stdcall *
                                                                  func) (void
                                                                         *),
                                                        void *arg, unsigned,
                                                        unsigned *threadID);
typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code);

/**
 *  Create a thread.
 */
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data,
                 pfnSDL_CurrentBeginThread pfnBeginThread,
                 pfnSDL_CurrentEndThread pfnEndThread);

#if defined(_WIN32_WCE)

/**
 *  Create a thread.
 */
#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, NULL, NULL)

#else

/**
 *  Create a thread.
 */
#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, _beginthreadex, _endthreadex)

#endif
#else

/**
 *  Create a thread.
 *
 *   Thread naming is a little complicated: Most systems have very small
 *    limits for the string length (BeOS has 32 bytes, Linux currently has 16,
 *    Visual C++ 6.0 has nine!), and possibly other arbitrary rules. You'll
 *    have to see what happens with your system's debugger. The name should be
 *    UTF-8 (but using the naming limits of C identifiers is a better bet).
 *   There are no requirements for thread naming conventions, so long as the
 *    string is null-terminated UTF-8, but these guidelines are helpful in
 *    choosing a name:
 *
 *    http://stackoverflow.com/questions/149932/naming-conventions-for-threads
 *
 *   If a system imposes requirements, SDL will try to munge the string for
 *    it (truncate, etc), but the original string contents will be available
 *    from SDL_GetThreadName().
 */
extern DECLSPEC SDL_Thread *SDLCALL
SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data);

#endif

/**
 * Get the thread name, as it was specified in SDL_CreateThread().
 *  This function returns a pointer to a UTF-8 string that names the
 *  specified thread, or NULL if it doesn't have a name. This is internal
 *  memory, not to be free()'d by the caller, and remains valid until the
 *  specified thread is cleaned up by SDL_WaitThread().
 */
extern DECLSPEC const char *SDLCALL SDL_GetThreadName(SDL_Thread *thread);

/**
 *  Get the thread identifier for the current thread.
 */
extern DECLSPEC SDL_threadID SDLCALL SDL_ThreadID(void);

/**
 *  Get the thread identifier for the specified thread.
 *
 *  Equivalent to SDL_ThreadID() if the specified thread is NULL.
 */
extern DECLSPEC SDL_threadID SDLCALL SDL_GetThreadID(SDL_Thread * thread);

/**
 *  Set the priority for the current thread
 */
extern DECLSPEC int SDLCALL SDL_SetThreadPriority(SDL_ThreadPriority priority);

/**
 *  Wait for a thread to finish.
 *
 *  The return code for the thread function is placed in the area
 *  pointed to by \c status, if \c status is not NULL.
 */
extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status);

/* Ends C function definitions when using C++ */
#ifdef __cplusplus
/* *INDENT-OFF* */
}
/* *INDENT-ON* */
#endif
#include "close_code.h"

#endif /* _SDL_thread_h */

/* vi: set ts=4 sw=4 expandtab: */


text:
 #if defined (_WIN32)
  #if defined(TestIndirectDependencies_Indirect_Dynamic_EXPORTS)
    #define  DECLEXPORT __declspec(dllexport)
  #else
    #define  DECLEXPORT __declspec(dllimport)
  #endif
#else
 #define DECLEXPORT
#endif

class DECLEXPORT TestIndirectDependencies_Indirect_Dynamic
{
    public:
	virtual void method();
};


text:
import os
import csv
import cv2
import sklearn
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

from keras.models import Sequential, Model, model_from_json
from keras.layers import Activation, Dense, Dropout, ELU, Flatten, Lambda, SpatialDropout2D
from keras.layers import Convolution2D, Cropping2D
from keras.layers.pooling import MaxPooling2D
from keras.optimizers import SGD, Adam, RMSprop
from keras.utils import np_utils
from keras.callbacks import ModelCheckpoint

from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split

# ### Define Data structures and functions

# In[2]:

raw_samples =   []
car_images =    []
steering_angles=[]

# #### defining image properties

# In[3]:

# define the input size
height = 160
width = 320
depth = 3

# define how images should be cropped
reduction_upper = 70
reduction_lower = 25
reduction_left  = 0
reduction_right = 0

# specify the batch size and training epochs
batch_size = 32
epochs = 5

# #### File-importing function

# In[4]:

def import_samples(csv_filepath, samples):
    with open(csv_filepath) as csvfile:
        reader = csv.reader(csvfile)
        for line in reader:
            samples.append(line)

        # samples = samples[1:] # headers removal
        print("Total number of samples right now = ", len(samples))

    return samples

# #### Augmentation Function

# In[5]:

def augmentation(image_path, angle_single):

    image_single = cv2.imread(image_path)
    image_flip = np.fliplr(image_single)
    angle_negative = (-1.0)*angle_single

    return image_flip, angle_negative

# #### create the generator function

# In[6]:

def generator(samples, batch_size):

    no_samples = len(samples)

    while 1:
        shuffle(samples)

        # loop through each batch of data
        for sample_pos in range(0, no_samples, batch_size):
            sample_batches = samples[sample_pos:sample_pos + batch_size]

            center_images = []
            center_angles = []
            left_images = []
            left_angles = []
            right_images=[]
            right_angles=[]
            correction = 0.25   # define the steering correction for left and right cameras.

            # loop through every single record within a batch of data
            for sample_no in sample_batches:

                source_path_A = sample_no[0]   # specify the path for images taken by central camera.
                center_angle_single = float(sample_no[3])
                center_image_single_flip, angle_negative_center = augmentation(source_path_A,center_angle_single)
                center_image_single = cv2.imread(source_path_A)
                center_images.append(center_image_single)
                center_angles.append(center_angle_single)
                center_images.append(center_image_single_flip)
                center_angles.append(angle_negative_center)
#_____________________________________________________________________________________________________________________

                source_path_B = sample_no[1]   # specify the path for images taken by left camera.
                left_angle_single = float(sample_no[3])+correction
                left_image_single_flip, angle_negative_left = augmentation(source_path_B,left_angle_single)
                left_image_single = cv2.imread(source_path_B)
                center_images.append(left_image_single)
                center_angles.append(left_angle_single)
                center_images.append(left_image_single_flip)
                center_angles.append(angle_negative_left)
#_____________________________________________________________________________________________________________________

                source_path_C = sample_no[2]  # specify the path for images taken by right camera.
                right_angle_single = float(sample_no[3])-correction
                right_image_single_flip, angle_negative_right = augmentation(source_path_C,right_angle_single)
                right_image_single = cv2.imread(source_path_C)
                center_images.append(right_image_single)
                center_angles.append(right_angle_single)
                center_images.append(right_image_single_flip)
                center_angles.append(angle_negative_right)
#_____________________________________________________________________________________________________________________

            X_train = np.array(center_images)
            y_train = np.array(center_angles)

            yield shuffle(X_train, y_train)

# In[7]:

# extracting data from CSV files
current_sample = import_samples('E:/DrivingDataTrackA/driving_log.csv', raw_samples)
current_sample = import_samples('E:/DrivingDataTrackA_enhanced/driving_log.csv', current_sample)

current_sample = import_samples('E:/DrivingDataTrackA_Recovery/driving_log.csv', current_sample)

current_sample = import_samples('E:/DrivingDataTrackB/driving_log.csv', current_sample)
current_sample = import_samples('E:/DrivingData/driving_log.csv', current_sample)

# In[8]:

# train-validation split
train_samples, valid_samples = train_test_split(current_sample, test_size=0.1)

# In[9]:

# define two generators that will be fed into the Nvidia pipeline.
train_generator = generator(train_samples, batch_size)
valid_generator = generator(valid_samples, batch_size)

# #### Use LeNet Architecture

# In[10]:

model = Sequential()
model.add(Cropping2D(cropping=((reduction_upper,reduction_lower),
                               (reduction_left,reduction_right)),input_shape=(height, width, depth)))
model.add(Lambda(lambda x: (x / 255.0) - 0.5))
model.add(Convolution2D(16, (5, 5), strides=(1, 1), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Convolution2D(32, (5, 5), strides=(1, 1), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(32))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.compile(loss='mse',optimizer=Adam(lr = 0.0001),metrics=['mean_absolute_error'])
model.summary()

'''
# NVIDIA MODEL

model = Sequential()
model.add(Cropping2D(cropping=((reduction_upper,reduction_lower),
                               (reduction_left,reduction_right)),input_shape=(height, width, depth)))
model.add(Lambda(lambda x: (x / 255.0) - 0.5))
model.add(Convolution2D(24, (5, 5), strides=(2, 2), activation='relu'))
model.add(Convolution2D(36, (5, 5), strides=(2, 2), activation='relu'))
model.add(Convolution2D(48, (5, 5), strides=(2, 2), activation='relu'))
model.add(Convolution2D(64, (3, 3), activation='relu'))
model.add(Convolution2D(64, (3, 3), activation='relu'))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(50, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(10, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(1, activation='tanh'))
model.compile(loss='mse', optimizer=Adam(lr=0.0001),metrics=['accuracy'])
model.summary()

'''

# #### Creating a checkpoint

# In[11]:

checkpointer = ModelCheckpoint(
                                    filepath= 'checkpoints/model{epoch:02d}.h5',
                                    verbose=1,
                                    save_best_only=False,
                                    save_weights_only=False,
                                    mode = 'auto'

                              )

# In[12]:

# starting the training process
history_object = model.fit_generator(
                                            generator = train_generator,
                                            steps_per_epoch=len(train_samples)/batch_size,
                                            epochs = epochs,
                                            verbose = 1,
                                            validation_data=valid_generator,
                                            validation_steps =len(valid_samples)/batch_size,

                                    )

print('Congratulations! Training completed successfully!')
model.save('model_LeNet_two.h5')
print('Model saved successfully!')

# In[13]:

print(history_object.history.keys())

### plot the training and validation loss for each epoch
plt.plot(history_object.history['loss'])
plt.plot(history_object.history['val_loss'])
plt.title('model mean squared error loss')
plt.ylabel('mean squared error loss')
plt.xlabel('epoch')
plt.legend(['training set', 'validation set'], loc='upper right')
plt.show()


text:
package kafka.consumer

import kafka.server.{BrokerAndInitialOffset, AbstractFetcherThread, AbstractFetcherManager}
import kafka.cluster.{BrokerEndPoint, Cluster}
import org.apache.kafka.common.protocol.SecurityProtocol
import org.apache.kafka.common.TopicPartition
import scala.collection.immutable
import collection.mutable.HashMap
import scala.collection.mutable
import java.util.concurrent.locks.ReentrantLock
import kafka.utils.CoreUtils.inLock
import kafka.utils.ZkUtils
import kafka.utils.{ShutdownableThread, SystemTime}
import kafka.client.ClientUtils
import java.util.concurrent.atomic.AtomicInteger

/**
 *  Usage:
 *  Once ConsumerFetcherManager is created, startConnections() and stopAllConnections() can be called repeatedly
 *  until shutdown() is called.
 */
class ConsumerFetcherManager(private val consumerIdString: String,
                             private val config: ConsumerConfig,
                             private val zkUtils : ZkUtils)
        extends AbstractFetcherManager("ConsumerFetcherManager-%d".format(SystemTime.milliseconds),
                                       config.clientId, config.numConsumerFetchers) {
  private var partitionMap: immutable.Map[TopicPartition, PartitionTopicInfo] = null
  private var cluster: Cluster = null
  private val noLeaderPartitionSet = new mutable.HashSet[TopicPartition]
  private val lock = new ReentrantLock
  private val cond = lock.newCondition()
  private var leaderFinderThread: ShutdownableThread = null
  private val correlationId = new AtomicInteger(0)

  private class LeaderFinderThread(name: String) extends ShutdownableThread(name) {
    // thread responsible for adding the fetcher to the right broker when leader is available
    override def doWork() {
      val leaderForPartitionsMap = new HashMap[TopicPartition, BrokerEndPoint]
      lock.lock()
      try {
        while (noLeaderPartitionSet.isEmpty) {
          trace("No partition for leader election.")
          cond.await()
        }

        trace("Partitions without leader %s".format(noLeaderPartitionSet))
        val brokers = zkUtils.getAllBrokerEndPointsForChannel(SecurityProtocol.PLAINTEXT)
        val topicsMetadata = ClientUtils.fetchTopicMetadata(noLeaderPartitionSet.map(m => m.topic).toSet,
                                                            brokers,
                                                            config.clientId,
                                                            config.socketTimeoutMs,
                                                            correlationId.getAndIncrement).topicsMetadata
        if(logger.isDebugEnabled) topicsMetadata.foreach(topicMetadata => debug(topicMetadata.toString()))
        topicsMetadata.foreach { tmd =>
          val topic = tmd.topic
          tmd.partitionsMetadata.foreach { pmd =>
            val topicAndPartition = new TopicPartition(topic, pmd.partitionId)
            if(pmd.leader.isDefined && noLeaderPartitionSet.contains(topicAndPartition)) {
              val leaderBroker = pmd.leader.get
              leaderForPartitionsMap.put(topicAndPartition, leaderBroker)
              noLeaderPartitionSet -= topicAndPartition
            }
          }
        }
      } catch {
        case t: Throwable => {
            if (!isRunning.get())
              throw t /* If this thread is stopped, propagate this exception to kill the thread. */
            else
              warn("Failed to find leader for %s".format(noLeaderPartitionSet), t)
          }
      } finally {
        lock.unlock()
      }

      try {
        addFetcherForPartitions(leaderForPartitionsMap.map { case (topicPartition, broker) =>
          topicPartition -> BrokerAndInitialOffset(broker, partitionMap(topicPartition).getFetchOffset())}
        )
      } catch {
        case t: Throwable => {
          if (!isRunning.get())
            throw t /* If this thread is stopped, propagate this exception to kill the thread. */
          else {
            warn("Failed to add leader for partitions %s; will retry".format(leaderForPartitionsMap.keySet.mkString(",")), t)
            lock.lock()
            noLeaderPartitionSet ++= leaderForPartitionsMap.keySet
            lock.unlock()
          }
        }
      }

      shutdownIdleFetcherThreads()
      Thread.sleep(config.refreshLeaderBackoffMs)
    }
  }

  override def createFetcherThread(fetcherId: Int, sourceBroker: BrokerEndPoint): AbstractFetcherThread = {
    new ConsumerFetcherThread(
      "ConsumerFetcherThread-%s-%d-%d".format(consumerIdString, fetcherId, sourceBroker.id),
      config, sourceBroker, partitionMap, this)
  }

  def startConnections(topicInfos: Iterable[PartitionTopicInfo], cluster: Cluster) {
    leaderFinderThread = new LeaderFinderThread(consumerIdString + "-leader-finder-thread")
    leaderFinderThread.start()

    inLock(lock) {
      partitionMap = topicInfos.map(tpi => (new TopicPartition(tpi.topic, tpi.partitionId), tpi)).toMap
      this.cluster = cluster
      noLeaderPartitionSet ++= topicInfos.map(tpi => new TopicPartition(tpi.topic, tpi.partitionId))
      cond.signalAll()
    }
  }

  def stopConnections() {
    /*
     * Stop the leader finder thread first before stopping fetchers. Otherwise, if there are more partitions without
     * leader, then the leader finder thread will process these partitions (before shutting down) and add fetchers for
     * these partitions.
     */
    info("Stopping leader finder thread")
    if (leaderFinderThread != null) {
      leaderFinderThread.shutdown()
      leaderFinderThread = null
    }

    info("Stopping all fetchers")
    closeAllFetchers()

    // no need to hold the lock for the following since leaderFindThread and all fetchers have been stopped
    partitionMap = null
    noLeaderPartitionSet.clear()

    info("All connections stopped")
  }

  def addPartitionsWithError(partitionList: Iterable[TopicPartition]) {
    debug("adding partitions with error %s".format(partitionList))
    inLock(lock) {
      if (partitionMap != null) {
        noLeaderPartitionSet ++= partitionList
        cond.signalAll()
      }
    }
  }
}


text:
var express = require('express')
    , path = require('path')
    , favicon = require('serve-favicon')
    , logger = require('morgan')
    , cookieParser = require('cookie-parser')
    , bodyParser = require('body-parser')
    , swig = require('swig')
    , rf = require("fs")
    , crypto = require('crypto')
    , session = require('express-session')
    , csrf = require('csurf')

    , routes = require('./routes')
    , configs = require('./configs')
    , staticFilesMD5Map = {};
var app = express();
var run_mod = app.get('env');
var config = configs[run_mod] || configs['development'];
var siteRootPath = __dirname.substring(0, __dirname.length - 8);

// view engine setup
app.set('views', path.join(siteRootPath, 'app', 'views'));
app.set('view engine', 'html');
app.engine('html', swig.renderFile);
if (run_mod !== 'production') {//非生产环境下,不使用缓存
    // Swig will cache templates for you, but you can disable that and use Express's caching instead, if you like:
    app.set('view cache', false);
    // To disable Swig's cache, do the following:
    swig.setDefaults({cache: false});
}

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//TODO cookie怎么跟域名绑定,比如,我如果通过ip直接访问项目,cookie是无效的,必须使用域名访问。
//TODO cookie的加密算法?底层实现了?
app.use(cookieParser(config.cookie_secret));
app.use(session({
    resave:false,
    saveUninitialized: true,
    secret: config.cookie_secret
}));
// 对应的连接写成:/css/common.css
//app.use(express.static(path.join(siteRootPath, 'public')));
// 创建一个虚拟目录,对应的连接要写成/s/css/common.css
app.use(config.static_url_prefix, express.static(path.join(siteRootPath, 'public'), {maxAge: 60 * 60 * 24 * 365 * 10, etag: true, lastModified: true}));
// app.locals中的属性,html模板语言可以直接访问,controller中可以通过req.app.locals访问。
app.locals.siteName = config.sitename;
app.locals.static_url = function (filePath) {
    /* 实现方案:
     * 读取本地服务器文件,计算md5,拼接查询字符串:v=xxxxxxxxxxxxx,并缓存计算结果。
     * nginx配置静态文件缓存为永久有效。
     * TODO 模板本身有没有提供一个这样的方法?
     * */
    var fileMD5 = staticFilesMD5Map[filePath];
    if (!fileMD5) {
        var data = rf.readFileSync(path.join(siteRootPath, 'public', filePath), "utf-8");
        fileMD5 = crypto.createHash('md5').update(data).digest('hex');
        staticFilesMD5Map[filePath] = fileMD5;
    }
    return config.static_url_prefix + filePath + '?v=' + fileMD5;
};

app.use(csrf());// 会创建 req.session.csrfSecret属性 但是这个属相好像过时了,以前的api有用到.
//app.use('/book', csrf()); // 可以具体精确到哪些请求使用csrf
app.use(function (req, res, next) {
    //所有的请求都会先经过这里,可以在这里做一些操作
    // res.locals的方法,模板语言也可以直接访问
    res.locals.csrf = req.csrfToken ? req.csrfToken() : '';
    res.locals.isAjax = req.xhr;
    next();
});
app.use('/', routes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (run_mod === 'development') {
    app.use(function (err, req, res, next) {
        console.log(err);
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            status: err.status,
            stack: err.stack
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        status: err.status,
        stack: ''
    });
});
module.exports = app;