问:
'git push origin MyBranchName' throws error "HTTP Basic: Access denied"
I am new to Git (just started 2 days ago). I'm attempting to create a project to practice the basic commands I've learned from here.

Where I am, so far:

[success] Create a new public git project (because I tried private and internal before but I could not clone it, and I don't know why). Here it is.

Added a README.md into the project.

[success] Create a new branch named develop.

[success] In my local folder C:\gitprojects, set global user.name and user.email with the commands:

git config --global user.name <my user name>

git config --global user.email <my-email>

[success] Clone the project into my local folder C:\gitprojects with the command git clone https://flamedenise19@gitlab.com/flamedenise19/speedtyping.git

[success] Create a local branch with the command git checkout -b "develop".

[success] Manually add a new file test.txt on local root folder for test pushing.

[success] Commit the new file with the command git commit -m "adds test.txt"

[attempting] Push the commit with the command git push origin develop

And now, I'm stuck with the push part. After entering git push origin develop, a new window pops up, asking for my credentials (see screenshot below):

So I did enter my credentials (the very same username and password I use when logging in to gitlab.com), but after that, I got this error (also see screenshot below):

```<code>remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/flamedenise19/speedtyping.git/'
</code>```

QUESTIONS:

Why can't I push successfully, even with the correct username and password? Am I missing something or have I done something wrong along the way?

Is there a way to remove the step of having to enter my credentials everytime I push something?

Please help.

NOTE: I have seen THIS ONE, and the answers are mentioning Tortoise. Is it always required to use tortoise in order to
  use Git?

SOME BACKGROUND INFO:

Two-Factor Authentication is disabled for my account (see screenshot below):

答:
After doing some digging of my own thanks to this problem I found out that it is more than likely coming from the credential manager.
I had no ssh keys since it was a fresh Gitlab account and it was not working with my username and password. The same setup however, was working on GitHub. After uninstalling git and reinstalling without the credential manager it worked.</p>

Body:
I am new to Git (just started 2 days ago). I'm attempting to create a project to practice the basic commands I've learned from here.

Where I am, so far:

[success] Create a new public git project (because I tried private and internal before but I could not clone it, and I don't know why). Here it is.

Added a README.md into the project.

[success] Create a new branch named develop.

[success] In my local folder C:\gitprojects, set global user.name and user.email with the commands:

git config --global user.name <my user name>

git config --global user.email <my-email>

[success] Clone the project into my local folder C:\gitprojects with the command git clone https://flamedenise19@gitlab.com/flamedenise19/speedtyping.git

[success] Create a local branch with the command git checkout -b "develop".

[success] Manually add a new file test.txt on local root folder for test pushing.

[success] Commit the new file with the command git commit -m "adds test.txt"

[attempting] Push the commit with the command git push origin develop

And now, I'm stuck with the push part. After entering git push origin develop, a new window pops up, asking for my credentials (see screenshot below):

So I did enter my credentials (the very same username and password I use when logging in to gitlab.com), but after that, I got this error (also see screenshot below):

remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/flamedenise19/speedtyping.git/'

QUESTIONS:

Why can't I push successfully, even with the correct username and password? Am I missing something or have I done something wrong along the way?

Is there a way to remove the step of having to enter my credentials everytime I push something?

Please help.

NOTE: I have seen THIS ONE, and the answers are mentioning Tortoise. Is it always required to use tortoise in order to
  use Git?

SOME BACKGROUND INFO:

Two-Factor Authentication is disabled for my account (see screenshot below):


来源: stackexchange

问:
Django uniqueness constraint when a specific field is True
I've got a Django model like this:

```<code>class Process(Place):
    isRunning = models.BooleanField(default=True)
    name      = models.CharField(max_length=20)
</code>```

I'd like to enforce that the name field is unique when isRunning is true.

Is this constraint possible in in Django models?

This might be a duplicate of this question, but it doesn't have an accepted answer, and Django has developed a lot since it was asked.

答:
You could add an extra field such as stopped_at to record the time a Process is killed.

And create an unique constraint:

```<code>unique_together = ('name', 'stopped_at')
</code>```

stopped_at could be set to None or some constant value for new processes.

This constraint will make sure that the names are unique among running processes. And stopped processes could have same names as their stopped_at are always different (hopefully or you could add other information to this tricky field to guarantee uniqueness for stopped processes).

ContentLicense: CC BY-SA 3.0

Body:
I've got a Django model like this:

class Process(Place):
    isRunning = models.BooleanField(default=True)
    name      = models.CharField(max_length=20)

I'd like to enforce that the name field is unique when isRunning is true.

Is this constraint possible in in Django models?

This might be a duplicate of this question, but it doesn't have an accepted answer, and Django has developed a lot since it was asked.

Body:
You could add an extra field such as stopped_at to record the time a Process is killed.

And create an unique constraint:

unique_together = ('name', 'stopped_at')

stopped_at could be set to None or some constant value for new processes.

This constraint will make sure that the names are unique among running processes. And stopped processes could have same names as their stopped_at are always different (hopefully or you could add other information to this tricky field to guarantee uniqueness for stopped processes).


问:
C++ Put string in array
I keep seeing similar questions to mine, however, I can't seem to find one that helps my situation. Honestly, it seems like such a mundane question, I shouldn't be asking it, but here I am 2 weeks latter, still with no answer.

```<code>{
    string word;
    ArrayWithWords[d] = word;
    d++;
}
</code>```

Every time this loop runs, I want to put word in position d of the array. Other examples I've found only turn the string into char*.

The array will be used more than once and having a solid value, if that's what it's called, is far more preferred. I'd like to avoid using a pointer.

答:
Pretty much the same thing that was just posted but a little bit more old school.</p>

```<code>#include <string>

using namespace std;

int main()
{
  string stringArray[10];

  string word;
  word = "hello";

  for (int i = 0; i < 10; i++)
  {
      stringArray[i] = string(word);
  }
}
</code>```

Title: C++ Put string in array

Body:
I keep seeing similar questions to mine, however, I can't seem to find one that helps my situation. Honestly, it seems like such a mundane question, I shouldn't be asking it, but here I am 2 weeks latter, still with no answer.

{
    string word;
    ArrayWithWords[d] = word;
    d++;
}

Every time this loop runs, I want to put word in position d of the array. Other examples I've found only turn the string into char*.

The array will be used more than once and having a solid value, if that's what it's called, is far more preferred. I'd like to avoid using a pointer.

Body:
Pretty much the same thing that was just posted but a little bit more old school.

#include <string>

using namespace std;

int main()
{
  string stringArray[10];

  string word;
  word = "hello";

  for (int i = 0; i < 10; i++)
  {
      stringArray[i] = string(word);
  }
}


问:
Remove lines from a text file which do not contain a certain string with python
I am trying to form a quotes file of a specific user name in a log file.  How do I remove every line that does not contain the specific user name in it?  Or how do I write all the lines which contain this user name to a new file?</p>

答:
I know you asked for python, but if you're on unix this is a job for grep.

```<code>grep name file
</code>```

If you're not on unix, well... the answer above does the trick :)

ContentLicense: CC BY-SA 2.5

Body:
I know you asked for python, but if you're on unix this is a job for grep.

grep name file

If you're not on unix, well... the answer above does the trick :)


问:
jQuery click event fires on parent element multiple times
https://jsfiddle.net/50Lw423g/2/

```<code>  gameLogic: function() {
    console.log("GAME LOGIC");
    alert("Your Turn!");
    var that = this;
    $(".game-screen").on("click", ".tic", function() {
      console.log("EVENT ATTACHED");
      var movesDisplay = $(this).text(),
        playerOne = that.playerOneMoves,
        moveID = +(this.id);
      if (movesDisplay !== "O" && movesDisplay !== "X") {
        that.playerOneMoves.push(moveID);
        if (playerOne.length > 2) {
          if (that.checkIfWinCondition(playerOne, that.winConditions)) {
            alert("GAME OVER!");
            that.inGame = false;
            ticTacToe.restartGame();
          }
        }
        $(this).text(that.playerFaction === "X" ? "X" : "O");
      }
    });
  },
</code>```

I'm writing a Tic-Tac-Toe game and ran into this problem - when multiple sessions are "played" click events keep compounding. Which I solved by clearing the previous click events every time before a new one is attached.

```<code>$(".game-screen").off().on("click", ".tic", function () { //do stuff }
</code>```

By the way event.stopPropagation() and event.stopImmediatePropagation() did NOT work.

Anyway, while I managed to fix the problem and understand why the click events where compounding, what I can't seem to wrap my head around is why those compounded click events kept calling the parent function gameLogic: function(). Try "playing" several sessions in a row -

console.log("GAME LOGIC");
        alert("Your Turn!");
get called exponentially more with every session. Does jQuery use the parent function to track the click events or something? Can anyone explain what's happening under the hood? Why do the event handlers keep referring to the parent function?

答:
Move your function implementation out from the gameLogic function like bellow;

```<code>function gameScreenClick(){
 // your click event handler code.....
}
</code>```

then

```<code>$(".game-screen").on("click", ".tic", gameScreenClick);
</code>```

Body:
https://jsfiddle.net/50Lw423g/2/

  gameLogic: function() {
    console.log("GAME LOGIC");
    alert("Your Turn!");
    var that = this;
    $(".game-screen").on("click", ".tic", function() {
      console.log("EVENT ATTACHED");
      var movesDisplay = $(this).text(),
        playerOne = that.playerOneMoves,
        moveID = +(this.id);
      if (movesDisplay !== "O" && movesDisplay !== "X") {
        that.playerOneMoves.push(moveID);
        if (playerOne.length > 2) {
          if (that.checkIfWinCondition(playerOne, that.winConditions)) {
            alert("GAME OVER!");
            that.inGame = false;
            ticTacToe.restartGame();
          }
        }
        $(this).text(that.playerFaction === "X" ? "X" : "O");
      }
    });
  },

I'm writing a Tic-Tac-Toe game and ran into this problem - when multiple sessions are "played" click events keep compounding. Which I solved by clearing the previous click events every time before a new one is attached.

$(".game-screen").off().on("click", ".tic", function () { //do stuff }

By the way event.stopPropagation() and event.stopImmediatePropagation() did NOT work.

Anyway, while I managed to fix the problem and understand why the click events where compounding, what I can't seem to wrap my head around is why those compounded click events kept calling the parent function gameLogic: function(). Try "playing" several sessions in a row -

console.log("GAME LOGIC");
        alert("Your Turn!");
get called exponentially more with every session. Does jQuery use the parent function to track the click events or something? Can anyone explain what's happening under the hood? Why do the event handlers keep referring to the parent function?

Body:
Move your function implementation out from the gameLogic function like bellow;

function gameScreenClick(){
 // your click event handler code.....
}

then

$(".game-screen").on("click", ".tic", gameScreenClick);


问:
What does the bind parameter do in Redis?
What is the bind parameter in Redis? The documentation for bind assumes that I already know what bind means (which I don't). Does bind set the IP address of:

the Redis server? (I think this is the correct answer, but then I don't understand why we need that)

the client that will be authorized to connect to Redis? (I tried and it didn't work, so probably incorrect)

答:
Open the redis.conf as a root user by typing command in the terminal, such as:nano /etc/redis/redis.conf and comment the line e.g

```<code>#bind 0.0.0.0.
</code>```

By doing this you'll be able to connect to redis-server through every remote PC.

Body:
Open the redis.conf as a root user by typing command in the terminal, such as:nano /etc/redis/redis.conf and comment the line e.g

#bind 0.0.0.0.

By doing this you'll be able to connect to redis-server through every remote PC.

ContentLicense: CC BY-SA 4.0


问:
(Protractor e2e) Getting error "A Jasmine Spec timed out: Resetting WebDriver Control Flow"
Hoping someone can help me out on this, as i've been searching around for days with no success

I'm currently attempting to use Protractor for e2e testing of an AngularJS application

I've got Protractor setup and running a test, however when I have more than one test / spec, the first test runs and then errors out with the following on the command line:

A Jasmine spec timed out. Resetting the WebDriver Control Flow.
  The last active task was: unknown

My config.js is as follows:

```<code>// conf.js
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js','fileupload.js'],
  allScriptsTimeout: 20000,

  // Options to be passed to Jasmine-node.
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 100000,
    isVerbose: true
  }
};
</code>```

Here are both of my Jasmine tests

// spec.js

```<code>describe('Site login', function () {
    it('should login', function () {
        browser.driver.get('http://mysite.co.uk');
        browser.driver.findElement(by.name('UserName')).sendKeys('user');
        browser.driver.findElement(by.name('Password')).sendKeys('xpassword');
        browser.driver.findElement(by.id('logIn')).click();

        expect(browser.driver.findElement(by.id('topUsername')).getText()).toContain('user');

        browser.close();
    });
});
</code>```

// File Upload spec

```<code>describe('File Upload', function() {
    it('should upload a file', function () {
        browser.driver.get('http://mysite.co.uk');
        browser.driver.findElement(by.name('UserName')).sendKeys('user');
        browser.driver.findElement(by.name('Password')).sendKeys('xpassword');
        browser.driver.findElement(by.id('logIn')).click();

        browser.driver.findElement(by.id('upload')).click();
        browser.driver.findElement(by.name('FileToUpload')).sendKeys("C:\\myfile.csv");
        browser.driver.findElement(by.xpath('html/body/div[1]/div[7]/div[2]/div/button[2]/span')).click();
        console.log('file has been uploaded');
        });
    });
</code>```

Any help would be greatly appreciated

P.S apologies if I've formatted anything wrong, first time poster :)

Edit: Issue resolved by updating to Protractor v1.0.0 via npm update

Thanks a lot for everyone's help :)

答:
refer to      framework: 'jasmine2',

this to your protractor config
i've been having the same issue for days! lemme know if it helps!

Body:
Hoping someone can help me out on this, as i've been searching around for days with no success

I'm currently attempting to use Protractor for e2e testing of an AngularJS application

I've got Protractor setup and running a test, however when I have more than one test / spec, the first test runs and then errors out with the following on the command line:

A Jasmine spec timed out. Resetting the WebDriver Control Flow.
  The last active task was: unknown

My config.js is as follows:

// conf.js
exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js','fileupload.js'],
  allScriptsTimeout: 20000,

  // Options to be passed to Jasmine-node.
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 100000,
    isVerbose: true
  }
};

Here are both of my Jasmine tests

// spec.js

describe('Site login', function () {
    it('should login', function () {
        browser.driver.get('http://mysite.co.uk');
        browser.driver.findElement(by.name('UserName')).sendKeys('user');
        browser.driver.findElement(by.name('Password')).sendKeys('xpassword');
        browser.driver.findElement(by.id('logIn')).click();

        expect(browser.driver.findElement(by.id('topUsername')).getText()).toContain('user');

        browser.close();
    });
});

// File Upload spec

describe('File Upload', function() {
    it('should upload a file', function () {
        browser.driver.get('http://mysite.co.uk');
        browser.driver.findElement(by.name('UserName')).sendKeys('user');
        browser.driver.findElement(by.name('Password')).sendKeys('xpassword');
        browser.driver.findElement(by.id('logIn')).click();

        browser.driver.findElement(by.id('upload')).click();
        browser.driver.findElement(by.name('FileToUpload')).sendKeys("C:\\myfile.csv");
        browser.driver.findElement(by.xpath('html/body/div[1]/div[7]/div[2]/div/button[2]/span')).click();
        console.log('file has been uploaded');
        });
    });

Any help would be greatly appreciated

P.S apologies if I've formatted anything wrong, first time poster :)

Edit: Issue resolved by updating to Protractor v1.0.0 via npm update

Thanks a lot for everyone's help :)


问:
Setting a UIImageView to an initial state of blurred
I'm attempting to initially blur a background image on a UIViewController. When an @IBAction is called, I'd like to unblur backgroundImage. I can get the image to initially blur, but I can't get rid of the blur if I initially blur it. However, if I don't initially blur backgroundImage, my method works as desired by toggling between a blurred and unblurred image.

These are the relevant variables on my UIViewController class.

```<code>@IBOutlet weak var backgroundImage: UIImageView!
// I also leave this hanging around so I can add/remove it as needed
var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
</code>```

When the view loads, I'd initially like backgroundImage to have a UIVisualEffectView over it. I initially tried to call toggleBlurView in viewDidLoad, but the display of the UIBlurEffect was off, so I added the code for toggleBlurView in viewDidLayoutSubviews, which fixed that problem.

```<code>override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // if I comment this out, the toggleBlurView() method works as desired
    toggleBlurView()
}
</code>```

Here's my toggleBlurView method.

```<code>func toggleBlurView() {
    // if there's a blurView, remove it...
    if blurView.isDescendant(of: backgroundImage) {
        blurView.removeFromSuperview()
    }
    // otherwise, add blurView to backgroundImage
    else {
        blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
        blurView.frame = backgroundImage.bounds
        backgroundImage.addSubview(blurView)
    }
}
</code>```

I have an @IBAction that, when called, also runs the toggleBlurView method.

```<code>@IBAction func playFrequency(_ sender: UIButton) {
    // do stuff
    toggleBlurView()
}
</code>```

My code does not crash, but I can't get the desired results. I'm not sure if I've found a bug or I'm doing something wrong. I'm wagering the latter. Thank you for reading and I welcome suggestions how to set an image to an initial state of blurred.

答:
I got the following code working as you want it to.  I changed up the toggleBlurView function so it's a little more flexible, but this shouldn't affect the functionality.

```<code>//
//  ViewController.swift
//  tableviewheader-test
//
//  Created by Forest Kunecke on 3/29/17.
//  Use this code for freeeeee!!!!  Free as in free beer!!
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myImage: UIImageView!
    var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))

    override func viewDidLoad() {
        super.viewDidLoad()

        toggleBlurView(myImage)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func toggleBlur(_ sender: Any) {
        toggleBlurView(myImage)
    }

    func toggleBlurView(_ imageView: UIImageView) {
        // if there's a blurView, remove it...
        if blurView.isDescendant(of: imageView) {
            blurView.removeFromSuperview()
        }
            // otherwise, add blurView to backgroundImage
        else {
            blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
            blurView.frame = imageView.bounds
            imageView.addSubview(blurView)
        }
    }

}
</code>```

Here is a screenshot of my storyboard:

Body:
I'm attempting to initially blur a background image on a UIViewController. When an @IBAction is called, I'd like to unblur backgroundImage. I can get the image to initially blur, but I can't get rid of the blur if I initially blur it. However, if I don't initially blur backgroundImage, my method works as desired by toggling between a blurred and unblurred image.

These are the relevant variables on my UIViewController class.

@IBOutlet weak var backgroundImage: UIImageView!
// I also leave this hanging around so I can add/remove it as needed
var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))

When the view loads, I'd initially like backgroundImage to have a UIVisualEffectView over it. I initially tried to call toggleBlurView in viewDidLoad, but the display of the UIBlurEffect was off, so I added the code for toggleBlurView in viewDidLayoutSubviews, which fixed that problem.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // if I comment this out, the toggleBlurView() method works as desired
    toggleBlurView()
}

Here's my toggleBlurView method.

func toggleBlurView() {
    // if there's a blurView, remove it...
    if blurView.isDescendant(of: backgroundImage) {
        blurView.removeFromSuperview()
    }
    // otherwise, add blurView to backgroundImage
    else {
        blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
        blurView.frame = backgroundImage.bounds
        backgroundImage.addSubview(blurView)
    }
}

I have an @IBAction that, when called, also runs the toggleBlurView method.

@IBAction func playFrequency(_ sender: UIButton) {
    // do stuff
    toggleBlurView()
}

My code does not crash, but I can't get the desired results. I'm not sure if I've found a bug or I'm doing something wrong. I'm wagering the latter. Thank you for reading and I welcome suggestions how to set an image to an initial state of blurred.

Body:
I got the following code working as you want it to.  I changed up the toggleBlurView function so it's a little more flexible, but this shouldn't affect the functionality.

//
//  ViewController.swift
//  tableviewheader-test
//
//  Created by Forest Kunecke on 3/29/17.
//  Use this code for freeeeee!!!!  Free as in free beer!!
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myImage: UIImageView!
    var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))

    override func viewDidLoad() {
        super.viewDidLoad()

        toggleBlurView(myImage)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func toggleBlur(_ sender: Any) {
        toggleBlurView(myImage)
    }

    func toggleBlurView(_ imageView: UIImageView) {
        // if there's a blurView, remove it...
        if blurView.isDescendant(of: imageView) {
            blurView.removeFromSuperview()
        }
            // otherwise, add blurView to backgroundImage
        else {
            blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
            blurView.frame = imageView.bounds
            imageView.addSubview(blurView)
        }
    }

}

Here is a screenshot of my storyboard:


问:
Updating an HTML list using Js
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

```<code><ul>
     <li>apple</li>
     <li>ball</li>
</ul>
</code>```

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

```<code>document.getElementById('currentword').innerHTML = word;
</code>```

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

答:
I use jQuery for dom manipulation and would recommend the same for you, it adds a lot of readability and tons of neat (x-browser friendly) functionality.

For example... the append api call would do the job if you were using jQuery.

```<code><ul id="words">
 <li>Some Word</li>
 <li>Another Word</li>
</ul>

$("#words").append("<li>" + yourNewWord + "</li>");
</code>```

Or with straight javascript...

```<code>document.getElementById('words').innerHTML += '<li>' + yourNewWord + '</li>';
</code>```

EDIT:
I believe in motools the equivalent to .append is .grab

Title: Updating an HTML list using Js

Body:
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

apple

ball

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

document.getElementById('currentword').innerHTML = word;

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

Body:
I use jQuery for dom manipulation and would recommend the same for you, it adds a lot of readability and tons of neat (x-browser friendly) functionality.

For example... the append api call would do the job if you were using jQuery.

<ul id="words">
 <li>Some Word</li>
 <li>Another Word</li>
</ul>

$("#words").append("<li>" + yourNewWord + "</li>");

Or with straight javascript...

document.getElementById('words').innerHTML += '<li>' + yourNewWord + '</li>';

EDIT:
I believe in motools the equivalent to .append is .grab


问:
Calling Haskell from c++
I'm trying to call Haskell from c++.

I tried to use this explanation; and already asked one question on SO.

However, I haven't got any answer so I'd like to reformulate to a Minimal, Complete, and Verifiable example.

I'm using Debian and this is what I have (In the same folder):

c++:

```<code>// main.cpp
#include <iostream>
#include "Hello_stub.h"

int main(int argc, char** argv) {
  hs_init(&argc, &argv);
  std::cout << "Hello from C++\n";
  helloFromHaskell();
  hs_exit();
  return 0;
}
</code>```

Haskell:

```<code>// hello.hs
module Hello where

foreign export ccall helloFromHaskell :: IO ()

helloFromHaskell :: IO ()
helloFromHaskell = putStrLn "Hello from Haskell"
</code>```

MakeFile:

```<code>CPP_SOURCES = main.cpp
HASKELL_SOURCES = Hello.hs
CFLAGS = -Wall -g -fno-stack-protector
HFLAGS = -fforce-recomp

all: main; ./main

main: $(CPP_SOURCES) HaskellPart; g++ \
    $(CFLAGS) -o main $(CPP_SOURCES) Hello.o \
    -I/usr/lib/ghc/include \
    -liconv \
    -I/usr/lib/ghc/ghc-8.0.1/include \
    -L/usr/lib/ghc/ghc-8.0.1 \
    -L/usr/lib/ghc/base-4.9.0.0 \
    -lHSbase-4.9.0.0 \
    -L/usr/lib/ghc/ghc-prim-0.5.0.0 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/integer-gmp-1.0.0.1 \
    -lHSinteger-gmp-1.0.0.1 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/rts \
    -lHSrts \

HaskellPart: $(HASKELL_SOURCES); ghc $(HFLAGS) $(HASKELL_SOURCES)

clean: ; rm -rf main && rm -rf *.o && rm -rf *.hi && rm -rf *_stub.h
</code>```

Here's the output. It seems to be a bunch of errors of the form

```<code>/usr/bin/ld: Hello.o: relocation R_X86_64_32S against symbol `stg_bh_upd_frame_info' can not be used when making a shared object; recompile with -fPIC
</code>```

What's wrong? Thank you for your help !

答:
Not sure whether that's actually in your file or whether it's just in the version you put in your question but "// hello.hs" won't compile. Comments are -- in Haskell not //.

Anyway on to the interesting part...

First you need to import the HsFFI.h header file into your C++ code.

```<code>#include <iostream>
#include "Hello_stub.h"
#include <HsFFI.h>
</code>```

Then use ghc to link the files after compiling them. Open a command prompt / terminal and navigate the directory containing your C++ and Haskell files. Then run the following commands:

```<code>ghc -c -XForeignFunctionInterface -O hello.hs
g++ -c -O main.cpp -I "C:\Program Files\Haskell Platform\7.10.3\lib\include"
ghc -no-hs-main hello.o main.o -lstdc++
</code>```

The filepath in the second command is to the directory containing the HsFFI.h file.

Running main then outputs:

```<code>Hello from C++
Hello from Haskell
</code>```

Title: Calling Haskell from c++

Body:
I'm trying to call Haskell from c++.

I tried to use this explanation; and already asked one question on SO.

However, I haven't got any answer so I'd like to reformulate to a Minimal, Complete, and Verifiable example.

I'm using Debian and this is what I have (In the same folder):

c++:

// main.cpp
#include <iostream>
#include "Hello_stub.h"

int main(int argc, char** argv) {
  hs_init(&argc, &argv);
  std::cout << "Hello from C++\n";
  helloFromHaskell();
  hs_exit();
  return 0;
}

Haskell:

// hello.hs
module Hello where

foreign export ccall helloFromHaskell :: IO ()

helloFromHaskell :: IO ()
helloFromHaskell = putStrLn "Hello from Haskell"

MakeFile:

CPP_SOURCES = main.cpp
HASKELL_SOURCES = Hello.hs
CFLAGS = -Wall -g -fno-stack-protector
HFLAGS = -fforce-recomp

all: main; ./main

main: $(CPP_SOURCES) HaskellPart; g++ \
    $(CFLAGS) -o main $(CPP_SOURCES) Hello.o \
    -I/usr/lib/ghc/include \
    -liconv \
    -I/usr/lib/ghc/ghc-8.0.1/include \
    -L/usr/lib/ghc/ghc-8.0.1 \
    -L/usr/lib/ghc/base-4.9.0.0 \
    -lHSbase-4.9.0.0 \
    -L/usr/lib/ghc/ghc-prim-0.5.0.0 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/integer-gmp-1.0.0.1 \
    -lHSinteger-gmp-1.0.0.1 \
    -lHSghc-prim-0.5.0.0 \
    -L/usr/lib/ghc/rts \
    -lHSrts \

HaskellPart: $(HASKELL_SOURCES); ghc $(HFLAGS) $(HASKELL_SOURCES)

clean: ; rm -rf main && rm -rf *.o && rm -rf *.hi && rm -rf *_stub.h

Here's the output. It seems to be a bunch of errors of the form

/usr/bin/ld: Hello.o: relocation R_X86_64_32S against symbol `stg_bh_upd_frame_info' can not be used when making a shared object; recompile with -fPIC

What's wrong? Thank you for your help !

Body:
Not sure whether that's actually in your file or whether it's just in the version you put in your question but "// hello.hs" won't compile. Comments are -- in Haskell not //.

Anyway on to the interesting part...

First you need to import the HsFFI.h header file into your C++ code.

#include <iostream>
#include "Hello_stub.h"
#include <HsFFI.h>

Then use ghc to link the files after compiling them. Open a command prompt / terminal and navigate the directory containing your C++ and Haskell files. Then run the following commands:

ghc -c -XForeignFunctionInterface -O hello.hs
g++ -c -O main.cpp -I "C:\Program Files\Haskell Platform\7.10.3\lib\include"
ghc -no-hs-main hello.o main.o -lstdc++

The filepath in the second command is to the directory containing the HsFFI.h file.

Running main then outputs:

Hello from C++
Hello from Haskell


问:
Find a duplicate in an extremely large data set
Recently, I was asked the following question in an interview.

Q : Given a N integers, only one of which is a duplicate, find that duplicate number.

I answered with a solution that had the numbers stored in a hashmap and finding duplicates by checking for the existence of a key.

He then followed it up with What if the data set is very large, so large that you cannot store it in memory, like a continuous stream?

That kinda stumped me. Can someone suggest some answers? Also, are there any more efficient solutions other than hashmaps for the original question ?

TIA

答:
How large or small are those integers? If it's certain all the integers fall within 2^30-1 to -2^30, or a smaller range, try java.util.BitSet.
2^31 bits = 2^28 bytes ~ 2^8 mega bytes = 256 mega bytes. This is small enough to be stored in memory for ordinary notebook computers.

Suppose the integers fall within 2^30-1 to -2^30, the method is simple; for each integer i in the large data set, set j = i + 2^30 first, and check if bitSet.get(j) is true, if true, the duplicate number is i, else invoke bitSet.set(j, true) and continue until the duplicate is found. It's similar if the integers fall within 0 to 2^31 -1.

```<code>BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream("a.txt"), StandardCharsets.UTF_8));
        String line = null;
        BitSet bitSet = new BitSet((1<<31)- 1);
        while ((line = reader.readLine()) != null) {
            int i = Integer.parseInt(line);
            boolean v = bitSet.get(i);
            if (v){
                System.out.println("the duplicate is " + i);
                break;
            }else{
                bitSet.set(i);
            }

        }
        reader.close();
</code>```

And if the range is slightly larger, like 0 to 2^34 - 1, one tryable idea is to copy paste the java.util.BitSet class and made some modification it to create a slightly different one; one long[] array can store maximally ((2^31 - 1) * 2^6 - 1) bits. Ordinary computer can still afford 2G memory for an object.

If the range is larger or this duplication finding module cannot take much memory, refer to questions in the comments above like Algorithm for detecting duplicates in a dataset which is too large to be completely loaded into memory

Body:
How large or small are those integers? If it's certain all the integers fall within 2^30-1 to -2^30, or a smaller range, try java.util.BitSet.
2^31 bits = 2^28 bytes ~ 2^8 mega bytes = 256 mega bytes. This is small enough to be stored in memory for ordinary notebook computers.

Suppose the integers fall within 2^30-1 to -2^30, the method is simple; for each integer i in the large data set, set j = i + 2^30 first, and check if bitSet.get(j) is true, if true, the duplicate number is i, else invoke bitSet.set(j, true) and continue until the duplicate is found. It's similar if the integers fall within 0 to 2^31 -1.

BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream("a.txt"), StandardCharsets.UTF_8));
        String line = null;
        BitSet bitSet = new BitSet((1<<31)- 1);
        while ((line = reader.readLine()) != null) {
            int i = Integer.parseInt(line);
            boolean v = bitSet.get(i);
            if (v){
                System.out.println("the duplicate is " + i);
                break;
            }else{
                bitSet.set(i);
            }

        }
        reader.close();

And if the range is slightly larger, like 0 to 2^34 - 1, one tryable idea is to copy paste the java.util.BitSet class and made some modification it to create a slightly different one; one long[] array can store maximally ((2^31 - 1) * 2^6 - 1) bits. Ordinary computer can still afford 2G memory for an object.

If the range is larger or this duplication finding module cannot take much memory, refer to questions in the comments above like Algorithm for detecting duplicates in a dataset which is too large to be completely loaded into memory


问:
lambda with more than one effect
I have three different classes of some common interface Bag. Those are simple containers with some properties. I can add a bunch of stuff in them, e.g ints. For purposes of unit testing, I wanted to add a number of values to each and every one of those Bags. So I used the following IntConsumer:

```<code>IntStream.rangeClosed(1, 300).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        staticBag.add(value);
        shuffledBag.add(value);
        randomAccessBag.add(value);
        }
    });
</code>```

My question is how that might be changeable to a lambda expression. Intellij is usually doing a pretty good job at changing those things automatically, but at this point it hasn't been showing me any tips.

答:
Intellij did it for me!  Here you go:</p>

```<code>IntStream.rangeClosed(1, 300).forEach(value -> {
    staticBag.add(value);
    shuffledBag.add(value);
    randomAccessBag.add(value);
});
</code>```

Title: lambda with more than one effect

Body:
I have three different classes of some common interface Bag. Those are simple containers with some properties. I can add a bunch of stuff in them, e.g ints. For purposes of unit testing, I wanted to add a number of values to each and every one of those Bags. So I used the following IntConsumer:

IntStream.rangeClosed(1, 300).forEach(new IntConsumer() {
    @Override
    public void accept(int value) {
        staticBag.add(value);
        shuffledBag.add(value);
        randomAccessBag.add(value);
        }
    });

My question is how that might be changeable to a lambda expression. Intellij is usually doing a pretty good job at changing those things automatically, but at this point it hasn't been showing me any tips.

Body:
Intellij did it for me!  Here you go:

IntStream.rangeClosed(1, 300).forEach(value -> {
    staticBag.add(value);
    shuffledBag.add(value);
    randomAccessBag.add(value);
});


问:
AngularJS cannot grab values with ng-model while using ng-repeat
I am trying to grab dynamically created information with ng-model (info created with ng-repeat). I am doing so in order to send the information in the form of an object to my flat database, Firebase. Unfortunately, the ng-model is only grabbing "" (empty strings) as my values. Any suggestions?

/////////// Controller below

 // Bookmark object
 $scope.bookmark = {
  url: "",
  illnessName: "",
  symptom: ""
 };

 // Save illness card to bookmarks
 $scope.saveToBookmarks = ($bookmark) => {
  console.log($bookmark);

  if ($scope.bookmark.illnessName === ""){
   alert("Hey, quit that NAME!");
   return;
  }
  if ($scope.bookmark.symptom === ""){
   alert("Hey, quit that SYMPTOM!");
   return;
  }
  if ($scope.bookmark.url === ""){
   alert("Hey, quit that URL!");
   return;
  }

  BookmarksFactory.addUserBookmark({
   url: $scope.bookmark.url,
   illnessName: $scope.bookmark.illnessName,
   symptom: $scope.bookmark.symptom
  });
  console.log("$scope.bookmark.url :",  $scope.bookmark.url);
 };

  ///////// Factory below
  "use strict";

app.factory("BookmarksFactory", function(FBCreds, $q, $http) {

 var addUserBookmark = (newBookmark) =>{
  console.log("Factory is working!");
  return $q( (resolve, reject) => {
   $http.post(`${FBCreds.databaseURL}/bookmarks.json`,
    JSON.stringify(newBookmark))
   .then( (FBObj) => {
    resolve(FBObj);
   })
   .catch( (error) => {
    reject(error);
   });
  });
 };

 return {
  addUserBookmark
 };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <!-- This will be search results populate -->
  <div class="search-results" >
   <div class="row">
    <div class="col-lg-4 text-center search-card box" ng-repeat="illness in illnesses | filter: searchText.search">
     <!-- Insert search results here -->
     <div class="inner ">
      <div class="card">
       <button type="button" class="close close-card" aria-label="Close" ng-click="removeCard($event)">
         <span class="close-card-x" aria-hidden="true">×</span>
       </button>
       <img class="card-img-top" src="{{illness.url}}" alt="Card image cap" ng-model="bookmark.url">
       <div class="card-block">
        <h4 class="card-title" ng-model="bookmark.illnessName">{{illness.illnessName}}</h4>
        <p class="card-text" ng-model="bookmark.symptom">{{illness.symptom}}</p>
        <button class="btn btn-primary" ng-click="saveToBookmarks(bookmark)">Save</button>
        <button class="btn btn-success" ng-click="goToEditPage()">Edit</button>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div></code>```

答:
change  to $scope.bookmark ={};
and use http to get data file you code , example of me is test.php

```<code>$http(){
           method:'POST',
           url:'test.php',
           data : $.param($scope.bookmark),
           headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).then(success)
function success(){
////
</code>```

}

Body:
I am trying to grab dynamically created information with ng-model (info created with ng-repeat). I am doing so in order to send the information in the form of an object to my flat database, Firebase. Unfortunately, the ng-model is only grabbing "" (empty strings) as my values. Any suggestions?

/////////// Controller below

 // Bookmark object
 $scope.bookmark = {
  url: "",
  illnessName: "",
  symptom: ""
 };

 // Save illness card to bookmarks
 $scope.saveToBookmarks = ($bookmark) => {
  console.log($bookmark);

  if ($scope.bookmark.illnessName === ""){
   alert("Hey, quit that NAME!");
   return;
  }
  if ($scope.bookmark.symptom === ""){
   alert("Hey, quit that SYMPTOM!");
   return;
  }
  if ($scope.bookmark.url === ""){
   alert("Hey, quit that URL!");
   return;
  }

  BookmarksFactory.addUserBookmark({
   url: $scope.bookmark.url,
   illnessName: $scope.bookmark.illnessName,
   symptom: $scope.bookmark.symptom
  });
  console.log("$scope.bookmark.url :",  $scope.bookmark.url);
 };

  ///////// Factory below
  "use strict";

app.factory("BookmarksFactory", function(FBCreds, $q, $http) {

 var addUserBookmark = (newBookmark) =>{
  console.log("Factory is working!");
  return $q( (resolve, reject) => {
   $http.post(`${FBCreds.databaseURL}/bookmarks.json`,
    JSON.stringify(newBookmark))
   .then( (FBObj) => {
    resolve(FBObj);
   })
   .catch( (error) => {
    reject(error);
   });
  });
 };

 return {
  addUserBookmark
 };

});

       <button type="button" class="close close-card" aria-label="Close" ng-click="removeCard($event)">
         ×
       </button>

{{illness.illnessName}}

{{illness.symptom}}

        <button class="btn btn-primary" ng-click="saveToBookmarks(bookmark)">Save</button>
        <button class="btn btn-success" ng-click="goToEditPage()">Edit</button>

Body:
change  to $scope.bookmark ={};
and use http to get data file you code , example of me is test.php

$http(){
           method:'POST',
           url:'test.php',
           data : $.param($scope.bookmark),
           headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).then(success)
function success(){
////

}


问:
Function of function(functional) in Maxima
I want to define a function of a function ( maybe functional) in Maxima. For example, I want to define T in the code:

```<code>f(r,GN,M)::=(2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2);
X(r,GN,M) ::= 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r));
T(r,GN,M) ::= diff(f(r,GN,M),r)+X(r,GN,M);
</code>```

But I don't know the code.

答:
Define T as a function, rather than a macro, so that it evaluates its arguments.

```<code>(%i) T(r,GN,M) := diff(f(r,GN,M),r)+X(r,GN,M)$
</code>```

Now define a function t on T which quotes ' its arguments (so that T knows which variable to differentiate with respect to) and then evaluates the result %% with ev.

```<code>(%i) t(r,GN,M) := (T('r,'GN,'M),ev(%%))$
(%i) t(1,2,3);
(%o)                               2142
</code>```

Body:
I want to define a function of a function ( maybe functional) in Maxima. For example, I want to define T in the code:

f(r,GN,M)::=(2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2);
X(r,GN,M) ::= 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r));
T(r,GN,M) ::= diff(f(r,GN,M),r)+X(r,GN,M);

But I don't know the code.

Body:
Define T as a function, rather than a macro, so that it evaluates its arguments.

(%i) T(r,GN,M) := diff(f(r,GN,M),r)+X(r,GN,M)$

Now define a function t on T which quotes ' its arguments (so that T knows which variable to differentiate with respect to) and then evaluates the result %% with ev.

(%i) t(r,GN,M) := (T('r,'GN,'M),ev(%%))$
(%i) t(1,2,3);
(%o)                               2142


问:
How to remove the two lowest numbers from a listbox in Visual Basic 2015?
Ok so I'm supposed to have the user input up to 13 grades, then have them averaged after removing the two lowest grades. I can't figure out what to use to remove the two lowest grades, whether it be from the listbox or during the calculation. Here's my code so far:</p>

```<code>    Dim strGrades As String
    Dim decGrades As Decimal = 0
    Dim decAverage As Decimal = 0
    Dim decTotal As Decimal = 0

    Dim strInputMessage As String = "Enter grade #"
    Dim strInputHeading As String = "Grade"
    Dim strNormalMessage As String = "Enter grade #"
    Dim strNonNumericError As String = "Error - Please enter a grade"
    Dim strNegativeError As String = "Error - Please enter a positive number"

    Dim strCancelClicked As String = ""
    Dim intMaxNumberOfEntries As Decimal = 13
    Dim intNumberOfEntries As Decimal = 1

    strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")

    Do Until intNumberOfEntries > intMaxNumberOfEntries Or strGrades = strCancelClicked
        If IsNumeric(strGrades) Then
            decGrades = Convert.ToDecimal(strGrades)
            If decGrades >= 0 Then
                lstGrades.Items.Add(decGrades)
                decTotal += decGrades
                intNumberOfEntries += 1
                strInputMessage = strNormalMessage
            Else
                strInputMessage = strNegativeError
            End If
        Else
            strInputMessage = strNonNumericError
        End If

        If intNumberOfEntries <= intMaxNumberOfEntries Then
            strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
        End If

    Loop
    lstGrades.Sorted = True
</code>```

答:
You can count the entries in the list box and remove the bottom 2 entries.

You can add them to a list and sort it.

Body:
Ok so I'm supposed to have the user input up to 13 grades, then have them averaged after removing the two lowest grades. I can't figure out what to use to remove the two lowest grades, whether it be from the listbox or during the calculation. Here's my code so far:

    Dim strGrades As String
    Dim decGrades As Decimal = 0
    Dim decAverage As Decimal = 0
    Dim decTotal As Decimal = 0

    Dim strInputMessage As String = "Enter grade #"
    Dim strInputHeading As String = "Grade"
    Dim strNormalMessage As String = "Enter grade #"
    Dim strNonNumericError As String = "Error - Please enter a grade"
    Dim strNegativeError As String = "Error - Please enter a positive number"

    Dim strCancelClicked As String = ""
    Dim intMaxNumberOfEntries As Decimal = 13
    Dim intNumberOfEntries As Decimal = 1

    strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")

    Do Until intNumberOfEntries > intMaxNumberOfEntries Or strGrades = strCancelClicked
        If IsNumeric(strGrades) Then
            decGrades = Convert.ToDecimal(strGrades)
            If decGrades >= 0 Then
                lstGrades.Items.Add(decGrades)
                decTotal += decGrades
                intNumberOfEntries += 1
                strInputMessage = strNormalMessage
            Else
                strInputMessage = strNegativeError
            End If
        Else
            strInputMessage = strNonNumericError
        End If

        If intNumberOfEntries <= intMaxNumberOfEntries Then
            strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
        End If

    Loop
    lstGrades.Sorted = True


问:
Loop through php array issues
I'm sure I've been staring at this WAY too long, so asking for a lifeline.

I'm pulling data from a MySQL database. In particular this:

```<code>$category[] = "$row->category";
$issue[] = "$row->issue";
</code>```

I need to cycle through the data. There are 6 categories in total and could be any number of issues for each category.

I would like to echo the data for each row as follows:

```<code>Category 1
Issue 1a
Issue 1b
Issue 1c

Category 2
Issue 2a
Issue 2b

Category 3
Issue 3a
Issue 3b
Issue 3c
Issue 3d
Issue 3e
</code>```

I probably need more sleep, but I cannot seem to cycle through this properly. Any help would be appreciated.

```<code>$stmt = $pdo->prepare("SELECT * FROM project INNER JOIN data1 ON project.p_key = data1.p_key_project WHERE data1.p_key_project=? AND data1.archived=? ORDER BY data1.category, data1.updated DESC");
$stmt->execute(array($passed_key,'n'));

while ($row = $stmt->fetchObject()) {
$cust[] = "$row->cust_name";
$p_key[] = "$row->p_key";
$pid[] = "$row->pid";
$account_key[] = "$row->account_key";
$p_key_data1[] = "$row->p_key_data1";
$date[] = "$row->date";
$updated[] = "$row->updated";
$category[] = "$row->category";
$ryg[] = "$row->ryg";
$issue[] = "$row->issue";
$proposed_resolution[] = "$row->proposed_resolution";
$action_items[] = "$row->action_items";
$owner[] = "$row->owner";
$status[] = "$row->status";
}
</code>```

答:
PDO version based on updates we've been talking about:

assume $issues is a multidimensional array of issues and categories you could do. i.e. $issue[] = "$row->issue, $row->category";

```<code>$numOfItems = count($issue); //counts number of times for should be run
   for ($row = 0; $row < $numofItems; $row++) {
     echo $issues[$row][$row] . "</br>";
     $i=0;
     while ($issues[$i][$row] == $issues[$row][$row]) {
      echo $issues[$i][$row] . "</br>";
      $i++;
    } }
</code>```

This is freehand - but it should work

OLD ANSWER BELOW

If you copy and paste the Database Schema (or a part of it) that would be helpful to see how Categories and Issues are related. Not seeing the exact relationship, I think this is probably how your database is structured

so lets that $category[] = "$row->category"; populates categories; now you have to match issues to each category. I assume that a row in your database has a category assigned to each issue. i.e. your database looks like

```<code>ID | Category | Issue
1  | Pizza    | Bad
2  | Pizza    | Good
</code>```

If thats the case then below should work

```<code>foreach ($category as $key => $value) {
    $query = mysqli_query($con,"SELECT * FROM project INNER JOIN data1 ON project.p_key = data1.p_key_project WHERE data1.p_key_project=? AND data1.archived=? AND data1.category='$value' ORDER BY data1.category, data1.updated DESC"); //value is the individual category
    echo $value . "</br>";
        while($row = mysqli_fetch_array($query)) {
            echo $row['issue'] . '</br>';
        }
    echo "</br>"; //adds an extra space between categories
}
</code>```

Updated to include your specific query

Title: Loop through php array issues

Body:
I'm sure I've been staring at this WAY too long, so asking for a lifeline.

I'm pulling data from a MySQL database. In particular this:

$category[] = "$row->category";
$issue[] = "$row->issue";

I need to cycle through the data. There are 6 categories in total and could be any number of issues for each category.

I would like to echo the data for each row as follows:

Category 1
Issue 1a
Issue 1b
Issue 1c

Category 2
Issue 2a
Issue 2b

Category 3
Issue 3a
Issue 3b
Issue 3c
Issue 3d
Issue 3e

I probably need more sleep, but I cannot seem to cycle through this properly. Any help would be appreciated.

$stmt = $pdo->prepare("SELECT * FROM project INNER JOIN data1 ON project.p_key = data1.p_key_project WHERE data1.p_key_project=? AND data1.archived=? ORDER BY data1.category, data1.updated DESC");
$stmt->execute(array($passed_key,'n'));

while ($row = $stmt->fetchObject()) {
$cust[] = "$row->cust_name";
$p_key[] = "$row->p_key";
$pid[] = "$row->pid";
$account_key[] = "$row->account_key";
$p_key_data1[] = "$row->p_key_data1";
$date[] = "$row->date";
$updated[] = "$row->updated";
$category[] = "$row->category";
$ryg[] = "$row->ryg";
$issue[] = "$row->issue";
$proposed_resolution[] = "$row->proposed_resolution";
$action_items[] = "$row->action_items";
$owner[] = "$row->owner";
$status[] = "$row->status";
}

Body:
PDO version based on updates we've been talking about:

assume $issues is a multidimensional array of issues and categories you could do. i.e. $issue[] = "$row->issue, $row->category";

$numOfItems = count($issue); //counts number of times for should be run
   for ($row = 0; $row < $numofItems; $row++) {
     echo $issues[$row][$row] . "</br>";
     $i=0;
     while ($issues[$i][$row] == $issues[$row][$row]) {
      echo $issues[$i][$row] . "</br>";
      $i++;
    } }

This is freehand - but it should work

OLD ANSWER BELOW

If you copy and paste the Database Schema (or a part of it) that would be helpful to see how Categories and Issues are related. Not seeing the exact relationship, I think this is probably how your database is structured

so lets that $category[] = "$row->category"; populates categories; now you have to match issues to each category. I assume that a row in your database has a category assigned to each issue. i.e. your database looks like

ID | Category | Issue
1  | Pizza    | Bad
2  | Pizza    | Good

If thats the case then below should work

foreach ($category as $key => $value) {
    $query = mysqli_query($con,"SELECT * FROM project INNER JOIN data1 ON project.p_key = data1.p_key_project WHERE data1.p_key_project=? AND data1.archived=? AND data1.category='$value' ORDER BY data1.category, data1.updated DESC"); //value is the individual category
    echo $value . "</br>";
        while($row = mysqli_fetch_array($query)) {
            echo $row['issue'] . '</br>';
        }
    echo "</br>"; //adds an extra space between categories
}

Updated to include your specific query


问:
Wordpress table prefix must not be empty
I'm using the next: PhPStorm, MAMP PRO and Wordpress.

I create a new database to create a new Wordpress webpage, but when i fill all i get 'table prefix must not be empty'. Of course is not empty. I put wp_, it_, rt_, etc. But I get always the same error. I saw a post that maybe was due to MySQL version and I should create the tables InnoDB again. Of course it didn't work. I tried with an older version of MAMP PRO -actually the v.3-.

I try to do the same but I get the same error. I go to mysql directory and i cannot find any of these tables innodb_index_stats, innodb_table_stats, slave_master_info, slave_relay_log_info, slave_worker_info. I should create them, but I cannot do it with 'STATS_PERSISTENT=0;'

¿What else can I do?

答: It sounds like you updated MySQL (or MAMP) but failed to run mysql_update.


问:
@ApiModelProperty Swagger-Mvc
Hello guys I have a problem with swagger-mvc (version 0.9.5).

I have the following restcontroller:

CanvasController.java (snippet)

/**
 * The Class CanvasController.
 */
@Api(description = "Operations for canvases", value="canvascontroller")
@RestController
@RequestMapping(value = "/api/canvas")
public class CanvasController {

  ...

  @ApiResponses(value = {
    @ApiResponse(code = 200, message = "No problem occurred.")
  })
  @ApiOperation(value = "Returns all canvases.", notes = "Returns all canvases.", response = Canvas.class, responseContainer = "List")
  @RequestMapping(value = {"/all", "", "/"}, method = {        RequestMethod.GET, RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_VALUE)
  public @ResponseBody ResponseEntity < List < Canvas >> getAll() {
    return new ResponseEntity < List < Canvas >> (canvasService.findAll(),
      HttpStatus.OK);
  }

}
```

<p>Canvas.java</p>

<pre class="lang-java prettyprint-override"><code>package cloudincubator.canvas.db;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.codehaus.jackson.annotate.JsonProperty;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.wordnik.swagger.annotations.ApiModel;
import com.wordnik.swagger.annotations.ApiModelProperty;

/**
 * The Class Canvas.
 */
@Entity
@Table(name = "Canvas", uniqueConstraints = {@UniqueConstraint(columnNames = {"C_Id"})})
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@canvasId")
@ApiModel(value = "Canvas", description = "Represents a canvas in the database.")
public class Canvas
 {

    /** The {@link CanvasGroup} to which this Canvas belongs. */
    @ManyToOne(optional = true)
    @JoinColumn(name = "C_Canvas_Group_Id", referencedColumnName = "CG_Id", nullable = true)
    private CanvasGroup ccanvasgroup;

    /** The description of this Canvas. */
    @Column(name = "C_Description")
    @ApiModelProperty(value="Description")
    @JsonProperty("TEST")
    private String cdescription;

    /** The x position in the CanvasGroup grid. */
    @Column(name = "C_GridX")
    @ApiModelProperty(value="GridX")
    private Integer cgridx;

    /** The y position in the CanvasGroup grid. */
    @Column(name = "C_GridY")
    @ApiModelProperty(value="GridY")
    private Integer cgridy;

    /** The height of this Canvas. */
    @Column(name = "C_Height")
    private Integer cheight;

    /** The path of the icon which belongs to this Canvas. */
    @Column(name = "C_Icon")
    private String cicon;

    /** The identifier of this Canvas. */
    @Id
    @Column(name = "C_Id", table = "Canvas")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long cid;

    /** The name of this Canvas. */
    @Column(name = "C_Name")
    private String cname;

    /** The shortcut of this Canvas. */
    @Column(name = "C_Shortcut")
    private String cshortcut;

    /** The {@link Sticker Stickers} which belong to this Canvas. */
    @OneToMany(cascade = CascadeType.ALL, mappedBy="scanvas")
    @Column(nullable = true)
    private List<Sticker> cstickers;

    /** The width of this Canvas. */
    @Column(name = "C_Width")
    private Integer cwidth;

    /**
     * Instantiates a new Canvas.
     */
    public Canvas(){}

    /**
     * Instantiates a new Canvas with the given identifier .
     *
     * @param cId : The identifier of this Canvas.
     */
    public Canvas(Long cId)
    {
        this.cid = cId;
    }

    /**
     * Instantiates a new Canvas with the given name.
     *
     * @param cName : The name of this Canvas.
     */
    public Canvas(String cName) {
        this.cname  = cName;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object other) {
        if (this == other) return true;
        if ( !(other instanceof Canvas) ) return false;

        final Canvas canvas = (Canvas) other;

        if ( !canvas.getCId().equals( getCId() ) ) return false;

        return true;
    }

    /**
     * Gets the {@link CanvasGroup} to which this Canvas belongs.
     *
     * @return the {@link CanvasGroup}.
     */
//  @ApiModelProperty(position=1, required = true, hidden = false, dataType="cloudincubator.canvas.db.CanvasGroup")
    public CanvasGroup getCCanvasGroup() {
        return ccanvasgroup;
    }

    /**
     * Gets the description of this Canvas.
     *
     * @return the description of this Canvas.
     */
    public String getCDescription() {
        return cdescription;
    }

    /**
     * Gets the x position in the CanvasGroup grid of this Canvas.
     *
     * @return the x position in the CanvasGroup grid of this Canvas.
     */
    public Integer getCGridX() {
        return cgridx;
    }

    /**
     * Gets the y position in the CanvasGroup grid of this Canvas.
     *
     * @return the y position in the Canvasgroup grid of this Canvas.
     */
    public Integer getCGridY() {
        return cgridy;
    }

    /**
     * Gets the height of this Canvas.
     *
     * @return the height of this Canvas.
     */
    public Integer getCHeight() {
        return cheight;
    }

    /**
     * Gets the path of the icon which belongs to this Canvas.
     *
     * @return the icon path of this Canvas.
     */
    public String getCIcon() {
        return cicon;
    }

    /**
     * Gets the identifier of this Canvas.
     *
     * @return the identifier of this Canvas.
     */
    public Long getCId() {
        return cid;
    }

    /**
     * Gets the name of this Canvas.
     *
     * @return the name of this Canvas.
     */
    public String getCName() {
        return cname;
    }

    /**
     * Gets the shortcut of this Canvas.
     *
     * @return the shortcut of this Canvas.
     */
    public String getCShortcut() {
        return cshortcut;
    }

    /**
     * Gets the {@link Sticker Stickers} which belong to this Canvas.
     *
     * @return the {@link Sticker Stickers} which belong to this Canvas.
     */
    public List<Sticker> getCStickers()
    {
        return cstickers;
    }

    /**
     * Gets the width of this Canvas.
     *
     * @return the width of this Canvas.
     */
    public Integer getCWidth() {
        return cwidth;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return getCId().hashCode();
    }

    /**
     * Sets the {@link CanvasGroup} to which this Canvas belongs.
     *
     * @param cCanvasGroup : The {@link CanvasGroup} to set.
     */
    public void setCCanvasGroup(CanvasGroup cCanvasGroup) {
        ccanvasgroup = cCanvasGroup;
    }

    /**
     * Sets the description of this Canvas.
     *
     * @param cDescription : The description to set.
     */
    public void setCDescription(String cDescription) {
        cdescription = cDescription;
    }

    /**
     * Sets the x position in the CanvasGroup grid.
     *
     * @param cGridX : The x position to set.
     */
    public void setCGridX(Integer cGridX) {
        cgridx = cGridX;
    }

    /**
     * Sets the y position in the CanvasGroup grid.
     *
     * @param cGridY : The y position to set.
     */
    public void setCGridY(Integer cGridY) {
        cgridy = cGridY;
    }

    /**
     * Sets the height of this Canvas.
     *
     * @param cHeight : The height to set.
     */
    public void setCHeight(Integer cHeight) {
        cheight = cHeight;
    }

    /**
     * Sets the icon path of this Canvas.
     *
     * @param cIcon : The icon path to set.
     */
    public void setCIcon(String cIcon) {
        cicon = cIcon;
    }

    /**
     * Sets the identifier of this Canvas.
     *
     * @param cid : The identifier to set.
     */
    public void setCId(Long cid)
    {
        this.cid = cid;
    }

    /**
     * Sets the name of this Canvas.
     *
     * @param cName : The name to set
     */
    public void setCName(String cName) {
        cname = cName;
    }

    /**
     * Sets the shortcut of this Canvas.
     *
     * @param cShortcut : The shortcut to set
     */
    public void setCShortcut(String cShortcut) {
        cshortcut = cShortcut;
    }

    /**
     * Sets the {@link Sticker Stickers} which belong to this Canvas.
     *
     * @param cStickers : The list of {@link Sticker Stickers} to set.
     */
    public void setCStickers(List<Sticker> cStickers)
    {
        this.cstickers = cStickers;
    }

    /**
     * Sets the width of this Canvas.
     *
     * @param cWidth : The width to set.
     */
    public void setCWidth(Integer cWidth) {
        cwidth = cWidth;
    }
}
</code>```

swagger output

{
    "apiVersion": "1.0",
    "swaggerVersion": "1.2",
    "basePath": "/",
    "resourcePath": "/api/canvas",
    "produces": [
        "application/json"
    ],
    "consumes": [
        "application/json"
    ],
    "apis": [
        {
            "path": "/api/canvas",
            "description": "getAll",
            "operations": [
                {
                    "method": "GET",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                },
                {
                    "method": "POST",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 201,
                            "message": "Created"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                }
            ]
        },
        {
            "path": "/api/canvas/",
            "description": "getAll",
            "operations": [
                {
                    "method": "GET",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                },
                {
                    "method": "POST",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 201,
                            "message": "Created"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                }
            ]
        }
    ],
    "models": {
        "ResponseEntity": {
            "description": "",
            "id": "ResponseEntity",
            "properties": {
                "headers": {
                    "required": false,
                    "type": "HttpHeaders"
                },
                "body": {
                    "required": false,
                    "type": "object"
                },
                "statusCode": {
                    "enum": [
                        "100",
                        "101",
                        "102",
                        "103",
                        "200",
                        "201",
                        "202",
                        "203",
                        "204",
                        "205",
                        "206",
                        "207",
                        "208",
                        "226",
                        "300",
                        "301",
                        "302",
                        "302",
                        "303",
                        "304",
                        "305",
                        "307",
                        "308",
                        "400",
                        "401",
                        "402",
                        "403",
                        "404",
                        "405",
                        "406",
                        "407",
                        "408",
                        "409",
                        "410",
                        "411",
                        "412",
                        "413",
                        "413",
                        "414",
                        "414",
                        "415",
                        "416",
                        "417",
                        "418",
                        "419",
                        "420",
                        "421",
                        "422",
                        "423",
                        "424",
                        "426",
                        "428",
                        "429",
                        "431",
                        "500",
                        "501",
                        "502",
                        "503",
                        "504",
                        "505",
                        "506",
                        "507",
                        "508",
                        "509",
                        "510",
                        "511"
                    ],
                    "required": false,
                    "type": "string"
                }
            }
        },
        "Canvas": {
            "description": "Represents a canvas in the database.",
            "id": "Canvas",
            "properties": {}
        },
        "Void": {
            "description": "",
            "id": "Void",
            "properties": {}
        }
    }
}
```

My problem is that swagger does not return the api model properties from the canvas class as you can see in the swagger output
I hope you guys can help me with that.

Thanks in advance.

答: The Reason of the problem is: there are annotations with the same name in other java files. you can look for in @ApiModel("Name"), and see whether the annotation exists in other files.

Title: @ApiModelProperty Swagger-Mvc

Body:
Hello guys I have a problem with swagger-mvc (version 0.9.5).

I have the following restcontroller:

CanvasController.java (snippet)

/**
 * The Class CanvasController.
 */
@Api(description = "Operations for canvases", value="canvascontroller")
@RestController
@RequestMapping(value = "/api/canvas")
public class CanvasController {

  ...

  @ApiResponses(value = {
    @ApiResponse(code = 200, message = "No problem occurred.")
  })
  @ApiOperation(value = "Returns all canvases.", notes = "Returns all canvases.", response = Canvas.class, responseContainer = "List")
  @RequestMapping(value = {"/all", "", "/"}, method = {        RequestMethod.GET, RequestMethod.POST}, produces = MediaType.APPLICATION_JSON_VALUE)
  public @ResponseBody ResponseEntity < List < Canvas >> getAll() {
    return new ResponseEntity < List < Canvas >> (canvasService.findAll(),
      HttpStatus.OK);
  }

}

Canvas.java

package cloudincubator.canvas.db;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.codehaus.jackson.annotate.JsonProperty;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.wordnik.swagger.annotations.ApiModel;
import com.wordnik.swagger.annotations.ApiModelProperty;

/**
 * The Class Canvas.
 */
@Entity
@Table(name = "Canvas", uniqueConstraints = {@UniqueConstraint(columnNames = {"C_Id"})})
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@canvasId")
@ApiModel(value = "Canvas", description = "Represents a canvas in the database.")
public class Canvas
 {

    /** The {@link CanvasGroup} to which this Canvas belongs. */
    @ManyToOne(optional = true)
    @JoinColumn(name = "C_Canvas_Group_Id", referencedColumnName = "CG_Id", nullable = true)
    private CanvasGroup ccanvasgroup;

    /** The description of this Canvas. */
    @Column(name = "C_Description")
    @ApiModelProperty(value="Description")
    @JsonProperty("TEST")
    private String cdescription;

    /** The x position in the CanvasGroup grid. */
    @Column(name = "C_GridX")
    @ApiModelProperty(value="GridX")
    private Integer cgridx;

    /** The y position in the CanvasGroup grid. */
    @Column(name = "C_GridY")
    @ApiModelProperty(value="GridY")
    private Integer cgridy;

    /** The height of this Canvas. */
    @Column(name = "C_Height")
    private Integer cheight;

    /** The path of the icon which belongs to this Canvas. */
    @Column(name = "C_Icon")
    private String cicon;

    /** The identifier of this Canvas. */
    @Id
    @Column(name = "C_Id", table = "Canvas")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long cid;

    /** The name of this Canvas. */
    @Column(name = "C_Name")
    private String cname;

    /** The shortcut of this Canvas. */
    @Column(name = "C_Shortcut")
    private String cshortcut;

    /** The {@link Sticker Stickers} which belong to this Canvas. */
    @OneToMany(cascade = CascadeType.ALL, mappedBy="scanvas")
    @Column(nullable = true)
    private List<Sticker> cstickers;

    /** The width of this Canvas. */
    @Column(name = "C_Width")
    private Integer cwidth;

    /**
     * Instantiates a new Canvas.
     */
    public Canvas(){}

    /**
     * Instantiates a new Canvas with the given identifier .
     *
     * @param cId : The identifier of this Canvas.
     */
    public Canvas(Long cId)
    {
        this.cid = cId;
    }

    /**
     * Instantiates a new Canvas with the given name.
     *
     * @param cName : The name of this Canvas.
     */
    public Canvas(String cName) {
        this.cname  = cName;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object other) {
        if (this == other) return true;
        if ( !(other instanceof Canvas) ) return false;

        final Canvas canvas = (Canvas) other;

        if ( !canvas.getCId().equals( getCId() ) ) return false;

        return true;
    }

    /**
     * Gets the {@link CanvasGroup} to which this Canvas belongs.
     *
     * @return the {@link CanvasGroup}.
     */
//  @ApiModelProperty(position=1, required = true, hidden = false, dataType="cloudincubator.canvas.db.CanvasGroup")
    public CanvasGroup getCCanvasGroup() {
        return ccanvasgroup;
    }

    /**
     * Gets the description of this Canvas.
     *
     * @return the description of this Canvas.
     */
    public String getCDescription() {
        return cdescription;
    }

    /**
     * Gets the x position in the CanvasGroup grid of this Canvas.
     *
     * @return the x position in the CanvasGroup grid of this Canvas.
     */
    public Integer getCGridX() {
        return cgridx;
    }

    /**
     * Gets the y position in the CanvasGroup grid of this Canvas.
     *
     * @return the y position in the Canvasgroup grid of this Canvas.
     */
    public Integer getCGridY() {
        return cgridy;
    }

    /**
     * Gets the height of this Canvas.
     *
     * @return the height of this Canvas.
     */
    public Integer getCHeight() {
        return cheight;
    }

    /**
     * Gets the path of the icon which belongs to this Canvas.
     *
     * @return the icon path of this Canvas.
     */
    public String getCIcon() {
        return cicon;
    }

    /**
     * Gets the identifier of this Canvas.
     *
     * @return the identifier of this Canvas.
     */
    public Long getCId() {
        return cid;
    }

    /**
     * Gets the name of this Canvas.
     *
     * @return the name of this Canvas.
     */
    public String getCName() {
        return cname;
    }

    /**
     * Gets the shortcut of this Canvas.
     *
     * @return the shortcut of this Canvas.
     */
    public String getCShortcut() {
        return cshortcut;
    }

    /**
     * Gets the {@link Sticker Stickers} which belong to this Canvas.
     *
     * @return the {@link Sticker Stickers} which belong to this Canvas.
     */
    public List<Sticker> getCStickers()
    {
        return cstickers;
    }

    /**
     * Gets the width of this Canvas.
     *
     * @return the width of this Canvas.
     */
    public Integer getCWidth() {
        return cwidth;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return getCId().hashCode();
    }

    /**
     * Sets the {@link CanvasGroup} to which this Canvas belongs.
     *
     * @param cCanvasGroup : The {@link CanvasGroup} to set.
     */
    public void setCCanvasGroup(CanvasGroup cCanvasGroup) {
        ccanvasgroup = cCanvasGroup;
    }

    /**
     * Sets the description of this Canvas.
     *
     * @param cDescription : The description to set.
     */
    public void setCDescription(String cDescription) {
        cdescription = cDescription;
    }

    /**
     * Sets the x position in the CanvasGroup grid.
     *
     * @param cGridX : The x position to set.
     */
    public void setCGridX(Integer cGridX) {
        cgridx = cGridX;
    }

    /**
     * Sets the y position in the CanvasGroup grid.
     *
     * @param cGridY : The y position to set.
     */
    public void setCGridY(Integer cGridY) {
        cgridy = cGridY;
    }

    /**
     * Sets the height of this Canvas.
     *
     * @param cHeight : The height to set.
     */
    public void setCHeight(Integer cHeight) {
        cheight = cHeight;
    }

    /**
     * Sets the icon path of this Canvas.
     *
     * @param cIcon : The icon path to set.
     */
    public void setCIcon(String cIcon) {
        cicon = cIcon;
    }

    /**
     * Sets the identifier of this Canvas.
     *
     * @param cid : The identifier to set.
     */
    public void setCId(Long cid)
    {
        this.cid = cid;
    }

    /**
     * Sets the name of this Canvas.
     *
     * @param cName : The name to set
     */
    public void setCName(String cName) {
        cname = cName;
    }

    /**
     * Sets the shortcut of this Canvas.
     *
     * @param cShortcut : The shortcut to set
     */
    public void setCShortcut(String cShortcut) {
        cshortcut = cShortcut;
    }

    /**
     * Sets the {@link Sticker Stickers} which belong to this Canvas.
     *
     * @param cStickers : The list of {@link Sticker Stickers} to set.
     */
    public void setCStickers(List<Sticker> cStickers)
    {
        this.cstickers = cStickers;
    }

    /**
     * Sets the width of this Canvas.
     *
     * @param cWidth : The width to set.
     */
    public void setCWidth(Integer cWidth) {
        cwidth = cWidth;
    }
}

swagger output

{
    "apiVersion": "1.0",
    "swaggerVersion": "1.2",
    "basePath": "/",
    "resourcePath": "/api/canvas",
    "produces": [
        "application/json"
    ],
    "consumes": [
        "application/json"
    ],
    "apis": [
        {
            "path": "/api/canvas",
            "description": "getAll",
            "operations": [
                {
                    "method": "GET",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                },
                {
                    "method": "POST",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 201,
                            "message": "Created"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                }
            ]
        },
        {
            "path": "/api/canvas/",
            "description": "getAll",
            "operations": [
                {
                    "method": "GET",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                },
                {
                    "method": "POST",
                    "summary": "Returns all canvases.",
                    "notes": "Returns all canvases.",
                    "nickname": "getAll",
                    "produces": [
                        "application/json"
                    ],
                    "consumes": [
                        "application/json"
                    ],
                    "parameters": [],
                    "responseMessages": [
                        {
                            "code": 200,
                            "message": "No problem occurred.",
                            "responseModel": "List"
                        },
                        {
                            "code": 201,
                            "message": "Created"
                        },
                        {
                            "code": 401,
                            "message": "Unauthorized"
                        },
                        {
                            "code": 403,
                            "message": "Forbidden"
                        },
                        {
                            "code": 404,
                            "message": "Not Found"
                        }
                    ],
                    "deprecated": "false",
                    "type": "Canvas"
                }
            ]
        }
    ],
    "models": {
        "ResponseEntity": {
            "description": "",
            "id": "ResponseEntity",
            "properties": {
                "headers": {
                    "required": false,
                    "type": "HttpHeaders"
                },
                "body": {
                    "required": false,
                    "type": "object"
                },
                "statusCode": {
                    "enum": [
                        "100",
                        "101",
                        "102",
                        "103",
                        "200",
                        "201",
                        "202",
                        "203",
                        "204",
                        "205",
                        "206",
                        "207",
                        "208",
                        "226",
                        "300",
                        "301",
                        "302",
                        "302",
                        "303",
                        "304",
                        "305",
                        "307",
                        "308",
                        "400",
                        "401",
                        "402",
                        "403",
                        "404",
                        "405",
                        "406",
                        "407",
                        "408",
                        "409",
                        "410",
                        "411",
                        "412",
                        "413",
                        "413",
                        "414",
                        "414",
                        "415",
                        "416",
                        "417",
                        "418",
                        "419",
                        "420",
                        "421",
                        "422",
                        "423",
                        "424",
                        "426",
                        "428",
                        "429",
                        "431",
                        "500",
                        "501",
                        "502",
                        "503",
                        "504",
                        "505",
                        "506",
                        "507",
                        "508",
                        "509",
                        "510",
                        "511"
                    ],
                    "required": false,
                    "type": "string"
                }
            }
        },
        "Canvas": {
            "description": "Represents a canvas in the database.",
            "id": "Canvas",
            "properties": {}
        },
        "Void": {
            "description": "",
            "id": "Void",
            "properties": {}
        }
    }
}

My problem is that swagger does not return the api model properties from the canvas class as you can see in the swagger output
I hope you guys can help me with that.

Thanks in advance.


问:
Servlet error in doGet when POST request
I'm building a website with a chat using a Tomcat server. For that chat, I've got a form (with text input) that calls a JS function, that performs a jQuery POST request...

```<code><!DOCTYPE html>

<html>
<body>
    <form method="post" action="javascript:submitNewMessage()" accept-charset="UTF-8" id="msgForm">
        <input type="text" name="msg" id="msgField"/>
        <input type="submit" name="submit" value="Send"/>
    </form>

    <script src="jquery.js"></script>
    <script>
"use strict";

function submitNewMessage() {
var msg = document.getElementById("msgField").value;
$.post("chatController", {message:msg, author:"${user.username}", gameId:"${game}", chat:"${chat.type}"});
}
</script>
</body>
</html>
</code>```

... to this controller, chatController.java :

```<code>@WebServlet(urlPatterns = {"/chatController"})
public class ChatController extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    request.setAttribute("user", new User(request.getParameter("user")));
    request.setAttribute("game", Integer.parseInt(request.getParameter("gameId")));
    request.setAttribute("chat", new ChatRoom(ChatRoomType.fromString(request.getParameter("chat"))));
    request.setAttribute("lastMessage", 0);

    request.getRequestDispatcher("/WEB-INF/chat.jsp").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
        ChatDAO dao = new ChatDAO(this.ds);
        if (dao.submitMessage(...) // not implemented yet, returns false) {
                throw new ServletException();
            }
    } catch (Exception e) {
        response.sendError(400);
    }
}
}
</code>```

The GET of chatController is used when the user joins the chat, and then only POST is used to submit messages. When I join the chat page, no error. But when I submit a message, the debugger (of Firefox) tells me XML parsing error : no element found at line 1. The HTML returned by chatController contains a Java error in the doGet method (NumberFormatException: null, at the 2nd line of doGet, where I do Integer.parseInt).

Why is the doGet method called here ? I do a POST request on chatController... And when I print something in doGet, it doesn't appear in the log : so why is that line throwing an error ? What's wrong with that code ?

Thanks for any help.

答: Your jsp and servlet works fine on my local. Probably, a JavaScript error occurred. Did you deploy jquery.js in the appropriate location?</p>

Body:
I'm building a website with a chat using a Tomcat server. For that chat, I've got a form (with text input) that calls a JS function, that performs a jQuery POST request...

<!DOCTYPE html>

    <form method="post" action="javascript:submitNewMessage()" accept-charset="UTF-8" id="msgForm">
        <input type="text" name="msg" id="msgField"/>
        <input type="submit" name="submit" value="Send"/>
    </form>

... to this controller, chatController.java :

@WebServlet(urlPatterns = {"/chatController"})
public class ChatController extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    request.setAttribute("user", new User(request.getParameter("user")));
    request.setAttribute("game", Integer.parseInt(request.getParameter("gameId")));
    request.setAttribute("chat", new ChatRoom(ChatRoomType.fromString(request.getParameter("chat"))));
    request.setAttribute("lastMessage", 0);

    request.getRequestDispatcher("/WEB-INF/chat.jsp").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
        ChatDAO dao = new ChatDAO(this.ds);
        if (dao.submitMessage(...) // not implemented yet, returns false) {
                throw new ServletException();
            }
    } catch (Exception e) {
        response.sendError(400);
    }
}
}

The GET of chatController is used when the user joins the chat, and then only POST is used to submit messages. When I join the chat page, no error. But when I submit a message, the debugger (of Firefox) tells me XML parsing error : no element found at line 1. The HTML returned by chatController contains a Java error in the doGet method (NumberFormatException: null, at the 2nd line of doGet, where I do Integer.parseInt).

Why is the doGet method called here ? I do a POST request on chatController... And when I print something in doGet, it doesn't appear in the log : so why is that line throwing an error ? What's wrong with that code ?

Thanks for any help.