text:
#ifndef MIRTK_BoundarySegment_H
#define MIRTK_BoundarySegment_H

#include "mirtk/Object.h"
#include "mirtk/Array.h"
#include "mirtk/Vector.h"
#include "mirtk/Point.h"
#include "mirtk/UnorderedMap.h"

#include "vtkSmartPointer.h"
#include "vtkPolyData.h"

namespace mirtk {

/**
 * Closed boundary segment of surface mesh
 *
 * A boundary segment is a closed line strip defined by an ordered list of point
 * indices with an edge between each consecutive pair of points. The boundary
 * loop is closed by the edge connecting the last point with the first point.
 * A surface mesh may have any number of boundary segments, including no boundary
 * at all in case of a closed genus-0 surface mesh which is topologically
 * equivalent to a sphere. This class represents a single boundary segment.
 */
class BoundarySegment : public Object
{
  mirtkObjectMacro(BoundarySegment);

  // ---------------------------------------------------------------------------
  // Types

  /// Type of surface point ID to boundary segment point index map
  typedef UnorderedMap<int, int> PointIdToIndexMap;

  // ---------------------------------------------------------------------------
  // Attributes

  /// Surface mesh which this boundary segment belongs to
  mirtkReadOnlyAttributeMacro(vtkSmartPointer<vtkPolyData>, Surface);

  /// IDs of boundary segment points
  mirtkReadOnlyAttributeMacro(Array<int>, PointIds);

  /// Pre-computed map from surface point ID to boundary segment point index
  mirtkAttributeMacro(PointIdToIndexMap, Index);

  /// Indices of selected points
  mirtkAttributeMacro(Array<int>, Selection);

  /// Pre-computed boundary segment edge lengths
  Vector _EdgeLengths;

  /// Length of boundary segment
  double _Length;

  /// Copy attributes of this class from another instance
  void CopyAttributes(const BoundarySegment &);

  // ---------------------------------------------------------------------------
  // Construction/Destruction

public:

  /// Default constructor
  BoundarySegment();

  /// Constructor
  ///
  /// \param[in] surface Surface mesh.
  /// \param[in] ptIds   Ordered list of IDs of surface points making up this
  ///                    boundary segment.
  BoundarySegment(vtkPolyData *surface, const Array<int> &ptIds);

  /// Copy constructor
  BoundarySegment(const BoundarySegment &);

  /// Assignment operator
  BoundarySegment &operator =(const BoundarySegment &);

  /// Destructor
  virtual ~BoundarySegment();

  // ---------------------------------------------------------------------------
  // Initialization

  /// Pre-compute map of surface point ID to boundary segment point index
  void InitializeIndex();

  // Pre-compute edge lengths and total length
  void InitializeLengths();

  /// Compute edge lengths
  Vector ComputeEdgeLengths() const;

  /// Compute length of boundary segment
  double ComputeLength() const;

  // ---------------------------------------------------------------------------
  // Boundary points

  /// Number of boundary segment points
  int NumberOfPoints() const;

  /// Get boundary segment point index in range [0, N)
  int IndexModuloNumberOfPoints(int i) const;

  /// Get surface point ID of i-th boundary segment point
  ///
  /// \param[in] i Index of boundary segment point.
  ///
  /// \returns Surface point ID of i-th boundary segment point.
  int PointId(int i) const;

  /// Get boundary segment point coordinates
  ///
  /// \param[in]  i Index of boundary segment point.
  /// \param[out] p Coordinates of i-th boundary segment point.
  void GetPoint(int i, double p[3]) const;

  /// Set boundary segment point coordinates
  ///
  /// \param[in] i Index of boundary segment point.
  /// \param[in] p New coordinates of i-th boundary segment point.
  void SetPoint(int i, const double p[3]);

  /// Get boundary segment point coordinates
  ///
  /// \param[in] i Index of boundary segment point.
  ///
  /// \returns Coordinates of i-th boundary segment point.
  class Point Point(int i) const;

  /// Set boundary segment point coordinates
  ///
  /// \param[in] i Index of boundary segment point.
  /// \param[in] p New coordinates of i-th boundary segment point.
  void Point(int i, const class Point &p);

  /// Find surface point in boundary segment
  ///
  /// \param[in] ptId Surface point ID.
  ///
  /// \returns Boundary segment point index or -1 if segment does not contain this point.
  int Find(int ptId) const;

  /// Find closest boundary point
  ///
  /// \param[in] x     Point coordinates.
  /// \param[in] dist2 Squared distance of closest boundary point.
  ///
  /// \returns Index of closest boundary segment point.
  int FindClosestPoint(const class Point &x, double *dist2 = nullptr) const;

  /// Whether this boundary segment contains a given surface point
  ///
  /// \param[in] ptId Surface point ID.
  ///
  /// \returns Whether surface point ID is part of this boundary segment.
  bool Contains(int ptId) const;

  // ---------------------------------------------------------------------------
  // Boundary edges

  /// Get total length of boundary segment
  double Length() const;

  /// Get lengths of boundary segment edges
  Vector EdgeLengths() const;

  /// Length of boundary segment edge
  ///
  /// \param[in] i  Index of first boundary segment point.
  /// \param[in] di Index increment +1 or -1, i.e., traversal direction.
  ///
  /// \returns Boundary segment edge lengths.
  double EdgeLength(int i, int di = +1) const;

  // ---------------------------------------------------------------------------
  // Selected points

  /// Reserve space for n selected points
  ///
  /// \param[in] n Number of points to be selected.
  void ReserveSelection(int n);

  /// Remove the i-th selected point
  ///
  /// \param[in] i Selected point index.
  void RemoveSelection(int i);

  /// Deselect all points
  void ClearSelection();

  /// Add i-th boundary segment point to selection
  ///
  /// \param[in] i Boundary segment point index.
  void SelectPoint(int i);

  /// Remove i-th boundary segment point from selection
  ///
  /// \param[in] i Boundary segment point index.
  void DeselectPoint(int i);

  /// Number of selected curve points
  int NumberOfSelectedPoints() const;

  /// Get boundary segment point index of i-th selected boundary point
  ///
  /// \param[in] i Index of selected point.
  ///
  /// \return Index of corresponding boundary segment point.
  int SelectedPointIndex(int i) const;

  /// Get surface point ID of i-th selected boundary point
  ///
  /// \param[in] i Index of selected point.
  ///
  /// \return Index of corresponding surface point.
  int SelectedPointId(int i) const;

  /// Get selected boundary segment point coordinates
  ///
  /// \param[in]  i Index of selected boundary segment point.
  /// \param[out] p Coordinates of i-th selected boundary segment point.
  void GetSelectedPoint(int i, double p[3]) const;

  /// Get selected boundary segment point coordinates
  ///
  /// \param[in] i Index of selected boundary segment point.
  ///
  /// \returns Coordinates of i-th selected boundary segment point.
  class Point SelectedPoint(int i) const;

  /// Check if boundary segment point is selected
  ///
  /// \param[in] i Index of boundary segment point.
  ///              The index is taken modulo the number of boundary
  ///              points and negative values count from the end of
  ///              the list of boundary points.
  ///
  /// \return Whether boundary segment point is selected.
  bool IsSelected(int i) const;

};

////////////////////////////////////////////////////////////////////////////////
// Inline definitions
////////////////////////////////////////////////////////////////////////////////

// =============================================================================
// Initialization
// =============================================================================

// -----------------------------------------------------------------------------
inline double BoundarySegment::ComputeLength() const
{
  if (_EdgeLengths) return _EdgeLengths.Sum();
  return ComputeEdgeLengths().Sum();
}

// =============================================================================
// Boundary points
// =============================================================================

// -----------------------------------------------------------------------------
inline int BoundarySegment::NumberOfPoints() const
{
  return static_cast<int>(_PointIds.size());
}

// -----------------------------------------------------------------------------
inline int BoundarySegment::IndexModuloNumberOfPoints(int i) const
{
  const int n = NumberOfPoints();
  if      (i <  0) i = (i + 1) % n + n - 1;
  else if (i >= n) i =  i      % n;
  return i;
}

// -----------------------------------------------------------------------------
inline int BoundarySegment::PointId(int i) const
{
  i = IndexModuloNumberOfPoints(i);
  return _PointIds[i];
}

// -----------------------------------------------------------------------------
inline void BoundarySegment::GetPoint(int i, double p[3]) const
{
  i = IndexModuloNumberOfPoints(i);
  _Surface->GetPoint(static_cast<vtkIdType>(PointId(i)), p);
}

// -----------------------------------------------------------------------------
inline void BoundarySegment::SetPoint(int i, const double p[3])
{
  i = IndexModuloNumberOfPoints(i);
  _Surface->GetPoints()->SetPoint(static_cast<vtkIdType>(PointId(i)), const_cast<double *>(p));
}

// -----------------------------------------------------------------------------
inline Point BoundarySegment::Point(int i) const
{
  double p[3];
  GetPoint(i, p);
  return p;
}

// -----------------------------------------------------------------------------
inline void BoundarySegment::Point(int i, const class Point &p)
{
  SetPoint(i, p);
}

// -----------------------------------------------------------------------------
inline bool BoundarySegment::Contains(int ptId) const
{
  return Find(ptId) != -1;
}

// =============================================================================
// Boundary edges
// =============================================================================

// -----------------------------------------------------------------------------
inline double BoundarySegment::Length() const
{
  if (_Length > 0.) return _Length;
  return ComputeLength();
}

// -----------------------------------------------------------------------------
inline Vector BoundarySegment::EdgeLengths() const
{
  if (_EdgeLengths) return _EdgeLengths;
  return ComputeEdgeLengths();
}

// -----------------------------------------------------------------------------
inline double BoundarySegment::EdgeLength(int i, int di) const
{
  if (_EdgeLengths) {
    return _EdgeLengths(IndexModuloNumberOfPoints(di < 0 ? i-1 : i));
  } else {
    return Point(i).Distance(Point(i + di));
  }
}

// =============================================================================
// Selected points
// =============================================================================

// -----------------------------------------------------------------------------
inline int BoundarySegment::NumberOfSelectedPoints() const
{
  return static_cast<int>(_Selection.size());
}

// -----------------------------------------------------------------------------
inline int BoundarySegment::SelectedPointIndex(int i) const
{
  return _Selection[i];
}

// -----------------------------------------------------------------------------
inline int BoundarySegment::SelectedPointId(int i) const
{
  return _PointIds[_Selection[i]];
}

// -----------------------------------------------------------------------------
inline void BoundarySegment::GetSelectedPoint(int i, double p[3]) const
{
  GetPoint(_Selection[i], p);
}

// -----------------------------------------------------------------------------
inline Point BoundarySegment::SelectedPoint(int i) const
{
  return Point(_Selection[i]);
}

// -----------------------------------------------------------------------------
inline bool BoundarySegment::IsSelected(int i) const
{
  for (auto it = _Selection.begin(); it != _Selection.end(); ++it) {
    if (*it == i) return true;
  }
  return false;
}

} // namespace mirtk

#endif // MIRTK_BoundarySegment_H


text:
angular.module('angularDeckster.controllers')
.controller('decksterCardCtrl', ['$scope', '$compile', '$window', 'decksterConfig', function($scope, $compile, $window, decksterConfig) {
  var cardEl = null;
  var summaryLoaded = false;
  var detailsLoaded = false;
  var self = this;
  var _origSize = {};
  var _origPos = [];

  $scope.expanded = false;
  $scope.loading = false;
  $scope.currentView = 'summary';

  $scope.toggleView = function() {
    $scope.currentView =  $scope.currentView === 'summary' ? 'details' : 'summary';
    self.loadContent($scope.currentView);
  };

  $scope.expandCard = function() {
    if(!$scope.expanded) {
      self.expandCard();
    } else {
      self.collapseCard();
    }
  };

  $scope.reloadCard = function() {
    self.reloadCard();
  };

  $scope.popoutCard = function() {

  };

  $scope.currentDate = function() {
    return Date.now();
  };

  $scope.hasPopout = function() {
    return self.hasPopout();
  };

  $scope.$on('deckster.cards.refresh', function() {
    self.reloadCard();
  });

  self.setCard = function(el) {
    cardEl = el;
    self.loadCard();
  };

  self.loadCard = function() {
    self.loadCardSummary();

    // If the card is a lazy one just load the summary content
    if(!$scope.card.isLazy()) {
     self.loadCardDetails();
    }
  };

  self.loadCardSummary = function() {
    $scope.loading = true;
    $scope.card.getSummaryContent(function(template) {
      var summaryEl = cardEl.find('.deckster-summary');
      summaryEl.html(template);

      $compile(summaryEl.contents())($scope);
      $scope.loading = false;
      summaryLoaded = true;
    });
  };

  self.loadCardDetails = function() {
    $scope.loading = true;
    $scope.card.getDetailContent(function(template) {
      var detailEl = cardEl.find('.deckster-detail');
      detailEl.html(template);

      $compile(detailEl.contents())($scope);
      $scope.loading = false;
      detailsLoaded = true;
    });
  };

  self.loadContent = function(view) {
    if(view === 'summary' && !summaryLoaded) {
      self.loadCardSummary();
    } else if(!detailsLoaded) {
      self.loadCardDetails();
    }
  };

  self.expandCard = function() {
    var $$window = angular.element($window);
    var maxRows = Math.floor($$window.height() / $scope.gridsterConfig.curRowHeight);

    _origSize = angular.copy($scope.card.size);
    _origPos = angular.copy($scope.card.position);

    $scope.card.size = {x: $scope.gridsterConfig.columns, y: maxRows};
    $scope.card.position = [0, 0];
    $scope.expanded = true;
  };

  self.collapseCard = function() {
    $scope.card.size = _origSize;
    $scope.card.position = _origPos;
    $scope.expanded = false;
  };

  self.hasPopout = function() {
    return angular.isDefined(decksterConfig.cardDefaults[$scope.card.id] && decksterConfig.cardDefaults[$scope.card.id].detailTemplateUrl);
  };

  self.reloadCard = function() {
    self.loadCard();
  };

}]);

redpajama_set_name: RedPajamaGithub


text:
@interface _ASCollectionGalleryLayoutInfo : NSObject

// Read-only properties
@property (nonatomic, readonly) CGSize itemSize;
@property (nonatomic, readonly) CGFloat minimumLineSpacing;
@property (nonatomic, readonly) CGFloat minimumInteritemSpacing;
@property (nonatomic, readonly) UIEdgeInsets sectionInset;

- (instancetype)initWithItemSize:(CGSize)itemSize
              minimumLineSpacing:(CGFloat)minimumLineSpacing
         minimumInteritemSpacing:(CGFloat)minimumInteritemSpacing
                    sectionInset:(UIEdgeInsets)sectionInset NS_DESIGNATED_INITIALIZER;

- (instancetype)init NS_UNAVAILABLE;

@end


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta content="yes" name="apple-mobile-web-app-capable">
	<meta content="yes" name="apple-touch-fullscreen">
	<meta content="telephone=no,email=no" name="format-detection">

	<link rel="apple-touch-icon" href="favicon.png">
	<link rel="Shortcut Icon" href="favicon.png" type="image/x-icon">

	<title>INCAKE | 我的喜欢</title>
	<link rel="stylesheet" href="assets/plugins/normalize/normalize.css" />
	<link rel="stylesheet" type="text/css" href="assets/css/global.css" />
	<link rel="stylesheet" href="assets/css/me-like.css" />
	<link rel="shortcut icon" href="favicon.ico" />


text:
using namespace vgui;
using namespace BaseModUI;

int GetScreenAspectMode( int width, int height );
void SetFlyoutButtonText( const char *pchCommand, FlyoutMenu *pFlyout, const char *pchNewText );

extern ConVar ui_gameui_modal;

//=============================================================================
Gameplay::Gameplay(Panel *parent, const char *panelName):
BaseClass(parent, panelName)
{
	if ( ui_gameui_modal.GetBool() )
	{
		GameUI().PreventEngineHideGameUI();
	}

	m_pHeaderFooter = new CNB_Header_Footer( this, "HeaderFooter" );
	m_pHeaderFooter->SetTitle( "" );
	m_pHeaderFooter->SetHeaderEnabled( false );
	m_pHeaderFooter->SetFooterEnabled( true );
	m_pHeaderFooter->SetGradientBarEnabled( true );
	m_pHeaderFooter->SetGradientBarPos( 200, 140 );

	SetDeleteSelfOnClose(true);

	SetProportional( true );

	SetUpperGarnishEnabled(true);
	SetLowerGarnishEnabled(true);

	m_sldGameVolume = NULL;
	m_drpSkillLevel = NULL;

	m_btnCancel = NULL;
}

//=============================================================================
Gameplay::~Gameplay()
{
	GameUI().AllowEngineHideGameUI();

	UpdateFooter( false );
}

//=============================================================================
void Gameplay::Activate()
{
	BaseClass::Activate();

	if ( m_sldGameVolume )
	{
		m_sldGameVolume->Reset();
	}

	if ( m_drpSkillLevel )
	{
		CGameUIConVarRef skill("skill");

		switch ( skill.GetInt() )
		{
		case 2:
			m_drpSkillLevel->SetCurrentSelection( "#HL2PORTUI_Skills_Medium" );
			break;
		case 3:
			m_drpSkillLevel->SetCurrentSelection( "#HL2PORTUI_Skills_Hard" );
			break;
		case 1:
		default:
			m_drpSkillLevel->SetCurrentSelection( "#HL2PORTUI_Skills_Easy" );
			break;
		}

		FlyoutMenu *pFlyout = m_drpSkillLevel->GetCurrentFlyout();
		if ( pFlyout )
		{
			pFlyout->SetListener( this );
		}
	}
	UpdateFooter( true );

	if ( m_sldGameVolume )
	{
		if ( m_ActiveControl )
			m_ActiveControl->NavigateFrom( );
		m_sldGameVolume->NavigateTo();
		m_ActiveControl = m_sldGameVolume;
	}
}

void Gameplay::OnThink()
{
	BaseClass::OnThink();

	bool needsActivate = false;

	if( !m_sldGameVolume )
	{
		m_sldGameVolume = dynamic_cast< SliderControl* >( FindChildByName( "SldGameVolume" ) ); //what's this?! [str]
		needsActivate = true;
	}

	if( !m_drpSkillLevel )
	{
		m_drpSkillLevel = dynamic_cast< DropDownMenu* >( FindChildByName( "DrpGameDifficulty" ) );
		needsActivate = true;
	}

	if( needsActivate )
	{
		Activate();
	}

}

void Gameplay::PerformLayout()
{
	BaseClass::PerformLayout();

	SetBounds( 0, 0, ScreenWidth(), ScreenHeight() );
}

void Gameplay::OnKeyCodePressed(KeyCode code)
{
	int joystick = GetJoystickForCode( code );
	int userId = CBaseModPanel::GetSingleton().GetLastActiveUserId();
	if ( joystick != userId || joystick < 0 )
	{
		return;
	}

	switch ( GetBaseButtonCode( code ) )
	{
	case KEY_XBUTTON_B:
		{
			// Ready to write that data... go ahead and nav back
			BaseClass::OnKeyCodePressed(code);
		}
		break;

	default:
		BaseClass::OnKeyCodePressed(code);
		break;
	}
}

//=============================================================================
void Gameplay::OnCommand(const char *command)
{
	if( Q_stricmp( "#HL2PORTUI_Skills_Hard", command ) == 0 )
	{
		// 3 is Hard
		CGameUIConVarRef skill( "skill" );
		skill.SetValue( 3 );
	}
	else if( Q_stricmp( "#HL2PORTUI_Skills_Medium", command ) == 0 )
	{
		// 2 is Medium
		CGameUIConVarRef skill( "skill" );
		skill.SetValue( 2 );
	}
	else if( Q_stricmp( "#HL2PORTUI_Skills_Easy", command ) == 0 )
	{
		// 1 is Easy
		CGameUIConVarRef skill( "skill" );
		skill.SetValue( 1 );
	}
	else if( Q_stricmp( "Back", command ) == 0 )
	{
		OnKeyCodePressed( ButtonCodeToJoystickButtonCode( KEY_XBUTTON_B, CBaseModPanel::GetSingleton().GetLastActiveUserId() ) );
	}
	else
	{
		BaseClass::OnCommand( command );
	}
}

void Gameplay::OnNotifyChildFocus( vgui::Panel* child )
{
}

void Gameplay::UpdateFooter( bool bEnableCloud )
{
	if ( !BaseModUI::CBaseModPanel::GetSingletonPtr() )
		return;

	CBaseModFooterPanel *footer = BaseModUI::CBaseModPanel::GetSingleton().GetFooterPanel();
	if ( footer )
	{
		footer->SetButtons( FB_ABUTTON | FB_BBUTTON, FF_AB_ONLY, false );
		footer->SetButtonText( FB_ABUTTON, "#L4D360UI_Select" );
		footer->SetButtonText( FB_BBUTTON, "#L4D360UI_Controller_Done" );

		footer->SetShowCloud( bEnableCloud );
	}
}

void Gameplay::OnFlyoutMenuClose( vgui::Panel* flyTo )
{
	UpdateFooter( true );
}

void Gameplay::OnFlyoutMenuCancelled()
{
}

//=============================================================================
Panel* Gameplay::NavigateBack()
{
	engine->ClientCmd_Unrestricted( VarArgs( "host_writeconfig_ss %d", XBX_GetPrimaryUserId() ) );

	return BaseClass::NavigateBack();
}

void Gameplay::PaintBackground()
{
	//BaseClass::DrawDialogBackground( "#GameUI_Audio", NULL, "#L4D360UI_AudioVideo_Desc", NULL, NULL, true );
}

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

	// required for new style
	SetPaintBackgroundEnabled( true );
	SetupAsDialogStyle();
}


text:
'use strict';

var OpenT2TConstants = require('opent2t').OpenT2TConstants;

function runTest(settings, t, testMethod) {
    let expectedException = settings.expectedExceptions === undefined ? undefined : settings.expectedExceptions[t.title];

    if (settings.setTestData) {
        settings.setTestData(t.title, t);
    }

    if (expectedException !== undefined) {
        return testMethod().then(() => {
            t.fail(`Error expected: ${expectedException}`);
        }).catch(error => {
            let message = expectedException.message;

            if (expectedException.isOpent2tError === undefined || expectedException.isOpent2tError === true) {
                t.is(error.name, 'OpenT2TError', `Verify error type, Actual: ${error.name}, Expected: OpenT2TError`);
                if (expectedException.statusCode !== undefined) {
                    t.is(error.statusCode, expectedException.statusCode, `Verify status code, Actual: ${error.statusCode}, Expected: ${expectedException.statusCode}`);
                }
                if (expectedException.messageConst !== undefined) {
                    message = OpenT2TConstants[expectedException.messageConst];
                }
            }

            if (message !== undefined) {
                t.is(error.message, message, `Verify error message, Actual: ${error.message}, Expected: ${message}`);
            }
        });
    }
    else {
        return testMethod();
    }
}

function verifyModesData(t, response) {
    t.is(response.rt[0], 'oic.r.mode', 'Verify mode resource type');
    t.is(Object.prototype.toString.call(response.modes), '[object Array]', 'Verify modes data is object array');
}

module.exports.runTest = runTest;
module.exports.verifyModesData = verifyModesData;


text:
.like-button {
    min-width:48px!important;
    height:50px;
	background: url(/etc/designs/scf/clientlibs/ideation/images/like.png) no-repeat right center!important;
}
.dislike-button {
    min-width:48px!important;
    height:50px;
	background: url(/etc/designs/scf/clientlibs/ideation/images/dislike.jpg) no-repeat right bottom!important;
}


text:
var get = Ember.get, set = Ember.set;

var serializer;

module("DS.RESTSerializer", {
  setup: function() {
    serializer = DS.RESTSerializer.create();
    serializer.configure('plurals', {
      person: 'people'
    });
  },
  teardown: function() {
    serializer.destroy();
  }
});

test("keyForAttributeName returns decamelized property name", function() {
  equal(serializer.keyForAttributeName(DS.Model, 'myName'), 'my_name');
  equal(serializer.keyForAttributeName(DS.Model, 'my_name'), 'my_name');
});

test("keyForBelongsTo returns the key appended with '_id'", function() {
  equal(serializer.keyForBelongsTo(DS.Model, 'person'), 'person_id');
  equal(serializer.keyForBelongsTo(DS.Model, 'town'), 'town_id');
  equal(serializer.keyForBelongsTo(DS.Model, 'homeTown'), 'home_town_id');
});

test("keyForHasMany returns the singularized key appended with '_ids'", function() {
  equal(serializer.keyForHasMany(DS.Model, 'people'), 'person_ids');
  equal(serializer.keyForHasMany(DS.Model, 'towns'), 'town_ids');
  equal(serializer.keyForHasMany(DS.Model, 'homeTowns'), 'home_town_ids');
});

test("extractBelongsToPolymorphic returns a tuple containing the type", function() {
  deepEqual(serializer.extractBelongsToPolymorphic(DS.Model, {message_id: 2, message_type: 'post'}, 'message_id'), {id: 2, type: 'post'});
});

test("Calling extract on a JSON payload with multiple records will tear them apart and call loader", function() {
  var App = Ember.Namespace.create({
    toString: function() { return "App"; }
  });

  App.Group = DS.Model.extend({
    name: DS.attr('string')
  });

  App.Post = DS.Model.extend({
    title: DS.attr('string'),
    groups: DS.hasMany(App.Group)
  });

  serializer.configure(App.Group, {
    sideloadAs: 'groups'
  });

  var payload = {
    post: {
      id: 1,
      title: "Fifty Ways to Bereave Your Lover",
      groups: [1]
    },

    groups: [{ id: 1, name: "Trolls" }]
  };

  var loadCallCount = 0,
      loadMainCallCount = 0;

  var loader = {
    sideload: function(type, data, prematerialized) {
      loadCallCount++;
    },

    load: function(type, data, prematerialized) {
      loadMainCallCount++;
    },

    prematerialize: Ember.K
  };

  serializer.extract(loader, payload, App.Post);

  equal(loadMainCallCount, 1, "one main record was loaded from a single payload");
  equal(loadCallCount, 1, "one secondary record was loaded from a single payload");

  //this.extractRecord(type, structure, loader)

  //function extractRecord(type, structure, loader) {
    //loader.load(type, structure, {
      //id: this.extractId(structure),
      //hasMany: { comments: [ 1,2,3 ] }
    //});
  //}
});

test("Sideloading can be done by specifying only an alias", function() {
  var App = Ember.Namespace.create({
    toString: function() { return "App"; }
  });

  App.Group = DS.Model.extend({
    name: DS.attr('string')
  });

  App.Post = DS.Model.extend({
    title: DS.attr('string')
  });

  serializer.configure(App.Group, {
    alias: 'group'
  });

  var payload = {
    post: {
      id: 1,
      title: "Fifty Ways to Bereave Your Lover"
    },

    groups: [{ id: 1, name: "Trolls" }]
  };

  var loadCallCount = 0,
      loadMainCallCount = 0;

  var loader = {
    sideload: function(type, data, prematerialized) {
      if(type === App.Group) {
        loadCallCount++;
      }
    },

    load: function(type, data, prematerialized) {
      loadMainCallCount++;
    },

    prematerialize: Ember.K
  };

  serializer.extract(loader, payload, App.Post);

  equal(loadMainCallCount, 1, "one main record was loaded from a single payload");
  equal(loadCallCount, 1, "one secondary record was loaded from a single payload");
});


text:
// Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Unit tests for the controller of the 'State Editor'. This also
 * includes unit tests for the training data service.
 */

describe('State Editor controller', function() {
  describe('StateEditor', function() {
    var scope, ctrl, ecs, cls, ess;
    var $httpBackend;
    var mockExplorationData;

    beforeEach(function() {
      module('oppia');
      // Set a global value for INTERACTION_SPECS that will be used by all the
      // descendant dependencies.
      module(function($provide) {
        $provide.constant('INTERACTION_SPECS', {
          TextInput: {
            display_mode: 'inline',
            is_terminal: false
          }
        });
      });
      mockExplorationData = {
        explorationId: 0,
        autosaveChangeList: function() {}
      };
      module(function($provide) {
        $provide.value('explorationData', mockExplorationData);
      });
      spyOn(mockExplorationData, 'autosaveChangeList');
    });

    beforeEach(inject(function($rootScope, $controller, $injector) {
      scope = $rootScope.$new();
      $httpBackend = $injector.get('$httpBackend');
      ecs = $injector.get('editorContextService');
      cls = $injector.get('changeListService');
      ess = $injector.get('explorationStatesService');
      IS = $injector.get('INTERACTION_SPECS');
      cof = $injector.get('ContentObjectFactory');

      GLOBALS.INVALID_NAME_CHARS = '#@&^%$';

      ess.init({
        'First State': {
          content: [{
            type: 'text',
            value: 'First State Content'
          }],
          interaction: {
            id: 'TextInput',
            answer_groups: [{
              rule_specs: [],
              outcome: {},
              correct: false
            }],
            fallbacks: []
          },
          param_changes: []
        },
        'Second State': {
          content: [{
            type: 'text',
            value: 'Second State Content'
          }],
          interaction: {
            id: 'TextInput',
            answer_groups: [{
              rule_specs: [],
              outcome: {},
              correct: false
            }],
            fallbacks: []
          },
          param_changes: []
        },
        'Third State': {
          content: [{
            type: 'text',
            value: 'This is some content.'
          }],
          interaction: {
            id: 'TextInput',
            answer_groups: [{
              rule_specs: [],
              outcome: {},
              correct: false
            }],
            fallbacks: []
          },
          param_changes: [{
            name: 'comparison',
            generator_id: 'Copier',
            customization_args: {
              value: 'something clever',
              parse_with_jinja: false
            }
          }]
        }
      });

      scope.getContent = function(contentString) {
        return [cof.createFromBackendDict({
          type: 'text',
          value: contentString
        })];
      };

      ctrl = $controller('StateEditor', {
        $scope: scope,
        editorContextService: ecs,
        changeListService: cls,
        explorationStatesService: ess,
        editabilityService: {
          isEditable: function() {
            return true;
          }
        },
        INTERACTION_SPECS: IS
      });
    }));

    it('should initialize the state name and related properties', function() {
      ecs.setActiveStateName('Third State');
      scope.initStateEditor();
      expect(scope.contentEditorIsOpen).toBe(false);
      expect(scope.content[0].value).toEqual('This is some content.');
    });

    it('should correctly handle no-op edits', function() {
      ecs.setActiveStateName('First State');
      scope.initStateEditor();
      expect(scope.contentEditorIsOpen).toBe(false);
      expect(scope.content).toEqual(scope.getContent('First State Content'));
      scope.openStateContentEditor();
      expect(scope.contentEditorIsOpen).toBe(true);
      scope.content = scope.getContent('First State Content');
      scope.saveTextContent();

      expect(scope.contentEditorIsOpen).toBe(false);
      expect(cls.getChangeList()).toEqual([]);
    });

    it('should check that content edits are saved correctly',
       function() {
      ecs.setActiveStateName('Third State');
      expect(cls.getChangeList()).toEqual([]);
      scope.openStateContentEditor();
      scope.content = scope.getContent('babababa');
      scope.saveTextContent();
      expect(cls.getChangeList().length).toBe(1);
      expect(cls.getChangeList()[0].new_value[0].value).toEqual('babababa');
      expect(cls.getChangeList()[0].old_value[0].value).toEqual(
        'This is some content.');

      scope.openStateContentEditor();
      scope.content = scope.getContent(
        'And now for something completely different.'
      );
      scope.saveTextContent();
      expect(cls.getChangeList().length).toBe(2);
      expect(cls.getChangeList()[1].new_value[0].value)
        .toEqual('And now for something completely different.');
      expect(cls.getChangeList()[1].old_value[0].value).toEqual('babababa');
    });

    it('should not save any changes to content when an edit is cancelled',
       function() {
      ecs.setActiveStateName('Third State');
      scope.initStateEditor();
      var contentBeforeEdit = angular.copy(scope.content);
      scope.content = scope.getContent('Test Content');
      scope.cancelEdit();
      expect(scope.contentEditorIsOpen).toBe(false);
      expect(scope.content).toEqual(contentBeforeEdit);
    });
  });

  describe('TrainingDataService', function() {
    var $httpBackend;
    var scope, siis, ecs, cls, rs, tds, ess, IS, RULE_TYPE_CLASSIFIER, rof;
    var mockExplorationData;

    beforeEach(module('oppia', GLOBALS.TRANSLATOR_PROVIDER_FOR_TESTS));

    beforeEach(function() {
      module('oppia');
      // Set a global value for INTERACTION_SPECS that will be used by all the
      // descendant dependencies.
      module(function($provide) {
        $provide.constant('INTERACTION_SPECS', {
          TextInput: {
            display_mode: 'inline',
            is_terminal: false
          }
        });
      });
      mockExplorationData = {
        explorationId: 0,
        autosaveChangeList: function() {}
      };
      module(function($provide) {
        $provide.value('explorationData', mockExplorationData);
      });
      spyOn(mockExplorationData, 'autosaveChangeList');
    });

    beforeEach(inject(function($rootScope, $controller, $injector) {
      scope = $rootScope.$new();
      $httpBackend = $injector.get('$httpBackend');
      siis = $injector.get('stateInteractionIdService');
      ecs = $injector.get('editorContextService');
      cls = $injector.get('changeListService');
      ess = $injector.get('explorationStatesService');
      rs = $injector.get('responsesService');
      tds = $injector.get('trainingDataService');
      IS = $injector.get('INTERACTION_SPECS');
      RULE_TYPE_CLASSIFIER = $injector.get('RULE_TYPE_CLASSIFIER');
      rof = $injector.get('RuleObjectFactory');

      // Set the currently loaded interaction ID.
      siis.savedMemento = 'TextInput';

      ess.init({
        State: {
          content: [{
            type: 'text',
            value: 'State Content'
          }],
          interaction: {
            id: 'TextInput',
            answer_groups: [{
              rule_specs: [{
                rule_type: 'Contains',
                inputs: {
                  x: 'Test'
                }
              }],
              outcome: {
                feedback: 'Feedback',
                dest: 'State'
              },
              correct: false
            }],
            default_outcome: {
              feedback: 'Default',
              dest: 'State'
            },
            fallbacks: [],
            confirmed_unclassified_answers: []
          },
          param_changes: []
        }
      });

      var state = ess.getState('State');
      rs.init({
        answerGroups: state.interaction.answerGroups,
        defaultOutcome: state.interaction.defaultOutcome,
        confirmedUnclassifiedAnswers: (
          state.interaction.confirmedUnclassifiedAnswers)
      });

      ecs.setActiveStateName('State');

      $httpBackend.when('GET', '/createhandler/training_data/0/State').respond({
        unhandled_answers: [{
          value: 'answer1',
          count: 2
        }, {
          value: 'answer2',
          count: 1
        }]
      });
    }));

    afterEach(function() {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    it('should call a backend handler to initialize training data', function() {
      // Answers should be in the order sent from the backend.
      $httpBackend.expectGET('/createhandler/training_data/0/State');
      tds.initializeTrainingData('0', 'State');
      $httpBackend.flush();
      expect(tds.getTrainingDataAnswers()).toEqual(['answer1', 'answer2']);
      expect(tds.getTrainingDataCounts()).toEqual([2, 1]);

      // Ensure it handles receiving no unhandled answers correctly.
      $httpBackend.expect(
        'GET', '/createhandler/training_data/0/State').respond({
          unhandled_answers: []
        });

      tds.initializeTrainingData('0', 'State');
      $httpBackend.flush();
      expect(tds.getTrainingDataAnswers()).toEqual([]);
      expect(tds.getTrainingDataCounts()).toEqual([]);
    });

    it('should be able to train answer groups and the default response',
        function() {
      // Training the first answer of a group should add a new classifier.
      tds.trainAnswerGroup(0, 'text answer');
      var state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer']
        })
      );

      // Training a second answer to the same group should append the answer to
      // the training data.
      tds.trainAnswerGroup(0, 'second answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer', 'second answer']
        })
      );

      // Training the default response should add information to the confirmed
      // unclassified answers.
      tds.trainDefaultResponse('third answer');
      state = ess.getState('State');
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([
        'third answer'
      ]);
    });

    it('should be able to retrain answers between answer groups and the ' +
        'default outcome', function() {
      // Retraining an answer from the answer group to the default outcome
      // should remove it from the first, then add it to the second.
      tds.trainAnswerGroup(0, 'text answer');
      tds.trainAnswerGroup(0, 'second answer');
      tds.trainDefaultResponse('third answer');

      // Verify initial state.
      var state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer', 'second answer']
        })
      );
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([
        'third answer'
      ]);

      // Try to retrain the second answer (answer group -> default response).
      tds.trainDefaultResponse('second answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer']
        })
      );
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([
        'third answer', 'second answer'
      ]);

      // Try to retrain the third answer (default response -> answer group).
      tds.trainAnswerGroup(0, 'third answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer', 'third answer']
        })
      );
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([
        'second answer'
      ]);
    });

    it('should properly clear the default answer and remove a classifier ' +
        'when it is not the last rule left in a group', function() {
      tds.trainAnswerGroup(0, 'text answer');
      tds.trainDefaultResponse('second answer');

      // Verify initial state.
      var state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer']
        })
      );
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([
        'second answer'
      ]);

      // Ensure emptying the default unclassified answers is handled properly.
      tds.trainAnswerGroup(0, 'second answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer', 'second answer']
        })
      );
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([]);

      // Ensure emptying the answer group's classifier properly deletes the rule
      // since there is another rule in the group.
      tds.trainDefaultResponse('second answer');
      tds.trainDefaultResponse('text answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules).toEqual([
        rof.createNew('Contains', {
          x: 'Test'
        })
      ]);
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([
        'second answer', 'text answer'
      ]);

      // Training the answer group should add the classifier back.
      tds.trainAnswerGroup(0, 'second answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules).toEqual([
        rof.createNew('Contains', {
          x: 'Test'
        }),
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['second answer']
        })
      ]);

      // Removing the the 'contains' rule from the group and then removing the
      // training data should not remove the classifier.
      state.interaction.answerGroups[0].rules.splice(0, 1);
      ess.setState('State', state);
      rs.init({
        answerGroups: state.interaction.answerGroups,
        defaultOutcome: state.interaction.defaultOutcome,
        confirmedUnclassifiedAnswers: (
          state.interaction.confirmedUnclassifiedAnswers)
      });

      tds.trainDefaultResponse('second answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules).toEqual([
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: []
        })
      ]);
    });

    it('should not be able to train duplicated answers', function() {
      tds.trainAnswerGroup(0, 'text answer');
      tds.trainDefaultResponse('second answer');

      // Verify initial state.
      var state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer']
        })
      );
      expect(state.interaction.confirmedUnclassifiedAnswers).toEqual([
        'second answer'
      ]);

      // Training a duplicate answer for the answer group should change nothing.
      tds.trainAnswerGroup(0, 'text answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer']
        })
      );

      // Training a duplicate answer for the default response should change
      // nothing.
      tds.trainDefaultResponse('second answer');
      state = ess.getState('State');
      expect(state.interaction.answerGroups[0].rules[1]).toEqual(
        rof.createNew(RULE_TYPE_CLASSIFIER, {
          training_data: ['text answer']
        })
      );
    });

    it('should remove unresolved answers after training', function() {
      tds.initializeTrainingData('0', 'State');
      $httpBackend.flush();

      // Training an answer group should remove an unresolved answer.
      tds.trainAnswerGroup(0, 'answer1');
      expect(tds.getTrainingDataAnswers()).toEqual(['answer2']);
      expect(tds.getTrainingDataCounts()).toEqual([1]);

      // Training the default response should also remove an answer.
      tds.trainDefaultResponse('answer2');
      expect(tds.getTrainingDataAnswers()).toEqual([]);
      expect(tds.getTrainingDataCounts()).toEqual([]);
    });

    it('should get all potential outcomes of an interaction', function() {
      // First the answer group's outcome is listed, then the default.
      expect(tds.getAllPotentialOutcomes(ess.getState('State'))).toEqual([{
          feedback: 'Feedback',
          dest: 'State'
        }, {
          feedback: 'Default',
          dest: 'State'
        }]);
    });
  });
});


text:
package snippets

// [START compute_start_enc_instance]
import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"google.golang.org/protobuf/proto"
)

// startInstanceWithEncKey starts a stopped Google Compute Engine instance (with encrypted disks).
func startInstanceWithEncKey(w io.Writer, projectID, zone, instanceName, key string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// key := "your_encryption_key"

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %v", err)
	}
	defer instancesClient.Close()

	instanceReq := &computepb.GetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	instance, err := instancesClient.Get(ctx, instanceReq)
	if err != nil {
		return fmt.Errorf("unable to get instance: %v", err)
	}

	req := &computepb.StartWithEncryptionKeyInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
		InstancesStartWithEncryptionKeyRequestResource: &computepb.InstancesStartWithEncryptionKeyRequest{
			Disks: []*computepb.CustomerEncryptionKeyProtectedDisk{
				{
					Source: proto.String(instance.GetDisks()[0].GetSource()),
					DiskEncryptionKey: &computepb.CustomerEncryptionKey{
						RawKey: proto.String(key),
					},
				},
			},
		},
	}

	op, err := instancesClient.StartWithEncryptionKey(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to start instance with encryption key: %v", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %v", err)
	}

	fmt.Fprintf(w, "Instance with encryption key started\n")

	return nil
}

// [END compute_start_enc_instance]


text: cp -f config/mongoid.template.yml config/mongoid.yml


text:
// Copyright (c) Petabridge <https://petabridge.com/>. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
// See ThirdPartyNotices.txt for references to third party code used inside Helios.

using System;
using Helios.Eventing;
using Helios.Eventing.Brokers;
using Helios.Eventing.Subscriptions;
using Xunit;

namespace Helios.Tests.Eventing
{
    /// <summary>
    ///     Tests for validating the approach of our SimpleEventBroker implementation
    /// </summary>
    public class SimpleEventBrokerTests
    {
        #region Setup / Teardown

        private readonly IEventBroker<int, int> eventBroker;

        public class SampleEventBrokerSubscriber
        {
            public bool ReceivedEvent { get; set; }
        }

        public SimpleEventBrokerTests()
        {
            eventBroker = new SimpleEventBroker<int, int>();
        }

        #endregion

        #region Tests

        [Fact]
        public void Should_notify_changes_in_subscribers()
        {
            //arrange
            var subscriberCount = 0;
            var changes = 0;
            var subscriber1 = new SampleEventBrokerSubscriber();

            //act
            eventBroker.SubscriptionAdded += (sender, args) =>
            {
                subscriberCount = args.SubscriberCount;
                changes++;
            };

            eventBroker.SubscriptionRemoved += (sender, args) =>
            {
                subscriberCount = args.SubscriberCount;
                changes++;
            };

            eventBroker.Subscribe(0, subscriber1.GetHashCode(), new NormalTopicSubscription((o, e) => { }));
            eventBroker.Unsubscribe(0, subscriber1.GetHashCode());

            //assert
            Assert.Equal(0, subscriberCount);
            Assert.Equal(2, changes);
        }

        [Fact]
        public void Should_notify_subscribers()
        {
            //arrange
            var subscriber1 = new SampleEventBrokerSubscriber();
            var subscriber2 = new SampleEventBrokerSubscriber();

            //act
            eventBroker.Subscribe(0, subscriber1.GetHashCode(),
                new NormalTopicSubscription((o, e) => { subscriber1.ReceivedEvent = true; }));
            eventBroker.Subscribe(0, subscriber2.GetHashCode(),
                new NormalTopicSubscription((o, e) => { subscriber2.ReceivedEvent = true; }));
            eventBroker.InvokeEvent(0, this, new EventArgs());

            //assert
            Assert.True(subscriber1.ReceivedEvent);
            Assert.True(subscriber2.ReceivedEvent);
        }

        [Fact]
        public void Should_only_notify_subscribers_on_relevant_topic()
        {
            //arrange
            var invoked = 0;
            var subscriber1 = new SampleEventBrokerSubscriber();
            var subscriber2 = new SampleEventBrokerSubscriber();
            var subscriber3 = new SampleEventBrokerSubscriber();
            var subscriber4 = new SampleEventBrokerSubscriber();

            eventBroker.Subscribe(0, subscriber1.GetHashCode(), new NormalTopicSubscription((o, e) =>
            {
                subscriber1.ReceivedEvent = true;
                invoked++;
            }));
            eventBroker.Subscribe(0, subscriber2.GetHashCode(), new NormalTopicSubscription((o, e) =>
            {
                subscriber2.ReceivedEvent = true;
                invoked++;
            }));

            eventBroker.Subscribe(2, subscriber3.GetHashCode(), new NormalTopicSubscription((o, e) =>
            {
                subscriber3.ReceivedEvent = true;
                invoked++;
            }));
            eventBroker.Subscribe(1, subscriber4.GetHashCode(), new NormalTopicSubscription((o, e) =>
            {
                subscriber4.ReceivedEvent = true;
                invoked++;
            }));

            //act
            eventBroker.InvokeEvent(1, this, new EventArgs());
            eventBroker.InvokeEvent(0, this, new EventArgs());

            //assert
            Assert.Equal(3, invoked);
            Assert.True(subscriber1.ReceivedEvent);
            Assert.True(subscriber2.ReceivedEvent);
            Assert.False(subscriber3.ReceivedEvent);
            Assert.True(subscriber4.ReceivedEvent);
        }

        #endregion
    }
}


text:
<!doctype html>

    <link rel="stylesheet" type="text/css" href="spectrum.css">

            <input type='text' id='custom' />


text:
/** \addtogroup netsocket */
/** @{*/
/* MeshInterface
 * Copyright (c) 2015 ARM Limited
 *
 * 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.
 */

#ifndef MESH_INTERFACE_H
#define MESH_INTERFACE_H

#include "netsocket/NetworkInterface.h"

/** MeshInterface class
 *
 *  Common interface that is shared between mesh hardware
 */
class MeshInterface : public virtual NetworkInterface {
public:

    virtual MeshInterface *meshInterface()
    {
        return this;
    }

    /** Get the default Mesh interface.
     *
     * This is provided as a weak method so applications can override.
     * Default behaviour is to get the target's default interface, if
     * any.
     *
     * @return pointer to interface, if any
     */
    static MeshInterface *get_default_instance();

protected:

    /** Get the target's default Mesh interface.
     *
     * This is provided as a weak method so targets can override. The
     * default implementation will invoke LoWPANNDInterface or ThreadInterface
     * with the default NanostackRfPhy.
     *
     * @return pointer to interface, if any
     */
    static MeshInterface *get_target_default_instance();
};

#endif

/** @}*/


text:
-- phpMyAdmin SQL Dump
-- version 2.11.11.3
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.3
-- Generation Time: Nov 22, 2012 at 04:06 PM
-- Server version: 5.1.60
-- PHP Version: 4.4.9

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `db102497_53`
--

-- --------------------------------------------------------

--
-- Table structure for table `entry`
--

CREATE TABLE `entry` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `text` text NOT NULL,
  `created` datetime NOT NULL,
  `author` varchar(60) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=108 ;

-
--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `display_name` varchar(50) DEFAULT NULL,
  `password` varchar(128) NOT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;


text:
<?php

use Ctct\Util\CurlResponse;
use Ctct\Services\ListService;
use Ctct\Util\RestClient;
use Ctct\Components\Contacts\ContactList;

class ListServiceUnitTest extends PHPUnit_Framework_TestCase
{
    private $restClient;
    private $listService;

    public function setUp()
    {
        $this->restClient = $this->getMock('Ctct\Util\RestClientInterface');
        $this->listService = new ListService("apikey", $this->restClient);
    }

    public function testGetLists()
    {
        $curlResponse = CurlResponse::create(JsonLoader::getListsJson(), array('http_code' => 200));
        $this->restClient->expects($this->once())
            ->method('get')
            ->with()
            ->will($this->returnValue($curlResponse));

        $response = $this->listService->getLists('access_token');

        $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $response[0]);
        $this->assertEquals(1, $response[0]->id);
        $this->assertEquals("General Interest", $response[0]->name);
        $this->assertEquals("ACTIVE", $response[0]->status);
        $this->assertEquals(17, $response[0]->contact_count);

        $this->assertEquals(3, $response[1]->id);
        $this->assertEquals("mod_Test List 1", $response[1]->name);
        $this->assertEquals("HIDDEN", $response[1]->status);
        $this->assertEquals(18, $response[1]->contact_count);
    }

    public function testGetListsModifiedSince()
    {
        $curlResponse = CurlResponse::create(JsonLoader::getListsJson(), array('http_code' => 200));
        $this->restClient->expects($this->once())
            ->method('get')
            ->with()
            ->will($this->returnValue($curlResponse));

        $response = $this->listService->getLists('access_token', array('modified_since' => '2013-01-12T20:04:59.436Z'));

        $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $response[0]);
        $this->assertEquals(1, $response[0]->id);
        $this->assertEquals("General Interest", $response[0]->name);
        $this->assertEquals("ACTIVE", $response[0]->status);
        $this->assertEquals(17, $response[0]->contact_count);

        $this->assertEquals(3, $response[1]->id);
        $this->assertEquals("mod_Test List 1", $response[1]->name);
        $this->assertEquals("HIDDEN", $response[1]->status);
        $this->assertEquals(18, $response[1]->contact_count);
    }

    public function testGetList()
    {
        $curlResponse = CurlResponse::create(JsonLoader::getListJson(), array('http_code' => 200));
        $this->restClient->expects($this->once())
            ->method('get')
            ->with()
            ->will($this->returnValue($curlResponse));

        $list = $this->listService->getList('access_token', 6);
        $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $list);
        $this->assertEquals(6, $list->id);
        $this->assertEquals("Test List 4", $list->name);
        $this->assertEquals("HIDDEN", $list->status);
        $this->assertEquals(19, $list->contact_count);
    }

    public function testAddList()
    {
        $curlResponse = CurlResponse::create(JsonLoader::getListJson(), array('http_code' => 204));
        $this->restClient->expects($this->once())
            ->method('post')
            ->with()
            ->will($this->returnValue($curlResponse));

        $list = $this->listService->addList('access_token', new ContactList());
        $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $list);
        $this->assertEquals(6, $list->id);
        $this->assertEquals("Test List 4", $list->name);
        $this->assertEquals("HIDDEN", $list->status);
        $this->assertEquals(19, $list->contact_count);
    }

    public function testUpdateList()
    {
        $curlResponse = CurlResponse::create(JsonLoader::getListJson(), array('http_code' => 200));
        $this->restClient->expects($this->once())
            ->method('put')
            ->with()
            ->will($this->returnValue($curlResponse));

        $list = $this->listService->updateList('access_token', new ContactList());
        $this->assertInstanceOf("Ctct\Components\Contacts\ContactList", $list);
        $this->assertEquals(6, $list->id);
        $this->assertEquals("Test List 4", $list->name);
        $this->assertEquals("HIDDEN", $list->status);
        $this->assertEquals(19, $list->contact_count);
    }

    public function testGetContactsFromList()
    {
        $curlResponse = CurlResponse::create(JsonLoader::getContactsJson(), array('http_code' => 200));
        $this->restClient->expects($this->once())
            ->method('get')
            ->with()
            ->will($this->returnValue($curlResponse));

        $response = $this->listService->getContactsFromList('access_token', 1);
        $this->assertInstanceOf("Ctct\Components\ResultSet", $response);

        $contact = $response->results[1];

        $this->assertEquals(231, $contact->id);
        $this->assertEquals("ACTIVE", $contact->status);
        $this->assertEquals("", $contact->fax);
        $this->assertEquals("", $contact->prefix_name);
        $this->assertEquals("Jimmy", $contact->first_name);
        $this->assertEquals("Roving", $contact->last_name);
        $this->assertEquals("Bear Tamer", $contact->job_title);
        $this->assertEquals("Animal Trainer Pro", $contact->company_name);
        $this->assertEquals("details", $contact->source_details);
        $this->assertEquals(false, $contact->confirmed);
        $this->assertEquals("", $contact->source);

        // custom fields
        $this->assertEquals("CustomField1", $contact->custom_fields[0]->name);
        $this->assertEquals("1", $contact->custom_fields[0]->value);

        //addresses
        $this->assertEquals("Suite 101", $contact->addresses[0]->line1);
        $this->assertEquals("line2", $contact->addresses[0]->line2);
        $this->assertEquals("line3", $contact->addresses[0]->line3);
        $this->assertEquals("Brookfield", $contact->addresses[0]->city);
        $this->assertEquals("PERSONAL", $contact->addresses[0]->address_type);
        $this->assertEquals("WI", $contact->addresses[0]->state_code);
        $this->assertEquals("us", $contact->addresses[0]->country_code);
        $this->assertEquals("53027", $contact->addresses[0]->postal_code);
        $this->assertEquals("", $contact->addresses[0]->sub_postal_code);

        //notes
        $this->assertEquals(0, count($contact->notes));

        //lists
        $this->assertEquals(1, $contact->lists[0]->id);
        $this->assertEquals("ACTIVE", $contact->lists[0]->status);

        // EmailAddress
        $this->assertEquals("ACTIVE", $contact->email_addresses[0]->status);
        $this->assertEquals("NO_CONFIRMATION_REQUIRED", $contact->email_addresses[0]->confirm_status);
        $this->assertEquals("ACTION_BY_OWNER", $contact->email_addresses[0]->opt_in_source);
        $this->assertEquals("2012-06-22T10:29:09.976Z", $contact->email_addresses[0]->opt_in_date);
        $this->assertEquals("", $contact->email_addresses[0]->opt_out_date);
        $this->assertEquals("anothertest@roving.com", $contact->email_addresses[0]->email_address);
    }
}


text:
#include "dev/amdgpu/amdgpu_device.hh"

#include <fstream>

#include "debug/AMDGPUDevice.hh"
#include "dev/amdgpu/amdgpu_vm.hh"
#include "dev/amdgpu/interrupt_handler.hh"
#include "dev/amdgpu/pm4_packet_processor.hh"
#include "dev/amdgpu/sdma_engine.hh"
#include "dev/hsa/hw_scheduler.hh"
#include "gpu-compute/gpu_command_processor.hh"
#include "mem/abstract_mem.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "params/AMDGPUDevice.hh"
#include "sim/byteswap.hh"
#include "sim/sim_exit.hh"

namespace gem5
{

AMDGPUDevice::AMDGPUDevice(const AMDGPUDeviceParams &p)
    : PciDevice(p), gpuMemMgr(p.memory_manager), deviceIH(p.device_ih),
      sdma0(p.sdma0), sdma1(p.sdma1), pm4PktProc(p.pm4_pkt_proc), cp(p.cp),
      checkpoint_before_mmios(p.checkpoint_before_mmios),
      init_interrupt_count(0), _lastVMID(0),
      deviceMem(name() + ".deviceMem", p.memories, false, "", false)
{
    // Loading the rom binary dumped from hardware.
    std::ifstream romBin;
    romBin.open(p.rom_binary, std::ios::binary);
    romBin.read((char *)rom.data(), ROM_SIZE);
    romBin.close();

    // System pointer needs to be explicitly set for device memory since
    // DRAMCtrl uses it to get (1) cache line size and (2) the mem mode.
    // Note this means the cache line size is system wide.
    for (auto& m : p.memories) {
        m->system(p.system);

        // Add to system's device memory map.
        p.system->addDeviceMemory(gpuMemMgr->getRequestorID(), m);
    }

    if (config.expansionROM) {
        romRange = RangeSize(config.expansionROM, ROM_SIZE);
    } else {
        romRange = RangeSize(VGA_ROM_DEFAULT, ROM_SIZE);
    }

    if (p.trace_file != "") {
        mmioReader.readMMIOTrace(p.trace_file);
    }

    sdma0->setGPUDevice(this);
    sdma0->setId(0);
    sdma1->setGPUDevice(this);
    sdma1->setId(1);
    deviceIH->setGPUDevice(this);
    pm4PktProc->setGPUDevice(this);
    cp->hsaPacketProc().setGPUDevice(this);
    cp->setGPUDevice(this);
}

void
AMDGPUDevice::readROM(PacketPtr pkt)
{
    Addr rom_offset = pkt->getAddr() & (ROM_SIZE - 1);
    uint64_t rom_data = 0;

    memcpy(&rom_data, rom.data() + rom_offset, pkt->getSize());
    pkt->setUintX(rom_data, ByteOrder::little);

    DPRINTF(AMDGPUDevice, "Read from addr %#x on ROM offset %#x data: %#x\n",
            pkt->getAddr(), rom_offset, rom_data);
}

AddrRangeList
AMDGPUDevice::getAddrRanges() const
{
    AddrRangeList ranges = PciDevice::getAddrRanges();
    AddrRangeList ret_ranges;
    ret_ranges.push_back(romRange);

    // If the range starts at zero assume OS hasn't assigned it yet. Do not
    // return ranges starting with zero as they will surely overlap with
    // another range causing the I/O crossbar to fatal.
    for (auto & r : ranges) {
        if (r.start() != 0) {
            ret_ranges.push_back(r);
        }
    }

    return ret_ranges;
}

Tick
AMDGPUDevice::readConfig(PacketPtr pkt)
{
    [[maybe_unused]] int offset = pkt->getAddr() & PCI_CONFIG_SIZE;
    DPRINTF(AMDGPUDevice, "Read Config: from offset: %#x size: %#x "
            "data: %#x\n", offset, pkt->getSize(), config.data[offset]);

    Tick delay = PciDevice::readConfig(pkt);

    // Before sending MMIOs the driver sends three interrupts in a row.
    // Use this to trigger creating a checkpoint to restore in timing mode.
    // This is only necessary until we can create a "hole" in the KVM VM
    // around the VGA ROM region such that KVM exits and sends requests to
    // this device rather than the KVM VM.
    if (checkpoint_before_mmios) {
        if (offset == PCI0_INTERRUPT_PIN) {
            if (++init_interrupt_count == 3) {
                DPRINTF(AMDGPUDevice, "Checkpointing before first MMIO\n");
                exitSimLoop("checkpoint", 0, curTick() + delay + 1);
            }
        } else {
            init_interrupt_count = 0;
        }
    }

    return delay;
}

Tick
AMDGPUDevice::writeConfig(PacketPtr pkt)
{
    [[maybe_unused]] int offset = pkt->getAddr() & PCI_CONFIG_SIZE;
    DPRINTF(AMDGPUDevice, "Write Config: from offset: %#x size: %#x "
            "data: %#x\n", offset, pkt->getSize(),
            pkt->getUintX(ByteOrder::little));

    return PciDevice::writeConfig(pkt);
}

void
AMDGPUDevice::dispatchAccess(PacketPtr pkt, bool read)
{
    DPRINTF(AMDGPUDevice, "%s from addr %#x size: %#x data: %#x\n",
            read ? "Read" : "Write", pkt->getAddr(), pkt->getSize(),
            pkt->getUintX(ByteOrder::little));

    pkt->makeAtomicResponse();
}

void
AMDGPUDevice::readFrame(PacketPtr pkt, Addr offset)
{
    DPRINTF(AMDGPUDevice, "Read framebuffer address %#lx\n", offset);

    /* Try MMIO trace for frame writes first. */
    mmioReader.readFromTrace(pkt, FRAMEBUFFER_BAR, offset);

    /* If the driver wrote something, use that value over the trace. */
    if (frame_regs.find(offset) != frame_regs.end()) {
        pkt->setUintX(frame_regs[offset], ByteOrder::little);
    }

    /* Handle special counter addresses in framebuffer. */
    if (offset == 0xa28000) {
        /* Counter addresses expect the read to return previous value + 1. */
        if (regs.find(pkt->getAddr()) == regs.end()) {
            regs[pkt->getAddr()] = 1;
        } else {
            regs[pkt->getAddr()]++;
        }

        pkt->setUintX(regs[pkt->getAddr()], ByteOrder::little);
    }
}

void
AMDGPUDevice::readDoorbell(PacketPtr pkt, Addr offset)
{
    DPRINTF(AMDGPUDevice, "Read doorbell %#lx\n", offset);
    mmioReader.readFromTrace(pkt, DOORBELL_BAR, offset);
}

void
AMDGPUDevice::readMMIO(PacketPtr pkt, Addr offset)
{
    Addr aperture = gpuvm.getMmioAperture(offset);
    Addr aperture_offset = offset - aperture;

    // By default read from MMIO trace. Overwrite the packet for a select
    // few more dynamic MMIOs.
    DPRINTF(AMDGPUDevice, "Read MMIO %#lx\n", offset);
    mmioReader.readFromTrace(pkt, MMIO_BAR, offset);

    switch (aperture) {
      case NBIO_BASE:
        switch (aperture_offset) {
          // This is a PCIe status register. At some point during driver init
          // the driver checks that interrupts are enabled. This is only
          // checked once, so if the MMIO trace does not exactly line up with
          // what the driver is doing in gem5, this may still have the first
          // bit zero causing driver to fail. Therefore, we always set this
          // bit to one as there is no harm to do so.
          case 0x3c: // mmPCIE_DATA2 << 2
            uint32_t value = pkt->getLE<uint32_t>() | 0x1;
            DPRINTF(AMDGPUDevice, "Marking interrupts enabled: %#lx\n", value);
            pkt->setLE<uint32_t>(value);
            break;
        } break;
      case GRBM_BASE:
        gpuvm.readMMIO(pkt, aperture_offset >> GRBM_OFFSET_SHIFT);
        break;
      case MMHUB_BASE:
        gpuvm.readMMIO(pkt, aperture_offset >> MMHUB_OFFSET_SHIFT);
        break;
      default:
        break;
    }
}

void
AMDGPUDevice::writeFrame(PacketPtr pkt, Addr offset)
{
    DPRINTF(AMDGPUDevice, "Wrote framebuffer address %#lx\n", offset);

    Addr aperture = gpuvm.getFrameAperture(offset);
    Addr aperture_offset = offset - aperture;

    // Record the value
    frame_regs[offset] = pkt->getUintX(ByteOrder::little);
    if (aperture == gpuvm.gartBase()) {
        frame_regs[aperture_offset] = pkt->getLE<uint32_t>();
        DPRINTF(AMDGPUDevice, "GART translation %p -> %p\n", aperture_offset,
            bits(frame_regs[aperture_offset], 48, 12));
        gpuvm.gartTable[aperture_offset] = pkt->getLE<uint32_t>();
    }
}

void
AMDGPUDevice::writeDoorbell(PacketPtr pkt, Addr offset)
{
    DPRINTF(AMDGPUDevice, "Wrote doorbell %#lx\n", offset);

    if (doorbells.find(offset) != doorbells.end()) {
        QueueType q_type = doorbells[offset];
        DPRINTF(AMDGPUDevice, "Doorbell offset %p queue: %d\n",
                              offset, q_type);
        switch (q_type) {
          case Compute:
            pm4PktProc->process(pm4PktProc->getQueue(offset),
                                pkt->getLE<uint64_t>());
          break;
          case Gfx:
            pm4PktProc->process(pm4PktProc->getQueue(offset, true),
                                pkt->getLE<uint64_t>());
          break;
          case SDMAGfx: {
            SDMAEngine *sdmaEng = getSDMAEngine(offset);
            sdmaEng->processGfx(pkt->getLE<uint64_t>());
          } break;
          case SDMAPage: {
            SDMAEngine *sdmaEng = getSDMAEngine(offset);
            sdmaEng->processPage(pkt->getLE<uint64_t>());
          } break;
          case ComputeAQL: {
            cp->hsaPacketProc().hwScheduler()->write(offset,
                pkt->getLE<uint64_t>() + 1);
            pm4PktProc->updateReadIndex(offset, pkt->getLE<uint64_t>() + 1);
          } break;
          case InterruptHandler:
            deviceIH->updateRptr(pkt->getLE<uint32_t>());
            break;
          case RLC: {
            panic("RLC queues not yet supported. Run with the environment "
                  "variable HSA_ENABLE_SDMA set to False");
          } break;
          default:
            panic("Write to unkown queue type!");
        }
    } else {
        warn("Unknown doorbell offset: %lx\n", offset);
    }
}

void
AMDGPUDevice::writeMMIO(PacketPtr pkt, Addr offset)
{
    Addr aperture = gpuvm.getMmioAperture(offset);
    Addr aperture_offset = offset - aperture;

    DPRINTF(AMDGPUDevice, "Wrote MMIO %#lx\n", offset);

    switch (aperture) {
      /* Write a register to the first System DMA. */
      case SDMA0_BASE:
        sdma0->writeMMIO(pkt, aperture_offset >> SDMA_OFFSET_SHIFT);
        break;
      /* Write a register to the second System DMA. */
      case SDMA1_BASE:
        sdma1->writeMMIO(pkt, aperture_offset >> SDMA_OFFSET_SHIFT);
        break;
      /* Write a general register to the graphics register bus manager. */
      case GRBM_BASE:
        gpuvm.writeMMIO(pkt, aperture_offset >> GRBM_OFFSET_SHIFT);
        pm4PktProc->writeMMIO(pkt, aperture_offset >> GRBM_OFFSET_SHIFT);
        break;
      /* Write a register to the interrupt handler. */
      case IH_BASE:
        deviceIH->writeMMIO(pkt, aperture_offset >> IH_OFFSET_SHIFT);
        break;
      default:
        DPRINTF(AMDGPUDevice, "Unknown MMIO aperture for %#x\n", offset);
        break;
    }
}

Tick
AMDGPUDevice::read(PacketPtr pkt)
{
    if (isROM(pkt->getAddr())) {
        readROM(pkt);
    } else {
        int barnum = -1;
        Addr offset = 0;
        getBAR(pkt->getAddr(), barnum, offset);

        switch (barnum) {
          case FRAMEBUFFER_BAR:
              readFrame(pkt, offset);
              break;
          case DOORBELL_BAR:
              readDoorbell(pkt, offset);
              break;
          case MMIO_BAR:
              readMMIO(pkt, offset);
              break;
          default:
            panic("Request with address out of mapped range!");
        }
    }

    dispatchAccess(pkt, true);
    return pioDelay;
}

Tick
AMDGPUDevice::write(PacketPtr pkt)
{
    int barnum = -1;
    Addr offset = 0;
    getBAR(pkt->getAddr(), barnum, offset);

    switch (barnum) {
      case FRAMEBUFFER_BAR:
          gpuMemMgr->writeRequest(offset, pkt->getPtr<uint8_t>(),
                                  pkt->getSize());
          writeFrame(pkt, offset);
          break;
      case DOORBELL_BAR:
          writeDoorbell(pkt, offset);
          break;
      case MMIO_BAR:
          writeMMIO(pkt, offset);
          break;
      default:
        panic("Request with address out of mapped range!");
    }

    // Record only if there is non-zero value, or a value to be overwritten.
    // Reads return 0 by default.
    uint64_t data = pkt->getUintX(ByteOrder::little);

    DPRINTF(AMDGPUDevice, "PCI Write to %#lx data %#lx\n",
                            pkt->getAddr(), data);

    if (data || regs.find(pkt->getAddr()) != regs.end())
        regs[pkt->getAddr()] = data;

    dispatchAccess(pkt, false);

    return pioDelay;
}

uint32_t
AMDGPUDevice::getRegVal(uint32_t addr)
{
    return regs[addr];
}
void
AMDGPUDevice::setRegVal(uint32_t addr, uint32_t value)
{
    DPRINTF(AMDGPUDevice, "Setting register 0x%lx to %x\n",
            addr, value);
    regs[addr] = value;
}

void
AMDGPUDevice::setDoorbellType(uint32_t offset, QueueType qt)
{
    DPRINTF(AMDGPUDevice, "Setting doorbell type for %x\n", offset);
    doorbells[offset] = qt;
}

void
AMDGPUDevice::setSDMAEngine(Addr offset, SDMAEngine *eng)
{
    sdmaEngs[offset] = eng;
}

SDMAEngine*
AMDGPUDevice::getSDMAById(int id)
{
    /**
     * PM4 packets selected SDMAs using an integer ID. This method simply maps
     * the integer ID to a pointer to the SDMA and checks for invalid IDs.
     */
    switch (id) {
        case 0:
            return sdma0;
            break;
        case 1:
            return sdma1;
            break;
        default:
            panic("No SDMA with id %d\n", id);
            break;
    }

    return nullptr;
}

SDMAEngine*
AMDGPUDevice::getSDMAEngine(Addr offset)
{
    return sdmaEngs[offset];
}

void
AMDGPUDevice::intrPost()
{
    PciDevice::intrPost();
}

void
AMDGPUDevice::serialize(CheckpointOut &cp) const
{
    // Serialize the PciDevice base class
    PciDevice::serialize(cp);

    uint64_t regs_size = regs.size();
    uint64_t doorbells_size = doorbells.size();
    uint64_t sdma_engs_size = sdmaEngs.size();

    SERIALIZE_SCALAR(regs_size);
    SERIALIZE_SCALAR(doorbells_size);
    SERIALIZE_SCALAR(sdma_engs_size);

    // Make a c-style array of the regs to serialize
    uint32_t reg_addrs[regs_size];
    uint64_t reg_values[regs_size];
    uint32_t doorbells_offset[doorbells_size];
    QueueType doorbells_queues[doorbells_size];
    uint32_t sdma_engs_offset[sdma_engs_size];
    int sdma_engs[sdma_engs_size];

    int idx = 0;
    for (auto & it : regs) {
        reg_addrs[idx] = it.first;
        reg_values[idx] = it.second;
        ++idx;
    }

    idx = 0;
    for (auto & it : doorbells) {
        doorbells_offset[idx] = it.first;
        doorbells_queues[idx] = it.second;
        ++idx;
    }

    idx = 0;
    for (auto & it : sdmaEngs) {
        sdma_engs_offset[idx] = it.first;
        sdma_engs[idx] = it.second == sdma0 ? 0 : 1;
        ++idx;
    }

    SERIALIZE_ARRAY(reg_addrs, sizeof(reg_addrs)/sizeof(reg_addrs[0]));
    SERIALIZE_ARRAY(reg_values, sizeof(reg_values)/sizeof(reg_values[0]));
    SERIALIZE_ARRAY(doorbells_offset, sizeof(doorbells_offset)/
        sizeof(doorbells_offset[0]));
    SERIALIZE_ARRAY(doorbells_queues, sizeof(doorbells_queues)/
        sizeof(doorbells_queues[0]));
    SERIALIZE_ARRAY(sdma_engs_offset, sizeof(sdma_engs_offset)/
        sizeof(sdma_engs_offset[0]));
    SERIALIZE_ARRAY(sdma_engs, sizeof(sdma_engs)/sizeof(sdma_engs[0]));

    // Serialize the device memory
    deviceMem.serializeSection(cp, "deviceMem");
}

void
AMDGPUDevice::unserialize(CheckpointIn &cp)
{
    // Unserialize the PciDevice base class
    PciDevice::unserialize(cp);

    uint64_t regs_size = 0;
    uint64_t doorbells_size = 0;
    uint64_t sdma_engs_size = 0;

    UNSERIALIZE_SCALAR(regs_size);
    UNSERIALIZE_SCALAR(doorbells_size);
    UNSERIALIZE_SCALAR(sdma_engs_size);

    if (regs_size > 0) {
        uint32_t reg_addrs[regs_size];
        uint64_t reg_values[regs_size];

        UNSERIALIZE_ARRAY(reg_addrs, sizeof(reg_addrs)/sizeof(reg_addrs[0]));
        UNSERIALIZE_ARRAY(reg_values,
                          sizeof(reg_values)/sizeof(reg_values[0]));

        for (int idx = 0; idx < regs_size; ++idx) {
            regs.insert(std::make_pair(reg_addrs[idx], reg_values[idx]));
        }
    }

    if (doorbells_size > 0) {
        uint32_t doorbells_offset[doorbells_size];
        QueueType doorbells_queues[doorbells_size];

        UNSERIALIZE_ARRAY(doorbells_offset, sizeof(doorbells_offset)/
                sizeof(doorbells_offset[0]));
        UNSERIALIZE_ARRAY(doorbells_queues, sizeof(doorbells_queues)/
                sizeof(doorbells_queues[0]));

        for (int idx = 0; idx < doorbells_size; ++idx) {
            regs.insert(std::make_pair(doorbells_offset[idx],
                      doorbells_queues[idx]));
            doorbells[doorbells_offset[idx]] = doorbells_queues[idx];
        }
    }

    if (sdma_engs_size > 0) {
        uint32_t sdma_engs_offset[sdma_engs_size];
        int sdma_engs[sdma_engs_size];

        UNSERIALIZE_ARRAY(sdma_engs_offset, sizeof(sdma_engs_offset)/
            sizeof(sdma_engs_offset[0]));
        UNSERIALIZE_ARRAY(sdma_engs, sizeof(sdma_engs)/sizeof(sdma_engs[0]));

        for (int idx = 0; idx < sdma_engs_size; ++idx) {
            SDMAEngine *sdma = sdma_engs[idx] == 0 ? sdma0 : sdma1;
            sdmaEngs.insert(std::make_pair(sdma_engs_offset[idx], sdma));
        }
    }

    // Unserialize the device memory
    deviceMem.unserializeSection(cp, "deviceMem");
}

uint16_t
AMDGPUDevice::allocateVMID(uint16_t pasid)
{
    for (uint16_t vmid = 1; vmid < AMDGPU_VM_COUNT; vmid++) {
        auto result = usedVMIDs.find(vmid);
        if (result == usedVMIDs.end()) {
            idMap.insert(std::make_pair(pasid, vmid));
            usedVMIDs[vmid] = {};
            _lastVMID = vmid;
            return vmid;
        }
    }
    panic("All VMIDs have been assigned");
}

void
AMDGPUDevice::deallocateVmid(uint16_t vmid)
{
    usedVMIDs.erase(vmid);
}

void
AMDGPUDevice::deallocatePasid(uint16_t pasid)
{
    auto result = idMap.find(pasid);
    assert(result != idMap.end());
    if (result == idMap.end()) return;
    uint16_t vmid = result->second;

    idMap.erase(result);
    usedVMIDs.erase(vmid);
}

void
AMDGPUDevice::deallocateAllQueues()
{
    idMap.erase(idMap.begin(), idMap.end());
    usedVMIDs.erase(usedVMIDs.begin(), usedVMIDs.end());
}

void
AMDGPUDevice::mapDoorbellToVMID(Addr doorbell, uint16_t vmid)
{
    doorbellVMIDMap[doorbell] = vmid;
}

std::unordered_map<uint16_t, std::set<int>>&
AMDGPUDevice::getUsedVMIDs()
{
    return usedVMIDs;
}

void
AMDGPUDevice::insertQId(uint16_t vmid, int id)
{
    usedVMIDs[vmid].insert(id);
}

} // namespace gem5


text:
class Category < ActiveRecord::Base
	has_many :indicators, dependent: :destroy

	default_scope	-> { order(:id) }

	validates :title, presence: true
end


text:
/**
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree. *
 *
 * @providesModule toHaveText
 * @flow
 */

export default {
  toHaveText() : Object {
    return {
      compare(enzymeWrapper:Object, text:?string) : Object {
        const actualText = enzymeWrapper.text();

        if (text === undefined) {
          return {
            pass: actualText.length > 0,
            message: 'Expected node to have text',
          };
        }

        return {
          pass: actualText === text,
          message: `Expected "${actualText}" to equal "${text}"`,
        };
      },
    };
  },
};