问:
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.

答: From the third error, it looks like there could be a conflicting declaration for "Polygon" in your code. Try enclosing Polygon in a namespace?</p>

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

问:
sed not responding for me
I'm trying to use sed but can't get it to work. My system is Ubuntu 16.04.2 with GNU sed 4.2.2

I have a folder with numerous text files that I want to edit. From a terminal in that folder I have tried the following (separately - one command at a time).

To remove blank lines from all the files: sed -i '/^$/d' *txt

In case the lines include white spaces: sed -i '/^\s*$/d' *txt

To remove line 4: sed -i '4d' *.txt

In each case, there is no error message in the terminal but the changes do not happen. I've tried the same commands but for an individual file rather than all, so with the filename instead of *.txt, but still no changes achieved.

The only sign of sed being active at all is if I don't do the -i but ask for a new file: sed '4d' fred.txt > fred2.text

The new file fred2 was created - but with line 4 still there!
What am I missing? How can I get sed to actually carry out these commands?
Thanks for any help.

答:
After looking at the files in more detail, and doing some experimenting, I discovered what the problem was: The text files I was trying to edit with sed had CR line-end characters. When I changed this to LF the sed commands worked fine.
Thank you to those who made suggestions.</p>

ContentLicense: CC BY-SA 3.0

Title: sed not responding for me


问:
How to enable basic caching with Spring Data JPA
I am trying to enable basic caching with Spring Data JPA. But I cannot understand why the DAO methods are still querying the database instead of using the cache.

Given the following Spring Boot 1.5.1 application

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Server{

    public static void main(String[] args) {
        SpringApplication.run(Server.class, args);
    }
}
</code>```

Controller

```<code>@Controller
public class PasswordsController {

    @Autowired
    private PasswordService service;

    @SuppressWarnings("unchecked")
    @RequestMapping("/passwords.htm")
    public void passwords(Map model,
            HttpServletRequest request) {
        model.put("passwords", service.getPasswords(request));
    }
...
</code>```

Service

```<code>@Service
@Transactional
public class PasswordService extends BaseService {

    @Autowired
    private PasswordJpaDao passwordDao;

    public Collection<Password> getPasswords(HttpServletRequest request) {
        Collection<Password> passwords = passwordDao.getPasswords(params);
        return passwords;
    }
...
</code>```

Interface

```<code>@Transactional
public interface PasswordJpaDaoCustom {

    public Collection<Password> getPasswords(PasswordSearchParameters params);
}
</code>```

and implementation

```<code>import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import com.crm.entity.Password;
import com.crm.search.PasswordSearchParameters;

@Transactional
@Repository
public class PasswordJpaDaoImpl implements PasswordJpaDaoCustom {

    @PersistenceContext
    private EntityManager em;

    @Override
    @Cacheable("passwords")
    public Collection<Password> getPasswords(PasswordSearchParameters params) {
       System.err.println("got here");
       return em.createQuery(hql, Password.class);
    }
...
</code>```

Maven Dependencies

```<code><!-- Spring Boot start -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Spring Boot end -->

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
</dependency>
</code>```

I understand that Spring Boot will implicitly use ConcurrentHashMap for caching without any specific configuration necessary?

But the getPasswords() dao method is always called instead of using the cache. Why is this?

答:
Yes, spring boot by default uses ConcurrentHashMap for caching and the issue with your code is that you did not set any key for your passwords cache, so it is calling the database every time for fetching the data.

So you need to the key (any unique identifier) using the params object variables as shown below:

```<code>@Cacheable(value="passwords", key="#params.id")//any unique identifier
public Collection<Password> getPasswords(PasswordSearchParameters params) {
   System.err.println("got here");
   return em.createQuery(hql, Password.class);
}
</code>```

Body:
I am trying to enable basic caching with Spring Data JPA. But I cannot understand why the DAO methods are still querying the database instead of using the cache.

Given the following Spring Boot 1.5.1 application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Server{

    public static void main(String[] args) {
        SpringApplication.run(Server.class, args);
    }
}

Controller

@Controller
public class PasswordsController {

    @Autowired
    private PasswordService service;

    @SuppressWarnings("unchecked")
    @RequestMapping("/passwords.htm")
    public void passwords(Map model,
            HttpServletRequest request) {
        model.put("passwords", service.getPasswords(request));
    }
...

Service

@Service
@Transactional
public class PasswordService extends BaseService {

    @Autowired
    private PasswordJpaDao passwordDao;

    public Collection<Password> getPasswords(HttpServletRequest request) {
        Collection<Password> passwords = passwordDao.getPasswords(params);
        return passwords;
    }
...

Interface

@Transactional
public interface PasswordJpaDaoCustom {

    public Collection<Password> getPasswords(PasswordSearchParameters params);
}

and implementation

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import com.crm.entity.Password;
import com.crm.search.PasswordSearchParameters;

@Transactional
@Repository
public class PasswordJpaDaoImpl implements PasswordJpaDaoCustom {

    @PersistenceContext
    private EntityManager em;

    @Override
    @Cacheable("passwords")
    public Collection<Password> getPasswords(PasswordSearchParameters params) {
       System.err.println("got here");
       return em.createQuery(hql, Password.class);
    }
...

Maven Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
</dependency>

I understand that Spring Boot will implicitly use ConcurrentHashMap for caching without any specific configuration necessary?

But the getPasswords() dao method is always called instead of using the cache. Why is this?

Body:
Yes, spring boot by default uses ConcurrentHashMap for caching and the issue with your code is that you did not set any key for your passwords cache, so it is calling the database every time for fetching the data.

So you need to the key (any unique identifier) using the params object variables as shown below:

@Cacheable(value="passwords", key="#params.id")//any unique identifier
public Collection<Password> getPasswords(PasswordSearchParameters params) {
   System.err.println("got here");
   return em.createQuery(hql, Password.class);
}


问:
Cannot install signed apk to device manually, got error "App not installed"
I'd like to publicate my app to GooglePlay but first i would like to do a last testing with the signed apk to ensure that all of the used API keys are working correctly with the release version (GMaps, Facebook, etc)

So i just made a signed version of my app with our release key and when i try to install the app to the device i got an error:

I have tried to copy the apk to the device and install it with an apk installer app.

Strange thing is when i do the same process with debug signing key, all is well, I can install and run the app.

Here are the steps of the procedure:

I select the release key, type password.

I do select release build type instead of debugging

Just in case i also defined in the gradle file the signing keys but I must admit i dont know is it necessary.

I tried like 7 seven times now so i assume this problem is not just a
mistyped password, also I can make this work with the standard debug android signing key.

Please help if you can.

答:
Here I resolved this issue

The reason behind this issue is, there is already an application with the same package name in the phone, but you cannot find it in phone menu(U already made the un-installation but actually its still in your phone).

To see the application go to phones SETTINGS -> APPS.
There you can see the application, but inside that the UNINSTALL button may be disabled. click on the menu overflow button to see Uninstall for all users.

After performed uninstalled for all users I have successfully installed my signed apk.
You can also use adb to uninstall the app from phone.

```<code>adb uninstall package name
</code>```

In addition to this,
if your mobile supports multiple users then check if respective app is not installed for other users. If it is installed for others then first uninstall previous app and try again

Body:
Here I resolved this issue

The reason behind this issue is, there is already an application with the same package name in the phone, but you cannot find it in phone menu(U already made the un-installation but actually its still in your phone).

To see the application go to phones SETTINGS -> APPS.
There you can see the application, but inside that the UNINSTALL button may be disabled. click on the menu overflow button to see Uninstall for all users.

After performed uninstalled for all users I have successfully installed my signed apk.
You can also use adb to uninstall the app from phone.

adb uninstall package name

In addition to this,
if your mobile supports multiple users then check if respective app is not installed for other users. If it is installed for others then first uninstall previous app and try again

ContentLicense: CC BY-SA 4.0


问:
Adding a solution file to asp.net 1.1 application using Visual Studio 2010
I'm trying to migrate an old asp.net 1.1 application to target the new .net 4.0 framework. There are good guides available on this (https://learn.microsoft.com/en-us/archive/msdn-magazine/2010/september/app-migration-migrate-your-asp-net-1-1-apps-to-visual-studio-2010). However, all approaches start with the assumption that the 1.1 project contains a solution file which one has to open using VS 2010 and go through the conversion wizard.

In my case, the project does not have any solution file, giving me a sort of chicken and egg issue.

Is there a way to add a 1.1 .net soution file with or without VS 2010? Using command line tools? What is so special about a solution file anyway?

答:
Are the file that you have in a website alreay? Are they located in C:\Inetpub\wwwroot\[SITE_FOLDER]?

This site might help as well. http://ondotnet.com/pub/a/dotnet/excerpt/vshacks_chap1/index.html?page=4

Here is a sample solution:

```<code>Microsoft Visual Studio Solution File, Format Version 7.0
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "C:\...\WebSite1\", "..\..\WebSites\WebSite1", "{A3EF0D1E-ABC0-4A4F-851F-EBC56FDF2C53}"
    ProjectSection(WebsiteProperties) = preProject
        Debug.AspNetCompiler.VirtualPath = "/WebSite1"
        Debug.AspNetCompiler.PhysicalPath = "..\..\WebSites\WebSite1\"
        Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\WebSite1\"
        Debug.AspNetCompiler.Updateable = "true"
        Debug.AspNetCompiler.ForceOverwrite = "true"
        Debug.AspNetCompiler.FixedNames = "false"
        Debug.AspNetCompiler.Debug = "True"
        Release.AspNetCompiler.VirtualPath = "/WebSite1"
        Release.AspNetCompiler.PhysicalPath = "..\..\WebSites\WebSite1\"
        Release.AspNetCompiler.TargetPath = "PrecompiledWeb\WebSite1\"
        Release.AspNetCompiler.Updateable = "true"
        Release.AspNetCompiler.ForceOverwrite = "true"
        Release.AspNetCompiler.FixedNames = "false"
        Release.AspNetCompiler.Debug = "False"
        VWDPort = "2220"
        DefaultWebSiteLanguage = "Visual Basic"
    EndProjectSection
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|.NET = Debug|.NET
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {A3EF0D1E-ABC0-4A4F-851F-EBC56FDF2C53}.Debug|.NET.ActiveCfg = Debug|.NET
        {A3EF0D1E-ABC0-4A4F-851F-EBC56FDF2C53}.Debug|.NET.Build.0 = Debug|.NET
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal
</code>```

Body:
Are the file that you have in a website alreay? Are they located in C:\Inetpub\wwwroot\[SITE_FOLDER]?

This site might help as well. http://ondotnet.com/pub/a/dotnet/excerpt/vshacks_chap1/index.html?page=4

Here is a sample solution:

Microsoft Visual Studio Solution File, Format Version 7.0
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "C:\...\WebSite1\", "..\..\WebSites\WebSite1", "{A3EF0D1E-ABC0-4A4F-851F-EBC56FDF2C53}"
    ProjectSection(WebsiteProperties) = preProject
        Debug.AspNetCompiler.VirtualPath = "/WebSite1"
        Debug.AspNetCompiler.PhysicalPath = "..\..\WebSites\WebSite1\"
        Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\WebSite1\"
        Debug.AspNetCompiler.Updateable = "true"
        Debug.AspNetCompiler.ForceOverwrite = "true"
        Debug.AspNetCompiler.FixedNames = "false"
        Debug.AspNetCompiler.Debug = "True"
        Release.AspNetCompiler.VirtualPath = "/WebSite1"
        Release.AspNetCompiler.PhysicalPath = "..\..\WebSites\WebSite1\"
        Release.AspNetCompiler.TargetPath = "PrecompiledWeb\WebSite1\"
        Release.AspNetCompiler.Updateable = "true"
        Release.AspNetCompiler.ForceOverwrite = "true"
        Release.AspNetCompiler.FixedNames = "false"
        Release.AspNetCompiler.Debug = "False"
        VWDPort = "2220"
        DefaultWebSiteLanguage = "Visual Basic"
    EndProjectSection
EndProject
Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
        Debug|.NET = Debug|.NET
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
        {A3EF0D1E-ABC0-4A4F-851F-EBC56FDF2C53}.Debug|.NET.ActiveCfg = Debug|.NET
        {A3EF0D1E-ABC0-4A4F-851F-EBC56FDF2C53}.Debug|.NET.Build.0 = Debug|.NET
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
        HideSolutionNode = FALSE
    EndGlobalSection
EndGlobal

ContentLicense: CC BY-SA 2.5


问:
Sort data with GROUP_CONCAT and COUNT
I have table produk and transaksi_detail

and then, I have two queries.

First query:

```<code>SELECT produk.idproduk, produk.nmproduk, COUNT(*) AS total
FROM produk, transaksi_detail
WHERE produk.idproduk=transaksi_detail.idproduk
GROUP BY produk.nmproduk
</code>```

The result:

```<code>idproduk   |   nmproduk    |    total_order
-------------------------------------------
I3               coffe           6
I4               pencil          2
I1               bread           6
I2               snack           7
I5               tea             2
</code>```

Second query:

```<code>SELECT GROUP_CONCAT(produk.idproduk) AS idproduk, transaksi_detail.idtransaksi
FROM produk, transaksi_detail
WHERE produk.idproduk=transaksi_detail.idproduk
GROUP BY transaksi_detail.idtransaksi
</code>```

The result:

```<code>idproduk   |   idtransaction
----------------------------
I2, I1, I5          1
I2, I4              2
I2, I3              3
I2, I1, I4          4
I1, I3              5
I2, I3              7
I1, I3              8
</code>```

How to make result like the second result but "idproduk->GROUP_CONCAT" order by based on total_order in first query.
Like this :

```<code> idproduk   |   idtransaction
----------------------------
I1, I2, I5          1
I4, I2              2
I3, I2              3
I4, I2, I1          4
I3, I1              5
I2, I3              7
I1, I3              8
</code>```

"idproduk" The first from "I2" because total_order larger than the other 'desc'.

答:
You could try   </p>

```<code>SELECT GROUP_CONCAT(order_count.idproduk ORDER BY order_count.total DESC) AS idproduk,
       transaksi_detail.idtransaksi
FROM   (SELECT produk.idproduk,
               COUNT(*) AS total
        FROM   produk,
               transaksi_detail
        WHERE  produk.idproduk = transaksi_detail.idproduk
        GROUP  BY produk.nmproduk) order_count
       INNER JOIN transaksi_detail
               ON order_count.idproduk = transaksi_detail.idproduk
GROUP BY transaksi_detail.idtransaksi
</code>```

Title: Sort data with GROUP_CONCAT and COUNT

Body:
I have table produk and transaksi_detail

and then, I have two queries.

First query:

SELECT produk.idproduk, produk.nmproduk, COUNT(*) AS total
FROM produk, transaksi_detail
WHERE produk.idproduk=transaksi_detail.idproduk
GROUP BY produk.nmproduk

The result:

idproduk   |   nmproduk    |    total_order
-------------------------------------------
I3               coffe           6
I4               pencil          2
I1               bread           6
I2               snack           7
I5               tea             2

Second query:

SELECT GROUP_CONCAT(produk.idproduk) AS idproduk, transaksi_detail.idtransaksi
FROM produk, transaksi_detail
WHERE produk.idproduk=transaksi_detail.idproduk
GROUP BY transaksi_detail.idtransaksi

The result:

idproduk   |   idtransaction
----------------------------
I2, I1, I5          1
I2, I4              2
I2, I3              3
I2, I1, I4          4
I1, I3              5
I2, I3              7
I1, I3              8

How to make result like the second result but "idproduk->GROUP_CONCAT" order by based on total_order in first query.
Like this :

 idproduk   |   idtransaction
----------------------------
I1, I2, I5          1
I4, I2              2
I3, I2              3
I4, I2, I1          4
I3, I1              5
I2, I3              7
I1, I3              8

"idproduk" The first from "I2" because total_order larger than the other 'desc'.

Body:
You could try

SELECT GROUP_CONCAT(order_count.idproduk ORDER BY order_count.total DESC) AS idproduk,
       transaksi_detail.idtransaksi
FROM   (SELECT produk.idproduk,
               COUNT(*) AS total
        FROM   produk,
               transaksi_detail
        WHERE  produk.idproduk = transaksi_detail.idproduk
        GROUP  BY produk.nmproduk) order_count
       INNER JOIN transaksi_detail
               ON order_count.idproduk = transaksi_detail.idproduk
GROUP BY transaksi_detail.idtransaksi


问:
How to track UTM tags in App Store URLs
I'm working on implementing my own analytics system. One part of it consists of tracking where users originated from. I use UTM tags for this. Reading UTM tags from the query parameters is quite easy in Android, iOS and web. However, I also want to track app installs.

I want to be able to share URLs to the Play/App store with UTM tags and mark the user's first session in the app with those tags. Android has a great solution for this: pass the referrer query parameter containing the UTM tags to the Play Store URL and after installation, the UTM tags will be available. (source: https://developers.google.com/analytics/devguides/collection/android/v4/campaigns)

However, the App store doesn't support this kind of tracking. I'm trying to figure out what the industry standard is for tracking app installs. I've seen the following solution:

Share a URL to your own domain. (e.g. myredirectdomain.com?utm_campaign=test)

Save the client ip, screen resolution and UTM tags in a DB table if the client is an iOS device

Redirect the user to the App Store

Once the user installs the app, the app will send the client ip and screen resolution to your server which checks if those are recently added in the DB.

If so, the corresponding UTM tags are returned and the user's session will be marked with those.

Of course, this will most definitely result in some false positives. I've been trying to figure how other companies do this. I've stumbled upon Google Analytics' implementation which utilizes the iPhones IDFA (source: https://developers.google.com/analytics/solutions/ios-install-tracking). However, the IDFA doesn't seem to be available to the mobile browser.

Do you know what the industry standard is for tracking app install campaigns?

答:
Short answer: there is no industry standard in attribution tracking for iOS. Just google the term "app attribution tracking" and see how many service providers show up. They all use some kind of device fingerprinting and call it their "secret sauce". I've used different services in parallel in the past and results were most of the time very different. (Localytics, Flurry, Tapstream)

The "official" recommended way from Apple is to use their own App Analytics attribution tracking. For that you add a provider token(pt=) and a campaign token (ct=) to your store links. You can get your provider token directly in iTunes Connect. You can nicely combine this with the App Store Affiliate program. The only downside is getting the information out of Apple's App Analytics/iTunes Connect. There are no official APIs to get your hands automatically on the raw data.

Sources:
https://developer.apple.com/app-store/user-acquisition-marketing/
https://developer.apple.com/app-store/app-analytics/

Title: How to track UTM tags in App Store URLs


问:
Get Alpha Percentage of image Swift
I have function to calculate alpha of image. But I got crash for iPhone 5, work well with iPhone 6 and later.

```<code>private func alphaOnlyPersentage(img: UIImage) -> Float {

    let width = Int(img.size.width)
    let height = Int(img.size.height)

    let bitmapBytesPerRow = width
    let bitmapByteCount = bitmapBytesPerRow * height

    let pixelData = UnsafeMutablePointer<UInt8>.allocate(capacity: bitmapByteCount)

    let colorSpace = CGColorSpaceCreateDeviceGray()

    let context = CGContext(data: pixelData,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: colorSpace,
                            bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.alphaOnly.rawValue).rawValue)!

    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    context.clear(rect)
    context.draw(img.cgImage!, in: rect)

    var alphaOnlyPixels = 0

    for x in 0...Int(width) {
        for y in 0...Int(height) {

            if pixelData[y * width + x] == 0 {
               alphaOnlyPixels += 1
            }
        }
    }

    free(pixelData)

    return Float(alphaOnlyPixels) / Float(bitmapByteCount)
}
</code>```

Please help me to fix! Thank you. Sorry I am newbie with iOS coding.

答:
Replace ... with ..< otherwise you are accessing one row and one column too many.

Note the crash is random depending on how the memory is allocated and whether you have access to the bytes at the given address, which is outside of the chunk allocated for you.

Or replace the iteration by simpler:

```<code>for i in 0 ..< bitmapByteCount {
    if pixelData[i] == 0 {
        alphaOnlyPixels += 1
    }
}
</code>```

You can also use Data to create your bytes, which will later simplify iteration:

```<code>var pixelData = Data(count: bitmapByteCount)

pixelData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in
    let context = CGContext(data: bytes,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)!

    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    context.clear(rect)
    context.draw(img.cgImage!, in: rect)
}

let alphaOnlyPixels = pixelData.filter { $0 == 0 }.count
</code>```

Title: Get Alpha Percentage of image Swift

Body:
I have function to calculate alpha of image. But I got crash for iPhone 5, work well with iPhone 6 and later.

private func alphaOnlyPersentage(img: UIImage) -> Float {

    let width = Int(img.size.width)
    let height = Int(img.size.height)

    let bitmapBytesPerRow = width
    let bitmapByteCount = bitmapBytesPerRow * height

    let pixelData = UnsafeMutablePointer<UInt8>.allocate(capacity: bitmapByteCount)

    let colorSpace = CGColorSpaceCreateDeviceGray()

    let context = CGContext(data: pixelData,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: colorSpace,
                            bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.alphaOnly.rawValue).rawValue)!

    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    context.clear(rect)
    context.draw(img.cgImage!, in: rect)

    var alphaOnlyPixels = 0

    for x in 0...Int(width) {
        for y in 0...Int(height) {

            if pixelData[y * width + x] == 0 {
               alphaOnlyPixels += 1
            }
        }
    }

    free(pixelData)

    return Float(alphaOnlyPixels) / Float(bitmapByteCount)
}

Please help me to fix! Thank you. Sorry I am newbie with iOS coding.

Body:
Replace ... with ..< otherwise you are accessing one row and one column too many.

Note the crash is random depending on how the memory is allocated and whether you have access to the bytes at the given address, which is outside of the chunk allocated for you.

Or replace the iteration by simpler:

for i in 0 ..< bitmapByteCount {
    if pixelData[i] == 0 {
        alphaOnlyPixels += 1
    }
}

You can also use Data to create your bytes, which will later simplify iteration:

var pixelData = Data(count: bitmapByteCount)

pixelData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in
    let context = CGContext(data: bytes,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)!

    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    context.clear(rect)
    context.draw(img.cgImage!, in: rect)
}

let alphaOnlyPixels = pixelData.filter { $0 == 0 }.count


问:
How to get a distribution app when using xcodebuild -exportArchive (Xcode8.3, Auto Signing)?
After update Xcode8.3, the options '-exportSigningIdentity', '-exportProvisioningProfile' and '-exportFormat' are removed from  'xcodebuild -exportArchive'.

When i try to get a distribution app, i get the error below:
 xcodebuild: error: invalid option '-exportProvisioningProfile'.

So how can i get distribution MyApp.ipa from MyApp.xcarchive, when the project has set Automatic Signing Enabled?

Automatic Signing

答:
Sounds like you want to create an IPA on the command line from an existing xcarchive. Since Xcode 7, the preferred way to do this is (from man xcodebuild):

```<code>xcodebuild -exportArchive -archivePath xcarchivepath -exportPath destinationpath -exportOptionsPlist path
</code>```

So in your case:

```<code>xcodebuild -exportArchive -archivePath MyApp.xcarchive -exportPath MyApp.ipa -exportOptionsPlist exportOptions.plist
</code>```

exportOptions.plist is a PLIST file that contains various parameters configuring the IPA export. See xcodebuild -help for all available options. You'll have to at least specifiy an entry for method (app-store, ad-hoc, enterprise etc. - defaults to development). If you just want to export for App-Store distribution, the file should look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>method</key>
    <string>app-store</string>
</dict>
</plist>
</code>```

Body:
Sounds like you want to create an IPA on the command line from an existing xcarchive. Since Xcode 7, the preferred way to do this is (from man xcodebuild):

xcodebuild -exportArchive -archivePath xcarchivepath -exportPath destinationpath -exportOptionsPlist path

So in your case:

xcodebuild -exportArchive -archivePath MyApp.xcarchive -exportPath MyApp.ipa -exportOptionsPlist exportOptions.plist

exportOptions.plist is a PLIST file that contains various parameters configuring the IPA export. See xcodebuild -help for all available options. You'll have to at least specifiy an entry for method (app-store, ad-hoc, enterprise etc. - defaults to development). If you just want to export for App-Store distribution, the file should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>method</key>
    <string>app-store</string>
</dict>
</plist>


问:
Index of multiple minimum elements in a list
I want a list

```<code>a = [2,4,5,2]
</code>```

to give

```<code>b = [0, 3]
</code>```

I know how to do it for when there is only a single min element, but not multiple min elements.
example:

```<code>b = a.index(min(a))
</code>```

This will give me b = 0.

答:
Find the minimum value, then iterate the list with index using enumerate to find the minimum values:

```<code>>>> a = [2,4,5,2]
>>> min_value = min(a)
>>> [i for i, x in enumerate(a) if x == min_value]
[0, 3]
</code>```

Body:
I want a list

a = [2,4,5,2]

to give

b = [0, 3]

I know how to do it for when there is only a single min element, but not multiple min elements.
example:

b = a.index(min(a))

This will give me b = 0.

Body:
Find the minimum value, then iterate the list with index using enumerate to find the minimum values:

>>> a = [2,4,5,2]
>>> min_value = min(a)
>>> [i for i, x in enumerate(a) if x == min_value]
[0, 3]


问:
Cast context of functional interface in lambda expression
There's an example of casting a functional interface (as I understand it) in a cast context: https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html with a code example:

```<code> // Cast context
 stream.map((ToIntFunction) e -> e.getSize())...
</code>```

It is described as "Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context".

I've tried to use ToIntFunction with stream().mapTo() but could only use it with stream().mapToInt() and also not using the cast.

Could someone please provide an example how to use the cast context example?
I've tried this:

```<code>// dlist is a list of Doubles
dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)
</code>```

but it works without (ToIntFunction). When do I need the cast context anyway?

Also what is the purpose of mapToInt. This seems to be equivalent:

```<code>dlist.stream().mapToInt(d -> d.intValue()).forEach(System.out::println);

dlist.stream().map(d -> d.intValue()).forEach(System.out::println);
</code>```

答:
mapToInt is used to return a stream of int primitive type, which could have performance benefits over a stream of Integer.
The same is true for the toIntFunction, which returns a function of int primitive type.

Body:
There's an example of casting a functional interface (as I understand it) in a cast context: https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html with a code example:

 // Cast context
 stream.map((ToIntFunction) e -> e.getSize())...

It is described as "Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context".

I've tried to use ToIntFunction with stream().mapTo() but could only use it with stream().mapToInt() and also not using the cast.

Could someone please provide an example how to use the cast context example?
I've tried this:

// dlist is a list of Doubles
dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)

but it works without (ToIntFunction). When do I need the cast context anyway?

Also what is the purpose of mapToInt. This seems to be equivalent:

dlist.stream().mapToInt(d -> d.intValue()).forEach(System.out::println);

dlist.stream().map(d -> d.intValue()).forEach(System.out::println);


问:
Ngrx Store, Effects, Http Ajax Polling Setup on Angular 2
I'm creating an Ngrx Angular 2 app and was trying to get my http calls to continue polling after a time interval. I have seen the use of the interval() function, but in case of Ngrx, when service calls are done inside @Effect(), it gives an error. Please advise:

```<code>@Injectable()
export class TasksEffects {
constructor(
    private actions$: Actions,
    private TS: TaskService
){}

@Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    });
</code>```

I want to run the switchMap function every ten seconds. This does not work.

```<code>    @Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    }).interval(10000);
</code>```

The type error is:

答:
In rxjs 5 interval() is a static function. You can only use it as a creator Observable.interval(1).

Try this.

```<code>this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
  .skipUntil(Observable.interval(10000))
  .switchMap(res => {...})
</code>```

Body:
I'm creating an Ngrx Angular 2 app and was trying to get my http calls to continue polling after a time interval. I have seen the use of the interval() function, but in case of Ngrx, when service calls are done inside @Effect(), it gives an error. Please advise:

@Injectable()
export class TasksEffects {
constructor(
    private actions$: Actions,
    private TS: TaskService
){}

@Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    });

I want to run the switchMap function every ten seconds. This does not work.

    @Effect()
onLoadTasksLoadTasks$: Observable<Action> = this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
    .switchMap(() => {
        return this.TS.index()
            .map((res) => new tasksActions.LoadTasksSuccessAction(res.json()))
            .catch(err => of(new tasksActions.LoadTasksFailAction(err)));
    }).interval(10000);

The type error is:

Body:
In rxjs 5 interval() is a static function. You can only use it as a creator Observable.interval(1).

Try this.

this.actions$.ofType(tasksActions.ActionTypes.LOAD_TASKS)
  .skipUntil(Observable.interval(10000))
  .switchMap(res => {...})


问:
Same RewriteCond and multiple RewriteRule
I've got in my application some review rules here's example:

```<code>RewriteCond %{HTTP_HOST} ^(.*)-street\.
RewriteRule ^(.*)/(.*)\.html$ index.php?street=%1&$1=$2 [L]
RewriteCond %{HTTP_HOST} ^(.*)-street\.
RewriteRule ^(.*)$ index.php?street=%1 [L]
</code>```

I expect if I type: example-street.example.com/type/param.html that it use this rule:

```<code>RewriteRule ^(.*)/(.*)\.html$ index.php?street=%1&$1=$2 [L]
</code>```

but unfortunately it use less specified one.

What should I add/change in my code to get expected result?

EDIT
I want to achive this result:

example-street.example.com/type/param.html -> index.php?street=example&type=param
example-street.example.com/whateverelse -> index.php?street=example

答:
Check this, hope it will work fine.

Check .htaccess here

```<code>RewriteEngine on
RewriteCond %{REQUEST_URI} ^/type/param.html$
RewriteCond %{HTTP_HOST} ([a-z]+)\-([a-z]+)\.example\.com$
RewriteRule ^([a-z]+)\/([a-z]+)\.html$ /index.php?%2=%1&$1=$2    [R=301,L,QSA]

RewriteCond %{REQUEST_URI} ^/[a-z]+$
RewriteCond %{HTTP_HOST} ([a-z]+)\-([a-z]+)\.example\.com$
RewriteRule ^.*$ /index.php?%2=%1    [R=301,L,QSA]
</code>```

Body:
I've got in my application some review rules here's example:

RewriteCond %{HTTP_HOST} ^(.*)-street\.
RewriteRule ^(.*)/(.*)\.html$ index.php?street=%1&$1=$2 [L]
RewriteCond %{HTTP_HOST} ^(.*)-street\.
RewriteRule ^(.*)$ index.php?street=%1 [L]

I expect if I type: example-street.example.com/type/param.html that it use this rule:

RewriteRule ^(.*)/(.*)\.html$ index.php?street=%1&$1=$2 [L]

but unfortunately it use less specified one.

What should I add/change in my code to get expected result?

EDIT
I want to achive this result:

example-street.example.com/type/param.html -> index.php?street=example&type=param
example-street.example.com/whateverelse -> index.php?street=example

Body:
Check this, hope it will work fine.

Check .htaccess here

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/type/param.html$
RewriteCond %{HTTP_HOST} ([a-z]+)\-([a-z]+)\.example\.com$
RewriteRule ^([a-z]+)\/([a-z]+)\.html$ /index.php?%2=%1&$1=$2    [R=301,L,QSA]

RewriteCond %{REQUEST_URI} ^/[a-z]+$
RewriteCond %{HTTP_HOST} ([a-z]+)\-([a-z]+)\.example\.com$
RewriteRule ^.*$ /index.php?%2=%1    [R=301,L,QSA]


问:
Which tools to build a SOAP server in PHP?
We are investigating options to build a SOAP webservice in PHP. We have some requirements:

Authentication via SOAP Headers

HTTPS

Fine control over XML used in SOAP response

Good documentation and support community.

(Optional) WS Security support

There's the following tools providing such functionality:

Native PHP SoapServer

Zend_Soap

NuSoap

WSO2 WSF/PHP

PEAR::SOAP

Zend_Soap is actually a framework-compatible wrapper for the native PHP Soap-implementation. We have some simple tests running, but SOAP headers are not supported, and we don't have full control over the XML response. For instance, the response XML has a namespace on the root element, but not on it's child elements. Pretty annoying.

NuSoap is not really maintained anymore and I have read it has some issues with PHP 5.3 naming conventions.

WSO2 WSF/PHP uses a php extension which has to be compiled manually. There are some dependencies and the entire compile process is not clearly documented. The documentation is scattered around the website (sometimes outdated) and in the packaged downloads. A linux binary is mentioned, but nowhere provided for download (at least not in the last 5/6 releases).

I don't really know a lot about PEAR::SOAP, but I have some experience with PEAR classes. Usually they are not well-documented and do not catch errors gracefully, leaving you googling every error message, with varying outcomes.

Do you know of any other tools that can help me build a full-fledged SOAP server in PHP, considering our requirements?

答:
If you need WS-Security, then WSO2 might be your only option. Did you install all the prerequisite packages (openssl, libxml2) before compiling. Compilation is simple with ./configure, make && make install (I didn't have any issues with 2.1.0 wrt. compiling). WSO2 offers full control of the payload XML structure.

If you can live without WS-Security, then any of the other options are good. I'd recommend PHP's own SOAP library. It's pretty decent, but doesn't offer very good control over the XML and lacks WSDL autogeneration.


答:
You can do that using numpy in the following way:</p>

```<code>import numpy as np
a = np.array([2,4,5,2])
np.where(a==a.min())
</code>```

Title: Index of multiple minimum elements in a list

Body:
You can do that using numpy in the following way:

import numpy as np
a = np.array([2,4,5,2])
np.where(a==a.min())


问:
jquery nested sortable list
i have this code

```<code>$(document).ready(function() {
    $("#test-list").sortable({
        items: "> li",
        handle : '.handle',
        axis: 'y',
        opacity: 0.6,
        update : function () {
            var order = $('#test-list').sortable('serialize');
            $("#info").load("process-sortable.asp?"+order+"&id=catid&order=orderid&table=tblCats");
        }
    });
    $("#test-sub").sortable({
        containment: "ul",
        items: "li",
        handle : '.handle',
        axis: 'y',
        opacity: 0.6,
        update : function () {
            var order = $('#test-list').sortable('serialize');
            $("#info").load("process-sortable.asp?"+order+"&id=catid&order=orderid&table=tblCats");
        }
    });
});
</code>```

for this kind of UL

```<code><ul id="test-list">
  <li></li>
  <li>
    <ul id="test-sub">
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
   </ul>
  </li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
</code>```

but it can be changed dynamiclly...
when i drag and drop the main li it is working
when i do it with the childs it will drag the main one

what is wrong?

答:
I wrote a drag and drop script specially designed for nested structures
Check it out...
https://supraniti.github.io/Lean-Mean-Drag-and-Drop/</p>

Title: jquery nested sortable list

Body:
i have this code

$(document).ready(function() {
    $("#test-list").sortable({
        items: "> li",
        handle : '.handle',
        axis: 'y',
        opacity: 0.6,
        update : function () {
            var order = $('#test-list').sortable('serialize');
            $("#info").load("process-sortable.asp?"+order+"&id=catid&order=orderid&table=tblCats");
        }
    });
    $("#test-sub").sortable({
        containment: "ul",
        items: "li",
        handle : '.handle',
        axis: 'y',
        opacity: 0.6,
        update : function () {
            var order = $('#test-list').sortable('serialize');
            $("#info").load("process-sortable.asp?"+order+"&id=catid&order=orderid&table=tblCats");
        }
    });
});

for this kind of UL

but it can be changed dynamiclly...
when i drag and drop the main li it is working
when i do it with the childs it will drag the main one

what is wrong?


问:
how to making an idle game using java
hi i'm tring to make idle game,
but i have some problem i want that every one sec X money will add to the player's currency
and to show the value in Jframe
i know to use with Threads but i dont know how.

```<code>package idle;
</code>```

class MyThread extends Thread{

```<code>int cash;
    public MyThread(String name) {
        super(name);
    }

public void run() {

    while(true){

        try {
            cash++;
            Thread.sleep(1000);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
        System.out.println(getName()+ " " + cash);
    }
</code>```

答:
```<code>public MyThread(String name, ThreadContext context) {
    super(name);
    this.context = context;
}
</code>```

class ThreadContext

```<code>public class ThreadContext {
    private int cash;
}
</code>```

Title: how to making an idle game using java

Body:
hi i'm tring to make idle game,
but i have some problem i want that every one sec X money will add to the player's currency
and to show the value in Jframe
i know to use with Threads but i dont know how.

package idle;

class MyThread extends Thread{

int cash;
    public MyThread(String name) {
        super(name);
    }

public void run() {

    while(true){

        try {
            cash++;
            Thread.sleep(1000);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
        System.out.println(getName()+ " " + cash);
    }

Body:
public MyThread(String name, ThreadContext context) {
    super(name);
    this.context = context;
}

class ThreadContext

public class ThreadContext {
    private int cash;
}


问:
Content assist failure for nested class constructors in Eclipse Neon.2
If I want to create a new class that is a static nested class, content assist fails to match the constructor, and this is very unconvenient.

How to configure content assist to match static nested classes' constructors like this TifImageSource?

```<code>public class ImageSources {

public static class TifImageSource extends ImageSource {
    public TifImageSource(Provider<InputStream> inputStreamProvider) {
        super(inputStreamProvider, "tif");
    }
}

public static class ImageSource {
   ....
}
</code>```

}

This not works (with new keyword):

This works (but unconvenient!):

答:
Go with the rules of Java syntax instead of fighting them.

Start with new ImageSources or new ImageS plus content assistance.

Add a period.

```<code>new ImageSources.
</code>```

Then start typing the nested class name (it's not an inner class or the syntax would be different).

```<code>new ImageSources.TifIm
</code>```

Content assistance should then be able to cue you for

```<code>new ImageSources.TifImageSource(...)
</code>```

Body:
If I want to create a new class that is a static nested class, content assist fails to match the constructor, and this is very unconvenient.

How to configure content assist to match static nested classes' constructors like this TifImageSource?

public class ImageSources {

public static class TifImageSource extends ImageSource {
    public TifImageSource(Provider<InputStream> inputStreamProvider) {
        super(inputStreamProvider, "tif");
    }
}

public static class ImageSource {
   ....
}

}

This not works (with new keyword):

This works (but unconvenient!):

Body:
Go with the rules of Java syntax instead of fighting them.

Start with new ImageSources or new ImageS plus content assistance.

Add a period.

new ImageSources.

Then start typing the nested class name (it's not an inner class or the syntax would be different).

new ImageSources.TifIm

Content assistance should then be able to cue you for

new ImageSources.TifImageSource(...)


问:
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?

答:
This issue is related to the path variable setting. Quoting from another SO post:

fire up your interpreter and add this line: export PATH=/Users/add
  your username here/anaconda/bin:$PATH

Now type python into the interpreter and you will see Anaconda 1.8.0
  or whatever version you have. You will have to do this each time you
  start a new interpreter.

Also, note that this might occur when the user name in the path on windows contains a space character. Taken from here.

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?