问:
Python: Assistance with json and reading from a file
Say i have a notepad file (.txt) with the following content:

```<code>"Hello I am really bad at programming"
</code>```

Using json, how would I get the sentence from the file to the python program which I can then use as a variable?

So far I have this code:

```<code>newfile = open((compfilename)+'.txt', 'r')

saveddata = json.load(newfile)

orgsentence = saveddata[0]
</code>```

I always get this error:

```<code>   return codecs.ascii_decode(input, self.errors)[0]
   UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0:           ordinal not in range(128)
</code>```

Thanks in advance for any help!

答:
Though you are using txt file. You could read this file without json. But as you mentioned in the question, you can try like this

hello.txt

```<code>"Hello I am really bad at programming"
</code>```

To read this txt file,

```<code>import json
from pprint import pprint

with open('hello.txt') as myfile:
    mydata = json.load(myfile) #to load json
    print myfile.read() #to print contents on stdout, not using json load

pprint(mydata)
</code>```

Output:

```<code>u'Hello I am really bad at programming'
</code>```

Body:
Say i have a notepad file (.txt) with the following content:

"Hello I am really bad at programming"

Using json, how would I get the sentence from the file to the python program which I can then use as a variable?

So far I have this code:

newfile = open((compfilename)+'.txt', 'r')

saveddata = json.load(newfile)

orgsentence = saveddata[0]

I always get this error:

   return codecs.ascii_decode(input, self.errors)[0]
   UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0:           ordinal not in range(128)

Thanks in advance for any help!

Body:
Though you are using txt file. You could read this file without json. But as you mentioned in the question, you can try like this

hello.txt

"Hello I am really bad at programming"

To read this txt file,

import json
from pprint import pprint

with open('hello.txt') as myfile:
    mydata = json.load(myfile) #to load json
    print myfile.read() #to print contents on stdout, not using json load

pprint(mydata)

Output:

u'Hello I am really bad at programming'


来源: stackexchange

问:
Send JSON string (array) from Javascript to PHP via POST
for hours I try to find a simple solution to send a ready JSON string to a PHP method.
Javascript part:

```<code>form = document.createElement("form"),
node = document.createElement("input");
var element1 = document.createElement("input");
form.method = "POST";
element1.value='[{"id": 110, "teamname": "first"}, {"id": 140, "teamname": "second"}]';
element1.name="teams";
form.appendChild(element1);
form.appendChild(node.cloneNode());
form.action = "?updateTeamnames";
form.style.display = "none";
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
</code>```

PHP:
If I echo the raw data with (echo file_get_contents('php://input');). I get this:

```<code>teams=%5B%7B%22id%22%3A+110%2C+%22teamname%22%3A+%22first%22%7D%2C+%7B%22id%22%3A+140%2C+%22teamname%22%3A+%22second%22%7D%5D
</code>```

How can I access the JSON string teams?
I tried this:

```<code>$data = json_decode(file_get_contents('php://input'), true);
echo $data;
</code>```

without success. I think $data is NULL.

I tried this:

```<code>echo $_POST['teams'];
</code>```

which led me to this:

```<code>[{\“id\“: 110, \“teamname\“: \“first\“}, {\“id\“: 140, \“teamname\“: \“second\“}]
</code>```

Which can't be used as string in json_decode.

The main problem is, that I don't know which part is wrong...

Thanks for helping

答:
You can use jQuery.ajax to post data as below:

```<code><script>
jQuery.ajax('./?updateTeamnames', {
    method: 'POST',
    data: {teams: [{id: 110, teamname: "first"}, {id: 140, teamname: "second"}]}
});
</script>
</code>```

In PHP script, you can see your data by dump:

```<code>var_dump($_POST['teams']);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
for hours I try to find a simple solution to send a ready JSON string to a PHP method.
Javascript part:

form = document.createElement("form"),
node = document.createElement("input");
var element1 = document.createElement("input");
form.method = "POST";
element1.value='[{"id": 110, "teamname": "first"}, {"id": 140, "teamname": "second"}]';
element1.name="teams";
form.appendChild(element1);
form.appendChild(node.cloneNode());
form.action = "?updateTeamnames";
form.style.display = "none";
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);

PHP:
If I echo the raw data with (echo file_get_contents('php://input');). I get this:

teams=%5B%7B%22id%22%3A+110%2C+%22teamname%22%3A+%22first%22%7D%2C+%7B%22id%22%3A+140%2C+%22teamname%22%3A+%22second%22%7D%5D

How can I access the JSON string teams?
I tried this:

$data = json_decode(file_get_contents('php://input'), true);
echo $data;

without success. I think $data is NULL.

I tried this:

echo $_POST['teams'];

which led me to this:

[{\“id\“: 110, \“teamname\“: \“first\“}, {\“id\“: 140, \“teamname\“: \“second\“}]

Which can't be used as string in json_decode.

The main problem is, that I don't know which part is wrong...

Thanks for helping

Body:
You can use jQuery.ajax to post data as below:

<script>
jQuery.ajax('./?updateTeamnames', {
    method: 'POST',
    data: {teams: [{id: 110, teamname: "first"}, {id: 140, teamname: "second"}]}
});
</script>

In PHP script, you can see your data by dump:

var_dump($_POST['teams']);


问:
Cloned element is not shown
The following code should clone the given element and insert it after:

```<code>function cloneMore(element) {
    var newElement = element.cloneNode(true);
    element.parentNode.insertBefore(newElement, element.nextSibling);
}
var addChoice = document.getElementById("add-choice")
addChoice.onclick = (function(){cloneMore(document.getElementById("choices").lastChild);})
</code>```

The html looks like this:

```<code><ul id="choices">
    <!-- form elements -->
</ul>
<p><a id="add-choice">Add another choice</a></p>
</code>```

No exception is thrown and everything executes but I can not see the new element. Why?

答:
lastChild picks all node types, not only Elements. So you are probably cloning a TextNode \n.

I guess that what you want is lastElementChild.

function cloneMore(element) {
  var newElement = element.cloneNode(true);
  element.parentNode.insertBefore(newElement, element.nextSibling);
}
var addChoice = document.getElementById("add-choice")
addChoice.onclick = function() {
  var choices = document.getElementById("choices");
  cloneMore(choices.lastElementChild); // only Elements
  console.log('lastChild type : ', choices.lastChild.nodeName);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="choices">
  <li> choice </li>
</ul>
<p>Add another choice</p></code>```

Title: Cloned element is not shown

Body:
The following code should clone the given element and insert it after:

function cloneMore(element) {
    var newElement = element.cloneNode(true);
    element.parentNode.insertBefore(newElement, element.nextSibling);
}
var addChoice = document.getElementById("add-choice")
addChoice.onclick = (function(){cloneMore(document.getElementById("choices").lastChild);})

The html looks like this:

Add another choice

No exception is thrown and everything executes but I can not see the new element. Why?

Body:
lastChild picks all node types, not only Elements. So you are probably cloning a TextNode \n.

I guess that what you want is lastElementChild.

function cloneMore(element) {
  var newElement = element.cloneNode(true);
  element.parentNode.insertBefore(newElement, element.nextSibling);
}
var addChoice = document.getElementById("add-choice")
addChoice.onclick = function() {
  var choices = document.getElementById("choices");
  cloneMore(choices.lastElementChild); // only Elements
  console.log('lastChild type : ', choices.lastChild.nodeName);
}

<ul id="choices">
  <li> choice </li>
</ul>
<p><a href="#" id="add-choice">Add another choice</a></p>


问:
Android : How to embed a custom view into a constraint layout?
I have a custom view with animation and I need to somehow get it in the constraint layout. Here is a little example of what I mean. I basically need a small area where I can use custom animations/bitmaps and all that stuff.

So far I've only managed to apply the view on all the screen with:
setContentView(customView).

customView:

```<code>public class CrashView extends View {

private int width, height,bheight, bwidth, boxwidth, boxheight;
private float x,y,vx,vy;

private Bitmap bullet;
private Paint AA = new Paint(Paint.ANTI_ALIAS_FLAG);

public CrashView (Context context){
    super(context);

    Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    bullet = BitmapFactory.decodeResource(getResources(), R.drawable.bullet);
    bullet = Bitmap.createScaledBitmap(bullet, bullet.getWidth()/5, bullet.getHeight()/5, true);

    width = size.x;
    height = size.y;

    bheight = bullet.getHeight();
    bwidth = bullet.getWidth();

    boxheight = height / 4;
    boxwidth = (width / 20) * 19;

    x = (width/20)/4;
    y = boxheight-bheight/4*3;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    vy = -0.1f - (float) ((Math.pow(x / 600, 2)) / 1.25);

    x += vx;
    y += vy;

    canvas.drawBitmap(bullet, x, y, AA);
    invalidate();
}
</code>```

答:
Combined your code with the code for onMeasure from the answer I mentioned in comments:

```<code>public class CrashView extends View {

    private int width, height, bheight, bwidth, boxwidth, boxheight;
    private float x, y, vx, vy;

    private Bitmap bullet;
    private Paint AA = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CrashView(Context context) {
        super(context);
        init(context);
    }

    public CrashView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CrashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CrashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context ctx) {

        Display display = ((Activity) ctx).getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        //REPLACE DRAWABLE HERE
        bullet = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        bullet = Bitmap.createScaledBitmap(bullet, bullet.getWidth() / 5, bullet.getHeight() / 5, true);

        width = size.x;
        height = size.y;

        bheight = bullet.getHeight();
        bwidth = bullet.getWidth();

        boxheight = height / 4;
        boxwidth = (width / 20) * 19;

        x = (width / 20) / 4;
        y = boxheight - bheight / 4 * 3;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int desiredWidth = boxwidth;
        int desiredHeight = boxwidth;

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            //Must be this size
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            width = Math.min(desiredWidth, widthSize);
        } else {
            //Be whatever you want
            width = desiredWidth;
        }

        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            //Must be this size
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            height = Math.min(desiredHeight, heightSize);
        } else {
            //Be whatever you want
            height = desiredHeight;
        }

        //MUST CALL THIS
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        vy = -0.1f - (float) ((Math.pow(x / 600, 2)) / 1.25);

        x += vx;
        y += vy;

        canvas.drawBitmap(bullet, x, y, AA);
        invalidate();
    }
}
</code>```

The XMl is as simple as:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root">

    <com.test.myapplication.CrashView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>
</code>```

Here is the layout with displaying bounds on:

Things to keep in mind:

Magic numbers - you got quite a few of those here, you know best what are they for but it's better to keep them as named constants

View size depends on size of a screen. This might not be a good idea. It should depend on the size of the resource you are drawing.

I used relative layout but it should be no different with constraint layout.

Extra constructors that appeared were needed for XML inflation

Body:
I have a custom view with animation and I need to somehow get it in the constraint layout. Here is a little example of what I mean. I basically need a small area where I can use custom animations/bitmaps and all that stuff.

So far I've only managed to apply the view on all the screen with:
setContentView(customView).

customView:

public class CrashView extends View {

private int width, height,bheight, bwidth, boxwidth, boxheight;
private float x,y,vx,vy;

private Bitmap bullet;
private Paint AA = new Paint(Paint.ANTI_ALIAS_FLAG);

public CrashView (Context context){
    super(context);

    Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    bullet = BitmapFactory.decodeResource(getResources(), R.drawable.bullet);
    bullet = Bitmap.createScaledBitmap(bullet, bullet.getWidth()/5, bullet.getHeight()/5, true);

    width = size.x;
    height = size.y;

    bheight = bullet.getHeight();
    bwidth = bullet.getWidth();

    boxheight = height / 4;
    boxwidth = (width / 20) * 19;

    x = (width/20)/4;
    y = boxheight-bheight/4*3;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    vy = -0.1f - (float) ((Math.pow(x / 600, 2)) / 1.25);

    x += vx;
    y += vy;

    canvas.drawBitmap(bullet, x, y, AA);
    invalidate();
}

Body:
Combined your code with the code for onMeasure from the answer I mentioned in comments:

public class CrashView extends View {

    private int width, height, bheight, bwidth, boxwidth, boxheight;
    private float x, y, vx, vy;

    private Bitmap bullet;
    private Paint AA = new Paint(Paint.ANTI_ALIAS_FLAG);

    public CrashView(Context context) {
        super(context);
        init(context);
    }

    public CrashView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CrashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CrashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context ctx) {

        Display display = ((Activity) ctx).getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        //REPLACE DRAWABLE HERE
        bullet = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        bullet = Bitmap.createScaledBitmap(bullet, bullet.getWidth() / 5, bullet.getHeight() / 5, true);

        width = size.x;
        height = size.y;

        bheight = bullet.getHeight();
        bwidth = bullet.getWidth();

        boxheight = height / 4;
        boxwidth = (width / 20) * 19;

        x = (width / 20) / 4;
        y = boxheight - bheight / 4 * 3;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int desiredWidth = boxwidth;
        int desiredHeight = boxwidth;

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        int height;

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            //Must be this size
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            width = Math.min(desiredWidth, widthSize);
        } else {
            //Be whatever you want
            width = desiredWidth;
        }

        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            //Must be this size
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            height = Math.min(desiredHeight, heightSize);
        } else {
            //Be whatever you want
            height = desiredHeight;
        }

        //MUST CALL THIS
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        vy = -0.1f - (float) ((Math.pow(x / 600, 2)) / 1.25);

        x += vx;
        y += vy;

        canvas.drawBitmap(bullet, x, y, AA);
        invalidate();
    }
}

The XMl is as simple as:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root">

    <com.test.myapplication.CrashView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

Here is the layout with displaying bounds on:

Things to keep in mind:

Magic numbers - you got quite a few of those here, you know best what are they for but it's better to keep them as named constants

View size depends on size of a screen. This might not be a good idea. It should depend on the size of the resource you are drawing.

I used relative layout but it should be no different with constraint layout.

Extra constructors that appeared were needed for XML inflation


问:
onClick handler is triggered on each render cycle
I have default state like this

```<code>this.state = {
  selectedTab : 'tab1'
}
</code>```

then

My render method like this

```<code>render(){
   const { selectedTab } = this.state;
   return(
      <li>tab1</li><li>tab2</li>
      <div id="content">
         {selectedTab == 'tab1' ? this.renderTab1Content() : this.renderTab2Content()}
      </div>
   )
}
</code>```

Everything worked above. But I failed to implement switch tab using click event.

I tried to bind onclick event on my li to change the state of selectedTab, but I got infinity loop error. Like this

```<code><li onClick={this.setState({selectedTab :'tab1'})}>Tab 1</li>
<li onClick={this.setState({selectedTab :'someothertab'})}>Tab 2/li>
</code>```

Why?

答:
This error happens because you onClick handler expects a function but you have called a statement to setState on the event and hence everytime you state changes using setState, the render is called again and hence the onClick again calls the setState which triggers an infinite loop. You can do  this by using an arrow function in onClick event or calling a separate function

```<code><li onClick={() => this.setState({selectedTab :'tab1'})}>Tab 1</li>
</code>```

or

```<code>handleClick = () =>{
    this.setState({selectedTab :'tab1'})
}

<li onClick={this.handleClick}>Tab 1</li>
</code>```

Body:
I have default state like this

this.state = {
  selectedTab : 'tab1'
}

then

My render method like this

render(){
   const { selectedTab } = this.state;
   return(

tab1

tab2

         {selectedTab == 'tab1' ? this.renderTab1Content() : this.renderTab2Content()}

   )
}

Everything worked above. But I failed to implement switch tab using click event.

I tried to bind onclick event on my li to change the state of selectedTab, but I got infinity loop error. Like this

Tab 1

Tab 2/li>

Why?

Body:
This error happens because you onClick handler expects a function but you have called a statement to setState on the event and hence everytime you state changes using setState, the render is called again and hence the onClick again calls the setState which triggers an infinite loop. You can do  this by using an arrow function in onClick event or calling a separate function

<li onClick={() => this.setState({selectedTab :'tab1'})}>Tab 1</li>

or

handleClick = () =>{
    this.setState({selectedTab :'tab1'})
}

<li onClick={this.handleClick}>Tab 1</li>


问:
SignTool returns "The filename, directory name, or volume label...." error
I am trying to code-sign my dlls using the SignTool and Post Build Events. I use this method:

```<code>“C:\Program Files (x86)\Windows Kits\8.1\bin\x86\signtool.exe” sign /f “$(ProjectDir)archilabCertificate.pfx” /t http://timestamp.comodoca.com/authenticode /p “mypassword” "$(TargetPath)"
</code>```

my certificate is located in the specified folder.

```<code>ProjectDir = D:\Google Drive\Work\GrimshawTools\GrimshawRibbon\GrimshawRibbon
TargetPath = C:\ProgramData\Autodesk\Revit\Addins\2016\GrimshawRibbon.dll
</code>```

There is nothing that I can think of that could be causing this issue. I checked these paths about 100 times. I tried moving the PFX file to C drive. I tried specifying direct path to the file instead of using shorthands. I can't think of anything. Else. Ideas? How can I even debug this to find exactly what's causing the issue? I have other post builds that are working just fine.

Cheers!

Ps. I use the same certificate on my home machine and it works just fine.

答:
The [ ” ] character is invalid! use [ " ] character.
[“]C:\Program Files (x86)\Windows Kits\8.1\bin\x86\signtool.exe[”] sign /f “$(ProjectDir)archilabCertificate.pfx” /t http://timestamp.comodoca.com/authenticode /p [“]mypassword[”] "$(TargetPath)"

Body:
I am trying to code-sign my dlls using the SignTool and Post Build Events. I use this method:

“C:\Program Files (x86)\Windows Kits\8.1\bin\x86\signtool.exe” sign /f “$(ProjectDir)archilabCertificate.pfx” /t http://timestamp.comodoca.com/authenticode /p “mypassword” "$(TargetPath)"

my certificate is located in the specified folder.

ProjectDir = D:\Google Drive\Work\GrimshawTools\GrimshawRibbon\GrimshawRibbon
TargetPath = C:\ProgramData\Autodesk\Revit\Addins\2016\GrimshawRibbon.dll

There is nothing that I can think of that could be causing this issue. I checked these paths about 100 times. I tried moving the PFX file to C drive. I tried specifying direct path to the file instead of using shorthands. I can't think of anything. Else. Ideas? How can I even debug this to find exactly what's causing the issue? I have other post builds that are working just fine.

Cheers!

Ps. I use the same certificate on my home machine and it works just fine.


问:
LDAP Search String for Two OUs
I am looking to include two separate OUs in an LDAP search string.  I've searched for answers and found some but none seem to work once I include the second OU.  Specifically, this is to narrow down a scan to email list on a Canon Copier.  The following string works on a single OU:

OU=People (Staff),DC=DOMAIN1,DC=DOMAIN2,DC=com

I'd like to add a second OU so all emails included in the second OU are also available in the scan to email address search.  The second one is OU=People (Vendors)

I can remove the OU completely but the search takes too long without the extra filter.  Is this possible?  Thanks.

答:
Depends.

The Extensible Match Search Filter supports this functionality assuming that your LDAP server implementations supports that functionality. (Microsoft Active Directory does NOT support this)

```<code>(&(|(ou:dn:=People (Staff))(ou:dn:=OU=People (Vendors)))(objectclass=inetorgperson))
</code>```

Title: LDAP Search String for Two OUs

Body:
Depends.

The Extensible Match Search Filter supports this functionality assuming that your LDAP server implementations supports that functionality. (Microsoft Active Directory does NOT support this)

(&(|(ou:dn:=People (Staff))(ou:dn:=OU=People (Vendors)))(objectclass=inetorgperson))


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

答: You are naming that class "Polygon" inside a namespace where a class with that name is already present (in wingdi.h). Do you read error message?

ContentLicense: CC BY-SA 2.5

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.


问:
Update Django model using Django forms
I'm trying to update user profile in Django. That is the user model and extended member model.

The RegistrationForm is as follows:

```<code>class RegistrationForm(forms.Form):
    first_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("First name *"), 'class': 'form-control'}))
    last_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Last name *"), 'class': 'form-control'}))
    email = forms.EmailField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Email address *"), 'class': 'form-control'}))
    password = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Password *"), 'class': 'form-control'}))
    password_confirm = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Re-type your password *"), 'class': 'form-control'}))

    company_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Company name *"), 'class': 'form-control'}))
    member_id = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Member number *"), 'class': 'form-control'}))
    vat_number = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("VAT number *"), 'class': 'form-control'}))
    address = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Address *"), 'class': 'form-control'}))
    postcode = forms.CharField(label='', max_length=7, widget=forms.TextInput(attrs={'placeholder': _("Postal code *"), 'class': 'form-control'}))
    city = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("City *"), 'class': 'form-control'}))
    telephone = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Telephone *"), 'class': 'form-control'}))
    mobile = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Mobile *"), 'class': 'form-control'}))

    terms = forms.BooleanField(label="", required=False, widget=forms.CheckboxInput(attrs={'class': 'magic-checkbox'}))

    def clean(self):
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")

        if password != password_confirm:
            msg = _("The passwords do not match.")
            self.add_error('password', msg)
            self.add_error('password_confirm', msg)

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(username=self.cleaned_data['email']).exists():
            raise forms.ValidationError(_("User with the given email address already exists."))
        return email

    def clean_member_id(self):
        member_id = self.cleaned_data['member_id']
        if User.objects.filter(member__number=member_id).exists():
            raise forms.ValidationError(_("User with the given member id already exists."))
        return member_id

    def clean_terms(self):
        terms = self.cleaned_data['terms']
        if not terms:
            raise forms.ValidationError(_("Please read and accept terms and conditions."))
        return terms
</code>```

The registration view is as follows:

```<code>@transaction.atomic
def new_registration(request):
    context = {}

    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            language = Language.objects.get(key="EN")
            country = Country.objects.get(key="BE")

            user = User()
            user.username = form.cleaned_data['email']
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.email = form.cleaned_data['email']
            user.set_password(form.cleaned_data['password'])
            user.save()

            member = Member()
            member.company_name = form.cleaned_data['company_name']
            member.number = form.cleaned_data['member_id']
            member.vat_number = form.cleaned_data['vat_number']
            member.address = form.cleaned_data['address']
            member.postcode = form.cleaned_data['postcode']
            member.city = form.cleaned_data['city']
            member.country = country
            member.telephone = form.cleaned_data['telephone']
            member.mobile = form.cleaned_data['mobile']
            member.user = user
            member.language = language
            member.active = False
            member.save()

            subscription = Subscription()
            subscription.started = datetime.date.today()
            subscription.type = Type.objects.get(default=True)
            subscription.member = member
            subscription.save()

            # Send an email to user and to the manager
            send_email_with_template({
                'subject': _("The account is created"),
                'plain_template': 'master/email_templates/account_created_member.txt',
                'html_template': 'master/email_templates/account_created_member.html',
                'data_dict': {'name': user.first_name},
                'send_to': [user.email]
            })

            send_email_with_template({
                'subject': _("A new account is created"),
                'plain_template': 'master/email_templates/account_created_manager.txt',
                'html_template': 'master/email_templates/account_created_manager.html',
                'data_dict': {'user': user, 'member': member},
                'send_to': [settings.EMAIL_MANAGER]
            })

            context['form'] = RegistrationForm()
            context['success'] = _("Your account has been created successfully. "
                                   "Once your information has been processed, your account will be activated.")

            return render(request, 'master/members/new-registration.html', context)
    else:
        form = RegistrationForm()

    context['form'] = form
    return render(request, 'master/members/new-registration.html', context)
</code>```

I want now to allow users to edit their profile. But I want that they can only edit a few fields like first_name, last_name, company_name, vat_number, ...

But how to do that using RegistrationForm.

I have update view as follows:

```<code>def update_member_profile(request, user_id):
    member = Member.objects \
        .filter(user_id=user_id) \
        .values('user_id',
                'user__first_name',
                'user__last_name',
                'user__email',
                'telephone',
                'mobile',
                'company_name',
                'vat_number',
                'address',
                'postcode',
                'city'
                )[0]

    context = {'member': member}
    return render(request, 'master/members/profile_update.html', context)
</code>```

In this view I get the user that I want to edit, but how can I now use RegistrationForm to do that?

Any advice?

答:
Use disabled attribute in your form fields
https://docs.djangoproject.com/en/1.10/ref/forms/fields/

```<code>class RegistrationForm(forms.Form):
    first_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("First name *"), 'class': 'form-control'}))
    last_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Last name *"), 'class': 'form-control'}))
    email = forms.EmailField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Email address *"), 'class': 'form-control'}))
    password = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Password *"), 'class': 'form-control'}))
    password_confirm = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Re-type your password *"), 'class': 'form-control'}))

    company_name = forms.CharField(disabled=True, label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Company name *"), 'class': 'form-control'}))
    member_id = forms.CharField(disabled=True, label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Member number *"), 'class': 'form-control'}))
    vat_number = forms.CharField(disabled=True, label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("VAT number *"), 'class': 'form-control'}))
    ....
</code>```

This only works with version 1.9 and after.
another solution is to remove the field from the form all together which will basically hide it rather than disable it

Title: Update Django model using Django forms

Body:
I'm trying to update user profile in Django. That is the user model and extended member model.

The RegistrationForm is as follows:

class RegistrationForm(forms.Form):
    first_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("First name *"), 'class': 'form-control'}))
    last_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Last name *"), 'class': 'form-control'}))
    email = forms.EmailField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Email address *"), 'class': 'form-control'}))
    password = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Password *"), 'class': 'form-control'}))
    password_confirm = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Re-type your password *"), 'class': 'form-control'}))

    company_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Company name *"), 'class': 'form-control'}))
    member_id = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Member number *"), 'class': 'form-control'}))
    vat_number = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("VAT number *"), 'class': 'form-control'}))
    address = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Address *"), 'class': 'form-control'}))
    postcode = forms.CharField(label='', max_length=7, widget=forms.TextInput(attrs={'placeholder': _("Postal code *"), 'class': 'form-control'}))
    city = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("City *"), 'class': 'form-control'}))
    telephone = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Telephone *"), 'class': 'form-control'}))
    mobile = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Mobile *"), 'class': 'form-control'}))

    terms = forms.BooleanField(label="", required=False, widget=forms.CheckboxInput(attrs={'class': 'magic-checkbox'}))

    def clean(self):
        password = self.cleaned_data.get("password")
        password_confirm = self.cleaned_data.get("password_confirm")

        if password != password_confirm:
            msg = _("The passwords do not match.")
            self.add_error('password', msg)
            self.add_error('password_confirm', msg)

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(username=self.cleaned_data['email']).exists():
            raise forms.ValidationError(_("User with the given email address already exists."))
        return email

    def clean_member_id(self):
        member_id = self.cleaned_data['member_id']
        if User.objects.filter(member__number=member_id).exists():
            raise forms.ValidationError(_("User with the given member id already exists."))
        return member_id

    def clean_terms(self):
        terms = self.cleaned_data['terms']
        if not terms:
            raise forms.ValidationError(_("Please read and accept terms and conditions."))
        return terms

The registration view is as follows:

@transaction.atomic
def new_registration(request):
    context = {}

    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            language = Language.objects.get(key="EN")
            country = Country.objects.get(key="BE")

            user = User()
            user.username = form.cleaned_data['email']
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.email = form.cleaned_data['email']
            user.set_password(form.cleaned_data['password'])
            user.save()

            member = Member()
            member.company_name = form.cleaned_data['company_name']
            member.number = form.cleaned_data['member_id']
            member.vat_number = form.cleaned_data['vat_number']
            member.address = form.cleaned_data['address']
            member.postcode = form.cleaned_data['postcode']
            member.city = form.cleaned_data['city']
            member.country = country
            member.telephone = form.cleaned_data['telephone']
            member.mobile = form.cleaned_data['mobile']
            member.user = user
            member.language = language
            member.active = False
            member.save()

            subscription = Subscription()
            subscription.started = datetime.date.today()
            subscription.type = Type.objects.get(default=True)
            subscription.member = member
            subscription.save()

            # Send an email to user and to the manager
            send_email_with_template({
                'subject': _("The account is created"),
                'plain_template': 'master/email_templates/account_created_member.txt',
                'html_template': 'master/email_templates/account_created_member.html',
                'data_dict': {'name': user.first_name},
                'send_to': [user.email]
            })

            send_email_with_template({
                'subject': _("A new account is created"),
                'plain_template': 'master/email_templates/account_created_manager.txt',
                'html_template': 'master/email_templates/account_created_manager.html',
                'data_dict': {'user': user, 'member': member},
                'send_to': [settings.EMAIL_MANAGER]
            })

            context['form'] = RegistrationForm()
            context['success'] = _("Your account has been created successfully. "
                                   "Once your information has been processed, your account will be activated.")

            return render(request, 'master/members/new-registration.html', context)
    else:
        form = RegistrationForm()

    context['form'] = form
    return render(request, 'master/members/new-registration.html', context)

I want now to allow users to edit their profile. But I want that they can only edit a few fields like first_name, last_name, company_name, vat_number, ...

But how to do that using RegistrationForm.

I have update view as follows:

def update_member_profile(request, user_id):
    member = Member.objects \
        .filter(user_id=user_id) \
        .values('user_id',
                'user__first_name',
                'user__last_name',
                'user__email',
                'telephone',
                'mobile',
                'company_name',
                'vat_number',
                'address',
                'postcode',
                'city'
                )[0]

    context = {'member': member}
    return render(request, 'master/members/profile_update.html', context)

In this view I get the user that I want to edit, but how can I now use RegistrationForm to do that?

Any advice?

Body:
Use disabled attribute in your form fields
https://docs.djangoproject.com/en/1.10/ref/forms/fields/

class RegistrationForm(forms.Form):
    first_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("First name *"), 'class': 'form-control'}))
    last_name = forms.CharField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Last name *"), 'class': 'form-control'}))
    email = forms.EmailField(label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Email address *"), 'class': 'form-control'}))
    password = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Password *"), 'class': 'form-control'}))
    password_confirm = forms.CharField(label='', max_length=40, widget=forms.PasswordInput(attrs={'placeholder': _("Re-type your password *"), 'class': 'form-control'}))

    company_name = forms.CharField(disabled=True, label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Company name *"), 'class': 'form-control'}))
    member_id = forms.CharField(disabled=True, label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("Member number *"), 'class': 'form-control'}))
    vat_number = forms.CharField(disabled=True, label='', max_length=40, widget=forms.TextInput(attrs={'placeholder': _("VAT number *"), 'class': 'form-control'}))
    ....

This only works with version 1.9 and after.
another solution is to remove the field from the form all together which will basically hide it rather than disable it


问:
How to get past 7 days and next 7 days in Javascript
I'm trying to get past 7 days and next 7 days date start data and end date using javascript date function.

For example : Today 31 march 2017 , When i click previous button, it will calculate from previous date ie: start and end date , (24 March 2017 to 30 March 2017) , again click previous (17 March 2017 to 23 March 2017)etcc..

Same thing will replicate for next button ..

I have tried the below things but its not working

```<code> function getPreviousWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

 function getNextWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

function getByWeek(){

      console.log("weekpreviouscount" + ProHistoryCtrl.weekPrevcount); //-6,-12,-18,-24
      console.log("weekprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24
      var d2 = new Date(); // 31.01.2017
      var d1 = new Date(d2);
      d1.setDate(d2.getDate() - 1); // 30.01.2017
      var previousWeek = '';
      var current_day = '';

      console.log("d2date" + d1.getDate());
      console.log("week2" + ProHistoryCtrl.weekPrevious)
      previousWeek = new Date(d1);
      previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17

      current_day = new Date(d1); // 30.01.2017
      current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23

      console.log("currentdayprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24

      var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
      var currentUTC = Math.floor(current_day.getTime() / 1000);

      console.log("previousWeekUTCTimestamp" + previousWeekUTCTimestamp);
      console.log("currentUTC" + currentUTC);

      var sinceUTC = previousWeekUTCTimestamp;
      var untilUTC = currentUTC;

}
</code>```

Its first time comes correct 24-march 2017 to 30 march 2017 , next previous its comes 24-march to 18march2017

Any ideas ?please

答:
The problem seems to be with your Maths, you get the previous week by subtracting 6 for each week and then subtracting an extra 1.  This is fine for the first week where -6 -1 = -7, however for the second week this is (-6 * 2) - 1 = -13 but two weeks should be -14.  The code that is incorrect is:

```<code>ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);

d1.setDate(d2.getDate() - 1);
</code>```

A solution would therefore be:

```<code> function getPreviousWeek(){
            ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
            ProHistoryCtrl.weekPrevious  = (-7 * ProHistoryCtrl.weekPrevcount);
            getByWeek();
}

 function getNextWeek(){
            ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
            ProHistoryCtrl.weekPrevious  = (-7 * ProHistoryCtrl.weekPrevcount);
            getByWeek();
}

function getByWeek(){

    var d2 = new Date(); // 31.01.2017
    var d1 = new Date(d2);
    d1.setDate(d2.getDate()); // 30.01.2017
    var previousWeek = '';
    var current_day = '';

    previousWeek = new Date(d1);
    previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17

    current_day = new Date(d1); // 30.01.2017
    current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23

    var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
    var currentUTC = Math.floor(current_day.getTime() / 1000);

    var sinceUTC = previousWeekUTCTimestamp;
    var untilUTC = currentUTC;
}
</code>```

Body:
I'm trying to get past 7 days and next 7 days date start data and end date using javascript date function.

For example : Today 31 march 2017 , When i click previous button, it will calculate from previous date ie: start and end date , (24 March 2017 to 30 March 2017) , again click previous (17 March 2017 to 23 March 2017)etcc..

Same thing will replicate for next button ..

I have tried the below things but its not working

 function getPreviousWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

 function getNextWeek(){
      ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
      ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);
      getByWeek();
}

function getByWeek(){

      console.log("weekpreviouscount" + ProHistoryCtrl.weekPrevcount); //-6,-12,-18,-24
      console.log("weekprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24
      var d2 = new Date(); // 31.01.2017
      var d1 = new Date(d2);
      d1.setDate(d2.getDate() - 1); // 30.01.2017
      var previousWeek = '';
      var current_day = '';

      console.log("d2date" + d1.getDate());
      console.log("week2" + ProHistoryCtrl.weekPrevious)
      previousWeek = new Date(d1);
      previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17

      current_day = new Date(d1); // 30.01.2017
      current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23

      console.log("currentdayprevious" + ProHistoryCtrl.weekPrevious); //-6,-12,-18,-24

      var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
      var currentUTC = Math.floor(current_day.getTime() / 1000);

      console.log("previousWeekUTCTimestamp" + previousWeekUTCTimestamp);
      console.log("currentUTC" + currentUTC);

      var sinceUTC = previousWeekUTCTimestamp;
      var untilUTC = currentUTC;

}

Its first time comes correct 24-march 2017 to 30 march 2017 , next previous its comes 24-march to 18march2017

Any ideas ?please

Body:
The problem seems to be with your Maths, you get the previous week by subtracting 6 for each week and then subtracting an extra 1.  This is fine for the first week where -6 -1 = -7, however for the second week this is (-6 * 2) - 1 = -13 but two weeks should be -14.  The code that is incorrect is:

ProHistoryCtrl.weekPrevious  = (-6 * ProHistoryCtrl.weekPrevcount);

d1.setDate(d2.getDate() - 1);

A solution would therefore be:

 function getPreviousWeek(){
            ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount + 1;
            ProHistoryCtrl.weekPrevious  = (-7 * ProHistoryCtrl.weekPrevcount);
            getByWeek();
}

 function getNextWeek(){
            ProHistoryCtrl.weekPrevcount = ProHistoryCtrl.weekPrevcount - 1;
            ProHistoryCtrl.weekPrevious  = (-7 * ProHistoryCtrl.weekPrevcount);
            getByWeek();
}

function getByWeek(){

    var d2 = new Date(); // 31.01.2017
    var d1 = new Date(d2);
    d1.setDate(d2.getDate()); // 30.01.2017
    var previousWeek = '';
    var current_day = '';

    previousWeek = new Date(d1);
    previousWeek.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious); // 30-13=17

    current_day = new Date(d1); // 30.01.2017
    current_day.setDate(d1.getDate() + ProHistoryCtrl.weekPrevious + 6); // 30-12+5=23

    var previousWeekUTCTimestamp = Math.floor(previousWeek.getTime() / 1000);
    var currentUTC = Math.floor(current_day.getTime() / 1000);

    var sinceUTC = previousWeekUTCTimestamp;
    var untilUTC = currentUTC;
}