text:
	#include "c_sdk_player.h"

#else

	#include "sdk_player.h"

#endif

// ----------------------------------------------------------------------------- //
// CWeaponSDKBase tables.
// ----------------------------------------------------------------------------- //

IMPLEMENT_NETWORKCLASS_ALIASED( WeaponSDKBase, DT_WeaponSDKBase )

BEGIN_NETWORK_TABLE( CWeaponSDKBase, DT_WeaponSDKBase )
#ifdef CLIENT_DLL
  	RecvPropFloat( RECVINFO( m_flDecreaseShotsFired ) ),
#else
	SendPropExclude( "DT_BaseAnimating", "m_nNewSequenceParity" ),
	SendPropExclude( "DT_BaseAnimating", "m_nResetEventsParity" ),
	SendPropFloat( SENDINFO( m_flDecreaseShotsFired ) ),
#endif
END_NETWORK_TABLE()

#ifdef CLIENT_DLL
BEGIN_PREDICTION_DATA( CWeaponSDKBase )
	DEFINE_PRED_FIELD( m_flTimeWeaponIdle, FIELD_FLOAT, FTYPEDESC_OVERRIDE | FTYPEDESC_NOERRORCHECK ),
END_PREDICTION_DATA()
#endif

LINK_ENTITY_TO_CLASS( weapon_sdk_base, CWeaponSDKBase );

#ifdef GAME_DLL

	BEGIN_DATADESC( CWeaponSDKBase )

		// New weapon Think and Touch Functions go here..

	END_DATADESC()

#endif

#ifdef CLIENT_DLL
bool CWeaponSDKBase::ShouldPredict()
{
       if ( GetOwner() && GetOwner() == C_BasePlayer::GetLocalPlayer())
               return true;

       return BaseClass::ShouldPredict();
}
#endif
// ----------------------------------------------------------------------------- //
// CWeaponCSBase implementation.
// ----------------------------------------------------------------------------- //
CWeaponSDKBase::CWeaponSDKBase()
{
	SetPredictionEligible( true );

	AddSolidFlags( FSOLID_TRIGGER ); // Nothing collides with these but it gets touches.
}

const CSDKWeaponInfo &CWeaponSDKBase::GetSDKWpnData() const
{
	const FileWeaponInfo_t *pWeaponInfo = &GetWpnData();
	const CSDKWeaponInfo *pSDKInfo;

	#ifdef _DEBUG
		pSDKInfo = dynamic_cast< const CSDKWeaponInfo* >( pWeaponInfo );
		Assert( pSDKInfo );
	#else
		pSDKInfo = static_cast< const CSDKWeaponInfo* >( pWeaponInfo );
	#endif

	return *pSDKInfo;
}

bool CWeaponSDKBase::PlayEmptySound()
{
	CPASAttenuationFilter filter( this );
	filter.UsePredictionRules();

	EmitSound( filter, entindex(), "Default.ClipEmpty_Rifle" );

	return 0;
}

CSDKPlayer* CWeaponSDKBase::GetPlayerOwner() const
{
	return dynamic_cast< CSDKPlayer* >( GetOwner() );
}

#ifdef CLIENT_DLL
void UTIL_ClipPunchAngleOffset( QAngle &in, const QAngle &punch, const QAngle &clip )
{
	QAngle	final = in + punch;

	//Clip each component
	for ( int i = 0; i < 3; i++ )
	{
		if ( final[i] > clip[i] )
		{
			final[i] = clip[i];
		}
		else if ( final[i] < -clip[i] )
		{
			final[i] = -clip[i];
		}

		//Return the result
		in[i] = final[i] - punch[i];
	}
}
#endif

//Tony; added as a default primary attack if it doesn't get overridden, ie: by CSDKWeaponMelee
void CWeaponSDKBase::PrimaryAttack( void )
{
	// If my clip is empty (and I use clips) start reload
	if ( UsesClipsForAmmo1() && !m_iClip1 )
	{
		Reload();
		return;
	}

	CSDKPlayer *pPlayer = GetPlayerOwner();

	if (!pPlayer)
		return;

	//Tony; check firemodes --
	switch(GetFireMode())
	{
	case FM_SEMIAUTOMATIC:
		if (pPlayer->GetShotsFired() > 0)
			return;
		break;
		//Tony; added an accessor to determine the max burst on a per-weapon basis.
	case FM_BURST:
		if (pPlayer->GetShotsFired() > MaxBurstShots())
			return;
		break;
	}
#ifdef GAME_DLL
	pPlayer->NoteWeaponFired();
#endif

	pPlayer->DoMuzzleFlash();

	SendWeaponAnim( GetPrimaryAttackActivity() );

	// Make sure we don't fire more than the amount in the clip
	if ( UsesClipsForAmmo1() )
		m_iClip1 --;
	else
		pPlayer->RemoveAmmo(1, m_iPrimaryAmmoType );

	pPlayer->IncreaseShotsFired();

	float flSpread = GetWeaponSpread();

	FX_FireBullets(
		pPlayer->entindex(),
		pPlayer->Weapon_ShootPosition(),
		pPlayer->EyeAngles() + pPlayer->GetPunchAngle(),
		GetWeaponID(),
		0, //Tony; fire mode - this is unused at the moment, left over from CSS when SDK* was created in the first place.
		CBaseEntity::GetPredictionRandomSeed() & 255,
		flSpread
		);

	//Add our view kick in
	AddViewKick();

	//Tony; update our weapon idle time
	SetWeaponIdleTime( gpGlobals->curtime + SequenceDuration() );

	m_flNextPrimaryAttack = gpGlobals->curtime + GetFireRate();
	m_flNextSecondaryAttack = gpGlobals->curtime + SequenceDuration();
}

void CWeaponSDKBase::SecondaryAttack()
{
}

//Tony; added so we can have base functionality without implementing it into every weapon.
void CWeaponSDKBase::ItemPostFrame( void )
{
	CSDKPlayer *pPlayer = GetPlayerOwner();
	if ( !pPlayer )
		return;

	//
	//Tony; totally override the baseclass
	//

	if ( UsesClipsForAmmo1() )
		CheckReload();

	bool bFired = false;

	// Secondary attack has priority
	if ((pPlayer->m_nButtons & IN_ATTACK2) && (m_flNextSecondaryAttack <= gpGlobals->curtime) && pPlayer->CanAttack())
	{
		if (UsesSecondaryAmmo() && pPlayer->GetAmmoCount(m_iSecondaryAmmoType)<=0 )
		{
			if (m_flNextEmptySoundTime < gpGlobals->curtime)
			{
				WeaponSound(EMPTY);
				m_flNextSecondaryAttack = m_flNextEmptySoundTime = gpGlobals->curtime + 0.5;
			}
		}
		else if (pPlayer->GetWaterLevel() == 3 && m_bAltFiresUnderwater == false)
		{
			// This weapon doesn't fire underwater
			WeaponSound(EMPTY);
			m_flNextPrimaryAttack = gpGlobals->curtime + 0.2;
		}
		else
		{
			bFired = true;
			SecondaryAttack();

			// Secondary ammo doesn't have a reload animation
			if ( UsesClipsForAmmo2() )
			{
				// reload clip2 if empty
				if (m_iClip2 < 1)
				{
					pPlayer->RemoveAmmo( 1, m_iSecondaryAmmoType );
					m_iClip2 = m_iClip2 + 1;
				}
			}
		}
	}

	if ( !bFired && (pPlayer->m_nButtons & IN_ATTACK) && (m_flNextPrimaryAttack <= gpGlobals->curtime) && pPlayer->CanAttack())
	{
		// Clip empty? Or out of ammo on a no-clip weapon?
		if ( !IsMeleeWeapon() && (( UsesClipsForAmmo1() && m_iClip1 <= 0) || ( !UsesClipsForAmmo1() && pPlayer->GetAmmoCount(m_iPrimaryAmmoType)<=0 )) )
		{
			HandleFireOnEmpty();
		}
		else if (pPlayer->GetWaterLevel() == 3 && m_bFiresUnderwater == false)
		{
			// This weapon doesn't fire underwater
			WeaponSound(EMPTY);
			m_flNextPrimaryAttack = gpGlobals->curtime + 0.2;
		}
		else
		{
			PrimaryAttack();
		}
	}

	// -----------------------
	//  Reload pressed / Clip Empty
	// -----------------------
	if ( pPlayer->m_nButtons & IN_RELOAD && UsesClipsForAmmo1() && !m_bInReload)
	{
		// reload when reload is pressed, or if no buttons are down and weapon is empty.
		Reload();
	}

	// -----------------------
	//  No buttons down
	// -----------------------
	if (!((pPlayer->m_nButtons & IN_ATTACK) || (pPlayer->m_nButtons & IN_ATTACK2) || (pPlayer->m_nButtons & IN_RELOAD)))
	{
		// no fire buttons down or reloading
		if ( !ReloadOrSwitchWeapons() && ( m_bInReload == false ) )
		{
			WeaponIdle();
		}
	}

	// Tony; decrease shots fired count - tweak the time as necessary.
	if ( !( pPlayer->m_nButtons & IN_ATTACK ) )
	{
		//Tony; check firemodes -- If we're semi or burst, we will clear shots fired now that the player has let go of the button.
		switch(GetFireMode())
		{
		case FM_SEMIAUTOMATIC:
			if (pPlayer->GetShotsFired() > 0)
				pPlayer->ClearShotsFired();
			break;
			//Tony; TODO; add an accessor to determine the max burst on a per-weapon basis!!
			//DONE!
		case FM_BURST:
			if (pPlayer->GetShotsFired() > MaxBurstShots())
				pPlayer->ClearShotsFired();
			break;
		}

		m_bFireOnEmpty = false;
		if ( (pPlayer->GetShotsFired() > 0) && (m_flDecreaseShotsFired < gpGlobals->curtime)	)
		{
			m_flDecreaseShotsFired = gpGlobals->curtime + 0.05495;
			pPlayer->DecreaseShotsFired();
		}
	}
}

void CWeaponSDKBase::WeaponIdle( void )
{
	//Idle again if we've finished
	if ( HasWeaponIdleTimeElapsed() )
	{
		SendWeaponAnim( GetIdleActivity() );
		SetWeaponIdleTime( gpGlobals->curtime + SequenceDuration() );
	}
}
bool CWeaponSDKBase::Reload( void )
{
	bool fRet;
	float fCacheTime = m_flNextSecondaryAttack;

	fRet = DefaultReload( GetMaxClip1(), GetMaxClip2(), GetReloadActivity() );
	if ( fRet )
	{

		SendReloadEvents();

		// Undo whatever the reload process has done to our secondary
		// attack timer. We allow you to interrupt reloading to fire
		// a grenade.
		m_flNextSecondaryAttack = GetOwner()->m_flNextAttack = fCacheTime;

		WeaponSound( RELOAD );
		if (GetPlayerOwner())
			GetPlayerOwner()->ClearShotsFired();
	}

	return fRet;
}
void CWeaponSDKBase::SendReloadEvents()
{
	CSDKPlayer *pPlayer = GetPlayerOwner();
	if ( !pPlayer )
		return;

#ifdef GAME_DLL
	// Send a message to any clients that have this entity to play the reload.
	CPASFilter filter( pPlayer->GetAbsOrigin() );
	filter.RemoveRecipient( pPlayer );

	UserMessageBegin( filter, "ReloadEffect" );
	WRITE_SHORT( pPlayer->entindex() );
	MessageEnd();
#endif
	// Make the player play his reload animation.
	//pPlayer->DoAnimationEvent( PLAYERANIMEVENT_RELOAD );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CWeaponSDKBase::Deploy( )
{
	MDLCACHE_CRITICAL_SECTION();

	//Tony; on deploy clear shots fired.
	if (GetPlayerOwner())
		GetPlayerOwner()->ClearShotsFired();

	return DefaultDeploy( (char*)GetViewModel(), (char*)GetWorldModel(), GetDeployActivity(), (char*)GetAnimPrefix() );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
//Tony; use the same name as the base context one.
#define SDK_HIDEWEAPON_THINK_CONTEXT			"BaseCombatWeapon_HideThink"
bool CWeaponSDKBase::Holster( CBaseCombatWeapon *pSwitchingTo )
{
	MDLCACHE_CRITICAL_SECTION();

	// cancel any reload in progress.
	m_bInReload = false;

	// kill any think functions
	SetThink(NULL);

	// Some weapon's don't have holster anims yet, so detect that
	float flSequenceDuration = 0;
	SendWeaponAnim( GetHolsterActivity() );
	{
		flSequenceDuration = SequenceDuration();
	}

	CBaseCombatCharacter *pOwner = GetOwner();
	if (pOwner)
	{
		pOwner->SetNextAttack( gpGlobals->curtime + flSequenceDuration );
	}

	// If we don't have a holster anim, hide immediately to avoid timing issues
	if ( !flSequenceDuration )
	{
		SetWeaponVisible( false );
	}
	else
	{
		// Hide the weapon when the holster animation's finished
		SetContextThink( &CBaseCombatWeapon::HideThink, gpGlobals->curtime + flSequenceDuration, SDK_HIDEWEAPON_THINK_CONTEXT );
	}

	return true;
}

#ifdef GAME_DLL
void CWeaponSDKBase::SetDieThink( bool bDie )
{
	if( bDie )
		SetContextThink( &CWeaponSDKBase::Die, gpGlobals->curtime + 45.0f, "DieContext" );
	else
		SetContextThink( NULL, gpGlobals->curtime, "DieContext" );
}
void CWeaponSDKBase::Die( void )
{
	UTIL_Remove( this );
}
#endif


text:
import React from "react";
import StorybookWrapper from "stories/helpers/storybookWrapper.js";

import baseProps from "stories/helpers/baseProps.js";
import Component from "components/views/TacticalMap/index";
import TacticalMapMock from "mocks/cards/TacticalMap.mock.js";

export default {
  title: "Cards|Viewscreen/TacticalMap",
};
export const TacticalMap = () => (
  <StorybookWrapper mocks={TacticalMapMock}>
    <Component {...baseProps} />
  </StorybookWrapper>
);

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace App\Test\TestCase\Controller;

use App\Controller\ProjectStagesController;
use Cake\TestSuite\IntegrationTestCase;

/**
 * App\Controller\ProjectStagesController Test Case
 */
class ProjectStagesControllerTest extends IntegrationTestCase
{

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'app.project_stages',
        'app.projects',
        'app.users',
        'app.genres',
        'app.organization_types',
        'app.countries',
        'app.subcontinents',
        'app.continents',
        'app.cities',
        'app.categories',
        'app.categories_projects'
    ];

    /**
     * Test index method
     *
     * @return void
     */
    public function testIndex()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test view method
     *
     * @return void
     */
    public function testView()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test add method
     *
     * @return void
     */
    public function testAdd()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test edit method
     *
     * @return void
     */
    public function testEdit()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test delete method
     *
     * @return void
     */
    public function testDelete()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }
}


text:
if [[ ${TRAVIS_PULL_REQUEST} = 'false' ]];
then
    mvn deploy --settings ./settings.xml;
else
    mvn clean verify;
fi


text:
<?php
/*
Plugin Name: SnapReplay
Plugin URI: http://code.google.com/p/cd34-wordpress/wiki/SnapReplay
Description: Display latest Event/Venue picture in sidebar
Author: Chris Davies
Version: 0.2
Author URI: http://cd34.com/

Update Event Title on page

*/

function widget_sr_control() {
?>
<?php
}

function widget_sr($args) {
?>

<a href="http://snapreplay.com/event_id/<?php echo get_option('snapreplay-stream-id'); ?>">SnapReplay Live Stream

<?php
}

function widget_sr_init() {
  if ( !function_exists('register_sidebar_widget') ||
       !function_exists('register_widget_control') ) {
    return;
  }

  register_sidebar_widget('SnapReplay Widget', 'widget_sr');

}

function sr_widget_menu() {
  add_options_page('SnapReplay Widget Options', 'SnapReplay Widget', 'manage_options', 'sr-widget-options', 'sr_widget_options');
}

function sr_widget_options() {
    if (!current_user_can('manage_options'))  {
        wp_die( __('You do not have sufficient permissions to access this page.') );
    }
?>

SnapReplay Widget setup

SnapReplay.com is a site that allows
you to crowdsource photos from events. This plugin allows you to select
an Event or Venue and display the last updated stream item Live in your
sidebar.

You need to configure the Event or Venue ID so that the widget knows
which stream to follow.

<form method="post" action="options.php">
    <?php settings_fields( 'snapreplay' ); ?>

        Event or Venue ID
        <input type="text" name="snapreplay-stream-id" value="<?php echo get_option('snapreplay-stream-id'); ?>" />

<input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />

</form>
<?php
}

function sr_widget_init() {
  register_setting('snapreplay', 'snapreplay-stream-id', 'intval');
  update_option('snapreplay-stream-id', 1);
}

add_action('init', 'widget_sr_init');

add_action('admin_menu', 'sr_widget_menu');
add_action('admin_init', 'sr_widget_init');

add_action('wp_footer', 'sr_jscript');

function sr_jscript() {
?>

<?php
}


text:
<?php
BigPipe::loadClass("PageController");
BigPipe::loadClass("BigPipeResource");

/**
 * 第一次请求页面时的输出控制器
 *
 *    共分为4个阶段输出:
 *
 *    1.渲染并收集最外层结构(未被pagelet包裹的内容)并收集使用到的Js和CSS
 *    2.输出html、head、body和最外层结构,并且输出前端库及使用到的CSS和Js资源
 *    3.根据优先级输出各层结构,并输出依赖资源表
 *    4.结束
 *
 * @uses PageController
 * @author Zhang Yuanwei <zhangyuanwei@baidu.com>
 */
class FirstController extends PageController
{
    const STAT_COLLECT = 1; // 收集阶段
    const STAT_OUTPUT = 2; // 输出阶段

    private $state = self::STAT_COLLECT; //初始状态
    private $headInnerHTML = null;
    private $bodyInnerHTML = null;
    private $loadedResource = array();

    protected $sessionId = 0; //此次会话ID,用于自动生成不重复id,第一次默认为0
    protected $uniqIds = array(); //不重复id种子
    protected static $knownEvents = array(
         "beforeload"       // Pagelet 开始加载前派发,return false 可以阻止加载
        ,"beforedisplay"    // Pagelet 加载完成CSS资源和html资源,准备渲染时派发
        ,"display"          //Pagelet dom渲染后派发
        ,"load"             // Pagelet 加载并渲染完成后派发
        ,"unload"
    );
    /**
     * 构造函数
     *
     * @access public
     * @return void
     */
    public function __construct()
    {
        $this->actionChain = array(
            //收集阶段
            'collect_html_open' => array(
                'outputOpenTag',
                true
            ),
            'collect_head_open' => array(
                'startCollect',
                true
            ),
            'collect_title_open' => array(
                'outputOpenTag',
                //FIXME collect and save title??
                true
            ),
            'collect_title_close' => array(
                'outputCloseTag'
            ),
            'collect_head_close' => array(
                'collectHeadHTML'
            ),
            'collect_body_open' => array(
                'startCollect',
                true
            ),
            'collect_pagelet_open' => array(
                //TODO 'outputPageletOpenTag',
                'addPagelet',
                'outputOpenTag',
                'startCollect',
                true
            ),
            'collect_pagelet_close' => array(
                'collectHTML',
                'setupBigrender',
                'outputCloseTag'
            ),
            'collect_body_close' => array(
                'collectBodyHTML'
            ),
            //'collect_html_close' => false,
            'collect_more' => array(
                'changeState',
                true
            ),
            //输出阶段
            //'output_html_open' => false,
            'output_head_open' => array(
                'outputOpenTag',
                'outputNoscriptFallback',
                'outputHeadHTML',
                false
            ),
            //'output_title_open' => false,
            //'output_title_close' => false,
            'output_head_close' => array(
                //TODO 'outputLayoutStyle',
                'outputLayoutStyle',
                'outputCloseTag'
            ),
            'output_body_open' => array(
                'outputOpenTag',
                'outputBodyHTML',
                false
            ),
            //'output_pagelet_open' => false,
            //'output_pagelet_close' => false,
            'output_body_close' => array(
                'outputBigPipeLibrary',
                'outputLoadedResource',
                //TODO 'sessionStart',
                //TODO 'outputLayoutPagelet',
                'outputLayoutPagelet',
                'outputPagelets',
                'outputCloseTag'
            ),
            'output_html_close' => array(
                'outputCloseTag'
            ),
            'output_more' => false,
            'default' => false
        );
    }

    /**
     * 收集阶段调用函数,收集 head 标签中的 HTML 内容
     *
     * @param PageletContext $context
     */
    protected function collectHeadHTML($context)
    {
        $this->headInnerHTML = ob_get_clean();
    }

    /**
     * 收集阶段调用函数,收集 body 标签中的HTML内容
     *
     * @param PageletContext $context
     */
    protected function collectBodyHTML($context)
    {
        $this->bodyInnerHTML = ob_get_clean();
    }

    /**
     * 将当前 pagelet 添加到输出列表中
     *
     * @param PageletContext $context
     */
    protected function addPagelet($context)
    {
        $context->getParam("id", $this->sessionUniqId("__elm_"), PageletContext::FLG_APPEND_PARAM);
        $this->pagelets[] = $context;
    }

    /**
     * outputNoscriptFallback 输出noscript跳转 {{{
     *
     * @param mixed $context
     * @access protected
     * @return void
     */
    protected function outputNoscriptFallback($context)
    {
        $uri=$_SERVER["REQUEST_URI"];
        $uri=$uri . (strpos($uri, "?")===false ? "?" : "&") . BigPipe::NO_JS . "=1";

        echo "";
        echo "<meta http-equiv=\"refresh\" content=\"0; URL=$uri\" />";
        echo "";
    }

    /**
     * 输出布局阶段调用函数,将收集到的 head 标签中的 HTML 内容输出
     *
     * @param PageletContext $context
     */
    protected function outputHeadHTML($context)
    {
        echo $this->headInnerHTML;
    }

    /**
     * 输出布局阶段调用函数,将收集到的 body 标签中的 HTML 内容输出
     *
     * @param PageletContext $context
     */
    protected function outputBodyHTML($context)
    {
        echo $this->bodyInnerHTML;
    }

    /**
     * 输出布局阶段调用函数,将收集到的 body 标签中的 HTML 内容输出
     *
     * @param PageletContext $context
     */
    protected function setupBigrender($context)
    {
        if(isset($context->bigrender)){
            $eventType = "beforeload";
            $context->addRequire($eventType, BigPipe::$bigrenderLib);
            $context->addHook($eventType, BigPipe::getBigrenderCode());
        }
    }

    /**
     * 输出布局阶段调用函数,将收集到的 head和body标签中的 HTML 内容输出
     *
     * @param PageletContext $context
     */
    protected function outputLayoutStyle($context)
    {
        $event = $context->parent->getEvent('beforedisplay');

        if($event != false){
            $styleLinks = $event->requires;

            $styleResources = BigPipeResource::pathToResource($styleLinks, 'css');
            $styleResources = BigPipeResource::getDependResource($styleResources, false);

            $this->loadedResource = BigPipe::array_merge($styleResources, $this->loadedResource);

            foreach ($styleResources as $resource) {
                echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"{$resource['src']}\" />";
            }
        }

    }

    protected function outputBigPipeLibrary($context)
    {

        $jsLibs = BigPipeResource::pathToResource(array(BigPipe::$jsLib));
        $jsLibs = BigPipeResource::getDependResource($jsLibs, false);

        $this->loadedResource = BigPipe::array_merge($jsLibs, $this->loadedResource);

        foreach ($jsLibs as $resource) {
           echo "";
        }
       //echo "\n";
       // echo "\n";
    } //

    protected function outputLoadedResource($context)
    {
       $loadedResource = json_encode(array_keys(($this->loadedResource)));
       echo "\n";
    }
    /**
     * 输出布局阶段调用函数,将收集到的 head和body标签中的 HTML 内容输出
     *
     * @param PageletContext $context
     */
    protected function outputLayoutPagelet($context)
    {
        $context->parent->children = $context->children;
        $this->outputPagelet($context->parent);
    }

    /**
     * 输出页面中所有的 pagelet
     *
     * @param PageletContext $context
     */
    protected function outputPagelets($context)
    {
        foreach ($this->pagelets as $pagelet) {
            $this->outputPagelet($pagelet);
        }
    }

    protected function outputPagelet($pagelet)
    {
        $resourceMap = array();
        $hooks = array();
        $config = $this->getPageletConfig($pagelet, $html, $resourceMap, $hooks);

        // 输出注释里的 HTML
        if (!empty($html)) {
            echo "\n" . $html;
        }

        echo "\n";

    }

    /**
     * 得到 pagelet 的配置,用于 BigPipe.onPageletArrive
     *
     * @param PageletContext $pagelet
     * @param string $html
     * @param array $resourceMap
     * @param array $hooks
     */
    private function getPageletConfig($pagelet, &$html, &$resourceMap, &$hooks)
    {
        $config      = array();

        $config["id"] = $pagelet->getParam("id");

        foreach ($pagelet->children as $child) {
            $config["children"][] = $child->getParam("id");
        }

        if($pagelet->parent) {
            $config["parent"] = $pagelet->parent->getParam("id");
        }

        if (!empty($pagelet->html)) {
            //生成容器ID
            $containerId = $this->sessionUniqId("__cnt_");

            //生成注释的内容
            $html = "";

            //设置html属性
            $config["html"]["container"] = $containerId;
        }

        foreach (self::$knownEvents as $type) {
            $event = $pagelet->getEvent($type);

            if ($event !== false) {
                foreach ($event->hooks as $hook) {
                    $hookId                   = $this->sessionUniqId("__cb_");
                    $hooks[$hookId]           = $hook;
                    $config["hooks"][$type][] = $hookId;
                }

                //deps
                $requireResources = BigPipeResource::pathToResource($event->requires);
                $config["deps"][$type] = array_keys($requireResources);

                $resourceMap = array_merge($resourceMap, $event->requires, $event->requireAsyncs);
            }
        }
        return $config;
    }

    /**
     * 得到注释包裹的HTML
     *
     * @param string $html
     * @return string
     */
    private function getCommentHTML($html)
    {
        return str_replace(array(
            "\\",
            "-->"
        ), array(
            "\\\\",
            "--\\>"
        ), $html);
    }

    /**
     * 改变状态
     *
     * @param PageletContext $context
     */
    protected function changeState($context)
    {
        if ($this->state === self::STAT_COLLECT) {
            $this->state = self::STAT_OUTPUT;
        }
    }

    /**
     * getActionKey 得到需要执行的动作索引
     *
     * @param mixed $context
     * @param mixed $action
     * @access protected
     * @return void
     */
    protected function getActionKey($type, $action)
    {
        $keys = array();
        switch ($this->state) {
            case self::STAT_COLLECT:
                $keys[] = "collect";
                break;
            case self::STAT_OUTPUT:
                $keys[] = "output";
                break;
            default:
        }

        switch ($type) {
            case BigPipe::TAG_HTML:
                $keys[] = "html";
                break;
            case BigPipe::TAG_HEAD:
                $keys[] = "head";
                break;
            case BigPipe::TAG_TITLE:
                $keys[] = "title";
                break;
            case BigPipe::TAG_BODY:
                $keys[] = "body";
                break;
            case BigPipe::TAG_PAGELET:
                $keys[] = "pagelet";
                break;
            default:
        }

        switch ($action) {
            case PageController::ACTION_OPEN:
                $keys[] = "open";
                break;
            case PageController::ACTION_CLOSE:
                $keys[] = "close";
                break;
            case PageController::ACTION_MORE:
                $keys[] = "more";
                break;
            default:
        }

        $key = join("_", $keys);
        if (!isset($this->actionChain[$key])) {
            $key = 'default';
        }
        return $key;
    }

    /**
     * 得到本次会话中唯一ID
     *
     * @param string $prefix 可选前缀
     * @return string
     */
    protected function sessionUniqId($prefix = "")
    {
        if (!isset($this->uniqIds[$prefix])) {
            $this->uniqIds[$prefix] = 0;
        }
        $this->uniqIds[$prefix]++;
        return $prefix . $this->sessionId . "_" . $this->uniqIds[$prefix];
        //sessionKey
    }

}

// vim600: sw=4 ts=4 fdm=marker syn=php


text:
package com.opengamma.strata.measure.fx;

import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;

import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableValidator;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.google.common.collect.ImmutableMap;
import com.opengamma.strata.basics.currency.CurrencyPair;
import com.opengamma.strata.basics.currency.FxRate;
import com.opengamma.strata.collect.Messages;
import com.opengamma.strata.market.observable.QuoteId;

/**
 * Configuration defining how to create {@link FxRate} instances from observable market data.
 *

 * Currently this only supports rates which are observable in the market. Cross rates derived from other
 * rates will be supported later.
 *

 * This class is likely to change when support for cross rates is added.
 *

 * When populating this class all currency pairs must be quoted using the market conventions.
 */
@BeanDefinition
public final class FxRateConfig implements ImmutableBean {

  /**
   * The keys identifying FX rates which are observable in the market.
   * Each entry is keyed by the conventional currency pair.
   */
  @PropertyDefinition(validate = "notNull", get = "private")
  private final ImmutableMap<CurrencyPair, QuoteId> observableRates;

  /**
   * Returns a key identifying the market quote for an observable FX rate.
   *

   * If the FX rate is not observable in the market an empty optional is returned.
   *

   * It is possible the quote is for the rate of the inverse of the currency pair. This does not matter as
   * the market data system ensures that the correct rate is always provided regardless of which way round
   * the pair is quoted.
   *
   * @param currencyPair  the currency pair
   * @return a key identifying the market quote for the rate if it is observable in the market
   */
  public Optional<QuoteId> getObservableRateKey(CurrencyPair currencyPair) {
    QuoteId quoteId = observableRates.get(currencyPair.toConventional());
    return Optional.ofNullable(quoteId);
  }

  /**
   * Returns FX rate configuration built using the data in the map.
   *
   * @param quotesMap  map of currency pairs to the market quotes defining their rates
   * @return FX rate configuration built using the data in the map
   */
  public static FxRateConfig of(Map<CurrencyPair, QuoteId> quotesMap) {
    return new FxRateConfig(quotesMap);
  }

  @ImmutableValidator
  private void validate() {
    for (CurrencyPair currencyPair : observableRates.keySet()) {
      if (!currencyPair.isConventional()) {
        throw new IllegalArgumentException(
            Messages.format(
                "Currency pairs must be quoted using market conventions but {} is not",
                currencyPair));
      }
    }
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code FxRateConfig}.
   * @return the meta-bean, not null
   */
  public static FxRateConfig.Meta meta() {
    return FxRateConfig.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(FxRateConfig.Meta.INSTANCE);
  }

  /**
   * Returns a builder used to create an instance of the bean.
   * @return the builder, not null
   */
  public static FxRateConfig.Builder builder() {
    return new FxRateConfig.Builder();
  }

  private FxRateConfig(
      Map<CurrencyPair, QuoteId> observableRates) {
    JodaBeanUtils.notNull(observableRates, "observableRates");
    this.observableRates = ImmutableMap.copyOf(observableRates);
    validate();
  }

  @Override
  public FxRateConfig.Meta metaBean() {
    return FxRateConfig.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the keys identifying FX rates which are observable in the market.
   * Each entry is keyed by the conventional currency pair.
   * @return the value of the property, not null
   */
  private ImmutableMap<CurrencyPair, QuoteId> getObservableRates() {
    return observableRates;
  }

  //-----------------------------------------------------------------------
  /**
   * Returns a builder that allows this bean to be mutated.
   * @return the mutable builder, not null
   */
  public Builder toBuilder() {
    return new Builder(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      FxRateConfig other = (FxRateConfig) obj;
      return JodaBeanUtils.equal(observableRates, other.observableRates);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(observableRates);
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(64);
    buf.append("FxRateConfig{");
    buf.append("observableRates").append('=').append(JodaBeanUtils.toString(observableRates));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code FxRateConfig}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code observableRates} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<ImmutableMap<CurrencyPair, QuoteId>> observableRates = DirectMetaProperty.ofImmutable(
        this, "observableRates", FxRateConfig.class, (Class) ImmutableMap.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "observableRates");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 1996176400:  // observableRates
          return observableRates;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public FxRateConfig.Builder builder() {
      return new FxRateConfig.Builder();
    }

    @Override
    public Class<? extends FxRateConfig> beanType() {
      return FxRateConfig.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code observableRates} property.
     * @return the meta-property, not null
     */
    public MetaProperty<ImmutableMap<CurrencyPair, QuoteId>> observableRates() {
      return observableRates;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 1996176400:  // observableRates
          return ((FxRateConfig) bean).getObservableRates();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code FxRateConfig}.
   */
  public static final class Builder extends DirectFieldsBeanBuilder<FxRateConfig> {

    private Map<CurrencyPair, QuoteId> observableRates = ImmutableMap.of();

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    /**
     * Restricted copy constructor.
     * @param beanToCopy  the bean to copy from, not null
     */
    private Builder(FxRateConfig beanToCopy) {
      this.observableRates = beanToCopy.getObservableRates();
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 1996176400:  // observableRates
          return observableRates;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 1996176400:  // observableRates
          this.observableRates = (Map<CurrencyPair, QuoteId>) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public Builder setString(String propertyName, String value) {
      setString(meta().metaProperty(propertyName), value);
      return this;
    }

    @Override
    public Builder setString(MetaProperty<?> property, String value) {
      super.setString(property, value);
      return this;
    }

    @Override
    public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
      super.setAll(propertyValueMap);
      return this;
    }

    @Override
    public FxRateConfig build() {
      return new FxRateConfig(
          observableRates);
    }

    //-----------------------------------------------------------------------
    /**
     * Sets the keys identifying FX rates which are observable in the market.
     * Each entry is keyed by the conventional currency pair.
     * @param observableRates  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder observableRates(Map<CurrencyPair, QuoteId> observableRates) {
      JodaBeanUtils.notNull(observableRates, "observableRates");
      this.observableRates = observableRates;
      return this;
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(64);
      buf.append("FxRateConfig.Builder{");
      buf.append("observableRates").append('=').append(JodaBeanUtils.toString(observableRates));
      buf.append('}');
      return buf.toString();
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../app/models/user.js');

// expose function to the app
module.exports = function(passport) {

    // =========================================================================
    // PASSPORT SESSION SETUP ==================================================
    // =========================================================================

    // used to serialize the user
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================

    passport.use('local-signup', new LocalStrategy({

        usernameField: 'username',
        passwordField: 'password',
        passReqToCallback: true

    },
    function(req, username, password, done) {

        // asynchronous
        // User.findOne won't fire unless data is sent back
        process.nextTick(function() {

            // check to see if the user already exists
            User.findOne({ 'local.username': username }, function(err, user) {
                // if there are errors, return the error
                if (err)
                    return done(err);

                // check to see if a user with the username already exists
                if (user) {
                    return done(null, false, req.flash('signupMessage', 'That username is already taken.'));

                } else {

                    // make sure that the password is at least 6 characters long
                    // this ensures that users cannot have incredibly weak passwords
                    if (password.length > 5) {

                        // if the user doesn't exist, create the user
                        var newUser = new User();

                        // set the user's credentials
                        newUser.local.username = username;
                        newUser.local.password = newUser.generateHash(password);
                        newUser.local.role = req.body.role;

                        // save the user
                        newUser.save(function(err) {
                            if (err)
                                throw err;
                            return done(null, false);
                        });

                    } else {

                        return done(null, false, req.flash('signupMessage', 'Please choose a password of at least 6 characters.'));

                    }

                }
            });

        });

    }));

    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================

    passport.use('local-login', new LocalStrategy({

        usernameField: 'username',
        passwordField: 'password',
        passReqToCallback: true

    },
    function(req, username, password, done) {

        // find a user with the username in the form
        User.findOne({ 'local.username': username }, function(err, user) {

            // if there are any errors, return the error before anyting else
            if (err)
                return done(err);

            // if no use is found, return a message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.'));

            // if the user is found but the password is wrong
            if (!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Wrong password.'));

            // all is well, return the user
            return done(null, user);

        });

    }));

};


text:
if [[ $(uname) == 'Darwin' ]] ; then
    (cd submodules/ghc-ios-scripts; ./installGHCiOS.sh)
fi

# Android Configuration
(cd submodules/docker; docker build -t HXSDL_build_env)


text:
var fs = require('fs');
var remote = require('electron').remote;
var BrowserWindow = remote.BrowserWindow;
var dialog = remote.dialog;
var path = require('path');
var file = window.location.href.split('?file=')[1];

//Code
editor = CodeMirror.fromTextArea(document.getElementById('code-part--code'), {
	lineNumbers: true,
	mode: "javascript"
});

fs.readFile(file, 'utf-8', (err, data) => {
	if(err){
		alert("Error ocurred reading the file: " + err.message);
		return;
	}

	editor.getDoc().setValue(data);
});

//Menu
document.getElementById('menu--save').addEventListener('click', function(){
	fs.writeFile(file, editor.getValue(), (err) => {
		if (err) {
		    alert("An error ocurred updating the file" + err.message);
		    return;
		}
	});
});

document.getElementById('menu--save-as').addEventListener('click', function(){
	dialog.showSaveDialog({title: "Create File", defaultPath: "project.js"}, (fileName) => {
		if (fileName === undefined){
			return;
		}

		fs.writeFile(fileName, editor.getValue(), (err) => {
			if(err){
			    alert("An error ocurred creating the file "+ err.message)
			}
		});
	});
});

document.getElementById('menu--run').addEventListener('click', function(){
	fs.writeFile(file, editor.getValue(), (err) => {
		if (err) {
		    alert("An error ocurred updating the file" + err.message);
		    return;
		}
	});

    runnerWindow = new BrowserWindow({ width: 465, height: 317, icon: path.join(__dirname, '/../assets/icon.png') });
    runnerWindow.setMenu(null);
    runnerWindow.setResizable(false);
    runnerWindow.setMinimizable(false);
    runnerWindow.setMaximizable(false);
    runnerWindow.loadURL('file://' + __dirname + '/../runner/runner.html?file=' + file);
});


text:
package com.asakusafw.windgate.hadoopfs.ssh;

import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.windgate.core.WindGateLogger;
import com.asakusafw.windgate.core.resource.ResourceProfile;
import com.asakusafw.windgate.core.util.PropertiesUtil;
import com.asakusafw.windgate.hadoopfs.HadoopFsLogger;

/**
 * A structured profile for {@link AbstractSshHadoopFsMirror}.
 * @since 0.2.2
 * @version 0.7.0
 */
public class SshProfile {

    static final WindGateLogger WGLOG = new HadoopFsLogger(SshProfile.class);

    static final Logger LOG = LoggerFactory.getLogger(SshProfile.class);

    /**
     * The remote base target.
     * @since 0.4.0
     */
    public static final String PATH_BASE_TARGET = "windgate-ssh";

    /**
     * The remote 'get' command path.
     */
    public static final String COMMAND_GET = "libexec/get.sh";

    /**
     * The remote 'put' command path.
     */
    public static final String COMMAND_PUT = "libexec/put.sh";

    /**
     * The remote 'delete' command path.
     */
    public static final String COMMAND_DELETE = "libexec/delete.sh";

    /**
     * The key of remote target installed path.
     */
    public static final String KEY_TARGET = "target";

    /**
     * The key of user name.
     */
    public static final String KEY_USER = "user";

    /**
     * The key of host name.
     */
    public static final String KEY_HOST = "host";

    /**
     * The key of port number.
     */
    public static final String KEY_PORT = "port";

    /**
     * The key of path to the private key.
     * This value can includes environment variables in form of <code>${VARIABLE-NAME}</code>.
     */
    public static final String KEY_PRIVATE_KEY = "privateKey";

    /**
     * The key of passphrase.
     */
    public static final String KEY_PASS_PHRASE = "passPhrase";

    /**
     * The key of {@link CompressionCodec} class name.
     */
    public static final String KEY_COMPRESSION = "compression";

    /**
     * The key prefix of additional remote environment variables.
     * @since 0.4.0
     */
    public static final String PREFIX_ENV = "env.";

    private final String resourceName;

    private final String target;

    private final String user;

    private final String host;

    private final int port;

    private final String privateKey;

    private final String passPhrase;

    private final Map<String, String> environmentVariables;

    /**
     * Creates a new instance.
     * @param name the resource name
     * @param target the remote target installed path
     * @param user the connection user name
     * @param host the connection target host
     * @param port the connection target port
     * @param privateKey the path to the private key file
     * @param passPhrase the passphrase of target private key
     * @param compressionCodec the compression codec, or {@code null} if does not compress
     * @param env environment variables
     * @throws IllegalArgumentException if any parameter is {@code null}
     * @deprecated Use {@link #SshProfile(String, String, String, String, int, String, String, Map)} instead
     */
    @Deprecated
    public SshProfile(
            String name,
            String target,
            String user,
            String host,
            int port,
            String privateKey,
            String passPhrase,
            CompressionCodec compressionCodec,
            Map<String, String> env) {
        this(name, target, user, host, port, privateKey, passPhrase, env);
    }

    /**
     * Creates a new instance.
     * @param name the resource name
     * @param target the remote target installed path
     * @param user the connection user name
     * @param host the connection target host
     * @param port the connection target port
     * @param privateKey the path to the private key file
     * @param passPhrase the passphrase of target private key
     * @param env environment variables
     * @throws IllegalArgumentException if any parameter is {@code null}
     * @since 0.7.0
     */
    public SshProfile(
            String name,
            String target,
            String user,
            String host,
            int port,
            String privateKey,
            String passPhrase,
            Map<String, String> env) {
        if (name == null) {
            throw new IllegalArgumentException("name must not be null"); //$NON-NLS-1$
        }
        if (target == null) {
            throw new IllegalArgumentException("target must not be null"); //$NON-NLS-1$
        }
        if (user == null) {
            throw new IllegalArgumentException("user must not be null"); //$NON-NLS-1$
        }
        if (host == null) {
            throw new IllegalArgumentException("host must not be null"); //$NON-NLS-1$
        }
        if (privateKey == null) {
            throw new IllegalArgumentException("privateKey must not be null"); //$NON-NLS-1$
        }
        if (passPhrase == null) {
            throw new IllegalArgumentException("passPhrase must not be null"); //$NON-NLS-1$
        }
        if (env == null) {
            throw new IllegalArgumentException("env must not be null"); //$NON-NLS-1$
        }
        this.resourceName = name;
        this.target = target;
        this.user = user;
        this.host = host;
        this.port = port;
        this.privateKey = privateKey;
        this.passPhrase = passPhrase;
        this.environmentVariables = Collections.unmodifiableMap(env);
    }

    /**
     * Converts {@link ResourceProfile} into {@link SshProfile}.
     * @param configuration the current configuration
     * @param profile target profile
     * @return the converted profile
     * @throws IllegalArgumentException if profile is not valid, or any parameter is {@code null}
     */
    public static SshProfile convert(Configuration configuration, ResourceProfile profile) {
        if (configuration == null) {
            throw new IllegalArgumentException("configuration must not be null"); //$NON-NLS-1$
        }
        if (profile == null) {
            throw new IllegalArgumentException("profile must not be null"); //$NON-NLS-1$
        }
        String name = profile.getName();
        String target = extract(profile, KEY_TARGET, false);
        String user = extract(profile, KEY_USER, true);
        String host = extract(profile, KEY_HOST, true);
        int port = extractPort(profile);
        String privateKey = extract(profile, KEY_PRIVATE_KEY, true);
        String passPhrase = extractPassPhrase(profile);
        extractCompressionCodec(configuration, profile);
        Map<String, String> env = extractEnv(profile);
        if (target == null) {
            String home = env.get("ASAKUSA_HOME");
            if (home == null || home.isEmpty()) {
                WGLOG.error("E10001",
                        profile.getName(),
                        PREFIX_ENV + "ASAKUSA_HOME",
                        null);
                throw new IllegalArgumentException(MessageFormat.format(
                        "Resource \"{0}\" must declare \"{1}\"",
                        profile.getName(),
                        PREFIX_ENV + "ASAKUSA_HOME"));
            }
            if (home.endsWith("/") == false) {
                home = home + "/";
            }
            target = home + PATH_BASE_TARGET;
        }

        return new SshProfile(
                name,
                target,
                user,
                host,
                port,
                privateKey,
                passPhrase,
                env);
    }

    private static String extract(ResourceProfile profile, String configKey, boolean mandatory) {
        assert profile != null;
        assert configKey != null;
        String value = profile.getConfiguration().get(configKey);
        if (value == null) {
            if (mandatory == false) {
                return null;
            } else {
                WGLOG.error("E10001",
                        profile.getName(),
                        configKey,
                        null);
                throw new IllegalArgumentException(MessageFormat.format(
                        "Resource \"{0}\" must declare \"{1}\"",
                        profile.getName(),
                        configKey));
            }
        }
        return resolve(profile, configKey, value.trim());
    }

    private static String resolve(ResourceProfile profile, String configKey, String value) {
        assert profile != null;
        assert configKey != null;
        assert value != null;
        try {
            return profile.getContext().getContextParameters().replace(value, true);
        } catch (IllegalArgumentException e) {
            WGLOG.error(e, "E10001",
                    profile.getName(),
                    configKey,
                    value);
            throw new IllegalArgumentException(MessageFormat.format(
                    "Failed to resolve environment variables: {2} (resource={0}, property={1})",
                    profile.getName(),
                    configKey,
                    value), e);
        }
    }

    private static int extractPort(ResourceProfile profile) {
        assert profile != null;
        String portString = extract(profile, KEY_PORT, true);
        try {
            return Integer.parseInt(portString);
        } catch (NumberFormatException e) {
            WGLOG.error("E10001",
                    profile.getName(),
                    KEY_PORT,
                    portString);
            throw new IllegalArgumentException(MessageFormat.format(
                    "The \"{1}\" must be a valid port number: {2} (resource={0})",
                    profile.getName(),
                    KEY_PORT,
                    portString));
        }
    }

    private static Map<String, String> extractEnv(ResourceProfile profile) {
        assert profile != null;
        Map<String, String> map = PropertiesUtil.createPrefixMap(profile.getConfiguration(), PREFIX_ENV);
        Map<String, String> results = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String resolved =  resolve(profile, PREFIX_ENV + entry.getKey(), entry.getValue());
            results.put(entry.getKey(), resolved);
        }
        LOG.debug("Remote Env ({}): {}", profile.getName(), results);
        return results;
    }

    private static String extractPassPhrase(ResourceProfile profile) {
        assert profile != null;
        String passPhrase = extract(profile, KEY_PASS_PHRASE, false);
        passPhrase = passPhrase == null ? "" : passPhrase;
        return passPhrase;
    }

    private static void extractCompressionCodec(Configuration configuration, ResourceProfile profile) {
        assert configuration != null;
        assert profile != null;
        String compressionCodecString = extract(profile, KEY_COMPRESSION, false);
        if (compressionCodecString != null) {
            WGLOG.warn("W10001",
                    profile.getName(),
                    KEY_COMPRESSION,
                    compressionCodecString);
        }
    }

    /**
     * Returns the resource name.
     * @return the resource name
     */
    public String getResourceName() {
        return resourceName;
    }

    /**
     * Return the remote installation path.
     * @return the remote installation path
     */
    public String getTarget() {
        return target;
    }

    /**
     * Returns the get command.
     * @return the get command
     */
    public String getGetCommand() {
        return getCommand(COMMAND_GET);
    }

    /**
     * Returns the put command.
     * @return the put command
     */
    public String getPutCommand() {
        return getCommand(COMMAND_PUT);
    }

    /**
     * Returns the delete command.
     * @return the delete command
     */
    public String getDeleteCommand() {
        return getCommand(COMMAND_DELETE);
    }

    private String getCommand(String command) {
        assert command != null;
        StringBuilder buf = new StringBuilder();
        buf.append(target);
        if (target.endsWith("/") == false) {
            buf.append('/');
        }
        buf.append(command);
        return buf.toString();
    }

    /**
     * Returns the user name.
     * @return the user name
     */
    public String getUser() {
        return user;
    }

    /**
     * Returns the target host name.
     * @return the target host
     */
    public String getHost() {
        return host;
    }

    /**
     * Return the target port.
     * @return the target port
     */
    public int getPort() {
        return port;
    }

    /**
     * Return the path to the private key file.
     * @return the path to the private key file
     */
    public String getPrivateKey() {
        return privateKey;
    }

    /**
     * Returns the pass phrase of the {@link #getPrivateKey()}.
     * @return the pass phrase
     */
    public String getPassPhrase() {
        return passPhrase;
    }

    /**
     * Returns the additional remote environment variables.
     * @return the remote environment variables
     * @since 0.4.0
     */
    public Map<String, String> getEnvironmentVariables() {
        return environmentVariables;
    }

    /**
     * Returns the compression codec of putting sequence files.
     * @return the compression codec, or {@code null} if does not compress
     * @deprecated from {@code 0.7.0}, WindGate does not use sequence files
     */
    @Deprecated
    public CompressionCodec getCompressionCodec() {
        return null;
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.tpch;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.tpch.PartColumn;
import io.airlift.tpch.TpchColumn;
import io.airlift.tpch.TpchTable;
import io.prestosql.plugin.tpch.util.PredicateUtils;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.connector.ConnectorSession;
import io.prestosql.spi.connector.ConnectorTableHandle;
import io.prestosql.spi.connector.ConnectorTableLayoutResult;
import io.prestosql.spi.connector.Constraint;
import io.prestosql.spi.connector.SchemaTableName;
import io.prestosql.spi.predicate.NullableValue;
import io.prestosql.spi.predicate.TupleDomain;
import io.prestosql.spi.statistics.ColumnStatistics;
import io.prestosql.spi.statistics.DoubleRange;
import io.prestosql.spi.statistics.Estimate;
import io.prestosql.spi.statistics.TableStatistics;
import org.testng.annotations.Test;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

import static com.google.common.collect.Iterables.getOnlyElement;
import static io.airlift.slice.Slices.utf8Slice;
import static io.airlift.tpch.CustomerColumn.MARKET_SEGMENT;
import static io.airlift.tpch.CustomerColumn.NAME;
import static io.airlift.tpch.LineItemColumn.LINE_NUMBER;
import static io.airlift.tpch.NationColumn.NATION_KEY;
import static io.airlift.tpch.OrderColumn.CLERK;
import static io.airlift.tpch.OrderColumn.ORDER_DATE;
import static io.airlift.tpch.OrderColumn.ORDER_KEY;
import static io.airlift.tpch.OrderColumn.ORDER_STATUS;
import static io.airlift.tpch.PartColumn.PART_KEY;
import static io.airlift.tpch.PartColumn.RETAIL_PRICE;
import static io.airlift.tpch.TpchTable.CUSTOMER;
import static io.airlift.tpch.TpchTable.LINE_ITEM;
import static io.airlift.tpch.TpchTable.NATION;
import static io.airlift.tpch.TpchTable.ORDERS;
import static io.airlift.tpch.TpchTable.PART;
import static io.airlift.tpch.TpchTable.PART_SUPPLIER;
import static io.airlift.tpch.TpchTable.REGION;
import static io.airlift.tpch.TpchTable.SUPPLIER;
import static io.prestosql.plugin.tpch.TpchMetadata.getPrestoType;
import static io.prestosql.plugin.tpch.util.PredicateUtils.filterOutColumnFromPredicate;
import static io.prestosql.spi.connector.Constraint.alwaysFalse;
import static io.prestosql.spi.connector.Constraint.alwaysTrue;
import static java.lang.String.format;
import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

public class TestTpchMetadata
{
    private static final double TOLERANCE = 0.01;

    private static final List<String> SUPPORTED_SCHEMAS = ImmutableList.of("tiny", "sf1");

    private final TpchMetadata tpchMetadata = new TpchMetadata();
    private final ConnectorSession session = null;

    @Test
    public void testTableStats()
    {
        SUPPORTED_SCHEMAS.forEach(schema -> {
            double scaleFactor = TpchMetadata.schemaNameToScaleFactor(schema);
            testTableStats(schema, REGION, 5);
            testTableStats(schema, NATION, 25);
            testTableStats(schema, SUPPLIER, 10_000 * scaleFactor);
            testTableStats(schema, CUSTOMER, 150_000 * scaleFactor);
            testTableStats(schema, PART, 200_000 * scaleFactor);
            testTableStats(schema, PART_SUPPLIER, 800_000 * scaleFactor);
            testTableStats(schema, ORDERS, 1_500_000 * scaleFactor);
            testTableStats(schema, LINE_ITEM, 6_000_000 * scaleFactor);
        });
    }

    @Test
    public void testNoTableStats()
    {
        Stream.of("sf10", "sf100").forEach(schema -> {
            testNoTableStats(schema, REGION);
            testNoTableStats(schema, NATION);
            testNoTableStats(schema, SUPPLIER);
            testNoTableStats(schema, CUSTOMER);
            testNoTableStats(schema, PART);
            testNoTableStats(schema, PART_SUPPLIER);
            testNoTableStats(schema, ORDERS);
            testNoTableStats(schema, LINE_ITEM);
        });
    }

    @Test
    public void testTableStatsWithConstraints()
    {
        SUPPORTED_SCHEMAS.forEach(schema -> {
            double scaleFactor = TpchMetadata.schemaNameToScaleFactor(schema);

            testTableStats(schema, ORDERS, alwaysFalse(), 0);
            testTableStats(schema, ORDERS, constraint(ORDER_STATUS, "NO SUCH STATUS"), 0);
            testTableStats(schema, ORDERS, constraint(ORDER_STATUS, "F"), 730_400 * scaleFactor);
            testTableStats(schema, ORDERS, constraint(ORDER_STATUS, "O"), 733_300 * scaleFactor);
            testTableStats(schema, ORDERS, constraint(ORDER_STATUS, "F", "NO SUCH STATUS"), 730_400 * scaleFactor);
            testTableStats(schema, ORDERS, constraint(ORDER_STATUS, "F", "O", "P"), 1_500_000 * scaleFactor);
        });
    }

    private void testTableStats(String schema, TpchTable<?> table, double expectedRowCount)
    {
        testTableStats(schema, table, alwaysTrue(), expectedRowCount);
    }

    private void testTableStats(String schema, TpchTable<?> table, Constraint<ColumnHandle> constraint, double expectedRowCount)
    {
        TpchTableHandle tableHandle = tpchMetadata.getTableHandle(session, new SchemaTableName(schema, table.getTableName()));
        TableStatistics tableStatistics = tpchMetadata.getTableStatistics(session, tableHandle, constraint);

        double actualRowCountValue = tableStatistics.getRowCount().getValue();
        assertEquals(tableStatistics.getRowCount(), Estimate.of(actualRowCountValue));
        assertEquals(actualRowCountValue, expectedRowCount, expectedRowCount * TOLERANCE);
    }

    private void testNoTableStats(String schema, TpchTable<?> table)
    {
        TpchTableHandle tableHandle = tpchMetadata.getTableHandle(session, new SchemaTableName(schema, table.getTableName()));
        TableStatistics tableStatistics = tpchMetadata.getTableStatistics(session, tableHandle, alwaysTrue());
        assertTrue(tableStatistics.getRowCount().isUnknown());
    }

    @Test
    public void testColumnStats()
    {
        Stream.of("tiny", "sf1").forEach(schema -> {
            double scaleFactor = TpchMetadata.schemaNameToScaleFactor(schema);

            //id column
            testColumnStats(schema, NATION, NATION_KEY, columnStatistics(25, 0, 24));

            //foreign key to dictionary identifier columns
            testColumnStats(schema, SUPPLIER, NATION_KEY, columnStatistics(25, 0, 24));

            //foreign key to scalable identifier column
            testColumnStats(schema, PART_SUPPLIER, PART_KEY, columnStatistics(200_000 * scaleFactor, 1, 200_000 * scaleFactor));

            //dictionary
            testColumnStats(schema, CUSTOMER, MARKET_SEGMENT, columnStatistics(5, 45));

            //low-valued numeric column
            testColumnStats(schema, LINE_ITEM, LINE_NUMBER, columnStatistics(7, 1, 7));

            //date
            testColumnStats(schema, ORDERS, ORDER_DATE, columnStatistics(2_400, 8_035, 10_440));

            //varchar and double columns
            if (schema.equals("tiny")) {
                testColumnStats(schema, CUSTOMER, NAME, columnStatistics(150_000 * scaleFactor, 27000));
                testColumnStats(schema, PART, RETAIL_PRICE, columnStatistics(1_099, 901, 1900.99));
            }
            else if (schema.equals("sf1")) {
                testColumnStats(schema, CUSTOMER, NAME, columnStatistics(150_000 * scaleFactor, 2700000));
                testColumnStats(schema, PART, RETAIL_PRICE, columnStatistics(20899, 901, 2089.99));
            }
        });
    }

    @Test
    public void testColumnStatsWithConstraints()
    {
        SUPPORTED_SCHEMAS.forEach(schema -> {
            double scaleFactor = TpchMetadata.schemaNameToScaleFactor(schema);

            //value count, min and max are supported for the constrained column
            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(ORDER_STATUS, "F"), columnStatistics(1, 1));
            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(ORDER_STATUS, "O"), columnStatistics(1, 1));
            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(ORDER_STATUS, "P"), columnStatistics(1, 1));

            //only min and max values for non-scaling columns can be estimated for non-constrained columns
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(ORDER_STATUS, "F"), rangeStatistics(3, 6_000_000 * scaleFactor));
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(ORDER_STATUS, "O"), rangeStatistics(1, 6_000_000 * scaleFactor));
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(ORDER_STATUS, "P"), rangeStatistics(65, 6_000_000 * scaleFactor));
            testColumnStats(schema, ORDERS, CLERK, constraint(ORDER_STATUS, "O"), createColumnStatistics(Optional.empty(), Optional.empty(), Optional.of(15000.0)));

            //nothing can be said for always false constraints
            testColumnStats(schema, ORDERS, ORDER_STATUS, alwaysFalse(), noColumnStatistics());
            testColumnStats(schema, ORDERS, ORDER_KEY, alwaysFalse(), noColumnStatistics());
            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(ORDER_STATUS, "NO SUCH STATUS"), noColumnStatistics());
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(ORDER_STATUS, "NO SUCH STATUS"), noColumnStatistics());

            //unmodified stats are returned for the always true constraint
            testColumnStats(schema, ORDERS, ORDER_STATUS, alwaysTrue(), columnStatistics(3, 3));
            testColumnStats(schema, ORDERS, ORDER_KEY, alwaysTrue(), columnStatistics(1_500_000 * scaleFactor, 1, 6_000_000 * scaleFactor));

            //constraints on columns other than ORDER_STATUS are not supported and are ignored
            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(CLERK, "NO SUCH CLERK"), columnStatistics(3, 3));
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(CLERK, "Clerk#000000001"), columnStatistics(1_500_000 * scaleFactor, 1, 6_000_000 * scaleFactor));

            //compound constraints are supported
            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(ORDER_STATUS, "F", "NO SUCH STATUS"), columnStatistics(1, 1));
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(ORDER_STATUS, "F", "NO SUCH STATUS"), rangeStatistics(3, 6_000_000 * scaleFactor));

            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(ORDER_STATUS, "F", "O"), columnStatistics(2, 2));
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(ORDER_STATUS, "F", "O"), rangeStatistics(1, 6_000_000 * scaleFactor));

            testColumnStats(schema, ORDERS, ORDER_STATUS, constraint(ORDER_STATUS, "F", "O", "P"), columnStatistics(3, 3));
            testColumnStats(schema, ORDERS, ORDER_KEY, constraint(ORDER_STATUS, "F", "O", "P"), columnStatistics(1_500_000 * scaleFactor, 1, 6_000_000 * scaleFactor));
        });
    }

    private void testColumnStats(String schema, TpchTable<?> table, TpchColumn<?> column, ColumnStatistics expectedStatistics)
    {
        testColumnStats(schema, table, column, alwaysTrue(), expectedStatistics);
    }

    private void testColumnStats(String schema, TpchTable<?> table, TpchColumn<?> column, Constraint<ColumnHandle> constraint, ColumnStatistics expected)
    {
        TpchTableHandle tableHandle = tpchMetadata.getTableHandle(session, new SchemaTableName(schema, table.getTableName()));
        TableStatistics tableStatistics = tpchMetadata.getTableStatistics(session, tableHandle, constraint);
        ColumnHandle columnHandle = tpchMetadata.getColumnHandles(session, tableHandle).get(column.getSimplifiedColumnName());

        ColumnStatistics actual = tableStatistics.getColumnStatistics().get(columnHandle);

        EstimateAssertion estimateAssertion = new EstimateAssertion(TOLERANCE);

        estimateAssertion.assertClose(actual.getDistinctValuesCount(), expected.getDistinctValuesCount(), "distinctValuesCount");
        estimateAssertion.assertClose(actual.getDataSize(), expected.getDataSize(), "dataSize");
        estimateAssertion.assertClose(actual.getNullsFraction(), expected.getNullsFraction(), "nullsFraction");
        estimateAssertion.assertClose(actual.getRange(), expected.getRange(), "range");
    }

    @Test
    public void testOrdersOrderStatusPredicatePushdown()
    {
        TpchTableHandle tableHandle = tpchMetadata.getTableHandle(session, new SchemaTableName("sf1", ORDERS.getTableName()));

        TupleDomain<ColumnHandle> domain;
        ConnectorTableLayoutResult tableLayout;

        domain = fixedValueTupleDomain(tpchMetadata, ORDER_STATUS, utf8Slice("P"));
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, ORDER_STATUS)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), TupleDomain.all(), session);
        assertTupleDomainEquals(tableLayout.getTableLayout().getPredicate(), domain, session);

        domain = fixedValueTupleDomain(tpchMetadata, ORDER_KEY, 42L);
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, ORDER_STATUS)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), domain, session);
        assertTupleDomainEquals(
                tableLayout.getTableLayout().getPredicate(),
                // The most important thing about the expected value that it is NOT TupleDomain.none() (or equivalent).
                // Using concrete expected value instead of checking TupleDomain::isNone to make sure the test doesn't pass on some other wrong value.
                TupleDomain.columnWiseUnion(
                        fixedValueTupleDomain(tpchMetadata, ORDER_STATUS, utf8Slice("F")),
                        fixedValueTupleDomain(tpchMetadata, ORDER_STATUS, utf8Slice("O")),
                        fixedValueTupleDomain(tpchMetadata, ORDER_STATUS, utf8Slice("P"))),
                session);
    }

    @Test
    public void testPartTypeAndPartContainerPredicatePushdown()
    {
        TpchTableHandle tableHandle = tpchMetadata.getTableHandle(session, new SchemaTableName("sf1", PART.getTableName()));

        TupleDomain<ColumnHandle> domain;
        ConnectorTableLayoutResult tableLayout;

        domain = fixedValueTupleDomain(tpchMetadata, PartColumn.TYPE, utf8Slice("SMALL BRUSHED COPPER"));
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, PartColumn.TYPE)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), TupleDomain.all(), session);
        assertTupleDomainEquals(
                filterOutColumnFromPredicate(tableLayout.getTableLayout().getPredicate(), tpchMetadata.toColumnHandle(PartColumn.CONTAINER)),
                domain,
                session);

        domain = fixedValueTupleDomain(tpchMetadata, PartColumn.TYPE, utf8Slice("UNKNOWN"));
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, PartColumn.TYPE)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), TupleDomain.all(), session);
        assertTupleDomainEquals(tableLayout.getTableLayout().getPredicate(), TupleDomain.none(), session);

        domain = fixedValueTupleDomain(tpchMetadata, PartColumn.CONTAINER, utf8Slice("SM BAG"));
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, PartColumn.CONTAINER)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), TupleDomain.all(), session);
        assertTupleDomainEquals(
                filterOutColumnFromPredicate(tableLayout.getTableLayout().getPredicate(), tpchMetadata.toColumnHandle(PartColumn.TYPE)),
                domain,
                session);

        domain = fixedValueTupleDomain(tpchMetadata, PartColumn.CONTAINER, utf8Slice("UNKNOWN"));
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, PartColumn.CONTAINER)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), TupleDomain.all(), session);
        assertTupleDomainEquals(tableLayout.getTableLayout().getPredicate(), TupleDomain.none(), session);

        domain = fixedValueTupleDomain(tpchMetadata, PartColumn.TYPE, utf8Slice("SMALL BRUSHED COPPER"), PartColumn.CONTAINER, utf8Slice("SM BAG"));
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, PartColumn.CONTAINER)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), TupleDomain.all(), session);
        assertTupleDomainEquals(tableLayout.getTableLayout().getPredicate(), domain, session);

        domain = fixedValueTupleDomain(tpchMetadata, PartColumn.TYPE, utf8Slice("UNKNOWN"), PartColumn.CONTAINER, utf8Slice("UNKNOWN"));
        tableLayout = getTableOnlyLayout(tpchMetadata, session, tableHandle, new Constraint<>(domain, convertToPredicate(domain, PartColumn.TYPE, PartColumn.CONTAINER)));
        assertTupleDomainEquals(tableLayout.getUnenforcedConstraint(), TupleDomain.all(), session);
        assertTupleDomainEquals(tableLayout.getTableLayout().getPredicate(), TupleDomain.none(), session);
    }

    private Predicate<Map<ColumnHandle, NullableValue>> convertToPredicate(TupleDomain<ColumnHandle> domain, TpchColumn... columns)
    {
        Preconditions.checkArgument(columns.length > 0, "No columns given");
        return bindings -> {
            for (TpchColumn column : columns) {
                ColumnHandle columnHandle = tpchMetadata.toColumnHandle(column);
                if (bindings.containsKey(columnHandle)) {
                    NullableValue nullableValue = requireNonNull(bindings.get(columnHandle), "binding is null");
                    if (!PredicateUtils.convertToPredicate(domain, tpchMetadata.toColumnHandle(column)).test(nullableValue)) {
                        return false;
                    }
                }
            }
            return true;
        };
    }

    private void assertTupleDomainEquals(TupleDomain<?> actual, TupleDomain<?> expected, ConnectorSession session)
    {
        if (!Objects.equals(actual, expected)) {
            fail(format("expected [%s] but found [%s]", expected.toString(session), actual.toString(session)));
        }
    }

    private Constraint<ColumnHandle> constraint(TpchColumn<?> column, String... values)
    {
        List<TupleDomain<ColumnHandle>> valueDomains = stream(values)
                .map(value -> fixedValueTupleDomain(tpchMetadata, column, utf8Slice(value)))
                .collect(toList());
        TupleDomain<ColumnHandle> domain = TupleDomain.columnWiseUnion(valueDomains);
        return new Constraint<>(domain, convertToPredicate(domain, column));
    }

    private static TupleDomain<ColumnHandle> fixedValueTupleDomain(TpchMetadata tpchMetadata, TpchColumn<?> column, Object value)
    {
        requireNonNull(column, "column is null");
        requireNonNull(value, "value is null");
        return TupleDomain.fromFixedValues(
                ImmutableMap.of(tpchMetadata.toColumnHandle(column), new NullableValue(getPrestoType(column), value)));
    }

    private static TupleDomain<ColumnHandle> fixedValueTupleDomain(TpchMetadata tpchMetadata, TpchColumn<?> column1, Object value1, TpchColumn<?> column2, Object value2)
    {
        return TupleDomain.fromFixedValues(
                ImmutableMap.of(
                        tpchMetadata.toColumnHandle(column1), new NullableValue(getPrestoType(column1), value1),
                        tpchMetadata.toColumnHandle(column2), new NullableValue(getPrestoType(column2), value2)));
    }

    private static ConnectorTableLayoutResult getTableOnlyLayout(TpchMetadata tpchMetadata, ConnectorSession session, ConnectorTableHandle tableHandle, Constraint<ColumnHandle> constraint)
    {
        List<ConnectorTableLayoutResult> tableLayouts = tpchMetadata.getTableLayouts(session, tableHandle, constraint, Optional.empty());
        return getOnlyElement(tableLayouts);
    }

    private ColumnStatistics noColumnStatistics()
    {
        return createColumnStatistics(Optional.of(0.0), Optional.empty(), Optional.of(0.0));
    }

    private ColumnStatistics columnStatistics(double distinctValuesCount, double dataSize)
    {
        return createColumnStatistics(Optional.of(distinctValuesCount), Optional.empty(), Optional.of(dataSize));
    }

    private ColumnStatistics columnStatistics(double distinctValuesCount, double min, double max)
    {
        return createColumnStatistics(Optional.of(distinctValuesCount), Optional.of(new DoubleRange(min, max)), Optional.empty());
    }

    private ColumnStatistics rangeStatistics(double min, double max)
    {
        return createColumnStatistics(Optional.empty(), Optional.of(new DoubleRange(min, max)), Optional.empty());
    }

    private static ColumnStatistics createColumnStatistics(Optional<Double> distinctValuesCount, Optional<DoubleRange> range, Optional<Double> dataSize)
    {
        return ColumnStatistics.builder()
                .setNullsFraction(Estimate.zero())
                .setDistinctValuesCount(toEstimate(distinctValuesCount))
                .setRange(range)
                .setDataSize(toEstimate(dataSize))
                .build();
    }

    private static Estimate toEstimate(Optional<Double> value)
    {
        return value
                .map(Estimate::of)
                .orElse(Estimate.unknown());
    }
}


text:
Simple php scripts for creating thumbnails.

Written in 2008, not tested on modern php :P


text:
import React from 'react';
import PropTypes from 'prop-types';
import {Disposable} from 'event-kit';

import {autobind, extractProps} from '../helpers';
import {RefHolderPropType} from '../prop-types';
import {TextEditorContext} from './atom-text-editor';
import RefHolder from '../models/ref-holder';

const gutterProps = {
  name: PropTypes.string.isRequired,
  priority: PropTypes.number.isRequired,
  visible: PropTypes.bool,
  type: PropTypes.oneOf(['line-number', 'decorated']),
  labelFn: PropTypes.func,
  onMouseDown: PropTypes.func,
  onMouseMove: PropTypes.func,
};

class BareGutter extends React.Component {
  static propTypes = {
    editorHolder: RefHolderPropType.isRequired,
    className: PropTypes.string,
    ...gutterProps,
  }

  static defaultProps = {
    visible: true,
    type: 'decorated',
    labelFn: () => {},
  }

  constructor(props) {
    super(props);
    autobind(this, 'observeEditor', 'forceUpdate');

    this.state = {
      gutter: null,
    };

    this.sub = new Disposable();
  }

  componentDidMount() {
    this.sub = this.props.editorHolder.observe(this.observeEditor);
  }

  componentDidUpdate(prevProps) {
    if (this.props.editorHolder !== prevProps.editorHolder) {
      this.sub.dispose();
      this.sub = this.props.editorHolder.observe(this.observeEditor);
    }
  }

  componentWillUnmount() {
    if (this.state.gutter !== null) {
      try {
        this.state.gutter.destroy();
      } catch (e) {
        // Gutter already destroyed. Disregard.
      }
    }
    this.sub.dispose();
  }

  render() {
    return null;
  }

  observeEditor(editor) {
    this.setState((prevState, props) => {
      if (prevState.gutter !== null) {
        prevState.gutter.destroy();
      }

      const options = extractProps(props, gutterProps);
      options.class = props.className;
      return {gutter: editor.addGutter(options)};
    });
  }
}

export default class Gutter extends React.Component {
  static propTypes = {
    editor: PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.state = {
      editorHolder: RefHolder.on(this.props.editor),
    };
  }

  static getDerivedStateFromProps(props, state) {
    const editorChanged = state.editorHolder.map(editor => editor !== props.editor).getOr(props.editor !== undefined);
    return editorChanged ? RefHolder.on(props.editor) : null;
  }

  render() {
    if (!this.state.editorHolder.isEmpty()) {
      return <BareGutter {...this.props} editorHolder={this.state.editorHolder} />;
    }

    return (
      <TextEditorContext.Consumer>
        {editorHolder => (
          <BareGutter {...this.props} editorHolder={editorHolder} />
        )}
      </TextEditorContext.Consumer>
    );
  }
}


text:
<?php

namespace QCloudSDK\Core\Exceptions;

use QCloudSDK\Core\Exception;

class ClientException extends Exception
{

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_18.c
Label Definition File: CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close.label.xml
Template File: source-sinks-18.tmpl.c
*/
/*
 * @description
 * CWE: 775 Missing Release of File Descriptor or Handle After Effective Lifetime
 * BadSource:  Open a file using CreateFile()
 * Sinks:
 *    GoodSink: Close the file using CloseHandle()
 *    BadSink : Do not close file
 * Flow Variant: 18 Control flow: goto statements
 *
 * */

#include "std_testcase.h"

#include <windows.h>

#ifndef OMITBAD

void CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_18_bad()
{
    HANDLE data;
    /* Initialize data */
    data = INVALID_HANDLE_VALUE;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    goto sink;
sink:
    /* FLAW: No attempt to close the file */
    ; /* empty statement needed for some flow variants */
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() - use badsource and goodsink by reversing the blocks on the goto statement */
static void goodB2G()
{
    HANDLE data;
    /* Initialize data */
    data = INVALID_HANDLE_VALUE;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = CreateFile("BadSource_w32CreateFile.txt",
                      (GENERIC_WRITE|GENERIC_READ),
                      0,
                      NULL,
                      OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL,
                      NULL);
    goto sink;
sink:
    /* FIX: If the file is still opened, close it */
    if (data != INVALID_HANDLE_VALUE)
    {
        CloseHandle(data);
    }
}

void CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_18_good()
{
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_18_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE775_Missing_Release_of_File_Descriptor_or_Handle__w32CreateFile_no_close_18_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_AUDIO_STREAM_SENDER_THREAD_H_
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_AUDIO_STREAM_SENDER_THREAD_H_

#include <string>
#include "utils/macro.h"
#include "utils/threads/thread_delegate.h"
#include "utils/conditional_variable.h"
#include "utils/lock.h"

namespace NsSmartDeviceLink {
namespace NsSmartObjects {
class SmartObject;
}
}

namespace application_manager {
  class ApplicationManager;
}

namespace media_manager {

typedef enum {
  SR_INVALID = -1,
  SR_8KHZ = 0,
  SR_16KHZ = 1,
  SR_22KHZ = 2,
  SR_44KHZ = 3
} SamplingRate;

typedef enum {
  ACQ_INVALID = -1,
  ACQ_8_BIT = 0,
  ACQ_16_BIT = 1
} AudioCaptureQuality;

typedef enum {
  AT_INVALID = -1,
  AT_PCM = 0
} AudioType;

/*
 * @brief AudioStreamSenderThread class used to read binary data written from microphone
 * and send it every 1 second to mobile device.
 */
class AudioStreamSenderThread : public threads::ThreadDelegate {
  public:
    /*
     * @brief AudioStreamSenderThread class constructor
     *
     * @param session_key     Session key of connection for Mobile side
     * @param correlation_id  Correlation id for response for Mobile side
     */
    AudioStreamSenderThread(const std::string& fileName,
                            uint32_t session_key,
                            application_manager::ApplicationManager& app_mngr);

    /*
     * @brief AudioStreamSenderThread class destructor
     */
    ~AudioStreamSenderThread();

    /**
     * @brief Thread procedure.
     */
    void threadMain();

    /*
     * @brief Retrieve session key
     *
     * @return Stored session key
     */
    uint32_t session_key() const;

    void exitThreadMain();

  private:
    /*
     * @brief Sends AudioPassThru request
     */
    bool SendEndAudioPassThru();

    void sendAudioChunkToMobile();

    bool getShouldBeStopped();
    void setShouldBeStopped(bool should_stop);

    uint32_t                              session_key_;
    const std::string                     fileName_;
    int32_t                               offset_;
    volatile bool                         shouldBeStoped_;
    sync_primitives::Lock                 shouldBeStoped_lock_;
    sync_primitives::ConditionalVariable  shouldBeStoped_cv_;

    static const int32_t                  kAudioPassThruTimeout;

    application_manager::ApplicationManager& application_manager_;

    DISALLOW_COPY_AND_ASSIGN(AudioStreamSenderThread);
};
}  // namespace media_manager

#endif  // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_AUDIO_STREAM_SENDER_THREAD_H_


text:
(function() {
  var globalOptions, logger, main, optimist, path, usage,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  optimist = require('optimist');

  path = require('path');

  logger = require('./../core/logger').logger;

  usage = "usage: wintersmith [options] [command]\n\ncommands:\n\n  " + 'build'.bold + " [options] - build a site\n  " + 'preview'.bold + " [options] - run local webserver\n  " + 'new'.bold + " <location> - create a new site\n  " + 'plugin'.bold + " - manage plugins\n\n  also see [command] --help\n\nglobal options:\n\n  -v, --verbose   show debug information\n  -q, --quiet     only output critical errors\n  -V, --version   output version and exit\n  -h, --help      show help\n";

  globalOptions = {
    verbose: {
      alias: 'v'
    },
    quiet: {
      alias: 'q'
    },
    version: {
      alias: 'V'
    },
    help: {
      alias: 'h'
    }
  };

  main = function() {
    var argv, cmd, error;
    argv = optimist.options(globalOptions).argv;
    if (argv._[0] != null) {
      try {
        cmd = require("./" + argv._[0]);
      } catch (_error) {
        error = _error;
        if (error.code === 'MODULE_NOT_FOUND') {
          console.log("'" + argv._[0] + "' - no such command");
          process.exit(1);
        } else {
          throw error;
        }
      }
    }
    if (argv.version) {
      console.log(require('./version'));
      process.exit(0);
    }
    if (argv.help || !cmd) {
      console.log(cmd ? cmd.usage : usage);
      process.exit(0);
    }
    if (argv.verbose) {
      if (__indexOf.call(process.argv, '-vv') >= 0) {
        logger.transports.cli.level = 'silly';
      } else {
        logger.transports.cli.level = 'verbose';
      }
    }
    if (argv.quiet) {
      logger.transports.cli.quiet = true;
    }
    if (cmd) {
      return cmd(optimist.options(globalOptions).options(cmd.options).argv);
    }
  };

  module.exports.main = main;

}).call(this);


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.swfarm.biz.chain.bo.StockKeepingUnitFeedback" table="stockKeepingUnitFeedback">
		<id name="id" column="id">
			<generator class="native" />
		</id>
		<property name="productQuality" column="productquality" />
		<property name="packageQuality" column="packagequality" />
		<property name="comments" column="comments" type="text"/>
		<property name="submitTime" column="submittime" />
		<property name="articleNumber" column="articleNumber" />
		<property name="productManagerNo" column="productManagerNo" />
		<many-to-one name="submitUser" column="user_id"
			class="com.swfarm.biz.oa.bo.User">
		</many-to-one>
		<many-to-one name="stockKeepingUnit" column="stockKeepingUnit_id"
			class="com.swfarm.biz.product.bo.StockKeepingUnit">
		</many-to-one>
	</class>
</hibernate-mapping>


text:
@interface RBTableView : UITableView <UITableViewDataSource, UITableViewDelegate>

@property NSArray *modelData;

+ (instancetype)create:(RBTableViewModel *)model;
- (void)update:(RBTableViewModel *)model;

@end


text:
package opendct.nanohttpd;

import com.google.gson.Gson;
import fi.iki.elonen.NanoHTTPD;
import opendct.config.options.DeviceOptionException;
import opendct.nanohttpd.pojo.JsonException;

import java.io.IOException;
import java.io.InputStream;

public class HttpUtil {
    public static final String JSON_OK = "{ \"message\": \"OK\" }";
    private static final Gson gson = new Gson();

    public static String getPostContent(NanoHTTPD.IHTTPSession session) {
        InputStream inputStream = null;
        try {
            inputStream = session.getInputStream();
            int contentLength;

            try {
                contentLength = Integer.parseInt(session.getHeaders().get("content-length"));
            } catch (NumberFormatException e) {
                try {
                    contentLength = inputStream.available();
                } catch (IOException e1) {
                    return "";
                }
            }

            if (contentLength == 0) {
                return "";
            }

            int index = 0;
            byte response[] = new byte[contentLength];

            while (contentLength > index) {
                int readBytes;
                try {
                    readBytes = inputStream.read(response, index, contentLength - index);
                } catch (IOException e) {
                    break;
                }
                index += readBytes;
            }

            return new String(response, 0, index).trim();
        } finally {
            // Do not close this here. It will close the stream needed for the response.
            /*if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {}
            }*/
        }
    }

    public static NanoHTTPD.Response returnException(DeviceOptionException e) {
        return NanoHTTPD.newFixedLengthResponse(
                NanoHTTPD.Response.Status.FORBIDDEN, "application/json",
                gson.toJson(new JsonException(e)));
    }

    public static NanoHTTPD.Response returnException(JsonException e) {
        return NanoHTTPD.newFixedLengthResponse(
                NanoHTTPD.Response.Status.FORBIDDEN, "application/json",
                gson.toJson(e));
    }

    public static NanoHTTPD.Response returnException(String object, String message) {
        return NanoHTTPD.newFixedLengthResponse(
                NanoHTTPD.Response.Status.FORBIDDEN, "application/json",
                gson.toJson(new JsonException(object, message)));
    }
}


text:
leetcode-cpp
============

record my solutions


text:
typedef struct z_stream_s z_stream;

namespace remoting {

// A lossless compressor using zlib.
class CompressorZlib : public Compressor {
 public:
  CompressorZlib();
  virtual ~CompressorZlib();

  // Compressor implementations.
  virtual bool Process(const uint8* input_data,
                       int input_size,
                       uint8* output_data,
                       int output_size,
                       CompressorFlush flush,
                       int* consumed,
                       int* written) OVERRIDE;

  virtual void Reset() OVERRIDE;

 private:
  scoped_ptr<z_stream> stream_;
};

}  // namespace remoting

#endif  // REMOTING_BASE_COMPRESSOR_ZLIB_H_


text:
import matchAllFilter from '../../src/filters/match-all-filter'
import {expect} from 'chai'

describe('matchAllFilter', () => {

  it('should create a simple match_all filter', () => {
    let result = matchAllFilter()
    expect(result).to.eql({
      match_all: {}
    })
  })

})


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <php.h>
#include "php_zephir.h"

int _zephir_array_isset_quick_string(const zval *arr, const char *index, uint index_length, unsigned long key) {
	if (Z_TYPE_P(arr) == IS_ARRAY) {
		return zend_hash_quick_exists(Z_ARRVAL_P(arr), index, index_length, key);
	}
	return 0;
}

int _zephir_array_fetch_string(zval **return_value, zval *arr, const char *index, uint index_length TSRMLS_DC){

	zval **zv;

	if (zend_hash_find(Z_ARRVAL_P(arr), index, index_length, (void**) &zv) == SUCCESS) {
		*return_value = *zv;
		return SUCCESS;
	}

	*return_value = EG(uninitialized_zval_ptr);
	return FAILURE;
}

int _zephir_hash_fetch_string(zval **return_value, HashTable *arr, const char *index, uint index_length TSRMLS_DC){

	zval **zv;

	if (zend_hash_find(arr, index, index_length, (void**) &zv) == SUCCESS) {
		*return_value = *zv;
		return SUCCESS;
	}

	*return_value = EG(uninitialized_zval_ptr);
	return FAILURE;
}


text:
<?php

namespace Sandbox\MainBundle\Document;

use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Cmf\Component\Routing\RouteAwareInterface;

/**
 * A document that we map to a template to be used with the generic content
 * controller
 *
 * @PHPCRODM\Document(referenceable=true)
 */
class DemoTemplateContent implements RouteAwareInterface
{
    /**
     * to create the document at the specified location. read only for existing documents.
     *
     * @PHPCRODM\Id
     */
    protected $path;

    /**
     * @PHPCRODM\Node
     */
    public $node;

    /**
     * @Assert\NotBlank
     * @PHPCRODM\String()
     */
    public $name;

    /**
     * @Assert\NotBlank
     * @PHPCRODM\String()
     */
    public $title;

    /**
     * @Assert\NotBlank
     * @PHPCRODM\String()
     */
    public $body;

    /**
     * @PHPCRODM\Referrers(referringDocument="Symfony\Cmf\Bundle\RoutingBundle\Document\Route", referencedBy="routeContent")
     */
    public $routes;

    /**
     * Set repository path of this navigation item for creation
     */
    public function setPath($path)
    {
      $this->path = $path;
    }

    public function getPath()
    {
      return $this->path;
    }

    public function getContent()
    {
        return $this->body;
    }

    public function setContent($content)
    {
        $this->body = $content;
    }

    /**
     * @return array of route objects that point to this content
     */
    public function getRoutes()
    {
        return $this->routes->toArray();
    }

    public function __toString()
    {
        return $this->name;
    }
}