/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkAffineRepresentation2D.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkAffineRepresentation2D.h"
#include "vtkActor2D.h"
#include "vtkAssemblyPath.h"
#include "vtkCellArray.h"
#include "vtkCoordinate.h"
#include "vtkCursor2D.h"
#include "vtkGlyph2D.h"
#include "vtkInteractorObserver.h"
#include "vtkLeaderActor2D.h"
#include "vtkLine.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkPolyDataAlgorithm.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkProperty2D.h"
#include "vtkRenderer.h"
#include "vtkTextMapper.h"
#include "vtkTextProperty.h"
#include "vtkTransform.h"
#include "vtkWindow.h"

vtkStandardNewMacro(vtkAffineRepresentation2D);

vtkCxxSetObjectMacro(vtkAffineRepresentation2D, Property, vtkProperty2D);
vtkCxxSetObjectMacro(vtkAffineRepresentation2D, SelectedProperty, vtkProperty2D);
vtkCxxSetObjectMacro(vtkAffineRepresentation2D, TextProperty, vtkTextProperty);

#define VTK_CIRCLE_RESOLUTION 64

//------------------------------------------------------------------------------
vtkAffineRepresentation2D::vtkAffineRepresentation2D()
{
  // It's best to have a small tolerance
  this->Tolerance = 3;

  // Initialize state
  this->InteractionState = vtkAffineRepresentation::Outside;

  // The width of the widget
  this->DisplayText = 1;
  this->BoxWidth = 100;
  this->CircleWidth = static_cast<int>(0.75 * this->BoxWidth);
  this->AxesWidth = static_cast<int>(0.60 * this->BoxWidth);
  this->CurrentWidth = 0.0;
  this->CurrentRadius = 0.0;
  this->CurrentAxesWidth = 0.0;

  // Keep track of transformations
  this->DisplayOrigin[0] = this->DisplayOrigin[1] = this->DisplayOrigin[2] = 0.0;
  this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0;

  // Create properties
  this->CreateDefaultProperties();

  // Text label
  this->TextMapper = vtkTextMapper::New();
  this->TextMapper->SetTextProperty(this->TextProperty);
  this->TextMapper->SetInput("foo");
  this->TextActor = vtkActor2D::New();
  this->TextActor->SetMapper(this->TextMapper);
  this->TextActor->VisibilityOff();

  // Box
  this->BoxPoints = vtkPoints::New();
  this->BoxPoints->SetNumberOfPoints(4);
  this->BoxCellArray = vtkCellArray::New();
  this->BoxCellArray->AllocateEstimate(1, 4);
  this->BoxCellArray->InsertNextCell(5);
  this->BoxCellArray->InsertCellPoint(0);
  this->BoxCellArray->InsertCellPoint(1);
  this->BoxCellArray->InsertCellPoint(2);
  this->BoxCellArray->InsertCellPoint(3);
  this->BoxCellArray->InsertCellPoint(0);
  this->Box = vtkPolyData::New();
  this->Box->SetPoints(this->BoxPoints);
  this->Box->SetLines(this->BoxCellArray);
  this->BoxMapper = vtkPolyDataMapper2D::New();
  this->BoxMapper->SetInputData(this->Box);
  this->BoxActor = vtkActor2D::New();
  this->BoxActor->SetMapper(this->BoxMapper);
  this->BoxActor->SetProperty(this->Property);

  this->HBoxPoints = vtkPoints::New();
  this->HBoxPoints->SetNumberOfPoints(4);
  this->HBoxCellArray = vtkCellArray::New();
  this->HBoxCellArray->AllocateEstimate(1, 4);
  this->HBoxCellArray->InsertNextCell(5);
  this->HBoxCellArray->InsertCellPoint(0);
  this->HBoxCellArray->InsertCellPoint(1);
  this->HBoxCellArray->InsertCellPoint(2);
  this->HBoxCellArray->InsertCellPoint(3);
  this->HBoxCellArray->InsertCellPoint(0);
  this->HBox = vtkPolyData::New();
  this->HBox->SetPoints(this->HBoxPoints);
  this->HBox->SetLines(this->HBoxCellArray);
  this->HBoxMapper = vtkPolyDataMapper2D::New();
  this->HBoxMapper->SetInputData(this->HBox);
  this->HBoxActor = vtkActor2D::New();
  this->HBoxActor->SetMapper(this->HBoxMapper);
  this->HBoxActor->VisibilityOff();
  this->HBoxActor->SetProperty(this->SelectedProperty);

  // Circle
  this->CirclePoints = vtkPoints::New();
  this->CirclePoints->SetNumberOfPoints(VTK_CIRCLE_RESOLUTION);
  this->CircleCellArray = vtkCellArray::New();
  this->CircleCellArray->AllocateEstimate(1, VTK_CIRCLE_RESOLUTION + 1);
  this->Circle = vtkPolyData::New();
  this->Circle->SetPoints(this->CirclePoints);
  this->Circle->SetLines(this->CircleCellArray);
  this->CircleMapper = vtkPolyDataMapper2D::New();
  this->CircleMapper->SetInputData(this->Circle);
  this->CircleActor = vtkActor2D::New();
  this->CircleActor->SetMapper(this->CircleMapper);
  this->CircleActor->SetProperty(this->Property);

  this->HCirclePoints = vtkPoints::New();
  this->HCircleCellArray = vtkCellArray::New();
  this->HCircleCellArray->AllocateEstimate(1, VTK_CIRCLE_RESOLUTION + 1);
  this->HCircle = vtkPolyData::New();
  this->HCircle->SetPoints(this->HCirclePoints);
  this->HCircle->SetLines(this->HCircleCellArray);
  this->HCircleMapper = vtkPolyDataMapper2D::New();
  this->HCircleMapper->SetInputData(this->HCircle);
  this->HCircleActor = vtkActor2D::New();
  this->HCircleActor->SetMapper(this->HCircleMapper);
  this->HCircleActor->VisibilityOff();
  this->HCircleActor->SetProperty(this->SelectedProperty);

  // Translation axes
  this->XAxis = vtkLeaderActor2D::New();
  this->XAxis->GetPositionCoordinate()->SetCoordinateSystemToDisplay();
  this->XAxis->GetPosition2Coordinate()->SetCoordinateSystemToDisplay();
  this->XAxis->SetArrowStyleToFilled();
  this->XAxis->SetProperty(this->Property);
  this->XAxis->SetMaximumArrowSize(12);

  this->YAxis = vtkLeaderActor2D::New();
  this->YAxis->GetPositionCoordinate()->SetCoordinateSystemToDisplay();
  this->YAxis->GetPosition2Coordinate()->SetCoordinateSystemToDisplay();
  this->YAxis->SetArrowStyleToFilled();
  this->YAxis->SetProperty(this->Property);
  this->YAxis->SetMaximumArrowSize(12);

  this->HXAxis = vtkLeaderActor2D::New();
  this->HXAxis->GetPositionCoordinate()->SetCoordinateSystemToDisplay();
  this->HXAxis->GetPosition2Coordinate()->SetCoordinateSystemToDisplay();
  this->HXAxis->SetArrowStyleToFilled();
  this->HXAxis->SetProperty(this->SelectedProperty);
  this->HXAxis->SetMaximumArrowSize(12);
  this->HXAxis->VisibilityOff();

  this->HYAxis = vtkLeaderActor2D::New();
  this->HYAxis->GetPositionCoordinate()->SetCoordinateSystemToDisplay();
  this->HYAxis->GetPosition2Coordinate()->SetCoordinateSystemToDisplay();
  this->HYAxis->SetArrowStyleToFilled();
  this->HYAxis->SetProperty(this->SelectedProperty);
  this->HYAxis->SetMaximumArrowSize(12);
  this->HYAxis->VisibilityOff();

  // Transformation matrix
  this->CurrentTransform = vtkTransform::New();
  this->TotalTransform = vtkTransform::New();

  this->CurrentTranslation[0] = 0.0;
  this->CurrentTranslation[1] = 0.0;
  this->CurrentTranslation[2] = 0.0;
  this->CurrentAngle = 0.0;
  this->CurrentScale[0] = 1.0;
  this->CurrentScale[1] = 1.0;
  this->CurrentShear[0] = 0.0;
  this->CurrentShear[1] = 0.0;
}

//------------------------------------------------------------------------------
vtkAffineRepresentation2D::~vtkAffineRepresentation2D()
{
  this->Property->Delete();
  this->SelectedProperty->Delete();
  this->TextProperty->Delete();

  this->TextMapper->Delete();
  this->TextActor->Delete();

  this->BoxPoints->Delete();
  this->BoxCellArray->Delete();
  this->Box->Delete();
  this->BoxMapper->Delete();
  this->BoxActor->Delete();

  this->HBoxPoints->Delete();
  this->HBoxCellArray->Delete();
  this->HBox->Delete();
  this->HBoxMapper->Delete();
  this->HBoxActor->Delete();

  this->CirclePoints->Delete();
  this->CircleCellArray->Delete();
  this->Circle->Delete();
  this->CircleMapper->Delete();
  this->CircleActor->Delete();

  this->HCirclePoints->Delete();
  this->HCircleCellArray->Delete();
  this->HCircle->Delete();
  this->HCircleMapper->Delete();
  this->HCircleActor->Delete();

  this->XAxis->Delete();
  this->YAxis->Delete();
  this->HXAxis->Delete();
  this->HYAxis->Delete();

  this->CurrentTransform->Delete();
  this->TotalTransform->Delete();
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::GetTransform(vtkTransform* t)
{
  this->CurrentTransform->Identity();
  this->CurrentTransform->Translate(this->Origin[0], this->Origin[1], this->Origin[2]);
  if (this->InteractionState != vtkAffineRepresentation::MoveOrigin &&
    this->InteractionState != vtkAffineRepresentation::MoveOriginX &&
    this->InteractionState != vtkAffineRepresentation::MoveOriginY)
  {
    this->CurrentTransform->Translate(
      this->CurrentTranslation[0], this->CurrentTranslation[1], this->CurrentTranslation[2]);
  }

  this->ApplyShear();
  this->CurrentTransform->RotateZ(vtkMath::DegreesFromRadians(this->CurrentAngle));
  this->CurrentTransform->Scale(this->CurrentScale[0], this->CurrentScale[1], 1.0);
  this->CurrentTransform->Translate(-this->Origin[0], -this->Origin[1], -this->Origin[2]);

  t->DeepCopy(this->CurrentTransform);
  t->Concatenate(this->TotalTransform);
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::PlaceWidget(double bounds[6])
{
  this->Origin[0] = (bounds[1] + bounds[0]) / 2.0;
  this->Origin[1] = (bounds[3] + bounds[2]) / 2.0;
  this->Origin[2] = (bounds[5] + bounds[4]) / 2.0;

  this->TotalTransform->Identity();
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::SetOrigin(double ox, double oy, double oz)
{
  if (this->Origin[0] != ox || this->Origin[1] != oy || this->Origin[2] != oz)
  {
    this->Origin[0] = ox;
    this->Origin[1] = oy;
    this->Origin[2] = oz;

    this->BuildRepresentation();
    this->Modified();
  }
}

//------------------------------------------------------------------------------
int vtkAffineRepresentation2D::ComputeInteractionState(int X, int Y, int modify)
{
  double p[3], tol = static_cast<double>(this->Tolerance);
  p[0] = static_cast<double>(X);
  p[1] = static_cast<double>(Y);
  p[2] = 0.0;
  this->InteractionState = vtkAffineRepresentation::Outside;

  // Box---------------------------------------------------------------
  double p1[3], p2[3], p3[3], p4[3];
  this->BoxPoints->GetPoint(0, p1); // min corner
  this->BoxPoints->GetPoint(2, p3); // max corner

  int e0 = (p[1] >= (p1[1] - tol) && p[1] <= (p1[1] + tol));
  int e1 = (p[0] >= (p3[0] - tol) && p[0] <= (p3[0] + tol));
  int e2 = (p[1] >= (p3[1] - tol) && p[1] <= (p3[1] + tol));
  int e3 = (p[0] >= (p1[0] - tol) && p[0] <= (p1[0] + tol));

  // Points
  if (e0 && e1)
  {
    this->InteractionState = vtkAffineRepresentation::ScaleSE;
  }
  else if (e1 && e2)
  {
    this->InteractionState = vtkAffineRepresentation::ScaleNE;
  }
  else if (e2 && e3)
  {
    this->InteractionState = vtkAffineRepresentation::ScaleNW;
  }
  else if (e3 && e0)
  {
    this->InteractionState = vtkAffineRepresentation::ScaleSW;
  }

  // Edges
  else if (e0)
  {
    if (!modify)
    {
      this->InteractionState = vtkAffineRepresentation::ScaleSEdge;
    }
    else
    {
      this->InteractionState = vtkAffineRepresentation::ShearSEdge;
    }
  }
  else if (e1)
  {
    if (!modify)
    {
      this->InteractionState = vtkAffineRepresentation::ScaleEEdge;
    }
    else
    {
      this->InteractionState = vtkAffineRepresentation::ShearEEdge;
    }
  }
  else if (e2)
  {
    if (!modify)
    {
      this->InteractionState = vtkAffineRepresentation::ScaleNEdge;
    }
    else
    {
      this->InteractionState = vtkAffineRepresentation::ShearNEdge;
    }
  }
  else if (e3)
  {
    if (!modify)
    {
      this->InteractionState = vtkAffineRepresentation::ScaleWEdge;
    }
    else
    {
      this->InteractionState = vtkAffineRepresentation::ShearWEdge;
    }
  }

  // Return if necessary
  if (this->InteractionState != vtkAffineRepresentation::Outside)
  {
    return this->InteractionState;
  }

  // Circle---------------------------------------------------------------
  double radius = sqrt((p[0] - this->DisplayOrigin[0]) * (p[0] - this->DisplayOrigin[0]) +
    (p[1] - this->DisplayOrigin[1]) * (p[1] - this->DisplayOrigin[1]));
  if (radius >= (this->CurrentRadius - tol) && radius <= (this->CurrentRadius + tol))
  {
    this->InteractionState = vtkAffineRepresentation::Rotate;
    return this->InteractionState;
  }

  // Translation Arrows----------------------------------------------------
  this->XAxis->GetPositionCoordinate()->GetValue(p1);
  this->XAxis->GetPosition2Coordinate()->GetValue(p2);
  this->YAxis->GetPositionCoordinate()->GetValue(p3);
  this->YAxis->GetPosition2Coordinate()->GetValue(p4);

  e0 = (p[0] >= (p1[0] - tol) && p[0] <= (p2[0] + tol));
  e1 = (p[1] >= (p1[1] - tol) && p[1] <= (p1[1] + tol));
  e2 = (p[1] >= (p3[1] - tol) && p[1] <= (p4[1] + tol));
  e3 = (p[0] >= (p3[0] - tol) && p[0] <= (p3[0] + tol));

  if (e0 && e1 && e2 && e3)
  {
    if (!modify)
    {
      this->InteractionState = vtkAffineRepresentation::Translate;
    }
    else
    {
      this->InteractionState = vtkAffineRepresentation::MoveOrigin;
    }
  }
  else if (e0 && e1)
  {
    if (!modify)
    {
      this->InteractionState = vtkAffineRepresentation::TranslateX;
    }
    else
    {
      this->InteractionState = vtkAffineRepresentation::MoveOriginX;
    }
  }
  else if (e2 && e3)
  {
    if (!modify)
    {
      this->InteractionState = vtkAffineRepresentation::TranslateY;
    }
    else
    {
      this->InteractionState = vtkAffineRepresentation::MoveOriginY;
    }
  }

  return this->InteractionState;
}

//------------------------------------------------------------------------------
// Record the current event position, and the rectilinear wipe position.
void vtkAffineRepresentation2D::StartWidgetInteraction(double startEventPos[2])
{
  // Initialize bookkeeping variables
  this->StartEventPosition[0] = startEventPos[0];
  this->StartEventPosition[1] = startEventPos[1];
  this->StartEventPosition[2] = 0.0;
  vtkInteractorObserver::ComputeDisplayToWorld(
    this->Renderer, startEventPos[0], startEventPos[1], 0.0, this->StartWorldPosition);

  this->StartAngle = VTK_FLOAT_MAX;

  this->WidgetInteraction(startEventPos);
}

//------------------------------------------------------------------------------
// Based on the displacement vector (computed in display coordinates) and
// the cursor state (which corresponds to which part of the widget has been
// selected), the widget points are modified.
// First construct a local coordinate system based on the display coordinates
// of the widget.
void vtkAffineRepresentation2D::WidgetInteraction(double eventPos[2])
{
  // Dispatch to the correct method
  switch (this->InteractionState)
  {
    case vtkAffineRepresentation::ShearWEdge:
    case vtkAffineRepresentation::ShearEEdge:
    case vtkAffineRepresentation::ShearNEdge:
    case vtkAffineRepresentation::ShearSEdge:
      this->Shear(eventPos);
      break;

    case vtkAffineRepresentation::ScaleNE:
    case vtkAffineRepresentation::ScaleSW:
    case vtkAffineRepresentation::ScaleNW:
    case vtkAffineRepresentation::ScaleSE:
    case vtkAffineRepresentation::ScaleNEdge:
    case vtkAffineRepresentation::ScaleSEdge:
    case vtkAffineRepresentation::ScaleWEdge:
    case vtkAffineRepresentation::ScaleEEdge:
      this->Scale(eventPos);
      break;

    case vtkAffineRepresentation::Rotate:
      this->Rotate(eventPos);
      break;

    case vtkAffineRepresentation::TranslateX:
    case vtkAffineRepresentation::TranslateY:
    case vtkAffineRepresentation::Translate:
    case vtkAffineRepresentation::MoveOriginX:
    case vtkAffineRepresentation::MoveOriginY:
    case vtkAffineRepresentation::MoveOrigin:
      this->Translate(eventPos);
      break;
  }

  // Book keeping
  this->LastEventPosition[0] = eventPos[0];
  this->LastEventPosition[1] = eventPos[1];

  this->Modified();
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::EndWidgetInteraction(double vtkNotUsed(eventPos)[2])
{
  // Have to play games here because of the "pipelined" nature of the
  // transformations.
  this->GetTransform(this->TempTransform);
  this->TotalTransform->SetMatrix(this->TempTransform->GetMatrix());

  // Adjust the origin as necessary
  this->Origin[0] += this->CurrentTranslation[0];
  this->Origin[1] += this->CurrentTranslation[1];
  this->Origin[2] += this->CurrentTranslation[2];

  // Reset the current transformations
  this->CurrentTranslation[0] = 0.0;
  this->CurrentTranslation[1] = 0.0;
  this->CurrentTranslation[2] = 0.0;

  this->CurrentAngle = 0.0;

  this->CurrentScale[0] = 1.0;
  this->CurrentScale[1] = 1.0;

  this->CurrentShear[0] = 0.0;
  this->CurrentShear[1] = 0.0;
}

//------------------------------------------------------------------------------
// Translate everything
void vtkAffineRepresentation2D::Translate(double eventPos[2])
{
  double x1[3], x2[3], y1[3], y2[3], dpos[3];
  dpos[0] = dpos[1] = dpos[2] = 0.0;

  this->XAxis->GetPositionCoordinate()->GetValue(x1);
  this->XAxis->GetPosition2Coordinate()->GetValue(x2);
  this->YAxis->GetPositionCoordinate()->GetValue(y1);
  this->YAxis->GetPosition2Coordinate()->GetValue(y2);

  switch (this->InteractionState)
  {
    case vtkAffineRepresentation::TranslateX:
    case vtkAffineRepresentation::MoveOriginX:
      dpos[0] = eventPos[0] - this->StartEventPosition[0];
      break;

    case vtkAffineRepresentation::TranslateY:
    case vtkAffineRepresentation::MoveOriginY:
      dpos[1] = eventPos[1] - this->StartEventPosition[1];
      break;

    case vtkAffineRepresentation::Translate:
    case vtkAffineRepresentation::MoveOrigin:
      dpos[0] = eventPos[0] - this->StartEventPosition[0];
      dpos[1] = eventPos[1] - this->StartEventPosition[1];
      break;
  }

  x1[0] += dpos[0];
  x2[0] += dpos[0];
  y1[0] += dpos[0];
  y2[0] += dpos[0];
  x1[1] += dpos[1];
  x2[1] += dpos[1];
  y1[1] += dpos[1];
  y2[1] += dpos[1];

  this->HXAxis->GetPositionCoordinate()->SetValue(x1);
  this->HXAxis->GetPosition2Coordinate()->SetValue(x2);
  this->HYAxis->GetPositionCoordinate()->SetValue(y1);
  this->HYAxis->GetPosition2Coordinate()->SetValue(y2);

  // Update the transform
  double wxyz[4];
  vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,
    this->StartEventPosition[0] + dpos[0], this->StartEventPosition[1] + dpos[1], 0.0, wxyz);

  this->CurrentTranslation[0] = wxyz[0] - this->StartWorldPosition[0];
  this->CurrentTranslation[1] = wxyz[1] - this->StartWorldPosition[1];
  this->CurrentTranslation[2] = wxyz[2] - this->StartWorldPosition[2];

  // Draw the text if necessary
  if (this->DisplayText)
  {
    char str[256];
    snprintf(
      str, sizeof(str), "(%0.2g, %0.2g)", this->CurrentTranslation[0], this->CurrentTranslation[1]);
    this->UpdateText(str, eventPos);
  }
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::Scale(double eventPos[2])
{
  // Determine the relative motion
  double d[3];
  d[0] = eventPos[0] - this->StartEventPosition[0];
  d[1] = eventPos[1] - this->StartEventPosition[1];

  double x0[3], x1[3], x2[3], x3[3];
  double p0[3], p1[3], p2[3], p3[3];
  this->BoxPoints->GetPoint(0, x0);
  this->BoxPoints->GetPoint(1, x1);
  this->BoxPoints->GetPoint(2, x2);
  this->BoxPoints->GetPoint(3, x3);

  double xChange = 0.0, yChange = 0.0;
  switch (this->InteractionState)
  {
    case vtkAffineRepresentation::ScaleEEdge:
      xChange = 1.0;
      break;

    case vtkAffineRepresentation::ScaleWEdge:
      xChange = -1.0;
      break;

    case vtkAffineRepresentation::ScaleNEdge:
      yChange = 1.0;
      break;

    case vtkAffineRepresentation::ScaleSEdge:
      yChange = -1.0;
      break;

    case vtkAffineRepresentation::ScaleNE:
      xChange = 1.0;
      yChange = 1.0;
      break;

    case vtkAffineRepresentation::ScaleSW:
      xChange = -1.0;
      yChange = -1.0;
      break;

    case vtkAffineRepresentation::ScaleNW:
      xChange = -1.0;
      yChange = 1.0;
      break;

    case vtkAffineRepresentation::ScaleSE:
      xChange = 1.0;
      yChange = -1.0;
      break;
  }

  p0[0] = x0[0] - xChange * d[0];
  p1[0] = x1[0] + xChange * d[0];
  p2[0] = x2[0] + xChange * d[0];
  p3[0] = x3[0] - xChange * d[0];

  p0[1] = x0[1] - yChange * d[1];
  p1[1] = x1[1] - yChange * d[1];
  p2[1] = x2[1] + yChange * d[1];
  p3[1] = x3[1] + yChange * d[1];

  p0[2] = x0[2];
  p1[2] = x1[2];
  p2[2] = x2[2];
  p3[2] = x3[2];

  this->HBoxPoints->SetPoint(0, p0);
  this->HBoxPoints->SetPoint(1, p1);
  this->HBoxPoints->SetPoint(2, p2);
  this->HBoxPoints->SetPoint(3, p3);
  this->HBoxPoints->Modified();

  this->CurrentScale[0] = (p1[0] - p0[0]) / (x1[0] - x0[0]);
  this->CurrentScale[1] = (p2[1] - p1[1]) / (x2[1] - x1[1]);

  if (this->DisplayText)
  {
    char str[256];
    snprintf(str, sizeof(str), "(%0.2g, %0.2g)", this->CurrentScale[0], this->CurrentScale[1]);
    this->UpdateText(str, eventPos);
  }
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::Rotate(double eventPos[2])
{
  double deltaAngle;
  // Compute the initial selection angle, and then the change in angle between
  // the starting point and subsequent points. The angle is constrained so that
  // it is in the range (-Pi < deltaAngle <= Pi).
  if (this->StartAngle >= VTK_FLOAT_MAX)
  {
    double delX = this->StartEventPosition[0] - this->DisplayOrigin[0];
    double delY = this->StartEventPosition[1] - this->DisplayOrigin[1];
    this->StartAngle = atan2(delY, delX);
    deltaAngle = 0.0;
  }
  else
  {
    double delEX = eventPos[0] - this->DisplayOrigin[0];
    double delEY = eventPos[1] - this->DisplayOrigin[1];
    double angle2 = atan2(delEY, delEX);
    // Compute difference in angle
    deltaAngle = angle2 - this->StartAngle;
    if (fabs(deltaAngle) > vtkMath::Pi()) // angle always less than Pi
    {
      if (deltaAngle > 0)
      {
        deltaAngle = -2.0 * vtkMath::Pi() + deltaAngle;
      }
      else
      {
        deltaAngle = 2.0 * vtkMath::Pi() + deltaAngle;
      }
    }
  }

  // Update the angle
  this->CurrentAngle = deltaAngle;

  // Create the arc
  vtkIdType pid;
  this->HCirclePoints->Reset();
  this->HCircleCellArray->Reset();
  this->HCircleCellArray->InsertNextCell(0);
  double p[3];
  p[2] = 0.0;
  double theta, delTheta = 2.0 * vtkMath::Pi() / VTK_CIRCLE_RESOLUTION;
  int numDivs = static_cast<int>(fabs(deltaAngle) / delTheta) + 1;
  delTheta = deltaAngle / numDivs;
  for (int i = 0; i <= numDivs; i++)
  {
    theta = this->StartAngle + i * delTheta;
    p[0] = this->DisplayOrigin[0] + this->CurrentRadius * cos(theta);
    p[1] = this->DisplayOrigin[1] + this->CurrentRadius * sin(theta);
    pid = this->HCirclePoints->InsertNextPoint(p);
    this->HCircleCellArray->InsertCellPoint(pid);
  }
  pid = this->HCirclePoints->InsertNextPoint(this->DisplayOrigin);
  this->HCircleCellArray->InsertCellPoint(pid);
  this->HCircleCellArray->InsertCellPoint(0);
  this->HCircleCellArray->UpdateCellCount(this->HCirclePoints->GetNumberOfPoints() + 1);
  this->HCirclePoints->Modified();

  if (this->DisplayText)
  {
    char str[256];
    double angle = vtkMath::DegreesFromRadians(deltaAngle);
    snprintf(str, sizeof(str), "(%1.1f)", angle);
    this->UpdateText(str, eventPos);
  }
}

//------------------------------------------------------------------------------
// Fiddle with matrix to apply shear
void vtkAffineRepresentation2D::ApplyShear() {}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::Shear(double eventPos[2])
{
  // Determine the relative motion
  double d[3];
  d[0] = eventPos[0] - this->StartEventPosition[0];
  d[1] = eventPos[1] - this->StartEventPosition[1];

  double x0[3], x1[3], x2[3], x3[3];
  double p0[3], p1[3], p2[3], p3[3];
  this->BoxPoints->GetPoint(0, x0);
  this->BoxPoints->GetPoint(1, x1);
  this->BoxPoints->GetPoint(2, x2);
  this->BoxPoints->GetPoint(3, x3);

  double xChange = 0.0, yChange = 0.0;
  switch (this->InteractionState)
  {
    case vtkAffineRepresentation::ShearSEdge:
      xChange = 1.0;
      break;

    case vtkAffineRepresentation::ShearNEdge:
      xChange = -1.0;
      break;

    case vtkAffineRepresentation::ShearEEdge:
      yChange = 1.0;
      break;

    case vtkAffineRepresentation::ShearWEdge:
      yChange = -1.0;
      break;
  }

  p0[0] = x0[0] + xChange * d[0];
  p1[0] = x1[0] + xChange * d[0];
  p2[0] = x2[0] - xChange * d[0];
  p3[0] = x3[0] - xChange * d[0];

  p0[1] = x0[1] - yChange * d[1];
  p1[1] = x1[1] + yChange * d[1];
  p2[1] = x2[1] + yChange * d[1];
  p3[1] = x3[1] - yChange * d[1];

  p0[2] = x0[2];
  p1[2] = x1[2];
  p2[2] = x2[2];
  p3[2] = x3[2];

  this->HBoxPoints->SetPoint(0, p0);
  this->HBoxPoints->SetPoint(1, p1);
  this->HBoxPoints->SetPoint(2, p2);
  this->HBoxPoints->SetPoint(3, p3);
  this->HBoxPoints->Modified();

  // Update the current shear
  double sx = (x2[1] - x1[1]) / 2.0;
  double sy = ((p0[0] - x0[0]) + (p0[1] - x0[1]));
  double angle = vtkMath::DegreesFromRadians(atan2(sy, sx));
  if (this->InteractionState == vtkAffineRepresentation::ShearNEdge ||
    this->InteractionState == vtkAffineRepresentation::ShearSEdge)
  {
    this->CurrentShear[0] = angle;
  }
  else
  {
    this->CurrentShear[1] = angle;
  }

  // Display text if requested
  if (this->DisplayText)
  {
    char str[256];
    snprintf(str, sizeof(str), "(%0.2g)", angle);
    this->UpdateText(str, eventPos);
  }
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::Highlight(int highlight)
{
  if (highlight) // enable appropriate highlight actor
  {
    // Make the text visible
    if (this->DisplayText)
    {
      this->TextActor->VisibilityOn();
    }

    // The existing widget is set translucent
    this->Opacity = this->Property->GetOpacity();
    this->Property->SetOpacity(0.33);
    this->SelectedOpacity = this->SelectedProperty->GetOpacity();
    this->SelectedProperty->SetOpacity(1.0);

    switch (this->InteractionState)
    {
      case vtkAffineRepresentation::ShearWEdge:
      case vtkAffineRepresentation::ShearEEdge:
      case vtkAffineRepresentation::ShearNEdge:
      case vtkAffineRepresentation::ShearSEdge:
      case vtkAffineRepresentation::ScaleNE:
      case vtkAffineRepresentation::ScaleSW:
      case vtkAffineRepresentation::ScaleNW:
      case vtkAffineRepresentation::ScaleSE:
      case vtkAffineRepresentation::ScaleNEdge:
      case vtkAffineRepresentation::ScaleSEdge:
      case vtkAffineRepresentation::ScaleWEdge:
      case vtkAffineRepresentation::ScaleEEdge:
        this->HBoxActor->VisibilityOn();
        break;

      case vtkAffineRepresentation::Rotate:
        this->HCircleActor->VisibilityOn();
        break;

      case vtkAffineRepresentation::TranslateX:
      case vtkAffineRepresentation::TranslateY:
      case vtkAffineRepresentation::Translate:
      case vtkAffineRepresentation::MoveOriginX:
      case vtkAffineRepresentation::MoveOriginY:
      case vtkAffineRepresentation::MoveOrigin:
        this->HXAxis->VisibilityOn();
        this->HYAxis->VisibilityOn();
        break;
    }
  }

  else // turn off highlight actor
  {
    this->TextActor->VisibilityOff();
    this->Property->SetOpacity(this->Opacity);
    this->SelectedProperty->SetOpacity(this->SelectedOpacity);
    this->HBoxActor->VisibilityOff();
    this->HCircleActor->VisibilityOff();
    this->HXAxis->VisibilityOff();
    this->HYAxis->VisibilityOff();
  }
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::CreateDefaultProperties()
{
  this->Property = vtkProperty2D::New();
  this->Property->SetColor(0.0, 1.0, 0.0);
  this->Property->SetLineWidth(0.5);

  this->SelectedProperty = vtkProperty2D::New();
  this->SelectedProperty->SetColor(1.0, 0.0, 0.0);
  this->SelectedProperty->SetLineWidth(1.0);

  this->TextProperty = vtkTextProperty::New();
  this->TextProperty->SetFontSize(12);
  this->TextProperty->SetColor(1.0, 0.0, 0.0);
  this->TextProperty->SetBold(1);
  this->TextProperty->SetFontFamilyToArial();
  this->TextProperty->SetJustificationToLeft();
  this->TextProperty->SetVerticalJustificationToBottom();
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::UpdateText(const char* text, double eventPos[2])
{
  this->TextMapper->SetInput(text);
  this->TextActor->SetPosition(eventPos[0] + 7, eventPos[1] + 7);
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::BuildRepresentation()
{
  if (this->GetMTime() > this->BuildTime ||
    (this->Renderer && this->Renderer->GetVTKWindow() &&
      this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime))
  {
    // Determine where the origin is on the display
    vtkInteractorObserver::ComputeWorldToDisplay(
      this->Renderer, this->Origin[0], this->Origin[1], this->Origin[2], this->DisplayOrigin);

    // draw the box
    this->CurrentWidth = this->BoxWidth;
    this->CurrentWidth /= 2.0;
    double p1[3], p2[3], p3[3], p4[3];
    p1[0] = this->DisplayOrigin[0] - this->CurrentWidth;
    p1[1] = this->DisplayOrigin[1] - this->CurrentWidth;
    p1[2] = 0.0;
    p2[0] = this->DisplayOrigin[0] + this->CurrentWidth;
    p2[1] = this->DisplayOrigin[1] - this->CurrentWidth;
    p2[2] = 0.0;
    p3[0] = this->DisplayOrigin[0] + this->CurrentWidth;
    p3[1] = this->DisplayOrigin[1] + this->CurrentWidth;
    p3[2] = 0.0;
    p4[0] = this->DisplayOrigin[0] - this->CurrentWidth;
    p4[1] = this->DisplayOrigin[1] + this->CurrentWidth;
    p4[2] = 0.0;
    this->BoxPoints->SetPoint(0, p1);
    this->BoxPoints->SetPoint(1, p2);
    this->BoxPoints->SetPoint(2, p3);
    this->BoxPoints->SetPoint(3, p4);
    this->BoxPoints->Modified();

    // draw the circle
    int i;
    double theta, delTheta = 2.0 * vtkMath::Pi() / VTK_CIRCLE_RESOLUTION;
    this->CurrentRadius = this->CurrentWidth * 0.75;
    this->CircleCellArray->InsertNextCell(VTK_CIRCLE_RESOLUTION + 1);
    for (i = 0; i < VTK_CIRCLE_RESOLUTION; i++)
    {
      theta = i * delTheta;
      p1[0] = this->DisplayOrigin[0] + this->CurrentRadius * cos(theta);
      p1[1] = this->DisplayOrigin[1] + this->CurrentRadius * sin(theta);
      this->CirclePoints->SetPoint(i, p1);
      this->CircleCellArray->InsertCellPoint(i);
    }
    this->CircleCellArray->InsertCellPoint(0);

    // draw the translation axes
    this->CurrentAxesWidth = this->CurrentWidth * this->AxesWidth / this->BoxWidth;
    p1[0] = this->DisplayOrigin[0] - this->CurrentAxesWidth;
    p1[1] = this->DisplayOrigin[1];
    this->XAxis->GetPositionCoordinate()->SetValue(p1);
    p2[0] = this->DisplayOrigin[0] + this->CurrentAxesWidth;
    p2[1] = this->DisplayOrigin[1];
    this->XAxis->GetPosition2Coordinate()->SetValue(p2);

    p1[0] = this->DisplayOrigin[0];
    p1[1] = this->DisplayOrigin[1] - this->CurrentAxesWidth;
    this->YAxis->GetPositionCoordinate()->SetValue(p1);
    p2[0] = this->DisplayOrigin[0];
    p2[1] = this->DisplayOrigin[1] + this->CurrentAxesWidth;
    this->YAxis->GetPosition2Coordinate()->SetValue(p2);

    this->BuildTime.Modified();
  }
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::ShallowCopy(vtkProp* prop)
{
  vtkAffineRepresentation2D* rep = vtkAffineRepresentation2D::SafeDownCast(prop);
  if (rep)
  {
    this->SetProperty(rep->GetProperty());
    this->SetSelectedProperty(rep->GetSelectedProperty());
    this->SetTextProperty(rep->GetTextProperty());
    this->BoxActor->SetProperty(this->Property);
    this->HBoxActor->SetProperty(this->SelectedProperty);
    this->CircleActor->SetProperty(this->Property);
    this->HCircleActor->SetProperty(this->SelectedProperty);
    this->XAxis->SetProperty(this->Property);
    this->YAxis->SetProperty(this->Property);
    this->HXAxis->SetProperty(this->SelectedProperty);
    this->HYAxis->SetProperty(this->SelectedProperty);
  }
  this->Superclass::ShallowCopy(prop);
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::GetActors2D(vtkPropCollection* pc)
{
  this->BoxActor->GetActors2D(pc);
  this->HBoxActor->GetActors2D(pc);
  this->CircleActor->GetActors2D(pc);
  this->HCircleActor->GetActors2D(pc);
  this->XAxis->GetActors2D(pc);
  this->YAxis->GetActors2D(pc);
  this->HXAxis->GetActors2D(pc);
  this->HYAxis->GetActors2D(pc);
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::ReleaseGraphicsResources(vtkWindow* win)
{
  this->TextActor->ReleaseGraphicsResources(win);
  this->BoxActor->ReleaseGraphicsResources(win);
  this->HBoxActor->ReleaseGraphicsResources(win);
  this->CircleActor->ReleaseGraphicsResources(win);
  this->HCircleActor->ReleaseGraphicsResources(win);
  this->XAxis->ReleaseGraphicsResources(win);
  this->YAxis->ReleaseGraphicsResources(win);
  this->HXAxis->ReleaseGraphicsResources(win);
  this->HYAxis->ReleaseGraphicsResources(win);
}

//------------------------------------------------------------------------------
int vtkAffineRepresentation2D::RenderOverlay(vtkViewport* viewport)
{
  this->BuildRepresentation();

  int count = 0;
  if (this->TextActor->GetVisibility())
  {
    count += this->TextActor->RenderOverlay(viewport);
  }

  count += this->BoxActor->RenderOverlay(viewport);
  if (this->HBoxActor->GetVisibility())
  {
    count += this->HBoxActor->RenderOverlay(viewport);
  }

  count += this->CircleActor->RenderOverlay(viewport);
  if (this->HCircleActor->GetVisibility())
  {
    count += this->HCircleActor->RenderOverlay(viewport);
  }

  count += this->XAxis->RenderOverlay(viewport);
  count += this->YAxis->RenderOverlay(viewport);
  if (this->HXAxis->GetVisibility())
  {
    count += this->HXAxis->RenderOverlay(viewport);
  }
  if (this->HYAxis->GetVisibility())
  {
    count += this->HYAxis->RenderOverlay(viewport);
  }

  return count;
}

//------------------------------------------------------------------------------
void vtkAffineRepresentation2D::PrintSelf(ostream& os, vtkIndent indent)
{
  // Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h
  this->Superclass::PrintSelf(os, indent);

  os << indent << "Display Text: " << (this->DisplayText ? "On\n" : "Off\n");

  os << indent << "Origin: (" << this->Origin[0] << "," << this->Origin[1] << "," << this->Origin[2]
     << ")\n";
  os << indent << "Box Width: " << this->BoxWidth << "\n";
  os << indent << "Circle Width: " << this->CircleWidth << "\n";
  os << indent << "Axes Width: " << this->AxesWidth << "\n";

  if (this->TextProperty)
  {
    os << indent << "Text Property:\n";
    this->TextProperty->PrintSelf(os, indent.GetNextIndent());
  }
  else
  {
    os << indent << "Property: (none)\n";
  }

  if (this->Property)
  {
    os << indent << "Property:\n";
    this->Property->PrintSelf(os, indent.GetNextIndent());
  }
  else
  {
    os << indent << "Property: (none)\n";
  }

  if (this->SelectedProperty)
  {
    os << indent << "Selected Property:\n";
    this->SelectedProperty->PrintSelf(os, indent.GetNextIndent());
  }
  else
  {
    os << indent << "Selected Property: (none)\n";
  }

  if (this->TextProperty)
  {
    os << indent << "Text Property:\n";
    this->TextProperty->PrintSelf(os, indent.GetNextIndent());
  }
  else
  {
    os << indent << "Text Property: (none)\n";
  }
}

{'repo_name': 'Kitware/VTK', 'stars': '1386', 'repo_language': 'C++', 'file_name': 'TestSVGContextExport.cxx', 'mime_type': 'text/x-c++', 'hash': -5254156641555238460, 'source_dataset': 'data'}


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Cache\Storage;

use ArrayObject;
use stdClass;
use Zend\Cache\Exception;
use Zend\EventManager\EventsCapableInterface;

class Capabilities
{
    /**
     * The storage instance
     *
     * @var StorageInterface
     */
    protected $storage;

    /**
     * A marker to set/change capabilities
     *
     * @var stdClass
     */
    protected $marker;

    /**
     * Base capabilities
     *
     * @var null|Capabilities
     */
    protected $baseCapabilities;

    /**
     * Expire read
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|bool
     */
    protected $expiredRead;

    /**
     * Max. key length
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|int
     */
    protected $maxKeyLength;

    /**
     * Min. TTL (0 means items never expire)
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|int
     */
    protected $minTtl;

    /**
     * Max. TTL (0 means infinite)
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|int
     */
    protected $maxTtl;

    /**
     * Namespace is prefix
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|bool
     */
    protected $namespaceIsPrefix;

    /**
     * Namespace separator
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|string
     */
    protected $namespaceSeparator;

    /**
     * Static ttl
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|bool
     */
    protected $staticTtl;

   /**
    * Supported datatypes
    *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
    *
    * @var null|array
    */
    protected $supportedDatatypes;

    /**
     * Supported metdata
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|array
     */
    protected $supportedMetadata;

    /**
     * TTL precision
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|int
     */
    protected $ttlPrecision;

    /**
     * Use request time
     *
    * If it's NULL the capability isn't set and the getter
    * returns the base capability or the default value.
     *
     * @var null|bool
     */
    protected $useRequestTime;

    /**
     * Constructor
     *
     * @param StorageInterface  $storage
     * @param stdClass          $marker
     * @param array             $capabilities
     * @param null|Capabilities $baseCapabilities
     */
    public function __construct(
        StorageInterface $storage,
        stdClass $marker,
        array $capabilities = array(),
        Capabilities $baseCapabilities = null
    ) {
        $this->storage = $storage;
        $this->marker  = $marker;
        $this->baseCapabilities = $baseCapabilities;

        foreach ($capabilities as $name => $value) {
            $this->setCapability($marker, $name, $value);
        }
    }

    /**
     * Get the storage adapter
     *
     * @return StorageInterface
     */
    public function getAdapter()
    {
        return $this->storage;
    }

    /**
     * Get supported datatypes
     *
     * @return array
     */
    public function getSupportedDatatypes()
    {
        return $this->getCapability('supportedDatatypes', array(
            'NULL'     => false,
            'boolean'  => false,
            'integer'  => false,
            'double'   => false,
            'string'   => true,
            'array'    => false,
            'object'   => false,
            'resource' => false,
        ));
    }

    /**
     * Set supported datatypes
     *
     * @param  stdClass $marker
     * @param  array $datatypes
     * @throws Exception\InvalidArgumentException
     * @return Capabilities Fluent interface
     */
    public function setSupportedDatatypes(stdClass $marker, array $datatypes)
    {
        $allTypes = array(
            'array',
            'boolean',
            'double',
            'integer',
            'NULL',
            'object',
            'resource',
            'string',
        );

        // check/normalize datatype values
        foreach ($datatypes as $type => &$toType) {
            if (!in_array($type, $allTypes)) {
                throw new Exception\InvalidArgumentException("Unknown datatype '{$type}'");
            }

            if (is_string($toType)) {
                $toType = strtolower($toType);
                if (!in_array($toType, $allTypes)) {
                    throw new Exception\InvalidArgumentException("Unknown datatype '{$toType}'");
                }
            } else {
                $toType = (bool) $toType;
            }
        }

        // add missing datatypes as not supported
        $missingTypes = array_diff($allTypes, array_keys($datatypes));
        foreach ($missingTypes as $type) {
            $datatypes[$type] = false;
        }

        return $this->setCapability($marker, 'supportedDatatypes', $datatypes);
    }

    /**
     * Get supported metadata
     *
     * @return array
     */
    public function getSupportedMetadata()
    {
        return $this->getCapability('supportedMetadata', array());
    }

    /**
     * Set supported metadata
     *
     * @param  stdClass $marker
     * @param  string[] $metadata
     * @throws Exception\InvalidArgumentException
     * @return Capabilities Fluent interface
     */
    public function setSupportedMetadata(stdClass $marker, array $metadata)
    {
        foreach ($metadata as $name) {
            if (!is_string($name)) {
                throw new Exception\InvalidArgumentException('$metadata must be an array of strings');
            }
        }
        return $this->setCapability($marker, 'supportedMetadata', $metadata);
    }

    /**
     * Get minimum supported time-to-live
     *
     * @return int 0 means items never expire
     */
    public function getMinTtl()
    {
        return $this->getCapability('minTtl', 0);
    }

    /**
     * Set minimum supported time-to-live
     *
     * @param  stdClass $marker
     * @param  int $minTtl
     * @throws Exception\InvalidArgumentException
     * @return Capabilities Fluent interface
     */
    public function setMinTtl(stdClass $marker, $minTtl)
    {
        $minTtl = (int) $minTtl;
        if ($minTtl < 0) {
            throw new Exception\InvalidArgumentException('$minTtl must be greater or equal 0');
        }
        return $this->setCapability($marker, 'minTtl', $minTtl);
    }

    /**
     * Get maximum supported time-to-live
     *
     * @return int 0 means infinite
     */
    public function getMaxTtl()
    {
        return $this->getCapability('maxTtl', 0);
    }

    /**
     * Set maximum supported time-to-live
     *
     * @param  stdClass $marker
     * @param  int $maxTtl
     * @throws Exception\InvalidArgumentException
     * @return Capabilities Fluent interface
     */
    public function setMaxTtl(stdClass $marker, $maxTtl)
    {
        $maxTtl = (int) $maxTtl;
        if ($maxTtl < 0) {
            throw new Exception\InvalidArgumentException('$maxTtl must be greater or equal 0');
        }
        return $this->setCapability($marker, 'maxTtl', $maxTtl);
    }

    /**
     * Is the time-to-live handled static (on write)
     * or dynamic (on read)
     *
     * @return bool
     */
    public function getStaticTtl()
    {
        return $this->getCapability('staticTtl', false);
    }

    /**
     * Set if the time-to-live handled static (on write) or dynamic (on read)
     *
     * @param  stdClass $marker
     * @param  bool $flag
     * @return Capabilities Fluent interface
     */
    public function setStaticTtl(stdClass $marker, $flag)
    {
        return $this->setCapability($marker, 'staticTtl', (bool) $flag);
    }

    /**
     * Get time-to-live precision
     *
     * @return float
     */
    public function getTtlPrecision()
    {
        return $this->getCapability('ttlPrecision', 1);
    }

    /**
     * Set time-to-live precision
     *
     * @param  stdClass $marker
     * @param  float $ttlPrecision
     * @throws Exception\InvalidArgumentException
     * @return Capabilities Fluent interface
     */
    public function setTtlPrecision(stdClass $marker, $ttlPrecision)
    {
        $ttlPrecision = (float) $ttlPrecision;
        if ($ttlPrecision <= 0) {
            throw new Exception\InvalidArgumentException('$ttlPrecision must be greater than 0');
        }
        return $this->setCapability($marker, 'ttlPrecision', $ttlPrecision);
    }

    /**
     * Get use request time
     *
     * @return bool
     */
    public function getUseRequestTime()
    {
        return $this->getCapability('useRequestTime', false);
    }

    /**
     * Set use request time
     *
     * @param  stdClass $marker
     * @param  bool $flag
     * @return Capabilities Fluent interface
     */
    public function setUseRequestTime(stdClass $marker, $flag)
    {
        return $this->setCapability($marker, 'useRequestTime', (bool) $flag);
    }

    /**
     * Get if expired items are readable
     *
     * @return bool
     */
    public function getExpiredRead()
    {
        return $this->getCapability('expiredRead', false);
    }

    /**
     * Set if expired items are readable
     *
     * @param  stdClass $marker
     * @param  bool $flag
     * @return Capabilities Fluent interface
     */
    public function setExpiredRead(stdClass $marker, $flag)
    {
        return $this->setCapability($marker, 'expiredRead', (bool) $flag);
    }

    /**
     * Get maximum key lenth
     *
     * @return int -1 means unknown, 0 means infinite
     */
    public function getMaxKeyLength()
    {
        return $this->getCapability('maxKeyLength', -1);
    }

    /**
     * Set maximum key length
     *
     * @param  stdClass $marker
     * @param  int $maxKeyLength
     * @throws Exception\InvalidArgumentException
     * @return Capabilities Fluent interface
     */
    public function setMaxKeyLength(stdClass $marker, $maxKeyLength)
    {
        $maxKeyLength = (int) $maxKeyLength;
        if ($maxKeyLength < -1) {
            throw new Exception\InvalidArgumentException('$maxKeyLength must be greater or equal than -1');
        }
        return $this->setCapability($marker, 'maxKeyLength', $maxKeyLength);
    }

    /**
     * Get if namespace support is implemented as prefix
     *
     * @return bool
     */
    public function getNamespaceIsPrefix()
    {
        return $this->getCapability('namespaceIsPrefix', true);
    }

    /**
     * Set if namespace support is implemented as prefix
     *
     * @param  stdClass $marker
     * @param  bool $flag
     * @return Capabilities Fluent interface
     */
    public function setNamespaceIsPrefix(stdClass $marker, $flag)
    {
        return $this->setCapability($marker, 'namespaceIsPrefix', (bool) $flag);
    }

    /**
     * Get namespace separator if namespace is implemented as prefix
     *
     * @return string
     */
    public function getNamespaceSeparator()
    {
        return $this->getCapability('namespaceSeparator', '');
    }

    /**
     * Set the namespace separator if namespace is implemented as prefix
     *
     * @param  stdClass $marker
     * @param  string $separator
     * @return Capabilities Fluent interface
     */
    public function setNamespaceSeparator(stdClass $marker, $separator)
    {
        return $this->setCapability($marker, 'namespaceSeparator', (string) $separator);
    }

    /**
     * Get a capability
     *
     * @param  string $property
     * @param  mixed $default
     * @return mixed
     */
    protected function getCapability($property, $default = null)
    {
        if ($this->$property !== null) {
            return $this->$property;
        } elseif ($this->baseCapabilities) {
            $getMethod = 'get' . $property;
            return $this->baseCapabilities->$getMethod();
        }
        return $default;
    }

    /**
     * Change a capability
     *
     * @param  stdClass $marker
     * @param  string $property
     * @param  mixed $value
     * @return Capabilities Fluent interface
     * @throws Exception\InvalidArgumentException
     */
    protected function setCapability(stdClass $marker, $property, $value)
    {
        if ($this->marker !== $marker) {
            throw new Exception\InvalidArgumentException('Invalid marker');
        }

        if ($this->$property !== $value) {
            $this->$property = $value;

            // trigger event
            if ($this->storage instanceof EventsCapableInterface) {
                $this->storage->getEventManager()->trigger('capability', $this->storage, new ArrayObject(array(
                    $property => $value
                )));
            }
        }

        return $this;
    }
}

{'repo_name': 'eryx/php-framework-benchmark', 'stars': '131', 'repo_language': 'PHP', 'file_name': 'base.html.twig', 'mime_type': 'text/html', 'hash': 1603997720450611547, 'source_dataset': 'data'}


<%doc>
###############################################################################

=head1 NAME

=head1 SYNOPSIS
$m->comp("/widgets/profile/textarea.mc",
$disp   => ''
$value  => ''
$name  => ''
$rows   => ''
$cols   => ''
$js     => ''
);
=head1 DESCRIPTION
 Pretty wrapper for displayFormElement.mc.
=cut
</%doc>

<%args>

$disp   => ''
$value  => ''
$name  => ''
$rows   => ''
$cols   => ''
$js     => ''
$req    => 0
$useTable => 1
$localize => 1
$readOnly => 0
$width     => ''
$indent    => ''
</%args>

<%perl>

my $vals = {
    disp      => $disp,
    value     => $value,
    props     => {
        type => 'textarea',
        rows => $rows,
        cols => $cols
    },
    js        => $js,
    req       => $req
};

$m->comp("/widgets/profile/displayFormElement.mc",
     key      => $name,
     vals     => $vals,
     useTable => $useTable,
     readOnly => $readOnly,
     width    => $width,
     localize => $localize,
     indent   => $indent
);

</%perl>

{'repo_name': 'bricoleurs/bricolage', 'stars': '110', 'repo_language': 'Perl', 'file_name': 'story.mc', 'mime_type': 'text/plain', 'hash': 469165665108418507, 'source_dataset': 'data'}


/**
 * This script helps switching the version in all Schemas and XML config files
 *
 * $Id$
 */

import org.codehaus.groovy.ant.FileScanner

def cliBuilder = new CliBuilder()
cliBuilder.f(longOpt: "from", args: 1, "switch from version (e.g. 2.2)")
cliBuilder.h(longOpt: "help", "show usage info")
cliBuilder.r(longOpt: "root", args: 1, "start scanning at this root folder")
cliBuilder.t(longOpt: "to", args: 1, "switch to version (e.g. 3.0)")

options = cliBuilder.parse(args)

if (!options)
{
    println ""
    println "Error parsing options " + args
    println ""
    System.exit(1)
}

if (options.h)
{
    cliBuilder.usage()
    System.exit(0)
}

def root = "."
if (options.r)
{
    root = options.r
}

sourceSchemaVersion = "2.2"
if (options.f)
{
    sourceSchemaVersion = options.f
}

destSchemaVersion = "3.0"
if (options.t)
{
    destSchemaVersion = options.t
}

// this regex matches both, the CE (.org) and EE (.com) schema in the source version
// There is one matching group around the whole schema so the matching schema name can be
// accessed from the code below
schemaRegex = /(http:\/\/www.mulesoft.[org|com]{3}?\/schema\/mule[\/\w+\/]+$sourceSchemaVersion)/
xsdRegex = /(http:\/\/www.mulesoft.[org|com]{3}?\/schema\/mule[\/\w+\/]+$sourceSchemaVersion\/.*xsd)/
//
// switch the version in all XSD and XML files
//
AntBuilder ant = new AntBuilder()
FileScanner scanner = ant.fileScanner
{
    fileset(dir: root)
    {
        include(name: "**/*.xsd")
        include(name: "**/*.xml")
        exclude(name: "**/pom.xml")
        exclude(name: "**/target/**")
        exclude(name: "**/test-data/out/**")
    }
}

def noChange = {
    return it
}

scanner.each
{
    println "switching schema version on $it"
    switchSchemaVersion(it, noChange, noChange, xsdRegex)
    switchSchemaVersion(it, noChange, noChange, schemaRegex)
}

//
// switch all spring.handlers and spring.schemas files
//
scanner = ant.fileScanner
{
    fileset(dir: root)
    {
        include(name: "**/spring.handlers")
        include(name: "**/spring.schemas")
        exclude(name: "**/target/**")
    }
}

def preProcess = {
    return it.replace("\\:", ":")
}

def postProcess = {
    return it.replace(":", "\\:")
}

scanner.each
{
    println "switching schema version on $it"
    switchSchemaVersion(it, preProcess, postProcess, xsdRegex)
    switchSchemaVersion(it, preProcess, postProcess, schemaRegex)
}

def switchSchemaVersion(File inFile, def preProcessFunction, def postProcessFunction, def matcher)
{
    def filename = inFile.name + ".version-switched"
    def outFile = new File(inFile.parentFile, filename)

    def schemaReplaced = false
    outFile.withWriter
    {
        outWriter ->

        inFile.eachLine
        {
            line ->

            line = preProcessFunction(line)

            def match = (line =~ matcher)
            while (match.find())
            {
                schemaReplaced = true

                def srcSchema = null
                srcSchema = match[0][1]
                def destSchema = null
                if(match =~ "xsd")
                {
                    destSchema = srcSchema.replace(sourceSchemaVersion, destSchemaVersion)
                }
                else
                {
                    destSchema = srcSchema.replace(sourceSchemaVersion, "")
                    //strip last '/'
                    destSchema = destSchema.substring(0,destSchema.length()-1)
                }
                line = line.replace(srcSchema, destSchema)

                match = (line =~ matcher)
            }

            def convertedLine = postProcessFunction(line)
            outWriter.writeLine(convertedLine)
        }
    }

    if (schemaReplaced)
    {
        def backupFile = new File(inFile.parentFile, inFile.name + ".bak")
        move(inFile, backupFile)
        move(outFile, inFile)
        delete(backupFile)
    }
    else
    {
        delete(outFile)
    }
}

def move(File sourceFile, File destFile)
{
    if (destFile.exists())
    {
        throw new IOException(destFile.canonicalPath + " exists!")
    }

    if (sourceFile.renameTo(destFile) == false)
    {
        throw new IOException("moving " + sourceFile.absolutePath + " to " + destFile.absolutePath + " failed")
    }
}

def delete(File file)
{
    if (file.delete() == false)
    {
        throw new IOException("deleting " + file.canonicalFile + " failed")
    }
}

{'repo_name': 'mulesoft/mule', 'stars': '134', 'repo_language': 'Java', 'file_name': 'libraries_disclaimer.txt', 'mime_type': 'text/plain', 'hash': 2621344160757945361, 'source_dataset': 'data'}


The Vector SMG is a delayed blowback submachine gun with a unique, in-line design that places both the shooter's hand and shoulder in line with the bore axis, reducing muzzle climb during bursts.  This one is chambered in .45 ACP.

Developed as a successor to the MP5 submachine gun, the UMP45 retains the earlier model's supreme accuracy and low recoil, but in the higher .45 caliber.

You can get 'em for over US$1K if you want.  This is a fairly cheap remake.

The M1911 was the US Military standard-issue sidearm for most of the 20th Century.  It remains one of the most popular .45 pistols today.

The M45A1 supplanted earlier M45 MEUSOC pistols in use by Force Recon elements of Marine Expeditionary Units.  Where the original M45 pistols were gutted M1911A1's hand-fitted by USMC armorers, the updated M45A1's are hardly different from any other commercial 1911 design save for their dual recoil springs.  Most were replaced in 2016 with Glock 19's due to logistics issues.

The MAC-10 is a popular machine pistol originally designed for military use.  For many years they were the most inexpensive automatic weapon in the US, and enjoyed great popularity among criminals less concerned with quality firearms.

A home-made rifle.  It is simply a pipe attached to a stock, with a hammer to strike the single round it holds.

A Luty pattern makeshift smoothbore SMG crudely constructed out of various steel parts using some of the more advanced powered hand tools; likely one of the most complex guns that are feasible to make outside of a machine shop, but still very unreliable.  This one is chambered for .45 ACP cartridges and accepts MAC-10 compatible magazines.

Crafting recipe must make use of angle grinder, bench grinder, set square and vise, which don't yet exist in game.

On one hand, it's very big for a handgun. On the other, it's still a scrap weapon.

A large and heavy pistol evidently welded from scrap.  It's not pretty, but the .45 it's chambered with packs a serious punch.  Just watch out for the kick.

An American-made submachine gun developed during the very end of World War I, too late to see action.  Infamous during the 1920s for its use by gangsters, and was used during World War II before being mostly replaced with less-expensive alternatives.

Jokingly referred to as "The World's Only Crew-Served Pistol", this massive pistol was designed as a primary weapon for select "special operators".  Its cumbersome nature, the introduction of the derivative HK USP series and the logistics of getting .45 ACP ammunition in theater doomed this behemoth to US SOCOM armories.  Like the USP, the Mk 23 is a remarkably reliable gun; someone could probably take out a nuclear equipped walking tank with this in their holster.

The Walther PPQ is a semi-automatic pistol originating from the Walther P99QA, and maintains compatibility with some of its predecessor's accessories.  This model is chambered in .45 ACP.

The Hi-Point Model JHP is a blowback operated semi-automatic pistol designed by Hi-Point Firearms, which is known for making inexpensive firearms, and for making said firearms bulky and uncomfortable.  Hi-Points have slides made with a zinc pot-metal which is relatively fragile compared to steel slides.

{'repo_name': 'CleverRaven/Cataclysm-DDA', 'stars': '4334', 'repo_language': 'C++', 'file_name': 'pages.h', 'mime_type': 'text/x-tex', 'hash': 5492172616315694381, 'source_dataset': 'data'}


-----------------------------------------------------------------------------
-- LTN12 - Filters, sources, sinks and pumps.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------

-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local table = require("table")
local base = _G
local _M = {}
if module then -- heuristic for exporting a global package table
    ltn12 = _M
end
local filter,source,sink,pump = {},{},{},{}

_M.filter = filter
_M.source = source
_M.sink = sink
_M.pump = pump

-- 2048 seems to be better in windows...
_M.BLOCKSIZE = 2048
_M._VERSION = "LTN12 1.0.3"

-----------------------------------------------------------------------------
-- Filter stuff
-----------------------------------------------------------------------------
-- returns a high level filter that cycles a low-level filter
function filter.cycle(low, ctx, extra)
    base.assert(low)
    return function(chunk)
        local ret
        ret, ctx = low(ctx, chunk, extra)
        return ret
    end
end

-- chains a bunch of filters together
-- (thanks to Wim Couwenberg)
function filter.chain(...)
    local arg = {...}
    local n = select('#',...)
    local top, index = 1, 1
    local retry = ""
    return function(chunk)
        retry = chunk and retry
        while true do
            if index == top then
                chunk = arg[index](chunk)
                if chunk == "" or top == n then return chunk
                elseif chunk then index = index + 1
                else
                    top = top+1
                    index = top
                end
            else
                chunk = arg[index](chunk or "")
                if chunk == "" then
                    index = index - 1
                    chunk = retry
                elseif chunk then
                    if index == n then return chunk
                    else index = index + 1 end
                else base.error("filter returned inappropriate nil") end
            end
        end
    end
end

-----------------------------------------------------------------------------
-- Source stuff
-----------------------------------------------------------------------------
-- create an empty source
local function empty()
    return nil
end

function source.empty()
    return empty
end

-- returns a source that just outputs an error
function source.error(err)
    return function()
        return nil, err
    end
end

-- creates a file source
function source.file(handle, io_err)
    if handle then
        return function()
            local chunk = handle:read(_M.BLOCKSIZE)
            if not chunk then handle:close() end
            return chunk
        end
    else return source.error(io_err or "unable to open file") end
end

-- turns a fancy source into a simple source
function source.simplify(src)
    base.assert(src)
    return function()
        local chunk, err_or_new = src()
        src = err_or_new or src
        if not chunk then return nil, err_or_new
        else return chunk end
    end
end

-- creates string source
function source.string(s)
    if s then
        local i = 1
        return function()
            local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1)
            i = i + _M.BLOCKSIZE
            if chunk ~= "" then return chunk
            else return nil end
        end
    else return source.empty() end
end

-- creates rewindable source
function source.rewind(src)
    base.assert(src)
    local t = {}
    return function(chunk)
        if not chunk then
            chunk = table.remove(t)
            if not chunk then return src()
            else return chunk end
        else
            table.insert(t, chunk)
        end
    end
end

function source.chain(src, f)
    base.assert(src and f)
    local last_in, last_out = "", ""
    local state = "feeding"
    local err
    return function()
        if not last_out then
            base.error('source is empty!', 2)
        end
        while true do
            if state == "feeding" then
                last_in, err = src()
                if err then return nil, err end
                last_out = f(last_in)
                if not last_out then
                    if last_in then
                        base.error('filter returned inappropriate nil')
                    else
                        return nil
                    end
                elseif last_out ~= "" then
                    state = "eating"
                    if last_in then last_in = "" end
                    return last_out
                end
            else
                last_out = f(last_in)
                if last_out == "" then
                    if last_in == "" then
                        state = "feeding"
                    else
                        base.error('filter returned ""')
                    end
                elseif not last_out then
                    if last_in then
                        base.error('filter returned inappropriate nil')
                    else
                        return nil
                    end
                else
                    return last_out
                end
            end
        end
    end
end

-- creates a source that produces contents of several sources, one after the
-- other, as if they were concatenated
-- (thanks to Wim Couwenberg)
function source.cat(...)
    local arg = {...}
    local src = table.remove(arg, 1)
    return function()
        while src do
            local chunk, err = src()
            if chunk then return chunk end
            if err then return nil, err end
            src = table.remove(arg, 1)
        end
    end
end

-----------------------------------------------------------------------------
-- Sink stuff
-----------------------------------------------------------------------------
-- creates a sink that stores into a table
function sink.table(t)
    t = t or {}
    local f = function(chunk, err)
        if chunk then table.insert(t, chunk) end
        return 1
    end
    return f, t
end

-- turns a fancy sink into a simple sink
function sink.simplify(snk)
    base.assert(snk)
    return function(chunk, err)
        local ret, err_or_new = snk(chunk, err)
        if not ret then return nil, err_or_new end
        snk = err_or_new or snk
        return 1
    end
end

-- creates a file sink
function sink.file(handle, io_err)
    if handle then
        return function(chunk, err)
            if not chunk then
                handle:close()
                return 1
            else return handle:write(chunk) end
        end
    else return sink.error(io_err or "unable to open file") end
end

-- creates a sink that discards data
local function null()
    return 1
end

function sink.null()
    return null
end

-- creates a sink that just returns an error
function sink.error(err)
    return function()
        return nil, err
    end
end

-- chains a sink with a filter
function sink.chain(f, snk)
    base.assert(f and snk)
    return function(chunk, err)
        if chunk ~= "" then
            local filtered = f(chunk)
            local done = chunk and ""
            while true do
                local ret, snkerr = snk(filtered, err)
                if not ret then return nil, snkerr end
                if filtered == done then return 1 end
                filtered = f(done)
            end
        else return 1 end
    end
end

-----------------------------------------------------------------------------
-- Pump stuff
-----------------------------------------------------------------------------
-- pumps one chunk from the source to the sink
function pump.step(src, snk)
    local chunk, src_err = src()
    local ret, snk_err = snk(chunk, src_err)
    if chunk and ret then return 1
    else return nil, src_err or snk_err end
end

-- pumps all data from a source to a sink, using a step function
function pump.all(src, snk, step)
    base.assert(src and snk)
    step = step or pump.step
    while true do
        local ret, err = step(src, snk)
        if not ret then
            if err then return nil, err
            else return 1 end
        end
    end
end

return _M

{'repo_name': 'raymondlu/super-animation-samples', 'stars': '229', 'repo_language': 'C++', 'file_name': 'attack_front.plist', 'mime_type': 'text/xml', 'hash': -514652189460375163, 'source_dataset': 'data'}


// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// +build integration

// Package integration_test contains core runners for integration tests
package integration_test

import (
	"context"
	"flag"
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/suite"

	"github.com/talos-systems/talos/internal/integration/api"
	"github.com/talos-systems/talos/internal/integration/base"
	"github.com/talos-systems/talos/internal/integration/cli"
	"github.com/talos-systems/talos/internal/integration/k8s"
	provision_test "github.com/talos-systems/talos/internal/integration/provision"
	"github.com/talos-systems/talos/pkg/machinery/client/config"
	"github.com/talos-systems/talos/pkg/provision"
	"github.com/talos-systems/talos/pkg/provision/providers"
	"github.com/talos-systems/talos/pkg/version"
)

// Accumulated list of all the suites to run.
var allSuites []suite.TestingSuite

// Flag values.
var (
	failFast         bool
	crashdumpEnabled bool
	talosConfig      string
	endpoint         string
	k8sEndpoint      string
	expectedVersion  string
	talosctlPath     string
	kubectlPath      string
	provisionerName  string
	clusterName      string
	stateDir         string
)

func TestIntegration(t *testing.T) {
	if talosConfig == "" {
		t.Error("--talos.config is not provided")
	}

	var (
		cluster     provision.Cluster
		provisioner provision.Provisioner
		err         error
	)

	if provisionerName != "" {
		// use provisioned cluster state as discovery source
		ctx := context.Background()

		provisioner, err = providers.Factory(ctx, provisionerName)
		if err != nil {
			t.Error("error initializing provisioner", err)
		}

		defer provisioner.Close() //nolint: errcheck

		cluster, err = provisioner.Reflect(ctx, clusterName, stateDir)
		if err != nil {
			t.Error("error reflecting cluster via provisioner", err)
		}
	}

	provision_test.DefaultSettings.CurrentVersion = expectedVersion

	for _, s := range allSuites {
		if configuredSuite, ok := s.(base.ConfiguredSuite); ok {
			configuredSuite.SetConfig(base.TalosSuite{
				Endpoint:     endpoint,
				K8sEndpoint:  k8sEndpoint,
				Cluster:      cluster,
				TalosConfig:  talosConfig,
				Version:      expectedVersion,
				TalosctlPath: talosctlPath,
				KubectlPath:  kubectlPath,
			})
		}

		var suiteName string
		if namedSuite, ok := s.(base.NamedSuite); ok {
			suiteName = namedSuite.SuiteName()
		}

		t.Run(suiteName, func(tt *testing.T) {
			suite.Run(tt, s) //nolint: scopelint
		})

		if failFast && t.Failed() {
			t.Log("fastfail mode enabled, aborting on first failure")
			break
		}
	}

	if t.Failed() && crashdumpEnabled && cluster != nil && provisioner != nil {
		// if provisioner & cluster are available,
		// debugging failed test is easier with crashdump
		provisioner.CrashDump(context.Background(), cluster, os.Stderr)
	}
}

func init() {
	defaultTalosConfig, _ := config.GetDefaultPath() //nolint: errcheck

	defaultStateDir, err := config.GetTalosDirectory()
	if err == nil {
		defaultStateDir = filepath.Join(defaultStateDir, "clusters")
	}

	flag.BoolVar(&failFast, "talos.failfast", false, "fail the test run on the first failed test")
	flag.BoolVar(&crashdumpEnabled, "talos.crashdump", true, "print crashdump on test failure (only if provisioner is enabled)")

	flag.StringVar(&talosConfig, "talos.config", defaultTalosConfig, "The path to the Talos configuration file")
	flag.StringVar(&endpoint, "talos.endpoint", "", "endpoint to use (overrides config)")
	flag.StringVar(&k8sEndpoint, "talos.k8sendpoint", "", "Kubernetes endpoint to use (overrides kubeconfig)")
	flag.StringVar(&provisionerName, "talos.provisioner", "", "Talos cluster provisioner to use, if not set cluster state is disabled")
	flag.StringVar(&stateDir, "talos.state", defaultStateDir, "directory path to store cluster state")
	flag.StringVar(&clusterName, "talos.name", "talos-default", "the name of the cluster")
	flag.StringVar(&expectedVersion, "talos.version", version.Tag, "expected Talos version")
	flag.StringVar(&talosctlPath, "talos.talosctlpath", "talosctl", "The path to 'talosctl' binary")
	flag.StringVar(&kubectlPath, "talos.kubectlpath", "kubectl", "The path to 'kubectl' binary")

	flag.StringVar(&provision_test.DefaultSettings.CIDR, "talos.provision.cidr", provision_test.DefaultSettings.CIDR, "CIDR to use to provision clusters (provision tests only)")
	flag.Var(&provision_test.DefaultSettings.RegistryMirrors, "talos.provision.registry-mirror", "registry mirrors to use (provision tests only)")
	flag.IntVar(&provision_test.DefaultSettings.MTU, "talos.provision.mtu", provision_test.DefaultSettings.MTU, "MTU to use for cluster network (provision tests only)")
	flag.Int64Var(&provision_test.DefaultSettings.CPUs, "talos.provision.cpu", provision_test.DefaultSettings.CPUs, "CPU count for each VM (provision tests only)")
	flag.Int64Var(&provision_test.DefaultSettings.MemMB, "talos.provision.mem", provision_test.DefaultSettings.MemMB, "memory (in MiB) for each VM (provision tests only)")
	flag.Int64Var(&provision_test.DefaultSettings.DiskGB, "talos.provision.disk", provision_test.DefaultSettings.DiskGB, "disk size (in GiB) for each VM (provision tests only)")
	flag.IntVar(&provision_test.DefaultSettings.MasterNodes, "talos.provision.masters", provision_test.DefaultSettings.MasterNodes, "master node count (provision tests only)")
	flag.IntVar(&provision_test.DefaultSettings.WorkerNodes, "talos.provision.workers", provision_test.DefaultSettings.WorkerNodes, "worker node count (provision tests only)")
	flag.StringVar(&provision_test.DefaultSettings.TargetInstallImageRegistry, "talos.provision.target-installer-registry", provision_test.DefaultSettings.TargetInstallImageRegistry, "image registry for target installer image (provision tests only)")
	flag.StringVar(&provision_test.DefaultSettings.CustomCNIURL, "talos.provision.custom-cni-url", provision_test.DefaultSettings.CustomCNIURL, "custom CNI URL for the cluster (provision tests only)")

	allSuites = append(allSuites, api.GetAllSuites()...)
	allSuites = append(allSuites, cli.GetAllSuites()...)
	allSuites = append(allSuites, k8s.GetAllSuites()...)
	allSuites = append(allSuites, provision_test.GetAllSuites()...)
}

{'repo_name': 'talos-systems/talos', 'stars': '1787', 'repo_language': 'Go', 'file_name': 'image.go', 'mime_type': 'text/plain', 'hash': 2433721245046589041, 'source_dataset': 'data'}


/*
 * mux.c
 *
 * Pinmux Setting for B&R LEIT Board(s)
 *
 * Copyright (C) 2013 Hannes Petermaier <oe5hpm@oevsv.at>
 * Bernecker & Rainer Industrieelektronik GmbH - http://www.br-automation.com
 *
 * SPDX-License-Identifier:	GPL-2.0+
 */

#include <common.h>
#include <asm/arch/sys_proto.h>
#include <asm/arch/hardware.h>
#include <asm/arch/mux.h>
#include <asm/io.h>
#include <i2c.h>

static struct module_pin_mux uart0_pin_mux[] = {
	/* UART0_CTS */
	{OFFSET(uart0_ctsn), (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* UART0_RXD */
	{OFFSET(uart0_rxd), (MODE(0) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* UART0_TXD */
	{OFFSET(uart0_txd), (MODE(0) | PULLUDEN)},
	{-1},
};
#ifdef CONFIG_MMC
static struct module_pin_mux mmc1_pin_mux[] = {
	{OFFSET(gpmc_ad3), (MODE(1) | RXACTIVE | PULLUP_EN)},	/* MMC1_DAT3 */
	{OFFSET(gpmc_ad2), (MODE(1) | RXACTIVE | PULLUP_EN)},	/* MMC1_DAT2 */
	{OFFSET(gpmc_ad1), (MODE(1) | RXACTIVE | PULLUP_EN)},	/* MMC1_DAT1 */
	{OFFSET(gpmc_ad0), (MODE(1) | RXACTIVE | PULLUP_EN)},	/* MMC1_DAT0 */
	{OFFSET(gpmc_csn1), (MODE(2) | RXACTIVE | PULLUP_EN)},	/* MMC1_CLK */
	{OFFSET(gpmc_csn2), (MODE(2) | RXACTIVE | PULLUP_EN)},	/* MMC1_CMD */
	{OFFSET(gpmc_csn0), (MODE(7) | RXACTIVE | PULLUP_EN)},	/* MMC1_WP */
	{OFFSET(gpmc_advn_ale), (MODE(7) | RXACTIVE | PULLUP_EN)},/* MMC1_CD */
	{-1},
};
#endif
static struct module_pin_mux i2c0_pin_mux[] = {
	/* I2C_DATA */
	{OFFSET(i2c0_sda), (MODE(0) | RXACTIVE | PULLUDEN | SLEWCTRL)},
	/* I2C_SCLK */
	{OFFSET(i2c0_scl), (MODE(0) | RXACTIVE | PULLUDEN | SLEWCTRL)},
	{-1},
};

static struct module_pin_mux spi0_pin_mux[] = {
	/* SPI0_SCLK */
	{OFFSET(spi0_sclk), (MODE(0) | RXACTIVE | PULLUDEN | PULLUP_EN)},
	/* SPI0_D0 */
	{OFFSET(spi0_d0), (MODE(0) | RXACTIVE |	PULLUDEN | PULLUP_EN)},
	/* SPI0_D1 */
	{OFFSET(spi0_d1), (MODE(0) | RXACTIVE | PULLUDEN | PULLUP_EN)},
	/* SPI0_CS0 */
	{OFFSET(spi0_cs0), (MODE(0) | RXACTIVE | PULLUDEN | PULLUP_EN)},
	{-1},
};

static struct module_pin_mux mii1_pin_mux[] = {
	{OFFSET(mii1_rxerr), MODE(0) | RXACTIVE},	/* MII1_RXERR */
	{OFFSET(mii1_txen), MODE(0)},			/* MII1_TXEN */
	{OFFSET(mii1_rxdv), MODE(0) | RXACTIVE},	/* MII1_RXDV */
	{OFFSET(mii1_txd3), MODE(0)},			/* MII1_TXD3 */
	{OFFSET(mii1_txd2), MODE(0)},			/* MII1_TXD2 */
	{OFFSET(mii1_txd1), MODE(0)},			/* MII1_TXD1 */
	{OFFSET(mii1_txd0), MODE(0)},			/* MII1_TXD0 */
	{OFFSET(mii1_txclk), MODE(0) | RXACTIVE},	/* MII1_TXCLK */
	{OFFSET(mii1_rxclk), MODE(0) | RXACTIVE},	/* MII1_RXCLK */
	{OFFSET(mii1_rxd3), MODE(0) | RXACTIVE},	/* MII1_RXD3 */
	{OFFSET(mii1_rxd2), MODE(0) | RXACTIVE},	/* MII1_RXD2 */
	{OFFSET(mii1_rxd1), MODE(0) | RXACTIVE},	/* MII1_RXD1 */
	{OFFSET(mii1_rxd0), MODE(0) | RXACTIVE},	/* MII1_RXD0 */
	{OFFSET(mdio_data), MODE(0) | RXACTIVE | PULLUP_EN},/* MDIO_DATA */
	{OFFSET(mdio_clk), MODE(0) | PULLUP_EN},	/* MDIO_CLK */
	{-1},
};

static struct module_pin_mux mii2_pin_mux[] = {
	{OFFSET(gpmc_a0), MODE(1)},		/* MII2_TXEN */
	{OFFSET(gpmc_a1), MODE(1) | RXACTIVE},	/* MII2_RXDV */
	{OFFSET(gpmc_a2), MODE(1)},		/* MII2_TXD3 */
	{OFFSET(gpmc_a3), MODE(1)},		/* MII2_TXD2 */
	{OFFSET(gpmc_a4), MODE(1)},		/* MII2_TXD1 */
	{OFFSET(gpmc_a5), MODE(1)},		/* MII2_TXD0 */
	{OFFSET(gpmc_a6), MODE(1) | RXACTIVE},	/* MII2_TXCLK */
	{OFFSET(gpmc_a7), MODE(1) | RXACTIVE},	/* MII2_RXCLK */
	{OFFSET(gpmc_a8), MODE(1) | RXACTIVE},	/* MII2_RXD3 */
	{OFFSET(gpmc_a9), MODE(1) | RXACTIVE},	/* MII2_RXD2 */
	{OFFSET(gpmc_a10), MODE(1) | RXACTIVE},	/* MII2_RXD1 */
	{OFFSET(gpmc_a11), MODE(1) | RXACTIVE},	/* MII2_RXD0 */
	{OFFSET(gpmc_wpn), (MODE(1) | RXACTIVE)},/* MII2_RXERR */
						/*
						 * MII2_CRS is shared with
						 * NAND_WAIT0
						 */
	{OFFSET(gpmc_be1n), (MODE(1) | RXACTIVE)},/* MII1_COL */
	{-1},
};
#ifdef CONFIG_NAND
static struct module_pin_mux nand_pin_mux[] = {
	{OFFSET(gpmc_ad0), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD0 */
	{OFFSET(gpmc_ad1), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD1 */
	{OFFSET(gpmc_ad2), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD2 */
	{OFFSET(gpmc_ad3), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD3 */
	{OFFSET(gpmc_ad4), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD4 */
	{OFFSET(gpmc_ad5), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD5 */
	{OFFSET(gpmc_ad6), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD6 */
	{OFFSET(gpmc_ad7), (MODE(0) | PULLUP_EN | RXACTIVE)},	/* NAND AD7 */
	{OFFSET(gpmc_wait0), (MODE(0) | RXACTIVE | PULLUP_EN)},	/* NAND WAIT */
	{OFFSET(gpmc_wpn), (MODE(7) | PULLUP_EN | RXACTIVE)},	/* NAND_WPN */
	{OFFSET(gpmc_csn0), (MODE(0) | PULLUDEN)},	/* NAND_CS0 */
	{OFFSET(gpmc_advn_ale), (MODE(0) | PULLUDEN)},	/* NAND_ADV_ALE */
	{OFFSET(gpmc_oen_ren), (MODE(0) | PULLUDEN)},	/* NAND_OE */
	{OFFSET(gpmc_wen), (MODE(0) | PULLUDEN)},	/* NAND_WEN */
	{OFFSET(gpmc_be0n_cle), (MODE(0) | PULLUDEN)},	/* NAND_BE_CLE */
	{-1},
};
#endif
static struct module_pin_mux gpIOs[] = {
	/* GPIO0_6  (SPI0_CS1) - 3v3_PWR_nEN (Display Power Supply) */
	{OFFSET(spi0_cs1),  (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* TIMER5   (MMC0_DAT3) - TIMER5 (Buzzer) */
	{OFFSET(mmc0_dat3), (MODE(3) | PULLUDEN | RXACTIVE)},
	/* TIMER6   (MMC0_DAT2) - PWM_BACK_3V3, later used as MODE3 for PWM */
	{OFFSET(mmc0_dat2), (MODE(7) | PULLUDEN | RXACTIVE)},
	/* GPIO2_28 (MMC0_DAT1)	 - MII_nNAND */
	{OFFSET(mmc0_dat1), (MODE(7) | PULLUDEN | RXACTIVE)},
	/* GPIO2_29 (MMC0_DAT0)	 - NAND_1n0 */
	{OFFSET(mmc0_dat0), (MODE(7) | PULLUDEN | RXACTIVE)},
	/* GPIO2_30 (MMC0_CLK) - nRESET (PHY) */
	{OFFSET(mmc0_clk), (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* GPIO3_18 (MCASP0_ACLKR) - CPLD JTAG TDI */
	{OFFSET(mcasp0_aclkr), (MODE(7) | PULLUDEN | PULLUP_EN  | RXACTIVE)},
	/* GPIO3_19 (MCASP0_FSR) - CPLD JTAG TMS */
	{OFFSET(mcasp0_fsr), (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* GPIO3_20 (MCASP0_AXR1) - CPLD JTAG TCK */
	{OFFSET(mcasp0_axr1), (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* GPIO3_21 (MCASP0_AHCLKX) - CPLD JTAG TDO */
	{OFFSET(mcasp0_ahclkx), (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* GPIO2_0  (GPMC_nCS3) - DCOK */
	{OFFSET(gpmc_csn3), (MODE(7) | PULLUDDIS | RXACTIVE) },
	/* GPIO0_29 (RMII1_REFCLK) - eMMC nRST */
	{OFFSET(rmii1_refclk), (MODE(7) | PULLUDDIS | RXACTIVE) },
	/*
	 * GPIO0_7 (PWW0 OUT)
	 * DISPLAY_ONOFF (Backlight Enable at LVDS Versions)
	 */
	{OFFSET(ecap0_in_pwm0_out), (MODE(7) | PULLUDEN | RXACTIVE)},
	/* GPIO0_19 (DMA_INTR0) - ISPLAY_MODE (CPLD) */
	{OFFSET(xdma_event_intr0), (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE)},
	/* GPIO0_20 (DMA_INTR1) - REP-Switch */
	{OFFSET(xdma_event_intr1), (MODE(7) | PULLUP_EN | RXACTIVE)},
	/* GPIO3_14 (MCASP0_ACLKX) - frei / PP709 */
	{OFFSET(mcasp0_aclkx), (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE) },
	/* GPIO3_15 (MCASP0_FSX) - PMIC_nRESET */
	{OFFSET(mcasp0_fsx),   (MODE(7) | PULLUDEN | PULLUP_EN | RXACTIVE) },
	/* GPIO3_16 (MCASP0_AXR0) - ETH1_LEDY */
	{OFFSET(mcasp0_axr0),  (MODE(7) | PULLUDDIS) },
	/* GPIO3_17 (MCASP0_AHCLKR) - ETH2_LEDY */
	{OFFSET(mcasp0_ahclkr), (MODE(7) | PULLUDDIS) },

	{-1},
};

static struct module_pin_mux lcd_pin_mux[] = {
	{OFFSET(lcd_data0), (MODE(0) | PULLUDDIS)},	/* LCD-Data(0) */
	{OFFSET(lcd_data1), (MODE(0) | PULLUDDIS)},	/* LCD-Data(1) */
	{OFFSET(lcd_data2), (MODE(0) | PULLUDDIS)},	/* LCD-Data(2) */
	{OFFSET(lcd_data3), (MODE(0) | PULLUDDIS)},	/* LCD-Data(3) */
	{OFFSET(lcd_data4), (MODE(0) | PULLUDDIS)},	/* LCD-Data(4) */
	{OFFSET(lcd_data5), (MODE(0) | PULLUDDIS)},	/* LCD-Data(5) */
	{OFFSET(lcd_data6), (MODE(0) | PULLUDDIS)},	/* LCD-Data(6) */
	{OFFSET(lcd_data7), (MODE(0) | PULLUDDIS)},	/* LCD-Data(7) */
	{OFFSET(lcd_data8), (MODE(0) | PULLUDDIS)},	/* LCD-Data(8) */
	{OFFSET(lcd_data9), (MODE(0) | PULLUDDIS)},	/* LCD-Data(9) */
	{OFFSET(lcd_data10), (MODE(0) | PULLUDDIS)},	/* LCD-Data(10) */
	{OFFSET(lcd_data11), (MODE(0) | PULLUDDIS)},	/* LCD-Data(11) */
	{OFFSET(lcd_data12), (MODE(0) | PULLUDDIS)},	/* LCD-Data(12) */
	{OFFSET(lcd_data13), (MODE(0) | PULLUDDIS)},	/* LCD-Data(13) */
	{OFFSET(lcd_data14), (MODE(0) | PULLUDDIS)},	/* LCD-Data(14) */
	{OFFSET(lcd_data15), (MODE(0) | PULLUDDIS)},	/* LCD-Data(15) */

	{OFFSET(gpmc_ad8), (MODE(1) | PULLUDDIS)},	/* LCD-Data(16) */
	{OFFSET(gpmc_ad9), (MODE(1) | PULLUDDIS)},	/* LCD-Data(17) */
	{OFFSET(gpmc_ad10), (MODE(1) | PULLUDDIS)},	/* LCD-Data(18) */
	{OFFSET(gpmc_ad11), (MODE(1) | PULLUDDIS)},	/* LCD-Data(19) */
	{OFFSET(gpmc_ad12), (MODE(1) | PULLUDDIS)},	/* LCD-Data(20) */
	{OFFSET(gpmc_ad13), (MODE(1) | PULLUDDIS)},	/* LCD-Data(21) */
	{OFFSET(gpmc_ad14), (MODE(1) | PULLUDDIS)},	/* LCD-Data(22) */
	{OFFSET(gpmc_ad15), (MODE(1) | PULLUDDIS)},	/* LCD-Data(23) */

	{OFFSET(lcd_vsync), (MODE(0) | PULLUDDIS)},	/* LCD-VSync */
	{OFFSET(lcd_hsync), (MODE(0) | PULLUDDIS)},	/* LCD-HSync */
	{OFFSET(lcd_ac_bias_en), (MODE(0) | PULLUDDIS)},/* LCD-DE */
	{OFFSET(lcd_pclk), (MODE(0) | PULLUDDIS)},	/* LCD-CLK */

	{-1},
};

void enable_uart0_pin_mux(void)
{
	configure_module_pin_mux(uart0_pin_mux);
}

void enable_i2c0_pin_mux(void)
{
	configure_module_pin_mux(i2c0_pin_mux);
}

void enable_board_pin_mux(void)
{
	configure_module_pin_mux(i2c0_pin_mux);
	configure_module_pin_mux(mii1_pin_mux);
	configure_module_pin_mux(mii2_pin_mux);
#ifdef CONFIG_NAND
	configure_module_pin_mux(nand_pin_mux);
#elif defined(CONFIG_MMC)
	configure_module_pin_mux(mmc1_pin_mux);
#endif
	configure_module_pin_mux(spi0_pin_mux);
	configure_module_pin_mux(lcd_pin_mux);
	configure_module_pin_mux(gpIOs);
}

{'repo_name': 'zhaohengbo/rt-uboot', 'stars': '102', 'repo_language': 'C', 'file_name': 'u-boot.onenand.lds', 'mime_type': 'text/x-asm', 'hash': 6629256418639258206, 'source_dataset': 'data'}


#include "StdAfx.h"
#include "UIGameTDM.h"

#include "game_cl_base.h"

#include "game_cl_teamdeathmatch.h"

#include "ui/TeamInfo.h"

#include "Common/object_broker.h"

#include "UITeamPanels.h"
#include "ui/UIMoneyIndicator.h"
#include "ui/UIRankIndicator.h"

#define MSGS_OFFS 510
#define TEAM_PANELS_TDM_XML_NAME "ui_team_panels_tdm.xml"

//--------------------------------------------------------------------
CUIGameTDM::CUIGameTDM() : m_game(NULL) {}
void CUIGameTDM::SetClGame(game_cl_GameState* g)
{
    inherited::SetClGame(g);
    m_game = smart_cast<game_cl_TeamDeathmatch*>(g);
    R_ASSERT(m_game);
}

void CUIGameTDM::Init(int stage)
{
    if (stage == 0)
    { // shared
        m_pUITeamSelectWnd = xr_new<CUISpawnWnd>();
        m_team1_icon = xr_new<CUIStatic>();
        m_team2_icon = xr_new<CUIStatic>();
        m_team1_score = xr_new<CUITextWnd>();
        m_team1_score->SetAutoDelete(true);
        m_team2_score = xr_new<CUITextWnd>();
        m_team2_score->SetAutoDelete(true);
        m_buy_msg_caption = xr_new<CUITextWnd>();
        m_buy_msg_caption->SetAutoDelete(true);

        inherited::Init(stage);
        CUIXmlInit::InitTextWnd(*MsgConfig, "mp_tdm_buy", 0, m_buy_msg_caption);
    }
    if (stage == 1)
    { // unique
        m_pTeamPanels->Init(TEAM_PANELS_TDM_XML_NAME, "team_panels_wnd");

        CUIXml uiXml, xml2;
        uiXml.Load(CONFIG_PATH, UI_PATH, UI_PATH_DEFAULT, "ui_game_tdm.xml");

        CUIXmlInit::InitWindow(uiXml, "global", 0, Window);
        CUIXmlInit::InitStatic(uiXml, "team1_icon", 0, m_team1_icon);
        CUIXmlInit::InitStatic(uiXml, "team2_icon", 0, m_team2_icon);
        CUIXmlInit::InitTextWnd(uiXml, "team1_score", 0, m_team1_score);
        CUIXmlInit::InitTextWnd(uiXml, "team2_score", 0, m_team2_score);
        CUIXmlInit::InitTextWnd(uiXml, "fraglimit", 0, m_pFragLimitIndicator);

        m_pMoneyIndicator->InitFromXML(uiXml);
        m_pRankIndicator->InitFromXml(uiXml);
    }
    if (stage == 2)
    { // after
        inherited::Init(stage);
        Window->AttachChild(m_team1_score);
        Window->AttachChild(m_team2_score);
        Window->AttachChild(m_buy_msg_caption);
    }
}

void CUIGameTDM::UnLoad()
{
    inherited::UnLoad();
    xr_delete(m_team1_icon);
    xr_delete(m_team2_icon);
    delete_data(m_pUITeamSelectWnd);
}

CUIGameTDM::~CUIGameTDM() {}
bool CUIGameTDM::IR_UIOnKeyboardPress(int dik)
{
    switch (dik)
    {
    case SDL_SCANCODE_CAPSLOCK:
    {
        if (m_game)
        {
            if (m_game->Get_ShowPlayerNamesEnabled())
                m_game->Set_ShowPlayerNames(!m_game->Get_ShowPlayerNames());
            else
                m_game->Set_ShowPlayerNames(true);
            return true;
        };
    }
    break;
    }
    return inherited::IR_UIOnKeyboardPress(dik);
}

bool CUIGameTDM::IR_UIOnKeyboardRelease(int dik)
{
    switch (dik)
    {
    case SDL_SCANCODE_CAPSLOCK:
    {
        if (m_game)
        {
            if (!m_game->Get_ShowPlayerNamesEnabled())
                m_game->Set_ShowPlayerNames(false);
            return true;
        };
    }
    break;
    }

    return inherited::IR_UIOnKeyboardRelease(dik);
}

void CUIGameTDM::OnFrame()
{
    inherited::OnFrame();
    m_team1_icon->Update();
    m_team2_icon->Update();
}

void CUIGameTDM::Render()
{
    m_team1_icon->Draw();
    m_team2_icon->Draw();
    inherited::Render();
}

void CUIGameTDM::SetScoreCaption(int t1, int t2)
{
    string32 str;
    xr_sprintf(str, "%d", t1);
    m_team1_score->SetText(str);

    xr_sprintf(str, "%d", t2);
    m_team2_score->SetText(str);

    m_pTeamPanels->SetArtefactsCount(t1, t2);
}

void CUIGameTDM::SetFraglimit(int local_frags, int fraglimit)
{
    string64 str;
    if (fraglimit)
        xr_sprintf(str, "%d", fraglimit);
    else
        xr_sprintf(str, "%s", "--");

    m_pFragLimitIndicator->SetText(str);
}

void CUIGameTDM::SetBuyMsgCaption(LPCSTR str)
{
    if (!str)
        m_buy_msg_caption->SetText("");
    else
        m_buy_msg_caption->SetTextST(str);
}

{'repo_name': 'OpenXRay/xray-16', 'stars': '1270', 'repo_language': 'C++', 'file_name': 'I_GridUser.pas', 'mime_type': 'text/plain', 'hash': -1841568632955805874, 'source_dataset': 'data'}


'use strict';

module.exports = (it, expect, collect) => {
  it('should return a new collection with the specified number of items', () => {
    const collection = collect([0, 1, 2, 3, 4, 5]);
    const chunk = collection.take(3);

    expect(chunk.all()).to.eql([0, 1, 2]);
    expect(collection.all()).to.eql([0, 1, 2, 3, 4, 5]);
  });

  it('should take from the end of the collection when passed a negative integer', () => {
    const collection = collect([0, 1, 2, 3, 4, 5]);
    const chunk = collection.take(-2);

    expect(chunk.all()).to.eql([4, 5]);
    expect(collection.all()).to.eql([0, 1, 2, 3, 4, 5]);
  });

  it('should work when the collection is based on an object', () => {
    const collection = collect({
      name: 'Sadio Mané',
      number: 19,
      club: 'Liverpool FC',
    });

    const chunk = collection.take(1);
    expect(chunk.all()).to.eql({ name: 'Sadio Mané' });

    const chunk2 = collection.take(-1);
    expect(chunk2.all()).to.eql({ club: 'Liverpool FC' });

    expect(collection.all()).to.eql({
      name: 'Sadio Mané',
      number: 19,
      club: 'Liverpool FC',
    });
  });
};

{'repo_name': 'ecrmnn/collect.js', 'stars': '5145', 'repo_language': 'JavaScript', 'file_name': 'clone.js', 'mime_type': 'text/plain', 'hash': 7160517660079509195, 'source_dataset': 'data'}


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.Person import Person
from alipay.aop.api.domain.Person import Person

class Injured(object):

    def __init__(self):
        self._cert_name = None
        self._cert_no = None
        self._cert_type = None
        self._damage_type = None
        self._injured_identity = None
        self._medical_assessor = None
        self._medical_surveyor = None
        self._mobile_no = None

    @property
    def cert_name(self):
        return self._cert_name

    @cert_name.setter
    def cert_name(self, value):
        self._cert_name = value
    @property
    def cert_no(self):
        return self._cert_no

    @cert_no.setter
    def cert_no(self, value):
        self._cert_no = value
    @property
    def cert_type(self):
        return self._cert_type

    @cert_type.setter
    def cert_type(self, value):
        self._cert_type = value
    @property
    def damage_type(self):
        return self._damage_type

    @damage_type.setter
    def damage_type(self, value):
        self._damage_type = value
    @property
    def injured_identity(self):
        return self._injured_identity

    @injured_identity.setter
    def injured_identity(self, value):
        self._injured_identity = value
    @property
    def medical_assessor(self):
        return self._medical_assessor

    @medical_assessor.setter
    def medical_assessor(self, value):
        if isinstance(value, Person):
            self._medical_assessor = value
        else:
            self._medical_assessor = Person.from_alipay_dict(value)
    @property
    def medical_surveyor(self):
        return self._medical_surveyor

    @medical_surveyor.setter
    def medical_surveyor(self, value):
        if isinstance(value, Person):
            self._medical_surveyor = value
        else:
            self._medical_surveyor = Person.from_alipay_dict(value)
    @property
    def mobile_no(self):
        return self._mobile_no

    @mobile_no.setter
    def mobile_no(self, value):
        self._mobile_no = value

    def to_alipay_dict(self):
        params = dict()
        if self.cert_name:
            if hasattr(self.cert_name, 'to_alipay_dict'):
                params['cert_name'] = self.cert_name.to_alipay_dict()
            else:
                params['cert_name'] = self.cert_name
        if self.cert_no:
            if hasattr(self.cert_no, 'to_alipay_dict'):
                params['cert_no'] = self.cert_no.to_alipay_dict()
            else:
                params['cert_no'] = self.cert_no
        if self.cert_type:
            if hasattr(self.cert_type, 'to_alipay_dict'):
                params['cert_type'] = self.cert_type.to_alipay_dict()
            else:
                params['cert_type'] = self.cert_type
        if self.damage_type:
            if hasattr(self.damage_type, 'to_alipay_dict'):
                params['damage_type'] = self.damage_type.to_alipay_dict()
            else:
                params['damage_type'] = self.damage_type
        if self.injured_identity:
            if hasattr(self.injured_identity, 'to_alipay_dict'):
                params['injured_identity'] = self.injured_identity.to_alipay_dict()
            else:
                params['injured_identity'] = self.injured_identity
        if self.medical_assessor:
            if hasattr(self.medical_assessor, 'to_alipay_dict'):
                params['medical_assessor'] = self.medical_assessor.to_alipay_dict()
            else:
                params['medical_assessor'] = self.medical_assessor
        if self.medical_surveyor:
            if hasattr(self.medical_surveyor, 'to_alipay_dict'):
                params['medical_surveyor'] = self.medical_surveyor.to_alipay_dict()
            else:
                params['medical_surveyor'] = self.medical_surveyor
        if self.mobile_no:
            if hasattr(self.mobile_no, 'to_alipay_dict'):
                params['mobile_no'] = self.mobile_no.to_alipay_dict()
            else:
                params['mobile_no'] = self.mobile_no
        return params

    @staticmethod
    def from_alipay_dict(d):
        if not d:
            return None
        o = Injured()
        if 'cert_name' in d:
            o.cert_name = d['cert_name']
        if 'cert_no' in d:
            o.cert_no = d['cert_no']
        if 'cert_type' in d:
            o.cert_type = d['cert_type']
        if 'damage_type' in d:
            o.damage_type = d['damage_type']
        if 'injured_identity' in d:
            o.injured_identity = d['injured_identity']
        if 'medical_assessor' in d:
            o.medical_assessor = d['medical_assessor']
        if 'medical_surveyor' in d:
            o.medical_surveyor = d['medical_surveyor']
        if 'mobile_no' in d:
            o.mobile_no = d['mobile_no']
        return o

{'repo_name': 'alipay/alipay-sdk-python-all', 'stars': '144', 'repo_language': 'Python', 'file_name': '__init__.py', 'mime_type': 'text/x-python', 'hash': 8430654664773892083, 'source_dataset': 'data'}


package org.support.project.knowledge.entity;

import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.entity.gen.GenAccountImagesEntity;

/**
 * アカウントの画像
 */
@DI(instance = Instance.Prototype)
public class AccountImagesEntity extends GenAccountImagesEntity {

    /** SerialVersion */
    private static final long serialVersionUID = 1L;

    /**
     * インスタンス取得 AOPに対応
     *
     * @return インスタンス
     */
    public static AccountImagesEntity get() {
        return Container.getComp(AccountImagesEntity.class);
    }

    /**
     * コンストラクタ
     */
    public AccountImagesEntity() {
        super();
    }

    /**
     * コンストラクタ
     *
     * @param imageId IMAGE_ID
     */

    public AccountImagesEntity(Long imageId) {
        super(imageId);
    }

}

{'repo_name': 'support-project/knowledge', 'stars': '569', 'repo_language': 'Java', 'file_name': 'default-logging.properties', 'mime_type': 'text/plain', 'hash': 5926793894598690385, 'source_dataset': 'data'}


{d "%w- %d %m-, %Y - %T"} - A "ipUnityModuleSoftwareError" event has occurred, from {t} device, named {m}.

" a software error occurs in a bank."

ipUnityTrapSeverity = {T ipUnityTrapSeverity 1}
ipUnityCardIndex = {I 2}
ipUnityBankIndex = {I 3}
ipUnityModuleIndex = {I 4}
ipUnityTrapInfoString = {S 5}
ipUnitySequenceNumber = {I 6}
(event [{e}])

{'repo_name': 'OpenNMS/opennms', 'stars': '506', 'repo_language': 'Java', 'file_name': 'ReportParameterBuilder.java', 'mime_type': 'text/x-java', 'hash': 3377220482568511284, 'source_dataset': 'data'}