答:
This is far too much code. Cut out as much as you can and see whether the error persists, before you post a bolus like this.

I don't have access to VS, so I can't test, but this looks like a namespace problem; your `Polygon` is in conflict with a Microsoft `Polygon`. So use your own namespace and don't say `using namespace std`, it's a scattergun.

Title: error C2143: syntax error : missing ';' before '*'


来源: stackexchange

问:
How do I use Bindings.bindContent?
I have a polygon that I want to grow in size when the window is resized. I have a DoubleBinding that it the baseline for the size of all of my shapes in the scene. I use this DoubleBinding to create a ListBinding that calculates how big the polygon should be. I tried to use Bindings.bindContent(list1, list2) to bind the ListBinding to the polygon's points, but it doesn't seem to work.

```<code>    Polygon triangle = new Polygon();

    ListBinding<Double> trianglePoints = new ListBinding<Double>() {
        {
            super.bind(width, height);
        }
        @Override
        protected ObservableList<Double> computeValue() {
            ObservableList<Double> points = FXCollections.observableArrayList();
            points.addAll(0.0, 0.0, width.get()/2, height.get()/4, 0.0, height.get()/2);
            return points;
        }
    };
    Bindings.bindContent(triangle.getPoints(), trianglePoints.get());
</code>```

I found that if I add an InvalidationListener to the triangle points and manually change the the polygon points when it fires off, it works.

```<code>    trianglePoints.addListener((InvalidationListener)(listener) -> triangle.getPoints().setAll(trianglePoints.get()));
</code>```

What am I doing wrong?

答:
I recommend not using a ListBinding. You do not need to recreate the list over and over again, you just need to modify some of the points:

```<code>@Override
public void start(Stage primaryStage) {
    Polygon triangle = new Polygon(
            0, 0,
            0, 0,
            0, 0);

    StackPane root = new StackPane();
    root.getChildren().add(triangle);

    root.heightProperty().addListener((observable, oldH, newH) -> {
        double h = newH.doubleValue();
        triangle.getPoints().set(3, h / 4);
        triangle.getPoints().set(5, h / 2);
    });

    root.widthProperty().addListener((observable, oldW, newW) -> {
        double w = newW.doubleValue();
        triangle.getPoints().set(2, w / 2);
    });

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}
</code>```

Furthermore it's also possible to do this using the scale properties (unless you're using a stroke or some exotic fill):

```<code>@Override
public void start(Stage primaryStage) {
    Polygon triangle = new Polygon(
            0, 0,
            0.5, 0.25,
            0, 0.5);

    StackPane root = new StackPane();
    root.getChildren().add(triangle);

    triangle.scaleXProperty().bind(root.widthProperty());
    triangle.scaleYProperty().bind(root.heightProperty());

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I use Bindings.bindContent?

Body:
I have a polygon that I want to grow in size when the window is resized. I have a DoubleBinding that it the baseline for the size of all of my shapes in the scene. I use this DoubleBinding to create a ListBinding that calculates how big the polygon should be. I tried to use Bindings.bindContent(list1, list2) to bind the ListBinding to the polygon's points, but it doesn't seem to work.

    Polygon triangle = new Polygon();

    ListBinding<Double> trianglePoints = new ListBinding<Double>() {
        {
            super.bind(width, height);
        }
        @Override
        protected ObservableList<Double> computeValue() {
            ObservableList<Double> points = FXCollections.observableArrayList();
            points.addAll(0.0, 0.0, width.get()/2, height.get()/4, 0.0, height.get()/2);
            return points;
        }
    };
    Bindings.bindContent(triangle.getPoints(), trianglePoints.get());

I found that if I add an InvalidationListener to the triangle points and manually change the the polygon points when it fires off, it works.

    trianglePoints.addListener((InvalidationListener)(listener) -> triangle.getPoints().setAll(trianglePoints.get()));

What am I doing wrong?

Body:
I recommend not using a ListBinding. You do not need to recreate the list over and over again, you just need to modify some of the points:

@Override
public void start(Stage primaryStage) {
    Polygon triangle = new Polygon(
            0, 0,
            0, 0,
            0, 0);

    StackPane root = new StackPane();
    root.getChildren().add(triangle);

    root.heightProperty().addListener((observable, oldH, newH) -> {
        double h = newH.doubleValue();
        triangle.getPoints().set(3, h / 4);
        triangle.getPoints().set(5, h / 2);
    });

    root.widthProperty().addListener((observable, oldW, newW) -> {
        double w = newW.doubleValue();
        triangle.getPoints().set(2, w / 2);
    });

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}

Furthermore it's also possible to do this using the scale properties (unless you're using a stroke or some exotic fill):

@Override
public void start(Stage primaryStage) {
    Polygon triangle = new Polygon(
            0, 0,
            0.5, 0.25,
            0, 0.5);

    StackPane root = new StackPane();
    root.getChildren().add(triangle);

    triangle.scaleXProperty().bind(root.widthProperty());
    triangle.scaleYProperty().bind(root.heightProperty());

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}


问:
Sending an email from R
I am using the following code to send an email to my Gmail account.
library(mailR)

```<code>    sender <- "*********@gmail.com"
recipients <- c("**********@gmail.com")
send.mail(from = sender,
             to = recipients,
             subject = "Test",
              body = "Test",
          smtp = list(host.name = "smtp.gmail.com", port = 465,
                      user.name = "**********@gmail.com",
                      passwd = "*********", ssl = TRUE),
          authenticate = TRUE,
          send = TRUE)
</code>```

I have tried to used different ports also like 25, 522 but nothing works. Also, I have also Enable access to 'less secure apps'. Kindly help.

But I am getting an error:

```<code>org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1410)
    at org.apache.commons.mail.Email.send(Email.java:1437)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at RJavaTools.invokeMethod(RJavaTools.java:386)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2055)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
    at javax.mail.Service.connect(Service.java:386)
    at javax.mail.Service.connect(Service.java:245)
    at javax.mail.Service.connect(Service.java:194)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1400)
    ... 6 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:543)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:348)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:215)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2019)
    ... 13 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.ValiNULL
dator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 25 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 31 more
Error: EmailException (Java): Sending the email to the following server failed : smtp.gmail.com:465
</code>```

答:
Since, nobody actually helped me on this issue but I kept on trying and exploring things and got a link/solution to address my issue.

Sending an email could be done with sendmailR or mailR package but you need to have the correct SMTP settings (from your IT), otherwise it won't work no matter how much you try. Whatever, I found out regarding mailR nothing worked for me.

The other part is to get set up an API and get a client ID for your gmail account and then use this file to build a connection and send email. The link to do it is shown below.

https://github.com/jennybc/send-email-with-r

Hope this helps everyone who faced the issue same as me.

Title: Sending an email from R

Body:
I am using the following code to send an email to my Gmail account.
library(mailR)

    sender <- "*********@gmail.com"
recipients <- c("**********@gmail.com")
send.mail(from = sender,
             to = recipients,
             subject = "Test",
              body = "Test",
          smtp = list(host.name = "smtp.gmail.com", port = 465,
                      user.name = "**********@gmail.com",
                      passwd = "*********", ssl = TRUE),
          authenticate = TRUE,
          send = TRUE)

I have tried to used different ports also like 25, 522 but nothing works. Also, I have also Enable access to 'less secure apps'. Kindly help.

But I am getting an error:

org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1410)
    at org.apache.commons.mail.Email.send(Email.java:1437)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at RJavaTools.invokeMethod(RJavaTools.java:386)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2055)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
    at javax.mail.Service.connect(Service.java:386)
    at javax.mail.Service.connect(Service.java:245)
    at javax.mail.Service.connect(Service.java:194)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1400)
    ... 6 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:543)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:348)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:215)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2019)
    ... 13 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.ValiNULL
dator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 25 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 31 more
Error: EmailException (Java): Sending the email to the following server failed : smtp.gmail.com:465


问:
Which file permission to write to text files?
my PHP script writes to text.txt files such

```<code> $filename = "pref.enc";  // TEXT FILE
    $file_content = file($filename);
    $x = count($file_content);
    $fp = fopen($filename, "w+");
$file_content[0] = "$my_station" . "\n";
    $y = 0;
    while($y < $x)
    {
    fwrite($fp, $file_content[$y]);
    $y++;
    }
    fclose($fp);
</code>```

Which CHMOD permission is recommended for text files AND folder (the folder holds the text files)?

755 or 777 ?

答:
0755 for directories

0644 for files

See chmod

This is assuming that you want everybody to read it.

Body:
my PHP script writes to text.txt files such

 $filename = "pref.enc";  // TEXT FILE
    $file_content = file($filename);
    $x = count($file_content);
    $fp = fopen($filename, "w+");
$file_content[0] = "$my_station" . "\n";
    $y = 0;
    while($y < $x)
    {
    fwrite($fp, $file_content[$y]);
    $y++;
    }
    fclose($fp);

Which CHMOD permission is recommended for text files AND folder (the folder holds the text files)?

755 or 777 ?


问:
strip comments from xml file and pretty-print it
I have this huge xml file which contains a lot of comments.

Whats the "best way" to strip out all the comments and nicely format the xml from the linux command line?

答:
To tidy up something simple like Tomcat's server.xml, I use

```<code>sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0' | grep -v "^\s*$"
</code>```

I.e.

```<code>function tidy() {
 echo "$( cat $1 | sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0' | grep -v "^\s*$")"
}

tidy server.xml
</code>```

... will print the xml without comments.

NOTE: while it works reasonably well for simple things, it will fail with certain CDATA blocks and some other situations. Only use it for controlled xml scripts that have no need and will never need to escape a single <-- or --> anywhere!

First sed marks comment's start and stop with 0x0 characters, then grep with -z treats 0x0 as the only line delimiter, searches for lines starting with comment, it's -v inverts the filter, leaving only meaningful lines. Finally, tr -d\0` deletes all these 0x0, and to polish it up, another grep removes empty lines: voila.

Body:
To tidy up something simple like Tomcat's server.xml, I use

sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0' | grep -v "^\s*$"

I.e.

function tidy() {
 echo "$( cat $1 | sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0' | grep -v "^\s*$")"
}

tidy server.xml

... will print the xml without comments.

NOTE: while it works reasonably well for simple things, it will fail with certain CDATA blocks and some other situations. Only use it for controlled xml scripts that have no need and will never need to escape a single <-- or --> anywhere!

First sed marks comment's start and stop with 0x0 characters, then grep with -z treats 0x0 as the only line delimiter, searches for lines starting with comment, it's -v inverts the filter, leaving only meaningful lines. Finally, tr -d\0` deletes all these 0x0, and to polish it up, another grep removes empty lines: voila.


问:
window border width and height in Win32 - how do I get it?
```
      ::GetSystemMetrics (SM_CYBORDER)
```

...comes back with 1 and I know the title bar is taller than ONE pixel :/

I also tried:

```
     RECT r;
      r.left = r.top = 0;   r.right = r.bottom = 400;
      ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE);
      _bdW = (uword)(r.right - r.left - 400);
      _bdH = (uword)(r.bottom - r.top - 400);
```

But border w,h came back as 0.

In my WM_SIZE handler, I need to make sure the window's height changes in
"steps" so, for example a whole new line of text could fit in the window
with no "junky partial line space" at the bottom.

But ::MoveWindow needs the dimensions WITH the border space added in.

SOMEbody must have done this before...
Thanks for any help :)

答:
The GetWindowRect and GetClientRect functions can be used calculate the size of all the window borders.

Suite101 has a article on resizing a window and the keeping client area at a know size.

Here is their sample code:

```<code>void ClientResize(HWND hWnd, int nWidth, int nHeight)
{
  RECT rcClient, rcWind;
  POINT ptDiff;
  GetClientRect(hWnd, &rcClient);
  GetWindowRect(hWnd, &rcWind);
  ptDiff.x = (rcWind.right - rcWind.left) - rcClient.right;
  ptDiff.y = (rcWind.bottom - rcWind.top) - rcClient.bottom;
  MoveWindow(hWnd,rcWind.left, rcWind.top, nWidth + ptDiff.x, nHeight + ptDiff.y, TRUE);
}
</code>```

OwnerDisplayName: Stephen Hazel

ContentLicense: CC BY-SA 2.5

Body:
      ::GetSystemMetrics (SM_CYBORDER)

...comes back with 1 and I know the title bar is taller than ONE pixel :/

I also tried:

     RECT r;
      r.left = r.top = 0;   r.right = r.bottom = 400;
      ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE);
      _bdW = (uword)(r.right - r.left - 400);
      _bdH = (uword)(r.bottom - r.top - 400);

But border w,h came back as 0.

In my WM_SIZE handler, I need to make sure the window's height changes in
"steps" so, for example a whole new line of text could fit in the window
with no "junky partial line space" at the bottom.

But ::MoveWindow needs the dimensions WITH the border space added in.

SOMEbody must have done this before...
Thanks for any help :)

Body:
The GetWindowRect and GetClientRect functions can be used calculate the size of all the window borders.

Suite101 has a article on resizing a window and the keeping client area at a know size.

Here is their sample code:

void ClientResize(HWND hWnd, int nWidth, int nHeight)
{
  RECT rcClient, rcWind;
  POINT ptDiff;
  GetClientRect(hWnd, &rcClient);
  GetWindowRect(hWnd, &rcWind);
  ptDiff.x = (rcWind.right - rcWind.left) - rcClient.right;
  ptDiff.y = (rcWind.bottom - rcWind.top) - rcClient.bottom;
  MoveWindow(hWnd,rcWind.left, rcWind.top, nWidth + ptDiff.x, nHeight + ptDiff.y, TRUE);
}

OwnerDisplayName: stukelly


问:
about depicting a variable (Sum) in Anylogic
For defining the behaviour of my agents, I created a state chart in which when a user likes a comment, the variable "likes" is changed as follows :

```<code>Likes=Likes+1;
</code>```

It should show me at the end the sum of likes. In order to depict this sum , as it is not a statistics, I cannot use a bar chart or anything for it. What if I define this in statistics:

```<code>Name : Totalallikes
Type:Sum
expressions: item.Likes
</code>```

Does it make sense? Or I am summing the likes twice this way?

Thank you

答: I believe your variable should already contain the sum, there's no need to create a Statistic or sum them up any more or else as you say, you would be summing them up twice.</p>

Body:
For defining the behaviour of my agents, I created a state chart in which when a user likes a comment, the variable "likes" is changed as follows :

Likes=Likes+1;

It should show me at the end the sum of likes. In order to depict this sum , as it is not a statistics, I cannot use a bar chart or anything for it. What if I define this in statistics:

Name : Totalallikes
Type:Sum
expressions: item.Likes

Does it make sense? Or I am summing the likes twice this way?

Thank you


问:
Xcode8.3 constantly crashes after update
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.</p>

```<code>Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}
</code>```

答:
I also had this problem.
After installing the pending Mac OS Sierra update, my Xcode is not crashing anymore.</p>

Body:
After update Xcode 8.3 is crashing constantly. At start it was 30 to 40 minutes but today it is crashing after just 10 seconds. Any help will be highly appreciated. Below is crash report.

Process:               Xcode [555]
Path:                  /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier:            com.apple.dt.Xcode
Version:               8.3 (12169)
Build Info:            IDEFrameworks-12169000000000000~2
App Item ID:           497799835
App External ID:       821487965
Code Type:             X86-64 (Native)
Parent Process:        ??? [1]
Responsible:           Xcode [555]
User ID:               501

Date/Time:             2017-03-29 17:52:50.427 +0500
OS Version:            Mac OS X 10.12.4 (16E195)
Report Version:        12
Anonymous UUID:        C95FFD88-0B61-915D-E373-1F31A265D400

Time Awake Since Boot: 250 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
MainQueue: _compat_sourcekitd_set_notification_handler_block_invoke_2
ProductBuildVersion: 8E162
ASSERTION FAILURE in /Library/Caches/com.apple.xbs/Sources/DVTFrameworks/DVTFrameworks-12150/DVTFoundation/FilePaths/DVTFilePath.m:905
Details:  Path must be absolute but is not: <built-in>
Object:   <DVTFilePath>
Method:   +filePathForPathString:
Thread:   <NSThread: 0x7fc33ae02970>{number = 1, name = main}


问:
How to install new module/package in python coding online environment?
I want to install third party package in python online coding environments. Could you please tell me how we can achieve this?

The below line needs to execute
from watson_developer_cloud import SpeechToTestV1 as STT
when I run the above line, I am getting the following error,

Error:
Traceback (most recent call last):
  File "..\Playground\", line 1, in
    \ufefffrom watson_developer_cloud import SpeechToTestV1 as STT
ImportError: No module named 'watson_developer_cloud'

Even tried the below command in CODE Playground but it throwing incorrect syntax.
pip install watson_developer_cloud

Thanks in advance,

答:
I think you have to execute pip install --upgrade watson-developer-cloud
and not pip install watson_developer_cloud

https://github.com/watson-developer-cloud/python-sdk


问:
Using UITabBar and UINavigationBar
I'm facing problem with using UITabBar and UINavigationBar at the same time. My intention is to have tabBar displaying my 3 tabs and navBar on each of these tabs displaying custom name and on some of these tabs additionally displaying some buttons (such as Add button).

I created view controllers in AppDelegate's didFinishLaunchingWithOptions:

```<code>AAA *vc1 = [[AAA alloc] init];
BBB *vc2 = [[BBB alloc] init];
CCC *vc3 = [[CCC alloc] init];
</code>```

Created tabBar and populated it:

```<code>self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[vc1, vc2, vc3];
</code>```

Next I have added some titles and images to the tabBarItems of these view controllers which is all working fine, but than I wanted to display navigation bar on top of the application. So I created navigation controller, but I don't know what view controller I need to initiate it with. If I use vc1 and set navController as rootViewController, application displays vc1's view and shows navBar, but doesn't show tabBar.

```<code>UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc1];
self.window.rootViewController = navController;

//self.window.rootViewController = self.tabBarController;
</code>```

I tried to set tabBarController to init navController and set navController as rootViewController - in this case views, tabBar and navBAr display correctly, but I don't have navBarItems associated with views vc1, vc2, vc3.

This is how I created navBarItems (e.g. in AAA.m):

```<code>- (instancetype)init {
self = [super init];
if (self) {
    UINavigationItem *navItem = self.navigationItem;
    navItem.title = @"name";
}
return self;
}
</code>```

What do I need to do to make it work all together? Thanks.

EDIT:

I made some modification to the code and now navigation bar is visible, but only on the view controller set in UINavigationController's initWithRootViewController method. For example in following code I can see tab bar on every view and nav bar on the vc2 only. And my intention is to have tab bar and nav bar on every of these three vc.

```<code>UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc2];

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:vc1, navController, vc3, nil];

self.window.rootViewController = self.tabBarController;
</code>```

答:
Ok, I have an approach for you...for this you need make changes in storyboard.
Here is a screenshot

Now create a class for UITabBar: class TabBarViewController: UITabBarController

Do not write anything in this class, it just for our reference.

In AppDelegate Class, method: didlaunchFinish:

```<code>let vcTabBarViewController = STORYBOARD.instantiateViewController(withIdentifier: "TabBarViewController") as? TabBarViewController
        navigationController.viewControllers = [vcTabBarViewController!]
</code>```

Now in your first view controller which is on 1st tab,
In viewDidLoad method:
paste these lines:

```<code>let tabBar = self.tabBarController?.tabBar
 let homeTab = tabBar?.items?[0] as UITabBarItem!
 let searchTab = tabBar?.items?[1] as UITabBarItem!
 let myProfileTab = tabBar?.items?[4] as UITabBarItem!

homeTab?.image = UIImage(named: "home-select")!.withRenderingMode(.alwaysOriginal)
homeTab?.image = UIImage(named: "home")!.withRenderingMode(.alwaysTemplate)

searchTab?.image = UIImage(named: "search-select")!.withRenderingMode(.alwaysOriginal)
searchTab?.image = UIImage(named: "search")!.withRenderingMode(.alwaysTemplate)
</code>```

I hope this will resolve your problem.

Title: Using UITabBar and UINavigationBar

Body:
I'm facing problem with using UITabBar and UINavigationBar at the same time. My intention is to have tabBar displaying my 3 tabs and navBar on each of these tabs displaying custom name and on some of these tabs additionally displaying some buttons (such as Add button).

I created view controllers in AppDelegate's didFinishLaunchingWithOptions:

AAA *vc1 = [[AAA alloc] init];
BBB *vc2 = [[BBB alloc] init];
CCC *vc3 = [[CCC alloc] init];

Created tabBar and populated it:

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[vc1, vc2, vc3];

Next I have added some titles and images to the tabBarItems of these view controllers which is all working fine, but than I wanted to display navigation bar on top of the application. So I created navigation controller, but I don't know what view controller I need to initiate it with. If I use vc1 and set navController as rootViewController, application displays vc1's view and shows navBar, but doesn't show tabBar.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc1];
self.window.rootViewController = navController;

//self.window.rootViewController = self.tabBarController;

I tried to set tabBarController to init navController and set navController as rootViewController - in this case views, tabBar and navBAr display correctly, but I don't have navBarItems associated with views vc1, vc2, vc3.

This is how I created navBarItems (e.g. in AAA.m):

- (instancetype)init {
self = [super init];
if (self) {
    UINavigationItem *navItem = self.navigationItem;
    navItem.title = @"name";
}
return self;
}

What do I need to do to make it work all together? Thanks.

EDIT:

I made some modification to the code and now navigation bar is visible, but only on the view controller set in UINavigationController's initWithRootViewController method. For example in following code I can see tab bar on every view and nav bar on the vc2 only. And my intention is to have tab bar and nav bar on every of these three vc.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc2];

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:vc1, navController, vc3, nil];

self.window.rootViewController = self.tabBarController;

Body:
Ok, I have an approach for you...for this you need make changes in storyboard.
Here is a screenshot

Now create a class for UITabBar: class TabBarViewController: UITabBarController

Do not write anything in this class, it just for our reference.

In AppDelegate Class, method: didlaunchFinish:

let vcTabBarViewController = STORYBOARD.instantiateViewController(withIdentifier: "TabBarViewController") as? TabBarViewController
        navigationController.viewControllers = [vcTabBarViewController!]

Now in your first view controller which is on 1st tab,
In viewDidLoad method:
paste these lines:

let tabBar = self.tabBarController?.tabBar
 let homeTab = tabBar?.items?[0] as UITabBarItem!
 let searchTab = tabBar?.items?[1] as UITabBarItem!
 let myProfileTab = tabBar?.items?[4] as UITabBarItem!

homeTab?.image = UIImage(named: "home-select")!.withRenderingMode(.alwaysOriginal)
homeTab?.image = UIImage(named: "home")!.withRenderingMode(.alwaysTemplate)

searchTab?.image = UIImage(named: "search-select")!.withRenderingMode(.alwaysOriginal)
searchTab?.image = UIImage(named: "search")!.withRenderingMode(.alwaysTemplate)

I hope this will resolve your problem.


问:
Semicolon after closing curly bracket in PHP
I am writing a script to make chunks of a text and send it via SMS. Earlier today i was reviewing some code to split the string in chunks and i saw something I've never seen before. I'm talking about the ";" right after the "}" at the en of the snippet.

Why this colon? i know it works but i don't know if it adds some semantics or some instruction to the interpreter, anybody know what is this for?

```<code>while(1)
{
    $length = (strlen($output)+strlen($words[$i]));
    if($length>$new_max)
    {
        if(count($words) > 0)
        {
            $out_array[] = $output;
            $output = '';

        }
        else
        {
            break;
        }
    }
    else
    {
        $output = $output." ".$words[$i];
        ++$i;
    };
};
</code>```

EDIT: Looks clear that the semicolons as well as multiple semicolons together has no effect over the result, but, do you know if it has some effect to the interpreter? is it doing some task (internally) when it parses it?

答: I think that those 2 semicolons do nothing here. It is probably being interpreted as an empty expression immediately following the if/while.

Body:
I am writing a script to make chunks of a text and send it via SMS. Earlier today i was reviewing some code to split the string in chunks and i saw something I've never seen before. I'm talking about the ";" right after the "}" at the en of the snippet.

Why this colon? i know it works but i don't know if it adds some semantics or some instruction to the interpreter, anybody know what is this for?

while(1)
{
    $length = (strlen($output)+strlen($words[$i]));
    if($length>$new_max)
    {
        if(count($words) > 0)
        {
            $out_array[] = $output;
            $output = '';

        }
        else
        {
            break;
        }
    }
    else
    {
        $output = $output." ".$words[$i];
        ++$i;
    };
};

EDIT: Looks clear that the semicolons as well as multiple semicolons together has no effect over the result, but, do you know if it has some effect to the interpreter? is it doing some task (internally) when it parses it?


问:
Frequency of a number in array faster than linear time
Find the frequency of a number in array in less than O(n) time.

```<code>Array 1,2,2,3,4,5,5,5,2
Input 5
Output 3
</code>```

```<code>Array 1,1,1,1
Input 1
Output 4
</code>```

答:
If the only information you have is an unsorted array (as your test data seems to indicate), you cannot do better than O(n) in finding the frequency of a given value. There's no getting around that.

In order to achieve a better time complexity, there are a variety of ways.

One would be to keep the array sorted (or a parallel sorted array if you didn't want to change the order). This way, you could use a binary search to find the first item with the given value then sequentially scan that portion to get a count. While the worst case (all items the same and that value is what you're looking for) is still O(n), it will tend toward O(log n) average case.

Note that sorting the data each time before looking for a value will not work since that will almost certainly push you above the O(n) limit. The idea would be to sort only on item insertion.

Another method, provided your domain (possible values) is limited, is to maintain the actual frequencies of those values separately. For example, if the domain is limited to the numbers one through a hundred, have a separate array containing the frequency of each value.

When the list is empty, all frequencies are zero. Whenever you add or remove an item, increment or decrement the frequency for that value. This would make frequency extraction a quick O(1) operation.

But, as stated, both these solutions require extra/modified data to be maintained. Without that, you cannot do better than O(n) since you will need to examine every item in the array to see if it matches the value you're looking for.

Body:
Find the frequency of a number in array in less than O(n) time.

Array 1,2,2,3,4,5,5,5,2
Input 5
Output 3

Array 1,1,1,1
Input 1
Output 4


问:
PHP & MySQL UPDATE 10 columns
I want to update customer data which means 10 different columns would be updated in one UPDATE SET WHERE statement but I keep getting a warning in NetBeans that says method length 26 ( allowed 20)
Can anyone tell me what the method length refers to and what another way is to update all those columns in one statement ? </p>

答:
This is an utterly ridiculous hint. You can disable it in
Tools->Options->Editor->Hints->PHP.
It won't disturb you again. </p>

Title: PHP & MySQL UPDATE 10 columns


问:
How do I add a formula with VBA that refers to another cell?
I searched but didn't found what I was looking for.
My goal is to have a big number of cells that shows the value of other cells in other sheets like a simple "=january!BP$43".
But I want to add this with a loop, here a simplified example:

```<code>  For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(3 + mois).Cells(40+i, 2 + sorte)"
    Next
    j = j + 13
    i=i+15
    k=k+1
Next
</code>```

I tried it without the " " around "Sheets...)" and it works but just inserts the value and not the formula.
Any Idea?
Thanks a lot

PS: j,i,k are just here to show that I have other variables coming there to change the position.

答:
Remember that everything in between quotation marks will be copied as a string. You need to close the quotation marks whenever you want to use the value of the variable, not the variable name:

```<code>For mois = 0 To 11
    Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(" & 3 + mois & ").Cells(" & 40+i & "," & 2 + sorte& ")"
Next
</code>```

However, wouldn't it be easier to just use Excel and copy to the cells you need?

Body:
I searched but didn't found what I was looking for.
My goal is to have a big number of cells that shows the value of other cells in other sheets like a simple "=january!BP$43".
But I want to add this with a loop, here a simplified example:

  For sorte = 0 To 5
    For mois = 0 To 11
        Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(3 + mois).Cells(40+i, 2 + sorte)"
    Next
    j = j + 13
    i=i+15
    k=k+1
Next

I tried it without the " " around "Sheets...)" and it works but just inserts the value and not the formula.
Any Idea?
Thanks a lot

PS: j,i,k are just here to show that I have other variables coming there to change the position.

Body:
Remember that everything in between quotation marks will be copied as a string. You need to close the quotation marks whenever you want to use the value of the variable, not the variable name:

For mois = 0 To 11
    Sheets(2).Range(4+k, 1 + mois + j).Formula = "=Sheets(" & 3 + mois & ").Cells(" & 40+i & "," & 2 + sorte& ")"
Next

However, wouldn't it be easier to just use Excel and copy to the cells you need?


问:
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 getting an ambiguous name call of Polygon perhaps?

Would be better if you at least indicated which line is 121

By the way, why do you use arrays rather than vector and why are you overloading operator new?

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.


问:
HTML5 picture element bug in IE11
Here is result in Chrome which is right

Here is result in IE which is wrong

And here is the code:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>
body, div, html
{
 align-items: center;
 display: flex;
 flex-direction: column;
 justify-content: center;
 width: 100%;
}
form
{
 align-items: center;
 display: flex;
 flex-direction: column;
 justify-content: center;
 max-width: 1280px;
 width: 100%;
}
img
{
 flex: none;
 max-width: 100%;
 min-height: 1px;
 width: 100%;
}
picture {width: 80%;}
#temp {background-color: red;}
</style>
</head>

<body>
<form id="form1">
<picture>
  <source media="(max-width: 600px)" srcset="../tmp.jpg">
  <source media="(max-width: 960px)" srcset="../tmp.jpg">
  <img src="../tmp.jpg">
</picture>
<div id="temp">123123123123</div>
</form>

</body>
</html>
</code>```

Why picture element in ie appear this blank while in chrome not?
IE version is IE 11 in windows 10,Chrome version is 57.0.2987.110.
What's wrong with IE?
And how can I delete the blank in IE?Thanks

答:
You can try this, may be it works in your browser.</p>

```<code><style type="text/css">
img {
        width:100%;
        max-width:100%;
        min-height:1px;
        -webkit-flex:none;
        -moz-flex:none;
        -ms-flex:none;
        -o-flex:none;
        flex:none;
    }
    form {
        max-width:1280px;
        width:100%;
        -webkit-display:flex;
        -moz-display:flex;
        -ms-display:flex;
        -o-display:flex;
        display:flex;
        -webkit-justify-content:center;
        -moz-justify-content:center;
        -ms-justify-content:center;
        -o-justify-content:center;
        justify-content:center;
        -webkit-align-items:center;
        -moz-align-items:center;
        -ms-align-items:center;
        -o-align-items:center;
        align-items:center;
        -webkit-flex-direction:column;
        -moz-flex-direction:column;
        -ms-flex-direction:column;
        -o-flex-direction:column;
        flex-direction:column;
    }
    html, body, div{
        width:100%;
        -webkit-display:flex;
        -moz-display:flex;
        -ms-display:flex;
        -o-display:flex;
        display:flex;
        -webkit-justify-content:center;
        -moz-justify-content:center;
        -ms-justify-content:center;
        -o-justify-content:center;
        justify-content:center;
        -webkit-align-items:center;
        -moz-align-items:center;
        -ms-align-items:center;
        -o-align-items:center;
        align-items:center;
        -webkit-flex-direction:column;
        -moz-flex-direction:column;
        -ms-flex-direction:column;
        -o-flex-direction:column;
        flex-direction:column;
    }
    picture {
        width:80%;
    }
    #temp {
        background-color:red;
    }
</style>

thanks!
</code>```

ContentLicense: CC BY-SA 4.0

Title: HTML5 picture element bug in IE11

Body:
Here is result in Chrome which is right

Here is result in IE which is wrong

And here is the code:

<!DOCTYPE html>

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<form id="form1">
<picture>
  <source media="(max-width: 600px)" srcset="../tmp.jpg">
  <source media="(max-width: 960px)" srcset="../tmp.jpg">

</picture>

123123123123

</form>

Why picture element in ie appear this blank while in chrome not?
IE version is IE 11 in windows 10,Chrome version is 57.0.2987.110.
What's wrong with IE?
And how can I delete the blank in IE?Thanks

Body:
You can try this, may be it works in your browser.

<style type="text/css">
img {
        width:100%;
        max-width:100%;
        min-height:1px;
        -webkit-flex:none;
        -moz-flex:none;
        -ms-flex:none;
        -o-flex:none;
        flex:none;
    }
    form {
        max-width:1280px;
        width:100%;
        -webkit-display:flex;
        -moz-display:flex;
        -ms-display:flex;
        -o-display:flex;
        display:flex;
        -webkit-justify-content:center;
        -moz-justify-content:center;
        -ms-justify-content:center;
        -o-justify-content:center;
        justify-content:center;
        -webkit-align-items:center;
        -moz-align-items:center;
        -ms-align-items:center;
        -o-align-items:center;
        align-items:center;
        -webkit-flex-direction:column;
        -moz-flex-direction:column;
        -ms-flex-direction:column;
        -o-flex-direction:column;
        flex-direction:column;
    }
    html, body, div{
        width:100%;
        -webkit-display:flex;
        -moz-display:flex;
        -ms-display:flex;
        -o-display:flex;
        display:flex;
        -webkit-justify-content:center;
        -moz-justify-content:center;
        -ms-justify-content:center;
        -o-justify-content:center;
        justify-content:center;
        -webkit-align-items:center;
        -moz-align-items:center;
        -ms-align-items:center;
        -o-align-items:center;
        align-items:center;
        -webkit-flex-direction:column;
        -moz-flex-direction:column;
        -ms-flex-direction:column;
        -o-flex-direction:column;
        flex-direction:column;
    }
    picture {
        width:80%;
    }
    #temp {
        background-color:red;
    }
</style>

thanks!


问:
Odoo 9.0 C How to add a new many2one field from an inherited view?
Could you guy please show me what is the right steps to follow when we want to add a new many2one field to an inherited view like account.invoice.order.</p>

答:
It's like the same :

```<code>  <template id="new_id" inherit_id="module_name.qweb_template_id" name="Template name as you want">
      <!-- specify the target that you want to add the many2one field
              than the place after,before or inside -->
        <xpath expr="//target_where_you_want_to_add" position="after/before/inside">
            <field name="your_one_to_many_field_name" />
        </xpath>
  </template>
</code>```

the hard part is targeting the write place
like if you want to add the the field to a div tag inside a div with id ="div_id" and the div contain a class="class_name"

```<code><xpath expr="//div[@id='div_id']/div[@class='class_name']" position="inside">
</code>```

or a after a field inside that div named field1

```<code><xpath expr="//div[@id='div_id']/div[@class='class_name']/field[@name='field1']" position="after">
</code>```

or after a field that named field1

```<code> <!-- // is like a shortcut -->
  <xpath expr="//field[@name='field1']" position="after">
</code>```

so see who can you target the place that you want to put the field using tag names and properties  like id,class,... (string is not supported in odoo 9)

Body:
It's like the same :

  <template id="new_id" inherit_id="module_name.qweb_template_id" name="Template name as you want">
      <!-- specify the target that you want to add the many2one field
              than the place after,before or inside -->
        <xpath expr="//target_where_you_want_to_add" position="after/before/inside">
            <field name="your_one_to_many_field_name" />
        </xpath>
  </template>

the hard part is targeting the write place
like if you want to add the the field to a div tag inside a div with id ="div_id" and the div contain a class="class_name"

<xpath expr="//div[@id='div_id']/div[@class='class_name']" position="inside">

or a after a field inside that div named field1

<xpath expr="//div[@id='div_id']/div[@class='class_name']/field[@name='field1']" position="after">

or after a field that named field1

 <!-- // is like a shortcut -->
  <xpath expr="//field[@name='field1']" position="after">

so see who can you target the place that you want to put the field using tag names and properties  like id,class,... (string is not supported in odoo 9)