text:
// The class this file defines and its required classes
R.Engine.define({
    "class":"R.text.AbstractTextRenderer",
    "requires":[
        "R.components.Base"
    ]
});

/**
 * @class Abstract class that provides the basic interface for all
 *        text render objects used by the {@link R.text.TextRenderer}.
 *
 * @constructor
 * @param componentName {String} The name of the renderer
 * @param priority {Number} The priority of the rendering order. Default: <tt>0.1</tt>
 * @extends R.components.Base
 */
R.text.AbstractTextRenderer = function () {
    return R.components.Base.extend(/** @scope R.text.AbstractTextRenderer.prototype */{

        text:null,
        color:"#000000",
        alignment:null,
        weight:null,
        size:1,
        font:null,
        style:null,
        lineSpacing:7,

        /** @private */
        constructor:function (componentName, priority) {
            this.base(componentName || "TextRenderObject", R.components.Base.TYPE_RENDERING, priority || 0.1);

            this.text = "";
            this.size = 1;
            this.weight = 1;
            this.font = null;
            this.style = null;
            this.alignment = R.text.AbstractTextRenderer.ALIGN_LEFT;
            this.lineSpacing = 7;
        },

        /**
         * Releases the object back into the object pool.  See {@link R.engine.PooledObject#release}
         * for more information.
         */
        release:function () {
            this.base();
            this.text = null;
            this.color = "#000000";
            this.size = 1;
            this.weight = null;
            this.font = null;
            this.style = null;
            this.alignment = null;
            this.lineSpacing = 7;
        },

        /**
         * Return <tt>true</tt> if the text renderer is native to the context.
         * @return {Boolean}
         */
        isNative:function () {
            return false;
        },

        /**
         * Get the text being rendered
         * @return {String} The text this renderer will draw
         */
        getText:function () {
            return this.text;
        },

        /**
         * Set the text to be rendered
         *
         * @param text {String} The text to render
         */
        setText:function (text) {
            this.text = text;
        },

        /**
         * Set the font of the text to be renderer
         * @param font {String} The font name
         */
        setTextFont:function (font) {
            this.font = font;
        },

        /**
         * Get the font of the text to be rendered
         * @return {String} The font name
         */
        getTextFont:function () {
            return this.font;
        },

        /**
         * Set the weight of the text to render.  Higher weights
         * are bolder text.
         *
         * @param weight {Number} The weight of the text.
         */
        setTextWeight:function (weight) {
            this.weight = weight;
        },

        /**
         * Get the weight of the text to render.
         * @return {Number} The weight of the text
         */
        getTextWeight:function () {
            return this.weight;
        },

        /**
         * Set the style of the text, usually italics or normal, for the text renderer.
         * @param style {Object} The style of the text
         */
        setTextStyle:function (style) {
            this.style = style;
        },

        /**
         * Get the style of the text for the renderer.
         * @return {Object} The style of the text
         */
        getTextStyle:function () {
            return this.style;
        },

        /**
         * Set the alignment of the text.
         *
         * @param alignment {Object} The alignment for the text renderer
         */
        setTextAlignment:function (alignment) {
            this.alignment = alignment;
            // Adjust the origin, based on the alignment
            var boundingBox = this.getGameObject().getBoundingBox();
            var center = boundingBox.getCenter();
            var textOrigin = R.math.Point2D.create(0, 0);
            if (this.alignment === R.text.AbstractTextRenderer.ALIGN_RIGHT) {
                textOrigin.set(center.x + boundingBox.getHalfWidth(), 0);
            }
            else if (this.alignment === R.text.AbstractTextRenderer.ALIGN_LEFT) {
                textOrigin.set(center.x - boundingBox.getHalfWidth(), 0);
            }
            else {
                textOrigin.set(center.x, 0);
            }

            this.getGameObject().setOrigin(textOrigin);
        },

        /**
         * Get the alignment of the text.
         * @return {Object} The alignment of the text renderer
         */
        getTextAlignment:function () {
            return this.alignment;
        },

        /**
         * Set the scaling of the text
         * @param size {Number}
         */
        setSize:function (size) {
            this.size = size;
        },

        /**
         * Get the scaling of the text
         * @return {Number}
         */
        getSize:function () {
            return this.size;
        },

        /**
         * Set the color of the text to render.
         *
         * @param color {String} The color of the text to render
         */
        setColor:function (color) {
            this.color = color;
        },

        /**
         * Get the color of the text to render.
         * @return {String} The text color
         */
        getColor:function () {
            return this.color;
        },

        /**
         * Set the line spacing between lines of text in a multi-line text string.
         * Multi-line text is separated by the carriage return (0xA).
         *
         * @param lineSpacing {Number} Line spacing (default: 7)
         */
        setLineSpacing:function (lineSpacing) {
            this.lineSpacing = lineSpacing;
        },

        /**
         * Get the space between lines in multi-line text.
         * @return {Number}
         */
        getLineSpacing:function () {
            return this.lineSpacing;
        }

    }, /** @scope R.text.AbstractTextRenderer.prototype */{

        /**
         * Get the class name of this object
         * @return {String} The string "R.text.AbstractTextRenderer"
         */
        getClassName:function () {
            return "R.text.AbstractTextRenderer";
        },

        /**
         * Align text with the left edge of the string at the point specified.
         * @type Number
         */
        ALIGN_LEFT:0,

        /**
         * Align text with the right edge of the string at the point specified
         * @type Number
         */
        ALIGN_RIGHT:1,

        /**
         * Align text with the center of the string at the point specified
         * @type Number
         */
        ALIGN_CENTER:2

    });

};


text:
#include "cbase.h"
#include "experience_stat_line.h"
#include "vgui_controls/AnimationController.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/ImagePanel.h"
#include "vgui/isurface.h"
#include "StatsBar.h"
#include "asw_gamerules.h"
#include "c_asw_player.h"
#include "c_asw_game_resource.h"
#include "c_asw_marine_resource.h"
#include "asw_marine_profile.h"
#include "asw_medals_shared.h"
#include "BriefingTooltip.h"
#include "asw_achievements.h"
#include "c_asw_debrief_stats.h"
#include "asw_briefing.h"
#include "vgui/ILocalize.h"

// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>

using namespace vgui;

ConVar asw_stats_reduce("asw_stats_reduce", "0", FCVAR_ARCHIVE, "Show 100+ kills instead of 1234 kills on the debriefing screen.", true, 0, true, 1);

ExperienceStatLine::ExperienceStatLine( Panel *parent, const char *name, CASW_Earned_XP_t XPType ) : vgui::EditablePanel( parent, name )
{
	m_XPType = XPType;
	m_pStatNum = new vgui::Label( this, "StatNum", "" );
	m_pTitle = new vgui::Label( this, "Title", "" );
	m_pCounter = new vgui::Label( this, "Counter", "" );
	m_pIcon = new vgui::ImagePanel( this, "Icon" );
	m_pIcon->SetShouldScaleImage( true );
	m_pStatsBar = new StatsBar( this, "StatsBar" );
	m_pStatsBar->UseExternalCounter( m_pCounter );
	m_pStatsBar->SetShowMaxOnCounter( true );
	m_pStatsBar->m_flBorder = 0.0f;

	switch( XPType )
	{
		case ASW_XP_MISSION: m_pTitle->SetText( "#asw_xp_mission" ); break;
		case ASW_XP_KILLS: m_pTitle->SetText( "#asw_xp_kills" ); break;
		case ASW_XP_TIME:
		{
			int nParTime = GetDebriefStats()->GetSpeedrunTime() + 5.0f * 60.0f;
			int nMinutes = nParTime / 60;
			int nSeconds = nParTime - nMinutes * 60;

			wchar_t minutes[ 5 ];
			V_snwprintf( minutes, sizeof( minutes ), L"%d", nMinutes );
			wchar_t seconds[ 3 ];
			V_snwprintf( seconds, sizeof( seconds ), L"%02d", nSeconds );

			wchar_t wszTitle[ 128 ];
			g_pVGuiLocalize->ConstructString( wszTitle, sizeof( wszTitle ), g_pVGuiLocalize->Find( "#asw_xp_time" ), 2, minutes, seconds );

			m_pTitle->SetText( wszTitle );
			break;
		}
		case ASW_XP_FRIENDLY_FIRE: m_pTitle->SetText( "#asw_xp_friendly_fire" ); break;
		case ASW_XP_DAMAGE_TAKEN: m_pTitle->SetText( "#asw_xp_damage_taken" ); break;
		case ASW_XP_HEALING: m_pTitle->SetText( "#asw_xp_healing" ); break;
		case ASW_XP_HACKING: m_pTitle->SetText( "#asw_xp_hacking" ); break;
	}
}

ExperienceStatLine::~ExperienceStatLine()
{

}

void ExperienceStatLine::PerformLayout()
{
	BaseClass::PerformLayout();
}

void ExperienceStatLine::OnThink()
{
}

void ExperienceStatLine::ApplySchemeSettings( vgui::IScheme *pScheme )
{
	BaseClass::ApplySchemeSettings( pScheme );

	LoadControlSettings( "resource/UI/ExperienceStatLine.res" );

	// no longer used / icons don't exist anymore
	/*
	switch( m_XPType )
	{
		case ASW_XP_MISSION: m_pIcon->SetImage( "swarm/Briefing/statshots" ); break;
		case ASW_XP_KILLS: m_pIcon->SetImage( "swarm/Briefing/statkilled" ); break;
		case ASW_XP_TIME: m_pIcon->SetImage( "swarm/Briefing/stattime" ); break;
		case ASW_XP_FRIENDLY_FIRE: m_pIcon->SetImage( "swarm/Briefing/statfriendly" ); break;
		case ASW_XP_DAMAGE_TAKEN: m_pIcon->SetImage( "swarm/Briefing/statdamage" ); break;
		case ASW_XP_HEALING: m_pIcon->SetImage( "swarm/Briefing/statheal" ); break;
		case ASW_XP_HACKING: m_pIcon->SetImage( "swarm/Briefing/stathack" ); break;
	}
	*/

	UpdateVisibility( ToASW_Player( m_hPlayer.Get() ) );
}

void ExperienceStatLine::UpdateVisibility( C_ASW_Player *pPlayer )
{
	if ( !pPlayer )
	{
		pPlayer = ToASW_Player( m_hPlayer.Get() );
	}

	if ( !pPlayer || !ASWGameResource() )
		return;

	C_ASW_Marine_Resource *pMR = ASWGameResource()->GetFirstMarineResourceForPlayer( pPlayer );
	if ( !pMR )
		return;

	bool bMedic = pMR->GetProfile() && pMR->GetProfile()->GetMarineClass() == MARINE_CLASS_MEDIC;
	bool bTech = pMR->GetProfile() && pMR->GetProfile()->GetMarineClass() == MARINE_CLASS_TECH;

	if ( !Briefing()->IsOfflineGame() )
	{
		if ( ( m_XPType == ASW_XP_HEALING && !bMedic ) || ( m_XPType == ASW_XP_HACKING && !bTech ) )
		{
			SetVisible( false );
			return;
		}
	}

	if ( pPlayer->GetStatNumXP( ASW_XP_MISSION ) < 100 )
	{
		// Don't do these if we failed
		if ( m_XPType == ASW_XP_DAMAGE_TAKEN || m_XPType == ASW_XP_FRIENDLY_FIRE || m_XPType == ASW_XP_TIME )
		{
			SetVisible( false );
			return;
		}
	}

	SetVisible( true );
}

void ExperienceStatLine::InitFor( C_ASW_Player *pPlayer )
{
	m_hPlayer = pPlayer;
	if ( !pPlayer )
		return;

	float flRate = 100.0f / 2.0f;
	float flMissionRate = 1000.0f / 2.0f;
	switch( m_XPType )
	{
		case ASW_XP_MISSION:
		{
			wchar_t num[ 8 ];
			V_snwprintf( num, sizeof( num ), L"%d%%", pPlayer->GetStatNumXP( ASW_XP_MISSION ) );
			m_pStatNum->SetText( num );

			m_pStatsBar->Init( 0, pPlayer->GetEarnedXP( ASW_XP_MISSION ), flMissionRate, true, false );
			m_pStatsBar->AddMinMax( 0, 1000 );
			break;
		}

		case ASW_XP_KILLS:
		{
			wchar_t num[ 8 ];
			if ( pPlayer->GetStatNumXP( ASW_XP_KILLS ) > 100 && asw_stats_reduce.GetBool() )
			{
				V_snwprintf( num, sizeof( num ), L"100+" );
			}
			else
			{
				V_snwprintf( num, sizeof( num ), L"%d", pPlayer->GetStatNumXP( ASW_XP_KILLS ) );
			}
			m_pStatNum->SetText( num );

			m_pStatsBar->Init( 0, pPlayer->GetEarnedXP( ASW_XP_KILLS ), flRate, true, false );
			m_pStatsBar->AddMinMax( 0, 100 );
			break;
		}

		case ASW_XP_TIME:
		{
			int nTime = pPlayer->GetStatNumXP( ASW_XP_TIME );
			wchar_t num[ 8 ];

			int nMinutes = nTime / 60;
			int nSeconds = nTime - nMinutes * 60;

			V_snwprintf( num, sizeof( num ), L"%d:%02d", nMinutes, nSeconds );

			m_pStatNum->SetText( num );

			m_pStatsBar->Init( 0, pPlayer->GetEarnedXP( ASW_XP_TIME ), flRate, true, false );
			m_pStatsBar->AddMinMax( 0, 100 );
			break;
		}

		case ASW_XP_FRIENDLY_FIRE:
		{
			wchar_t num[ 8 ];
			if ( pPlayer->GetStatNumXP( ASW_XP_FRIENDLY_FIRE ) > 100 && asw_stats_reduce.GetBool() )
			{
				V_snwprintf( num, sizeof( num ), L"100+" );
			}
			else
			{
				V_snwprintf( num, sizeof( num ), L"%d", pPlayer->GetStatNumXP( ASW_XP_FRIENDLY_FIRE ) );
			}
			m_pStatNum->SetText( num );

			m_pStatsBar->Init( 0, pPlayer->GetEarnedXP( ASW_XP_FRIENDLY_FIRE ), flRate, true, false );
			m_pStatsBar->AddMinMax( 0, 100 );
			break;
		}

		case ASW_XP_DAMAGE_TAKEN:
		{
			wchar_t num[ 8 ];
			if ( pPlayer->GetStatNumXP( ASW_XP_DAMAGE_TAKEN ) > 100 && asw_stats_reduce.GetBool() )
			{
				V_snwprintf( num, sizeof( num ), L"100+" );
			}
			else
			{
				V_snwprintf( num, sizeof( num ), L"%d", pPlayer->GetStatNumXP( ASW_XP_DAMAGE_TAKEN ) );
			}
			m_pStatNum->SetText( num );

			m_pStatsBar->Init( 0, pPlayer->GetEarnedXP( ASW_XP_DAMAGE_TAKEN ), flRate, true, false );
			m_pStatsBar->AddMinMax( 0, 100 );
			break;
		}

		case ASW_XP_HEALING:
		{
			wchar_t num[ 8 ];
			if ( pPlayer->GetStatNumXP( ASW_XP_HEALING ) > 500 && asw_stats_reduce.GetBool() )
			{
				V_snwprintf( num, sizeof( num ), L"500+" );
			}
			else
			{
				V_snwprintf( num, sizeof( num ), L"%d", pPlayer->GetStatNumXP( ASW_XP_HEALING ) );
			}
			m_pStatNum->SetText( num );

			m_pStatsBar->Init( 0, pPlayer->GetEarnedXP( ASW_XP_HEALING ), flRate, true, false );
			m_pStatsBar->AddMinMax( 0, 50 );
			break;
		}

		case ASW_XP_HACKING:
		{
			wchar_t num[ 8 ];
			if ( pPlayer->GetStatNumXP( ASW_XP_HACKING ) > 2 && asw_stats_reduce.GetBool() )
			{
				V_snwprintf( num, sizeof( num ), L"2+" );
			}
			else
			{
				V_snwprintf( num, sizeof( num ), L"%d", pPlayer->GetStatNumXP( ASW_XP_HACKING ) );
			}
			m_pStatNum->SetText( num );

			m_pStatsBar->Init( 0, pPlayer->GetEarnedXP( ASW_XP_HACKING ), flRate, true, false );
			m_pStatsBar->AddMinMax( 0, 50 );
			break;
		}
	}

	m_pStatsBar->SetStartCountingTime( gpGlobals->curtime + 7.0f + 0.5f * (int) m_XPType );

	UpdateVisibility( pPlayer );
}

void ExperienceStatLine::SetVisible(bool state)
{
	BaseClass::SetVisible( state );
}

// ===================================================

MedalStatLine::MedalStatLine( Panel *parent, const char *name ) : vgui::EditablePanel( parent, name )
{
	m_pTitle = new vgui::Label( this, "Title", "" );
	m_pDescription = new vgui::Label( this, "Description", "" );
	m_pCounter = new vgui::Label( this, "Counter", "" );
	m_pIcon = new vgui::ImagePanel( this, "Icon" );
	m_pIcon->SetShouldScaleImage( true );

	m_nAchievementIndex = -1;
	m_nMedalIndex = -1;

	m_szMedalName[0] = '\0';
	m_szMedalDescription[0] = '\0';
	m_bShowTooltip = true;
	m_nXP = 0;
}

MedalStatLine::~MedalStatLine()
{

}

void MedalStatLine::PerformLayout()
{
	BaseClass::PerformLayout();
}

BriefingTooltip* MedalStatLine::GetTooltip()
{
	if ( m_hTooltip.Get() )
		return m_hTooltip.Get();

	return g_hBriefingTooltip.Get();
}

void MedalStatLine::OnThink()
{
	if ( ( m_nMedalIndex != -1 || m_nAchievementIndex != -1 ) && m_bShowTooltip && IsCursorOver()
		&& GetTooltip() && GetTooltip()->GetTooltipPanel()!= this
		&& IsFullyVisible())
	{
		int tx, ty, w, h;
		tx = ty = 0;
		LocalToScreen(tx, ty);
		GetSize(w, h);
		tx += w * 0.5f;
		ty -= h * 0.01f;
		GetTooltip()->SetTooltip(this, m_szMedalName, m_szMedalDescription,
			tx, ty);
	}
}

void MedalStatLine::ApplySchemeSettings( vgui::IScheme *pScheme )
{
	BaseClass::ApplySchemeSettings( pScheme );

	LoadControlSettings( "resource/UI/MedalStatLine.res" );

	if ( m_nMedalIndex != -1 )
	{
		//int nMedalImage = m_nMedalIndex;
		bool bCheckSingleplayerTooltip = false;
// 		if ( nMedalImage >= 44 && nMedalImage <= 51 )	// speedrun
// 		{
// 			nMedalImage = 44;
// 			bCheckSingleplayerTooltip = true;
// 		}

		if ( ASWGameRules() )
		{
			int nAchievementIndex = GetAchievementIndexForMedal( m_nMedalIndex );
			if ( nAchievementIndex != -1 )
			{
				CAchievementMgr *pAchievementMgr = dynamic_cast<CAchievementMgr *>( engine->GetAchievementMgr() );
				if ( pAchievementMgr )
				{
					CBaseAchievement *pAch = pAchievementMgr->GetAchievementByID( nAchievementIndex, 0 );
					if ( pAch )
					{
						char buffer[128];
						Q_snprintf( buffer, sizeof(buffer), "achievements/%s", pAch->GetName() );
						m_pIcon->SetImage(buffer);
					}
				}
			}
		}

		//m_pIcon->SetImage( VarArgs( "swarm/medals/medal%d", nMedalImage ) );
		Q_snprintf( m_szMedalName, sizeof( m_szMedalName ), "#asw_medal%d", m_nMedalIndex );
		m_pTitle->SetText( m_szMedalName );

		if ( bCheckSingleplayerTooltip && ASWGameResource() && ASWGameResource()->IsOfflineGame() )
		{
			Q_snprintf( m_szMedalDescription, sizeof( m_szMedalDescription ), "#asw_medaltt%dsp", m_nMedalIndex );
		}
		else
		{
			Q_snprintf( m_szMedalDescription, sizeof( m_szMedalDescription ), "#asw_medaltt%d", m_nMedalIndex );
		}
		m_pDescription->SetText( m_szMedalDescription );
		m_pCounter->SetText( VarArgs( "+%d", GetXPForMedal( m_nMedalIndex ) ) );
		m_nXP = GetXPForMedal( m_nMedalIndex );
	}
	else if ( m_nAchievementIndex != -1 )
	{
		CAchievementMgr *pAchievementMgr = dynamic_cast<CAchievementMgr *>( engine->GetAchievementMgr() );
		if ( !pAchievementMgr )
			return;

		CBaseAchievement *pAchievement = pAchievementMgr->GetAchievementByID ( m_nAchievementIndex, 0 );
		if ( pAchievement)
		{
			m_pIcon->SetImage( pAchievement->GetIconPath() );
			Q_snprintf( m_szMedalName, sizeof( m_szMedalName ), "#%s_NAME", pAchievement->GetName() );
			m_pTitle->SetText( m_szMedalName );

			Q_snprintf( m_szMedalDescription, sizeof( m_szMedalDescription ), "#%s_DESC", pAchievement->GetName() );
			m_pDescription->SetText( m_szMedalDescription );
			m_pCounter->SetText( VarArgs( "+%d", GetXPForMedal( -m_nAchievementIndex ) ) );
			m_nXP = GetXPForMedal( -m_nAchievementIndex );
		}
	}
}

void MedalStatLine::SetMedalIndex( int nMedalIndex )
{
	if ( m_nMedalIndex != nMedalIndex )
	{
		m_nMedalIndex = nMedalIndex;
		if ( nMedalIndex != -1 )
		{
			m_nAchievementIndex = -1;
		}
		InvalidateLayout( false, true );
	}
}

void MedalStatLine::SetAchievementIndex( int nAchievementIndex )
{
	if ( m_nAchievementIndex != nAchievementIndex )
	{
		m_nAchievementIndex = nAchievementIndex;
		if ( m_nAchievementIndex != -1 )
		{
			m_nMedalIndex = -1;
		}
		InvalidateLayout( false, true );
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace ticpp
{
	namespace mock
	{
		struct Element;
		struct Declaration;

		struct Node
		{
			MOCK_METHOD0( Clear, void ( void ) );
			MOCK_METHOD1( SetValue, void( const std::string& ) );
			MOCK_METHOD1( InsertEndChild, void( const StrictMock< Element >& ) );
			MOCK_METHOD1( LinkEndChild, void( const StrictMock< Node >* ) );
			MOCK_METHOD1( LinkEndChild, void( const StrictMock< Element >* ) );
			MOCK_METHOD1( LinkEndChild, void( const StrictMock< Declaration >* ) );
			MOCK_METHOD1( SetText, void ( const double ) );
			MOCK_METHOD1( SetText, void ( const std::string& ) );
			MOCK_METHOD1( GetValue, void ( std::string* ) );
			MOCK_METHOD1( SetIntText, void ( const unsigned int ) );
			MOCK_METHOD1( RemoveChild, void ( Node* ) );
			MOCK_CONST_METHOD0( Clone, const StrictMock< Node >& ( void ) );		//This is done because auto_ptr's copy constructor is declared explicit and generates a compiler error inside googlemock.
			MOCK_CONST_METHOD0( ToElement, StrictMock< Element >* ( void ) );
			MOCK_CONST_METHOD0( NoChildren, bool ( void ) );
			MOCK_CONST_METHOD0( FirstChild, StrictMock< Node >* ( void ) );
			MOCK_CONST_METHOD1( FirstChild, StrictMock< Node >* ( const std::string& ) );
			MOCK_CONST_METHOD2( FirstChild, StrictMock< Node >* ( const std::string&, bool ) );
			MOCK_CONST_METHOD1( IterateChildren, StrictMock< Node >* ( StrictMock< Node >* ) );
			MOCK_CONST_METHOD2( IterateChildren, StrictMock< Node >* ( const std::string, StrictMock< Node >* ) );
			MOCK_CONST_METHOD0( FirstChildElement, StrictMock< Element >* () );
			MOCK_CONST_METHOD1( FirstChildElement, StrictMock< Element >* ( bool ) );
			MOCK_CONST_METHOD0( Value, std::string( void ) );

			//This is the work around for the Clone method not returning auto_ptr.
			const Node* release( void ) const
			{
				return this;
			}
		};

		struct Element : public Node
		{
			Element( const std::string& ) : Node()
			{
			}
			MOCK_CONST_METHOD1( GetAttribute, std::string( const std::string& ) );
			MOCK_CONST_METHOD2( GetAttribute, std::string( std::string, bool ) );
			MOCK_METHOD2( SetAttribute, void ( const std::string&, const int ) );
			MOCK_METHOD2( SetAttribute, void ( const std::string&, const std::string& ) );
			MOCK_CONST_METHOD0( GetText, std::string( void ) );
			MOCK_CONST_METHOD1( GetText, std::string( bool ) );

			bool operator==( const Element& other ) const
			{
				return *this == other;
			}
		};

		struct Document : public Node
		{
			Document( void ) : Node()
			{
			}
			Document( const std::string& ) : Node()
			{
			}
			MOCK_METHOD0( SaveFile, void ( void ) );
			MOCK_METHOD1( SaveFile, void ( const std::string& ) );
			MOCK_METHOD0( LoadFile, void ( void ) );
			MOCK_METHOD1( LoadFile, void ( const std::string& ) );
			MOCK_METHOD1( Parse, void ( const std::string& ) );
			MOCK_CONST_METHOD0( GetDocument, StrictMock< Document >* ( void ) );
		};

		struct Declaration : public Node
		{
			Declaration( void )
			{
			}
			Declaration( const std::string&, const std::string&, const std::string& )
			{
			}
		};

		struct Comment : public Node
		{
		};
	}
}
inline std::ostream& operator << ( std::ostream& os, const ticpp::mock::Node& )
{
	return( os );
}

#endif // !defined ( __TINY_XML_MOCK__ )


text:
package org.wso2.carbon.apimgt.impl.clients;

import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.identity.application.common.model.xsd.*;
import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceIdentityApplicationManagementException;
import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceStub;

import java.rmi.RemoteException;

@SuppressWarnings("unused")
public class ApplicationManagementServiceClient {

    private static final Log log = LogFactory.getLog(ApplicationManagementServiceClient.class);
    boolean debugEnabled = log.isErrorEnabled();
    private static final int TIMEOUT_IN_MILLIS = 15 * 60 * 1000;

    private IdentityApplicationManagementServiceStub identityApplicationManagementServiceStub;

    public ApplicationManagementServiceClient() throws APIManagementException {
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().
                getAPIManagerConfiguration();
        String serviceURL = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL);
        //username = config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME);

        if (serviceURL == null) {
            throw new APIManagementException("Required connection details for the key management server not provided");
        }

        try {

            ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            identityApplicationManagementServiceStub = new IdentityApplicationManagementServiceStub(ctx, serviceURL
                    + "IdentityApplicationManagementService");
            ServiceClient client = identityApplicationManagementServiceStub._getServiceClient();
            Options options = client.getOptions();
            options.setTimeOutInMilliSeconds(TIMEOUT_IN_MILLIS);
            options.setProperty(HTTPConstants.SO_TIMEOUT, TIMEOUT_IN_MILLIS);
            options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, TIMEOUT_IN_MILLIS);
            options.setCallTransportCleanup(true);
            options.setManageSession(true);

        } catch (AxisFault axisFault) {
            throw new APIManagementException("Error while initializing the OAuth admin service stub", axisFault);
        }
    }

    /**
     * This method is used to create application according to the given sp and user
     *
     * @param serviceProvider Service Provider
     * @param username        UserName of the user
     * @throws Exception
     */
    public void createApplication(ServiceProvider serviceProvider, String username) throws Exception {
        try {
            if (debugEnabled) {
                log.debug("Registering Service Provider " + serviceProvider.getApplicationName());
            }
            Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
            identityApplicationManagementServiceStub.createApplication(serviceProvider);
        } catch (RemoteException  e ) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage(), e);
        } catch (IdentityApplicationManagementServiceIdentityApplicationManagementException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    /**
     * This method is used to get application details for given application name
     *
     * @param applicationName Name of the application
     * @param username        UserName of the user
     * @return service provider
     * @throws Exception
     */
    public ServiceProvider getApplication(String applicationName, String username) throws Exception {
        try {
            if (debugEnabled) {
                log.debug("Loading Service Provider " + applicationName);
            }
            Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
            return identityApplicationManagementServiceStub.getApplication(applicationName);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage(), e);
        }

    }

    /**
     * This method is used to get the application information of a given user
     *
     * @param username UserName of the user
     * @return Basic information of the application as an array
     * @throws Exception
     */
    public ApplicationBasicInfo[] getAllApplicationBasicInfo(String username) throws Exception {
        try {
            Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
            return identityApplicationManagementServiceStub.getAllApplicationBasicInfo();
        } catch (RemoteException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        } catch (IdentityApplicationManagementServiceIdentityApplicationManagementException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    /**
     * This method is used to update the application data
     *
     * @param serviceProvider Service Provider
     * @param username        UserName of the user
     * @throws Exception
     */
    public void updateApplicationData(ServiceProvider serviceProvider, String username) throws Exception {
        try {
            Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
            identityApplicationManagementServiceStub.updateApplication(serviceProvider);
        } catch (RemoteException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        } catch (IdentityApplicationManagementServiceIdentityApplicationManagementException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
    }

    /**
     * This method is used to delete a given application
     *
     * @param applicationID application id
     * @param username      UserName of the user
     * @throws Exception
     */
    public void deleteApplication(String applicationID, String username) throws Exception {
        try {
            Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
            identityApplicationManagementServiceStub.deleteApplication(applicationID);
        } catch (RemoteException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage(), e);
        } catch (IdentityApplicationManagementServiceIdentityApplicationManagementException e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage(), e);
        }

    }

    /**
     * This method is ued to retrieve federated identity providers
     *
     * @param identityProviderName Name of the idp
     * @param username             UserName of the user
     * @return Identity Provider
     * @throws Exception
     */
    public IdentityProvider getFederatedIdentityProvider(String identityProviderName, String username)
            throws Exception {
        Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
        return identityApplicationManagementServiceStub.getIdentityProvider(identityProviderName);
    }

    /**
     * This method is used to get all request path authenticators
     *
     * @param username UserName of the user
     * @return request path authenticators
     * @throws Exception
     */
    public RequestPathAuthenticatorConfig[] getAllRequestPathAuthenticators(String username) throws Exception {
        Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
        return identityApplicationManagementServiceStub.getAllRequestPathAuthenticators();
    }

    /**
     * This method is used to get all local authenticators
     *
     * @param username UserName of the user
     * @return local authenticators
     * @throws Exception
     */
    public LocalAuthenticatorConfig[] getAllLocalAuthenticators(String username) throws Exception {
        Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
        return identityApplicationManagementServiceStub.getAllLocalAuthenticators();
    }

    /**
     * This method is used to get all federated identity providers
     *
     * @param username UserName of the user
     * @return federated identity providers
     * @throws Exception
     */
    public IdentityProvider[] getAllFederatedIdentityProvider(String username) throws Exception {
        IdentityProvider[] identityProviders;

        try {
            Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
            identityProviders = identityApplicationManagementServiceStub.getAllIdentityProviders();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception(e.getMessage());
        }
        return identityProviders;
    }

    /**
     * This method is used to get all claim uris
     *
     * @param username UserName of the user
     * @return all claim uris
     * @throws Exception
     */
    public String[] getAllClaimUris(String username) throws Exception {
        Util.setAuthHeaders(identityApplicationManagementServiceStub._getServiceClient(), username);
        return identityApplicationManagementServiceStub.getAllLocalClaimUris();
    }

}


text:
package com.invariantproperties.project.student.matcher;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import com.invariantproperties.project.student.domain.Classroom;

/**
 * Hamcrest matcher for 'Classroom' class.
 *
 * @author Bear Giles <bgiles@coyotesong.com>
 */
public class ClassroomEquality extends TypeSafeMatcher<Classroom> {
    private final Classroom expected;

    private ClassroomEquality(Classroom expected) {
        this.expected = expected;
    }

    @Override
    public boolean matchesSafely(Classroom actual) {
        if (actual == null) {
            return false;
        }

        EqualsBuilder eq = new EqualsBuilder();
        eq.append(expected.getId(), actual.getId());
        eq.append(expected.getUuid(), actual.getUuid());
        eq.append(expected.getName(), actual.getName());
        eq.append(expected.getCreationDate(), actual.getCreationDate());

        return eq.isEquals();
    }

    public void describeTo(Description description) {
        description.appendText("Course comparison");
    }

    @Factory
    public static <T> Matcher<Classroom> equalTo(Classroom classroom) {
        return new ClassroomEquality(classroom);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/done_text_color_disabled" android:state_enabled="false" />
    <item android:color="@color/done_text_color_normal" android:state_enabled="true" />
</selector>


text:
import numpy as np
import warnings
import matplotlib.pyplot as plt
from matplotlib import style
from collections import Counter

style.use('bmh')

dataset = {'k': [[1, 2], [2, 3], [3, 1]], 'r': [[8, 7], [6, 9], [9, 4]]}
new_features = [5, 7]

def k_nearest_neighbors(data, predict, k=3):
    if len(data) >= k:
        warnings.warn('K is greater than classes number!')
    distances = []
    for group in data:
        for features in data[group]:
            euclidean_distance = np.linalg.norm(np.array(features) - np.array(predict))
            distances.append([euclidean_distance, group])
    votes = [i[1] for i in sorted(distances)[:k]]
    vote_result = Counter(votes).most_common(1)[0][0]
    return vote_result

new_features_group = k_nearest_neighbors(dataset, new_features)

for i in dataset:
    for ii in dataset[i]:
        plt.scatter(ii[0], ii[1], color=i)

plt.scatter(new_features[0], new_features[1], color=new_features_group)
plt.show()


text:
from sentry.testutils import TestCase
from sentry.utils.data_scrubber import SensitiveDataFilter

VARS = {
    'foo': 'bar',
    'password': 'hello',
    'the_secret': 'hello',
    'a_password_here': 'hello',
    'api_key': 'secret_key',
    'apiKey': 'secret_key',
}

class SensitiveDataFilterTest(TestCase):

    def _check_vars_sanitized(self, vars, proc):
        """
        Helper to check that keys have been sanitized.
        """
        self.assertTrue('foo' in vars)
        self.assertEquals(vars['foo'], 'bar')
        self.assertTrue('password' in vars)
        self.assertEquals(vars['password'], proc.MASK)
        self.assertTrue('the_secret' in vars)
        self.assertEquals(vars['the_secret'], proc.MASK)
        self.assertTrue('a_password_here' in vars)
        self.assertEquals(vars['a_password_here'], proc.MASK)
        self.assertTrue('api_key' in vars)
        self.assertEquals(vars['api_key'], proc.MASK)
        self.assertTrue('apiKey' in vars)
        self.assertEquals(vars['apiKey'], proc.MASK)

    def test_stacktrace(self):
        data = {
            'sentry.interfaces.Stacktrace': {
                'frames': [{'vars': VARS}],
            }
        }

        proc = SensitiveDataFilter()
        proc.apply(data)

        self.assertTrue('sentry.interfaces.Stacktrace' in data)
        stack = data['sentry.interfaces.Stacktrace']
        self.assertTrue('frames' in stack)
        self.assertEquals(len(stack['frames']), 1)
        frame = stack['frames'][0]
        self.assertTrue('vars' in frame)
        self._check_vars_sanitized(frame['vars'], proc)

    def test_http(self):
        data = {
            'sentry.interfaces.Http': {
                'data': VARS,
                'env': VARS,
                'headers': VARS,
                'cookies': VARS,
            }
        }

        proc = SensitiveDataFilter()
        proc.apply(data)

        self.assertTrue('sentry.interfaces.Http' in data)
        http = data['sentry.interfaces.Http']
        for n in ('data', 'env', 'headers', 'cookies'):
            self.assertTrue(n in http)
            self._check_vars_sanitized(http[n], proc)

    def test_extra(self):
        data = {
            'extra': VARS
        }

        proc = SensitiveDataFilter()
        proc.apply(data)

        self.assertTrue('extra' in data)
        self._check_vars_sanitized(data['extra'], proc)

    def test_querystring_as_string(self):
        data = {
            'sentry.interfaces.Http': {
                'query_string': 'foo=bar&password=hello&the_secret=hello'
                                '&a_password_here=hello&api_key=secret_key',
            }
        }

        proc = SensitiveDataFilter()
        proc.apply(data)

        self.assertTrue('sentry.interfaces.Http' in data)
        http = data['sentry.interfaces.Http']
        self.assertEquals(
            http['query_string'],
            'foo=bar&password=%(m)s&the_secret=%(m)s'
            '&a_password_here=%(m)s&api_key=%(m)s' % dict(m=proc.MASK))

    def test_querystring_as_string_with_partials(self):
        data = {
            'sentry.interfaces.Http': {
                'query_string': 'foo=bar&password&baz=bar',
            }
        }

        proc = SensitiveDataFilter()
        proc.apply(data)

        self.assertTrue('sentry.interfaces.Http' in data)
        http = data['sentry.interfaces.Http']
        self.assertEquals(http['query_string'], 'foo=bar&password&baz=bar' % dict(m=proc.MASK))

    def test_sanitize_additional_sensitive_fields(self):
        additional_sensitive_dict = {
            'fieldy_field': 'value',
            'moar_other_field': 'another value'
        }
        data = {
            'extra': dict(VARS.items() + additional_sensitive_dict.items())
        }

        proc = SensitiveDataFilter(additional_sensitive_dict.keys())
        proc.apply(data)

        for field in additional_sensitive_dict.keys():
            self.assertEquals(data['extra'][field], proc.MASK)

        self._check_vars_sanitized(data['extra'], proc)

    def test_sanitize_credit_card(self):
        proc = SensitiveDataFilter()
        result = proc.sanitize('foo', '4242424242424242')
        self.assertEquals(result, proc.MASK)

    def test_sanitize_credit_card_amex(self):
        # AMEX numbers are 15 digits, not 16
        proc = SensitiveDataFilter()
        result = proc.sanitize('foo', '424242424242424')
        self.assertEquals(result, proc.MASK)

    def test_sanitize_credit_card_within_value(self):
        proc = SensitiveDataFilter()
        result = proc.sanitize('foo', "'4242424242424242'")
        self.assertEquals(result, proc.MASK)

        proc = SensitiveDataFilter()
        result = proc.sanitize('foo', "foo 4242424242424242")
        self.assertEquals(result, proc.MASK)


text:
package dao

import java.sql.Blob
import javax.inject.Inject

import com.google.inject.Singleton
import models.Club.Club
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.db.NamedDatabase
import slick.driver.JdbcProfile
import slick.driver.PostgresDriver.api._
import slick.lifted.{TableQuery, Tag}

import scala.concurrent.Future

class ClubTable(tag: Tag) extends Table[Club](tag, "club") {
  def clubid = column[Int]("clubid", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  def street = column[String]("street")
  def zipcode = column[String]("zipcode")
  def city = column[String]("city")
  def logo = column[Option[Array[Byte]]]("logo")
  def contact = column[Option[String]]("contact")
  def email = column[Option[String]]("email")
  def telefon = column[Option[String]]("telefon")
  def web = column[Option[String]]("web")
  def * = (clubid, name, street, zipcode, city, logo, contact, email, telefon, web) <> (Club.tupled, Club.unapply _)
}

@Singleton()
class ClubDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {

  private val clubs = TableQuery[ClubTable]

  def all(): Future[Seq[Club]] = db.run(clubs.result)

  def getClub(clubId: Int): Future[Option[Club]] = db.run(clubs.filter(_.clubid === clubId).result.headOption)

  def deleteClub(clubId: Int): Future[Int] = db.run(clubs.filter(_.clubid === clubId).delete)

  def createClub(club: Club): Future[Int] = {
    val query = (clubs returning clubs.map(_.clubid)) += club
    db.run(query)
  }

  def updateClub(clubId: Int, club: Club): Future[Int] = {
    val clubToUpdate: Club = club.copy(clubId)
    db.run(clubs.filter(_.clubid === clubId).update(clubToUpdate))
  }
}


text:
var request = require('superagent');

METHOD_MAP = {
  'create': 'post',
  'update': 'put',
  'delete': 'del',
  'read': 'get'
};

module.exports = function(method, model, options) {
  var url = options.url || (typeof model.url == 'function' ? model.url() : model.url);
  var data = options.data || (method === 'create' || method === 'update' ? model.toJSON() : {});
  var req = request[METHOD_MAP[method]](url);

  // Allow intercepting of the request object to inject sync-wide things like an oAuth token.
  module.exports.editRequest(req, method, model, options);

  // Inject POST/PUT data in body or GET data in querystring
  if (method == 'create' || method == 'update') {
    req.send(data).set('content-length', JSON.stringify(data).length);
  } else {
    req.query(data);
  }

  req.end(function(res) {
    if (res.ok && options.success) {
      options.res = res;
      options.success(res.body, res);
    } else if (!res.ok && options.error) {
      options.error(res);
    }
  });

  model.trigger('request', model, req, options);
};

module.exports.editRequest = function(req) {}


text:
<?php

use Faker\Generator as Faker;

/* @var Illuminate\Database\Eloquent\Factory $factory */

$factory->define(App\Permission::class, function (Faker $faker) {
	return [
		'name' => $faker->word,
		'display_name' => $faker->sentence(),
		'description' => $faker->sentence(),
	];
});


text:
<?php
/**
 * Created by PhpStorm.
 * User: haoboyi
 * Date: 2015/8/27
 * Time: 10:32
 */

defined('BASEPATH') OR exit('No direct script access allowed');
function format(){
    printf("%s", "aaa");
}


text:
class arrayImageBlobController {

  constructor(state, action, _drawFrame){
        this.state = state;
        this.action = action;
        this.drawFrame = _drawFrame;
  }
  setArrayImage(){
    return this.drawFrame({
      arrayImage: {
        $set: this.action.array
      }
    });
  }

  deleteArrayImage(){
    return this.drawFrame({
      arrayImage: {
        $splice: [[this.action.index, 1]]
      }
    });
  }
  addArrayImage(){
    return this.drawFrame({
      arrayImage: {
        $push: [this.action.object]
      }
    });
  }
  updateArrayImage(){
    return this.drawFrame({
      arrayImage: {
        $splice: [
          [this.action.index, 1, this.action.object]
        ]
      }
    });
  }

}

export default arrayImageBlobController;


text:
(function () {
    var controllerId = 'app.views.entries.edit';
    angular.module('app').controller(controllerId, [
        '$rootScope',
        '$scope',
        'abp.services.mgmt.entry',
        '$compile',
        '$stateParams',
        '$location',
        function ($rootScope, $scope, entryService, $compile, $stateParams, $location) {
            var vm = this;
            vm.entry = {};
            vm.pageform = undefined;

            function getEntry() {
                entryService.getEntry({ id: $stateParams.entryid }).success(function (result) {
                    vm.entry = result;

                    if (vm.entry.dateIn) {
                        var dateIn = moment(vm.entry.dateIn);
                        vm.entry.dateIn = (dateIn.isValid() ? dateIn.format("DD/MM/YYYY") : "");
                    }

                    if (vm.entry.dateOut) {
                        var dateOut = moment(vm.entry.dateOut);
                        vm.entry.dateOut = (dateOut.isValid() ? dateOut.format("DD/MM/YYYY") : "");
                    }
                });
            };

            vm.save = function () {
                entryService.updateEntry(vm.entry).success(function () {
                    $location.path("entries");
                });
            };

            getEntry();
        }
    ]);
})();


text:
namespace DAVA
{

#if (DAVA_DEBUG_TEXTURE_DISABLE_LOADING)
Texture* GetSharedPinkTexture()
{
    static Texture* pink = nullptr;
    if (pink == nullptr)
    {
        pink = Texture::CreatePink();
    }
    return SafeRetain(pink);
}
#endif

namespace Validator
{
bool IsFormatHardwareSupported(PixelFormat format)
{
    const auto& formatDescriptor = PixelFormatDescriptor::GetPixelFormatDescriptor(format);
    return formatDescriptor.isHardwareSupported;
}

bool AreImagesSquare(const Vector<DAVA::Image*>& imageSet)
{
    for (Image* image : imageSet)
    {
        if (!IsPowerOf2(image->GetWidth()) || !IsPowerOf2(image->GetHeight()))
        {
            return false;
        }
    }

    return true;
}

bool AreImagesCorrectForTexture(const Vector<DAVA::Image*>& imageSet)
{
    if (0 == imageSet.size())
    {
        return false;
    }

    if (imageSet[0]->width < Texture::MINIMAL_WIDTH || imageSet[0]->height < Texture::MINIMAL_HEIGHT)
    {
        Logger::Error("[TextureValidator] Loaded images size is too small. Minimal size for texture is 8x8");
        return false;
    }

    bool isSizeCorrect = Validator::AreImagesSquare(imageSet);
    if (!isSizeCorrect)
    {
        Logger::Error("[TextureValidator] Size if loaded images is invalid (not power of 2)");
        return false;
    }

    return true;
}

bool CheckAndFixImageFormat(Vector<Image*>* images)
{
    Vector<Image*>& imageSet = *images;
    PixelFormat format = imageSet[0]->format;
    if (IsFormatHardwareSupported(format))
    {
        return true;
    }

#if defined(__DAVAENGINE_MACOS__) || defined(__DAVAENGINE_WIN32__) || defined(__DAVAENGINE_WIN_UAP__)
    //we should decode all images for RE/QE
    if (ImageConvert::CanConvertFromTo(format, FORMAT_RGBA8888))
#else
    //We should decode only RGB888 into RGBA8888
    if (format == PixelFormat::FORMAT_RGB888 && ImageConvert::CanConvertFromTo(format, FORMAT_RGBA8888))
#endif
    {
        for (Image*& image : imageSet)
        {
            Image* newImage = Image::Create(image->width, image->height, FORMAT_RGBA8888);
            bool converted = ImageConvert::ConvertImage(image, newImage);
            if (converted)
            {
                newImage->mipmapLevel = image->mipmapLevel;
                newImage->cubeFaceID = image->cubeFaceID;

                image->Release();
                image = newImage;
            }
            else
            {
                SafeRelease(newImage);
                return false;
            }
        }

        return true;
    }

    return false;
}
}

Array<String, Texture::CUBE_FACE_COUNT> Texture::FACE_NAME_SUFFIX =
{ {
String("_px"),
String("_nx"),
String("_py"),
String("_ny"),
String("_pz"),
String("_nz")
} };

class TextureMemoryUsageInfo
{
public:
    TextureMemoryUsageInfo()
    {
        pvrTexturesMemoryUsed = 0;
        texturesMemoryUsed = 0;
        fboMemoryUsed = 0;
    }

    void AllocPVRTexture(int size)
    {
        pvrTexturesMemoryUsed += size;
    }

    void ReleasePVRTexture(int size)
    {
        pvrTexturesMemoryUsed -= size;
    }

    void AllocTexture(int size)
    {
        texturesMemoryUsed += size;
    }

    void ReleaseTexture(int size)
    {
        texturesMemoryUsed -= size;
    }

    void AllocFBOTexture(int size)
    {
        fboMemoryUsed += size;
    }

    void ReleaseFBOTexture(int size)
    {
        fboMemoryUsed -= size;
    }

    // STATISTICS
    int pvrTexturesMemoryUsed;
    int texturesMemoryUsed;
    int fboMemoryUsed;
};

static TextureMemoryUsageInfo texMemoryUsageInfo;

TexturesMap Texture::textureMap;
Vector<eGPUFamily> Texture::gpuLoadingOrder;

Mutex Texture::textureMapMutex;

static int32 textureFboCounter = 0;

bool Texture::pixelizationFlag = false;

// Main constructors
Texture* Texture::Get(const FilePath& pathName)
{
    LockGuard<Mutex> guard(textureMapMutex);

    Texture* texture = nullptr;
    TexturesMap::iterator it = textureMap.find(FILEPATH_MAP_KEY(pathName));
    if (it != textureMap.end())
    {
        texture = it->second;
        texture->Retain();
    }
    return texture;
}

void Texture::AddToMap(Texture* tex)
{
    if (!tex->texDescriptor->pathname.IsEmpty())
    {
        DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

        LockGuard<Mutex> guard(textureMapMutex);
        DVASSERT(textureMap.find(FILEPATH_MAP_KEY(tex->texDescriptor->pathname)) == textureMap.end());
        textureMap[FILEPATH_MAP_KEY(tex->texDescriptor->pathname)] = tex;
    }
}

Texture::Texture()
    : handle(rhi::InvalidHandle)
    , samplerStateHandle(rhi::InvalidHandle)
    , singleTextureSet(rhi::InvalidHandle)
    , width(0)
    , height(0)
    , loadedAsFile(GPU_ORIGIN)
    , state(STATE_INVALID)
    , textureType(rhi::TEXTURE_TYPE_2D)
    , isRenderTarget(false)
    , isPink(false)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    texDescriptor = new TextureDescriptor;
    Renderer::GetSignals().needRestoreResources.Connect(this, &Texture::RestoreRenderResource);
}

Texture::~Texture()
{
    Renderer::GetSignals().needRestoreResources.Disconnect(this);
    ReleaseTextureData();
    SafeDelete(texDescriptor);
}

void Texture::ReleaseTextureData()
{
    if (handle.IsValid())
    {
        rhi::DeleteTexture(handle);
        handle = rhi::HTexture(rhi::InvalidHandle);
    }

    if (handleDepthStencil.IsValid())
    {
        rhi::DeleteTexture(handleDepthStencil);
        handleDepthStencil = rhi::HTexture();
    }

    if (samplerStateHandle.IsValid())
    {
        rhi::ReleaseSamplerState(samplerStateHandle);
        samplerStateHandle = rhi::HSamplerState(rhi::InvalidHandle);
    }

    if (singleTextureSet.IsValid())
    {
        rhi::ReleaseTextureSet(singleTextureSet);
        singleTextureSet = rhi::HTextureSet(rhi::InvalidHandle);
    }

    state = STATE_INVALID;
    isRenderTarget = false;
}

Texture* Texture::CreateTextFromData(PixelFormat format, uint8* data, uint32 width, uint32 height, bool generateMipMaps, const char* addInfo)
{
#if (DAVA_DEBUG_TEXTURE_DISABLE_LOADING)
    return GetSharedPinkTexture();
#endif

    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    Texture* tx = CreateFromData(format, data, width, height, generateMipMaps);

    if (!addInfo)
    {
        tx->texDescriptor->pathname = Format("Text texture %d", textureFboCounter);
    }
    else
    {
        tx->texDescriptor->pathname = Format("Text texture %d info:%s", textureFboCounter, addInfo);
    }
    AddToMap(tx);

    textureFboCounter++;
    return tx;
}

void Texture::TexImage(int32 level, uint32 width, uint32 height, const void* _data, uint32 dataSize, uint32 cubeFaceId)
{
    rhi::UpdateTexture(handle, _data, level, rhi::TextureFace(cubeFaceId));
}

Texture* Texture::CreateFromData(PixelFormat _format, const uint8* _data, uint32 _width, uint32 _height, bool generateMipMaps)
{
#if (DAVA_DEBUG_TEXTURE_DISABLE_LOADING)
    return GetSharedPinkTexture();
#endif

    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    if ((_width < Texture::MINIMAL_WIDTH || _height < Texture::MINIMAL_HEIGHT) && (_format == FORMAT_PVR2 || _format == FORMAT_PVR4))
    {
        return nullptr;
    }

    Image* image = Image::CreateFromData(_width, _height, _format, _data);
    if (nullptr == image)
        return nullptr;

    Texture* texture = new Texture();
    texture->texDescriptor->Initialize(rhi::TEXADDR_CLAMP, generateMipMaps);

    Vector<Image*>* images = new Vector<Image*>();
    images->push_back(image);

    Validator::CheckAndFixImageFormat(images);

    texture->SetParamsFromImages(images);
    texture->FlushDataToRenderer(images);

    return texture;
}

Texture* Texture::CreateFromData(Image* image, bool generateMipMaps)
{
#if (DAVA_DEBUG_TEXTURE_DISABLE_LOADING)
    return GetSharedPinkTexture();
#endif

    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    if ((image->width < Texture::MINIMAL_WIDTH || image->height < Texture::MINIMAL_HEIGHT) && (image->format == FORMAT_PVR2 || image->format == FORMAT_PVR4))
    {
        return nullptr;
    }

    Texture* texture = new Texture();
    texture->texDescriptor->Initialize(rhi::TEXADDR_CLAMP, generateMipMaps);

    Vector<Image*>* images = new Vector<Image*>();
    image->Retain();
    images->push_back(image);

    Validator::CheckAndFixImageFormat(images);

    texture->SetParamsFromImages(images);
    texture->FlushDataToRenderer(images);

    return texture;
}

Texture* Texture::CreateFromData(const Vector<Image*>& imgs)
{
#if (DAVA_DEBUG_TEXTURE_DISABLE_LOADING)
    return GetSharedPinkTexture();
#endif

    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    Texture* texture = new Texture();
    texture->texDescriptor->Initialize(rhi::TEXADDR_CLAMP, false);

    Vector<Image*>* images = new Vector<Image*>(imgs);
    for (Image* image : (*images))
        image->Retain();

    Validator::CheckAndFixImageFormat(images);

    texture->SetParamsFromImages(images);
    texture->FlushDataToRenderer(images);

    return texture;
}

void Texture::SetWrapMode(rhi::TextureAddrMode wrapU, rhi::TextureAddrMode wrapV, rhi::TextureAddrMode wrapW)
{
    samplerState.addrU = wrapU;
    samplerState.addrV = wrapV;
    samplerState.addrW = wrapW;

    rhi::ReleaseSamplerState(samplerStateHandle);
    samplerStateHandle = CreateSamplerStateHandle(samplerState);
}

void Texture::SetMinMagFilter(rhi::TextureFilter minFilter, rhi::TextureFilter magFilter, rhi::TextureMipFilter mipFilter)
{
    samplerState.minFilter = minFilter;
    samplerState.magFilter = magFilter;
    samplerState.mipFilter = mipFilter;

    rhi::ReleaseSamplerState(samplerStateHandle);
    samplerStateHandle = CreateSamplerStateHandle(samplerState);
}

void Texture::GenerateMipmaps()
{
    DVASSERT(0, "Mipmap generation on fly is not supported anymore!");
}

Texture* Texture::CreateFromImage(TextureDescriptor* descriptor, eGPUFamily gpu)
{
#if (DAVA_DEBUG_TEXTURE_DISABLE_LOADING)
    return GetSharedPinkTexture();
#endif

    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    Texture* texture = new Texture();
    texture->texDescriptor->Initialize(descriptor);

    Vector<Image*>* images = new Vector<Image*>();

    bool loaded = texture->LoadImages(gpu, images);
    if (!loaded)
    {
        SafeDelete(images);
        SafeRelease(texture);
        return nullptr;
    }

    texture->SetParamsFromImages(images);
    texture->FlushDataToRenderer(images);

    if (!texture->singleTextureSet.IsValid())
    {
        Logger::Error
        (
        "[Texture::CreateFromImage] Cannot create rhi.texture from image. Descriptor: %s, GPU: %s",
        descriptor->pathname.GetAbsolutePathname().c_str(), GlobalEnumMap<eGPUFamily>::Instance()->ToString(gpu)
        );
        SafeRelease(texture);
        return nullptr;
    }

    return texture;
}

bool Texture::LoadImages(eGPUFamily gpu, Vector<Image*>* images)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    DVASSERT(gpu != GPU_INVALID);

    if (!IsLoadAvailable(gpu))
    {
        Logger::Error("[Texture::LoadImages] Load not available: invalid requested GPU family (%s)", GlobalEnumMap<eGPUFamily>::Instance()->ToString(gpu));
        return false;
    }

    uint32 baseMipMap = GetBaseMipMap();
    ImageSystem::LoadingParams params;
    params.baseMipmap = baseMipMap;
    params.firstMipmapIndex = 0;
    params.minimalWidth = Texture::MINIMAL_WIDTH;
    params.minimalHeight = Texture::MINIMAL_HEIGHT;

    if (texDescriptor->IsCubeMap() && (!GPUFamilyDescriptor::IsGPUForDevice(gpu)))
    {
        Vector<FilePath> facePathes;
        texDescriptor->GetFacePathnames(facePathes);

        PixelFormat imagesFormat = FORMAT_INVALID;
        for (uint32 i = 0; i < CUBE_FACE_COUNT; ++i)
        {
            const FilePath& currentfacePath = facePathes[i];
            if (currentfacePath.IsEmpty())
                continue;

            Vector<Image*> faceImage;
            ImageSystem::Load(currentfacePath, faceImage, params);
            if (faceImage.empty())
            {
                Logger::Error("[Texture::LoadImages] Cannot open file %s", currentfacePath.GetAbsolutePathname().c_str());

                ReleaseImages(images);
                return false;
            }

            DVASSERT(faceImage.size() == 1);

            faceImage[0]->cubeFaceID = i;
            faceImage[0]->mipmapLevel = 0;

            //cubemap formats validation
            if (FORMAT_INVALID == imagesFormat)
            {
                imagesFormat = faceImage[0]->format;
            }
            else if (imagesFormat != faceImage[0]->format)
            {
                Logger::Error("[Texture::LoadImages] Face(%s) has different pixel format(%s)", currentfacePath.GetAbsolutePathname().c_str(), PixelFormatDescriptor::GetPixelFormatString(faceImage[0]->format));

                ReleaseImages(images);
                return false;
            }
            //end of cubemap formats validation

            if (texDescriptor->GetGenerateMipMaps())
            {
                Vector<Image*> mipmapsImages = faceImage[0]->CreateMipMapsImages();
                images->insert(images->end(), mipmapsImages.begin(), mipmapsImages.end());
                SafeRelease(faceImage[0]);
            }
            else
            {
                images->push_back(faceImage[0]);
            }
        }
    }
    else
    {
        Vector<FilePath> singleMipFiles;
        bool hasSingleMipFiles = texDescriptor->CreateSingleMipPathnamesForGPU(gpu, singleMipFiles);
        if (hasSingleMipFiles)
        {
            uint32 singleMipFilesCount = static_cast<uint32>(singleMipFiles.size());
            for (uint32 index = baseMipMap; index < singleMipFilesCount; ++index)
            {
                params.baseMipmap = 0;
                eErrorCode loadingCode = ImageSystem::Load(singleMipFiles[index], *images, params);
                if (loadingCode == eErrorCode::SUCCESS)
                {
                    ++params.firstMipmapIndex;
                }
            }

            params.baseMipmap = Max(static_cast<int32>(baseMipMap) - static_cast<int32>(singleMipFilesCount), 0);
        }

        FilePath multipleMipPathname = texDescriptor->CreateMultiMipPathnameForGPU(gpu);
        ImageSystem::Load(multipleMipPathname, *images, params);

        ImageSystem::EnsurePowerOf2Images(*images);
    }

    if (!Validator::AreImagesCorrectForTexture(*images))
    {
        ReleaseImages(images);
        return false;
    }

    if (!Validator::CheckAndFixImageFormat(images))
    {
        Logger::Error("[Texture::LoadImages] cannot create texture from images because of wrong image format");

        ReleaseImages(images);
        return false;
    }

    if (images->size() == 1 && texDescriptor->GetGenerateMipMaps())
    {
        Image* img = *images->begin();
        *images = img->CreateMipMapsImages(texDescriptor->dataSettings.GetIsNormalMap());
        SafeRelease(img);

        if (images->empty())
        {
            Logger::Error("[Texture::LoadImages] Can't create mipmaps for GPU (%s) for %s", GlobalEnumMap<eGPUFamily>::Instance()->ToString(gpu), texDescriptor->pathname.GetStringValue().c_str());
            return false;
        }
    }

    isPink = false;
    state = STATE_DATA_LOADED;

    return true;
}

void Texture::ReleaseImages(Vector<Image*>* images)
{
    for_each(images->begin(), images->end(), SafeRelease<Image>);
    images->clear();
}

void Texture::SetParamsFromImages(const Vector<Image*>* images)
{
    DVASSERT(images->size() != 0);

    Image* img = *images->begin();
    width = img->width;
    height = img->height;
    texDescriptor->format = img->format;

    textureType = (img->cubeFaceID != Texture::INVALID_CUBEMAP_FACE) ? rhi::TEXTURE_TYPE_CUBE : rhi::TEXTURE_TYPE_2D;

    state = STATE_DATA_LOADED;
}

void Texture::FlushDataToRenderer(Vector<Image*>* images)
{
    DVASSERT(images->size() != 0);

    const PixelFormatDescriptor& formatDescriptor = PixelFormatDescriptor::GetPixelFormatDescriptor(texDescriptor->format);
    rhi::Texture::Descriptor descriptor;
    descriptor.autoGenMipmaps = false;
    descriptor.isRenderTarget = false;
    descriptor.width = (*images)[0]->width;
    descriptor.height = (*images)[0]->height;
    descriptor.type = ((*images)[0]->cubeFaceID == Texture::INVALID_CUBEMAP_FACE) ? rhi::TEXTURE_TYPE_2D : rhi::TEXTURE_TYPE_CUBE;
    descriptor.format = formatDescriptor.format;
    descriptor.levelCount = static_cast<uint32>((descriptor.type == rhi::TEXTURE_TYPE_CUBE) ? images->size() / 6 : images->size());

    const uint32 oldLevelCountVerify = descriptor.levelCount; //to notify about wrong images
    for (Image* img : (*images))
    { // kostil for some wrong data
        descriptor.levelCount = Max(descriptor.levelCount, img->mipmapLevel + 1);
    }
    if (oldLevelCountVerify != descriptor.levelCount)
    {
        Logger::Error("Something wrong with image mipmap levels at %s", texDescriptor->pathname.GetStringValue().c_str());
    }

    DVASSERT(descriptor.format != static_cast<rhi::TextureFormat>(-1)); //unsupported format

#if 1

    if (descriptor.type == rhi::TEXTURE_TYPE_2D)
    {
        for (size_t i = 0, sz = images->size(); i < sz; ++i)
            descriptor.initialData[i] = (*images)[i]->data;
    }
    else if (descriptor.type == rhi::TEXTURE_TYPE_CUBE)
    {
        rhi::TextureFace face[] = { rhi::TEXTURE_FACE_POSITIVE_X, rhi::TEXTURE_FACE_NEGATIVE_X, rhi::TEXTURE_FACE_POSITIVE_Y, rhi::TEXTURE_FACE_NEGATIVE_Y, rhi::TEXTURE_FACE_POSITIVE_Z, rhi::TEXTURE_FACE_NEGATIVE_Z };
        void** data = descriptor.initialData;

        for (unsigned f = 0; f != CUBE_FACE_COUNT; ++f)
        {
            for (unsigned m = 0; m != descriptor.levelCount; ++m)
            {
                *data = nullptr;

                for (size_t i = 0, sz = images->size(); i < sz; ++i)
                {
                    Image* img = (*images)[i];

                    if (img->cubeFaceID == face[f] && img->mipmapLevel == m)
                    {
                        *data = img->data;
                        break;
                    }
                }

                ++data;
            }
        }
    }

    handle = rhi::CreateTexture(descriptor);
    if (handle != rhi::InvalidHandle)
    {
        rhi::TextureSetDescriptor textureSetDesc;
        textureSetDesc.fragmentTexture[0] = handle;
        textureSetDesc.fragmentTextureCount = 1;
        singleTextureSet = rhi::AcquireTextureSet(textureSetDesc);
    }
    else
    {
        singleTextureSet = rhi::HTextureSet(rhi::InvalidHandle);
    }

#else

    handle = rhi::CreateTexture(descriptor);
    DVASSERT(handle != rhi::InvalidHandle);

    rhi::TextureSetDescriptor textureSetDesc;
    textureSetDesc.fragmentTexture[0] = handle;
    textureSetDesc.fragmentTextureCount = 1;
    singleTextureSet = rhi::AcquireTextureSet(textureSetDesc);

    for (uint32 i = 0; i < (uint32)images->size(); ++i)
    {
        Image* img = (*images)[i];
        TexImage((img->mipmapLevel != (uint32)-1) ? img->mipmapLevel : i, img->width, img->height, img->data, img->dataSize, img->cubeFaceID);
    }

#endif

    samplerState.addrU = texDescriptor->drawSettings.wrapModeS;
    samplerState.addrV = texDescriptor->drawSettings.wrapModeT;
    samplerState.minFilter = pixelizationFlag ? rhi::TextureFilter::TEXFILTER_NEAREST : texDescriptor->drawSettings.minFilter;
    samplerState.magFilter = pixelizationFlag ? rhi::TextureFilter::TEXFILTER_NEAREST : texDescriptor->drawSettings.magFilter;
    samplerState.mipFilter = pixelizationFlag ? rhi::TextureMipFilter::TEXMIPFILTER_NONE : texDescriptor->drawSettings.mipFilter;

    rhi::ReleaseSamplerState(samplerStateHandle);
    samplerStateHandle = CreateSamplerStateHandle(samplerState);

    state = STATE_VALID;

    ReleaseImages(images);
    SafeDelete(images);
}

Texture* Texture::CreateFromFile(const FilePath& pathName, const FastName& group, rhi::TextureType typeHint)
{
#if (DAVA_DEBUG_TEXTURE_DISABLE_LOADING)
    return GetSharedPinkTexture();
#endif

    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    Texture* texture = PureCreate(pathName, group);
    if (nullptr == texture)
    {
        TextureDescriptor* descriptor = TextureDescriptor::CreateFromFile(pathName);
        if (descriptor)
        {
            texture = CreatePink(descriptor->IsCubeMap() ? rhi::TEXTURE_TYPE_CUBE : typeHint);
            texture->texDescriptor->Initialize(descriptor);
            SafeDelete(descriptor);
        }
        else
        {
            texture = CreatePink(typeHint);
            texture->texDescriptor->pathname = (!pathName.IsEmpty()) ? TextureDescriptor::GetDescriptorPathname(pathName) : FilePath();
        }

        texture->texDescriptor->SetQualityGroup(group);

        AddToMap(texture);
    }

    return texture;
}

Texture* Texture::PureCreate(const FilePath& pathName, const FastName& group)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    if (pathName.IsEmpty() || (pathName.GetType() == FilePath::PATH_IN_MEMORY))
        return nullptr;

    if (!Renderer::GetOptions()->IsOptionEnabled(RenderOptions::TEXTURE_LOAD_ENABLED))
        return nullptr;

    FilePath descriptorPathname = TextureDescriptor::GetDescriptorPathname(pathName);
    Texture* texture = Texture::Get(descriptorPathname);
    if (texture)
        return texture;

    TextureDescriptor* descriptor(TextureDescriptor::CreateFromFile(descriptorPathname));
    if (nullptr == descriptor)
        return nullptr;

    descriptor->SetQualityGroup(group);
    for (eGPUFamily gpu : gpuLoadingOrder)
    {
        eGPUFamily gpuForLoading = GetGPUForLoading(gpu, descriptor);
        texture = CreateFromImage(descriptor, gpuForLoading);
        if (texture)
        {
            texture->loadedAsFile = gpuForLoading;
            AddToMap(texture);
            break;
        }
    }

    if (texture == nullptr)
    {
        Logger::Error("[Texture::PureCreate] Cannot create texture. Descriptor: %s, GPU: %s",
                      descriptor->pathname.GetAbsolutePathname().c_str(), GlobalEnumMap<eGPUFamily>::Instance()->ToString(GetPrimaryGPUForLoading()));
    }

    delete descriptor;
    return texture;
}

void Texture::ReloadFromData(PixelFormat format, uint8* data, uint32 _width, uint32 _height)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    rhi::HTexture oldHandle = handle;
    ReleaseTextureData();

    Image* image = Image::CreateFromData(_width, _height, format, data);
    if (!image)
        return;

    Vector<Image*>* images = new Vector<Image*>();
    images->push_back(image);

    SetParamsFromImages(images);
    FlushDataToRenderer(images);
    rhi::ReplaceTextureInAllTextureSets(oldHandle, handle);
}

void Texture::Reload()
{
    ReloadAs(loadedAsFile);
}

void Texture::ReloadAs(eGPUFamily gpuFamily)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();
    rhi::HTexture oldHandle = handle;

    DVASSERT(isRenderTarget == false);

    ReleaseTextureData();

    bool descriptorReloaded = texDescriptor->Reload();

    eGPUFamily gpuForLoading = GetGPUForLoading(gpuFamily, texDescriptor);
    Vector<Image*>* images = new Vector<Image*>();

    bool loaded = false;
    if (descriptorReloaded && Renderer::GetOptions()->IsOptionEnabled(RenderOptions::TEXTURE_LOAD_ENABLED))
    {
        loaded = LoadImages(gpuForLoading, images);
    }

    if (loaded)
    {
        loadedAsFile = gpuForLoading;

        SetParamsFromImages(images);
        FlushDataToRenderer(images);
    }
    else
    {
        SafeDelete(images);

        Logger::Error("[Texture::ReloadAs] Cannot reload from file %s for GPU %s", texDescriptor->pathname.GetAbsolutePathname().c_str(), GlobalEnumMap<eGPUFamily>::Instance()->ToString(gpuFamily));
        MakePink();
    }
    rhi::ReplaceTextureInAllTextureSets(oldHandle, handle);
}

bool Texture::IsLoadAvailable(const eGPUFamily gpuFamily) const
{
    if (texDescriptor->IsCompressedFile())
    {
        return true;
    }

    if (GPUFamilyDescriptor::IsGPUForDevice(gpuFamily) && texDescriptor->compression[gpuFamily].format == FORMAT_INVALID)
    {
        return false;
    }

    return true;
}

int32 Texture::Release()
{
    if (GetRetainCount() == 1)
    {
        textureMapMutex.Lock();
        textureMap.erase(FILEPATH_MAP_KEY(texDescriptor->pathname));
        textureMapMutex.Unlock();
    }
    return BaseObject::Release();
}

Texture* Texture::CreateFBO(const Texture::FBODescriptor& fboDesc)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    uint32 w = fboDesc.width;
    uint32 h = fboDesc.height;
    PixelFormat format = fboDesc.format;
    bool needDepth = fboDesc.needDepth;
    rhi::TextureType requestedType = fboDesc.textureType;

    int32 dx = Max(static_cast<int32>(w), 8);
    if (fboDesc.ensurePowerOf2)
    {
        EnsurePowerOf2(dx);
    }

    int32 dy = Max(static_cast<int32>(h), 8);
    if (fboDesc.ensurePowerOf2)
    {
        EnsurePowerOf2(dy);
    }

    Texture* tx = new Texture();
    tx->width = dx;
    tx->height = dy;
    tx->textureType = requestedType;
    tx->texDescriptor->format = format;
    tx->samplerState.mipFilter = tx->texDescriptor->drawSettings.mipFilter = rhi::TEXMIPFILTER_NONE;
    tx->samplerStateHandle = CreateSamplerStateHandle(tx->samplerState);

    const PixelFormatDescriptor& formatDescriptor = PixelFormatDescriptor::GetPixelFormatDescriptor(format);
    rhi::Texture::Descriptor descriptor;
    descriptor.width = tx->width;
    descriptor.height = tx->height;
    descriptor.autoGenMipmaps = false;
    descriptor.isRenderTarget = true;
    descriptor.needRestore = false;
    descriptor.type = requestedType;
    descriptor.format = formatDescriptor.format;
    descriptor.sampleCount = fboDesc.sampleCount;
    if (fboDesc.needPixelReadback)
    {
        descriptor.cpuAccessRead = true;
        descriptor.cpuAccessWrite = false;
    }

    DVASSERT(descriptor.format != static_cast<rhi::TextureFormat>(-1)); //unsupported format
    tx->handle = rhi::CreateTexture(descriptor);

    if (needDepth)
    {
        descriptor.isRenderTarget = false;
        descriptor.format = rhi::TEXTURE_FORMAT_D24S8;
        descriptor.type = rhi::TEXTURE_TYPE_2D;
        tx->handleDepthStencil = rhi::CreateTexture(descriptor);
    }

    rhi::TextureSetDescriptor textureSetDesc;
    textureSetDesc.fragmentTexture[0] = tx->handle;
    textureSetDesc.fragmentTextureCount = 1;
    tx->singleTextureSet = rhi::AcquireTextureSet(textureSetDesc);

    tx->isRenderTarget = true;
    tx->texDescriptor->pathname = Format("FBO texture %d", textureFboCounter);
    AddToMap(tx);

    textureFboCounter++;

    return tx;
}

Texture* Texture::CreateFBO(uint32 w, uint32 h, PixelFormat format, bool needDepth, rhi::TextureType requestedType, bool ensurePowerOf2)
{
    FBODescriptor fboDesc;

    fboDesc.width = w;
    fboDesc.height = h;
    fboDesc.format = format;
    fboDesc.needDepth = needDepth;
    fboDesc.needPixelReadback = false;
    fboDesc.textureType = requestedType;
    fboDesc.ensurePowerOf2 = ensurePowerOf2;

    return CreateFBO(fboDesc);
}

void Texture::DumpTextures()
{
    uint32 allocSize = 0;
    int32 cnt = 0;
    Logger::FrameworkDebug("============================================================");
    Logger::FrameworkDebug("--------------- Currently allocated textures ---------------");

    textureMapMutex.Lock();
    for (TexturesMap::iterator it = textureMap.begin(); it != textureMap.end(); ++it)
    {
        Texture* t = it->second;
        Logger::FrameworkDebug("%s with id %d (%dx%d) retainCount: %d debug: %s format: %s", t->texDescriptor->pathname.GetAbsolutePathname().c_str(), static_cast<uint32>(t->handle), t->width, t->height,
                               t->GetRetainCount(), t->debugInfo.c_str(), PixelFormatDescriptor::GetPixelFormatString(t->texDescriptor->format));
        cnt++;

        DVASSERT((0 <= t->texDescriptor->format) && (t->texDescriptor->format < FORMAT_COUNT));
        if (FORMAT_INVALID != t->texDescriptor->format)
        {
            allocSize += t->width * t->height * PixelFormatDescriptor::GetPixelFormatSizeInBits(t->texDescriptor->format);
        }
    }
    textureMapMutex.Unlock();

    Logger::FrameworkDebug("      Total allocated textures %d    memory size %d", cnt, allocSize / 8);
    Logger::FrameworkDebug("============================================================");
}

void Texture::SetDebugInfo(const String& _debugInfo)
{
#if defined(__DAVAENGINE_DEBUG__)
    debugInfo = FastName(_debugInfo.c_str());
#endif
}

void Texture::RestoreRenderResource()
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();
    if ((!handle.IsValid()) || (!NeedRestoreTexture(handle)))
        return;

    Vector<Image*> images;

    const FilePath& relativePathname = texDescriptor->GetSourceTexturePathname();
    FilePath::ePathType pathType = relativePathname.GetType();

    bool shouldMakePink = isPink || (pathType == FilePath::PATH_EMPTY);

    if ((pathType == FilePath::PATH_IN_FILESYSTEM) || (pathType == FilePath::PATH_IN_RESOURCES) || (pathType == FilePath::PATH_IN_DOCUMENTS))
    {
        eGPUFamily gpuForLoading = GetGPUForLoading(loadedAsFile, texDescriptor);
        LoadImages(gpuForLoading, &images);
        if (images.empty())
        {
            String absolutePath = relativePathname.GetAbsolutePathname();
            Logger::Error("Unable to restore texture from file: %s", absolutePath.c_str());
            shouldMakePink = true;
        }
    }

    if (shouldMakePink)
    {
        DVASSERT(images.empty());

        if (texDescriptor->IsCubeMap())
        {
            for (uint32 i = 0; i < Texture::CUBE_FACE_COUNT; ++i)
            {
                Image* img = Image::Create(width, height, FORMAT_RGBA8888);
                img->MakePink(true);
                img->cubeFaceID = i;
                img->mipmapLevel = 0;
                images.push_back(img);
            }
        }
        else
        {
            Image* img = Image::Create(width, height, FORMAT_RGBA8888);
            img->MakePink(true);
            images.push_back(img);
        }
    }

    for (uint32 i = 0, sz = static_cast<uint32>(images.size()); i < sz; ++i)
    {
        Image* img = images[i];
        TexImage((img->mipmapLevel != static_cast<uint32>(-1)) ? img->mipmapLevel : i, img->width, img->height, img->data, img->dataSize, img->cubeFaceID);
    }

    ReleaseImages(&images);
}

Image* Texture::CreateImageFromMemory()
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    Image* image = nullptr;

    void* mappedData = rhi::MapTexture(handle);
    image = Image::CreateFromData(width, height, texDescriptor->format, static_cast<uint8*>(mappedData));
    rhi::UnmapTexture(handle);

    return image;
}

const TexturesMap& Texture::GetTextureMap()
{
    return textureMap;
}

uint32 Texture::GetDataSize() const
{
    DVASSERT((0 <= texDescriptor->format) && (texDescriptor->format < FORMAT_COUNT));

    uint32 allocSize = width * height * PixelFormatDescriptor::GetPixelFormatSizeInBits(texDescriptor->format) / 8;
    return allocSize;
}

Texture* Texture::CreatePink(rhi::TextureType requestedType, bool checkers)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    // we need instances for pink textures for ResourceEditor. We use it for reloading for different GPUs
    // pink textures at game is invalid situation
    Texture* tex = new Texture();
    if (rhi::TEXTURE_TYPE_CUBE == requestedType)
    {
        tex->texDescriptor->Initialize(rhi::TEXADDR_CLAMP, true);
        tex->texDescriptor->dataSettings.cubefaceFlags = 0x000000FF;
    }
    else
    {
        tex->texDescriptor->Initialize(rhi::TEXADDR_CLAMP, false);
    }

    tex->MakePink(checkers);

    return tex;
}

void Texture::MakePink(bool checkers)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    Vector<Image*>* images = new Vector<Image*>();
    if (texDescriptor->IsCubeMap())
    {
        for (uint32 i = 0; i < Texture::CUBE_FACE_COUNT; ++i)
        {
            Image* img = Image::CreatePinkPlaceholder(checkers);
            img->cubeFaceID = i;
            img->mipmapLevel = 0;

            images->push_back(img);
        }
    }
    else
    {
        images->push_back(Image::CreatePinkPlaceholder(checkers));
    }

    SetParamsFromImages(images);
    FlushDataToRenderer(images);

    isPink = true;

    SetMinMagFilter(rhi::TEXFILTER_NEAREST, rhi::TEXFILTER_NEAREST, rhi::TEXMIPFILTER_NONE);
}

bool Texture::IsPinkPlaceholder()
{
    return isPink;
}

void Texture::SetGPULoadingOrder(const Vector<eGPUFamily>& gpuLoadingOrder_)
{
    gpuLoadingOrder = gpuLoadingOrder_;
}

const Vector<eGPUFamily>& Texture::GetGPULoadingOrder()
{
    return gpuLoadingOrder;
}

eGPUFamily Texture::GetPrimaryGPUForLoading()
{
    if (gpuLoadingOrder.empty())
    {
        return eGPUFamily::GPU_INVALID;
    }

    return gpuLoadingOrder[0];
}

eGPUFamily Texture::GetGPUForLoading(const eGPUFamily requestedGPU, const TextureDescriptor* descriptor)
{
    if (descriptor->IsCompressedFile())
        return descriptor->gpu;

    return requestedGPU;
}

const FilePath& Texture::GetPathname() const
{
    return texDescriptor->pathname;
}

void Texture::SetPathname(const FilePath& path)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    textureMapMutex.Lock();
    textureMap.erase(FILEPATH_MAP_KEY(texDescriptor->pathname));
    texDescriptor->OverridePathName(path);
    if (!texDescriptor->pathname.IsEmpty())
    {
        DVASSERT(textureMap.find(FILEPATH_MAP_KEY(texDescriptor->pathname)) == textureMap.end());
        textureMap[FILEPATH_MAP_KEY(texDescriptor->pathname)] = this;
    }
    textureMapMutex.Unlock();
}

PixelFormat Texture::GetFormat() const
{
    return texDescriptor->format;
}

void Texture::SetPixelization(bool value)
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    //     if (value == pixelizationFlag)
    //     {
    //         return;
    //     }

    pixelizationFlag = value;
    const TexturesMap& texturesMap = GetTextureMap();

    textureMapMutex.Lock();
    for (Map<FilePath, Texture*>::const_iterator iter = texturesMap.begin(); iter != texturesMap.end(); iter++)
    {
        Texture* texture = iter->second;
        rhi::TextureFilter minFilter = pixelizationFlag ? rhi::TextureFilter::TEXFILTER_NEAREST : rhi::TextureFilter(texture->GetDescriptor()->drawSettings.minFilter);
        rhi::TextureFilter magFilter = pixelizationFlag ? rhi::TextureFilter::TEXFILTER_NEAREST : rhi::TextureFilter(texture->GetDescriptor()->drawSettings.magFilter);
        rhi::TextureMipFilter mipFilter = pixelizationFlag ? rhi::TextureMipFilter::TEXMIPFILTER_NONE : rhi::TextureMipFilter(texture->GetDescriptor()->drawSettings.mipFilter);

        texture->SetMinMagFilter(minFilter, magFilter, mipFilter);
    }
    textureMapMutex.Unlock();
    //RHI_COMPLETE
}

uint32 Texture::GetBaseMipMap() const
{
    DAVA_MEMORY_PROFILER_CLASS_ALLOC_SCOPE();

    if (texDescriptor->GetQualityGroup().IsValid())
    {
        const TextureQuality* curTxQuality = QualitySettingsSystem::Instance()->GetTxQuality(QualitySettingsSystem::Instance()->GetCurTextureQuality());
        if (nullptr != curTxQuality)
        {
            return static_cast<uint32>(curTxQuality->albedoBaseMipMapLevel);
        }
    }

    return 0;
}
rhi::HSamplerState Texture::CreateSamplerStateHandle(const rhi::SamplerState::Descriptor::Sampler& samplerState)
{
    rhi::SamplerState::Descriptor samplerDesc;

    samplerDesc.fragmentSampler[0] = samplerState;
    samplerDesc.fragmentSamplerCount = 1;

    return rhi::AcquireSamplerState(samplerDesc);
}
};


text:
<title>Trees - GNU Compiler Collection (GCC) Internals</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="GNU Compiler Collection (GCC) Internals">
<meta name="generator" content="makeinfo 4.7">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="Passes.html#Passes" title="Passes">
<link rel="next" href="RTL.html#RTL" title="RTL">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: RTL,
Previous: Passes,
Up: Top

9 Trees: The intermediate representation used by the C and C++ front ends

This chapter documents the internal representation used by GCC to
represent C and C++ source programs.  When presented with a C or C++
source program, GCC parses the program, performs semantic analysis
(including the generation of error messages), and then produces the
internal representation described here.  This representation contains a
complete representation for the entire translation unit provided as
input to the front end.  This representation is then typically processed
by a code-generator in order to produce machine code, but could also be
used in the creation of source browsers, intelligent editors, automatic
documentation generators, interpreters, and any other programs needing
the ability to process C or C++ code.

This chapter explains the internal representation.  In particular, it
documents the internal representation for C and C++ source
constructs, and the macros, functions, and variables that can be used to
access these constructs.  The C++ representation is largely a superset
of the representation used in the C front end.  There is only one
construct used in C that does not appear in the C++ front end and that
is the GNU “nested function” extension.  Many of the macros documented
here do not apply in C because the corresponding language constructs do
not appear in C.

If you are developing a “back end”, be it is a code-generator or some
other tool, that uses this representation, you may occasionally find
that you need to ask questions not easily answered by the functions and
macros available here.  If that situation occurs, it is quite likely
that GCC already supports the functionality you desire, but that the
interface is simply not documented here.  In that case, you should ask
the GCC maintainers (via mail to gcc@gcc.gnu.org) about
documenting the functionality you require.  Similarly, if you find
yourself writing functions that do not deal directly with your back end,
but instead might be useful to other people using the GCC front end, you
should submit your patches for inclusion in GCC.

Deficiencies:         Topics net yet covered in this document.

Tree overview:        All about trees.

Types:                Fundamental and aggregate types.

Scopes:               Namespaces and classes.

Functions:            Overloading, function bodies, and linkage.

Declarations:         Type declarations and variables.

Attributes:           Declaration and type attributes.

Expression trees:     From typeid to throw.


text:
/// <reference path="fourslash.ts" />

////import x = M./**/

verify.completions({ marker: "", exact: undefined });


text:
import sys
from typing import TYPE_CHECKING

if sys.version_info < (3, 7) or TYPE_CHECKING:
    from ._layout import LayoutValidator
    from ._data import DataValidator
else:
    from _plotly_utils.importers import relative_import

    __all__, __getattr__, __dir__ = relative_import(
        __name__, [], ["._layout.LayoutValidator", "._data.DataValidator"]
    )


text:
package org.hisrc.azw.camel.gcm;

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

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.hisrc.azw.event.FacilityStateChangedEvent;
import org.hisrc.azw.model.Facility;
import org.hisrc.azw.model.FacilityStateSnapshot;
import org.hisrc.azw.model.FacilityType;
import org.hisrc.azw.model.Station;
import org.hisrc.camel.component.gcm.GcmConstants;

public class FacilityStateChangedEventToGcmPayloadProcessor implements Processor {

	@Override
	public void process(Exchange exchange) throws Exception {

		final FacilityStateChangedEvent event = exchange.getIn().getBody(FacilityStateChangedEvent.class);

		if (event != null) {
			final Map<String, String> data = new HashMap<String, String>();
			final Station station = event.getSource();
			data.put("stationnumber", station.getStationnumber().toString());
			data.put("stationname", station.getName());
			final Facility facility = event.getFacility();
			final String facilityDescription = facility.getDescription();
			if (facilityDescription != null) {
				data.put("facilityDescription", facilityDescription);
			}
			final Long facilityEquipmentnumber = facility.getEquipmentnumber();
			data.put("facilityEquipmentnumber", facilityEquipmentnumber.toString());
			final FacilityType facilityType = facility.getType();
			data.put("facilityType", facilityType.name());

			final FacilityStateSnapshot oldSnapshot = event.getOldSnapshot();
			if (oldSnapshot != null) {
				data.put("oldFacilityState", oldSnapshot.getState().name());
				data.put("oldFacilityStateKnownSince", oldSnapshot.getTimestamp().toString());
			}
			final FacilityStateSnapshot newSnapshot = event.getNewSnapshot();
			data.put("newFacilityState", newSnapshot.getState().name());
			data.put("newFacilityStateKnownSince", newSnapshot.getTimestamp().toString());
			final String topic = MessageFormat.format("/topics/facility-{0,number,#}", facilityEquipmentnumber);
			exchange.getIn().setHeader(GcmConstants.TO, topic);
			exchange.getIn().setBody(data);
		}
	}

}


text:
using System;
using Swashbuckle.Swagger;

namespace Swashbuckle.Dummy.SwaggerExtensions
{
    public class ApplySchemaVendorExtensions : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            schema.vendorExtensions.Add("x-schema", "bar");
        }
    }
}


text:
namespace NadekoBot.DataModels {
    internal class CurrencyTransaction : IDataModel {
        public string Reason { get; set; }
        public int Value { get; set; }
        public long UserId { get; set; }
    }
}


text:
<?php

namespace CultuurNet\UDB3\Offer;

use TwoDotsTwice\Collection\AbstractCollection;

/**
 * @method OfferIdentifierCollection with($item)
 * @method IriOfferIdentifier[] toArray()
 */
class OfferIdentifierCollection extends AbstractCollection
{
    protected function getValidObjectType()
    {
        return IriOfferIdentifier::class;
    }
}


text:
CScript_EventPseudoModel::CScript_EventPseudoModel(CXFA_Document* pDocument)
    : CXFA_Object(pDocument,
                  XFA_ObjectType::Object,
                  XFA_Element::EventPseudoModel,
                  pdfium::MakeUnique<CJX_EventPseudoModel>(this)) {}

CScript_EventPseudoModel::~CScript_EventPseudoModel() = default;