问:
error C2143: syntax error : missing ';' before '*'
I'm not new to C++ but I am used to running a g++ compiler vs Microsoft's VS C++. I understand what this error should mean. It should mean that I'm missing a ';' on the line before or in the class Polygon. I can't seem to find anything wrong. g++ compiles the code without error. It seems like the Polygon Class isn't being loaded. Can anyone please show me what I'm missing please.I have the Application.cpp, Polygon.h, and Polygon.cpp below.

Application.cpp throwing errors but if I can fix the first others will follow:

application.cpp(121) : error C2143: syntax error : missing ';' before '*'

application.cpp(121) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

application.cpp(121) : error C2365: 'Polygon' : redefinition; previous definition was 'function'
c:\program files\microsoft sdks\windows\v6.0a\include\wingdi.h(4203) : see declaration of 'Polygon'

```#include <sstream>
#include <numeric>
#include <math.h>
#include "Polygon.h"

#define PI 3.14159265

//use standard namespace
using namespace std;

 /**************************** Window Variables ****************************/

double _window_height   = 500;
double _window_width   = 500;
double _window_position_x  = 0;
double _window_position_y  = 0;

string _window_title ("Assignment 5");

/**************************** Object Variables ****************************/

int _my_shape     = 0;
GLint _object_shine    = 40;
double _object_y_rotation  = 0;

GLfloat ambient_reflection[3] = {1.0, 1.0, 1.0};
GLfloat diffuse_reflection[3] = {1.0, 1.0, 1.0};
GLfloat specular_reflection[3] = {1.0, 1.0, 1.0};
GLfloat emissive_color[3]  = {0.0, 0.0, 0.0};
int specular_exponent   = 0;

/*************************** Lighting Variables ***************************/

//Global Light settings

GLfloat _global_ambient_light[] = {0.5, 0.5, 0.5, 1.0};
GLfloat _global_diffuse_light[] = {0.7, 0.7, 0.7, 1.0};

int rotation_int     = 0;
int rotation_angle    = 90;
int _CAMERA_DISTANCE   = 2;

//Light 0 Settings

GLfloat _z_axis_rotations[8][4] = {{(_CAMERA_DISTANCE*cos((90)*PI/180)), (_CAMERA_DISTANCE*sin((90)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((45)*PI/180)), (_CAMERA_DISTANCE*sin((45)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((0)*PI/180)), (_CAMERA_DISTANCE*sin((0)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((315)*PI/180)), (_CAMERA_DISTANCE*sin((315)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((270)*PI/180)), (_CAMERA_DISTANCE*sin((270)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((225)*PI/180)), (_CAMERA_DISTANCE*sin((225)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((180)*PI/180)), (_CAMERA_DISTANCE*sin((180)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((135)*PI/180)), (_CAMERA_DISTANCE*sin((135)*PI/180)), 0.0, 1.0}};

GLfloat _ambient_0_light[]   = {0.3f, 0.3f, 0.3f, 1.0f};
GLfloat _diffuse_0_light[]   = {0.6f, 0.6f, 0.6f, 1.0f};
GLfloat _specular_0_light[]  = {0.6f, 0.6f, 0.6f, 1.0f};
GLfloat _specular_0_property[]  = {0.6f, 0.6f, 0.6f, 1.0f};

//Light 1 Settings

// Green Spotlight with narrow angle
GLfloat _light_1_position[]  = {2.0, 0.0, -0.5, 1.0};
GLfloat _diffuse_1_light[]   = {0.2, 0.4, 0.9, 1.0};
GLfloat _spot_1_direction[]  = {-0.3, -2.0, -0.3};

//Light 2 Settings

// Red Spotlight with wide angle
GLfloat _light_2_position[]  = {0.3, -0.5, 4.0, 1.0};
GLfloat _diffuse_2_light[]   = {1.0, 0.2, 0.6, 1.0};
GLfloat _spot_2_direction[]  = {0.3, -0.5, -2.0};

GLfloat _cutoff     = 90.0;

GLfloat _AMBIENT_CONSTANT  = 0.1;
GLfloat _DIFFUSE_CONSTANT  = 0.1;
GLfloat _EMISSION_CONSTANT  = 0.05;
GLfloat _SPECULAR_CONSTANT  = 0.1;
int _SPECULAR_EXPONENT_CONSTANT = 1;
int _CUTOFF_CONSTANT   = 1;

/*************************** Shading Variables ***************************/

bool _shade_model_smooth  = true;

/**************************** File Variables *****************************/

//Error String printed if the file is not found
string _FILE_OPEN_ERROR = "Error: File could not be found or opened.";

//Error String printed if the file is not formed correctly
string _CHOICE_INVALID_ERROR = "Error: The choice you made was not one that is defined.";

/** for file reading **/
//The Array for holding all the Polygons
Polygon** _Polygons;
//the current size of the Polygon Array
int _polygons_max = 10;
//the current element for processing in the Polygon Array
int _polygons_current = 0;

/* ReadFromFile
 *
 * This method will ask a filename from the user and either return to
 * the user a file not found error or will read in from the file the
 * coordinates and place them in the coordinate array, while also setting
 * the number of lines that make up a shape.
 */
void ReadFromFile(){

 ifstream input; //  input file stream
 string filename = ""; //  used to store filename
 string line = ""; // temporary storage for reading lines at a time

 // cout << "Type a filename and press Enter: ";
 // cin >> filename;
 //cout << "Type a filename and press Enter: dodecahedron.dat" << endl;
 filename = "dodec.dat";//"dodecahedron.dat"; //should be 36 polygons

 input.open (filename.c_str(), ifstream::in);//try to open the file
 if(input.is_open()){ //check if file is open

  _Polygons = new Polygon*[_polygons_max];

  double _light_settings[12] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  int SH = 0;
  double _normals[3] = {0.0, 0.0, 0.0};

  int _coordinate_count = 0;
  int _coordinate_max = 4;
  double** _coordinates = new double*[_coordinate_max];

  while (input.good()){ //not eof or failbit

   /* Ensure space is available */
   if(_polygons_current >= _polygons_max){

    _polygons_max = _polygons_max * 2; //double max size
    Polygon** temp = new Polygon*[_polygons_max]; //create bigger array

    for (int j = 0; j <_polygons_current; j++) {
     temp[j] = _Polygons[j]; // copy values to new array.
    }

    delete [] _Polygons; //free old array memory
    _Polygons = temp; //transfer polygons
   }

   getline(input, line); //get the line from input

   string::size_type _last_pos = line.find_first_not_of(" ", 0);
   string::size_type _pos = line.find_first_of(" ", _last_pos);

   if((line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == '#'){ //comment
    //do nothing for this line
   }else if((line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == 'J' ||
     (line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == 'j'){ //polygon start

    if(_coordinate_count != 0){

     //cout << "Polygon #" << _polygons_current << endl;

     _Polygons[_polygons_current] = new Polygon(_coordinate_count, _coordinates);
     _Polygons[_polygons_current]->setAmbientReflection(_light_settings[0], _light_settings[1], _light_settings[2]);
     _Polygons[_polygons_current]->setDiffuseReflection(_light_settings[3], _light_settings[4], _light_settings[5]);
     _Polygons[_polygons_current]->setSpecularReflection(_light_settings[6], _light_settings[7], _light_settings[8]);
     _Polygons[_polygons_current]->setEmissiveColor(_light_settings[9], _light_settings[10], _light_settings[11]);
     _Polygons[_polygons_current]->setSurfaceNormals(_normals[0], _normals[1], _normals[2]);
     _Polygons[_polygons_current]->setSpecularExponent(SH);

     for(int i=0; i<_coordinate_count; i++){
      delete _coordinates[i];
     }

     _coordinate_count = 0;
     _polygons_current++;
    }

    if(line.find_first_not_of(" ", _pos) != string::npos){

     for(int i=0; i<12; i++){
      _last_pos = line.find_first_not_of(" ", _pos);
      _pos = line.find_first_of(" ", _last_pos);
      _light_settings[i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
     }

     _last_pos = line.find_first_not_of(" ", _pos);
     _pos = line.find_first_of(" ", _last_pos);
     SH = atoi(line.substr(_last_pos, _pos - _last_pos).c_str());

     for(int i=0; i<3; i++){
      _last_pos = line.find_first_not_of(" ", _pos);
      _pos = line.find_first_of(" ", _last_pos);
      _normals[i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
     }
    }

   }else{

    /* Ensure space is available */
    if(_coordinate_count >= _coordinate_max){

     _coordinate_max = _coordinate_max * 2; //double max size
     double** temp = new double*[_coordinate_max]; //create bigger array

     for (int i = 0; i < _coordinate_count; i++) {
      temp[i] = new double[3];
      temp[i][0] = _coordinates[i][0]; // copy values to new array.
      temp[i][1] = _coordinates[i][1];
      temp[i][2] = _coordinates[i][3];
     }

     delete [] _coordinates; //free old array memory
     _coordinates = temp; //transfer polygons
    }

    _coordinates[_coordinate_count] = new double[3];

    for(int i=0; i<3; i++){
     _coordinates[_coordinate_count][i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
     _last_pos = line.find_first_not_of(" ", _pos);
     _pos = line.find_first_of(" ", _last_pos);
    }
    _coordinate_count++;
   }
  }

  input.close();

 }else{

  //if the file could not be opened output to the screen the error
  cout << _FILE_OPEN_ERROR;
  exit(0);
 }
}

/* InitializeWindow
 *
 * Initializes the GLUT Library settings and creates a window for the
 * program to be displayed in.
 *
 */
void InitializeWindow(int argc, char** argv){

 glutInit(&argc,argv); /* Initialize GLUT */
 glutInitDisplayMode( GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH );/* Specify display mode */
 glutInitWindowSize(_window_width, _window_height); /* Set window size */
 glutInitWindowPosition(_window_position_x, _window_position_y); /* Set window position */
 glutCreateWindow(_window_title.c_str()); /* Create Window */
}

/* InitializeEnvironment
 *
 * Initializes the Glut environment in which the drawing is to be done.
 */
void InitializeEnvironment(){

 glClearColor (0.0, 0.0, 0.0, 0.0);
 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();

 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
 glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);

 glLoadIdentity();
 glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[0]);
 glLightfv(GL_LIGHT0, GL_SPECULAR, _specular_0_light);
 glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
 glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0);

 glLoadIdentity();
 glLightfv(GL_LIGHT1, GL_POSITION, _light_1_position);
 glLightfv(GL_LIGHT1, GL_DIFFUSE, _diffuse_1_light);
 //
 // glLoadIdentity();
 // glLightfv(GL_LIGHT2, GL_POSITION, light3_position);
 // glLightfv(GL_LIGHT2, GL_DIFFUSE, light3_diffuse_light);

 glEnable(GL_LIGHTING);
 glEnable(GL_DEPTH_TEST);

 glEnable(GL_LIGHT0);
 glEnable(GL_LIGHT1);

 if(_my_shape == 1){
  glFrontFace(GL_CW);
 }else{
  glFrontFace(GL_CCW);
 }

 glEnable(GL_CULL_FACE);

}

// In the main method we registered this method as the callback function for
// Keyboard input.  Anytime a key is pressed the ascii value of the key and
// the x and y positions of the mouse cursor within the window are passed to
// this function.
void Keyboard(unsigned char key, int x, int y) {

 switch (key) {
 case '1':
  glEnable(GL_LIGHT0);
  break;
 case '2':
  glEnable(GL_LIGHT1);
  break;
 case '+': /* Increase the cutoff angle of the positional light. */
  if(_cutoff == 90){
   _cutoff = 180;
  }else if((_cutoff-_CUTOFF_CONSTANT) > 180){
   _cutoff = 180;
  }else{
   _cutoff += _CUTOFF_CONSTANT;
  }
  glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
  break;
 case '-': /* Decrease the cutoff angle of the positional light. */
  if(_cutoff == 180){
   _cutoff = 90;
  }else if((_cutoff-_CUTOFF_CONSTANT) < 0){
   _cutoff = 0;
  }else{
   _cutoff -= _CUTOFF_CONSTANT;
  }
  glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
  break;
 case '0': /* Turn off the directional and positional light. */
  glDisable(GL_LIGHT0);
  glDisable(GL_LIGHT1);
  break;
 case 'a': /* Decrease the ambient light. */
  if(_global_ambient_light[0]>0){
   _global_ambient_light[0] = _global_ambient_light[1] = _global_ambient_light[2] -= _AMBIENT_CONSTANT;
   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
  }
  break;
 case 'A': /* Increase the ambient light. */
  if(_global_ambient_light[0]<1){
   _global_ambient_light[0] = _global_ambient_light[1] = _global_ambient_light[2] += _AMBIENT_CONSTANT;
   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
  }
  break;
 case 'd': /* Decrease the diffuse light. */
  if(_global_diffuse_light[0]>0){
   _global_diffuse_light[0] = _global_diffuse_light[1] = _global_diffuse_light[2] -= _DIFFUSE_CONSTANT;
   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);
  }
  break;
 case 'D': /* Increase the diffuse light. */
  if(_global_diffuse_light[0]<1){
   _global_diffuse_light[0] = _global_diffuse_light[1] = _global_diffuse_light[2] += _DIFFUSE_CONSTANT;
   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);
  }
  break;
 case 's': /* Decrease the specular component of the positional light. */
  if(_my_shape != 1){
   for(int i=0; i<3; i++){
    if((specular_reflection[i]-_SPECULAR_CONSTANT) < -1.0){
     specular_reflection[i] = -1.0;
    }else{
     specular_reflection[i] -= _SPECULAR_CONSTANT;
    }
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* sr = _Polygons[i]->getSpecularReflection();

    for(int j=0; j<3; j++){
     if((sr[j]-_SPECULAR_CONSTANT) < -1.0){
      sr[j] = -1.0;
     }else{
      sr[j] -= _SPECULAR_CONSTANT;
     }
    }
   }
  }
  break;
 case 'S': /* Increase the specular component of the positional light. */
  if(_my_shape != 1){
   for(int i=0; i<3; i++){
    if((specular_reflection[i]+_SPECULAR_CONSTANT) > 1.0){
     specular_reflection[i] = 1.0;
    }else{
     specular_reflection[i] += _SPECULAR_CONSTANT;
    }
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* sr = _Polygons[i]->getSpecularReflection();

    for(int j=0; j<3; j++){
     if((sr[j]+_SPECULAR_CONSTANT) > 1.0){
      sr[j] = 1.0;
     }else{
      sr[j] += _SPECULAR_CONSTANT;
     }
    }
   }
  }
  break;
 case 'h': /* Decrease the shininess of the object. */
  if(_my_shape != 1){
   if((specular_exponent-_SPECULAR_EXPONENT_CONSTANT) < 0){
    specular_exponent = 0;
   }else{
    specular_exponent-=_SPECULAR_EXPONENT_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    int sh = _Polygons[i]->getSpecularExponent();

    if((sh-_SPECULAR_EXPONENT_CONSTANT) < 0){
     _Polygons[i]->setSpecularExponent(0);
    }else{
     _Polygons[i]->setSpecularExponent(sh-_SPECULAR_EXPONENT_CONSTANT);
    }
   }
  }
  break;
 case 'H': /* Increase the shininess of the object. */
  if(_my_shape != 1){
   if((specular_exponent+_SPECULAR_EXPONENT_CONSTANT) > 128){
    specular_exponent = 128;
   }else{
    specular_exponent+=_SPECULAR_EXPONENT_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    int sh = _Polygons[i]->getSpecularExponent();

    if((sh+_SPECULAR_EXPONENT_CONSTANT) > 128){
     _Polygons[i]->setSpecularExponent(128);
    }else{
     _Polygons[i]->setSpecularExponent(sh+_SPECULAR_EXPONENT_CONSTANT);
    }
   }
  }
  break;
 case 'e': /* Decrease the emissive light of the object. */
  if(_my_shape != 1){
   if((emissive_color[0]-_EMISSION_CONSTANT) < 0){
    emissive_color[0] = 0;
   }else{
    emissive_color[0] -= _EMISSION_CONSTANT;
   }

   if((emissive_color[1]-_EMISSION_CONSTANT) < 0){
    emissive_color[1] = 0;
   }else{
    emissive_color[1] -= _EMISSION_CONSTANT;
   }

   if((emissive_color[2]-_EMISSION_CONSTANT) < 0){
    emissive_color[2] = 0;
   }else{
    emissive_color[2] -= _EMISSION_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* ep = _Polygons[i]->getEmissiveColor();

    if((ep[0]-_EMISSION_CONSTANT) < 0){
     ep[0] = 0;
    }else{
     ep[0] -= _EMISSION_CONSTANT;
    }

    if((ep[1]-_EMISSION_CONSTANT) < 0){
     ep[1] = 0;
    }else{
     ep[1] -= _EMISSION_CONSTANT;
    }

    if((ep[2]-_EMISSION_CONSTANT) < 0){
     ep[2] = 0;
    }else{
     ep[2] -= _EMISSION_CONSTANT;
    }
   }
  }
  break;
 case 'E': /* Increase the emissive light of the object. */
  if(_my_shape != 1){
   if((emissive_color[0]+_EMISSION_CONSTANT) > 1){
    emissive_color[0] = 1;
   }else{
    emissive_color[0] += _EMISSION_CONSTANT;
   }

   if((emissive_color[1]+_EMISSION_CONSTANT) > 1){
    emissive_color[1] = 1;
   }else{
    emissive_color[1] += _EMISSION_CONSTANT;
   }

   if((emissive_color[2]+_EMISSION_CONSTANT) > 1){
    emissive_color[2] = 1;
   }else{
    emissive_color[2] += _EMISSION_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* ep = _Polygons[i]->getEmissiveColor();

    if((ep[0]+_EMISSION_CONSTANT) > 1){
     ep[0] = 1;
    }else{
     ep[0] += _EMISSION_CONSTANT;
    }

    if((ep[1]+_EMISSION_CONSTANT) > 1){
     ep[1] = 1;
    }else{
     ep[1] += _EMISSION_CONSTANT;
    }

    if((ep[2]+_EMISSION_CONSTANT) > 1){
     ep[2] = 1;
    }else{
     ep[2] += _EMISSION_CONSTANT;
    }
   }
  }
  break;
 case 'p': /* Rotate the positional light about the Z-axis */
  glLoadIdentity();
  if(rotation_int == 7){
   rotation_int = 0;
  }else{
   rotation_int++;
  }
  glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[rotation_int]);
  break;
 case 'P': /* Rotate the positional light about the Z-axis */
  glLoadIdentity();
  if(rotation_int == 0){
   rotation_int = 7;
  }else{
   rotation_int--;
  }
  glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[rotation_int]);
  break;
 case 'o': /* Rotate the objects around the Y-axis : negative */
  _object_y_rotation -= 15.0;
  break;
 case 'O': /* Rotate the objects around the Y-axis : positive */
  _object_y_rotation += 15.0;
  break;
 case 'q': case 'Q': /* Quit the program */
  exit(0);
 }

 //Call redisplay to draw changes
 glutPostRedisplay();
}

void DrawFromFile(){

 glPushMatrix();

 for(int i=0; i < _polygons_current; i++){ //Over all Polygons

  double* ap = _Polygons[i]->getAmbientReflection();
  double* dp = _Polygons[i]->getDiffuseReflection();
  double* ep = _Polygons[i]->getEmissiveColor();
  double* sp = _Polygons[i]->getSpecularReflection();
  GLfloat amt[] = {ap[0], ap[1], ap[2], 1};
  GLfloat dif[] = {dp[0], dp[1], dp[2], 1};
  GLfloat emc[] = {ep[0], ep[1], ep[2], 1};
  GLfloat spc[] = {sp[0], sp[1], sp[2], 1};

  int _p_sides = _Polygons[i]->getSides();

  glMaterialfv(GL_FRONT, GL_AMBIENT, amt);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, dif);
  glMaterialfv(GL_FRONT, GL_EMISSION, emc);
  glMaterialfv(GL_FRONT, GL_SPECULAR, spc);
  glMateriali(GL_FRONT, GL_SHININESS, _Polygons[i]->getSpecularExponent());

  glBegin(GL_POLYGON);

  for(int j=0; j < _p_sides; j++){

   glNormal3dv(_Polygons[i]->getSurfaceNormals());
   glVertex3dv(_Polygons[i]->getVertex(j));
  }

  glEnd();

 }

 glPopMatrix();

}

void Display(void){

 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
 glShadeModel (GL_SMOOTH);

 //Perspective data here
 glMatrixMode(GL_PROJECTION);
 gluPerspective(45, 1, 0, 2);

 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();

 glPushMatrix();

 switch(_my_shape){

 case 1:
  glTranslated(0, 0, -1);
  glRotated(_object_y_rotation, 0, 1, 0);
  DrawFromFile();
  break;
 case 2:
  glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
  glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
  glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
  glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
  glRotated(_object_y_rotation, 0, 1, 0);
  glutSolidTeapot(0.8);
  break;
 case 3:
  glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
  glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
  glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
  glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
  glRotated(_object_y_rotation, 0, 1, 0);
  glutSolidIcosahedron();
  break;
 case 4:
  glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
  glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
  glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
  glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
  glRotated(_object_y_rotation, 0, 1, 0);
  glutSolidTorus(0.3, 0.8, 10, 30);
  break;
 default:
  cout << _CHOICE_INVALID_ERROR << endl;
  exit(1);
  break;
 }

 glPopMatrix();

 glFlush();

}

int PollUser(){

 int choice = 0;

 cout << "Use the menu below to pick a shape to draw:" << endl << endl;
 cout << "1: Dodecahedron (Drawn from file)" << endl;
 cout << "2: Teapot (GLUT drawn)" << endl;
 cout << "3: Icosahedron (GLUT drawn)" << endl;
 cout << "4: Torus (GLUT drawn)" << endl;
 cout << endl << "Enter choice: ";
 cin >> choice;

 return choice;
}

int main(int argc, char** argv){

 _my_shape = PollUser();
 InitializeWindow(argc, argv); /* Initialize window */
 InitializeEnvironment(); /* Initialize other parameter */
 glutDisplayFunc(Display); /* Redisplay callback event handling */
 glutKeyboardFunc(Keyboard); /* Keyboard callback function */

 ReadFromFile(); /* Read from file */

 glutMainLoop(); /* Start glut functions */

 return 0;
}
```

<p>Polygon.h</p>

```#ifndef POLYGON_H_
#define POLYGON_H_

#include <iostream>
#include <cstdlib>
#include <new>

class Polygon {
public:
 Polygon();
 Polygon(int, double**);
 virtual ~Polygon();
 void *operator new(size_t size);
 void operator delete(void *p);
 void *operator new[](size_t size);
 void operator delete[](void *p);
 double* getVertex(int);
 void setSpecularExponent(int);
 void setSurfaceNormals(double,double,double);
 void setAmbientReflection(double,double,double);
 void setDiffuseReflection(double,double,double);
 void setSpecularReflection(double,double,double);
 void setEmissiveColor(double,double,double);
 int getSides(void);
 int getSpecularExponent(void);
 double* getSurfaceNormals(void);
 double* getAmbientReflection(void);
 double* getDiffuseReflection(void);
 double* getSpecularReflection(void);
 double* getEmissiveColor(void);

private:
 double** verticies;
 double surface_normals[3];
 double ambient_reflection[3];
 double diffuse_reflection[3];
 double specular_reflection[3];
 double emissive_color[3];
 int sides;
 int spec_ex;
};

#endif /* POLYGON_H_ */
```

<p>Polygon.cpp</p>

```#include "Polygon.h"

using namespace std;

Polygon::Polygon(){

 sides = 0;
}

Polygon::Polygon(int numberOfSides, double** polyVerticies){

 sides = numberOfSides;
 verticies = new double*[numberOfSides];

 for(int n=0; n<numberOfSides; n++){
  verticies[n] = new double[3];
  verticies[n][0] = polyVerticies[n][0];
  verticies[n][1] = polyVerticies[n][1];
  verticies[n][2] = polyVerticies[n][2];
 }
}

void *Polygon::operator new(size_t size){

 void *p;

 p =  malloc(size);
 if(!p) {
  bad_alloc ba;
  throw ba;
 }
 return p;
}

void Polygon::operator delete(void *p){

 free(p);
}

// new overloaded for loc arrays.
void *Polygon::operator new[](size_t size){

 void *p;

 p =  malloc(size);
 if(!p) {
  bad_alloc ba;
  throw ba;
 }
 return p;
}

void Polygon::operator delete[](void *p){

 free(p);
}

void Polygon::setSpecularExponent(int exponent){

 spec_ex = exponent;
}

void Polygon::setSurfaceNormals(double x, double y, double z){

 surface_normals[0] = x;
 surface_normals[1] = y;
 surface_normals[2] = z;
}

void Polygon::setAmbientReflection(double r, double g, double b){

 ambient_reflection[0] = r;
 ambient_reflection[1] = g;
 ambient_reflection[2] = b;
}

void Polygon::setDiffuseReflection(double r, double g, double b){

 diffuse_reflection[0] = r;
 diffuse_reflection[1] = g;
 diffuse_reflection[2] = b;
}

void Polygon::setSpecularReflection(double r, double g, double b){

 specular_reflection[0] = r;
 specular_reflection[1] = g;
 specular_reflection[2] = b;
}

void Polygon::setEmissiveColor(double r, double g, double b){

 emissive_color[0] = r;
 emissive_color[1] = g;
 emissive_color[2] = b;
}

double* Polygon::getVertex(int index){

 if(index < sides){

  double* _temp = new double[3];

  _temp[0] = verticies[index][0];
  _temp[1] = verticies[index][1];
  _temp[2] = verticies[index][2];

  return _temp;
 }

 return new double;
}

int Polygon::getSides(){

 return sides;
}

int Polygon::getSpecularExponent(){

 return spec_ex;
}

double* Polygon::getSurfaceNormals(){

 return surface_normals;
}

double* Polygon::getAmbientReflection(){

 return ambient_reflection;
}

double* Polygon::getDiffuseReflection(){

 return diffuse_reflection;
}

double* Polygon::getSpecularReflection(){

 return specular_reflection;
}

double* Polygon::getEmissiveColor(){

 return emissive_color;
}

Polygon::~Polygon() {
 delete[] verticies;
}
```

Thanks for any help anyone can offer.

答:
I have a feeling the issue at hand here is the last of the errors you listed.  Namely:

application.cpp(121) : error C2365: 'Polygon' : redefinition; previous definition was 'function' c:\program files\microsoft sdks\windows\v6.0a\include\wingdi.h(4203) : see declaration of 'Polygon'

Try putting your Polygon class in a separate namespace to prevent the name clash.  That should clear it up.  And reference it by the fully scoped name in application.cpp.

Body:
I'm not new to C++ but I am used to running a g++ compiler vs Microsoft's VS C++. I understand what this error should mean. It should mean that I'm missing a ';' on the line before or in the class Polygon. I can't seem to find anything wrong. g++ compiles the code without error. It seems like the Polygon Class isn't being loaded. Can anyone please show me what I'm missing please.I have the Application.cpp, Polygon.h, and Polygon.cpp below.

Application.cpp throwing errors but if I can fix the first others will follow:

application.cpp(121) : error C2143: syntax error : missing ';' before '*'

application.cpp(121) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

application.cpp(121) : error C2365: 'Polygon' : redefinition; previous definition was 'function'
c:\program files\microsoft sdks\windows\v6.0a\include\wingdi.h(4203) : see declaration of 'Polygon'

#include <sstream>
#include <numeric>
#include <math.h>
#include "Polygon.h"

#define PI 3.14159265

//use standard namespace
using namespace std;

 /**************************** Window Variables ****************************/

double _window_height   = 500;
double _window_width   = 500;
double _window_position_x  = 0;
double _window_position_y  = 0;

string _window_title ("Assignment 5");

/**************************** Object Variables ****************************/

int _my_shape     = 0;
GLint _object_shine    = 40;
double _object_y_rotation  = 0;

GLfloat ambient_reflection[3] = {1.0, 1.0, 1.0};
GLfloat diffuse_reflection[3] = {1.0, 1.0, 1.0};
GLfloat specular_reflection[3] = {1.0, 1.0, 1.0};
GLfloat emissive_color[3]  = {0.0, 0.0, 0.0};
int specular_exponent   = 0;

/*************************** Lighting Variables ***************************/

//Global Light settings

GLfloat _global_ambient_light[] = {0.5, 0.5, 0.5, 1.0};
GLfloat _global_diffuse_light[] = {0.7, 0.7, 0.7, 1.0};

int rotation_int     = 0;
int rotation_angle    = 90;
int _CAMERA_DISTANCE   = 2;

//Light 0 Settings

GLfloat _z_axis_rotations[8][4] = {{(_CAMERA_DISTANCE*cos((90)*PI/180)), (_CAMERA_DISTANCE*sin((90)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((45)*PI/180)), (_CAMERA_DISTANCE*sin((45)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((0)*PI/180)), (_CAMERA_DISTANCE*sin((0)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((315)*PI/180)), (_CAMERA_DISTANCE*sin((315)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((270)*PI/180)), (_CAMERA_DISTANCE*sin((270)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((225)*PI/180)), (_CAMERA_DISTANCE*sin((225)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((180)*PI/180)), (_CAMERA_DISTANCE*sin((180)*PI/180)), 0.0, 1.0},
         {(_CAMERA_DISTANCE*cos((135)*PI/180)), (_CAMERA_DISTANCE*sin((135)*PI/180)), 0.0, 1.0}};

GLfloat _ambient_0_light[]   = {0.3f, 0.3f, 0.3f, 1.0f};
GLfloat _diffuse_0_light[]   = {0.6f, 0.6f, 0.6f, 1.0f};
GLfloat _specular_0_light[]  = {0.6f, 0.6f, 0.6f, 1.0f};
GLfloat _specular_0_property[]  = {0.6f, 0.6f, 0.6f, 1.0f};

//Light 1 Settings

// Green Spotlight with narrow angle
GLfloat _light_1_position[]  = {2.0, 0.0, -0.5, 1.0};
GLfloat _diffuse_1_light[]   = {0.2, 0.4, 0.9, 1.0};
GLfloat _spot_1_direction[]  = {-0.3, -2.0, -0.3};

//Light 2 Settings

// Red Spotlight with wide angle
GLfloat _light_2_position[]  = {0.3, -0.5, 4.0, 1.0};
GLfloat _diffuse_2_light[]   = {1.0, 0.2, 0.6, 1.0};
GLfloat _spot_2_direction[]  = {0.3, -0.5, -2.0};

GLfloat _cutoff     = 90.0;

GLfloat _AMBIENT_CONSTANT  = 0.1;
GLfloat _DIFFUSE_CONSTANT  = 0.1;
GLfloat _EMISSION_CONSTANT  = 0.05;
GLfloat _SPECULAR_CONSTANT  = 0.1;
int _SPECULAR_EXPONENT_CONSTANT = 1;
int _CUTOFF_CONSTANT   = 1;

/*************************** Shading Variables ***************************/

bool _shade_model_smooth  = true;

/**************************** File Variables *****************************/

//Error String printed if the file is not found
string _FILE_OPEN_ERROR = "Error: File could not be found or opened.";

//Error String printed if the file is not formed correctly
string _CHOICE_INVALID_ERROR = "Error: The choice you made was not one that is defined.";

/** for file reading **/
//The Array for holding all the Polygons
Polygon** _Polygons;
//the current size of the Polygon Array
int _polygons_max = 10;
//the current element for processing in the Polygon Array
int _polygons_current = 0;

/* ReadFromFile
 *
 * This method will ask a filename from the user and either return to
 * the user a file not found error or will read in from the file the
 * coordinates and place them in the coordinate array, while also setting
 * the number of lines that make up a shape.
 */
void ReadFromFile(){

 ifstream input; //  input file stream
 string filename = ""; //  used to store filename
 string line = ""; // temporary storage for reading lines at a time

 // cout << "Type a filename and press Enter: ";
 // cin >> filename;
 //cout << "Type a filename and press Enter: dodecahedron.dat" << endl;
 filename = "dodec.dat";//"dodecahedron.dat"; //should be 36 polygons

 input.open (filename.c_str(), ifstream::in);//try to open the file
 if(input.is_open()){ //check if file is open

  _Polygons = new Polygon*[_polygons_max];

  double _light_settings[12] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  int SH = 0;
  double _normals[3] = {0.0, 0.0, 0.0};

  int _coordinate_count = 0;
  int _coordinate_max = 4;
  double** _coordinates = new double*[_coordinate_max];

  while (input.good()){ //not eof or failbit

   /* Ensure space is available */
   if(_polygons_current >= _polygons_max){

    _polygons_max = _polygons_max * 2; //double max size
    Polygon** temp = new Polygon*[_polygons_max]; //create bigger array

    for (int j = 0; j <_polygons_current; j++) {
     temp[j] = _Polygons[j]; // copy values to new array.
    }

    delete [] _Polygons; //free old array memory
    _Polygons = temp; //transfer polygons
   }

   getline(input, line); //get the line from input

   string::size_type _last_pos = line.find_first_not_of(" ", 0);
   string::size_type _pos = line.find_first_of(" ", _last_pos);

   if((line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == '#'){ //comment
    //do nothing for this line
   }else if((line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == 'J' ||
     (line.substr(_last_pos, _pos - _last_pos)).c_str()[0] == 'j'){ //polygon start

    if(_coordinate_count != 0){

     //cout << "Polygon #" << _polygons_current << endl;

     _Polygons[_polygons_current] = new Polygon(_coordinate_count, _coordinates);
     _Polygons[_polygons_current]->setAmbientReflection(_light_settings[0], _light_settings[1], _light_settings[2]);
     _Polygons[_polygons_current]->setDiffuseReflection(_light_settings[3], _light_settings[4], _light_settings[5]);
     _Polygons[_polygons_current]->setSpecularReflection(_light_settings[6], _light_settings[7], _light_settings[8]);
     _Polygons[_polygons_current]->setEmissiveColor(_light_settings[9], _light_settings[10], _light_settings[11]);
     _Polygons[_polygons_current]->setSurfaceNormals(_normals[0], _normals[1], _normals[2]);
     _Polygons[_polygons_current]->setSpecularExponent(SH);

     for(int i=0; i<_coordinate_count; i++){
      delete _coordinates[i];
     }

     _coordinate_count = 0;
     _polygons_current++;
    }

    if(line.find_first_not_of(" ", _pos) != string::npos){

     for(int i=0; i<12; i++){
      _last_pos = line.find_first_not_of(" ", _pos);
      _pos = line.find_first_of(" ", _last_pos);
      _light_settings[i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
     }

     _last_pos = line.find_first_not_of(" ", _pos);
     _pos = line.find_first_of(" ", _last_pos);
     SH = atoi(line.substr(_last_pos, _pos - _last_pos).c_str());

     for(int i=0; i<3; i++){
      _last_pos = line.find_first_not_of(" ", _pos);
      _pos = line.find_first_of(" ", _last_pos);
      _normals[i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
     }
    }

   }else{

    /* Ensure space is available */
    if(_coordinate_count >= _coordinate_max){

     _coordinate_max = _coordinate_max * 2; //double max size
     double** temp = new double*[_coordinate_max]; //create bigger array

     for (int i = 0; i < _coordinate_count; i++) {
      temp[i] = new double[3];
      temp[i][0] = _coordinates[i][0]; // copy values to new array.
      temp[i][1] = _coordinates[i][1];
      temp[i][2] = _coordinates[i][3];
     }

     delete [] _coordinates; //free old array memory
     _coordinates = temp; //transfer polygons
    }

    _coordinates[_coordinate_count] = new double[3];

    for(int i=0; i<3; i++){
     _coordinates[_coordinate_count][i] = atof(line.substr(_last_pos, _pos - _last_pos).c_str());
     _last_pos = line.find_first_not_of(" ", _pos);
     _pos = line.find_first_of(" ", _last_pos);
    }
    _coordinate_count++;
   }
  }

  input.close();

 }else{

  //if the file could not be opened output to the screen the error
  cout << _FILE_OPEN_ERROR;
  exit(0);
 }
}

/* InitializeWindow
 *
 * Initializes the GLUT Library settings and creates a window for the
 * program to be displayed in.
 *
 */
void InitializeWindow(int argc, char** argv){

 glutInit(&argc,argv); /* Initialize GLUT */
 glutInitDisplayMode( GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH );/* Specify display mode */
 glutInitWindowSize(_window_width, _window_height); /* Set window size */
 glutInitWindowPosition(_window_position_x, _window_position_y); /* Set window position */
 glutCreateWindow(_window_title.c_str()); /* Create Window */
}

/* InitializeEnvironment
 *
 * Initializes the Glut environment in which the drawing is to be done.
 */
void InitializeEnvironment(){

 glClearColor (0.0, 0.0, 0.0, 0.0);
 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();

 glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
 glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);

 glLoadIdentity();
 glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[0]);
 glLightfv(GL_LIGHT0, GL_SPECULAR, _specular_0_light);
 glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
 glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0);

 glLoadIdentity();
 glLightfv(GL_LIGHT1, GL_POSITION, _light_1_position);
 glLightfv(GL_LIGHT1, GL_DIFFUSE, _diffuse_1_light);
 //
 // glLoadIdentity();
 // glLightfv(GL_LIGHT2, GL_POSITION, light3_position);
 // glLightfv(GL_LIGHT2, GL_DIFFUSE, light3_diffuse_light);

 glEnable(GL_LIGHTING);
 glEnable(GL_DEPTH_TEST);

 glEnable(GL_LIGHT0);
 glEnable(GL_LIGHT1);

 if(_my_shape == 1){
  glFrontFace(GL_CW);
 }else{
  glFrontFace(GL_CCW);
 }

 glEnable(GL_CULL_FACE);

}

// In the main method we registered this method as the callback function for
// Keyboard input.  Anytime a key is pressed the ascii value of the key and
// the x and y positions of the mouse cursor within the window are passed to
// this function.
void Keyboard(unsigned char key, int x, int y) {

 switch (key) {
 case '1':
  glEnable(GL_LIGHT0);
  break;
 case '2':
  glEnable(GL_LIGHT1);
  break;
 case '+': /* Increase the cutoff angle of the positional light. */
  if(_cutoff == 90){
   _cutoff = 180;
  }else if((_cutoff-_CUTOFF_CONSTANT) > 180){
   _cutoff = 180;
  }else{
   _cutoff += _CUTOFF_CONSTANT;
  }
  glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
  break;
 case '-': /* Decrease the cutoff angle of the positional light. */
  if(_cutoff == 180){
   _cutoff = 90;
  }else if((_cutoff-_CUTOFF_CONSTANT) < 0){
   _cutoff = 0;
  }else{
   _cutoff -= _CUTOFF_CONSTANT;
  }
  glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, _cutoff);
  break;
 case '0': /* Turn off the directional and positional light. */
  glDisable(GL_LIGHT0);
  glDisable(GL_LIGHT1);
  break;
 case 'a': /* Decrease the ambient light. */
  if(_global_ambient_light[0]>0){
   _global_ambient_light[0] = _global_ambient_light[1] = _global_ambient_light[2] -= _AMBIENT_CONSTANT;
   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
  }
  break;
 case 'A': /* Increase the ambient light. */
  if(_global_ambient_light[0]<1){
   _global_ambient_light[0] = _global_ambient_light[1] = _global_ambient_light[2] += _AMBIENT_CONSTANT;
   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, _global_ambient_light);
  }
  break;
 case 'd': /* Decrease the diffuse light. */
  if(_global_diffuse_light[0]>0){
   _global_diffuse_light[0] = _global_diffuse_light[1] = _global_diffuse_light[2] -= _DIFFUSE_CONSTANT;
   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);
  }
  break;
 case 'D': /* Increase the diffuse light. */
  if(_global_diffuse_light[0]<1){
   _global_diffuse_light[0] = _global_diffuse_light[1] = _global_diffuse_light[2] += _DIFFUSE_CONSTANT;
   glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, _global_diffuse_light);
  }
  break;
 case 's': /* Decrease the specular component of the positional light. */
  if(_my_shape != 1){
   for(int i=0; i<3; i++){
    if((specular_reflection[i]-_SPECULAR_CONSTANT) < -1.0){
     specular_reflection[i] = -1.0;
    }else{
     specular_reflection[i] -= _SPECULAR_CONSTANT;
    }
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* sr = _Polygons[i]->getSpecularReflection();

    for(int j=0; j<3; j++){
     if((sr[j]-_SPECULAR_CONSTANT) < -1.0){
      sr[j] = -1.0;
     }else{
      sr[j] -= _SPECULAR_CONSTANT;
     }
    }
   }
  }
  break;
 case 'S': /* Increase the specular component of the positional light. */
  if(_my_shape != 1){
   for(int i=0; i<3; i++){
    if((specular_reflection[i]+_SPECULAR_CONSTANT) > 1.0){
     specular_reflection[i] = 1.0;
    }else{
     specular_reflection[i] += _SPECULAR_CONSTANT;
    }
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* sr = _Polygons[i]->getSpecularReflection();

    for(int j=0; j<3; j++){
     if((sr[j]+_SPECULAR_CONSTANT) > 1.0){
      sr[j] = 1.0;
     }else{
      sr[j] += _SPECULAR_CONSTANT;
     }
    }
   }
  }
  break;
 case 'h': /* Decrease the shininess of the object. */
  if(_my_shape != 1){
   if((specular_exponent-_SPECULAR_EXPONENT_CONSTANT) < 0){
    specular_exponent = 0;
   }else{
    specular_exponent-=_SPECULAR_EXPONENT_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    int sh = _Polygons[i]->getSpecularExponent();

    if((sh-_SPECULAR_EXPONENT_CONSTANT) < 0){
     _Polygons[i]->setSpecularExponent(0);
    }else{
     _Polygons[i]->setSpecularExponent(sh-_SPECULAR_EXPONENT_CONSTANT);
    }
   }
  }
  break;
 case 'H': /* Increase the shininess of the object. */
  if(_my_shape != 1){
   if((specular_exponent+_SPECULAR_EXPONENT_CONSTANT) > 128){
    specular_exponent = 128;
   }else{
    specular_exponent+=_SPECULAR_EXPONENT_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    int sh = _Polygons[i]->getSpecularExponent();

    if((sh+_SPECULAR_EXPONENT_CONSTANT) > 128){
     _Polygons[i]->setSpecularExponent(128);
    }else{
     _Polygons[i]->setSpecularExponent(sh+_SPECULAR_EXPONENT_CONSTANT);
    }
   }
  }
  break;
 case 'e': /* Decrease the emissive light of the object. */
  if(_my_shape != 1){
   if((emissive_color[0]-_EMISSION_CONSTANT) < 0){
    emissive_color[0] = 0;
   }else{
    emissive_color[0] -= _EMISSION_CONSTANT;
   }

   if((emissive_color[1]-_EMISSION_CONSTANT) < 0){
    emissive_color[1] = 0;
   }else{
    emissive_color[1] -= _EMISSION_CONSTANT;
   }

   if((emissive_color[2]-_EMISSION_CONSTANT) < 0){
    emissive_color[2] = 0;
   }else{
    emissive_color[2] -= _EMISSION_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* ep = _Polygons[i]->getEmissiveColor();

    if((ep[0]-_EMISSION_CONSTANT) < 0){
     ep[0] = 0;
    }else{
     ep[0] -= _EMISSION_CONSTANT;
    }

    if((ep[1]-_EMISSION_CONSTANT) < 0){
     ep[1] = 0;
    }else{
     ep[1] -= _EMISSION_CONSTANT;
    }

    if((ep[2]-_EMISSION_CONSTANT) < 0){
     ep[2] = 0;
    }else{
     ep[2] -= _EMISSION_CONSTANT;
    }
   }
  }
  break;
 case 'E': /* Increase the emissive light of the object. */
  if(_my_shape != 1){
   if((emissive_color[0]+_EMISSION_CONSTANT) > 1){
    emissive_color[0] = 1;
   }else{
    emissive_color[0] += _EMISSION_CONSTANT;
   }

   if((emissive_color[1]+_EMISSION_CONSTANT) > 1){
    emissive_color[1] = 1;
   }else{
    emissive_color[1] += _EMISSION_CONSTANT;
   }

   if((emissive_color[2]+_EMISSION_CONSTANT) > 1){
    emissive_color[2] = 1;
   }else{
    emissive_color[2] += _EMISSION_CONSTANT;
   }
  }else{
   for(int i=0; i < _polygons_current; i++){ //Over all Polygons

    double* ep = _Polygons[i]->getEmissiveColor();

    if((ep[0]+_EMISSION_CONSTANT) > 1){
     ep[0] = 1;
    }else{
     ep[0] += _EMISSION_CONSTANT;
    }

    if((ep[1]+_EMISSION_CONSTANT) > 1){
     ep[1] = 1;
    }else{
     ep[1] += _EMISSION_CONSTANT;
    }

    if((ep[2]+_EMISSION_CONSTANT) > 1){
     ep[2] = 1;
    }else{
     ep[2] += _EMISSION_CONSTANT;
    }
   }
  }
  break;
 case 'p': /* Rotate the positional light about the Z-axis */
  glLoadIdentity();
  if(rotation_int == 7){
   rotation_int = 0;
  }else{
   rotation_int++;
  }
  glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[rotation_int]);
  break;
 case 'P': /* Rotate the positional light about the Z-axis */
  glLoadIdentity();
  if(rotation_int == 0){
   rotation_int = 7;
  }else{
   rotation_int--;
  }
  glLightfv(GL_LIGHT0, GL_POSITION, _z_axis_rotations[rotation_int]);
  break;
 case 'o': /* Rotate the objects around the Y-axis : negative */
  _object_y_rotation -= 15.0;
  break;
 case 'O': /* Rotate the objects around the Y-axis : positive */
  _object_y_rotation += 15.0;
  break;
 case 'q': case 'Q': /* Quit the program */
  exit(0);
 }

 //Call redisplay to draw changes
 glutPostRedisplay();
}

void DrawFromFile(){

 glPushMatrix();

 for(int i=0; i < _polygons_current; i++){ //Over all Polygons

  double* ap = _Polygons[i]->getAmbientReflection();
  double* dp = _Polygons[i]->getDiffuseReflection();
  double* ep = _Polygons[i]->getEmissiveColor();
  double* sp = _Polygons[i]->getSpecularReflection();
  GLfloat amt[] = {ap[0], ap[1], ap[2], 1};
  GLfloat dif[] = {dp[0], dp[1], dp[2], 1};
  GLfloat emc[] = {ep[0], ep[1], ep[2], 1};
  GLfloat spc[] = {sp[0], sp[1], sp[2], 1};

  int _p_sides = _Polygons[i]->getSides();

  glMaterialfv(GL_FRONT, GL_AMBIENT, amt);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, dif);
  glMaterialfv(GL_FRONT, GL_EMISSION, emc);
  glMaterialfv(GL_FRONT, GL_SPECULAR, spc);
  glMateriali(GL_FRONT, GL_SHININESS, _Polygons[i]->getSpecularExponent());

  glBegin(GL_POLYGON);

  for(int j=0; j < _p_sides; j++){

   glNormal3dv(_Polygons[i]->getSurfaceNormals());
   glVertex3dv(_Polygons[i]->getVertex(j));
  }

  glEnd();

 }

 glPopMatrix();

}

void Display(void){

 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
 glShadeModel (GL_SMOOTH);

 //Perspective data here
 glMatrixMode(GL_PROJECTION);
 gluPerspective(45, 1, 0, 2);

 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();

 glPushMatrix();

 switch(_my_shape){

 case 1:
  glTranslated(0, 0, -1);
  glRotated(_object_y_rotation, 0, 1, 0);
  DrawFromFile();
  break;
 case 2:
  glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
  glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
  glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
  glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
  glRotated(_object_y_rotation, 0, 1, 0);
  glutSolidTeapot(0.8);
  break;
 case 3:
  glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
  glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
  glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
  glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
  glRotated(_object_y_rotation, 0, 1, 0);
  glutSolidIcosahedron();
  break;
 case 4:
  glMaterialfv(GL_FRONT, GL_AMBIENT, ambient_reflection);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_reflection);
  glMaterialfv(GL_FRONT, GL_EMISSION, emissive_color);
  glMaterialfv(GL_FRONT, GL_SPECULAR, specular_reflection);
  glMateriali(GL_FRONT, GL_SHININESS, specular_exponent);
  glRotated(_object_y_rotation, 0, 1, 0);
  glutSolidTorus(0.3, 0.8, 10, 30);
  break;
 default:
  cout << _CHOICE_INVALID_ERROR << endl;
  exit(1);
  break;
 }

 glPopMatrix();

 glFlush();

}

int PollUser(){

 int choice = 0;

 cout << "Use the menu below to pick a shape to draw:" << endl << endl;
 cout << "1: Dodecahedron (Drawn from file)" << endl;
 cout << "2: Teapot (GLUT drawn)" << endl;
 cout << "3: Icosahedron (GLUT drawn)" << endl;
 cout << "4: Torus (GLUT drawn)" << endl;
 cout << endl << "Enter choice: ";
 cin >> choice;

 return choice;
}

int main(int argc, char** argv){

 _my_shape = PollUser();
 InitializeWindow(argc, argv); /* Initialize window */
 InitializeEnvironment(); /* Initialize other parameter */
 glutDisplayFunc(Display); /* Redisplay callback event handling */
 glutKeyboardFunc(Keyboard); /* Keyboard callback function */

 ReadFromFile(); /* Read from file */

 glutMainLoop(); /* Start glut functions */

 return 0;
}

Polygon.h

#ifndef POLYGON_H_
#define POLYGON_H_

#include <iostream>
#include <cstdlib>
#include <new>

class Polygon {
public:
 Polygon();
 Polygon(int, double**);
 virtual ~Polygon();
 void *operator new(size_t size);
 void operator delete(void *p);
 void *operator new[](size_t size);
 void operator delete[](void *p);
 double* getVertex(int);
 void setSpecularExponent(int);
 void setSurfaceNormals(double,double,double);
 void setAmbientReflection(double,double,double);
 void setDiffuseReflection(double,double,double);
 void setSpecularReflection(double,double,double);
 void setEmissiveColor(double,double,double);
 int getSides(void);
 int getSpecularExponent(void);
 double* getSurfaceNormals(void);
 double* getAmbientReflection(void);
 double* getDiffuseReflection(void);
 double* getSpecularReflection(void);
 double* getEmissiveColor(void);

private:
 double** verticies;
 double surface_normals[3];
 double ambient_reflection[3];
 double diffuse_reflection[3];
 double specular_reflection[3];
 double emissive_color[3];
 int sides;
 int spec_ex;
};

#endif /* POLYGON_H_ */

Polygon.cpp

#include "Polygon.h"

using namespace std;

Polygon::Polygon(){

 sides = 0;
}

Polygon::Polygon(int numberOfSides, double** polyVerticies){

 sides = numberOfSides;
 verticies = new double*[numberOfSides];

 for(int n=0; n<numberOfSides; n++){
  verticies[n] = new double[3];
  verticies[n][0] = polyVerticies[n][0];
  verticies[n][1] = polyVerticies[n][1];
  verticies[n][2] = polyVerticies[n][2];
 }
}

void *Polygon::operator new(size_t size){

 void *p;

 p =  malloc(size);
 if(!p) {
  bad_alloc ba;
  throw ba;
 }
 return p;
}

void Polygon::operator delete(void *p){

 free(p);
}

// new overloaded for loc arrays.
void *Polygon::operator new[](size_t size){

 void *p;

 p =  malloc(size);
 if(!p) {
  bad_alloc ba;
  throw ba;
 }
 return p;
}

void Polygon::operator delete[](void *p){

 free(p);
}

void Polygon::setSpecularExponent(int exponent){

 spec_ex = exponent;
}

void Polygon::setSurfaceNormals(double x, double y, double z){

 surface_normals[0] = x;
 surface_normals[1] = y;
 surface_normals[2] = z;
}

void Polygon::setAmbientReflection(double r, double g, double b){

 ambient_reflection[0] = r;
 ambient_reflection[1] = g;
 ambient_reflection[2] = b;
}

void Polygon::setDiffuseReflection(double r, double g, double b){

 diffuse_reflection[0] = r;
 diffuse_reflection[1] = g;
 diffuse_reflection[2] = b;
}

void Polygon::setSpecularReflection(double r, double g, double b){

 specular_reflection[0] = r;
 specular_reflection[1] = g;
 specular_reflection[2] = b;
}

void Polygon::setEmissiveColor(double r, double g, double b){

 emissive_color[0] = r;
 emissive_color[1] = g;
 emissive_color[2] = b;
}

double* Polygon::getVertex(int index){

 if(index < sides){

  double* _temp = new double[3];

  _temp[0] = verticies[index][0];
  _temp[1] = verticies[index][1];
  _temp[2] = verticies[index][2];

  return _temp;
 }

 return new double;
}

int Polygon::getSides(){

 return sides;
}

int Polygon::getSpecularExponent(){

 return spec_ex;
}

double* Polygon::getSurfaceNormals(){

 return surface_normals;
}

double* Polygon::getAmbientReflection(){

 return ambient_reflection;
}

double* Polygon::getDiffuseReflection(){

 return diffuse_reflection;
}

double* Polygon::getSpecularReflection(){

 return specular_reflection;
}

double* Polygon::getEmissiveColor(){

 return emissive_color;
}

Polygon::~Polygon() {
 delete[] verticies;
}

Thanks for any help anyone can offer.


来源: stackexchange

问:
function "onclick" is called even though it is not set in button
I have following code. I haven't been able able to figure out why click event occurs even though I haven't set the function to onclick attribute of button.

var x = 0;
var onclick = function() {
  console.log("x = " + ++x);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="">Click</button></code>```

答:
As @dfsq mentioned, you're creating window.onclick when you do var onclick=. On a similar note:

var onerror = function() {
  console.log("ERROR HAPPENED!");
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" onclick="ThisFunctionIsNotDefined()">Click</button></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have following code. I haven't been able able to figure out why click event occurs even though I haven't set the function to onclick attribute of button.

var x = 0;
var onclick = function() {
  console.log("x = " + ++x);
};

<button type="button" onclick="">Click</button>

Body:
As @dfsq mentioned, you're creating window.onclick when you do var onclick=. On a similar note:

var onerror = function() {
  console.log("ERROR HAPPENED!");
};

<button type="button" onclick="ThisFunctionIsNotDefined()">Click</button>


问:
In Java, what is the order of initialization for those statements after main method
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

```<code>public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}
</code>```

The result is:

```<code>2
4
6
8
11
5
Constructor!
12
Main method!
10
</code>```

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?

答:
Static initializer are the first, so you get

```<code>2
4
</code>```

But in the next static initializer you call a new instance of Test1.class, so instance initializers are triggered, constructor is triggered after them and you get:

```<code>6
8
11
5
Constructor!
</code>```

After that the rest of static initializers are called. so:

```<code>12
</code>```

And the last is main method:

```<code>Main method!
10
</code>```

Body:
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}

The result is:

2
4
6
8
11
5
Constructor!
12
Main method!
10

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?

Body:
Static initializer are the first, so you get

2
4

But in the next static initializer you call a new instance of Test1.class, so instance initializers are triggered, constructor is triggered after them and you get:

6
8
11
5
Constructor!

After that the rest of static initializers are called. so:

12

And the last is main method:

Main method!
10


问:
Anaconda error after install on Windows
I want to install Anaconda on my x64 Windows machine, and I downloaded the Python 2.7 version 64-bit installer. The installation process looks good.

Then I installed pip with choco and installed several packages like zbar,
however, when I want to try to launch Anaconda, I entered conda in Powershell, this is what I got:

```<code>Traceback (most recent call last):
  File "C:\Users\Ruiyang\Anaconda2\Scripts\conda-script.py", line 3, in <module>
    import conda.cli
ImportError: No module named conda.cli
</code>```

Does anyone knows how to fix this?

答:
add anaconda's bin directory to path.
set path=whatever\anaconda\bin;path;

Title: Anaconda error after install on Windows

Body:
I want to install Anaconda on my x64 Windows machine, and I downloaded the Python 2.7 version 64-bit installer. The installation process looks good.

Then I installed pip with choco and installed several packages like zbar,
however, when I want to try to launch Anaconda, I entered conda in Powershell, this is what I got:

Traceback (most recent call last):
  File "C:\Users\Ruiyang\Anaconda2\Scripts\conda-script.py", line 3, in <module>
    import conda.cli
ImportError: No module named conda.cli

Does anyone knows how to fix this?


问:
Bootstrap table inside other table | Fix the height of table
I have little problem in my web page. I use bootstrap 4 and in table box I set  inside other table as in the picture below. How to make the height of table inside the same as the hieght of the box (td)?

html:

```<code><table class="table table-bordered">
   <tbody>
      <tr>
         <td>REVERT</td>
         <td>
            <table class="table" style="height: 100%">
               <tbody>
                  <tr>
                     <td>Name</td>
                     <td>LONG TEXT</td>
                  </tr>
               </tbody>
            </table>
         </td>
      </tr>
   </tbody>
</table>
</code>```

Browser:

答:
This is happening because your nested table has a margin-bottom of 1rem(default bootstrap css). override it that's it.

Working example

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

         REVERT

                     Name
                     LONG TEXT

```

Body:
I have little problem in my web page. I use bootstrap 4 and in table box I set  inside other table as in the picture below. How to make the height of table inside the same as the hieght of the box (td)?

html:

         REVERT

                     Name
                     LONG TEXT

Browser:

Body:
This is happening because your nested table has a margin-bottom of 1rem(default bootstrap css). override it that's it.

Working example

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<table class="table table-bordered">
   <tbody>
      <tr>
         <td>REVERT</td>
         <td>
            <table class="table" style="height: 100%; margin-bottom:0px;">
               <tbody>
                  <tr>
                     <td>Name</td>
                     <td>LONG TEXT</td>
                  </tr>
               </tbody>
            </table>
         </td>
      </tr>
   </tbody>
</table>


问:
Converting XML to CSV using xsltproc with complicated file
I've a big XML file that I am desperately trying to convert it into a CSV file with xsltproc.

All the data I wish to extract can be found under [GRP alias="TRIUT" level="5"].

What I need are only these tags of the file:

Matricule

Name

Value of Mount1 from the "Rubrique" 976 of the ELEMENT_1

This is my XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<RPT>
   <GRP alias="Reglementation" level="1">
      <FLD id="Reglementation">USA</FLD>
      <GRP alias="RUPT1" level="2">
         <FLD id="RUPT1" />
         <GRP alias="RUPT2" level="3">
            <FLD id="RUPT2" />
            <GRP alias="RUPT3" level="4">
               <FLD id="RUPT3" />
               <GRP alias="TRIUT" level="5">
                  <FLD id="TRIUT">00-532</FLD>
                  <DTL>
                     <FLD id="DateEdition" type="DATE">2017-02-01</FLD>
                     <FLD id="Name">MR CHARLIE CHAPLIN</FLD>
                     <FLD id="Matricule">12345678</FLD>
                     <SRPT id="ELEMENT_1">
                        <DTL>
                           <FLD id="Rubrique">038</FLD>
                           <FLD id="Mount1" type="FLOAT">2200.95</FLD>
                           <FLD id="Mount2" type="FLOAT">00000.00</FLD>
                        </DTL>
                        <DTL>
                           <FLD id="Rubrique">976</FLD>
                           <FLD id="Mount1">9926.96</FLD>
                           <FLD id="Mount2">00000.00</FLD>
                        </DTL>
                     </SRPT>
                  </DTL>
               </GRP>
               <GRP alias="TRIUT" level="5">
                  <FLD id="TRIUT">00186</FLD>
                  <DTL>
                     <FLD id="DateEdition">2017-03-31</FLD>
                     <FLD id="Nom">MR JAMES BOND</FLD>
                     <FLD id="Matricule">00000007</FLD>
                     <SRPT id="ELEMENT_1">
                        <DTL>
                           <FLD id="Rubrique">038</FLD>
                           <FLD id="Mount1">2054.22</FLD>
                           <FLD id="Mount2">000000.00</FLD>
                        </DTL>
                        <DTL>
                           <FLD id="Rubrique">976</FLD>
                           <FLD id="Mount1">2054.22</FLD>
                           <FLD id="Mount2">00000.22</FLD>
                        </DTL>
                     </SRPT>
                  </DTL>
               </GRP>
            </GRP>
         </GRP>
      </GRP>
   </GRP>
</RPT>
</code>```

What I want to see is:

```<code>Matricule;Name;Rubrique976_Mount1
12345678;MR CHARLIE CHAPLIN;9926.96
00000007;MR JAMES BOND;2054.22
</code>```

Do you think it's possible ?

This is what i tried to do, but it doesnt answer at all to what i need...

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:output method="text" encoding="UTF-8" />
   <xsl:strip-space elements="*" />
   <xsl:template match="/">
      <xsl:text>Matricule;Name;Rubrique976_Mount1</xsl:text>
      <xsl:text>\n</xsl:text>
      <xsl:for-each select="RPT/GRP/GRP/GRP/GRP/GRP/DTL">
         <xsl:for-each select="FLD">
            <xsl:value-of select="@id" />
            <xsl:text>;</xsl:text>
            <xsl:value-of select="." />
            <xsl:text>;</xsl:text>
            <xsl:for-each select="SRPT">
               <xsl:value-of select="@id" />
               <xsl:text>;</xsl:text>
               <xsl:value-of select="." />
               <xsl:text>;</xsl:text>
            </xsl:for-each>
         </xsl:for-each>
         <xsl:text>\n</xsl:text>
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>
</code>```

This is what I get, but not what I wanted...

```<code>Matricule;Name;Rubrique976_Mount1
DateEdition;2017-02-01;Name;MR CHARLIE CHAPLIN;Matricule;12345678;
DateEdition;2017-03-31;Nom;MR JAMES BOND;Matricule;00000007;
</code>```

Thanks for people who want to rack their brain !

答:
You should start off by selecting GRP which have the matching attributes

```<code><xsl:apply-templates select="//GRP[@alias='TRIUT' and @level='5']" />
</code>```

You can then have a template matching GRP which outputs the fields you need. For example, to output the "Matricule", it would look like this

```<code><xsl:value-of select="DTL/FLD[@id='Matricule']" />
</code>```

Outputting the "Value of Mount1 from the "Rubrique" 976 of the ELEMENT_1" is a bit more complicated because a number of conditions are involved:

```<code><xsl:value-of select="DTL
                       /SRPT[@id='ELEMENT_1']
                        /DTL[FLD[@id='Rubrique']='976']
                         /FLD[@id='Mount1']" />
</code>```

Try this XSLT

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="/">
    <xsl:text>Matricule;Name;Rubrique976_Mount1
</xsl:text>
    <xsl:apply-templates select="//GRP[@alias='TRIUT' and @level='5']" />
  </xsl:template>

  <xsl:template match="GRP">
    <xsl:value-of select="DTL/FLD[@id='Matricule']" />
    <xsl:text>,</xsl:text>
    <xsl:value-of select="DTL/FLD[@id='Name' or @id='Nom']" />
    <xsl:text>,</xsl:text>
    <xsl:value-of select="DTL/SRPT[@id='ELEMENT_1']/DTL[FLD[@id='Rubrique']='976']/FLD[@id='Mount1']" />
    <xsl:text>
</xsl:text>
  </xsl:template>

</xsl:stylesheet>
</code>```

EDIT: To sort by "Matricule", change the xsl:apply-templates to have an xsl:sort statement, like so:

```<code><xsl:apply-templates select="//GRP[@alias='TRIUT' and @level='5']">
    <xsl:sort select="DTL/FLD[@id='Matricule']" />
</xsl:apply-templates>
</code>```

Body:
I've a big XML file that I am desperately trying to convert it into a CSV file with xsltproc.

All the data I wish to extract can be found under [GRP alias="TRIUT" level="5"].

What I need are only these tags of the file:

Matricule

Name

Value of Mount1 from the "Rubrique" 976 of the ELEMENT_1

This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<RPT>
   <GRP alias="Reglementation" level="1">
      <FLD id="Reglementation">USA</FLD>
      <GRP alias="RUPT1" level="2">
         <FLD id="RUPT1" />
         <GRP alias="RUPT2" level="3">
            <FLD id="RUPT2" />
            <GRP alias="RUPT3" level="4">
               <FLD id="RUPT3" />
               <GRP alias="TRIUT" level="5">
                  <FLD id="TRIUT">00-532</FLD>
                  <DTL>
                     <FLD id="DateEdition" type="DATE">2017-02-01</FLD>
                     <FLD id="Name">MR CHARLIE CHAPLIN</FLD>
                     <FLD id="Matricule">12345678</FLD>
                     <SRPT id="ELEMENT_1">
                        <DTL>
                           <FLD id="Rubrique">038</FLD>
                           <FLD id="Mount1" type="FLOAT">2200.95</FLD>
                           <FLD id="Mount2" type="FLOAT">00000.00</FLD>
                        </DTL>
                        <DTL>
                           <FLD id="Rubrique">976</FLD>
                           <FLD id="Mount1">9926.96</FLD>
                           <FLD id="Mount2">00000.00</FLD>
                        </DTL>
                     </SRPT>
                  </DTL>
               </GRP>
               <GRP alias="TRIUT" level="5">
                  <FLD id="TRIUT">00186</FLD>
                  <DTL>
                     <FLD id="DateEdition">2017-03-31</FLD>
                     <FLD id="Nom">MR JAMES BOND</FLD>
                     <FLD id="Matricule">00000007</FLD>
                     <SRPT id="ELEMENT_1">
                        <DTL>
                           <FLD id="Rubrique">038</FLD>
                           <FLD id="Mount1">2054.22</FLD>
                           <FLD id="Mount2">000000.00</FLD>
                        </DTL>
                        <DTL>
                           <FLD id="Rubrique">976</FLD>
                           <FLD id="Mount1">2054.22</FLD>
                           <FLD id="Mount2">00000.22</FLD>
                        </DTL>
                     </SRPT>
                  </DTL>
               </GRP>
            </GRP>
         </GRP>
      </GRP>
   </GRP>
</RPT>

What I want to see is:

Matricule;Name;Rubrique976_Mount1
12345678;MR CHARLIE CHAPLIN;9926.96
00000007;MR JAMES BOND;2054.22

Do you think it's possible ?

This is what i tried to do, but it doesnt answer at all to what i need...

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:output method="text" encoding="UTF-8" />
   <xsl:strip-space elements="*" />
   <xsl:template match="/">
      <xsl:text>Matricule;Name;Rubrique976_Mount1</xsl:text>
      <xsl:text>&#xA;</xsl:text>
      <xsl:for-each select="RPT/GRP/GRP/GRP/GRP/GRP/DTL">
         <xsl:for-each select="FLD">
            <xsl:value-of select="@id" />
            <xsl:text>;</xsl:text>
            <xsl:value-of select="." />
            <xsl:text>;</xsl:text>
            <xsl:for-each select="SRPT">
               <xsl:value-of select="@id" />
               <xsl:text>;</xsl:text>
               <xsl:value-of select="." />
               <xsl:text>;</xsl:text>
            </xsl:for-each>
         </xsl:for-each>
         <xsl:text>&#xA;</xsl:text>
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

This is what I get, but not what I wanted...

Matricule;Name;Rubrique976_Mount1
DateEdition;2017-02-01;Name;MR CHARLIE CHAPLIN;Matricule;12345678;
DateEdition;2017-03-31;Nom;MR JAMES BOND;Matricule;00000007;

Thanks for people who want to rack their brain !

Body:
You should start off by selecting GRP which have the matching attributes

<xsl:apply-templates select="//GRP[@alias='TRIUT' and @level='5']" />

You can then have a template matching GRP which outputs the fields you need. For example, to output the "Matricule", it would look like this

<xsl:value-of select="DTL/FLD[@id='Matricule']" />

Outputting the "Value of Mount1 from the "Rubrique" 976 of the ELEMENT_1" is a bit more complicated because a number of conditions are involved:

<xsl:value-of select="DTL
                       /SRPT[@id='ELEMENT_1']
                        /DTL[FLD[@id='Rubrique']='976']
                         /FLD[@id='Mount1']" />

Try this XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="/">
    <xsl:text>Matricule;Name;Rubrique976_Mount1&#10;</xsl:text>
    <xsl:apply-templates select="//GRP[@alias='TRIUT' and @level='5']" />
  </xsl:template>

  <xsl:template match="GRP">
    <xsl:value-of select="DTL/FLD[@id='Matricule']" />
    <xsl:text>,</xsl:text>
    <xsl:value-of select="DTL/FLD[@id='Name' or @id='Nom']" />
    <xsl:text>,</xsl:text>
    <xsl:value-of select="DTL/SRPT[@id='ELEMENT_1']/DTL[FLD[@id='Rubrique']='976']/FLD[@id='Mount1']" />
    <xsl:text>&#10;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

EDIT: To sort by "Matricule", change the xsl:apply-templates to have an xsl:sort statement, like so:

<xsl:apply-templates select="//GRP[@alias='TRIUT' and @level='5']">
    <xsl:sort select="DTL/FLD[@id='Matricule']" />
</xsl:apply-templates>


问:
MySql database synchronization
I have two different servers for mysql databases. First server is for master database and second server to act as slave. Now i need to synchronization all the changes being done on my master database to be applied to the slave database on real time basis.

Please guide me with all the steps to implement real time mysql database synchronization.

答:
Sometimes errors that occur silently/louding on the MASTER will cause the replication to break on the SLAVE (if the query was invalid on the master it will also be invalid on the slave).  There are two solutions: 1.  prevent bad entry on the MASTER by fixing the table (ie required fields) or the logic that allows inserts.  2.  ignore certain errors that occur by modifying the my.ini file on the slave.

On a related note:  The book High Performance MySQL is a excellent resource on how to setup replication.

ContentLicense: CC BY-SA 2.5

Title: MySql database synchronization


问:
SciTE sort selection tool : numbers with leading spaces are not sorted as expected
The SciTE editor comes with embedded Lua scripting engine having access to the text buffer of the editor. This makes it possible to extend SciTE's functionality with tools programmed in Lua and started from the Tools Menu. One such tool available from here:

http://lua-users.org/wiki/SciteSortSelection

is a tool for sorting of selected lines in alphabetical order.
Annoying for me was/is that it doesn't sort lines containing numbers in their numerical order but like this:

```<code>    1
  111
    2
  222
    3
  333
</code>```

where I would rather expect:

```<code>    1
    2
    3
  111
  222
  333
</code>```

Google and Co. are not of much help here as there is to my knowledge no solution to this problem available yet online. It is also not that easy to find and deeply understand the Lua documentation for table.sort(). So the question for a knowledgeable Lua programmer would be, what is the best way to patch the existing Lua script code, so that numbers (and also lines with text in case of leading spaces) become sorted as expected and the Lua code for this task runs so fast, that even sorting of huge files (50 MByte and more) won't take much time?

答:
Below what I finally came up with myself. It's sure a quick and dirty solution which slows the already slow </p>

<p>( compared to jEdit [Plugins]->[Text Tools]->[Sort Lines] or to bash command line 'sort -g' ) </p>

<p>process of sorting huge buffers of text lines, but it is at least there for use and works as expected. For the sake of completeness here the entire section of code currently present in my Lua Startup Script for SciTE: </p>

```<code>-- =============================================================================
-- Sort Selected Lines (available in MENU -> Tools):
-- -----------------------------------------------------------
-- Specify in .SciTEUser.properties:
--     command.name.2.*=# Sort Selected Lines    '
--     command.subsystem.2.*=3
--     command.mode.2.*=savebefore:no
--     command.2.*=SortSelectedLines
--     # command.shortcut.2.*=Ctrl+2 # Ctrl+2 is DEFAULT for command.2.*

function lines(str)
  local t = {}
  local i, lstr = 1, #str
  while i <= lstr do
    local x, y = string.find(str, "\r?\n", i)
    if x then t[#t + 1] = string.sub(str, i, x - 1)
    else break
    end
    i = y + 1
  end
  if i <= lstr then t[#t + 1] = string.sub(str, i) end
  return t
end

-- It was an annoying for me that using table.sort(buffer) in Lua
-- didn't sort numbers with leading spaces in their numerical order.
-- Using following comparison function helps to avoid that problem:
function compare(a,b)
  return a:gsub(" ", "0") < b:gsub(" ", "0")
-- If 'compare' is not used ( table.sort(buf) )
-- Lua uses implicit for sorting (see Lua tutorial):
--   return a < b
-- so changing the provided return statement to this above
-- would be enough to restore sorting to how it was before
end

function SortSelectedLines()
  local sel = editor:GetSelText()
  if #sel == 0 then return end
  local eol = string.match(sel, "\n$")
  local buf = lines(sel)
  table.sort(buf, compare)
--table.foreach (buf, print) --used for debugging
  local out = table.concat(buf, "\n")
  if eol then out = out.."\n" end
  editor:ReplaceSel(out)
end

--  ---------
-- :Sort Selected Lines
-- -----------------------------------------------------------------------------
</code>```

Body:
The SciTE editor comes with embedded Lua scripting engine having access to the text buffer of the editor. This makes it possible to extend SciTE's functionality with tools programmed in Lua and started from the Tools Menu. One such tool available from here:

http://lua-users.org/wiki/SciteSortSelection

is a tool for sorting of selected lines in alphabetical order.
Annoying for me was/is that it doesn't sort lines containing numbers in their numerical order but like this:

    1
  111
    2
  222
    3
  333

where I would rather expect:

    1
    2
    3
  111
  222
  333

Google and Co. are not of much help here as there is to my knowledge no solution to this problem available yet online. It is also not that easy to find and deeply understand the Lua documentation for table.sort(). So the question for a knowledgeable Lua programmer would be, what is the best way to patch the existing Lua script code, so that numbers (and also lines with text in case of leading spaces) become sorted as expected and the Lua code for this task runs so fast, that even sorting of huge files (50 MByte and more) won't take much time?

Body:
Below what I finally came up with myself. It's sure a quick and dirty solution which slows the already slow

( compared to jEdit [Plugins]->[Text Tools]->[Sort Lines] or to bash command line 'sort -g' )

process of sorting huge buffers of text lines, but it is at least there for use and works as expected. For the sake of completeness here the entire section of code currently present in my Lua Startup Script for SciTE:

-- =============================================================================
-- Sort Selected Lines (available in MENU -> Tools):
-- -----------------------------------------------------------
-- Specify in .SciTEUser.properties:
--     command.name.2.*=# Sort Selected Lines    '
--     command.subsystem.2.*=3
--     command.mode.2.*=savebefore:no
--     command.2.*=SortSelectedLines
--     # command.shortcut.2.*=Ctrl+2 # Ctrl+2 is DEFAULT for command.2.*

function lines(str)
  local t = {}
  local i, lstr = 1, #str
  while i <= lstr do
    local x, y = string.find(str, "\r?\n", i)
    if x then t[#t + 1] = string.sub(str, i, x - 1)
    else break
    end
    i = y + 1
  end
  if i <= lstr then t[#t + 1] = string.sub(str, i) end
  return t
end

-- It was an annoying for me that using table.sort(buffer) in Lua
-- didn't sort numbers with leading spaces in their numerical order.
-- Using following comparison function helps to avoid that problem:
function compare(a,b)
  return a:gsub(" ", "0") < b:gsub(" ", "0")
-- If 'compare' is not used ( table.sort(buf) )
-- Lua uses implicit for sorting (see Lua tutorial):
--   return a < b
-- so changing the provided return statement to this above
-- would be enough to restore sorting to how it was before
end

function SortSelectedLines()
  local sel = editor:GetSelText()
  if #sel == 0 then return end
  local eol = string.match(sel, "\n$")
  local buf = lines(sel)
  table.sort(buf, compare)
--table.foreach (buf, print) --used for debugging
  local out = table.concat(buf, "\n")
  if eol then out = out.."\n" end
  editor:ReplaceSel(out)
end

--  ---------
-- :Sort Selected Lines
-- -----------------------------------------------------------------------------


问:
3D Modeling (Software or Method) Using Boolean Operations
I am looking for a 3D modeling software that will allow me to build a model using shapes. Now, yes, I could use Blender (and have been for some time), but I find it absolutely frustrating to use based on the way I like to 3D model. My 'method' is to start with a simple shape and subtract and add to it using other simple shapes until the final design. Using Blender, only the Boolean modifier seems to work for this purpose, but even then it usually fails me, and in the end the object isn't solid. The piece that I just cut from will have a gaping hole in it (since models in Blender are hollow). I have to go into edit mode and join the points together to make faces so the object appears solid, which can be very time consuming. I do not want to do this process manually.

So, in summary...

Problem: Need other (hopefully free) software to suit my modeling method or a better method (A different modifier? Different modeling techniques?) for creating the desired object using Blender.

Here is an example of my current problem I am working on, before and after the Boolean modifier was applied in Blender, as a series of images. The final design would have this process completed on all four sides of the 'cube'.

Before and After Boolean Modifier

Before on the left, after on the right. Not so good in the photo below, I will have to fill in that gap manually (or see below for the way I cheated...)

Desired and Actual Result

The following top photo looks good, right, so why am I complaining? I cheated using the solidify modifier (adding thickness until the 'hole' was filled). As you see below in the X-ray view (bottom photo), all sorts of crazy geometry is generated as a result of the solidify modifier...maybe not desired, but maybe there is a way to fix this? There also seem to be some glitchy parts in the 'desired' photo near the bottom of the cut.

答: You are looking for something based on CSG (Constructive Solid Geometry). One of the examples is Unreal Engine: a powerful tool; you could export a model from UE to pretty much any format you like. It does allow you to subtract as well add 3D shapes. And it is free.</p>


问:
How to show related objects in a jstl using a spring?
I have 3 objects: User, Comment and StatusUpdate(news). This is the User...

```<code>@Entity
@Table(name = "users")
@PasswordMatch(message = "{register.repeatpassword.mismatch}")
public class SiteUser {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true)
@Email(message = "{register.email.invalid}")
@NotBlank(message = "{register.email.invalid}")
private String email;

@Transient
@Size(min = 5, max = 15, message = "{register.password.size}")
private String plainPassword;

@Column(name = "password", length = 60)
private String password;

@Column(name = "enabled")
private Boolean enabled = false;

@NotNull
@Column(name = "firstname", length = 20)
@Size(min = 2, max = 20, message = "{register.firstname.size}")
private String firstname;

@NotNull
@Column(name = "surname", length = 25)
@Size(min = 2, max = 25, message = "{register.surname.size}")
private String surname;

@Transient
private String repeatPassword;

@Column(name = "role", length = 20)
private String role;

public SiteUser() {

}
</code>```

Here comes the StatusUpdate(you can call it piece of news or article). That has a site user that is the one who has created that article.

```<code>@Entity
@Table(name = "status_update")
public class StatusUpdate {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Size(min=5, max=255, message="{addstatus.title.size}")
@Column(name = "title")
private String title;

@Size(min=5, max=5000, message="{addstatus.text.size}")
@Column(name = "text")
private String text;

@Column(name = "added")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss")
private Date added;

@OneToOne(targetEntity = SiteUser.class)
@JoinColumn(name="user_id")
private SiteUser siteUser;

@PrePersist
protected void onCreate() {
    if (added == null) {
        added = new Date();
    }
}

public StatusUpdate() {

}
</code>```

And the Comment which can be done by any registered user, right? As you will notice the Comment has no User object to avoid circular references.

```<code>@Entity
@Table(name = "comments")
public class Comment {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "statusupdateid")
private StatusUpdate statusUpdate;

@Column(name = "commenttext")
private String commenttext;

@Column(name = "commentdate")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy/MM/dd hh:mm:ss")
private Date commentdate;

@Column(name = "userid")
private Long userid;

public Comment() {
}
</code>```

Now I would like to show in my JSP an article, with all the related comments and each of them belong to a different user. Can I use a HashMap to relate the users and their comments? I do not see how.

```<code>@RequestMapping(value ="/viewonestatus/{id}")
public ModelAndView viewOneStatus(@PathVariable("id") Long id) {

    StatusUpdate status = statusUpdateService.get(id);

    int countComments = commentService.countStatusComments(status);

    List<Comment> comments = commentService.readAllComments(status);

    ModelAndView modelAndView = new ModelAndView();

    for (Comment comment: comments){

        SiteUser user = userService.get(comment.getUserid());

        modelAndView.getModel().put("user", user);

    }

    modelAndView.getModel().put("commentscounter", countComments);
    modelAndView.getModel().put("status", status);
    modelAndView.getModel().put("comments", comments); //!!

    modelAndView.setViewName("app.viewonestatus");

    return modelAndView;
}
</code>```

As you expect, when my JSP shows just one user (the last one) for all the comments, but I can not relate all the Comments with the corresponding Users

```<code><table class="table table-hover">
    <c:forEach var="comment" items="${comments}">
    <tr>
        <td>

    <div class="col-sm-2 sm-margin-bottom-40">
        <img class="img-responsive profile-img margin-bottom-20" id="profilePhotoImage" src="/profilephoto/${comment.userid}" />
    </div>
                                                <h4>
            ${user.firstname} ${user.surname}
            <span>
              <!--  <span>${counterUserMap[comment.key]}</span> -->
            5 hours ago / <a href="#">Reply</a>
            </span>
        </h4>
        <p>
            <fmt:formatDate pattern="EEEE d MMMM y 'at' H:mm:ss" value="${comment.commentdate}" />
        </p>
        <p>${comment.commenttext}</p>
    </td>
</tr>
</c:forEach>
</code>```

I do not want to use JSON. I'm thinking about an anonymous class with all the stuff inside. Well, I'm open to your thoughts. Thanks.

答:
Shokulei answer was the solution:

Since you have the userid, you can link it using the @ManyToOne annotation. This would be the most ideal way. But if you really don't want to link them, then you can create a new @Transient SiteUser siteUser; attribute in Comment class. And then in your for loop, you can use comment.setSiteUser(user); instead of modelAndView.getModel().put("user", user);. Hope this will help.

Thanks Shokulei

Body:
I have 3 objects: User, Comment and StatusUpdate(news). This is the User...

@Entity
@Table(name = "users")
@PasswordMatch(message = "{register.repeatpassword.mismatch}")
public class SiteUser {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true)
@Email(message = "{register.email.invalid}")
@NotBlank(message = "{register.email.invalid}")
private String email;

@Transient
@Size(min = 5, max = 15, message = "{register.password.size}")
private String plainPassword;

@Column(name = "password", length = 60)
private String password;

@Column(name = "enabled")
private Boolean enabled = false;

@NotNull
@Column(name = "firstname", length = 20)
@Size(min = 2, max = 20, message = "{register.firstname.size}")
private String firstname;

@NotNull
@Column(name = "surname", length = 25)
@Size(min = 2, max = 25, message = "{register.surname.size}")
private String surname;

@Transient
private String repeatPassword;

@Column(name = "role", length = 20)
private String role;

public SiteUser() {

}

Here comes the StatusUpdate(you can call it piece of news or article). That has a site user that is the one who has created that article.

@Entity
@Table(name = "status_update")
public class StatusUpdate {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Size(min=5, max=255, message="{addstatus.title.size}")
@Column(name = "title")
private String title;

@Size(min=5, max=5000, message="{addstatus.text.size}")
@Column(name = "text")
private String text;

@Column(name = "added")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss")
private Date added;

@OneToOne(targetEntity = SiteUser.class)
@JoinColumn(name="user_id")
private SiteUser siteUser;

@PrePersist
protected void onCreate() {
    if (added == null) {
        added = new Date();
    }
}

public StatusUpdate() {

}

And the Comment which can be done by any registered user, right? As you will notice the Comment has no User object to avoid circular references.

@Entity
@Table(name = "comments")
public class Comment {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "statusupdateid")
private StatusUpdate statusUpdate;

@Column(name = "commenttext")
private String commenttext;

@Column(name = "commentdate")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy/MM/dd hh:mm:ss")
private Date commentdate;

@Column(name = "userid")
private Long userid;

public Comment() {
}

Now I would like to show in my JSP an article, with all the related comments and each of them belong to a different user. Can I use a HashMap to relate the users and their comments? I do not see how.

@RequestMapping(value ="/viewonestatus/{id}")
public ModelAndView viewOneStatus(@PathVariable("id") Long id) {

    StatusUpdate status = statusUpdateService.get(id);

    int countComments = commentService.countStatusComments(status);

    List<Comment> comments = commentService.readAllComments(status);

    ModelAndView modelAndView = new ModelAndView();

    for (Comment comment: comments){

        SiteUser user = userService.get(comment.getUserid());

        modelAndView.getModel().put("user", user);

    }

    modelAndView.getModel().put("commentscounter", countComments);
    modelAndView.getModel().put("status", status);
    modelAndView.getModel().put("comments", comments); //!!

    modelAndView.setViewName("app.viewonestatus");

    return modelAndView;
}

As you expect, when my JSP shows just one user (the last one) for all the comments, but I can not relate all the Comments with the corresponding Users

    <c:forEach var="comment" items="${comments}">

            ${user.firstname} ${user.surname}

            5 hours ago / Reply

            <fmt:formatDate pattern="EEEE d MMMM y 'at' H:mm:ss" value="${comment.commentdate}" />

${comment.commenttext}

</c:forEach>

I do not want to use JSON. I'm thinking about an anonymous class with all the stuff inside. Well, I'm open to your thoughts. Thanks.


问:
Efficiently wrapping a double
I have a number of geometric functions that only accept angles in the range 0° to 360°.  If the angle is outside that range then the angle is invalid (i.e. converting 365° to 5° is not an option) and there's no point in calling the functions.  To this end I've created the following class:

```<code>struct PositiveAngle {
    public let value: Double

    init?(value: Double) {
        guard 0.0 <= value && value <= 360.0 else {
            return nil
        }
        self.value = value
    }
}
</code>```

To be used as follows:

```<code>let angle = PositiveAngle(value: 30.0)
print(angle.value)

func foo(angle: PositiveAngle) -> PositiveAngle {
    ...
}
</code>```

This works but it feels "clunky" because I have extract the value of the angle from the struct whenever I need to use it.  Given that all I am after is a Double that has a restricted range, is there a more efficient way to achieve this?

答:
If you don't want to access .value in every function, you will have to add helper functions by yourself.

For example, to define sin:

```<code>func sin(_ angle: PositiveAngle) -> Double {
    return sin(angle.value * Double.pi / 180)
}
</code>```

Now you will be able to call sin with your PositiveAngle as an argument directly.

You can do the same for operators, e.g. +, - etc.

Title: Efficiently wrapping a double

Body:
I have a number of geometric functions that only accept angles in the range 0° to 360°.  If the angle is outside that range then the angle is invalid (i.e. converting 365° to 5° is not an option) and there's no point in calling the functions.  To this end I've created the following class:

struct PositiveAngle {
    public let value: Double

    init?(value: Double) {
        guard 0.0 <= value && value <= 360.0 else {
            return nil
        }
        self.value = value
    }
}

To be used as follows:

let angle = PositiveAngle(value: 30.0)
print(angle.value)

func foo(angle: PositiveAngle) -> PositiveAngle {
    ...
}

This works but it feels "clunky" because I have extract the value of the angle from the struct whenever I need to use it.  Given that all I am after is a Double that has a restricted range, is there a more efficient way to achieve this?

Body:
If you don't want to access .value in every function, you will have to add helper functions by yourself.

For example, to define sin:

func sin(_ angle: PositiveAngle) -> Double {
    return sin(angle.value * Double.pi / 180)
}

Now you will be able to call sin with your PositiveAngle as an argument directly.

You can do the same for operators, e.g. +, - etc.


问:
UITableView and custom UITableViewCell using .xib
In my app I am using a custom tableViewCell using a xib file. I create the .xib file outlet the labels etc to my TableViewCell class

In my ViewController the code I used to populate and show the cell on the table view is as follows:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let transaction = statementArray[indexPath.row]
    let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell

    cell.transAmount.text = String(transaction.transAmount)
    cell.transDesc.text = transaction.transDesc
    cell.transFees.text = String(transaction.transFees)

    return cell
}
</code>```

I am aware that the way tableViews work is that they reuse the cell that goes off the screen. Is the way i am loading the .xib and populating the cell correct? Or do I have to add something to my code?

答:
FIrst Register Custom cell nibCalss in tableview

```<code>let str1 : NSString = "StatementCell"

tableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: str1 as String)
</code>```

Now initialise tableviewcell

```<code>let cell1:StatementCell = tableView.dequeueReusableCell(withIdentifier: str1 as String) as! StatementCell!
</code>```

Now access tableviewcell outlet collection.

ContentLicense: CC BY-SA 4.0

Body:
In my app I am using a custom tableViewCell using a xib file. I create the .xib file outlet the labels etc to my TableViewCell class

In my ViewController the code I used to populate and show the cell on the table view is as follows:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let transaction = statementArray[indexPath.row]
    let cell = Bundle.main.loadNibNamed("StatementCell", owner: self, options: nil)?.first as! StatementCell

    cell.transAmount.text = String(transaction.transAmount)
    cell.transDesc.text = transaction.transDesc
    cell.transFees.text = String(transaction.transFees)

    return cell
}

I am aware that the way tableViews work is that they reuse the cell that goes off the screen. Is the way i am loading the .xib and populating the cell correct? Or do I have to add something to my code?

Body:
FIrst Register Custom cell nibCalss in tableview

let str1 : NSString = "StatementCell"

tableView.register(UINib(nibName: "StatementCell", bundle: nil), forCellReuseIdentifier: str1 as String)

Now initialise tableviewcell

let cell1:StatementCell = tableView.dequeueReusableCell(withIdentifier: str1 as String) as! StatementCell!

Now access tableviewcell outlet collection.


问:
Proper way of cancelling accept and closing a Python processing/multiprocessing Listener connection
(I'm using the pyprocessing module in this example, but replacing processing with multiprocessing should probably work if you run python 2.6 or use the multiprocessing backport)

I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:

```<code>import processing
from processing.connection import Listener
import threading
import time
import os
import signal
import socket
import errno

# This is actually called by the connection handler.
def closeme():
    time.sleep(1)
    print 'Closing socket...'
    listener.close()
    os.kill(processing.currentProcess().getPid(), signal.SIGPIPE)

oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None)

listener = Listener('/tmp/asdf', 'AF_UNIX')
# This is a thread that handles one already accepted connection, left out for brevity
threading.Thread(target=closeme).start()
print 'Accepting...'
try:
    listener.accept()
except socket.error, e:
    if e.args[0] != errno.EINTR:
        raise
# Cleanup here...
print 'Done...'
</code>```

The only other way I've thought about is reaching deep into the connection (listener._listener._socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.

Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.

Clarification:
Thanks all! As usual, ambiguities in my original question are revealed :)

I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.

I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy

The reasons for threads are that:

They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.

I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.

Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing.

答:
Isnt that what select is for??

Only call accept on the socket if the select indicates it will not block...

The select has a timeout, so you can break out occasionally occasionally to check
if its time to shut down....

OwnerDisplayName: Henrik Gustafsson

Body:
(I'm using the pyprocessing module in this example, but replacing processing with multiprocessing should probably work if you run python 2.6 or use the multiprocessing backport)

I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:

import processing
from processing.connection import Listener
import threading
import time
import os
import signal
import socket
import errno

# This is actually called by the connection handler.
def closeme():
    time.sleep(1)
    print 'Closing socket...'
    listener.close()
    os.kill(processing.currentProcess().getPid(), signal.SIGPIPE)

oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None)

listener = Listener('/tmp/asdf', 'AF_UNIX')
# This is a thread that handles one already accepted connection, left out for brevity
threading.Thread(target=closeme).start()
print 'Accepting...'
try:
    listener.accept()
except socket.error, e:
    if e.args[0] != errno.EINTR:
        raise
# Cleanup here...
print 'Done...'

The only other way I've thought about is reaching deep into the connection (listener._listener._socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.

Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.

Clarification:
Thanks all! As usual, ambiguities in my original question are revealed :)

I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.

I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy

The reasons for threads are that:

They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.

I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.

Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing.

LastEditorDisplayName: Henrik Gustafsson

OwnerDisplayName: Roger