text:
import logging

from collections import OrderedDict
from exception import WebNodeException
from proxy import ClientCenter

class MediumYieldNode(object):

    def __init__(self):
        self._key2child = {}
        self._call_iter = None
        self._child_iter = None
        self._current_level_key2value = OrderedDict()
        self._current_keys = []
        self._center = ClientCenter(self)
        self._key = ''

    def key(self):
        if not self._key:
            name = self.__class__.__name__
            params = []
            for k, v in self.__dict__.iteritems():
                if k not in ['_key2child', '_call_iter', '_child_iter', '_current_level_key2value', '_current_keys', '_center', '_key']:
                    params.append('%s:%s' % (str(k), str(v)))
            self._key = '%s|%s' % (name, ','.join(params))
        return self._key

    def register(self):
        yield []

    def children(self):
        yield []

    def submit(self, call_tuple):
        key = call_tuple.generate_key()
        self._current_level_key2value[key] = call_tuple
        return key

    def send(self, key2value):
        try:
            if self._call_iter is None:
                self._call_iter = self.register()
                self._current_level_key2value.clear()
                self._current_keys = self._call_iter.next()
            else:
                assert(isinstance(self._current_keys, (basestring, list)))
                if isinstance(self._current_keys, basestring):
                    to_send = key2value.get(self._current_keys).result()
                else:
                    to_send = []
                    for item in self._current_keys:
                        assert(isinstance(item, (basestring, list)))
                        if isinstance(item, list):
                            to_send.append([key2value.get(k).result() for k in item])
                        else:
                            to_send.append(key2value.get(item).result())
                self._current_level_key2value.clear()
                self._current_keys = self._call_iter.send(to_send)
        except StopIteration:
            self._current_level_key2value.clear()
            pass
        finally:
            return self._current_level_key2value

    def nurture(self):
        if self._child_iter is None:
            self._child_iter = self.children()
        _child = next(self._child_iter, [])
        nodes = []
        for item in _child:
            if isinstance(item, list):
                nodes.extend(item)
                for node in item:
                    self._key2child[node.key()] = node
            else:
                nodes.append(item)
                self._key2child[item.key()] = item
        try:
            self._child_iter.send(_child)
        except StopIteration:
            pass
        return nodes

    def center(self):
        return self._center

    def __getattr__(self, name):
        client = self._center.get(name)
        if not client:
            raise WebNodeException('No such rpc client: %s' % name)
        return client

class MediumYieldRoot(MediumYieldNode):

    def __init__(self, drivers):
        super(MediumYieldRoot, self).__init__()
        self.drivers = drivers
        self.all_key2value = {}

    def prepare(self):
        self.on_prepare()

    def on_prepare(self):
        pass

    def finish(self):
        self.on_finish()

    def on_finish(self):
        pass

    def gao(self):
        self.prepare()
        nodes = self.nurture()
        level = 0
        while nodes:
            logging.debug('level: %d' % level)
            level += 1
            next_level_nodes = []
            current_key2value = {}

            for node in nodes:
                key2value = node.send(self.all_key2value)
                # key2value = node.next()
                if not key2value:
                    next_generation = node.nurture()
                    if next_generation:
                        next_level_nodes.extend(next_generation)
                else:
                    next_level_nodes.append(node)
                current_key2value.update(key2value)

            # aggregate and filter duplicate fetch
            current_key2value.update((key, self.all_key2value[key]) for key in current_key2value.viewkeys() & self.all_key2value.viewkeys())

            logging.debug(self.all_key2value)

            for driver in self.drivers:
                driver.prepare(current_key2value)

            for driver in self.drivers:
                driver.execute(current_key2value)

            for driver in self.drivers:
                driver.finish(current_key2value)

            self.all_key2value.update(current_key2value)

            nodes = next_level_nodes

        self.finish()


text:
var http = require("http"),
    fs = require("fs"),
    server = {},
    requestFile = fs.openSync('tests/data/actual/date-request.json', 'w'),
    dateAfterInitialCommit = '{"lastModifiedOn" : "2014-05-06T15:28:19Z"}';

module.exports = function(grunt){
    grunt.registerTask('start-date-server', function(){
        server = http.createServer(function(request, response) {
            fs.writeSync(requestFile, JSON.stringify({ headers: request.headers, url: request.url }));

            response.writeHead(200, {"Content-Type": "application/json"});
            response.write(dateAfterInitialCommit);
            response.end();
        }).listen(8888);
    });
};

redpajama_set_name: RedPajamaGithub


text:
body {
  background-color: #ccc;
  color: red;
}


text:
package com.khorn.terraincontrol.configuration.settingType;

import static org.junit.Assert.assertEquals;

import com.khorn.terraincontrol.exception.InvalidConfigException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class LongSettingTest extends AbstractSettingTest
{
    @Test
    public void testRoundTrips() throws InvalidConfigException
    {
        LongSetting setting = new LongSetting("TestSetting", 0, Long.MIN_VALUE, Long.MAX_VALUE);
        testValue(setting, Long.MIN_VALUE);
        testValue(setting, 0L);
        testValue(setting, Long.MAX_VALUE);
    }

    @Test(expected = InvalidConfigException.class)
    public void testInvalidSetting() throws InvalidConfigException
    {
        new LongSetting("TestSetting", 0, -1, 1).read("NotANumber");
    }

    @Test
    public void testOutOfBoundsSetting() throws InvalidConfigException
    {
        long min = -1;
        long max = 1;

        assertEquals(max, new LongSetting("TestSetting", 0, min, max).read("2").intValue());
        assertEquals(min, new LongSetting("TestSetting", 0, min, max).read("-2").intValue());
    }
}


text:
#if !defined(AFX_H264AVCDECODER_H__FBF0345F_A5E5_4D18_8BEC_4A68790901F7__INCLUDED_)
#define AFX_H264AVCDECODER_H__FBF0345F_A5E5_4D18_8BEC_4A68790901F7__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

//#include "GOPDecoder.h"
#include "H264AVCCommonLib/Sei.h"
// ying{{
#include "H264AVCCommonLib/MbDataCtrl.h"
#include "DownConvert.h"
#include "H264AVCCommonLib/MotionCompensation.h"

// TMM_ESS
#include "ResizeParameters.h"
// ying}}
//#include "Multiview_dec.h"

H264AVC_NAMESPACE_BEGIN

class SliceReader;
class SliceDecoder;
class FrameMng;
class PocCalculator;
class LoopFilter;
class HeaderSymbolReadIf;
class ParameterSetMng;
class NalUnitParser;
class ControlMngIf;
//class RQFGSDecoder; ying

class H264AVCDECODERLIB_API H264AVCDecoder
{
protected:
	H264AVCDecoder         ();
  virtual ~H264AVCDecoder();

public:
  static  ErrVal create ( H264AVCDecoder*& rpcH264AVCDecoder );
  ErrVal destroy();
  ErrVal init   ( /*MCTFDecoder*        apcMCTFDecoder[MAX_LAYERS],*/
                  SliceReader*        pcSliceReader,
                  SliceDecoder*       pcSliceDecoder,
//                  RQFGSDecoder*       pcRQFGSDecoder, ying
                  FrameMng*           pcFrameMng,
                  NalUnitParser*      pcNalUnitParser,
                  ControlMngIf*       pcControlMng,
                  LoopFilter*         pcLoopFilter,
                  HeaderSymbolReadIf* pcHeaderSymbolReadIf,
                  ParameterSetMng*    pcParameterSetMng,
                  PocCalculator*      pcPocCalculator,
                  MotionCompensation* pcMotionCompensation );
  ErrVal uninit ();

//JVT-V054
  SliceHeader *getPrevSliceHeader() const { return m_pcPrevSliceHeader ; }

//JVT-S036 start
  SliceHeader *getSliceHeader() const { return m_pcSliceHeader ; }
  ErrVal  initPacketPrefix( BinDataAccessor*  pcBinDataAccessor,
                            UInt&             ruiNalUnitType
                            , Bool            bPreParseHeader //FRAG_FIX
                            , Bool			      bConcatenated //FRAG_FIX_3
                            , Bool&           rbStartDecoding
                            ,SliceHeader *   pcSliceHeader
                           ,NalUnitParser*          pcNalUnitParser
    );
//JVT-S036 lsj end
  ErrVal  initPacket( BinDataAccessor*  pcBinDataAccessor,
	                    UInt&             ruiNalUnitType,
	                    UInt&             ruiMbX,
	                    UInt&             ruiMbY,
	                    UInt&             ruiSize
						//,UInt&				ruiNonRequiredPic  //NonRequired JVT-Q066
                        //JVT-P031
	                      ,Bool              bPreParseHeader //FRAG_FIX
		                  , Bool			bConcatenated //FRAG_FIX_3
                        ,Bool&             rbStartDecoding,
                        UInt&             ruiStartPos,
                        UInt&             ruiEndPos,
                        Bool&             bFragmented,
                        Bool&             bDiscardable
                        //~JVT-P031
						,Bool&			  UnitAVCFlag	//JVT-S036
                        );
//Dec. 1 fix view order for base view {{
  UInt*   getViewOrder  () { return m_puiViewOrder; }
//}}
  //JVT-P031
  ErrVal  initPacket( BinDataAccessor*  pcBinDataAccessor);
  Void    getDecodedResolution(UInt &uiLayerId);
  UInt    getNumOfNALInAU() {return m_uiNumOfNALInAU;}
  Void    decreaseNumOfNALInAU(){ m_uiNumOfNALInAU--;}
  Void    setDependencyInitialized(Bool b) { m_bDependencyInitialized = b;}
  Void    initNumberOfFragment();
  //~JVT-P031
  ErrVal  process   ( PicBuffer*        pcPicBuffer,
                      PicBufferList&    rcPicBufferOutputList,
                      PicBufferList&    rcPicBufferUnusedList,
                      PicBufferList&    rcPicBufferReleaseList );

  // ROI DECODE Init ICU/ETRI
  Void	  RoiDecodeInit()
  {
	    m_bCurNalIsEndOfPic		= false;
		m_iCurNalSpatialLayer 	= -1;
		m_iNextNalSpatialLayer  = -1;
		m_iCurNalPOC			= -1;
		m_iNextNalPOC			= -1;
		m_iCurNalFirstMb		= -1;
  }

  Bool	  IsSliceEndOfPic()				{ return m_bCurNalIsEndOfPic;  }
  /*
  ErrVal  getBaseLayerData              ( IntFrame*&      pcFrame,
                                          IntFrame*&      pcResidual,
                                          MbDataCtrl*&    pcMbDataCtrl,
                                          MbDataCtrl*&    pcMbDataCtrlEL,
                                          Bool&           rbConstrainedIPred,
                                          Bool&           rbSpatialScalability,
                                          UInt            uiLayerId,
                                          UInt            uiBaseLayerId,
                                          Int             iPoc,
                                          UInt            uiBaseQualityLevel); //JVT-T054
                                          */
  ErrVal  getBaseLayerPWTable          ( SliceHeader::PredWeightTable*& rpcPredWeightTable,
                                         UInt                           uiBaseLayerId,
                                         ListIdx                        eListIdx,
                                         Int                            iPoc );

  Void    setBaseAVCCompatible        ( Bool                        bAVCCompatible )    { m_bBaseLayerIsAVCCompatible = bAVCCompatible; }
  Void    setReconstructionLayerId    ( UInt                        uiLayerId )         { m_uiRecLayerId = uiLayerId; }
  Void    setVeryFirstSPS             (  SequenceParameterSet* pcSPS )                  { m_pcVeryFirstSPS = pcSPS; }

  ErrVal  calculatePoc                ( NalUnitType       eNalUnitType,
                                        SliceHeader&      rcSliceHeader,
                                        Int&              slicePoc  );
  ErrVal  checkSliceLayerDependency   ( BinDataAccessor*  pcBinDataAccessor,
                                        Bool&             bFinishChecking
									    ,Bool&			  UnitAVCFlag    //JVT-S036
									   );
//	TMM_EC {{
	Bool		checkSEIForErrorConceal();
  ErrVal  checkSliceGap   ( BinDataAccessor*  pcBinDataAccessor,
                            MyList<BinData*>&	cVirtualSliceList
							,Bool&			  UnitAVCFlag		//JVT-S036
						   );
	ErrVal	setec( UInt uiErrorConceal) { m_eErrorConceal = (ERROR_CONCEAL)(EC_NONE + uiErrorConceal); if ( m_eErrorConceal == 0) m_bNotSupport = true; return	Err::m_nOK;}
	UInt	m_uiNextFrameNum;
	UInt	m_uiNextLayerId;
	UInt	m_uiNextPoc;
	UInt	m_uiNextTempLevel;
	UInt	*m_pauiPocInGOP[MAX_LAYERS];
	UInt	*m_pauiFrameNumInGOP[MAX_LAYERS];
	UInt	*m_pauiTempLevelInGOP[MAX_LAYERS];
	UInt	m_uiDecompositionStages[MAX_LAYERS];
	UInt	m_uiNumLayers;
	UInt	m_uiFrameIdx[MAX_LAYERS];
	ERROR_CONCEAL	m_eErrorConceal;
	UInt	m_uiDefNumLayers;
	UInt	m_uiDefDecompositionStages[MAX_LAYERS];
	UInt	m_uiMaxDecompositionStages;
	UInt	m_uiMaxGopSize;
	UInt	m_uiGopSize[MAX_LAYERS];
	Bool	m_bNotSupport;
	UInt	m_uiMaxLayerId;
//  TMM_EC }}
  Void    setQualityLevelForPrediction( UInt ui ) { m_uiQualityLevelForPrediction = ui; }

  UInt isNonRequiredPic()						  { return m_uiNonRequiredPic;  } //NonRequired JVT-Q066
  Bool isRedundantPic()             { return m_bRedundantPic; }  // JVT-Q054 Red. Picture
  ErrVal  checkRedundantPic();  // JVT-Q054 Red. Picture
  Void    setFGSRefInAU(Bool &b); //JVT-T054
protected:

  ErrVal  xInitSlice                ( SliceHeader*    pcSliceHeader );
  ErrVal  xStartSlice               ( Bool& bPreParseHeader, Bool& bLastFragment, Bool& bDiscardable, Bool UnitAVCFlag); //FRAG_FIX //TMM_EC//JVT-S036
  // TMM_EC {{
  ErrVal  xProcessSliceVirtual      ( SliceHeader&    rcSH,
	                                    SliceHeader* pcPrevSH,
									                    PicBuffer* &    rpcPicBuffer);
  // TMM_EC }}
  ErrVal  xProcessSlice             ( SliceHeader&    rcSH,
                                      SliceHeader*    pcPrevSH,
                                      PicBuffer*&     rpcPicBuffer,
                                      PicBufferList&   rcPicBufferOutputList,
                                      PicBufferList&   rcPicBufferUnusedList,
                                      Bool            bHighestLayer); //JVT-T054
//  ErrVal  xReconstructLastFGS       (Bool bHighestLayer); //JVT-T054
/*  ErrVal  xDecodeFGSRefinement      ( SliceHeader*&   rpcSliceHeader,
                                      PicBuffer*&     rpcPicBuffer );
*/ //ying
  ErrVal  xZeroIntraMacroblocks     ( IntFrame*       pcFrame,
                                      MbDataCtrl*     pcMbDataCtrl,
                                      SliceHeader*    pcSliceHeader );
/*
  ErrVal  setDiffPrdRefLists        ( RefFrameList&               diffPrdRefList,
                                      YuvBufferCtrl*              pcYuvFullPelBufferCtrl);
                                      */
  ErrVal  freeDiffPrdRefLists       ( RefFrameList& diffPrdRefList);

protected:
  SliceReader*                  m_pcSliceReader;
  SliceDecoder*                 m_pcSliceDecoder;
  FrameMng*                     m_pcFrameMng;
  NalUnitParser*                m_pcNalUnitParser;
  ControlMngIf*                 m_pcControlMng;
  LoopFilter*                   m_pcLoopFilter;
  HeaderSymbolReadIf*           m_pcHeaderSymbolReadIf;
  ParameterSetMng*              m_pcParameterSetMng;
  PocCalculator*                m_pcPocCalculator;
  SliceHeader*                  m_pcSliceHeader;
  SliceHeader*                  m_pcPrevSliceHeader;
  SliceHeader*                  m_pcSliceHeader_backup; //JVT-Q054 Red. Picture
  Bool                          m_bFirstSliceHeaderBackup;  //JVT-Q054 Red. Picture
  Bool                          m_bRedundantPic;  // JVT-Q054 Red. Picture
  Bool                          m_bInitDone;
  Bool                          m_bLastFrame;
  Bool                          m_bFrameDone;
  MotionCompensation*           m_pcMotionCompensation;

  //MCTFDecoder*                  m_apcMCTFDecoder[MAX_LAYERS];
  //RQFGSDecoder*                 m_pcRQFGSDecoder; ying
  PicBuffer*                    m_pcFGSPicBuffer;

  Bool                          m_bEnhancementLayer;
  Bool                          m_bActive;
  Bool                          m_bReconstruct;
  Bool                          m_bBaseLayerIsAVCCompatible;
	Bool                          m_bNewSPS;
  UInt                          m_uiRecLayerId;
  UInt                          m_uiLastLayerId;
  SequenceParameterSet*         m_pcVeryFirstSPS;
  SliceHeader*                  m_pcVeryFirstSliceHeader;

  Bool                          m_bCheckNextSlice;
  Bool                          m_bDependencyInitialized;

  Int                           m_iLastPocChecked;
  Int                           m_iFirstSlicePoc;

  Int                           m_iFirstLayerIdx;
  Int                           m_iLastLayerIdx;
  Bool                          m_bBaseLayerAvcCompliant;

  Int                           m_auiBaseLayerId[MAX_LAYERS];
  Int                           m_auiBaseQualityLevel[MAX_LAYERS];

  // should this layer be decoded at all, and up to which FGS layer should be decoded
  UInt                          m_uiQualityLevelForPrediction;

  Bool                          m_bFGSCodingMode;
  UInt                          m_uiGroupingSize;
  UInt                          m_uiPosVect[16];

//Dec. 1 fix view order for base view {{
  UInt*                         m_puiViewOrder;
//}}

//SEI {
  UInt							m_uiScalableNestingSeiFlag;
  UInt							m_uiScalableNestingSeiRead;
  UInt							m_uiSnapshotSeiFlag;
  Bool							m_bAllPicturesInAuFlag;
  UInt							m_uiNumPicturesMinus1;
  UInt						    m_uiTemporalId;
  UInt							m_uiPicId[MAX_PICTURES_IN_ACCESS_UNIT];
  UInt							m_uiSnapShotId;
  int							m_uiPoc;

  Bool							m_bOpPresentFlag;
  UInt						    m_uiOperationPointId;
  UInt							m_uiNumActiveViews;
  //UInt							m_uiViewId[MAX_VIEWS]; // YSH
  UInt							m_uiNumDecodeViews;
  //UInt							m_uiDecodeView[MAX_VIEWS]; // YSH
  UInt							m_uiNumOpMinus1;
  UInt							m_uiNumViews[MAX_OPERATION_POINTS];
  UInt*							m_OpViewId[MAX_OPERATION_POINTS];
  //JVT-AB025 {{
  UInt              m_uiTargetViewId;
  UInt              *m_auiViewOrderIndex;
  UInt              *m_auiNumNonReqViewCop;
  UInt              **m_aauiIndexDelta;
  UInt              **m_aauiNonReqViewOrderIndex;
  UInt              m_uiNumTargetViewMinus1;
  UInt              m_uiOPNotPresentSeiFlag;
  UInt              m_uiNumNotPresentOP;
  UInt              m_auiNotPresentOPID[MAX_OPERATION_POINTS];
  //JVT-AB025 }}
//SEI }

  UInt							m_uiMultiviewSceneInfoSeiFlag; // SEI JVT-W060
  UInt							m_uiMaxDisparity; // SEI JVT-W060
  UInt							m_uiMultiviewAcquisitionInfoSeiFlag; // SEI JVT-W060
  SEI::NonRequiredSei*			m_pcNonRequiredSei;
  UInt							m_uiNonRequiredSeiReadFlag;
	UInt							m_uiNonRequiredSeiRead;
	UInt							m_uiNonRequiredPic;	//NonRequired JVT-Q066
  UInt							m_uiPrevPicLayer;
  UInt							m_uiCurrPicLayer;
  //JVT-P031
  UInt                          m_uiFirstFragmentPPSId;
  UInt                          m_uiFirstFragmentNumMbsInSlice;
  Bool                          m_bFirstFragmentFGSCompSep;
  UInt                          m_uiLastFragOrder;
  UInt                          m_uiNumberOfFragment[MAX_LAYERS];
  UInt                          m_uiNumberOfSPS;
  UInt                          m_uiSPSId[MAX_LAYERS];
  UInt                          m_uiDecodedLayer;
  UInt                          m_uiNumOfNALInAU;
  SliceHeader*                  m_pcSliceHeaderStored;
  Int                           m_iPrevPoc;
  //~JVT-P031

  SliceHeader::PredWeightTable  m_acLastPredWeightTable[2];

  // ROI DECODE ICU/ETRI
  int	m_iCurNalSpatialLayer;
  int	m_iNextNalSpatialLayer;

  int	m_iCurNalPOC;
  int	m_iNextNalPOC;
  int   m_iCurNalFirstMb;

  bool	m_bCurNalIsEndOfPic;
  bool	m_bFirstFGS;

//JVT-T054{
  Bool                          m_bLastNalInAU;
  Bool                          m_bFGSRefInAU;
  Bool                          m_bAVCBased;
  Bool                          m_bCGSSNRInAU;
  Bool                          m_bOnlyAVCAtLayer;
//JVT-T054}
public:
  MbDataCtrl*         m_pcBaseLayerCtrlEL;
};

H264AVC_NAMESPACE_END

#endif // !defined(AFX_H264AVCDECODER_H__FBF0345F_A5E5_4D18_8BEC_4A68790901F7__INCLUDED_)


text:
<?php

namespace Go\Console\Command;

use Go\Core\AspectKernel;
use Go\Instrument\ClassLoading\SourceTransformingLoader;
use Go\Instrument\Transformer\FilterInjectorTransformer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Console command for warming the cache
 */
class WarmupCommand extends Command
{

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this
            ->setName('goaop:warmup')
            ->addArgument('loader', InputArgument::REQUIRED, "Path to the aspect loader file")
            ->setDescription("Warm up the cache with woven aspects")
            ->setHelp(<<<EOT
Initializes the kernel and, if successful, warm up the cache for PHP
files under the application directory.

By default, the cache directory is taken from configured AspectKernel class.
EOT
            );
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("Loading aspect kernel for warmup...");
        $loader = $input->getArgument('loader');
        $path   = stream_resolve_include_path($loader);
        if (!is_readable($path)) {
            throw new \InvalidArgumentException("Invalid loader path: {$loader}");
        }
        include_once $path;

        if (!class_exists('Go\Core\AspectKernel', false)) {
            $message = "Kernel was not initialized yet, please configure it in the {$path}";
            throw new \InvalidArgumentException($message);
        }

        $kernel  = AspectKernel::getInstance();
        $options = $kernel->getOptions();

        if (empty($options['cacheDir'])) {
            throw new \InvalidArgumentException("Cache warmer require the `cacheDir` options to be configured");
        }

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator(
                $options['appDir'],
                \FilesystemIterator::SKIP_DOTS
            )
        );

        /** @var \CallbackFilterIterator|\SplFileInfo[] $iterator */
        $iterator   = new \CallbackFilterIterator($iterator, $this->getFileFilter($options));
        $totalFiles = iterator_count($iterator);
        $output->writeln("Total <info>{$totalFiles}</info> files to process.");
        $iterator->rewind();

        set_error_handler(function ($errno, $errstr, $errfile, $errline) {
            throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
        });

        $index  = 0;
        $errors = array();
        foreach ($iterator as $file) {
            if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
                $output->writeln("Processing file <info>{$file->getRealPath()}</info>");
            }
            $isSuccess = null;
            try {
                // This will trigger creation of cache
                file_get_contents(
                    FilterInjectorTransformer::PHP_FILTER_READ.
                    SourceTransformingLoader::FILTER_IDENTIFIER.
                    "/resource=" . $file->getRealPath()
                );
                $isSuccess = true;
            } catch (\Exception $e) {
                $isSuccess = false;
                $errors[$file->getRealPath()] = $e;
            }
            if ($output->getVerbosity() == OutputInterface::VERBOSITY_NORMAL) {
                $output->write($isSuccess ? '.' : '<error>E</error>');
                if (++$index % 50 == 0) {
                    $output->writeln("($index/$totalFiles)");
                }
            }
        }

        restore_error_handler();

        if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
            foreach ($errors as $file=>$error) {
                $message = "File {$file} is not processed correctly due to exception: {$error->getMessage()}";
                $output->writeln($message);
            }
        }

        $output->writeln("<info>Done</info>");
    }

    /**
     * Filter for files
     *
     * @param array $options Kernel options
     *
     * @return callable
     */
    protected function getFileFilter(array $options)
    {
        $includePaths   = $options['includePaths'];
        $excludePaths   = $options['excludePaths'];
        $excludePaths[] = $options['cacheDir'];

        return function (\SplFileInfo $file) use ($includePaths, $excludePaths) {
            if ($file->getExtension() !== 'php') {
                return false;
            };

            if ($includePaths) {
                $found = false;
                foreach ($includePaths as $includePath) {
                    if (strpos($file->getRealPath(), realpath($includePath)) === 0) {
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    return false;
                }
            }

            foreach ($excludePaths as $excludePath) {
                if (strpos($file->getRealPath(), realpath($excludePath)) === 0) {
                    return false;
                }
            }

            return true;
        };
    }
}


text:
package objectReadWrite;

import java.io.*;
import java.util.*;
import java.util.logging.*;

/** JDK before version 7. */
public class ExerciseSerializableLessThanJDK7 {
	//Use Java's logging facilities to record exceptions.
	//The behavior of the logger can be configured through a
	//text file, or programmatically through the logging API.
	private static final Logger fLogger = Logger.getLogger(ExerciseSerializableLessThanJDK7.class.getPackage().getName());
	public static void main(String... aArguments) {
		//create a Serializable List
		List<String> quarks = Arrays.asList("up", "down", "strange", "charm", "top", "bottom");

		//serialize the List
		//note the use of abstract base class references
		try{
			//use buffering
			OutputStream file = new FileOutputStream("quarks.ser");
			OutputStream buffer = new BufferedOutputStream(file);
			ObjectOutput output = new ObjectOutputStream(buffer);
			try{
				output.writeObject(quarks);
			}finally{
				output.close();
			}
		}catch(IOException ex){
			fLogger.log(Level.SEVERE, "Cannot perform output.", ex);
		}

		//deserialize the quarks.ser file
		//note the use of abstract base class references

		try{
			//use buffering
			InputStream file = new FileInputStream("quarks.ser");
			InputStream buffer = new BufferedInputStream(file);
			ObjectInput input = new ObjectInputStream (buffer);
			try{
				//deserialize the List
				List<String> recoveredQuarks = (List<String>)input.readObject();
				//display its data
				for(String quark: recoveredQuarks){
					System.out.println("Recovered Quark: " + quark);
				}
			}finally{
				input.close();
			}
		}
		catch(ClassNotFoundException ex){
			fLogger.log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
		}catch(IOException ex){
			fLogger.log(Level.SEVERE, "Cannot perform input.", ex);
		}
	}
}


text:
''' Python script to generate a stub README.md files from a plugin.json file '''
import json
import argparse
import os
import sys
import configparser
from collections import OrderedDict

parser = argparse.ArgumentParser(description = 'Generate README.md index of all plugins')
parser.add_argument("-f", "--force", help = 'will automatically overwrite existing README', action='store_true')

args = parser.parse_args()

os.path.realpath(__file__)

basedir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'plugins')
outputfile = os.path.join(basedir, 'README.md')

if not args.force and os.path.isfile(outputfile):
	print("Cowardly refusing to overwrite an existing README. Remove or re-run with -f.")
	sys.exit(0)

channels = os.walk(basedir).next()[1]

template = '# Binary Ninja Plugins\n\n'

config = configparser.ConfigParser()
config.readfp(open(os.path.join(basedir, '..', '.gitmodules')))
submodules = {}

for section in config.items()[1:]:
	sectionname = section[0].split('"')[1]
	submodules[sectionname] = config.get(section[0], 'url')

for channel in ['official', 'community']:  # Because otherwise it's alphabetical
	index = os.path.join(basedir, channel + ".json")
	if not args.force and os.path.isfile(index):
		print("Cowardly refusing to overwrite an existing index. Remove or re-run with -f.")
		sys.exit(0)

	plugins = []

	if channel.startswith('.'):
		continue

	template += "## {}\n\n".format(channel.title())

	template += '''| PluginName | Author | License | Description |
|------------|--------|---------|-------------|
'''

	for plugin in os.walk(os.path.join(basedir, channel)).next()[1]:
		try:
			url = submodules[os.path.join('plugins', channel, plugin)]
			if url.endswith('.git'):
				url = url[:-4]
			authorlink = '/'.join(url.split('/')[:4])
		except:
			url = 'https://github.com/Vector35/binaryninja-plugins/tree/master/plugins/{channel}/{plugin}'.format(channel = channel, plugin = plugin)
			authorlink = 'https://github.com/Vector35/'
		data = json.load(open(os.path.join(basedir, channel, plugin, "plugin.json")), object_pairs_hook=OrderedDict)['plugin']
		data['url'] = url
		data['path'] = plugin
		plugins.append(data)
		template += '|[{name}]({url})|[{author}]({authorlink})|[{license}]({channel}/{plugin}/LICENSE)|{description}|\n'.format(name = data['name'], channel = channel,
		            url = url, plugin = plugin, author = data['author'], authorlink = authorlink,
		            license = data['license']['name'], description = data['description'])
	template += "\n\n"
	print("Writing {outputfile}".format(outputfile=index))
	open(index, 'w').write(json.dumps(plugins, indent=4, sort_keys=True))

print("Writing {outputfile}".format(outputfile=outputfile))
open(outputfile, 'w').write(template)


text:
package protocol

import (
	"strings"

	"github.com/aws/aws-sdk-go/aws/request"
)

// ValidateEndpointHostHandler is a request handler that will validate the
// request endpoint's hosts is a valid RFC 3986 host.
var ValidateEndpointHostHandler = request.NamedHandler{
	Name: "awssdk.protocol.ValidateEndpointHostHandler",
	Fn: func(r *request.Request) {
		err := ValidateEndpointHost(r.Operation.Name, r.HTTPRequest.URL.Host)
		if err != nil {
			r.Error = err
		}
	},
}

// ValidateEndpointHost validates that the host string passed in is a valid RFC
// 3986 host. Returns error if the host is not valid.
func ValidateEndpointHost(opName, host string) error {
	paramErrs := request.ErrInvalidParams{Context: opName}
	labels := strings.Split(host, ".")

	for i, label := range labels {
		if i == len(labels)-1 && len(label) == 0 {
			// Allow trailing dot for FQDN hosts.
			continue
		}

		if !ValidHostLabel(label) {
			paramErrs.Add(request.NewErrParamFormat(
				"endpoint host label", "[a-zA-Z0-9-]{1,63}", label))
		}
	}

	if len(host) > 255 {
		paramErrs.Add(request.NewErrParamMaxLen(
			"endpoint host", 255, host,
		))
	}

	if paramErrs.Len() > 0 {
		return paramErrs
	}
	return nil
}

// ValidHostLabel returns if the label is a valid RFC 3986 host label.
func ValidHostLabel(label string) bool {
	if l := len(label); l == 0 || l > 63 {
		return false
	}
	for _, r := range label {
		switch {
		case r >= '0' && r <= '9':
		case r >= 'A' && r <= 'Z':
		case r >= 'a' && r <= 'z':
		case r == '-':
		default:
			return false
		}
	}

	return true
}


text:
This project contains a simple harness to run performance tests and measure the
results.

## Run the Performance Tests
**Pre-requisite:** The dotnet cli is available at the root in the dotnetcli directory. On a clean repo, build.cmd at the root installs the latest available dotnet.exe.

1. Navigate to the PerfHarness directory (corefxlab\scripts\PerfHarness\)

2. Restore this project

   (`..\..\dotnetcli\dotnet.exe restore`)

3a. Run the harness--make sure to use the release configuration

   (`..\..\dotnetcli\dotnet.exe run -c Release`)

3b. To run specific tests only, pass in the type names to the harness (this run types found in any of the assemblies):

   (`..\..\dotnetcli\dotnet.exe run -c Release -- --perf:typenames name1 [name2] [...]`)

3c. To run specific tests found in a specific assembly only, pass in the assembly name and type names to the harness:

   (`..\..\dotnetcli\dotnet.exe run -c Release -- --assembly <name> --perf:typenames name1 [name2] [...]`)

   Example: `..\..\dotnetcli\dotnet.exe run -c Release -- --assembly System.Text.Primitives.Tests --perf:typenames System.Text.Primitives.Tests.EncodingPerfComparisonTests`

## Add a New Performance Test

When adding a new xunit-performance compatible test project, simply make the
following changes to enable it to run using this harness:

* Add a project reference in this project's `csproj` file referencing the new
  test project.

* Add the new element to the array returned by `GetTestAssemblies()` inside
  `PerfHarness.cs`. The element should be the name of the perf test project
  assembly, excluding the file extension.

## Xunit-Performance-Api

Here are the list of command line options available when running performance tests (starting from build [1.0.0-alpha-build0048](https://dotnet.myget.org/feed/dotnet-core/package/nuget/xunit.performance.api) onwards).

Option | Description
--- | ---
--perf:outputdir | Specifies the output directory name.
--perf:runid | User defined id given to the performance harness.
--perf:typenames | The (optional) type names of the test classes to run.
--help | Display this help screen.
--version | Display version information.


text:
from fontParts.base import BaseBPoint
from fontParts.fontshell.base import RBaseObject

class RBPoint(BaseBPoint, RBaseObject):
    pass


text:
extern "Java"
{
  namespace gnu
  {
    namespace CORBA
    {
      namespace Poa
      {
          class gnuPOA;
          class gnuPOA$RefTemplate;
      }
    }
  }
  namespace org
  {
    namespace omg
    {
      namespace CORBA
      {
          class Object;
      }
    }
  }
}

class gnu::CORBA::Poa::gnuPOA$RefTemplate : public ::java::lang::Object
{

public: // actually package-private
  gnuPOA$RefTemplate(::gnu::CORBA::Poa::gnuPOA *);
public:
  virtual JArray< ::java::lang::String * > * adapter_name();
  virtual ::java::lang::String * orb_id();
  virtual ::java::lang::String * server_id();
  virtual ::org::omg::CORBA::Object * make_object(::java::lang::String *, JArray< jbyte > *);
  virtual JArray< ::java::lang::String * > * _truncatable_ids();
private:
  static const jlong serialVersionUID = 1LL;
public: // actually package-private
  JArray< ::java::lang::String * > * __attribute__((aligned(__alignof__( ::java::lang::Object)))) m_adapter_name;
  ::gnu::CORBA::Poa::gnuPOA * this$0;
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_CORBA_Poa_gnuPOA$RefTemplate__


text:
title: Configuration
weight: 13
product: "Uchiwa"
version: "1.0"
menu:
  uchiwa-1.0:
    parent: getting-started
---

## Configuration Load Order
Uchiwa loads configuration from these sources in the following order:

1. Uchiwa loads configuration from the configuration file (by default, this is located at `/etc/sensu/uchiwa.json` which is provided with the `-c` command line argument).
2. Uchiwa loads configuration snippets from configuration files located in one or multiple Uchiwa configuration directories (by default, this is the `/etc/sensu/dashboard.d/` directory which is provided with the `-d` command line argument).

## Minimal Configuration

{{< code json >}}
{
  "sensu": [
    {
      "name": "Site 1",
      "host": "api1.example.com",
      "port": 4567
    }
  ],
  "uchiwa": {
    "host": "0.0.0.0",
    "port": 3000
  }
}{{< /code >}}

## Datacenters Configuration (Sensu) {#datacenters-configuration-sensu}
The *sensu* array contains a hash for every Sensu API, represented as **datacenters** in Uchiwa.

Each hash can contain the following attributes:
{{< code json >}}
{
  "sensu": [
    {
      "name": "API Name",
      "host": "127.0.0.1",
      "port": 443,
      "ssl": true,
      "insecure": true,
      "path": "/site2",
      "timeout": 5,
      "user": "admin",
      "pass": "secret"
    }
  ]
}{{< /code >}}

Key     | Required | Type | Description
--------|----------|------|------
name | false | string | Name of the Sensu API (used as datacenter name). If empty, a random one will be generated.
host | true | string | Hostname or IP address of the Sensu API.
port | false | integer | Port of the Sensu API. The default value is `4567`.
ssl | false | boolean | Determines whether or not to use the HTTPS protocol. The default value is `false`.
insecure | false | boolean | Determines whether or not to accept an insecure SSL certificate. The default value is `false`.
path | false | string | Path of the Sensu API.
timeout | false | integer | Timeout for the Sensu API, in seconds. The default value is `5`.
user | false | string | Username of the Sensu API.
pass | false | string | Password of the Sensu API.

## Uchiwa Configuration

The *uchiwa* hash can contain the following attributes:

{{< code json >}}
{
  "uchiwa": {
    "host": "0.0.0.0",
    "port": 3000,
    "loglevel": "info",
    "refresh": 10,
    "user": "admin",
    "pass": "secret",
    "users": {"...":"..."},
    "auth": {"...":"..."},
    "ssl": {"...":"..."},
    "usersOptions": {"...":"..."}
  }
}{{< /code >}}

Key     | Required | Type | Description
--------|----------|------|------
host | false | string | Address on which Uchiwa will listen. The default value is `0.0.0.0`. To use an IPv6 address, use square brackets (e.g. `[::1]`)
port | false | integer | Port on which Uchiwa will listen. The default value is `3000`.
loglevel | false | string | Level of logging to show after Uchiwa has started. The default value is `info`. Allowed values are `trace`, `debug`, `info`, `warn`, `fatal`
refresh | false | integer | Determines the interval to pull the Sensu APIs, in seconds. The default value is `10`.
user | false | string | Username of the Uchiwa dashboard. Remove to disable authentication.
pass | false | string | Password of the Uchiwa dashboard. Remove to disable authentication.
users | false | hash | [See the Mutliple Users documentation](#multiple-users). Has precedence over the **user** attribute.
auth | false | hash | [See the High Availability documentation][1].
ssl | false | hash | [See the HTTPS Encryption documentation][2].
usersOptions | false | hash | [See the Users Options documentation](#users-options).

### Multiple Users {#multiple-users}

You can define multiple users, including read-only users, within your
users attribute. The **users** attribute has precedence over the **user** attribute.

{{< code json >}}
{
  "uchiwa": {
    "users": [
      {
        "username" : "admin",
        "password": "secret",
        "accessToken": "vFzX6rFDAn3G9ieuZ4ZhN-XrfdRow4Hd5CXXOUZ5NsTw4h3k3l4jAw__",
        "readonly": false
      },
      {
        "username" : "guest",
        "password": "secret",
        "accessToken": "hrKMW3uIt2RGxuMIoXQ-bVp-TL1MP4St5Hap3KAanMxI3OovFV48ww__",
        "readonly": true
      }
    ]
  }
}{{< /code >}}

Key     | Required | Type | Description
--------|----------|------|------
username | true | string | Username of the user.
password | true | string | Password of the user. Also see the [Encrypted Passwords documentation][3]].
accessToken | false | string | A unique and secure token to interact with the Uchiwa API as the related user. Remember to keep your access tokens secret. Must only contain friendly URL characters. See [Generating an access token](#generating-an-access-token) and [API Authentication][4]].
readonly | false | boolean | Restrict write access to the dashboard (create stashes, delete clients, etc.). The default value is `false`.

### Users Options {#users-options}

This hash can set various global users options.

{{< code json >}}
{
  "uchiwa": {
    "usersOptions": {
      "dateFormat": "YYYY-MM-DD HH:mm:ss",
      "defaultTheme": "uchiwa-default",
      "disableNoExpiration": false,
      "favicon": "http://127.0.0.1/favicon.png",
      "logoURL": "http://127.0.0.1/logo.png",
      "requireSilencingReason": false,
      "silenceDurations": [ 0.5, 2 ]
    }
  }
}{{< /code >}}

Key     | Required | Type | Description
--------|----------|------|------
dateFormat | false | string | Determines the format of dates displayed. Default value is `YYYY-MM-DD HH:mm:ss`. See http://momentjs.com/docs/#/displaying/format/ for possible values.
defaultTheme | false | string | Determines the default theme to use for new users. Can be overridden at the user level in settings view. Possible values are `uchiwa-default` (light theme) and `uchiwa-dark` (dark theme). The default value is `uchiwa-default`.
disableNoExpiration | false | boolean | Disables the `only if manually removed` option from the silencing entry creation. The default value is `false`.
favicon | false | string | URL or full path to a custom favicon. Leave empty to use the default favicon.
logoURL | false | string | URL to a custom logo. Leave empty to use the default logo.
requireSilencingReason | false | boolean | Determines whether a reason must be provided or not when creating a silence entry. The default value is `false`.
silenceDurations | false | array of decimals | Additional preset durations (**in hours**) when silencing an item. Decimal values are allowed. The default value is `[ 0.25, 1, 24 ]`, which corresponds to `15 minutes`, `an hour` and `a day`.

### Generating an access token {#generating-an-access-token}
An access token must only contain friendly URL characters. We recommend using
the following command to create a proper token:
{{< code shell >}}
openssl rand -base64 40 |  tr -- '+=/' '-_~'{{< /code >}}

[1]:  ../../guides/high-availability/#uchiwa-high-availability
[2]:  ../../guides/security/#https-encryption
[3]:  ../../guides/security/#encrypted-passwords
[4]:  ../../api/authentication/


text:
import chai from 'chai';
import spies from 'chai-spies';

chai.use(spies);

import { IBefore, Interactor, IRollback, Organizer } from '../src';
import { Test } from 'mocha';

const expect = chai.expect;

/* tslint:disable:max-classes-per-file */

interface ITest {
  called: boolean;
  count: number;
  rejectOnCount: number;
  rejectMe: boolean;
  error?: Error;
  rejectOn: number;
  beforeCalled: boolean;
  rolledBack: boolean;
  rolledBackCount: number;
  rejectLabels: string[];
}

class TestInteractor extends Interactor<ITest> {
  public call() {
    this.context.called = true;
    this.context.count += 1;
    const rejectOnCount = this.context.rejectOnCount || 1;
    if (this.context.rejectMe && rejectOnCount === this.context.count) {
      this.reject(this.context.error || new Error('You told me to!'));
    } else if (this.context.rejectOn && this.context.rejectOn === this.context.count) {
      this.reject(this.context.error || new Error(`Reject on error count: ${this.context.count}`));
    } else {
      this.resolve();
    }
  }
}

class TestOrganizer extends Organizer<ITest> {
  private orgs: Array<new(context: ITest) => Interactor<ITest>> = [];
  public push(org: new(context: ITest) => Interactor<ITest>) {
    this.orgs.push(org);
  }

  public organize(): Array<new(context: ITest) => Interactor<ITest>> {
    return this.orgs;
  }
}

describe('Organizer', function() {
  let baseContext: ITest = {
    called: false,
    count: 0,
    rejectOnCount: -1,
    rejectMe: false,
    rejectOn: -1,
    beforeCalled: false,
    rolledBack: false,
    rolledBackCount: 0,
    rejectLabels: [],
  };
  beforeEach(() => {
    baseContext = {
      called: false,
      count: 0,
      rejectOnCount: -1,
      rejectMe: false,
      rejectOn: -1,
      beforeCalled: false,
      rolledBack: false,
      rolledBackCount: 0,
      rejectLabels: [],
    };
  });

  describe('organize', function() {
    it('calls organize to get interactors', () => {
      const org = new TestOrganizer(baseContext);
      org.organize = () => [TestInteractor];
      chai.spy.on(org, 'organize');

      return org.exec().then(() => {
        expect(org.organize).to.have.been.called();
      });
    });

    it('defaults to throwing an exception if not implemented', () => {
      const org = new TestOrganizer(baseContext);
      delete org.organize;
      expect(org.organize).to.throw();
    });

    it('rejects if organize throws exception', () => {
      const org = new TestOrganizer(baseContext);

      return org.exec().catch((err: any) => {
        expect(err.message).to.equal('organize must be implemented');
        return null;
      });
    });
  });

  it('single works', function() {
    const org = new TestOrganizer(baseContext);
    org.organize = () => [TestInteractor];
    return org.exec().then((org) => {
      expect(org.context.count).to.equal(1);
    });
  });

  it('multiple works', function() {
    const org = new TestOrganizer(baseContext);
    org.organize = () => [TestInteractor, TestInteractor];
    return org.exec().then((org) => {
      expect(org.context.count).to.equal(2);
    });
  });

  it('multiple does not chain calls on reject', function() {
    baseContext.rejectOn = 2;
    const org = new TestOrganizer(baseContext);
    org.organize = () => [TestInteractor, TestInteractor, TestInteractor];
    return org.exec().catch((error: any) => {
      expect(error.message).to.equal('Reject on error count: 2');
      expect(org.context.count).to.equal(2);
    });
  });

  context('before', () => {
    it('called if defined', (done) => {
      class TestOrgWithBefore extends TestOrganizer implements IBefore {
        public before(): Promise<any> {
          this.context.beforeCalled = true;
          return Promise.resolve();
        }
      }
      const org = new TestOrgWithBefore(baseContext);
      org.organize = () => [TestInteractor];
      chai.spy.on(org, 'before');

      org.exec().then(() => {
        expect(org.context.beforeCalled).to.be.true;
        expect(org.before).to.have.been.called;
        done();
      });
    });

    it('rejects immediately if the before returns a rejected promise', (done) => {
      class TestOrgWithBefore extends TestOrganizer implements IBefore {
        public before(): Promise<any> {
          this.context.beforeCalled = true;
          return Promise.reject(new Error('Taco not included'));
        }
      }
      const org = new TestOrgWithBefore(baseContext);
      org.organize = () => [TestInteractor];
      chai.spy.on(org, 'before');

      org.exec().catch((err) => {
        expect(err.message).to.equal('Taco not included');
        expect(org.context.beforeCalled).to.be.true;
        expect(org.before).to.have.been.called;
      }).then(done);
    });
  });

  context('rollback', () => {

    it('called with rejection err', () => {
      class TestOrgWithRollback extends TestOrganizer implements IRollback {
        public rollback(): Promise<any> {
          this.context.rolledBack = true;
          return Promise.resolve();
        }
      }
      const error = new Error('squirrel!');
      baseContext.rejectMe = true;
      baseContext.error = error;
      const org = new TestOrgWithRollback(baseContext);
      org.push(TestInteractor);
      chai.spy.on(org, 'rollback');
      return org.exec().catch((err) => {
        expect(org.rollback).to.have.been.called.with(error);
        expect(err).to.equal(error);
      });
    });

    it('called if one fails', () => {
      class TestOrgWithRollback extends TestOrganizer implements IRollback {
        public rollback() {
          return Promise.resolve();
        }
      }
      baseContext.rejectMe = true;
      const org = new TestOrgWithRollback(baseContext);
      org.push(TestInteractor);
      chai.spy.on(org, 'rollback');
      return org.exec().catch(() => {
        expect(org.rollback).to.have.been.called();
      });
    });

    it('replaced err of reject with new one', () => {
      class TestOrgWithRollback extends TestOrganizer implements IRollback {
        public rollback(): Promise<any> {
          return new Promise((resolve, reject) => {
            reject(new Error('alternate reject'));
          });
        }
      }
      baseContext.rejectMe = true;
      const org = new TestOrgWithRollback(baseContext);
      org.push(TestInteractor);
      return org.exec().catch((err) => {
        expect(err.message).to.equal('alternate reject');
      });
    });

    it('calls rollback on prior called interactors', () => {
      class TestOrgWithRollback extends TestOrganizer {
      }
      class TestRolllBackInteractor extends TestInteractor implements IRollback {
        public rollback(): Promise<any> {
          this.context.rolledBackCount += 1;
          this.context.rejectLabels.push(`reject-count-${this.context.rolledBackCount}`);
          return Promise.resolve();
        }
      }
      const error = new Error('squirrel!');
      baseContext.rejectOnCount = 2;
      baseContext.rejectMe = true;
      baseContext.error = error;
      const org = new TestOrgWithRollback(baseContext);
      org.push(TestRolllBackInteractor);
      org.push(TestRolllBackInteractor);
      return org.exec().catch(() => {
        expect(org.context.rejectLabels).to.contain('reject-count-1');
        expect(org.context.rejectLabels).to.contain('reject-count-2');
        expect(org.context.rolledBackCount).to.equal(2);
      });
    });
  });
});


text:
package main

import (
	"os"
)

func use(_ string) {}

type passStruct struct {
	password string
}

func (p passStruct) getPassword() string {
	return p.password
}

func (p passStruct) get(key string) string {
	return ""
}

func get(key string) string {
	return ""
}

var (
	password, PassWord, myPasswordInCleartext                                      string
	hashed_password, password_hashed, password_hash, hash_password, hashedPassword string
	secret                                                                         string
)

func main() {
	use(password)
	use(PassWord)
	use(myPasswordInCleartext)

	var p passStruct
	use(p.password)
	p.getPassword()
	p.get("password")
	get("password")

	use(hashed_password)
	use(password_hashed)
	use(password_hash)
	use(hash_password)
	use(hashedPassword)

	os.Exit(0)

	use(secret)
}


text:
[![Build Status](https://travis-ci.org/alephcloud/hs-aws-performance-tests.svg?branch=master)](https://travis-ci.org/alephcloud/hs-aws-performance-tests)

**By using the dynamo-performace application from this package with your AWS API
credentials costs will incure to your AWS account. Depending on the provisioned
test table read and write throughput these costs can be in the order of several
dollars per hour.**

**Also be aware that there is an option to keep the table after the tests are finished
(for example for usage with successive test runs). If you use that option you have to
make sure that you delete the table yourself when you don't need it any more.**

Installation
============

First make sure that you have at least version 1.20 of *Cabal*. You can upgrade
to a recent version via

~~~{.bash}
cabal install Cabal --constraint='cabal>=1.20'
~~~

It is important that you upgrade to a recent *Cabal* version *before* you
run one of the following commands.

For installation from [Hackage](http://hackage.haskell.org/package/aws-performance-tests)
you run:

~~~{.bash}
cabal install aws-performance-tests
~~~

For installation from the [GitHub repository](https://github.com/alephcloud/hs-aws-performance-tests)
can can use the following commands:

~~~{.bash}
git clone https://github.com/alephcloud/hs-aws-performance-tests
cd hs-aws-performance-tests
cabal install
~~~

Charts
------

Optionally the application can be compiled with support for generating charts. For
this you must install *cairo* and *gtk2hs-buildtools*. You also need recent versions
of *alex* and *happy*. On a Linux/Debian system you can install *cairo* as follows:

~~~{.bash}
sudo apt-get install libcairo2
~~~

The Haskell build-tools are installed via:

~~~
cabal install alex happy gtk2hs-buildtools
~~~

You then pass the flag `-fwith-chart` to the the installation commands:

~~~{.bash}
cabal install aws-performance-tests -fwith-chart
~~~

Or when compiling the sources from GitHub:

~~~{.bash}
git clone https://github.com/alephcloud/hs-aws-performance-tests
cd hs-aws-performance-tests
cabal install -fwith-chart
~~~

Usage
=====

After installing the package you'll find the executable `dynamodb-performance` in the
default location where cabal is configured to install binaries.

In order to use the application you must put your AWS API credentials for
your AWS account in the file `~/.aws-keys` as described in the
[Documentation of the aws package](https://github.com/aristidb/aws#example-usage).

For help on available options you may call the executable with `--help`:

~~~{.bash}
dynamodb-performance --help
~~~


text:
import json
import pandas
import matplotlib.pyplot as plt

# store the path to the file we wish to read the data from
tweets_data_path = 'tweet_mining.json'

# create a list to store the data from the json file
results = []

# read the data from the json file line by line and store it in the list
tweets_file = open(tweets_data_path, "r")

# test the code to see if it has been populated
for tweet_line in tweets_file:
    try:
        status = json.loads(tweet_line)
        results.append(status)
    except:
        continue

# print the data
print len(results)

###
# format the results in to columns of data based on:
# Text
# Language (that the tweet was written in)
# Country
###

# create a dataframe
statuses = pandas.DataFrame()

# store the text values
statuses['text'] = map(lambda status: status['text'], results)

# store the language values
statuses['lang'] = map(lambda status: status['lang'], results)

# sometimes there may not be a 'place' listed in the tweet,
# so set 'None' if not present
statuses['country'] = map(lambda status: status['place']['country'] if status['place'] != None else None, results)

# get each tweet language and the count of its appearance (not to be confused with programming languages)
tweets_by_lang = statuses['lang'].value_counts()

# create our drawing space/window (figure)
fig = plt.figure()

# add a plot area for our data on the figure - 1,1,1 means a single chart/graph
ax = fig.add_subplot(1,1,1)

#style the axes and labels of our plot
ax.tick_params(axis='x', labelsize=15)
ax.tick_params(axis='y', labelsize=10)
ax.set_xlabel('Tweet Languages', fontsize=15)
ax.set_ylabel('Num of Tweets' , fontsize=15)
ax.xaxis.label.set_color('#666666')
ax.yaxis.label.set_color('#666666')
ax.tick_params(axis='x', colors='#666666')
ax.tick_params(axis='y', colors='#666666')

#style the title
ax.set_title('Top 10 languages', fontsize=15, color='#666666')

# plot the top 10 tweet languages and appearance count using a bar chart
tweets_by_lang[:10].plot(ax=ax, kind='bar', color='#FF7A00')

# color the spines (borders)
for spine in ax.spines.values():
        spine.set_edgecolor('#666666')

# render the graph
plt.show()


text:
using namespace std;

BOOL EnumDeviceInterface(const GUID * InterfaceClassGUID){
	HDEVINFO DeviceInfoSet;
	HDEVINFO NewDeviceInfoSet;
	SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
	PSP_DEVICE_INTERFACE_DETAIL_DATA lpDeviceInterfaceDetailData;
	DWORD dwBufferSize = 0;
	DWORD i;

	DeviceInfoSet = SetupDiCreateDeviceInfoList(NULL,NULL);
	if(DeviceInfoSet == INVALID_HANDLE_VALUE){
		printf("Create device interface failed.(%d)\n",GetLastError());
		return 0;
	}
	NewDeviceInfoSet = SetupDiGetClassDevsEx(InterfaceClassGUID,NULL,NULL,DIGCF_DEVICEINTERFACE|DIGCF_PRESENT,DeviceInfoSet,NULL,NULL);
	if(NewDeviceInfoSet == INVALID_HANDLE_VALUE){
		printf("Get device interface infomation failed.");
		return 0;
	}
	DeviceInterfaceData.cbSize = sizeof(DeviceInterfaceData);
	for(i=0;;i++){
		BOOL bResult = SetupDiEnumDeviceInterfaces(NewDeviceInfoSet,NULL,InterfaceClassGUID,i,&DeviceInterfaceData);
		if(!bResult){
			if(bResult != NO_ERROR && GetLastError()!=ERROR_NO_MORE_ITEMS){
				printf("ERROR:%d\n",GetLastError());
				return FALSE;
			}
			break;
		}else{
			SetupDiGetDeviceInterfaceDetail(NewDeviceInfoSet, &DeviceInterfaceData, NULL, NULL, &dwBufferSize, NULL);
			if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
			{
				printf("Error:%d\n", GetLastError());
			}

			lpDeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)HeapAlloc(GetProcessHeap(), 0, sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + dwBufferSize);
			lpDeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

			if (!SetupDiGetDeviceInterfaceDetail(NewDeviceInfoSet, &DeviceInterfaceData, lpDeviceInterfaceDetailData, dwBufferSize, &dwBufferSize, NULL)){
				printf("Error:%d\n", GetLastError());
			}
			printf("DevicePath:%S\n",lpDeviceInterfaceDetailData->DevicePath);
			//wcout.imbue(locale("chs"));
			//wcout << L"DevicePath:" << lpDeviceInterfaceDetailData->DevicePath << endl;
			HeapFree(GetProcessHeap(),0,lpDeviceInterfaceDetailData);
		}
	}
	return TRUE;
}

int main(){
	printf("Get device interface information.\n");
	EnumDeviceInterface(&GUID_DEVINTERFACE_VOLUME);
	system("pause");
	return 0;
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using ImpromptuInterface;
using ImpromptuInterface.Dynamic;

#if !SELFRUNNER
using DynObj = Dynamitey.DynamicObjects;

using NUnit.Framework;
#endif

#if SILVERLIGHT
namespace UnitTestImpromptuInterface.Silverlight
#else
namespace UnitTestImpromptuInterface
#endif
{
    [TestFixture]
    public class ImpromptuDynamic : Helper
    {

        [Test]
        public void DictionaryPropertyTest()
        {

            dynamic tNew = new ImpromptuDictionary();
            tNew.Prop1 = "Test";
            tNew.Prop2 = 42L;
            tNew.Prop3 = Guid.NewGuid();

            var tActsLike = Impromptu.ActLike<ISimpeleClassProps>(tNew);

            Assert.AreEqual(tNew.Prop1, tActsLike.Prop1);
            Assert.AreEqual(tNew.Prop2, tActsLike.Prop2);
            Assert.AreEqual(tNew.Prop3, tActsLike.Prop3);
        }

        [Test]
        public void DictionaryNullPropertyTest()
        {

            dynamic tNew = new ImpromptuDictionary();

            ISimpeleClassProps tActsLike = Impromptu.ActLike<ISimpeleClassProps>(tNew);

            Assert.AreEqual(default(string), tActsLike.Prop1);
            Assert.AreEqual(default(long), tActsLike.Prop2);
            Assert.AreEqual(default(Guid), tActsLike.Prop3);
        }

        [Test]
        public void GetterAnonTest()
        {
            var tAnon = new { Prop1 = "Test", Prop2 = 42L, Prop3 = Guid.NewGuid() };

            dynamic tTest =new ImpromptuGet(tAnon);

            Assert.AreEqual(tAnon.Prop1, tTest.Prop1);
            Assert.AreEqual(tAnon.Prop2, tTest.Prop2);
            Assert.AreEqual(tAnon.Prop3, tTest.Prop3);
        }

        [Test]
        public void GetterVoidTest()
        {
            var tPoco = new VoidMethodPoco();

            dynamic tTest = new ImpromptuGet(tPoco);

            tTest.Action();
        }

        [Test]
        public void GetterArrayTest()
        {

            var tArray = new int[]{1,2,3};

            IStringIntIndexer tTest =  ImpromptuGet.Create<IStringIntIndexer>(tArray);

            Assert.AreEqual(tArray[2].ToString(), tTest[2]);
        }

        [Test]
        public void GetterEventTest()
        {
            var tActsLike = ImpromptuGet.Create<IEvent>(new PocoEvent());
            var tSet = false;
            tActsLike.Event += (obj, args) => tSet = true;

            tActsLike.OnEvent(null, null);
            Assert.AreEqual(true, tSet);

        }

        [Test]
        public void GetterEventTest2()
        {
            var tActsLike = ImpromptuGet.Create<IEvent>(new PocoEvent());
            var tSet = false;
            EventHandler<EventArgs> tActsLikeOnEvent = (obj, args) => tSet = true;
            tActsLike.Event += tActsLikeOnEvent;
            tActsLike.Event -= tActsLikeOnEvent;
            tActsLike.OnEvent(null, null);
            Assert.AreEqual(false, tSet);

        }

        [Test]
        public void GetterDynamicTest()
        {
            dynamic tNew = new ExpandoObject();
            tNew.Prop1 = "Test";
            tNew.Prop2 = 42L;
            tNew.Prop3 = Guid.NewGuid();

            dynamic tTest = new ImpromptuGet(tNew);

            Assert.AreEqual(tNew.Prop1, tTest.Prop1);
            Assert.AreEqual(tNew.Prop2, tTest.Prop2);
            Assert.AreEqual(tNew.Prop3, tTest.Prop3);
        }

        [Test]
        public void ForwardAnonTest()
        {
            var tAnon = new { Prop1 = "Test", Prop2 = 42L, Prop3 = Guid.NewGuid() };

            dynamic tTest = new TestForwarder(tAnon);

            Assert.AreEqual(tAnon.Prop1, tTest.Prop1);
            Assert.AreEqual(tAnon.Prop2, tTest.Prop2);
            Assert.AreEqual(tAnon.Prop3, tTest.Prop3);
        }

        [Test]
        public void ForwardVoidTest()
        {
            var tPoco = new VoidMethodPoco();

            dynamic tTest = new TestForwarder(tPoco);

            tTest.Action();
        }

        [Test]
        public void ForwardDynamicTest()
        {
            dynamic tNew = new ExpandoObject();
            tNew.Prop1 = "Test";
            tNew.Prop2 = 42L;
            tNew.Prop3 = Guid.NewGuid();

            dynamic tTest = new TestForwarder(tNew);

            Assert.AreEqual(tNew.Prop1, tTest.Prop1);
            Assert.AreEqual(tNew.Prop2, tTest.Prop2);
            Assert.AreEqual(tNew.Prop3, tTest.Prop3);
        }

        [Test]
        public void DictionaryMethodsTest()
        {

            dynamic tNew = new ImpromptuDictionary();
            tNew.Action1 = new Action(Assert.Fail);
            tNew.Action2 = new Action<bool>(Assert.IsFalse);
            tNew.Action3 = new Func<string>(() => "test");
            tNew.Action4 = new Func<int, string>(arg => "test" + arg);

            ISimpeleClassMeth2 tActsLike = Impromptu.ActLike<ISimpeleClassMeth2>(tNew);

            AssertException<AssertionException>(tActsLike.Action1);
            AssertException<AssertionException>(() => tActsLike.Action2(true));

            Assert.AreEqual("test", tActsLike.Action3());

            Assert.AreEqual("test4", tActsLike.Action4(4));
        }

        [Test]
        public void ForwardMethodsTest()
        {

            dynamic tNew = new ImpromptuDictionary();
            tNew.Action1 = new Action(Assert.Fail);
            tNew.Action2 = new Action<bool>(Assert.IsFalse);
            tNew.Action3 = new Func<string>(() => "test");
            tNew.Action4 = new Func<int, string>(arg => "test" + arg);

            dynamic tFwd = new TestForwarder(tNew);

            AssertException<AssertionException>(()=> tFwd.Action1());
            AssertException<AssertionException>(() => tFwd.Action2(true));

            Assert.AreEqual("test", tFwd.Action3());

            Assert.AreEqual("test4", tFwd.Action4(4));
        }

        [Test]
        public void DictionaryMethodsOutTest()
        {

            dynamic tNew = new ImpromptuDictionary();
            tNew.Func = new DynamicTryString(TestOut);

            String tOut;

            Assert.AreEqual(true, tNew.Func(null, "Test", out tOut));
            Assert.AreEqual("Test", tOut);

            String tOut2;
            Assert.AreEqual(false, tNew.Func(null, 1, out tOut2));
            Assert.AreEqual(null, tOut2);
        }

        private static object TestOut(CallSite dummy, object @in, out string @out)
        {
            @out = @in as string;

            return @out != null;
        }

        [Test]
        public void DictionaryMethodsTestWithPropertyAccess()
        {

            dynamic tNew = new ImpromptuDictionary();
            tNew.PropCat = "Cat-";
            tNew.Action1 = new Action(Assert.Fail);
            tNew.Action2 = new Action<bool>(Assert.IsFalse);
            tNew.Action3 = new ThisFunc<string>(@this => @this.PropCat + "test");

            ISimpeleClassMeth tActsLike = Impromptu.ActLike<ISimpeleClassMeth>(tNew);

            AssertException<AssertionException>(tActsLike.Action1);
            AssertException<AssertionException>(() => tActsLike.Action2(true));

            Assert.AreEqual("Cat-test", tActsLike.Action3());

        }

        [Test]
        public void DictionaryNullMethodsTest()
        {

            dynamic tNew = new ImpromptuDictionary();

            ISimpleStringMethod tActsLike = Impromptu.ActLike<ISimpleStringMethod>(tNew);

            Assert.AreEqual(false, tActsLike.StartsWith("Te"));

        }
        #if !SELFRUNNER
        [Test]
        public void DynamiteyDictionaryNullMethodsTest()
        {

            dynamic tNew = new DynObj.Dictionary();

            ISimpleStringMethod tActsLike = Impromptu.ActLike<ISimpleStringMethod>(tNew);

            Assert.AreEqual(false, tActsLike.StartsWith("Te"));

        }
    #endif

        [Test]
        public void DynamicDictionaryWrappedTest()
        {

            var tDictionary = new Dictionary<string, object>
                                  {
                                      {"Test1", 1},
                                      {"Test2", 2},
                                      {"TestD",  new Dictionary<string,object>()
                                                     {
                                                         {"TestA","A"},
                                                         {"TestB","B"}
                                                     }
                                      }
                                  };

            dynamic tNew = new ImpromptuDictionary(tDictionary);

            Assert.AreEqual(1, tNew.Test1);
            Assert.AreEqual(2, tNew.Test2);
            Assert.AreEqual("A", tNew.TestD.TestA);
            Assert.AreEqual("B", tNew.TestD.TestB);
        }

        [Test]
        public void InterfaceDictionaryWrappedTest()
        {

            var tDictionary = new Dictionary<string, object>
                                  {
                                      {"Test1", 1},
                                      {"Test2", 2L},
                                      {"Test3",1},
                                      {"Test4","Two"},
                                      {"TestD",  new Dictionary<string,object>()
                                                     {
                                                         {"TestA","A"},
                                                         {"TestB","B"}
                                                     }
                                      }
                                  };

            dynamic tDynamic = ImpromptuDictionary.Create<IDynamicDict>(tDictionary);
            dynamic tNotDynamic = ImpromptuDictionary.Create<INonDynamicDict>(tDictionary);

            Assert.AreEqual(tDynamic, tNotDynamic);

            Assert.AreEqual(1, tDynamic.Test1);
            Assert.AreEqual(2L, tDynamic.Test2);
            Assert.AreEqual(TestEnum.One, tDynamic.Test3);
            Assert.AreEqual(TestEnum.Two, tDynamic.Test4);

            Assert.AreEqual("A", tDynamic.TestD.TestA);
            Assert.AreEqual("B", tDynamic.TestD.TestB);

            Assert.AreEqual(1, tNotDynamic.Test1);
            Assert.AreEqual(2L, tNotDynamic.Test2);
            Assert.AreEqual(TestEnum.One, tNotDynamic.Test3);
            Assert.AreEqual(TestEnum.Two, tNotDynamic.Test4);

            Assert.AreEqual(typeof(Dictionary<string, object>), tNotDynamic.TestD.GetType());
            Assert.AreEqual(typeof(ImpromptuDictionary), tDynamic.TestD.GetType());
        }

        [Test]
        public void DynamicObjectEqualsTest()
        {
            var tDictionary = new Dictionary<string, object>
                                  {
                                      {"Test1", 1},
                                      {"Test2", 2},
                                      {"TestD",  new Dictionary<string,object>()
                                                     {
                                                         {"TestA","A"},
                                                         {"TestB","B"}
                                                     }
                                      }
                                  };

            dynamic tDynamic = ImpromptuDictionary.Create<IDynamicDict>(tDictionary);
            dynamic tNotDynamic = ImpromptuDictionary.Create<INonDynamicDict>(tDictionary);

            Assert.AreEqual(tDynamic, tNotDynamic);

            Assert.AreEqual(tDynamic, tDictionary);

            Assert.AreEqual(tNotDynamic, tDictionary);
        }

        [Test]
        public void DynamicAnnonymousWrapper()
        {
            var tData = new Dictionary<int, string> {{1, "test"}};
            var tDyn = ImpromptuGet.Create(new
                                               {
                                                   Test1 = 1,
                                                   Test2 = "2",
                                                   IsGreaterThan5 = Return<bool>.Arguments<int>(it => it > 5),
                                                   ClearData = ReturnVoid.Arguments(() => tData.Clear())
                                               });

            Assert.AreEqual(1,tDyn.Test1);
            Assert.AreEqual("2", tDyn.Test2);
            Assert.AreEqual(true, tDyn.IsGreaterThan5(6));
            Assert.AreEqual(false, tDyn.IsGreaterThan5(4));

            Assert.AreEqual(1, tData.Count);
            tDyn.ClearData();
            Assert.AreEqual(0, tData.Count);

        }

        [Test]
        public void TestAnonInterface()
        {
            var tInterface = ImpromptuGet.Create<ICollection>(new
                                                                  {
                                                                     CopyArray = ReturnVoid.Arguments<Array,int>((ar,i) => Enumerable.Range(1,10)),
                                                                     Count =  10,
                                                                     IsSynchronized = false,
                                                                     SyncRoot = this,
                                                                     GetEnumerator = Return<IEnumerator>.Arguments(()=>Enumerable.Range(1, 10).GetEnumerator())
                                                                  });

            Assert.AreEqual(10, tInterface.Count);
            Assert.AreEqual(false, tInterface.IsSynchronized);
            Assert.AreEqual(this, tInterface.SyncRoot);
            Assert.AreEqual(true,tInterface.GetEnumerator().MoveNext());
        }

		[Test]
		public void TestBuilder(){
			var New = Builder.New<ExpandoObject>();

			  var tExpando =New.Object(
										Test:"test1",
										Test2:"Test 2nd"
									);
		   Assert.AreEqual("test1",tExpando.Test );
		   Assert.AreEqual("Test 2nd",tExpando.Test2);

		    dynamic NewD = new ImpromptuBuilder<ExpandoObject>();

			var tExpandoNamedTest =NewD.Robot(
				LeftArm:"Rise",
				RightArm:"Clamp"
				);

			 Assert.AreEqual("Rise",tExpandoNamedTest.LeftArm);
		  	 Assert.AreEqual("Clamp",tExpandoNamedTest.RightArm);
		}

		[Test]
		public void TestSetupOtherTypes(){
			var New = Builder.New().Setup(
					Expando: typeof(ExpandoObject),
					Dict: typeof(ImpromptuDictionary)
				);

			var tExpando =New.Expando(
				LeftArm:"Rise",
				RightArm:"Clamp"
				);

			var tDict =New.Dict(
				LeftArm:"RiseD",
				RightArm:"ClampD"
				);

			 Assert.AreEqual("Rise",tExpando.LeftArm);
		  	 Assert.AreEqual("Clamp",tExpando.RightArm);
			Assert.AreEqual(typeof(ExpandoObject),tExpando.GetType());

			 Assert.AreEqual("RiseD",tDict.LeftArm);
			 Assert.AreEqual("ClampD",tDict.RightArm);
			Assert.AreEqual(typeof(ImpromptuDictionary),tDict.GetType());

		}

		[Test]

        //This test data is modified from MS-PL Clay project http://clay.codeplex.com
        public void TestClayFactorySyntax()
        {
            dynamic New = Builder.New();

            {
                var person = New.Person();
                person.FirstName = "Louis";
                person.LastName = "Dejardin";
                Assert.AreEqual("Louis",person.FirstName );
                Assert.AreEqual("Dejardin", person.LastName);
            }
            {
                var person = New.Person();
                person["FirstName"] = "Louis";
                person["LastName"] = "Dejardin";
                Assert.AreEqual("Louis", person.FirstName);
                Assert.AreEqual("Dejardin", person.LastName);
            }
            {
                var person = New.Person(
                    FirstName: "Bertrand",
                    LastName: "Le Roy"
                    ).Aliases("bleroy", "boudin");

                Assert.AreEqual("Bertrand", person.FirstName);
                Assert.AreEqual("Le Roy", person.LastName);
                Assert.AreEqual("boudin", person.Aliases[1]);
            }

            {
                var person = New.Person()
                    .FirstName("Louis")
                    .LastName("Dejardin")
                    .Aliases(new[] {"Lou"});

                Assert.AreEqual(person.FirstName, "Louis");
                Assert.AreEqual(person.Aliases[0], "Lou");
            }

            {
                var person = New.Person(new
                {
                    FirstName = "Louis",
                    LastName = "Dejardin"
                });
                Assert.AreEqual(person.FirstName, "Louis");
                Assert.AreEqual(person.LastName, "Dejardin");
            }

        }

		[Test]
		public void TestBuilderActLikeAnon()
		{
		    var New = Builder.New().ActLike<IBuilder>();

		var tNest =New.Nester(new {
				NameLevel1 = "Lvl1",
				Nested =  New.Nester2(new{
					NameLevel2 = "Lvl2"
				})
			});

			Assert.AreEqual("Lvl1", tNest.NameLevel1);
			Assert.AreEqual("Lvl2",tNest.Nested.NameLevel2);
	    }

        [Test]
        public void TestBuilderActLikeNamed()
        {
            var New = Builder.New().ActLike<IBuilder>();

            var tNest = New.Nester(
                NameLevel1 :"Lvl1",
                Nested : New.Nester2(
                            NameLevel2 : "Lvl2"
                        )
            );

            Assert.AreEqual("Lvl1", tNest.NameLevel1);
            Assert.AreEqual("Lvl2", tNest.Nested.NameLevel2);
        }

			[Test]
        //This test data is modified from MS-PL Clay project http://clay.codeplex.com
		public void TestFactoryListSyntax(){
			dynamic New = Builder.New();

			//Test using Clay Syntax
			var people = New.Array(
    						 New.Person().FirstName("Louis").LastName("Dejardin"),
   							 New.Person().FirstName("Bertrand").LastName("Le Roy")
						 );

			Assert.AreEqual("Dejardin",people[0].LastName);
		  	Assert.AreEqual("Le Roy",people[1].LastName);

			var people2 =  new ImpromptuList(){
							New.Robot(Name:"Bender"),
							New.Robot(Name:"RobotDevil")
						   };

			Assert.AreEqual("Bender", people2[0].Name);
		  	Assert.AreEqual("RobotDevil",people2[1].Name);

		}

        [Test]
            public void TestQuicListSyntax()
            {
                var tList =Build.NewList("test", "one", "two");
                Assert.AreEqual("one", tList[1]);

                var tList2 = Build.NewList("test", "one", "two", "three");
                Assert.AreEqual("three", tList2[3]);
            }

        [Test]
        public void TestLateLibrarybind()
        {

            dynamic tBigIntType = new ImpromptuLateLibraryType("System.Numerics.BigInteger, System.Numerics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

            if (tBigIntType.IsAvailable)
            {

                var one = tBigIntType.@new(1);
                var two = tBigIntType.@new(2);

                Assert.IsFalse(one.IsEven);
                Assert.AreEqual(true, two.IsEven);

                var tParsed =tBigIntType.Parse("4");

                Assert.AreEqual(true, tParsed.IsEven);

            }
            else
            {
#if !SILVERLIGHT
                Assert.Fail("Big Int Didn't Load");
#endif

            }
        }

    }
}


text:
package iht.controllers.application.assets.trusts

import iht.config.AppConfig
import iht.controllers.application.ApplicationControllerTest
import iht.testhelpers.CommonBuilder
import iht.views.html.application.asset.trusts.trusts_overview
import play.api.mvc.MessagesControllerComponents
import play.api.test.Helpers._
import uk.gov.hmrc.play.bootstrap.frontend.controller.FrontendController

/**
 * Created by jennygj on 30/06/16.
 */
class TrustsOverviewControllerTest extends ApplicationControllerTest {

  protected abstract class TestController extends FrontendController(mockControllerComponents) with TrustsOverviewController {
    override val cc: MessagesControllerComponents = mockControllerComponents
    override implicit val appConfig: AppConfig = mockAppConfig
    override val trustsOverviewView: trusts_overview = app.injector.instanceOf[trusts_overview]
  }

  "TrustsOverviewControllerTest" must {

    def trustsOverviewController = new TestController  {
      override val authConnector = mockAuthConnector
      override val cachingConnector = mockCachingConnector
      override val ihtConnector = mockIhtConnector
    }

    def trustsOverviewControllerNotAuthorised = new TestController  {
      override val authConnector = mockAuthConnector
      override val cachingConnector = mockCachingConnector
      override val ihtConnector = mockIhtConnector
    }

    "respond with OK on page load" in {
      val applicationDetails = CommonBuilder.buildApplicationDetails

      createMocksForApplication(mockCachingConnector,
        mockIhtConnector,
        appDetails = Some(applicationDetails),
        getAppDetails = true,
        saveAppDetails= true,
        storeAppDetailsInCache = true)

      val result = trustsOverviewController.onPageLoad(createFakeRequest())
      status(result) mustBe (OK)
    }

    "redirect to login page on PageLoad if the user is not logged in" in {
      val applicationDetails = CommonBuilder.buildApplicationDetails

      createMocksForApplication(mockCachingConnector,
        mockIhtConnector,
        appDetails = Some(applicationDetails),
        getAppDetails = true,
        saveAppDetails= true,
        storeAppDetailsInCache = true)

      val result = trustsOverviewControllerNotAuthorised.onPageLoad(createFakeRequest(false))
      status(result) must be(SEE_OTHER)
      redirectLocation(result) must be (Some(loginUrl))
    }

    "display the correct content title" in {
      val applicationDetails = CommonBuilder.buildApplicationDetails
      createMocksForApplication(mockCachingConnector,
        mockIhtConnector,
        appDetails = Some(applicationDetails),
        getAppDetails = true,
        saveAppDetails= true,
        storeAppDetailsInCache = true)

      val result = trustsOverviewController.onPageLoad(createFakeRequest())
      status(result) mustBe (OK)
      contentAsString(result) must include(messagesApi("iht.estateReport.assets.heldInTrust.title"))
    }

    behave like controllerOnPageLoadWithNoExistingRegistrationDetails(mockCachingConnector,
      trustsOverviewController.onPageLoad(createFakeRequest()))
  }
}


text:
layout: page
title: Gibbs Forest Company Conference
date: 2016-05-24
author: Timothy Mendez
tags: weekly links, java
status: published
summary: Aliquam erat volutpat. Cras quis pharetra nisl, ut dapibus velit.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 04/12/2018
  endDate: 04/14/2018
  ctyhocn: ATSJJHX
  groupCode: GFCC
published: true
---
Nam nec laoreet est. Nunc sed ligula euismod, convallis quam ac, dictum leo. Duis nulla massa, consectetur dapibus fringilla ultricies, condimentum quis justo. Aenean elementum finibus tempor. Nullam luctus nulla massa, at facilisis dolor accumsan a. Phasellus vel ligula fermentum, consequat justo nec, posuere justo. Sed augue dui, ornare eget pellentesque ac, interdum non leo. Cras arcu nibh, ornare eget nisl nec, faucibus lacinia sapien. Donec eget sem quis ante pharetra maximus. Curabitur in leo ac sapien vulputate lobortis. Duis volutpat nisi est, sed vehicula magna sodales sit amet. Morbi ultricies lorem felis, vel laoreet nunc dapibus id. Vestibulum dignissim purus nulla. Cras ornare a metus sit amet pellentesque. Quisque ante risus, porta vitae mollis nec, mattis sed magna.

1 Integer in turpis vel purus dapibus efficitur
1 Morbi rutrum nulla at nulla elementum, sed egestas purus faucibus.

Nulla facilisi. Mauris feugiat, ipsum vel tempor interdum, nibh arcu pulvinar tortor, sed tincidunt lectus dui eu mauris. Duis enim urna, commodo facilisis dui id, pellentesque mollis purus. Proin convallis fermentum metus, nec molestie diam tincidunt nec. Sed rutrum tortor odio. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.


text:
					    综合等级

						平均成绩

						系统排名

Congraulations

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab totam voluptas animi eius ducimus molestiae aspernatur ratione sed! Quidem, dolor, soluta iure eveniet porro praesentium possimus perspiciatis architecto expedita suscipit.

			<button type="button" class="btn btn-danger">成绩分析</button>

规则说明

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab totam voluptas animi eius ducimus molestiae aspernatur ratione sed! Quidem, dolor, soluta iure eveniet porro praesentium possimus perspiciatis architecto expedita suscipit.


text:
package net.sf.jasperreports.charts.base;

import net.sf.jasperreports.charts.JRXyzDataset;
import net.sf.jasperreports.charts.JRXyzSeries;
import net.sf.jasperreports.engine.JRChartDataset;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.engine.JRExpressionCollector;
import net.sf.jasperreports.engine.base.JRBaseChartDataset;
import net.sf.jasperreports.engine.base.JRBaseObjectFactory;
import net.sf.jasperreports.engine.design.JRVerifier;
import net.sf.jasperreports.engine.util.JRCloneUtils;

/**
 * @author Flavius Sana (flavius_sana@users.sourceforge.net)
 * @version $Id: JRBaseXyzDataset.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class JRBaseXyzDataset extends JRBaseChartDataset implements JRXyzDataset {

	public static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;

	protected JRXyzSeries[] xyzSeries;

	public JRBaseXyzDataset( JRChartDataset dataset){
		super( dataset);
	}

	public JRBaseXyzDataset( JRXyzDataset dataset, JRBaseObjectFactory factory ){
		super( dataset, factory );

		JRXyzSeries[] srcXyzSeries = dataset.getSeries();

		if( srcXyzSeries != null && srcXyzSeries.length > 0 ){

			xyzSeries = new JRXyzSeries[ srcXyzSeries.length ];
			for( int i = 0; i < srcXyzSeries.length; i++ ){
				xyzSeries[i] = factory.getXyzSeries( srcXyzSeries[i] );
			}
		}
	}

	public JRXyzSeries[] getSeries(){
		return xyzSeries;
	}

	/**
	 *
	 */
	public byte getDatasetType() {
		return JRChartDataset.XYZ_DATASET;
	}

	/**
	 *
	 */
	public void collectExpressions(JRExpressionCollector collector)
	{
		collector.collect(this);
	}

	public void validate(JRVerifier verifier)
	{
		verifier.verify(this);
	}

	/**
	 *
	 */
	public Object clone()
	{
		JRBaseXyzDataset clone = (JRBaseXyzDataset)super.clone();
		clone.xyzSeries = JRCloneUtils.cloneArray(xyzSeries);
		return clone;
	}
}