问:
Abstract Factory Design Pattern implementation in C++ using Qt Creator
I am trying to make all the creational design patterns and I'm having some trouble with the abstract factory method. I normally program in Python, however, I had heard C++ was good for really having to understand design patterns explicitly, which is proving to be right, err.

I'm basically following this guide on Tutorials Point.

My question is how would I change my current code to correctly implement the abstract factory method in C++ with a factory producer as I believe its something to do with my Factory Producer extra layer of abstraction that is causing my issues. I have included all my code.

I tried to make a simple diagram to explain better but it's not the most formal UML but is essentially what I would like to make. My main.cpp file should illustrate better the functionality I'm trying to understand how to make.

P.s. I'm just trying to improve to apply for jobs so please let me know if you have any feedback on writing better SO questions, coding style, variable naming or even C++ conventions.

Main

main.cpp - Main implementation file

Tests creating an abstract factory, abstract sword and abstract warrior.

```<code>#include "factoryproducer.h"

using namespace std;

int main(int argc, char *argv[]) {
    AbstractFactory* warriorFactory = FactoryProducer::createFactory("warriorfactory");

    Warrior* tinyWarrior = warriorFactory->createWarrior("tinywarrior");
    Warrior* normalWarrior = warriorFactory->createWarrior("normalwarrior");
    Warrior* largeWarrior = warriorFactory->createWarrior("largewarrior");
    Warrior* giantWarrior = warriorFactory->createWarrior("giantwarrior");

    cout<<tinyWarrior->getName().toStdString()<<endl;
    cout<<normalWarrior->getName().toStdString()<<endl;
    cout<<largeWarrior->getName().toStdString()<<endl;
    cout<<giantWarrior->getName().toStdString()<<endl;

    AbstractFactory* SwordFactory = FactoryProducer::createFactory("swordfactory");

    Sword* tinySword = swordFactory->createSword("tinysword");
    Sword* normalSword = swordFactory->createSword("normalsword");
    Sword* largeSword = swordFactory->createSword("largesword");
    Sword* giantSword = swordFactory->createSword("giantsword");

    cout<<tinySword->getName().toStdString()<<endl;
    cout<<normalSword->getName().toStdString()<<endl;
    cout<<largeSword->getName().toStdString()<<endl;
    cout<<giantSword->getName().toStdString()<<endl;

    return a.exec();
}
</code>```

Abstract Factory Class

abstractfactory.h - Abstract Factory header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```

abstractfactory.cpp Abstract Factory implementation file

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```

Factory Producer Class

factoryproducer.h - Factory Producer header file

```<code>#ifndef FACTORYPRODUCER_H
#define FACTORYPRODUCER_H

#include "abstractfactory.h"
#include "warriorfactory.h"
#include "swordfactory.h"
#include <QString>

class FactoryProducer {
public:
    // Public Methods
    static AbstractFactory* createFactory(QString factoryType);
};

#endif // FACTORYPRODUCER_H
</code>```

factoryproducer.cpp - Factory Producer implementation file

```<code>#include "factoryproducer.h"

AbstractFactory* AbstractFactory::createFactory(QString factoryType) {
    if (factoryType == nullptr) {
        return nullptr;
    }

    if (QString::compare(factoryType, "WARRIORFACTORY", Qt::CaseInsensitive) == 0) {
        return new WarriorFactory();
    }

    if (QString::compare(factoryType, "SWORDFACTORY", Qt::CaseInsensitive) == 0) {
        return new SwordFactory();
    }

    return nullptr;
}
</code>```

Abstract Warrior Class

warrior.h - Abstract Warrior header file

```<code>#ifndef WARRIOR_H
#define WARRIOR_H

#include "tinywarrior.h"
#include "normalwarrior.h"
#include "largewarrior.h"
#include "giantwarrior.h"
#include <QString>

class Warrior {
public:
    // Public Methods
    ~Warrior();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // WARRIOR_H
</code>```

warrior.cpp - Abstract Warrior implementation file

```<code>#include "warrior.h"

Warrior::~Warrior(){}
</code>```

Abstract Sword Class

sword.h - Abstract Sword header file

```<code>#ifndef SWORD_H
#define SWORD_H

#include "tinysword.h"
#include "normalsword.h"
#include "largesword.h"
#include "giantsword.h"
#include <QString>

class Sword {
public:
    // Public Methods
    ~Sword();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // SWORD_H
</code>```

sword.cpp - Abstract Sword implementation file

```<code>#include "sword.h"

Sword::~Sword(){}
</code>```

Concrete TinySword Class

tinysword.h - Concrete Tiny Sword header file

```<code>#ifndef TINYSWORD_H
#define TINYSWORD_H

#include "sword.h"

class TinySword : public Sword {
public:
    // Public Methods
    TinySword();
    ~TinySword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // TINYSWORD_H
</code>```

tinysword.cpp - Concrete Tiny Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```0

Concrete Normal Sword

normalsword.h - Concrete Normal Sword header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```1

normalsword.cpp - Concrete Normal Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```2

Concrete Large Sword Class

largesword.h - Concrete Large Sword header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```3

largesword.cpp - Concrete Large Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```4

Concrete Giant Sword Class

giantsword.h - Concrete Giant Sword header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```5

giantsword.cpp - Concrete Giant Sword implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```6

Concrete Tiny Warrior Class

tinywarrior.h - Concrete Tiny Warrior header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```7

tinywarrior.cpp - Concrete Tiny Warrior implementation file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```8

Concrete Normal Warrior Class

normalwarrior.h - Concrete Normal Warrior header file

```<code>#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H
</code>```9

normalwarrior.cpp Concrete Normal Warrior implementation

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```0

Concrete Large Warrior Class

largewarrior.h Concrete Large Warrior header file

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```1

largewarrior.cpp Concrete Large Warrior implementation file

```<code>#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}
</code>```2

Concrete Giant Warrior Class

giantwarrior.h - Concrete Giant Warrior header file

```<code>#ifndef GIANTWARRIOR_H
#define GIANTWARRIOR_H

#include "warrior.h"

class GiantWarrior : public Warrior {
public:
    // Methods
    GiantWarrior();
    ~GiantWarrior();
    QString getName();
    QString getPicture();
    void setXPosition(int x);
    int getXPosition();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // GIANTWARRIOR_H
</code>```

giantwarrior.cpp - Concrete Giant Warrior implementation file

```<code>#include "giantwarrior.h"

GiantWarrior::GiantWarrior(){
    m_name = "Giant Warrior";
    m_picture = ":/images/giant-warrior.png";
}

GiantWarrior::~GiantWarrior(){}

QString GiantWarrior::getName() {
    return m_name;
}

QString GiantWarrior::getPicture() {
    return m_picture;
}
</code>```

答:
The given example from TutorialsPoint is misleading.
For example what does your WarriorFactory return if createSword is called? Returning nullptr is not an option because of this:

```<code>void doSomethingWithFactory(AbstractFactory* f)
{
    Warrior* w = f->createWarrior();
    Sword* s = f->createSword();
}
</code>```

You actually need to know if you have been given a warrior or a sword factory and thus you are not abstracting anything away.

I coded an example which uses an abstract EnemyFactory which creates Monsters and Warriors. Depending on the concrete factory these enemies are either strong or weak.
EnemyFactory
This factory always creates enemies but their attributes differ depending on the concrete factory.

Body:
I am trying to make all the creational design patterns and I'm having some trouble with the abstract factory method. I normally program in Python, however, I had heard C++ was good for really having to understand design patterns explicitly, which is proving to be right, err.

I'm basically following this guide on Tutorials Point.

My question is how would I change my current code to correctly implement the abstract factory method in C++ with a factory producer as I believe its something to do with my Factory Producer extra layer of abstraction that is causing my issues. I have included all my code.

I tried to make a simple diagram to explain better but it's not the most formal UML but is essentially what I would like to make. My main.cpp file should illustrate better the functionality I'm trying to understand how to make.

P.s. I'm just trying to improve to apply for jobs so please let me know if you have any feedback on writing better SO questions, coding style, variable naming or even C++ conventions.

Main

main.cpp - Main implementation file

Tests creating an abstract factory, abstract sword and abstract warrior.

#include "factoryproducer.h"

using namespace std;

int main(int argc, char *argv[]) {
    AbstractFactory* warriorFactory = FactoryProducer::createFactory("warriorfactory");

    Warrior* tinyWarrior = warriorFactory->createWarrior("tinywarrior");
    Warrior* normalWarrior = warriorFactory->createWarrior("normalwarrior");
    Warrior* largeWarrior = warriorFactory->createWarrior("largewarrior");
    Warrior* giantWarrior = warriorFactory->createWarrior("giantwarrior");

    cout<<tinyWarrior->getName().toStdString()<<endl;
    cout<<normalWarrior->getName().toStdString()<<endl;
    cout<<largeWarrior->getName().toStdString()<<endl;
    cout<<giantWarrior->getName().toStdString()<<endl;

    AbstractFactory* SwordFactory = FactoryProducer::createFactory("swordfactory");

    Sword* tinySword = swordFactory->createSword("tinysword");
    Sword* normalSword = swordFactory->createSword("normalsword");
    Sword* largeSword = swordFactory->createSword("largesword");
    Sword* giantSword = swordFactory->createSword("giantsword");

    cout<<tinySword->getName().toStdString()<<endl;
    cout<<normalSword->getName().toStdString()<<endl;
    cout<<largeSword->getName().toStdString()<<endl;
    cout<<giantSword->getName().toStdString()<<endl;

    return a.exec();
}

Abstract Factory Class

abstractfactory.h - Abstract Factory header file

#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H

#include "warrior.h"
#include "sword.h"
#include <QString>

class AbstractFactory {
public:
    // Public Methods
    ~AbstractFactory();
    virtual Warrior* createWarrior(QString warriorType) = 0;
    virtual Sword* createSword(QString swordType) = 0;
};

#endif // ABSTRACTFACTORY_H

abstractfactory.cpp Abstract Factory implementation file

#include "abstractfactory.h"

AbstractFactory::~AbstractFactory(){}

Factory Producer Class

factoryproducer.h - Factory Producer header file

#ifndef FACTORYPRODUCER_H
#define FACTORYPRODUCER_H

#include "abstractfactory.h"
#include "warriorfactory.h"
#include "swordfactory.h"
#include <QString>

class FactoryProducer {
public:
    // Public Methods
    static AbstractFactory* createFactory(QString factoryType);
};

#endif // FACTORYPRODUCER_H

factoryproducer.cpp - Factory Producer implementation file

#include "factoryproducer.h"

AbstractFactory* AbstractFactory::createFactory(QString factoryType) {
    if (factoryType == nullptr) {
        return nullptr;
    }

    if (QString::compare(factoryType, "WARRIORFACTORY", Qt::CaseInsensitive) == 0) {
        return new WarriorFactory();
    }

    if (QString::compare(factoryType, "SWORDFACTORY", Qt::CaseInsensitive) == 0) {
        return new SwordFactory();
    }

    return nullptr;
}

Abstract Warrior Class

warrior.h - Abstract Warrior header file

#ifndef WARRIOR_H
#define WARRIOR_H

#include "tinywarrior.h"
#include "normalwarrior.h"
#include "largewarrior.h"
#include "giantwarrior.h"
#include <QString>

class Warrior {
public:
    // Public Methods
    ~Warrior();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // WARRIOR_H

warrior.cpp - Abstract Warrior implementation file

#include "warrior.h"

Warrior::~Warrior(){}

Abstract Sword Class

sword.h - Abstract Sword header file

#ifndef SWORD_H
#define SWORD_H

#include "tinysword.h"
#include "normalsword.h"
#include "largesword.h"
#include "giantsword.h"
#include <QString>

class Sword {
public:
    // Public Methods
    ~Sword();
    virtual QString getName() = 0;
    virtual QString getPicture() = 0;
};

#endif // SWORD_H

sword.cpp - Abstract Sword implementation file

#include "sword.h"

Sword::~Sword(){}

Concrete TinySword Class

tinysword.h - Concrete Tiny Sword header file

#ifndef TINYSWORD_H
#define TINYSWORD_H

#include "sword.h"

class TinySword : public Sword {
public:
    // Public Methods
    TinySword();
    ~TinySword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // TINYSWORD_H

tinysword.cpp - Concrete Tiny Sword implementation file

#include "tinysword.h"

TinySword::TinySword(){
    m_name = "Tiny Sword";
    m_picture = "";
}

TinySword::~TinySword(){}

QString TinySword::getName() {
    return m_name;
}

QString TinySword::getPicture() {
    return m_picture;
}

Concrete Normal Sword

normalsword.h - Concrete Normal Sword header file

#ifndef NORMALSWORD_H
#define NORMALSWORD_H

#include "sword.h"

class NormalSword : public Sword {
public:
    // Public Methods
    NormalSword();
    ~NormalSword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // NORMALSWORD_H

normalsword.cpp - Concrete Normal Sword implementation file

#include "normalsword.h"

NormalSword::NormalSword() {
    m_name = "Normal Sword";
    m_picture = "";
}

NormalSword::~NormalSword(){}

QString NormalSword::getName() {
    return m_name;
}

QString NormalSword::getPicture() {
    return m_picture;
}

Concrete Large Sword Class

largesword.h - Concrete Large Sword header file

#ifndef LARGESWORD_H
#define LARGESWORD_H

#include "sword.h"

class LargeSword : public Sword {
public:
    // Public Methods
    LargeSword();
    ~LargeSword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // LARGESWORD_H

largesword.cpp - Concrete Large Sword implementation file

#include "largesword.h"

LargeSword::LargeSword() {
    m_name = "Large Sword";
    m_picture = "";
}

LargeSword::~LargeSword(){}

QString LargeSword::getName() {
    return m_name;
}

QString LargeSword::getPicture() {
    return m_picture;
}

Concrete Giant Sword Class

giantsword.h - Concrete Giant Sword header file

#ifndef GIANTSWORD_H
#define GIANTSWORD_H

#include "sword.h"

class GiantSword : public Sword {
public:
    // Public Methods
    GiantSword();
    ~GiantSword();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // GIANTSWORD_H

giantsword.cpp - Concrete Giant Sword implementation file

#include "giantsword.h"

GiantSword::GiantSword() {
    m_name = "Giant Sword";
    m_picture = "";
}

GiantSword::~GiantSword(){}

QString GiantSword::getName() {
    return m_name;
}

QString GiantSword::getPicture() {
    return m_picture;
}

Concrete Tiny Warrior Class

tinywarrior.h - Concrete Tiny Warrior header file

#ifndef TINYWARRIOR_H
#define TINYWARRIOR_H

#include "warrior.h"

class TinyWarrior : public Warrior {
public:
    // Methods
    TinyWarrior();
    ~TinyWarrior();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // TINYWARRIOR_H

tinywarrior.cpp - Concrete Tiny Warrior implementation file

#include "tinywarrior.h"

TinyWarrior::TinyWarrior(){
    m_name = "Tiny Warrior";
    m_picture = ":/images/tiny-warrior.png";
}

TinyWarrior::~TinyWarrior(){}

QString TinyWarrior::getName() {
    return m_name;
}

QString TinyWarrior::getPicture() {
    return m_picture;
}

Concrete Normal Warrior Class

normalwarrior.h - Concrete Normal Warrior header file

#ifndef NORMALWARRIOR_H
#define NORMALWARRIOR_H

#include "warrior.h"

class NormalWarrior : public Warrior {
public:
    // Public Methods
    NormalWarrior();
    ~NormalWarrior();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // NORMALWARRIOR_H

normalwarrior.cpp Concrete Normal Warrior implementation

#include "normalwarrior.h"

NormalWarrior::NormalWarrior() {
    m_name = "Normal Warrior";
    m_picture = ":/images/normal-warrior.png";
}

NormalWarrior::~NormalWarrior(){}

QString NormalWarrior::getName() {
    return m_name;
}

QString NormalWarrior::getPicture() {
    return m_picture;
}

Concrete Large Warrior Class

largewarrior.h Concrete Large Warrior header file

#ifndef LARGEWARRIOR_H
#define LARGEWARRIOR_H

#include "warrior.h"

class LargeWarrior : public Warrior {
public:
    // Methods
    LargeWarrior();
    ~LargeWarrior();
    QString getName();
    QString getPicture();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // LARGEWARRIOR_H

largewarrior.cpp Concrete Large Warrior implementation file

#include "largewarrior.h"

LargeWarrior::LargeWarrior(){
    m_name = "Large Warrior";
    m_picture = ":/images/large-warrior.png";
}

LargeWarrior::~LargeWarrior(){}

QString LargeWarrior::getName() {
    return m_name;
}

QString LargeWarrior::getPicture() {
    return m_picture;
}

Concrete Giant Warrior Class

giantwarrior.h - Concrete Giant Warrior header file

#ifndef GIANTWARRIOR_H
#define GIANTWARRIOR_H

#include "warrior.h"

class GiantWarrior : public Warrior {
public:
    // Methods
    GiantWarrior();
    ~GiantWarrior();
    QString getName();
    QString getPicture();
    void setXPosition(int x);
    int getXPosition();
private:
    // Private Member Variables
    QString m_name;
    QString m_picture;
};

#endif // GIANTWARRIOR_H

giantwarrior.cpp - Concrete Giant Warrior implementation file

#include "giantwarrior.h"

GiantWarrior::GiantWarrior(){
    m_name = "Giant Warrior";
    m_picture = ":/images/giant-warrior.png";
}

GiantWarrior::~GiantWarrior(){}

QString GiantWarrior::getName() {
    return m_name;
}

QString GiantWarrior::getPicture() {
    return m_picture;
}

Body:
The given example from TutorialsPoint is misleading.
For example what does your WarriorFactory return if createSword is called? Returning nullptr is not an option because of this:

void doSomethingWithFactory(AbstractFactory* f)
{
    Warrior* w = f->createWarrior();
    Sword* s = f->createSword();
}

You actually need to know if you have been given a warrior or a sword factory and thus you are not abstracting anything away.

I coded an example which uses an abstract EnemyFactory which creates Monsters and Warriors. Depending on the concrete factory these enemies are either strong or weak.
EnemyFactory
This factory always creates enemies but their attributes differ depending on the concrete factory.


来源: stackexchange

问:
MYSQL: can foreign key contain a collection?
I want do a foreign key in a one table that will points on a collection of other values.

For example I want do a parent table, and a child table. while each parent should contain all his children, and each children should contain his parent.

So my question is can I do this in MySQL? How can I do this if yes, and what can I use otherwise;

答:
A Foreign Key defines a column (or a collection of columns) that enforces a relationship between two Tables. It is the responsibility of the database server to enforce this relationship to ensure accurate data. The model definition of a Foreign Key consists of a parent (primary) Table containing a unique set of data that is then referred to in a child (foreign) Table.

For complete explanation have a look at this :http://www.sparxsystems.com/enterprise_architect_user_guide/12.1/database_engineering/foreignkeys.html

ContentLicense: CC BY-SA 3.0


问:
How do I center text in Swift?
In a Swift playground, how do I center a UILabel inside of a UIViewController?

When I use title.center = CGPoint(x: vc.view.frame.width / 2, y: 20) the text goes off of the screen.

This is the problem

If it helps, here's my code.

```<code>import UIKit
import PlaygroundSupport

// Set up ViewController and other things
var vc = UIViewController()
vc.view.frame.size.height = 75
vc.view.backgroundColor = .white

let title = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
title.textAlignment = .center
title.center = vc.view.center
title.text = "Which code is correct?"
vc.view.addSubview(title)

PlaygroundPage.current.liveView = vc
</code>```

答:
If we're talking about top view in hierarchy (i.e. view controller's view), this line should be enough:

```<code>title.center = vc.view.center
</code>```

Otherwise, if you ever want to center your view/label/button/whatever inside any view controller view's subview — the next solution is universal:

```<code>title.center = CGPoint(x: parentView.bounds.size.width / 2, y: parentView.bounds.size.height / 2)
</code>```

If you want to center only horizontally or vertically — modify y or x parameter of CGPoint(x:y:) function correspondingly:

```<code>// Center horizontally but with vertical offset of 20 points
title.center = CGPoint(x: parentView.bounds.size.width / 2, y: 20 - title.bounds.size.height / 2)
</code>```

Title: How do I center text in Swift?

Body:
In a Swift playground, how do I center a UILabel inside of a UIViewController?

When I use title.center = CGPoint(x: vc.view.frame.width / 2, y: 20) the text goes off of the screen.

This is the problem

If it helps, here's my code.

import UIKit
import PlaygroundSupport

// Set up ViewController and other things
var vc = UIViewController()
vc.view.frame.size.height = 75
vc.view.backgroundColor = .white

let title = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
title.textAlignment = .center
title.center = vc.view.center
title.text = "Which code is correct?"
vc.view.addSubview(title)

PlaygroundPage.current.liveView = vc

Body:
If we're talking about top view in hierarchy (i.e. view controller's view), this line should be enough:

title.center = vc.view.center

Otherwise, if you ever want to center your view/label/button/whatever inside any view controller view's subview — the next solution is universal:

title.center = CGPoint(x: parentView.bounds.size.width / 2, y: parentView.bounds.size.height / 2)

If you want to center only horizontally or vertically — modify y or x parameter of CGPoint(x:y:) function correspondingly:

// Center horizontally but with vertical offset of 20 points
title.center = CGPoint(x: parentView.bounds.size.width / 2, y: 20 - title.bounds.size.height / 2)


问:
I am getting an internal server error on my local Python server when authenticating to Yelp API
I am trying to authenticate to the Yelp API and this is what I'm getting:

{ "error": { "description": "client_id or client_secret parameters not found. Make sure to provide client_id and client_secret in the body with the application/x-www-form-urlencoded content-type", "code": "VALIDATION_ERROR" } }

This is the method I have defined in Python and I am have installed Python Flask. I have never worked with an API before this:

```<code>@app.route("/run_post")
def run_post():
   url = "https://api.yelp.com/oauth2/token"
   data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'Content-type': 'application/x-www-form-urlencoded'}

   body = requests.post(url, data=json.dumps(data))

   return json.dumps(body.json(), indent=4)
</code>```

答:
I followed @destiner 's and added the content type to the header and it worked. Here's the resulting code:</p>

```<code>@app.route("/run_post")
def run_post():
  url = "https://api.yelp.com/oauth2/token"
  data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET}
  headers = {'Content-type': 'application/x-www-form-urlencoded'}

body = requests.post(url, data=data, headers=headers)

return json.dumps(body.json(), indent=4)
</code>```

Body:
I am trying to authenticate to the Yelp API and this is what I'm getting:

{ "error": { "description": "client_id or client_secret parameters not found. Make sure to provide client_id and client_secret in the body with the application/x-www-form-urlencoded content-type", "code": "VALIDATION_ERROR" } }

This is the method I have defined in Python and I am have installed Python Flask. I have never worked with an API before this:

@app.route("/run_post")
def run_post():
   url = "https://api.yelp.com/oauth2/token"
   data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'Content-type': 'application/x-www-form-urlencoded'}

   body = requests.post(url, data=json.dumps(data))

   return json.dumps(body.json(), indent=4)

Body:
I followed @destiner 's and added the content type to the header and it worked. Here's the resulting code:

@app.route("/run_post")
def run_post():
  url = "https://api.yelp.com/oauth2/token"
  data = {'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET}
  headers = {'Content-type': 'application/x-www-form-urlencoded'}

body = requests.post(url, data=data, headers=headers)

return json.dumps(body.json(), indent=4)


问:
Scraping a webpage that has JavaScript with BeautifulSoup
guys! I am applying to you once again. I am ok with scraping simple websites with tags but recently I've encountered a quite complex website which has JavaScript. As a result I would like to obtain all the estimates at the bottom of the page in a format of table (csv). Like 'User', 'Revenue estimate', 'EPS estimate'.

I hoped to figure it by myself but kinda failed.

Here is my code:

```<code>from urllib import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://www.estimize.com/jpm/fq3-2016?sort=rank&direction=asc&estimates_per_page=142&show_confirm=false")
soup = BeautifulSoup(html.read(), "html.parser")
print(soup.findAll('script')[11].string.encode('utf8'))
</code>```

The output has a strange format and I don't know how to extract the data in an adequate form.
 I'll appreciate any help!

答:
This is how I've resolved the problem, using some tips above:</p>

```<code>from bs4 import BeautifulSoup
from urllib import urlopen
import json
import csv

f = csv.writer(open("estimize.csv", "a"))
f.writerow(["User Name", "Revenue Estimate", "EPS Estimate"])

html = "https://www.estimize.com/jpm/fq3-2016?sort=rank&direction=asc&estimates_per_page=142&show_confirm=false"
html = urlopen(html)
soup = BeautifulSoup(html.read(), "html.parser").encode('utf8')
data_string = soup.split("\"allEstimateRows\":")[1]
data_string = data_string.split(",\"tableSortDirection")[0]
data = json.loads(data_string)

for item in data:
    f.writerow([item["userName"], item["revenue"], item["eps"]])
</code>```

Body:
guys! I am applying to you once again. I am ok with scraping simple websites with tags but recently I've encountered a quite complex website which has JavaScript. As a result I would like to obtain all the estimates at the bottom of the page in a format of table (csv). Like 'User', 'Revenue estimate', 'EPS estimate'.

I hoped to figure it by myself but kinda failed.

Here is my code:

from urllib import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://www.estimize.com/jpm/fq3-2016?sort=rank&direction=asc&estimates_per_page=142&show_confirm=false")
soup = BeautifulSoup(html.read(), "html.parser")
print(soup.findAll('script')[11].string.encode('utf8'))

The output has a strange format and I don't know how to extract the data in an adequate form.
 I'll appreciate any help!

Body:
This is how I've resolved the problem, using some tips above:

from bs4 import BeautifulSoup
from urllib import urlopen
import json
import csv

f = csv.writer(open("estimize.csv", "a"))
f.writerow(["User Name", "Revenue Estimate", "EPS Estimate"])

html = "https://www.estimize.com/jpm/fq3-2016?sort=rank&direction=asc&estimates_per_page=142&show_confirm=false"
html = urlopen(html)
soup = BeautifulSoup(html.read(), "html.parser").encode('utf8')
data_string = soup.split("\"allEstimateRows\":")[1]
data_string = data_string.split(",\"tableSortDirection")[0]
data = json.loads(data_string)

for item in data:
    f.writerow([item["userName"], item["revenue"], item["eps"]])


问:
how to add int and int[ ] in java using var args method?
This is my first question so I might sound stupid, so please don't mind !
I was working on a concept which is var args and I come up with a program as follows :

```<code>package Method;
public class VariableArguments {
public static void main(String[] args) {
    m1();
    m1(10);
    m1(10,20);
    m1(10,20,30,40);
    m1(10,20,30,40,50);
}
public static void m1(int... x)
{
    int total = 0;
    for(int i:x)
    {
        total = total + x;
    }
    System.out.println("Sum is: "+total);
 }
}
</code>```

While I was running this program, I was getting an error which is-

Error:(15, 27) java: bad operand types for binary operator '+'

first type:  int   second type: int[]

In line 15 it says "Operator '+' cannot be applied on int, int[]"

So can anybody give me the solution for this problem ?
Thanks !!

答:
You need to add total to i (each element), not to the var args. array (i.e., x), so change the code as:

```<code>total = total + i;
</code>```

Body:
This is my first question so I might sound stupid, so please don't mind !
I was working on a concept which is var args and I come up with a program as follows :

package Method;
public class VariableArguments {
public static void main(String[] args) {
    m1();
    m1(10);
    m1(10,20);
    m1(10,20,30,40);
    m1(10,20,30,40,50);
}
public static void m1(int... x)
{
    int total = 0;
    for(int i:x)
    {
        total = total + x;
    }
    System.out.println("Sum is: "+total);
 }
}

While I was running this program, I was getting an error which is-

Error:(15, 27) java: bad operand types for binary operator '+'

first type:  int   second type: int[]

In line 15 it says "Operator '+' cannot be applied on int, int[]"

So can anybody give me the solution for this problem ?
Thanks !!

Body:
You need to add total to i (each element), not to the var args. array (i.e., x), so change the code as:

total = total + i;


问:
Can't return my value correctly when recursing a Binary Search Tree
I've tested to see if my trees are being inserted properly and am using pseudoclassical instantiation to make this work. My issue is that the debugger will tell me that truth is being set to true, then when I return the truth value from the end of the function I get false. I have tried everything I can think of but I can't figure out why this is happening. Here's my code that searches the binary search tree.

  var valuetest;
  var truth = false;
  if (this.value === value) {
    var truth = true;
    return truth;
  } else if (value > this.value) {
    valuetest = this.right.value;
    if (valuetest === value) {
      truth = true;
      return truth;
    } else {
      this.right.contains(value);
    }
  } else {
    valuetest = this.left.value;
    if (valuetest === value) {
      truth = true;
      return truth;
    } else {
      this.left.contains(value);
    }
  }
  return truth;
  //returns false even if truth is set to true for some reason.```

答:
You forgot to return the recursive call. So you see thruth getting true, but then one level back out of the recursion, the truth variable there is a different variable, and it does not get set at all.

Also, you have implemented arm's length recursion by repeating equality checks, which really is not necessary here. You can condense your code to :

```<code>return value === this.value  ||
       value > this.value && this.right && this.right.contains(value) ||
       value < this.value && this.left && this.left.contains(value);
</code>```

If the value is not found, the recursion should stop. The above will work if you have built your tree in such a way that value is null or undefined when it represents a leaf.

Or, you might omit left and/or right properties when there are no more children in that direction. Also if the tree is built like that, the code above will work.

Or still a bit smarter:

```<code>const branch = this[value > this.value ? 'right' : 'left'];
return value === this.value  || branch && branch.contains(value);
</code>```

Body:
You forgot to return the recursive call. So you see thruth getting true, but then one level back out of the recursion, the truth variable there is a different variable, and it does not get set at all.

Also, you have implemented arm's length recursion by repeating equality checks, which really is not necessary here. You can condense your code to :

return value === this.value  ||
       value > this.value && this.right && this.right.contains(value) ||
       value < this.value && this.left && this.left.contains(value);

If the value is not found, the recursion should stop. The above will work if you have built your tree in such a way that value is null or undefined when it represents a leaf.

Or, you might omit left and/or right properties when there are no more children in that direction. Also if the tree is built like that, the code above will work.

Or still a bit smarter:

const branch = this[value > this.value ? 'right' : 'left'];
return value === this.value  || branch && branch.contains(value);


问:
Getting a `$digest already in progress` error when testing a `catch()` error handler
This is my test:

```<code>it('add.user() should POST to /users/, failure', function() {
    mockBackend.expectPOST("/users/", {username:'u', password: 'p', email: 'e', location: 'loc'}).respond(400, {msg: "bad request"});

    BaseService.add.user({username:'u', password: 'p', email: 'e', location: 'loc'});

    mockBackend.flush();
});

afterEach(function() {
    mockBackend.verifyNoOutstandingExpectation();
    mockBackend.verifyNoOutstandingRequest();
});
</code>```

And when I run this test, I get this error:

```<code>Chromium 53.0.2785 (Ubuntu 0.0.0) Factory: BaseService add.user() should POST to /users/, failure FAILED
    [object Object] thrown
    Error: [$rootScope:inprog] $digest already in progress
    http://errors.angularjs.org/1.3.15/$rootScope/inprog?p0=%24digest
        at /home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:63:12
        at beginPhase (/home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:14820:15)
        at Scope.$digest (/home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:14262:9)
        at Function.$httpBackend.verifyNoOutstandingExpectation (node_modules/angular-mocks/angular-mocks.js:1557:38)
        at Object.<anonymous> (tests/test_base.js:61:21)
</code>```

This is BaseService.add.user():

```<code>self.add = {
    user: function(user) {
    return $http.post("/users/", user)
        .then(function successHandler(response) {
            return $http.post("/custom-api-auth/login", user)
         }).then(function successHandler(response) {
             $window.location.href = "/";

    // if there are errors, rewrite the error messages
    }).catch(function rejectHandler(errorResponse) {
                     for (prop in errorResponse.data) {
                             if (prop == "email") {
                                 errorResponse.data[prop] = "Please enter a valid email address.";
                             } else if (prop == "username") {
                                 errorResponse.data[prop] = "Username can only contain alphanumeric characters and '.'";
                             } else if (prop == "password") {
                                 errorResponse.data[prop] = "Please enter a valid password";
                             }
                     }
         throw errorResponse;
};
</code>```

How do I prevent a $digest already in progress error from occurring?

Edit: If I remove throw errorResponse;, the test works But I need throw errorResponse; there because I need to display the errors on the front end (which another controller takes care of.. BaseService.add.user().catch() basically rewrites the errors which should be displayed on the front end).

Edit 2: When the error message says at Object.<anonymous> (tests/test_base.js:61:21) it points to the line: mockBackend.verifyNoOutstandingExpectation();

答:
The problem with the code above is that it throws inside catch block. As opposed to other promise implementations, throwing and rejecting in $q is not the same thing.

Considering that $q promise chains are executed on digest ($httpBackend.flush() here) synchronously, throwing inside catch block will result in uncaught error, not in rejected promise. It likely prevents a digest from being completed and results in $digest already in progress error on next digest.

So generally $q.reject should be used for expected errors in promises, while throw should be used only for critical errors. It should be

```<code>return $q.reject(errorResponse);
</code>```

It is recommended to use Jasmine promise matchers to test it:

```<code>expect(BaseService.add.user({ ... }).toBeRejectedWith({ ... });
</code>```

Otherwise it has to be tested by more complicated promise chain:

```<code>var noError = new Error;

BaseService.add.user({ ... })
.then(() => $q.reject(noError))
.catch((err) => {
  expect(err).not.toBe(noError);
  expect(err).toEqual(...);
});

$rootScope.$digest();
</code>```

Location changes should be stubbed in tests, because changing real location in tests is the last thing the one needs:

```<code>module({ $window: {
  location: jasmine.spyObj(['href'])
} })
</code>```

And it is preferable to use $location service in Angular applications instead of accessing location directly, unless proven otherwise, $location.path('/...') instead of location.href = '/...'.

It is already safe for using in tests, although $location.path can be additionally spied for testing.

Body:
This is my test:

it('add.user() should POST to /users/, failure', function() {
    mockBackend.expectPOST("/users/", {username:'u', password: 'p', email: 'e', location: 'loc'}).respond(400, {msg: "bad request"});

    BaseService.add.user({username:'u', password: 'p', email: 'e', location: 'loc'});

    mockBackend.flush();
});

afterEach(function() {
    mockBackend.verifyNoOutstandingExpectation();
    mockBackend.verifyNoOutstandingRequest();
});

And when I run this test, I get this error:

Chromium 53.0.2785 (Ubuntu 0.0.0) Factory: BaseService add.user() should POST to /users/, failure FAILED
    [object Object] thrown
    Error: [$rootScope:inprog] $digest already in progress
    http://errors.angularjs.org/1.3.15/$rootScope/inprog?p0=%24digest
        at /home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:63:12
        at beginPhase (/home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:14820:15)
        at Scope.$digest (/home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:14262:9)
        at Function.$httpBackend.verifyNoOutstandingExpectation (node_modules/angular-mocks/angular-mocks.js:1557:38)
        at Object.<anonymous> (tests/test_base.js:61:21)

This is BaseService.add.user():

self.add = {
    user: function(user) {
    return $http.post("/users/", user)
        .then(function successHandler(response) {
            return $http.post("/custom-api-auth/login", user)
         }).then(function successHandler(response) {
             $window.location.href = "/";

    // if there are errors, rewrite the error messages
    }).catch(function rejectHandler(errorResponse) {
                     for (prop in errorResponse.data) {
                             if (prop == "email") {
                                 errorResponse.data[prop] = "Please enter a valid email address.";
                             } else if (prop == "username") {
                                 errorResponse.data[prop] = "Username can only contain alphanumeric characters and '.'";
                             } else if (prop == "password") {
                                 errorResponse.data[prop] = "Please enter a valid password";
                             }
                     }
         throw errorResponse;
};

How do I prevent a $digest already in progress error from occurring?

Edit: If I remove throw errorResponse;, the test works But I need throw errorResponse; there because I need to display the errors on the front end (which another controller takes care of.. BaseService.add.user().catch() basically rewrites the errors which should be displayed on the front end).

Edit 2: When the error message says at Object.<anonymous> (tests/test_base.js:61:21) it points to the line: mockBackend.verifyNoOutstandingExpectation();

Body:
The problem with the code above is that it throws inside catch block. As opposed to other promise implementations, throwing and rejecting in $q is not the same thing.

Considering that $q promise chains are executed on digest ($httpBackend.flush() here) synchronously, throwing inside catch block will result in uncaught error, not in rejected promise. It likely prevents a digest from being completed and results in $digest already in progress error on next digest.

So generally $q.reject should be used for expected errors in promises, while throw should be used only for critical errors. It should be

return $q.reject(errorResponse);

It is recommended to use Jasmine promise matchers to test it:

expect(BaseService.add.user({ ... }).toBeRejectedWith({ ... });

Otherwise it has to be tested by more complicated promise chain:

var noError = new Error;

BaseService.add.user({ ... })
.then(() => $q.reject(noError))
.catch((err) => {
  expect(err).not.toBe(noError);
  expect(err).toEqual(...);
});

$rootScope.$digest();

Location changes should be stubbed in tests, because changing real location in tests is the last thing the one needs:

module({ $window: {
  location: jasmine.spyObj(['href'])
} })

And it is preferable to use $location service in Angular applications instead of accessing location directly, unless proven otherwise, $location.path('/...') instead of location.href = '/...'.

It is already safe for using in tests, although $location.path can be additionally spied for testing.


问:
using unallocated memory without error?
Why does that work?

```<code>#include <iostream>
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = new float[3-i];
        i++;
    }

    cout << tab[2][7] << endl;
    tab[2][7] = 6.87;
    cout << tab[2][7] << endl;

    i = 0;
    while(i < 3)
        delete[] tab[i];
}
</code>```

while this one doesn't?

```<code>#include <iostream>
using namespace std;

int main() {
    float* tab = new float[3];

    cout << tab[7] << endl;
    tab[7] = 6.87;
    cout << tab[7] << endl;

    delete[] tab;
}
</code>```

I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).

I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.

Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?

I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?

答:
Both of them do out-of-bounds array access - you have an array of 3 float pointers, and you're accessing the 8th array. This is bound to crash.

However, unlike Java or some other managed languages, there is no explicit bounds checking for each array access (since the performance cost of that is prohibitive). So the only bounds checking you have is your MMU. If you end up accessing memory that does not belong to your application, you'll crash. If you hit memory that is not allocated but still happens to be part of your process (could be a guard word, for example), it'll silently succeed. This is a great recipe for very-hard-to-track-down bugs.

Bounds checking is key. Do it whenever you can.

ContentLicense: CC BY-SA 2.5

Title: using unallocated memory without error?

Body:
Why does that work?

#include <iostream>
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = new float[3-i];
        i++;
    }

    cout << tab[2][7] << endl;
    tab[2][7] = 6.87;
    cout << tab[2][7] << endl;

    i = 0;
    while(i < 3)
        delete[] tab[i];
}

while this one doesn't?

#include <iostream>
using namespace std;

int main() {
    float* tab = new float[3];

    cout << tab[7] << endl;
    tab[7] = 6.87;
    cout << tab[7] << endl;

    delete[] tab;
}

I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).

I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.

Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?

I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?


答:
When you do this :

```<code>total = total + x;
</code>```

x is the array. You can't use the + operator on arrays, and therefore the error. Since you are iterating over the array x,I sense you wanted this:

```<code>total = total + i;
</code>```

Title: how to add int and int[ ] in java using var args method?

Body:
When you do this :

total = total + x;

x is the array. You can't use the + operator on arrays, and therefore the error. Since you are iterating over the array x,I sense you wanted this:

total = total + i;


问:
How to create a bat file for a Java program using J Connector and other jar files?
I have written a java program using Blue J as environment. Now this program uses some external libraries (jar files), for example the jar file for the J Connector to connect to MySQL database and also 2 other jar files. In Blue J I simply added the jar files to my project and when I start the program in Blue J, everything works fine.
But now I would like to create a .bat file to make it possible to run the program on other computers.
I know that normally I start the compiled program with a batch file simply by writing into the batch file

```<code>java myApplication
</code>```

But how can I "tell" the batch file that it should also use the jar files mentioned above? When I use just the code above the bat file doesn't see them and I get the exception "No suitable driver found for jdbc:mysql ... ", which obviously means, he has problems with finding the jar file (because, as I said, starting the program in Blue J works fine).
I'm quite new to creating batch files.
Can you please tell me how I can get this working?

Thanks and greetings,
Daniel

答:
You just need to set the classpath:

```<code>java -cp jarfile1.jar;jarfile2.jar;jarfile3.jar;yourmainjar.jar MainClass
</code>```

In -cp you list all the JARs needed to run your application (including your main application JAR). On Windows, you separate them with semicolon ;, on Unix-like systems the separator is colon :.

If you use Maven to build your program, you could assemble a fat JAR: that is a JAR that, along with your application classes, contains all the classes from the JARs it uses. Maven Assembly plugin may be used to build such a JAR: http://maven.apache.org/plugins/maven-assembly-plugin/ For example, its jar-with-dependencies http://maven.apache.org/plugins/maven-assembly-plugin/descriptor-refs.html#jar-with-dependencies may be useful.

To launch your program from a fat JAR you just do

```<code>java -jar the-fat-jar.jar
</code>```

Body:
I have written a java program using Blue J as environment. Now this program uses some external libraries (jar files), for example the jar file for the J Connector to connect to MySQL database and also 2 other jar files. In Blue J I simply added the jar files to my project and when I start the program in Blue J, everything works fine.
But now I would like to create a .bat file to make it possible to run the program on other computers.
I know that normally I start the compiled program with a batch file simply by writing into the batch file

java myApplication

But how can I "tell" the batch file that it should also use the jar files mentioned above? When I use just the code above the bat file doesn't see them and I get the exception "No suitable driver found for jdbc:mysql ... ", which obviously means, he has problems with finding the jar file (because, as I said, starting the program in Blue J works fine).
I'm quite new to creating batch files.
Can you please tell me how I can get this working?

Thanks and greetings,
Daniel

Body:
You just need to set the classpath:

java -cp jarfile1.jar;jarfile2.jar;jarfile3.jar;yourmainjar.jar MainClass

In -cp you list all the JARs needed to run your application (including your main application JAR). On Windows, you separate them with semicolon ;, on Unix-like systems the separator is colon :.

If you use Maven to build your program, you could assemble a fat JAR: that is a JAR that, along with your application classes, contains all the classes from the JARs it uses. Maven Assembly plugin may be used to build such a JAR: http://maven.apache.org/plugins/maven-assembly-plugin/ For example, its jar-with-dependencies http://maven.apache.org/plugins/maven-assembly-plugin/descriptor-refs.html#jar-with-dependencies may be useful.

To launch your program from a fat JAR you just do

java -jar the-fat-jar.jar


问:
How to set up debugging in GoLand?
I am trying out GoLand and hear that the debugger is supposedly awesome, but I can’t find any documentation explaining how to set it up (GoLand is in preview stage, so that’s not really surprising). My use case: I am writing a REST API to which I send requests using curl. Could someone please tell me, step by step, how to get started with the debugger ?

[edit 1] (moved from comment) When I click Run/Debug (or Run/Run), a window is displayed, asking me to edit configurations. I am given a choice of several kinds of configurations, I try to choose "Go application" but the Debug button never is grayed and I can't get it to become clickable. I am very new to GoLand, I may be missing something obvious, but I can’t find whatever settings are missing.

[edit 2] It turns out that my workspace did not conform to the Go specifications : my code was not in a directory named src. Now that it is the case, I can click Run/Debug and GoLand seems to be doing the right thing, except it doesn’t stop at breakpoints or otherwise behave like a debugger, my code just runs.

[edit 3] Tried again, and it works. Sort of. I have no idea why it works now, even though it didn’t previously and I didn’t change anything. Now breakpoints work at some lines, and not at others. Or the debugger stops at the breakpoint, but I wait forever for the list of variables to be loaded. Well, it is a preview, after all...

[edit 4] I was notified just today that a new version of GoLand was available. I upgraded, and debugging is working well for me now.

答:
I had this exact problem.

Deleted and recreated the Debug run configuration. Debugging then worked perfectly.

ContentLicense: CC BY-SA 4.0

Title: How to set up debugging in GoLand?


问:
Running docker with pgadmin on mac getting Error: Unable to initialize GTK+, is DISPLAY set properly?
I am trying to run pgadmin from my mac (Sierra 10.12.4) as described here

```<code>docker run --rm --name pgadmin --link postgres:postgres -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY mdouchement/pgadmin3:1.20.0
</code>```

but I am getting this error:

Error: Unable to initialize GTK+, is DISPLAY set properly?

how can I run docker pgadmin ?

答:
Containers don't have a windows manager, so if you want to run GUI applications you need (e.g.) XQuartz / X11 on your Mac and have the container attach to this. This is a bit tricky, and may, or may not work. A longer discussion with hint to get this working, can be found in the Docker issue tracker; https://github.com/docker/docker/issues/8710

However, pgAdmin 4 has an option to run through a webserver, which makes it better suitable for running in a container. I created a (very simple/minimal) pgAdmin image that can be run on Docker; https://hub.docker.com/r/thajeztah/pgadmin4/, and allows you to access pgAdmin by publishing port 5050 (note the default configuration does not have access control / password protection enabled, so be sure you don't publish the port on a publicly accessible host)

Body:
I am trying to run pgadmin from my mac (Sierra 10.12.4) as described here

docker run --rm --name pgadmin --link postgres:postgres -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY mdouchement/pgadmin3:1.20.0

but I am getting this error:

Error: Unable to initialize GTK+, is DISPLAY set properly?

how can I run docker pgadmin ?


问:
how to use this element of edittext in android

when input is not valid, instead of toast or sth else this kind of new thing appears to warn the user . Does anyone know how I can use it in my own app  ?
Image is attached . Tnx in advance .

答:
That pop up is an error pop up which appears when error is set.</p>

```<code>TextInputLayout til = (TextInputLayout) findViewById(R.id.text_input_layout);
til.setError("Your error");
</code>```

Body:
That pop up is an error pop up which appears when error is set.

TextInputLayout til = (TextInputLayout) findViewById(R.id.text_input_layout);
til.setError("Your error");


答:
In the first example, tab[2] has a value that points to valid memory.  tab[2]+7 isn't allocated, But It Could Be.  No seg-fault.

In the second, tab[7] has no value... it's random bits (possibly zeros, or 0xDEADBEEF or just whatever value was there last).  This almost certainly does not point to memory that is valid for this application to access.  Thus: boom.

Title: using unallocated memory without error?


答:
The error is because you are trying to do math operations with totally incompatible data types... you are in fact trying to add an integer with an array of ints

you mean for sure

```<code>total = total + i;
</code>```

since both are the same type(int)

by doing this

```<code>total = total + x;
</code>```

you are adding int to an array of ints...

Body:
The error is because you are trying to do math operations with totally incompatible data types... you are in fact trying to add an integer with an array of ints

you mean for sure

total = total + i;

since both are the same type(int)

by doing this

total = total + x;

you are adding int to an array of ints...


答:
If I understand correctly, this is just a foreign key relationship:

```<code>create table children as (
    childId int auto_increment primary key,
    parentId int not null,
    . . .
    constraint fk_children_parent foreign key (parentId) references parents(parentId)
);
</code>```

This fulfills your two requiremens:

each parent should contain all its children

each child should contain its parent

If you want the children for a parent, you do:

```<code>select parentId, group_concat(childId) as children
from children
group by parentId;
</code>```

Title: MYSQL: can foreign key contain a collection?

Body:
I want do a foreign key in a one table that will points on a collection of other values.

For example I want do a parent table, and a child table. while each parent should contain all his children, and each children should contain his parent.

So my question is can I do this in MySQL? How can I do this if yes, and what can I use otherwise;

Body:
If I understand correctly, this is just a foreign key relationship:

create table children as (
    childId int auto_increment primary key,
    parentId int not null,
    . . .
    constraint fk_children_parent foreign key (parentId) references parents(parentId)
);

This fulfills your two requiremens:

each parent should contain all its children

each child should contain its parent

If you want the children for a parent, you do:

select parentId, group_concat(childId) as children
from children
group by parentId;


问:
Python3 Tkinter display Listbox items in a Label when clicked
I have this listbox as part of a class:

```<code>def myListbox(self):
selection = Label(self, text="Please select Country").grid(row=0,column=0)

countries = Listbox(self, width = 20, height = 75)
countries.grid(row=0, column=1)

# I have a function that populates the country names from
# a text file and displays the names in the Listbox.
# I want to be able to select a country from the Listbox
# and have it displayed in a Label

country_display = Label(self, text = "").grid(row = 0, column = 9)
# this is where I'm not sure what code to use.
# my code is
countries.bind("<<ListboxSelect>>",country_display)
</code>```

At the moment nothing is displaying. What am I missing here?
Thanks

答:
First of all, when you perform the method grid on a widget, it will return None. This means that your variable now holds the value None, instead of the reference to the widget.
Secondly, the method bind, binds a function to an event. This function cannot be called yet. However, in your bind, you try to assign the Label (which is not a function) to the event; this is simply not possible.
In the solution below, a function is assigned to the event, which retrieves the country, and sets the label.

```<code>from tkinter import *

countries_list = ["Netherlands",
                  "America",
                  "Sweden",
                  "England"]

class MyClass(Tk):
    def myListbox(self):

        # better to structure it this way. The method grid simply returns None
        # which meant that the variable hold None
        # Now, the variable selection holds the widget
        selection = Label(self, text="Please select Country")
        selection.grid(row=0,column=0)

        countries = Listbox(self, width = 20, height = len(countries_list))
        countries.grid(row=0, column=1)
        for country in countries_list:
            countries.insert(END, country)

        country_display = Label(self, text = country, width = 15)
        country_display.grid(row = 0, column = 9)

        def get_country(*x):
            # gets which country is selected, and changes
            # the label accordingly
            country = countries_list[countries.curselection()[0]]
            country_display.config(text = country)
        countries.bind("<<ListboxSelect>>", get_country)

app = MyClass()
app.myListbox()
</code>```

edit: for more information on Listbox see http://effbot.org/tkinterbook/listbox.htm
(although I get the feeling you might want to use a Combobox, as described in http://www.tkdocs.com/tutorial/widgets.html?)

Body:
I have this listbox as part of a class:

def myListbox(self):
selection = Label(self, text="Please select Country").grid(row=0,column=0)

countries = Listbox(self, width = 20, height = 75)
countries.grid(row=0, column=1)

# I have a function that populates the country names from
# a text file and displays the names in the Listbox.
# I want to be able to select a country from the Listbox
# and have it displayed in a Label

country_display = Label(self, text = "").grid(row = 0, column = 9)
# this is where I'm not sure what code to use.
# my code is
countries.bind("<<ListboxSelect>>",country_display)

At the moment nothing is displaying. What am I missing here?
Thanks

Body:
First of all, when you perform the method grid on a widget, it will return None. This means that your variable now holds the value None, instead of the reference to the widget.
Secondly, the method bind, binds a function to an event. This function cannot be called yet. However, in your bind, you try to assign the Label (which is not a function) to the event; this is simply not possible.
In the solution below, a function is assigned to the event, which retrieves the country, and sets the label.

from tkinter import *

countries_list = ["Netherlands",
                  "America",
                  "Sweden",
                  "England"]

class MyClass(Tk):
    def myListbox(self):

        # better to structure it this way. The method grid simply returns None
        # which meant that the variable hold None
        # Now, the variable selection holds the widget
        selection = Label(self, text="Please select Country")
        selection.grid(row=0,column=0)

        countries = Listbox(self, width = 20, height = len(countries_list))
        countries.grid(row=0, column=1)
        for country in countries_list:
            countries.insert(END, country)

        country_display = Label(self, text = country, width = 15)
        country_display.grid(row = 0, column = 9)

        def get_country(*x):
            # gets which country is selected, and changes
            # the label accordingly
            country = countries_list[countries.curselection()[0]]
            country_display.config(text = country)
        countries.bind("<<ListboxSelect>>", get_country)

app = MyClass()
app.myListbox()

edit: for more information on Listbox see http://effbot.org/tkinterbook/listbox.htm
(although I get the feeling you might want to use a Combobox, as described in http://www.tkdocs.com/tutorial/widgets.html?)


问:
Defining a queue datastructure in JavaScript
I am just trying to learn JavaScript. I want to design a queue which takes the following format:

```<code>[{(0,0),0}], [{(0,1),1}], [{(0,2),2}]
</code>```

So I tried to define the queue in the following way, but obviously it's not correct

```<code>var queue = [{}] ;
</code>```

答:
You can build queue as follows:

```<code>function Queue () {
 this.dataStore = [];
 this.enqueue = enqueue;
 this.dequeue = dequeue;
 this.front = front;
 this.back = back;
 this.toString = toString;
 this.empty = empty;
}

// Insetion
function enqueue(element){
 this.dataStore.push(element);
}

// Deletion
function dequeue(){
 this.dataStore.shift();
}

// front
function front(){
 return this.dataStore[0];
}

//back
function back(){
 return this.dataStore[this.dataStore.length-1];
}

//toString
function toString(){
  var retStr = '';
  for(var i = 0; i < this.dataStore.length; i++){
    retStr = retStr + this.dataStore[i]
  }
  return retStr;
 }

//empty
function empty(){
 if(this.dataStore.length === 0) {
  return true;
 }
 return false;
}
</code>```

Now use it as a constructor method, var q = new Queue().

Body:
I am just trying to learn JavaScript. I want to design a queue which takes the following format:

[{(0,0),0}], [{(0,1),1}], [{(0,2),2}]

So I tried to define the queue in the following way, but obviously it's not correct

var queue = [{}] ;

Body:
You can build queue as follows:

function Queue () {
 this.dataStore = [];
 this.enqueue = enqueue;
 this.dequeue = dequeue;
 this.front = front;
 this.back = back;
 this.toString = toString;
 this.empty = empty;
}

// Insetion
function enqueue(element){
 this.dataStore.push(element);
}

// Deletion
function dequeue(){
 this.dataStore.shift();
}

// front
function front(){
 return this.dataStore[0];
}

//back
function back(){
 return this.dataStore[this.dataStore.length-1];
}

//toString
function toString(){
  var retStr = '';
  for(var i = 0; i < this.dataStore.length; i++){
    retStr = retStr + this.dataStore[i]
  }
  return retStr;
 }

//empty
function empty(){
 if(this.dataStore.length === 0) {
  return true;
 }
 return false;
}

Now use it as a constructor method, var q = new Queue().


问:
Widget does not work when app is transfered to SD Card. What is solution for it?
My android music player when transferred to the SD card then it does not show in the widget (It does not show in the widget list). You cannot set widget in such cases. Is there any solution for it?</p>

答: Do not allow the app to be moved to removable storage, since your app has an app widget. Do this by either removing your android:installLocation attribute or setting its value to internalOnly.


问:
PHP - Get Array value by Index instead of Key

I've got a multidimensional array returned by an API call. The values into this array are stored with a key like this :

```<code>Array(["BTC_XRP"] => 1)
</code>```

I can get the values of the Array by getting them using the keys (like BTC_XRP), but what if I need to get the value using the Index?

For example, how do I get each value of the Array using a for loop if I can't get the values by the Index?

Since the Array is composed by something like 100 values, I need to echo every one using a for loop, but this gives me this error :

Notice: Undefined offset: 0

Is it possible to get to a value using the Index instead of the Key?

Furthermore, I'd like to get the Key by the Index. If I want to get the Key of the first value, I'd like to get it using the 0 Index.

Thanks!

答:
Try:

```<code>foreach ($array as $key => $value) {
  echo "Key: $key";
}
</code>```

Where $array is the array you want to loop through.

It will print out all the keys

Body:
I've got a multidimensional array returned by an API call. The values into this array are stored with a key like this :

Array(["BTC_XRP"] => 1)

I can get the values of the Array by getting them using the keys (like BTC_XRP), but what if I need to get the value using the Index?

For example, how do I get each value of the Array using a for loop if I can't get the values by the Index?

Since the Array is composed by something like 100 values, I need to echo every one using a for loop, but this gives me this error :

Notice: Undefined offset: 0

Is it possible to get to a value using the Index instead of the Key?

Furthermore, I'd like to get the Key by the Index. If I want to get the Key of the first value, I'd like to get it using the 0 Index.

Thanks!

Body:
Try:

foreach ($array as $key => $value) {
  echo "Key: $key";
}

Where $array is the array you want to loop through.

It will print out all the keys


问:
Is there a "Group Box" equivalent in Java Swing?
Trying to build a GUI application in Java/Swing. I'm mainly used to "painting" GUIs on the Windows side with tools like VB (or to be more precise, Gupta SQLWindows... wonder how many people know what that is ;-)).

I can't find an equivalent of a Group Box in Swing...

With a group box, you have a square box (usually with a title) around a couple of related widgets. One example is a group box around a few radio buttons (with the title explaining what the radio buttons are about, e.g. Group Box entitled "Sex" with "Male" and "Female" radio buttons).

I've searched around a bit... the only way I found was to add a sub-pane, set the border on the sub-pane and then add all the widgets in the "group" to the sub-pane. Is there a more elegant way to do that?

答:
I'm responding based on the Uri's comment which explaind what the OP meant by Group Box:

Uri: I think he means the control group you see in many dialog boxes, where you have a square around a bunch of widgets such as radio buttons, for example.

As far as I know, every JComponent can set a border for itself, so you don't need a second panel.

OwnerDisplayName: IronGoofy

LastEditorDisplayName: A. Rex

OwnerDisplayName: Donovan


问:
How to avoid micro lags while music is playing?
I'm writing Audio Player in Qt. I use QMediaPlayer. I tried to connect music position with QSlider, but when 2 connecting are working, it makes micro lags. That's my code:

```<code>connect(player, &QMediaPlayer::positionChanged, this, [&](qint64 value){
    int pos = static_cast<int>(value);
    ui->positionSlider->setValue(pos);
});
connect(ui->positionSlider, &QSlider::valueChanged, this, [&](int value){
    player->setPosition(value);
});
</code>```

How can I fix this bug?

答:
You need to check if the slider is pressed when the slider value changes.

If it's not pressed, it means it is just a progress event.

If it is pressed, then it means the user is interacting with it, therefore set the mediaplayer position

```<code>connect(ui->positionSlider, &QSlider::valueChanged, this, [&](int value)
{
    if (ui->positionSlider->isSliderDown())
        player->setPosition(value);
});
</code>```

By the way, that's exactly what they do in the reference example.

Body:
I'm writing Audio Player in Qt. I use QMediaPlayer. I tried to connect music position with QSlider, but when 2 connecting are working, it makes micro lags. That's my code:

connect(player, &QMediaPlayer::positionChanged, this, [&](qint64 value){
    int pos = static_cast<int>(value);
    ui->positionSlider->setValue(pos);
});
connect(ui->positionSlider, &QSlider::valueChanged, this, [&](int value){
    player->setPosition(value);
});

How can I fix this bug?

Body:
You need to check if the slider is pressed when the slider value changes.

If it's not pressed, it means it is just a progress event.

If it is pressed, then it means the user is interacting with it, therefore set the mediaplayer position

connect(ui->positionSlider, &QSlider::valueChanged, this, [&](int value)
{
    if (ui->positionSlider->isSliderDown())
        player->setPosition(value);
});

By the way, that's exactly what they do in the reference example.


问:
Retrieve all values from child i collectionView
I´m trying to retrieve all the values from one child into a collectionView

I keep getting this error

Could not cast value of type '__NSDictionaryM' in this line

```<code>let follower = snapshotValue!["Followers"] as! String
</code>```

here is my code

```<code>followRef.child("users").child((FIRAuth.auth()?.currentUser?.displayName)!).observe(FIRDataEventType.value, with: {
            snapshot in
            let snapshotValue = snapshot.value as? Dictionary<String,AnyObject>
            let follower = snapshotValue!["Followers"] as! String
            self.postsFollow.insert(postFollowStruct(follower: follower) , at: 0)
            self.followersView.reloadData()
            })
</code>```

答:
By what i understand you have many json objects in your snapshot.value? Then you want to cast to an object each one of them and put them into an array?</p>

```<code>if let dict = snapshot.value as? [String: AnyObject]{
                    let followers = dict
                    for follower in followers {
                        if let restDict = follower.value as? [String:AnyObject] {
                            let followerObj = Follower()
                            followerObj.setValuesForKeys(restDict)
                            //add to array
                        }
                    }
                }
</code>```

Body:
I´m trying to retrieve all the values from one child into a collectionView

I keep getting this error

Could not cast value of type '__NSDictionaryM' in this line

let follower = snapshotValue!["Followers"] as! String

here is my code

followRef.child("users").child((FIRAuth.auth()?.currentUser?.displayName)!).observe(FIRDataEventType.value, with: {
            snapshot in
            let snapshotValue = snapshot.value as? Dictionary<String,AnyObject>
            let follower = snapshotValue!["Followers"] as! String
            self.postsFollow.insert(postFollowStruct(follower: follower) , at: 0)
            self.followersView.reloadData()
            })

Body:
By what i understand you have many json objects in your snapshot.value? Then you want to cast to an object each one of them and put them into an array?

if let dict = snapshot.value as? [String: AnyObject]{
                    let followers = dict
                    for follower in followers {
                        if let restDict = follower.value as? [String:AnyObject] {
                            let followerObj = Follower()
                            followerObj.setValuesForKeys(restDict)
                            //add to array
                        }
                    }
                }


问:
Does verilog have a way to make global parameters in a single file similar to VHDL package storing constants?
Does verilog have a way to store global parameters in a single file similar to VHDL package storing constants?

Would it be correct to use systemVerilog for this

```<code>// File my_pkg.sv

package my_pkg;

    class my_class;
    endclass
    enter code here
endpackage
</code>```

Then this in the main code

```<code>`include "my_class.sv"
</code>```

Thanks

答:
SystemVerilog has a package concept similar to VHDL (no coincidence). And most modern tools that support Verilog also support SystemVerilog.

What you would do is

```<code>package my_pkg;

class my_class;
endclass
`include "other_class_files.svh"
enter code here
endpackage
</code>```

Then in your code

import my_pkg::*;

See http://go.mentor.com/package-import-versus-include

Body:
Does verilog have a way to store global parameters in a single file similar to VHDL package storing constants?

Would it be correct to use systemVerilog for this

// File my_pkg.sv

package my_pkg;

    class my_class;
    endclass
    enter code here
endpackage

Then this in the main code

`include "my_class.sv"

Thanks

Body:
SystemVerilog has a package concept similar to VHDL (no coincidence). And most modern tools that support Verilog also support SystemVerilog.

What you would do is

package my_pkg;

class my_class;
endclass
`include "other_class_files.svh"
enter code here
endpackage

Then in your code

import my_pkg::*;

See http://go.mentor.com/package-import-versus-include


问:
How to create a 2d list from a input data?
I was trying this

```<code>n = int(input())
m = int(input())
print(n,m)
for i in range(0,n):
    for j in range(0,m):
        ar[i][j] = int(input())
for i in range(0,n):
    for j in range(0,m):
        print (ar[i][j])
</code>```

But it was showing an error

```<code>Traceback (most recent call last):
  File "C:/Users/shivansh/Desktop/test.py", line 6, in <module>
    ar[i][j] = int(input())
NameError: name 'ar' is not defined
</code>```

I used to do the same in C language but it works. So, how to this in Python?

答:
You should know that ar is not defined when you are trying to perform an assignment like ar[i][j] = int(input()), there are many ways to fix that.

In C/C++

In C/C++, I presume you would do such work like this:

```<code>#include <cstdio>

int main()
{
    int m, n;
    scanf("%d %d", &m, &n);
    int **ar = new int*[m];
    for(int i = 0; i < m; i++)
        ar[i] = new int[n];
    for(int i = 0; i < m; i++)
        for(int j = 0; j < n; j++)
            scanf("%d", &ar[i][j]);
    // Do what you want to do

    for(int i = 0; i < m; i++)
        delete ar[i];
    delete ar;

    return 0;
}
</code>```

Before you get inputs by scanf in C/C++, you should allocate storage by calling new or malloc, then you can perform your scanf, or it will crash.

How to do like that in Python

It's very similar to what you had done in C/C++, according to your code, when you are trying to perform assignment to ar[i][j], Python has no idea what ar it is! So you have to let it know first.

A NOT-pythonic way

A NOT-Pythonic way is do something like you did in C/C++:

```<code>n = int(input())
m = int(input())

ar = []
for i in range(m):
    ar.append([])
    for j in range(n):
        k = int(input())
        ar[i].append(k)

for i in range(m):
    for j in range(n):
        print(ar[i][j])
</code>```

You initialize the list by ar = [] like you did int **ar = new int*[m]; in C/C++. For each row in the 2-d list, initialize the row by using ar.append([]) like you did ar[i] = new int[n]; in C/C++. Then, get your data by using input and append it to ar[i].

A pythonic way

The way to perform such a job like above it's not very pythonic, instead, you can get it done by using a feature called List Comprehensions, then the code can be simplified into this:

```<code>n = int(input())
m = int(input())

ar = [[0 for j in range(n)] for i in range(m)]
for i in range(m):
    for j in range(n):
        k = int(input())
        ar[i][j] = k

for i in range(m):
    for j in range(n):
        print(ar[i][j])
</code>```

Note that the core ar = [[0 for j in range(n)] for i in range(m)] is a list comprehension that it creates a list which has m lists and for each list of these m lists it has n 0s.

Body:
I was trying this

n = int(input())
m = int(input())
print(n,m)
for i in range(0,n):
    for j in range(0,m):
        ar[i][j] = int(input())
for i in range(0,n):
    for j in range(0,m):
        print (ar[i][j])

But it was showing an error

Traceback (most recent call last):
  File "C:/Users/shivansh/Desktop/test.py", line 6, in <module>
    ar[i][j] = int(input())
NameError: name 'ar' is not defined

I used to do the same in C language but it works. So, how to this in Python?

Body:
You should know that ar is not defined when you are trying to perform an assignment like ar[i][j] = int(input()), there are many ways to fix that.

In C/C++

In C/C++, I presume you would do such work like this:

#include <cstdio>

int main()
{
    int m, n;
    scanf("%d %d", &m, &n);
    int **ar = new int*[m];
    for(int i = 0; i < m; i++)
        ar[i] = new int[n];
    for(int i = 0; i < m; i++)
        for(int j = 0; j < n; j++)
            scanf("%d", &ar[i][j]);
    // Do what you want to do

    for(int i = 0; i < m; i++)
        delete ar[i];
    delete ar;

    return 0;
}

Before you get inputs by scanf in C/C++, you should allocate storage by calling new or malloc, then you can perform your scanf, or it will crash.

How to do like that in Python

It's very similar to what you had done in C/C++, according to your code, when you are trying to perform assignment to ar[i][j], Python has no idea what ar it is! So you have to let it know first.

A NOT-pythonic way

A NOT-Pythonic way is do something like you did in C/C++:

n = int(input())
m = int(input())

ar = []
for i in range(m):
    ar.append([])
    for j in range(n):
        k = int(input())
        ar[i].append(k)

for i in range(m):
    for j in range(n):
        print(ar[i][j])

You initialize the list by ar = [] like you did int **ar = new int*[m]; in C/C++. For each row in the 2-d list, initialize the row by using ar.append([]) like you did ar[i] = new int[n]; in C/C++. Then, get your data by using input and append it to ar[i].

A pythonic way

The way to perform such a job like above it's not very pythonic, instead, you can get it done by using a feature called List Comprehensions, then the code can be simplified into this:

n = int(input())
m = int(input())

ar = [[0 for j in range(n)] for i in range(m)]
for i in range(m):
    for j in range(n):
        k = int(input())
        ar[i][j] = k

for i in range(m):
    for j in range(n):
        print(ar[i][j])

Note that the core ar = [[0 for j in range(n)] for i in range(m)] is a list comprehension that it creates a list which has m lists and for each list of these m lists it has n 0s.


问:
javafx how to plot a chart in real time
Im trying to plot a chart in real time to create an illustration of the trajectory of a projectile and simulate how it moves through the air. However, when I try to do this, nothing is plotted on the chart but no errors are thrown. </p>

```<code>    String seriesName = " ";
    fireButton.setOnAction(e -> {
        double initialVelValue = initialVelSlider.getValue();
        double angleValue = angleSlider.getValue();
        double gravityValue = gravitySlider.getValue();
        // Define series
        XYChart.Series series = new XYChart.Series();
        series.setName(seriesName);     // Title of the series
        graph.setLegendVisible(false);
        long startTime = System.nanoTime();
        new AnimationTimer() {
            @Override
            public void handle(long now) {
                double elapsedTime = (now - startTime)/1000000000d;
                updateGraph(graph, initialVelValue, angleValue, gravityValue, 0,
                        projectileCalculations.getTotalDisplacement(initialVelValue, angleValue, gravityValue),
                        " ", elapsedTime);

                System.out.println(elapsedTime);
                if(elapsedTime > projectileCalculations.getTotalTime(initialVelValue, angleValue, gravityValue)) {
                    this.stop();
                }
            }
        }.start();

public void updateGraph(LineChart chart, double initialVel, double angle, double gravity, double start, double stop, String seriesName, double elapsedTime){
    double step = (stop-start) / 100; // Divide the visible area into 1000 parts

    int vMax = 0;
    double vDisplacement = projectileCalculations.getVDisplacement(initialVel, angle, gravity, elapsedTime);
    double hDisplacement = projectileCalculations.getHDisplacement(initialVel, angle, elapsedTime);
    vMax = (int) (vDisplacement > vMax ? Math.ceil(vDisplacement) : vMax);

    XYChart.Series series;
    boolean newChart = false;
    if (chart.getData().size() > 0) {
        newChart = true;
        series = (XYChart.Series) chart.getData().get(0);
    } else {
        series = new Series();
    }

    series.getData().clear();
    series.getData().add(new XYChart.Data(hDisplacement, vDisplacement));

    ((NumberAxis) chart.getYAxis()).setAutoRanging(false); // Alow manual choosing of range
    ((NumberAxis) chart.getYAxis()).setLowerBound(0); // Set start and stop of axis
    ((NumberAxis) chart.getYAxis()).setUpperBound(vMax);

    if (newChart) {
        chart.getData().add(series); // Add data series to line chart
    }
}
</code>```

答:
I don't understand what you are exactly trying to do, but since chart.getData() starts empty newChart is false and no series gets added to chart data.

I would simplify this to work with just 1 series first the tackle the problem of painting more then 1 series.

Title: javafx how to plot a chart in real time

Body:
Im trying to plot a chart in real time to create an illustration of the trajectory of a projectile and simulate how it moves through the air. However, when I try to do this, nothing is plotted on the chart but no errors are thrown.

    String seriesName = " ";
    fireButton.setOnAction(e -> {
        double initialVelValue = initialVelSlider.getValue();
        double angleValue = angleSlider.getValue();
        double gravityValue = gravitySlider.getValue();
        // Define series
        XYChart.Series series = new XYChart.Series();
        series.setName(seriesName);     // Title of the series
        graph.setLegendVisible(false);
        long startTime = System.nanoTime();
        new AnimationTimer() {
            @Override
            public void handle(long now) {
                double elapsedTime = (now - startTime)/1000000000d;
                updateGraph(graph, initialVelValue, angleValue, gravityValue, 0,
                        projectileCalculations.getTotalDisplacement(initialVelValue, angleValue, gravityValue),
                        " ", elapsedTime);

                System.out.println(elapsedTime);
                if(elapsedTime > projectileCalculations.getTotalTime(initialVelValue, angleValue, gravityValue)) {
                    this.stop();
                }
            }
        }.start();

public void updateGraph(LineChart chart, double initialVel, double angle, double gravity, double start, double stop, String seriesName, double elapsedTime){
    double step = (stop-start) / 100; // Divide the visible area into 1000 parts

    int vMax = 0;
    double vDisplacement = projectileCalculations.getVDisplacement(initialVel, angle, gravity, elapsedTime);
    double hDisplacement = projectileCalculations.getHDisplacement(initialVel, angle, elapsedTime);
    vMax = (int) (vDisplacement > vMax ? Math.ceil(vDisplacement) : vMax);

    XYChart.Series series;
    boolean newChart = false;
    if (chart.getData().size() > 0) {
        newChart = true;
        series = (XYChart.Series) chart.getData().get(0);
    } else {
        series = new Series();
    }

    series.getData().clear();
    series.getData().add(new XYChart.Data(hDisplacement, vDisplacement));

    ((NumberAxis) chart.getYAxis()).setAutoRanging(false); // Alow manual choosing of range
    ((NumberAxis) chart.getYAxis()).setLowerBound(0); // Set start and stop of axis
    ((NumberAxis) chart.getYAxis()).setUpperBound(vMax);

    if (newChart) {
        chart.getData().add(series); // Add data series to line chart
    }
}


问:
JAVA: non-static variable randomNums cannot be referenced from a static context
```<code>import java.util.Random;
public class Enemy extends Character{
Random randomNums = new Random();

public Enemy (Type enemyType){
    super(enemyType);
}

public int dropCoins(){
    return randomNums.nextInt((50-30)+1)+30;
}

public static int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public static int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}
</code>```

}

```<code>import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();

//methods

public Player(Type playerType){
    super(playerType);
    coins = 0;
    inventory = new Potion[5];
}

public void increaseStrength(int strengthIncrease){

}
public int getCoins(){
    return coins;
}
public void increaseCoins(int coins){

}
public void decreaseCoins(int coins){

}
public void addToInventory(String a, Type potion){

}
public void removeFromInventory(int index){

}
public void displayInventory(){

}
/*public int getNumOpenSlots(){
    return numOpenSlots;
}*/

public void battleMinion(Enemy enemy){

    Enemy goblin = new Enemy(Character.Type.GOBLIN);

    if (enemy.getName() == "Goblin"){
        for (int i = 1; i <= goblin.getNumGoblins(); i++)
        {
          System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);

public abstract class Character{

public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}

private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes

//methods

public Character(Type characterType){
    switch(characterType){
        case ROGUE:
            //set the attributes for a Rogue
            name = "Rogue";
            // TODO: set other attributes
            hitPoints = 55;
            strength = 8;
            Weapon rogue = new Weapon("Short Sword", 1, 4);

            break;
        case PALADIN:
            //set the attributes for a Rogue
            name = "Paladin";
            // TODO: set other attributes
            hitPoints = 35;
            strength = 14;
            Weapon paladin = new Weapon("Long Sword",3,7);
            break;
        case JACKIE_CHEN:
            name = "Jackie Chen";
            hitPoints =45;
            strength = 10;
            Weapon jackie = new Weapon("Jump Kick",2, 6);
            break;
        case SKELETON:
            name = "Skeleton";
            hitPoints = 25;
            strength = 3;
            Weapon skeleton = new Weapon("Short Sword" ,1, 4);
            break;
        case GOBLIN:
            name = "Goblin";
            hitPoints = 25;
            strength = 4;
            Weapon goblin = new Weapon("Axe",2,6);
            break;
        case WIZARD:
            name = "Wizard";
            hitPoints = 40;
            strength = 8;
            Weapon wizard = new Weapon("Fire Blast", 4, 10);
            break;
    }
}

public String getName(){
    return name;
}

public int getHitPoints(){
    return hitPoints;
}
public int getStrength(){
    return strength;
}
public void setStrength(int _strength){
    this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
    this.weapon = _weapon;

}

public void attack(){

}

public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}
</code>```

get error message

```<code>./Enemy.java:14: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((5-2)+1)+2;
               ^
./Enemy.java:17: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((7-3)+1)+3;
               ^
</code>```

2 errors

No idea how to figure it out...

答:
Because randomNums reference is object scoped, you can't directly access it inside the static methods, so declare it's scope as static, shown below:

```<code>static Random randomNums = new Random();
</code>```

OR anyhow, you are calling getNumGoblins() and getNumSkeletons() methods using goblin (reference type of Enemy), so just remove the static keyword from the method signature like:

```<code>public int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}
</code>```

Body:
import java.util.Random;
public class Enemy extends Character{
Random randomNums = new Random();

public Enemy (Type enemyType){
    super(enemyType);
}

public int dropCoins(){
    return randomNums.nextInt((50-30)+1)+30;
}

public static int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public static int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}

}

import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();

//methods

public Player(Type playerType){
    super(playerType);
    coins = 0;
    inventory = new Potion[5];
}

public void increaseStrength(int strengthIncrease){

}
public int getCoins(){
    return coins;
}
public void increaseCoins(int coins){

}
public void decreaseCoins(int coins){

}
public void addToInventory(String a, Type potion){

}
public void removeFromInventory(int index){

}
public void displayInventory(){

}
/*public int getNumOpenSlots(){
    return numOpenSlots;
}*/

public void battleMinion(Enemy enemy){

    Enemy goblin = new Enemy(Character.Type.GOBLIN);

    if (enemy.getName() == "Goblin"){
        for (int i = 1; i <= goblin.getNumGoblins(); i++)
        {
          System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);

public abstract class Character{

public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}

private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes

//methods

public Character(Type characterType){
    switch(characterType){
        case ROGUE:
            //set the attributes for a Rogue
            name = "Rogue";
            // TODO: set other attributes
            hitPoints = 55;
            strength = 8;
            Weapon rogue = new Weapon("Short Sword", 1, 4);

            break;
        case PALADIN:
            //set the attributes for a Rogue
            name = "Paladin";
            // TODO: set other attributes
            hitPoints = 35;
            strength = 14;
            Weapon paladin = new Weapon("Long Sword",3,7);
            break;
        case JACKIE_CHEN:
            name = "Jackie Chen";
            hitPoints =45;
            strength = 10;
            Weapon jackie = new Weapon("Jump Kick",2, 6);
            break;
        case SKELETON:
            name = "Skeleton";
            hitPoints = 25;
            strength = 3;
            Weapon skeleton = new Weapon("Short Sword" ,1, 4);
            break;
        case GOBLIN:
            name = "Goblin";
            hitPoints = 25;
            strength = 4;
            Weapon goblin = new Weapon("Axe",2,6);
            break;
        case WIZARD:
            name = "Wizard";
            hitPoints = 40;
            strength = 8;
            Weapon wizard = new Weapon("Fire Blast", 4, 10);
            break;
    }
}

public String getName(){
    return name;
}

public int getHitPoints(){
    return hitPoints;
}
public int getStrength(){
    return strength;
}
public void setStrength(int _strength){
    this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
    this.weapon = _weapon;

}

public void attack(){

}

public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}

get error message

./Enemy.java:14: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((5-2)+1)+2;
               ^
./Enemy.java:17: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((7-3)+1)+3;
               ^

2 errors

No idea how to figure it out...

Body:
Because randomNums reference is object scoped, you can't directly access it inside the static methods, so declare it's scope as static, shown below:

static Random randomNums = new Random();

OR anyhow, you are calling getNumGoblins() and getNumSkeletons() methods using goblin (reference type of Enemy), so just remove the static keyword from the method signature like:

public int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}