问:
Centering nav menu on screen
Hey I'm pretty new to web development and was wondering if anyone could help me out figure my problem, I can't seem to make this menu be centered in the center quite a bunch of code in here and im not sure on which elements to focus and what where to focus exactly, if you could explain me or give a quick fix i would really appreciate some help

nav ul ul {
  display: none;
  text-align: center;
}

nav ul li:hover>ul {
  display: block;
  text-align: center;
}

nav ul {
  background: #efefef;
  background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -webkit-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
  padding: 0 20px;
  border-radius: 10px;
  list-style: none;
  position: relative;
  display: inline-table;
  text-align: center;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
  text-align: center;
}

nav ul li {
  float: left;
}

nav ul li:hover {
  background: #4b545f;
  background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -webkit-linear-gradient(top, #4f5964 0%, #5f6975 40%);
}

nav ul li:hover a {
  color: #fff;
}

nav ul li a {
  display: block;
  padding: 25px 40px;
  color: #757575;
  text-decoration: none;
}

nav ul ul {
  background: #5f6975;
  border-radius: 0px;
  padding: 0;
  position: absolute;
  top: 100%;
}

nav ul ul li {
  float: none;
  border-top: 1px solid #6b727c;
  border-bottom: 1px solid #575f6a;
  position: relative;
}

nav ul ul li a {
  padding: 15px 40px;
  color: #fff;
}

nav ul ul li a:hover {
  background: #4b545f;
}

nav ul ul ul {
  position: absolute;
  right: 100%;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
    <ul>
      <li>1</li>
      <li>2
        <ul>
          <li>21</li>
          <li>22</li>
          <li>23
          <li>24
              <li>25
                <ul>
                  <li>251</li>
                  <li>252</li>
                </ul>
              </li>
        </ul>
        </li>
        <li>3
          <ul>
            <li>31</li>
            <li>32</li>
            <li>33</li>
          </ul>
        </li>
        <li>4
          <ul>
            <li>41</li>
            <li>42</li>
            <li>43</li>
            <li>44</li>
          </ul>
        </li>
        <li>5
        </li>
    </ul>
  </nav>
    </code>```

答:
Since you use display: inline-table; on the ul inside the nav tag, you can add this to center the ul inside the full-width nav:

```<code>nav {
  text-align: center;
}
</code>```

nav ul ul {
  display: none;
  text-align: center;
}

nav ul li:hover>ul {
  display: block;
  text-align: center;
}
nav {
  text-align: center;
}
nav ul {
  background: #efefef;
  background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -webkit-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
  padding: 0 20px;
  border-radius: 10px;
  list-style: none;
  position: relative;
  display: inline-table;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
  text-align: center;
}

nav ul li {
  float: left;
}

nav ul li:hover {
  background: #4b545f;
  background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -webkit-linear-gradient(top, #4f5964 0%, #5f6975 40%);
}

nav ul li:hover a {
  color: #fff;
}

nav ul li a {
  display: block;
  padding: 25px 40px;
  color: #757575;
  text-decoration: none;
}

nav ul ul {
  background: #5f6975;
  border-radius: 0px;
  padding: 0;
  position: absolute;
  top: 100%;
}

nav ul ul li {
  float: none;
  border-top: 1px solid #6b727c;
  border-bottom: 1px solid #575f6a;
  position: relative;
}

nav ul ul li a {
  padding: 15px 40px;
  color: #fff;
}

nav ul ul li a:hover {
  background: #4b545f;
}

nav ul ul ul {
  position: absolute;
  right: 100%;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>1</li>
    <li>2
      <ul>
        <li>21</li>
        <li>22</li>
        <li>23
          <li>24
            <li>25
              <ul>
                <li>251</li>
                <li>252</li>
              </ul>
            </li>
      </ul>
      </li>
      <li>3
        <ul>
          <li>31</li>
          <li>32</li>
          <li>33</li>
        </ul>
      </li>
      <li>4
        <ul>
          <li>41</li>
          <li>42</li>
          <li>43</li>
          <li>44</li>
        </ul>
      </li>
      <li>5
      </li>
  </ul></code>```

Title: Centering nav menu on screen

Body:
Hey I'm pretty new to web development and was wondering if anyone could help me out figure my problem, I can't seem to make this menu be centered in the center quite a bunch of code in here and im not sure on which elements to focus and what where to focus exactly, if you could explain me or give a quick fix i would really appreciate some help

nav ul ul {
  display: none;
  text-align: center;
}

nav ul li:hover>ul {
  display: block;
  text-align: center;
}

nav ul {
  background: #efefef;
  background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -webkit-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
  padding: 0 20px;
  border-radius: 10px;
  list-style: none;
  position: relative;
  display: inline-table;
  text-align: center;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
  text-align: center;
}

nav ul li {
  float: left;
}

nav ul li:hover {
  background: #4b545f;
  background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -webkit-linear-gradient(top, #4f5964 0%, #5f6975 40%);
}

nav ul li:hover a {
  color: #fff;
}

nav ul li a {
  display: block;
  padding: 25px 40px;
  color: #757575;
  text-decoration: none;
}

nav ul ul {
  background: #5f6975;
  border-radius: 0px;
  padding: 0;
  position: absolute;
  top: 100%;
}

nav ul ul li {
  float: none;
  border-top: 1px solid #6b727c;
  border-bottom: 1px solid #575f6a;
  position: relative;
}

nav ul ul li a {
  padding: 15px 40px;
  color: #fff;
}

nav ul ul li a:hover {
  background: #4b545f;
}

nav ul ul ul {
  position: absolute;
  right: 100%;
  top: 0;
}

1

2

21

22

23

24

25

251

252

3

31

32

33

4

41

42

43

44

5

Body:
Since you use display: inline-table; on the ul inside the nav tag, you can add this to center the ul inside the full-width nav:

nav {
  text-align: center;
}

nav ul ul {
  display: none;
  text-align: center;
}

nav ul li:hover>ul {
  display: block;
  text-align: center;
}
nav {
  text-align: center;
}
nav ul {
  background: #efefef;
  background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -webkit-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
  padding: 0 20px;
  border-radius: 10px;
  list-style: none;
  position: relative;
  display: inline-table;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
  text-align: center;
}

nav ul li {
  float: left;
}

nav ul li:hover {
  background: #4b545f;
  background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -webkit-linear-gradient(top, #4f5964 0%, #5f6975 40%);
}

nav ul li:hover a {
  color: #fff;
}

nav ul li a {
  display: block;
  padding: 25px 40px;
  color: #757575;
  text-decoration: none;
}

nav ul ul {
  background: #5f6975;
  border-radius: 0px;
  padding: 0;
  position: absolute;
  top: 100%;
}

nav ul ul li {
  float: none;
  border-top: 1px solid #6b727c;
  border-bottom: 1px solid #575f6a;
  position: relative;
}

nav ul ul li a {
  padding: 15px 40px;
  color: #fff;
}

nav ul ul li a:hover {
  background: #4b545f;
}

nav ul ul ul {
  position: absolute;
  right: 100%;
  top: 0;
}

<nav>
  <ul>
    <li><a href="#">1</a></li>
    <li><a href="#">2</a>
      <ul>
        <li><a href="#">21</a></li>
        <li><a href="#">22</a></li>
        <li><a href="#">23</a>
          <li><a href="#">24</a>
            <li><a href="">25</a>
              <ul>
                <li><a href="#">251</a></li>
                <li><a href="#">252</a></li>
              </ul>
            </li>
      </ul>
      </li>
      <li><a href="#">3</a>
        <ul>
          <li><a href="#">31</a></li>
          <li><a href="#">32</a></li>
          <li><a href="#">33</a></li>
        </ul>
      </li>
      <li><a href="#">4</a>
        <ul>
          <li><a href="#">41</a></li>
          <li><a href="#">42</a></li>
          <li><a href="#">43</a></li>
          <li><a href="#">44</a></li>
        </ul>
      </li>
      <li><a href="#">5</a>
      </li>
  </ul>


来源: stackexchange

问:
Nested looping for simple logic parser
I am writing a parser for a simple programming language consisting of possibly an axis number, a two letter command, and possibly an input value. All commands are separated by a comma. I have a parser that splits the input by the delineator and runs each valid command one at a time. I'm having issues programming the looping function RP.

I could have a command like this

MD1,TP,RP5,TT,RP10

in which I would want it to run as

```<code>for (int i = 0; i < 10; i++) {
    TT();
    for (int j = 0; j < 5; j++) {
        TP();
    }
}
</code>```

So far the main parser that I have will see the first RP command and run that then see the second RP command and run it. The RP command is set to loop from the end of the last RP command giving something more like this.

```<code>for (int j = 0; j < 5; j++) {
    TP();
}
for (int i = 0; i < 10; i++) {
    TT();
}
</code>```

I've tried a few different approaches, but so far no luck. Any and all help is appreciated.

答:
Actually, I considered the question a little bit too broad. On the other hand, I couldn't resist to "try out".

Preface

First, I want to criticize (a little bit) the question title. simple logic parser sounds for me like an interpreter of boolean expressions. However, I remember that my engineering colleagues are often talking about "program logic" (and I've not yet achieved that they get rid of this). Hence, my recommendation: If you (the questioner) are talking with computer scientists, use the term "logic" sensible (or they might look confused sometimes...)

The sample code MD1,TP,RP5,TT,RP10 looks somehow familiar to me. A short google/wikipedia research cleared my mind: The Wikipedia article Numerical control is about CNC machines. Close to the end of the article, the programming is mentioned. (The German "sibling" article provides even more.) IMHO, the code really looks similar a bit but seems to be even simpler. (No offense – I consider it as good to keep things as simple as possible.)

The program notation which seems to be intended is somehow like Reverse Polish notation. I wanted at least mention that term as googling for "rpn interpreter" throws a lot of sufficient hits including github sites. Actually, the description of the intended language is a little bit too short to decide certainly which existing S/W project could be appropriate.

Having said this, I want to show what I got...

Parser

I started first with a parser (as the questioner didn't dare to expose his). This is the code of mci1.cc:

```<code>#include <iostream>
#include <sstream>

using namespace std;

typedef unsigned char uchar;

enum Token {
  TkMD = 'M' | 'D' << 8,
  TkRP = 'R' | 'P' << 8,
  TkTP = 'T' | 'P' << 8,
  TkTT = 'T' | 'T' << 8
};

inline Token tokenize(uchar c0, uchar c1) { return (Token)(c0 | c1 << 8); }

bool parse(istream &in)
{
  for (;;) {
    // read command (2 chars)
    char cmd[2];
    if (in >> cmd[0] >> cmd[1]) {
      //cout << "DEBUG: token: " << hex << tokenize(cmd[0], cmd[1]) << endl;
      switch (tokenize(cmd[0], cmd[1])) {
        case TkMD: { // MD<num>
          int num;
          if (in >> num) {
            cout << "Received 'MD" << dec << num << "'." << endl;
          } else {
            cerr << "ERROR: Number expected after 'MD'!" << endl;
            return false;
          }
        } break;
        case TkRP:  { // RP<num>
          int num;
          if (in >> num) {
            cout << "Received 'RP" << dec << num << "'." << endl;
          } else {
            cerr << "ERROR: Number expected after 'RP'!" << endl;
            return false;
          }
        } break;
        case TkTP: // TP
          cout << "Received 'TP'." << endl;
          break;
        case TkTT: // TT
          cout << "Received 'TT'." << endl;
          break;
        default:
          cerr << "ERROR: Wrong command '" << cmd[0] << cmd[1] << "'!" << endl;
          return false;
      }
    } else {
      cerr << "ERROR: Command expected!" << endl;
      return false;
    }
    // try to read separator
    char sep;
    if (!(in >> sep)) break; // probably EOF (further checks possible)
    if (sep != ',') {
      cerr << "ERROR: ',' expected!" << endl;
      return false;
    }
  }
  return true;
}

int main()
{
  // test string
  string sample("MD1,TP,RP5,TT,RP10");
  // read test string
  istringstream in(sample);
  if (parse(in)) cout << "Done." << endl;
  else cerr << "Interpreting aborted!" << endl;
  // done
  return 0;
}
</code>```

I compiled and tested with g++ and bash in Cygwin on Windows 10:

```<code>$ g++ --version
g++ (GCC) 6.4.0

$ g++ -std=c++11 -o mci mci1.cc

$ ./mci
Received 'MD1'.
Received 'TP'.
Received 'RP5'.
Received 'TT'.
Received 'RP10'.
Done.

$
</code>```

Uploaded for life demo on ideone.

I introduced the function tokenize() as part of an update. (I got the idea when I was tooth brushing and poring how to get rid of the ugly nested switches of the previous version.) Tokenizing is a common technique in parsing – however, the implementation is usually a little bit different.

Thus, the parser seems to work. Not yet the next big thing but sufficient for the next step...

Interpreter

To interprete the parsed commands, I started to make a resp. back-end – a set of classes which may store and execute the required operations.

The parse() function of the first step became the compile() function where simple standard output was replaced by code building and nesting the operations. mci2.cc:

```<code>#include <cassert>
#include <iostream>
#include <stack>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

// super class of all operations
class Op {
  protected:
    Op() = default;
  public:
    virtual ~Op() = default;
    virtual void exec() const = 0;
  // disabled: (to prevent accidental usage)
    Op(const Op&) = delete;
    Op& operator=(const Op&) = delete;
};

// super class of grouping operations
class Grp: public Op {
  protected:
    vector<Op*> _pOps; // nested operations

  protected:
    Grp() = default;
    virtual ~Grp()
    {
      for (Op *pOp : _pOps) delete pOp;
    }
  public:
    void add(Op *pOp) { _pOps.push_back(pOp); }
  // disabled: (to prevent accidental usage)
    Grp(const Grp&) = delete;
    Grp& operator=(const Grp&) = delete;
};

// class for repeat op.
class RP: public Grp {
  private:
    unsigned _n; // repeat count
  public:
    RP(unsigned n): Grp(), _n(n) { }
    virtual ~RP() = default;
    virtual void exec() const
    {
      cout << "Exec. RP" << _n << endl;
      for (unsigned i = 0; i < _n; ++i) {
        for (const Op *pOp : _pOps) pOp->exec();
      }
    }
  // disabled: (to prevent accidental usage)
    RP(const RP&) = delete;
    RP& operator=(const RP&) = delete;
};

// class for TP op.
class TP: public Op {
  public:
    TP() = default;
    virtual ~TP() = default;
    virtual void exec() const
    {
      cout << "Exec. TP" << endl;
    }
};

// class for TT op.
class TT: public Op {
  public:
    TT() = default;
    virtual ~TT() = default;
    virtual void exec() const
    {
      cout << "Exec. TT" << endl;
    }
};

// class for MD sequence
class MD: public Grp {
  private:
    unsigned _axis;
  public:
    MD(unsigned axis): Grp(), _axis(axis) { }
    virtual ~MD() = default;
    virtual void exec() const
    {
      cout << "Exec. MD" << _axis << endl;
      for (const Op *pOp : _pOps) pOp->exec();
    }
};

typedef unsigned char uchar;

enum Token {
  TkMD = 'M' | 'D' << 8,
  TkRP = 'R' | 'P' << 8,
  TkTP = 'T' | 'P' << 8,
  TkTT = 'T' | 'T' << 8
};

inline Token tokenize(uchar c0, uchar c1) { return (Token)(c0 | c1 << 8); }

MD* compile(istream &in)
{
  MD *pMD = nullptr;
  stack<Op*> pOpsNested;
#define ERROR \
  delete pMD; \
  while (pOpsNested.size()) { delete pOpsNested.top(); pOpsNested.pop(); } \
  return nullptr
  for (;;) {
    // read command (2 chars)
    char cmd[2];
    if (in >> cmd[0] >> cmd[1]) {
      //cout << "DEBUG: token: " << hex << tokenize(cmd[0], cmd[1]) << dec << endl;
      switch (tokenize(cmd[0], cmd[1])) {
        case TkMD: { // MD<num>
          int num;
          if (in >> num) {
            if (pMD) {
              cerr << "ERROR: Unexpected command 'MD" << num << "'!" << endl;
              ERROR;
            }
            pMD = new MD(num);
          } else {
            cerr << "ERROR: Number expected after 'MD'!" << endl;
            ERROR;
          }
        } break;
        case TkRP:  { // RP<num>
          int num;
          if (in >> num) {
            if (!pMD) {
              cerr << "ERROR: Unexpected command 'RP" << num << "'!" << endl;
              ERROR;
            }
            RP *pRP = new RP(num);
            while (pOpsNested.size()) {
              pRP->add(pOpsNested.top());
              pOpsNested.pop();
            }
            pOpsNested.push(pRP);
          } else {
            cerr << "ERROR: Number expected after 'RP'!" << endl;
            ERROR;
          }
        } break;
        case TkTP: { // TP
          if (!pMD) {
            cerr << "ERROR: Unexpected command 'TP'!" << endl;
            ERROR;
          }
          pOpsNested.push(new TP());
        } break;
        case TkTT: { // TT
          if (pOpsNested.empty()) {
            cerr << "ERROR: Unexpected command 'TT'!" << endl;
            ERROR;
          }
          pOpsNested.push(new TT());
        } break;
        default:
          cerr << "ERROR: Wrong command '" << cmd[0] << cmd[1] << "'!" << endl;
          ERROR;
      }
    } else {
      cerr << "ERROR: Command expected!" << endl;
      ERROR;
    }
    // try to read separator
    char sep;
    if (!(in >> sep)) break; // probably EOF (further checks possible)
    if (sep != ',') {
      cerr << "ERROR: ',' expected!" << endl;
      ERROR;
    }
  }
#undef ERROR
  assert(pMD != nullptr);
  while (pOpsNested.size()) {
    pMD->add(pOpsNested.top());
    pOpsNested.pop();
  }
  return pMD;
}

int main()
{
  // test string
  string sample("MD1,TP,RP3,TT,RP2");
  // read test string
  istringstream in(sample);
  MD *pMD = compile(in);
  if (!pMD) {
    cerr << "Interpreting aborted!" << endl;
    return 1;
  }
  // execute sequence
  pMD->exec();
  delete pMD;
  // done
  return 0;
}
</code>```

Again, I compiled and tested with g++ and bash in Cygwin on Windows 10:

```<code>$ g++ -std=c++11 -o mci mci2.cc

$ ./mci
Exec. MD1
Exec. RP2
Exec. TT
Exec. RP3
Exec. TP
Exec. TP
Exec. TP
Exec. TT
Exec. RP3
Exec. TP
Exec. TP
Exec. TP

$
</code>```

Uploaded for life demo on ideone.

The trick with the nesting is rather simple done in the compile() function:

commands TP and TT are added to a temporary stack pOpsNested

for command RP, all collected operations are added to the RP instance popping the pOpsNested stack (and thus reversing their order),

afterwards, the RP instance itself is pushed into pOpsNested stack instead

finally the contents of buffer pOpsNested is added to sequence MD (as these are the top-level ops).

ContentLicense: CC BY-SA 3.0

Title: Nested looping for simple logic parser

Body:
I am writing a parser for a simple programming language consisting of possibly an axis number, a two letter command, and possibly an input value. All commands are separated by a comma. I have a parser that splits the input by the delineator and runs each valid command one at a time. I'm having issues programming the looping function RP.

I could have a command like this

MD1,TP,RP5,TT,RP10

in which I would want it to run as

for (int i = 0; i < 10; i++) {
    TT();
    for (int j = 0; j < 5; j++) {
        TP();
    }
}

So far the main parser that I have will see the first RP command and run that then see the second RP command and run it. The RP command is set to loop from the end of the last RP command giving something more like this.

for (int j = 0; j < 5; j++) {
    TP();
}
for (int i = 0; i < 10; i++) {
    TT();
}

I've tried a few different approaches, but so far no luck. Any and all help is appreciated.

Body:
Actually, I considered the question a little bit too broad. On the other hand, I couldn't resist to "try out".

Preface

First, I want to criticize (a little bit) the question title. simple logic parser sounds for me like an interpreter of boolean expressions. However, I remember that my engineering colleagues are often talking about "program logic" (and I've not yet achieved that they get rid of this). Hence, my recommendation: If you (the questioner) are talking with computer scientists, use the term "logic" sensible (or they might look confused sometimes...)

The sample code MD1,TP,RP5,TT,RP10 looks somehow familiar to me. A short google/wikipedia research cleared my mind: The Wikipedia article Numerical control is about CNC machines. Close to the end of the article, the programming is mentioned. (The German "sibling" article provides even more.) IMHO, the code really looks similar a bit but seems to be even simpler. (No offense – I consider it as good to keep things as simple as possible.)

The program notation which seems to be intended is somehow like Reverse Polish notation. I wanted at least mention that term as googling for "rpn interpreter" throws a lot of sufficient hits including github sites. Actually, the description of the intended language is a little bit too short to decide certainly which existing S/W project could be appropriate.

Having said this, I want to show what I got...

Parser

I started first with a parser (as the questioner didn't dare to expose his). This is the code of mci1.cc:

#include <iostream>
#include <sstream>

using namespace std;

typedef unsigned char uchar;

enum Token {
  TkMD = 'M' | 'D' << 8,
  TkRP = 'R' | 'P' << 8,
  TkTP = 'T' | 'P' << 8,
  TkTT = 'T' | 'T' << 8
};

inline Token tokenize(uchar c0, uchar c1) { return (Token)(c0 | c1 << 8); }

bool parse(istream &in)
{
  for (;;) {
    // read command (2 chars)
    char cmd[2];
    if (in >> cmd[0] >> cmd[1]) {
      //cout << "DEBUG: token: " << hex << tokenize(cmd[0], cmd[1]) << endl;
      switch (tokenize(cmd[0], cmd[1])) {
        case TkMD: { // MD<num>
          int num;
          if (in >> num) {
            cout << "Received 'MD" << dec << num << "'." << endl;
          } else {
            cerr << "ERROR: Number expected after 'MD'!" << endl;
            return false;
          }
        } break;
        case TkRP:  { // RP<num>
          int num;
          if (in >> num) {
            cout << "Received 'RP" << dec << num << "'." << endl;
          } else {
            cerr << "ERROR: Number expected after 'RP'!" << endl;
            return false;
          }
        } break;
        case TkTP: // TP
          cout << "Received 'TP'." << endl;
          break;
        case TkTT: // TT
          cout << "Received 'TT'." << endl;
          break;
        default:
          cerr << "ERROR: Wrong command '" << cmd[0] << cmd[1] << "'!" << endl;
          return false;
      }
    } else {
      cerr << "ERROR: Command expected!" << endl;
      return false;
    }
    // try to read separator
    char sep;
    if (!(in >> sep)) break; // probably EOF (further checks possible)
    if (sep != ',') {
      cerr << "ERROR: ',' expected!" << endl;
      return false;
    }
  }
  return true;
}

int main()
{
  // test string
  string sample("MD1,TP,RP5,TT,RP10");
  // read test string
  istringstream in(sample);
  if (parse(in)) cout << "Done." << endl;
  else cerr << "Interpreting aborted!" << endl;
  // done
  return 0;
}

I compiled and tested with g++ and bash in Cygwin on Windows 10:

$ g++ --version
g++ (GCC) 6.4.0

$ g++ -std=c++11 -o mci mci1.cc

$ ./mci
Received 'MD1'.
Received 'TP'.
Received 'RP5'.
Received 'TT'.
Received 'RP10'.
Done.

$

Uploaded for life demo on ideone.

I introduced the function tokenize() as part of an update. (I got the idea when I was tooth brushing and poring how to get rid of the ugly nested switches of the previous version.) Tokenizing is a common technique in parsing – however, the implementation is usually a little bit different.

Thus, the parser seems to work. Not yet the next big thing but sufficient for the next step...

Interpreter

To interprete the parsed commands, I started to make a resp. back-end – a set of classes which may store and execute the required operations.

The parse() function of the first step became the compile() function where simple standard output was replaced by code building and nesting the operations. mci2.cc:

#include <cassert>
#include <iostream>
#include <stack>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

// super class of all operations
class Op {
  protected:
    Op() = default;
  public:
    virtual ~Op() = default;
    virtual void exec() const = 0;
  // disabled: (to prevent accidental usage)
    Op(const Op&) = delete;
    Op& operator=(const Op&) = delete;
};

// super class of grouping operations
class Grp: public Op {
  protected:
    vector<Op*> _pOps; // nested operations

  protected:
    Grp() = default;
    virtual ~Grp()
    {
      for (Op *pOp : _pOps) delete pOp;
    }
  public:
    void add(Op *pOp) { _pOps.push_back(pOp); }
  // disabled: (to prevent accidental usage)
    Grp(const Grp&) = delete;
    Grp& operator=(const Grp&) = delete;
};

// class for repeat op.
class RP: public Grp {
  private:
    unsigned _n; // repeat count
  public:
    RP(unsigned n): Grp(), _n(n) { }
    virtual ~RP() = default;
    virtual void exec() const
    {
      cout << "Exec. RP" << _n << endl;
      for (unsigned i = 0; i < _n; ++i) {
        for (const Op *pOp : _pOps) pOp->exec();
      }
    }
  // disabled: (to prevent accidental usage)
    RP(const RP&) = delete;
    RP& operator=(const RP&) = delete;
};

// class for TP op.
class TP: public Op {
  public:
    TP() = default;
    virtual ~TP() = default;
    virtual void exec() const
    {
      cout << "Exec. TP" << endl;
    }
};

// class for TT op.
class TT: public Op {
  public:
    TT() = default;
    virtual ~TT() = default;
    virtual void exec() const
    {
      cout << "Exec. TT" << endl;
    }
};

// class for MD sequence
class MD: public Grp {
  private:
    unsigned _axis;
  public:
    MD(unsigned axis): Grp(), _axis(axis) { }
    virtual ~MD() = default;
    virtual void exec() const
    {
      cout << "Exec. MD" << _axis << endl;
      for (const Op *pOp : _pOps) pOp->exec();
    }
};

typedef unsigned char uchar;

enum Token {
  TkMD = 'M' | 'D' << 8,
  TkRP = 'R' | 'P' << 8,
  TkTP = 'T' | 'P' << 8,
  TkTT = 'T' | 'T' << 8
};

inline Token tokenize(uchar c0, uchar c1) { return (Token)(c0 | c1 << 8); }

MD* compile(istream &in)
{
  MD *pMD = nullptr;
  stack<Op*> pOpsNested;
#define ERROR \
  delete pMD; \
  while (pOpsNested.size()) { delete pOpsNested.top(); pOpsNested.pop(); } \
  return nullptr
  for (;;) {
    // read command (2 chars)
    char cmd[2];
    if (in >> cmd[0] >> cmd[1]) {
      //cout << "DEBUG: token: " << hex << tokenize(cmd[0], cmd[1]) << dec << endl;
      switch (tokenize(cmd[0], cmd[1])) {
        case TkMD: { // MD<num>
          int num;
          if (in >> num) {
            if (pMD) {
              cerr << "ERROR: Unexpected command 'MD" << num << "'!" << endl;
              ERROR;
            }
            pMD = new MD(num);
          } else {
            cerr << "ERROR: Number expected after 'MD'!" << endl;
            ERROR;
          }
        } break;
        case TkRP:  { // RP<num>
          int num;
          if (in >> num) {
            if (!pMD) {
              cerr << "ERROR: Unexpected command 'RP" << num << "'!" << endl;
              ERROR;
            }
            RP *pRP = new RP(num);
            while (pOpsNested.size()) {
              pRP->add(pOpsNested.top());
              pOpsNested.pop();
            }
            pOpsNested.push(pRP);
          } else {
            cerr << "ERROR: Number expected after 'RP'!" << endl;
            ERROR;
          }
        } break;
        case TkTP: { // TP
          if (!pMD) {
            cerr << "ERROR: Unexpected command 'TP'!" << endl;
            ERROR;
          }
          pOpsNested.push(new TP());
        } break;
        case TkTT: { // TT
          if (pOpsNested.empty()) {
            cerr << "ERROR: Unexpected command 'TT'!" << endl;
            ERROR;
          }
          pOpsNested.push(new TT());
        } break;
        default:
          cerr << "ERROR: Wrong command '" << cmd[0] << cmd[1] << "'!" << endl;
          ERROR;
      }
    } else {
      cerr << "ERROR: Command expected!" << endl;
      ERROR;
    }
    // try to read separator
    char sep;
    if (!(in >> sep)) break; // probably EOF (further checks possible)
    if (sep != ',') {
      cerr << "ERROR: ',' expected!" << endl;
      ERROR;
    }
  }
#undef ERROR
  assert(pMD != nullptr);
  while (pOpsNested.size()) {
    pMD->add(pOpsNested.top());
    pOpsNested.pop();
  }
  return pMD;
}

int main()
{
  // test string
  string sample("MD1,TP,RP3,TT,RP2");
  // read test string
  istringstream in(sample);
  MD *pMD = compile(in);
  if (!pMD) {
    cerr << "Interpreting aborted!" << endl;
    return 1;
  }
  // execute sequence
  pMD->exec();
  delete pMD;
  // done
  return 0;
}

Again, I compiled and tested with g++ and bash in Cygwin on Windows 10:

$ g++ -std=c++11 -o mci mci2.cc

$ ./mci
Exec. MD1
Exec. RP2
Exec. TT
Exec. RP3
Exec. TP
Exec. TP
Exec. TP
Exec. TT
Exec. RP3
Exec. TP
Exec. TP
Exec. TP

$

Uploaded for life demo on ideone.

The trick with the nesting is rather simple done in the compile() function:

commands TP and TT are added to a temporary stack pOpsNested

for command RP, all collected operations are added to the RP instance popping the pOpsNested stack (and thus reversing their order),

afterwards, the RP instance itself is pushed into pOpsNested stack instead

finally the contents of buffer pOpsNested is added to sequence MD (as these are the top-level ops).


问:
jQuery counting function
I wrote this to launch a counting function when I reach #counter. when I scroll to #counter the number go from 1 to 600 like it suppose to. the problem is that it goes back to 1. I just wanted to stay at 600.

$(window).scroll(function() {
  var hT = $('#counter').offset().top,
    hH = $('#counter').outerHeight(),
    wH = $(window).height(),
    wS = $(this).scrollTop();
  console.log((hT - wH), wS);

  if (wS > (hT + hH - wH)) {
    $('.count').each(function() {
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 2000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    });
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  height: 900px;
  background: red;
}</code>```

600

```

答:
You could just stop the animation once the value is 600 using .stop() jQuery method.

$(window).scroll(function() {
   var hT = $('#counter').offset().top,
   hH = $('#counter').outerHeight(),
   wH = $(window).height(),
   wS = $(this).scrollTop();

if (wS > (hT+hH-wH)) {

$('.count').each(function (index, value) {
    $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
 }, {
        duration: 2000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
   if(Math.ceil(now) === 600){
    $(this).stop(true, true);
   }
        }
    });
    });
}

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#counter{
 margin-top: 100vh;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Counter</title>

scroll to view the counter

600

```

Here is a jsbin of the above snippet https://jsbin.com/dejeji/edit?html,js,output

Title: jQuery counting function

Body:
I wrote this to launch a counting function when I reach #counter. when I scroll to #counter the number go from 1 to 600 like it suppose to. the problem is that it goes back to 1. I just wanted to stay at 600.

$(window).scroll(function() {
  var hT = $('#counter').offset().top,
    hH = $('#counter').outerHeight(),
    wH = $(window).height(),
    wS = $(this).scrollTop();
  console.log((hT - wH), wS);

  if (wS > (hT + hH - wH)) {
    $('.count').each(function() {
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 2000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    });
  }

});

.box {
  height: 900px;
  background: red;
}

600

Body:
You could just stop the animation once the value is 600 using .stop() jQuery method.

$(window).scroll(function() {
   var hT = $('#counter').offset().top,
   hH = $('#counter').outerHeight(),
   wH = $(window).height(),
   wS = $(this).scrollTop();

if (wS > (hT+hH-wH)) {

$('.count').each(function (index, value) {
    $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
 }, {
        duration: 2000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
   if(Math.ceil(now) === 600){
    $(this).stop(true, true);
   }
        }
    });
    });
}

});

#counter{
 margin-top: 100vh;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Counter</title>
</head>
<body>
<p>scroll to view the counter</p>
<div id="counter">
<div><span class="count">600</span></div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

</body>
</html>

Here is a jsbin of the above snippet https://jsbin.com/dejeji/edit?html,js,output


答:
```<code>SELECT *
  FROM STUDENT
 WHERE student_id IN ( SELECT student_id
                         FROM GRADE
                        WHERE grade IN ( 'A', 'B' ) );
</code>```

Alternatively:

```<code>SELECT DISTINCT student_id, first_name, last_name
  FROM STUDENT NATURAL JOIN GRADE
 WHERE grade IN ( 'A', 'B' );
</code>```

Title: how to select records with specific value/condition in another table

Body:
I have 3 tables STUDENT, SUBJECT and GRADE.

STUDENT

+------------+------------+------------+
| student_id | first_name |  last_name |
+------------+------------+------------+
|          0 | Arthur     | Pain       |
|          1 | Richard    | Gordon     |
|          2 | Jennifer   | Adelaide   |
+------------+------------+------------+

SUBJECT

+------------+--------------+
| subject_id | subject_name |
+------------+--------------+
|        001 | Math         |
|        002 | Science      |
|        003 | English      |
+------------+--------------+

GRADE

+-------------+-------------+--------+
| student_id  | subject_id  |  grade |
+-------------+-------------+--------+
| 0           | 001         | A      |
| 0           | 002         | B      |
| 0           | 003         | A      |
| 1           | 001         | B      |
| 1           | 002         | A      |
| 1           | 003         | F      |
| 2           | 001         | A      |
| 2           | 002         | B      |
| 2           | 003         | B      |
+-------------+-------------+--------+

I have tried the query below.

SELECT * FROM student st WHERE EXISTS
       (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B');

I want to select the students with grades only 'A' OR 'B'.

Body:
SELECT *
  FROM STUDENT
 WHERE student_id IN ( SELECT student_id
                         FROM GRADE
                        WHERE grade IN ( 'A', 'B' ) );

Alternatively:

SELECT DISTINCT student_id, first_name, last_name
  FROM STUDENT NATURAL JOIN GRADE
 WHERE grade IN ( 'A', 'B' );


问:
how do I update and array of users with rails 3
I am trying to pass an array of user objects from flash to rails 3 and update them all at once. Here is the code that I am using.

```<code>  def update_by_fbid
    if params[:users]

     params[:users].each do |u|
       puts u
        user = User.find_by_fbid(u.fbid)
        user.update_attributes(:first_name => u.first_name, :last_name => u.last_name)
      end
    end
    render :json => {:updated_users => true}
  end
</code>```

Here is my code from Flash

```<code>private function updateUsers(e:Event):void
{
    var users:Array = [{fbid:"93847566", first_name:"Joe", last_name:"Blow"},
        {fbid:"7654321", first_name:"Ronda", last_name:"Smith"}
        ];

    var vars : URLVariables = new URLVariables();
        vars.users = users;

    var request : URLRequest = new URLRequest("http://localhost:3000/update");
    request.method = URLRequestMethod.POST;
    request.data = vars;

    var loader : URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, registerHandler);
    loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    loader.load(request);
    }
</code>```

here is the error that I am seeing in the terminal

```<code>Started POST "/update" for 127.0.0.1 at Sat Jan 22 13:41:42 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[object Object]"}
Completed   in 8ms

NoMethodError (undefined method `fbid' for "[object Object]":String):
  app/controllers/users_controller.rb:68:in `update_by_fbid'
  app/controllers/users_controller.rb:66:in `each'
  app/controllers/users_controller.rb:66:in `update_by_fbid'

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.8ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.9ms)
</code>```

Still a little new at rails so I am sure I am just selecting my objects from the parmas incorrectly or something of that nature. Hoping someone can school me a bit on what I am doing wrong on the rails side of things.

-m

答:
I took @nathanvda advice and and I have Flash send over JSON now. Here is what my consol shows now.

```<code>Started POST "/updatethem" for 127.0.0.1 at Sat Jan 22 20:11:51 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[{\"first_name\":\"Joe\",\"last_name\":\"Blow\",\"fbid\":\"93847566\"},{\"first_name\":\"Ronda\",\"last_name\":\"Smith\",\"fbid\":\"7654321\"}]"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE ("users"."fbid" IS NULL) LIMIT 1
Completed 200 OK in 13ms (Views: 2.4ms | ActiveRecord: 0.2ms)
</code>```

doing a puts params[:users] does give me the following in the consol

```<code>[{"first_name":"Joe","last_name":"Blow","fbid":"93847566"},{"first_name":"Ronda","last_name":"Smith","fbid":"7654321"}]
</code>```

This looks like an array of users as I would like to send over but doing the following does not seem to iterate over an array. Rails seems to only see params[:users] as a single object and not an array.

```<code>params[:users].each do |u|
  user = User.find_by_fbid(u[:fbid])
    if user.nil?
      puts u[:fbid]
    else
      user.update_attributes u
      puts u[:fbid]
    end
 end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to pass an array of user objects from flash to rails 3 and update them all at once. Here is the code that I am using.

  def update_by_fbid
    if params[:users]

     params[:users].each do |u|
       puts u
        user = User.find_by_fbid(u.fbid)
        user.update_attributes(:first_name => u.first_name, :last_name => u.last_name)
      end
    end
    render :json => {:updated_users => true}
  end

Here is my code from Flash

private function updateUsers(e:Event):void
{
    var users:Array = [{fbid:"93847566", first_name:"Joe", last_name:"Blow"},
        {fbid:"7654321", first_name:"Ronda", last_name:"Smith"}
        ];

    var vars : URLVariables = new URLVariables();
        vars.users = users;

    var request : URLRequest = new URLRequest("http://localhost:3000/update");
    request.method = URLRequestMethod.POST;
    request.data = vars;

    var loader : URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, registerHandler);
    loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    loader.load(request);
    }

here is the error that I am seeing in the terminal

Started POST "/update" for 127.0.0.1 at Sat Jan 22 13:41:42 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[object Object]"}
Completed   in 8ms

NoMethodError (undefined method `fbid' for "[object Object]":String):
  app/controllers/users_controller.rb:68:in `update_by_fbid'
  app/controllers/users_controller.rb:66:in `each'
  app/controllers/users_controller.rb:66:in `update_by_fbid'

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.8ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.9ms)

Still a little new at rails so I am sure I am just selecting my objects from the parmas incorrectly or something of that nature. Hoping someone can school me a bit on what I am doing wrong on the rails side of things.

-m

Body:
I took @nathanvda advice and and I have Flash send over JSON now. Here is what my consol shows now.

Started POST "/updatethem" for 127.0.0.1 at Sat Jan 22 20:11:51 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[{\"first_name\":\"Joe\",\"last_name\":\"Blow\",\"fbid\":\"93847566\"},{\"first_name\":\"Ronda\",\"last_name\":\"Smith\",\"fbid\":\"7654321\"}]"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE ("users"."fbid" IS NULL) LIMIT 1
Completed 200 OK in 13ms (Views: 2.4ms | ActiveRecord: 0.2ms)

doing a puts params[:users] does give me the following in the consol

[{"first_name":"Joe","last_name":"Blow","fbid":"93847566"},{"first_name":"Ronda","last_name":"Smith","fbid":"7654321"}]

This looks like an array of users as I would like to send over but doing the following does not seem to iterate over an array. Rails seems to only see params[:users] as a single object and not an array.

params[:users].each do |u|
  user = User.find_by_fbid(u[:fbid])
    if user.nil?
      puts u[:fbid]
    else
      user.update_attributes u
      puts u[:fbid]
    end
 end


问:
Why am I getting 'missing comma'?
I am completely new to SQL, and for a project for my intro level class.

I am getting a "missing comma" error for all of my INSERT statements when my numbers are in single quotes, and a "missing expression" error when they are not in quotes. I can not figure out where I am going wrong. Below is just one of my tables and an INSERT statement for that table, but this issue extends to all of my INSERT statements.

```<code>CREATE TABLE Cast(
Cast_ID NUMBER(7) NOT NULL PRIMARY KEY,
Cast_Member_Name VARCHAR2(64),
Oscars NUMBER(2)
);
COMMIT;

INSERT INTO Cast VALUES (17,’Tom Cruise’,0)
</code>```

Below is the error I receive when entering the above INSERT:

```<code>INSERT INTO Cast VALUES (17,.Tom Cruise.,0);
INSERT INTO Cast VALUES (17,.Tom Cruise.,0)

ERROR at line 1:
ORA-00936: missing expression
</code>```

答:
You miss quotes in Tom cruise. Put it query will cruise.
INSERT INTO Cast VALUES (17,'Tom Cruise',0)

Title: Why am I getting 'missing comma'?

Body:
I am completely new to SQL, and for a project for my intro level class.

I am getting a "missing comma" error for all of my INSERT statements when my numbers are in single quotes, and a "missing expression" error when they are not in quotes. I can not figure out where I am going wrong. Below is just one of my tables and an INSERT statement for that table, but this issue extends to all of my INSERT statements.

CREATE TABLE Cast(
Cast_ID NUMBER(7) NOT NULL PRIMARY KEY,
Cast_Member_Name VARCHAR2(64),
Oscars NUMBER(2)
);
COMMIT;

INSERT INTO Cast VALUES (17,’Tom Cruise’,0)

Below is the error I receive when entering the above INSERT:

INSERT INTO Cast VALUES (17,.Tom Cruise.,0);
INSERT INTO Cast VALUES (17,.Tom Cruise.,0)

ERROR at line 1:
ORA-00936: missing expression


问:
Calculating Diff To Specific Value Within Groups
I need to calculate the differences within groups for thousands of simulated experiments. Here is a simplified version of the data:

```<code>import pandas as pd

data = {
    'experiment':['exp_1','exp_1','exp_1','exp_2','exp_2','exp_3','exp_3','exp_3','exp_3'],
    'variation':['control','variation_1','variation_2','control','variation_1','control','variation_1','variation_2','variation_3'],
    'revenue': [100,120,155,50,95,300,500,350,610]
}
df = pd.DataFrame(data,columns=['experiment','variation','revenue'])

In [16]: df
Out[16]:
  experiment    variation  revenue
0      exp_1      control      100
1      exp_1  variation_1       90
2      exp_1  variation_2      155
3      exp_2      control       50
4      exp_2  variation_1       95
5      exp_3      control      300
6      exp_3  variation_1      500
7      exp_3  variation_2      250
8      exp_3  variation_3      610
</code>```

Notice that each experiment does not have a fixed number number of variations--there can be just an A/B test, or an A/B/C/D test.

The goal is to calculate the diffs by comparing each variation to the control within each experiment. That would give the following results for the example data:

```<code>In [17]: df
Out[17]:
  experiment    variation  revenue  diffs
0      exp_1      control      100    NaN
1      exp_1  variation_1       90    -10
2      exp_1  variation_2      155     55
3      exp_2      control       50    NaN
4      exp_2  variation_1       95     45
5      exp_3      control      300    NaN
6      exp_3  variation_1      500    200
7      exp_3  variation_2      250    -50
8      exp_3  variation_3      610    310
</code>```

This answer is really close, but it is a cumulative diff at each point in time, rather than to a comparison to the first value in each group.

答:
I was able to accomplish this by making a new dataframe of only rows with variation == control, then outer-merging it back in to the original dataframe and subtracting the resulting columns.</p>

```<code>controls = df[df.variation == 'control'][['experiment','revenue']]
merged = pd.merge(controls,df,on='experiment',how='outer',suffixes=['_control',''])
df['diffs'] = merged['revenue'] - merged['revenue_control']
</code>```

Body:
I need to calculate the differences within groups for thousands of simulated experiments. Here is a simplified version of the data:

import pandas as pd

data = {
    'experiment':['exp_1','exp_1','exp_1','exp_2','exp_2','exp_3','exp_3','exp_3','exp_3'],
    'variation':['control','variation_1','variation_2','control','variation_1','control','variation_1','variation_2','variation_3'],
    'revenue': [100,120,155,50,95,300,500,350,610]
}
df = pd.DataFrame(data,columns=['experiment','variation','revenue'])

In [16]: df
Out[16]:
  experiment    variation  revenue
0      exp_1      control      100
1      exp_1  variation_1       90
2      exp_1  variation_2      155
3      exp_2      control       50
4      exp_2  variation_1       95
5      exp_3      control      300
6      exp_3  variation_1      500
7      exp_3  variation_2      250
8      exp_3  variation_3      610

Notice that each experiment does not have a fixed number number of variations--there can be just an A/B test, or an A/B/C/D test.

The goal is to calculate the diffs by comparing each variation to the control within each experiment. That would give the following results for the example data:

In [17]: df
Out[17]:
  experiment    variation  revenue  diffs
0      exp_1      control      100    NaN
1      exp_1  variation_1       90    -10
2      exp_1  variation_2      155     55
3      exp_2      control       50    NaN
4      exp_2  variation_1       95     45
5      exp_3      control      300    NaN
6      exp_3  variation_1      500    200
7      exp_3  variation_2      250    -50
8      exp_3  variation_3      610    310

This answer is really close, but it is a cumulative diff at each point in time, rather than to a comparison to the first value in each group.

Body:
I was able to accomplish this by making a new dataframe of only rows with variation == control, then outer-merging it back in to the original dataframe and subtracting the resulting columns.

controls = df[df.variation == 'control'][['experiment','revenue']]
merged = pd.merge(controls,df,on='experiment',how='outer',suffixes=['_control',''])
df['diffs'] = merged['revenue'] - merged['revenue_control']


问:
Semantic UI Grid disable equal height columns to get smaller columns to stack
I have two different widget-categories with different width and heights.
The big widget has 2x the width and height of the small widget.

Now I specify the column width depending on the screen size  with the semantic ui classes like "six wide widescreen" and so on.
So the order is first all big widgets and then the small widgets get displayed.
On Computer and tablet size first two big widgets get the class eight wide each so they take the first row on their own.
On wide screen I give the big widgets only six wide so both just take 12 of the 16 columns per row so 2 columns of the small widgets can get up to the first row.

The Html

```<code><div  class="ui internally celled stackable grid" >
  <div class="row">
    <div style="background-color: blue; height: 600px;" class="column six wide widescreen eight wide computer eight wide tablet sixteen wide mobile">
      Big Widget 1
    </div>
    <div style="background-color: green; height: 600px;" class="column six wide widescreen eight wide computer eight wide tablet sixteen wide mobile">
      Big Widget 2
    </div>
    <div style="background-color: red; height: 300px;" class="column two wide widescreen two wide large-screen four wide computer eight wide mobile four wide tablet">
      Small Widget 1
    </div>
    <div style="background-color: orange; height: 300px;" class="column two wide widescreen two wide large-screen four wide computer eight wide mobile four wide tablet">
      Small Widget 2
    </div>
    <div style="background-color: purple; height: 300px;" class="column two wide widescreen two wide large-screen four wide computer eight wide mobile four wide tablet">
      Small Widget 3
    </div>
    <div style="background-color: gray; height: 300px;" class="column two wide widescreen two wide large-screen four wide computer eight wide mobile four wide tablet">
      Small Widget 4
    </div>
  </div>
</div>
</code>```

Codepen Demo

Now my question: The Small widgets have exactly the half height of the big widgets so the white space underneath the 2 small widgets in widescreen mode could be filled with the third and fourth small widget.

Is there a way to break the first two small widgets columns by half to fit the third and fourth widget in the first row?

How it looks right now

How I want it to

答:
I have got it done based on the built-in CSS Grid instead of the external library you used. Please see the Codepen Demo.

I have not touched the  part of your HTML, but I've removed the two files you referred to in your .  And then added the following CSS:

```<code>.row{
  display:grid;
  grid-template-columns:1fr 1fr 1fr 1fr 1fr 1fr;
  grid-template-rows: 300px 300px 300px;
  grid-auto-flow: dense;
}
.six{
  grid-column: span 2;
  grid-row: span 2;
}
</code>```

Now CSS Grid is supported by mainstream browsers with built-in CSS. No need to depend on any other libraries. If you search for "CSS Grid", there are quite some tutorials available.

Hope this helps.

Body:
I have two different widget-categories with different width and heights.
The big widget has 2x the width and height of the small widget.

Now I specify the column width depending on the screen size  with the semantic ui classes like "six wide widescreen" and so on.
So the order is first all big widgets and then the small widgets get displayed.
On Computer and tablet size first two big widgets get the class eight wide each so they take the first row on their own.
On wide screen I give the big widgets only six wide so both just take 12 of the 16 columns per row so 2 columns of the small widgets can get up to the first row.

The Html

      Big Widget 1

      Big Widget 2

      Small Widget 1

      Small Widget 2

      Small Widget 3

      Small Widget 4

Codepen Demo

Now my question: The Small widgets have exactly the half height of the big widgets so the white space underneath the 2 small widgets in widescreen mode could be filled with the third and fourth small widget.

Is there a way to break the first two small widgets columns by half to fit the third and fourth widget in the first row?

How it looks right now

How I want it to

Body:
I have got it done based on the built-in CSS Grid instead of the external library you used. Please see the Codepen Demo.

I have not touched the <body> part of your HTML, but I've removed the two files you referred to in your <head>.  And then added the following CSS:

.row{
  display:grid;
  grid-template-columns:1fr 1fr 1fr 1fr 1fr 1fr;
  grid-template-rows: 300px 300px 300px;
  grid-auto-flow: dense;
}
.six{
  grid-column: span 2;
  grid-row: span 2;
}

Now CSS Grid is supported by mainstream browsers with built-in CSS. No need to depend on any other libraries. If you search for "CSS Grid", there are quite some tutorials available.

Hope this helps.


问:
password_verify keeps bringing back false
ok so ive got password_hash working on one of my pages.

I'm wondering how would i apply password_verify to the following code:

function selectUser($conn, $username, $password)
{

```<code>$query = "SELECT username, password FROM login WHERE password = :password AND username = :username";

$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $password);
$stmt->execute();

if ($row = $stmt->fetch()) {
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $password;
    echo "Welcome, you are now logged in as " . $username;
    return true;
}

else {
    //echo "Your details were not found";
    return false;
}
</code>```

tried it myself and its been very confusing to me.

thank you

also got this:

```<code>if(!isset($_POST["Login"]))
{
    header("Location:new-user.php");
}

$username=trim($_POST['username']);
$password=$_POST['password'];

$username= htmlspecialchars($username);
$validForm = true;

if (empty($_POST["username"]))
            {
            $validForm=false;
            }
if (empty($_POST["password"]))
            {
            $validForm=false;
            }
if (!$validForm) {

$error = "please ensure all fields are filled in";
include("add.php");
return false;

}

$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{
       header( "Location: search.php" );
}else{
       $error = "The details you have entered are incorrect";
      include("add.php");
}

$conn=NULL; //close the connection
</code>```

Update

also tried this: Knowing this doesnt work, tested with echo statements but still no luck

```<code>function hash_input() {

$password = "sfafgsd";

return $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
}

function selectUser($conn, $username, $password)
{
    $query = "SELECT password FROM login WHERE username = :username";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':username', $username);
    $stmt->execute();
echo $username . " " . $password;
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        echo "WE MADE IT";
        if(password_verify(hash_input($password), $row['password'])){
            $_SESSION['username'] = $username;
            echo "Welcome, you are now logged in as " . $username;
            return true;
        }

        //echo "Your details were not found";
        sleep(1);
        return false;
    }
    else
    {
        //echo "Your details were not found";
        return false;
    }
}
</code>```

答:
The comments given by Mark cover the below exactly.

Order of events:

Send username to database and collect the hashed password from the row found.

run the password string given through password_verify to compare with the hashed value

return this result (true/false).

Celebrate. Have a coffeee or a tea.

There is no need to $_SESSION password data and this is a bad idea. Password data (hash or plaintext) should not be retained beyond this function call. If you do for some reason need to have a nonce value associated with this account/membership/login then this should be setup using a random string in its own column in the database.

Improved Function Code

```<code>function selectUser($conn, $username, $password)
{
    $query = "SELECT password FROM login WHERE username = :username LIMIT 1";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':username', $username);
 // $stmt->bindValue(':password', $password); NO Don't do this.
    $stmt->execute();

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        if(password_verify($password,$row['password'])){
            $_SESSION['username'] = $username;
   //       $_SESSION['password'] = $password; DO NOT DO THIS
            echo "Welcome, you are now logged in as " . $username;
            return true;
        }
        //bad password
        //echo "Your details were not found";
        sleep(1); // it can be a good idea to add a forced pause on
                  // password fail to discourage brute force cracking.
        return false;
    }
    //echo "Your details were not found";
    return false;
}
</code>```

Body:
ok so ive got password_hash working on one of my pages.

I'm wondering how would i apply password_verify to the following code:

function selectUser($conn, $username, $password)
{

$query = "SELECT username, password FROM login WHERE password = :password AND username = :username";

$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $password);
$stmt->execute();

if ($row = $stmt->fetch()) {
    $_SESSION['username'] = $username;
    $_SESSION['password'] = $password;
    echo "Welcome, you are now logged in as " . $username;
    return true;
}

else {
    //echo "Your details were not found";
    return false;
}

tried it myself and its been very confusing to me.

thank you

also got this:

if(!isset($_POST["Login"]))
{
    header("Location:new-user.php");
}

$username=trim($_POST['username']);
$password=$_POST['password'];

$username= htmlspecialchars($username);
$validForm = true;

if (empty($_POST["username"]))
            {
            $validForm=false;
            }
if (empty($_POST["password"]))
            {
            $validForm=false;
            }
if (!$validForm) {

$error = "please ensure all fields are filled in";
include("add.php");
return false;

}

$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{
       header( "Location: search.php" );
}else{
       $error = "The details you have entered are incorrect";
      include("add.php");
}

$conn=NULL; //close the connection

Update

also tried this: Knowing this doesnt work, tested with echo statements but still no luck

function hash_input() {

$password = "sfafgsd";

return $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
}

function selectUser($conn, $username, $password)
{
    $query = "SELECT password FROM login WHERE username = :username";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':username', $username);
    $stmt->execute();
echo $username . " " . $password;
    if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        echo "WE MADE IT";
        if(password_verify(hash_input($password), $row['password'])){
            $_SESSION['username'] = $username;
            echo "Welcome, you are now logged in as " . $username;
            return true;
        }

        //echo "Your details were not found";
        sleep(1);
        return false;
    }
    else
    {
        //echo "Your details were not found";
        return false;
    }
}

Body:
The comments given by Mark cover the below exactly.

Order of events:

Send username to database and collect the hashed password from the row found.

run the password string given through password_verify to compare with the hashed value

return this result (true/false).

Celebrate. Have a coffeee or a tea.

There is no need to $_SESSION password data and this is a bad idea. Password data (hash or plaintext) should not be retained beyond this function call. If you do for some reason need to have a nonce value associated with this account/membership/login then this should be setup using a random string in its own column in the database.

Improved Function Code

function selectUser($conn, $username, $password)
{
    $query = "SELECT password FROM login WHERE username = :username LIMIT 1";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':username', $username);
 // $stmt->bindValue(':password', $password); NO Don't do this.
    $stmt->execute();

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        if(password_verify($password,$row['password'])){
            $_SESSION['username'] = $username;
   //       $_SESSION['password'] = $password; DO NOT DO THIS
            echo "Welcome, you are now logged in as " . $username;
            return true;
        }
        //bad password
        //echo "Your details were not found";
        sleep(1); // it can be a good idea to add a forced pause on
                  // password fail to discourage brute force cracking.
        return false;
    }
    //echo "Your details were not found";
    return false;
}


问:
Doing a SHA256withRSA with Google Apps Script
I am trying to do a Google oAuth2 method in Google Apps Script by constructing the descripbed JWS/JWT stuff.

Now, I can read a key file from Drive or maybe from another source, but how should I sign it with this file? Are there any methods or JavaSCript pieces to do this?

```<code>function Auth20(user) {
var header = Utilities.base64Encode(JSON.stringify( {"alg":"RS256","typ":"JWT"} ) );
var claimdata = {
"iss":"1002979611916q0iraclc6q33xxxxxxxx@developer.gserviceaccount.com",
             "prn": user,
             "scope":"https://www.googleapis.com/auth/plus.circles.read",
             "aud":"https://accounts.google.com/o/oauth2/token",
               "exp":new Date().getTime()/1000,
               "iat":(new Date().getTime()/1000)+3600
              }
var claim = Utilities.base64Encode(JSON.stringify( claimdata ))

 var jws = header+"."+claim;
 var jwsbytes = [];

 for (var i = 0; i < jws.length; ++i)
 {
 jwsbytes.push(jws.charCodeAt(i));
 }
  var key = DriveApp.getFileById("0B_5HSTQXtXmsU29fTE5xNWhvOVE").getBlob()
</code>```

答:
A function like the one below should do the trick. Two things to note:

1) The Private Key needs to be in the format of a PRIVATE KEY not an RSA PRIVATE KEY. If your key is the latter, you'll need openssl, which would allow you to run the following for your key stored in the private.pem file. Note also the string format with explicit \n when used within GAS:

```<code>openssl pkcs8 -topk8 -inform pem -in private.pem -outform pem -nocrypt -out newPrivate.pem
</code>```

2) Utilities.base64EncodeWebSafe() may return terminal padding in the form of = signs. These need to be removed, hence my inclusion of steps with .replace(/=+$/, '')

Putting it all together:

```<code>function Auth20(user) {
  var privateKey = "-----BEGIN PRIVATE KEY-----\n{privatekeyhere}\n-----END PRIVATE KEY-----\n"
  var header = {
    alg: 'RS256',
    typ: 'JWT'
  };
  var now = new Date();
  var claimSet = {
    iss: {your_iss},
    prn: user,
    scope: "https://www.googleapis.com/auth/plus.circles.read",
    aud:"https://accounts.google.com/o/oauth2/token",
    exp: (now.getTime() / 1000) + 3000,
    iat: now.getTime() / 1000
  };
  var toSign = Utilities.base64EncodeWebSafe(JSON.stringify(header)) + '.' + Utilities.base64EncodeWebSafe(JSON.stringify(claimSet));
  toSign = toSign.replace(/=+$/, '');
  var signatureBytes = Utilities.computeRsaSha256Signature(toSign, privateKey);
  var signature = Utilities.base64EncodeWebSafe(signatureBytes);
  signature = signature.replace(/=+$/, '');
  return toSign + '.' + signature;
};
</code>```

Body:
I am trying to do a Google oAuth2 method in Google Apps Script by constructing the descripbed JWS/JWT stuff.

Now, I can read a key file from Drive or maybe from another source, but how should I sign it with this file? Are there any methods or JavaSCript pieces to do this?

function Auth20(user) {
var header = Utilities.base64Encode(JSON.stringify( {"alg":"RS256","typ":"JWT"} ) );
var claimdata = {
"iss":"1002979611916q0iraclc6q33xxxxxxxx@developer.gserviceaccount.com",
             "prn": user,
             "scope":"https://www.googleapis.com/auth/plus.circles.read",
             "aud":"https://accounts.google.com/o/oauth2/token",
               "exp":new Date().getTime()/1000,
               "iat":(new Date().getTime()/1000)+3600
              }
var claim = Utilities.base64Encode(JSON.stringify( claimdata ))

 var jws = header+"."+claim;
 var jwsbytes = [];

 for (var i = 0; i < jws.length; ++i)
 {
 jwsbytes.push(jws.charCodeAt(i));
 }
  var key = DriveApp.getFileById("0B_5HSTQXtXmsU29fTE5xNWhvOVE").getBlob()

Body:
A function like the one below should do the trick. Two things to note:

1) The Private Key needs to be in the format of a PRIVATE KEY not an RSA PRIVATE KEY. If your key is the latter, you'll need openssl, which would allow you to run the following for your key stored in the private.pem file. Note also the string format with explicit \n when used within GAS:

openssl pkcs8 -topk8 -inform pem -in private.pem -outform pem -nocrypt -out newPrivate.pem

2) Utilities.base64EncodeWebSafe() may return terminal padding in the form of = signs. These need to be removed, hence my inclusion of steps with .replace(/=+$/, '')

Putting it all together:

function Auth20(user) {
  var privateKey = "-----BEGIN PRIVATE KEY-----\n{privatekeyhere}\n-----END PRIVATE KEY-----\n"
  var header = {
    alg: 'RS256',
    typ: 'JWT'
  };
  var now = new Date();
  var claimSet = {
    iss: {your_iss},
    prn: user,
    scope: "https://www.googleapis.com/auth/plus.circles.read",
    aud:"https://accounts.google.com/o/oauth2/token",
    exp: (now.getTime() / 1000) + 3000,
    iat: now.getTime() / 1000
  };
  var toSign = Utilities.base64EncodeWebSafe(JSON.stringify(header)) + '.' + Utilities.base64EncodeWebSafe(JSON.stringify(claimSet));
  toSign = toSign.replace(/=+$/, '');
  var signatureBytes = Utilities.computeRsaSha256Signature(toSign, privateKey);
  var signature = Utilities.base64EncodeWebSafe(signatureBytes);
  signature = signature.replace(/=+$/, '');
  return toSign + '.' + signature;
};


问:
ObjectMapper readValue always adds time zone at the end of XMLGregorianCalendar from a JSON date string
I am writing a junit test case which I need to give the following data file (request):

```<code>  data_file:

  {
    "birthDate" : "2017-12-08"
   }
</code>```

The junit test file uses:

```<code>     fasterxml.jackson.databind.ObjectMapper.readValue(data_file)
</code>```

to read this request data file and convert the date into XMLGregorianCalendar.  However, the converted value has a "Z" at the end, I think that is the default time zone:

```<code>     2017-12-08T00:00:00.000Z
</code>```

I can't change the java class that contains the code for reading the Json value because we don't own the code.  So what date string should I give in my test data file so that the "Z" won't appear at the end of converted XMLGregorianCalendar value?

```<code>     2017-12-08T00:00:00.000
</code>```

Many Thanks.

答:
I don’t know how your JSON mapper gets to the result it does. I tried:

```<code>    System.out.println(
            DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-12-08"));
</code>```

This prints

```<code>2017-12-08
</code>```

No offset from UTC and also no time of day, just the same string as I fed into the XMLGregorianCalendar.

However, once you have got an XMLGregorianCalendar, say, xgc, you can remove the offset by setting it to undefined:

```<code>    xgc.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
</code>```

Now the toString method will produce a string without the Z in the end.

Body:
I am writing a junit test case which I need to give the following data file (request):

  data_file:

  {
    "birthDate" : "2017-12-08"
   }

The junit test file uses:

     fasterxml.jackson.databind.ObjectMapper.readValue(data_file)

to read this request data file and convert the date into XMLGregorianCalendar.  However, the converted value has a "Z" at the end, I think that is the default time zone:

     2017-12-08T00:00:00.000Z

I can't change the java class that contains the code for reading the Json value because we don't own the code.  So what date string should I give in my test data file so that the "Z" won't appear at the end of converted XMLGregorianCalendar value?

     2017-12-08T00:00:00.000

Many Thanks.

Body:
I don’t know how your JSON mapper gets to the result it does. I tried:

    System.out.println(
            DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-12-08"));

This prints

2017-12-08

No offset from UTC and also no time of day, just the same string as I fed into the XMLGregorianCalendar.

However, once you have got an XMLGregorianCalendar, say, xgc, you can remove the offset by setting it to undefined:

    xgc.setTimezone(DatatypeConstants.FIELD_UNDEFINED);

Now the toString method will produce a string without the Z in the end.


问:
Grouping Edges in DOT (Graphviz)
Is there a way to group edges together into a single bus in DOT/Graphviz, while still fraying the edges near nodes?

Eg:

Changing this:

```<code>graph my_graph {
    rankdir=LR
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- C;
}
</code>```

into something like this:

答:
One way to do it is with dummy [shape=point] nodes, like so:

```<code>graph my_graph {
    rankdir=LR;
    {rank = same; B; C;}
    aa [ shape=point ];
    bb [ shape=point ];
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;

    aa -- bb [ penwidth=4.0];

    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;

    A -- C;
}
</code>```

This has some downsides though:

it doubles the number of edges in your source file, and makes it hard to manage.

If you have head and tail labels, then you need to place them accordingly.

It mucks up your node ranks, so you have to manually adjust all the other nodes.

The frayed ends are still rounded and taking up a lot of space. This might be fixable by setting the splines attribute, but I haven't been able to get it to work (it seems like no multiple edges between two nodes are always shown as splines no matter what the value of splines is).

Another option:

There's also the concentrate attribute, but this will only collect lines going to the same point. It will not 1) fray ends or 2) increase line thickness to represent the bus:

```<code>graph my_graph {
    rankdir=LR
    concentrate=true;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- C;
}
</code>```

Title: Grouping Edges in DOT (Graphviz)

Body:
Is there a way to group edges together into a single bus in DOT/Graphviz, while still fraying the edges near nodes?

Eg:

Changing this:

graph my_graph {
    rankdir=LR
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- C;
}

into something like this:

Body:
One way to do it is with dummy [shape=point] nodes, like so:

graph my_graph {
    rankdir=LR;
    {rank = same; B; C;}
    aa [ shape=point ];
    bb [ shape=point ];
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;
    A -- aa;

    aa -- bb [ penwidth=4.0];

    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;
    bb -- B;

    A -- C;
}

This has some downsides though:

it doubles the number of edges in your source file, and makes it hard to manage.

If you have head and tail labels, then you need to place them accordingly.

It mucks up your node ranks, so you have to manually adjust all the other nodes.

The frayed ends are still rounded and taking up a lot of space. This might be fixable by setting the splines attribute, but I haven't been able to get it to work (it seems like no multiple edges between two nodes are always shown as splines no matter what the value of splines is).

Another option:

There's also the concentrate attribute, but this will only collect lines going to the same point. It will not 1) fray ends or 2) increase line thickness to represent the bus:

graph my_graph {
    rankdir=LR
    concentrate=true;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- B;
    A -- C;
}


答:
Check this:
If it okay, I will explain.

 nav{
     text-align:center;
 }
nav ul ul {
  display: none;
  text-align: center;
}

nav ul li:hover>ul {
  display: block;
  text-align: center;
  width: 88px;
}

nav ul {
  background: #efefef;
  background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -webkit-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
  padding: 0 20px;
  border-radius: 10px;
  list-style: none;
  position: relative;
  display: inline-table;
  text-align: center;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
  text-align: center;
}

nav ul li {
  float: left;
}

nav ul li:hover {
  background: #4b545f;
  background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -webkit-linear-gradient(top, #4f5964 0%, #5f6975 40%);
}

nav ul li:hover a {
  color: #fff;
}

nav ul li a {
  display: block;
  padding: 25px 40px;
  color: #757575;
  text-decoration: none;
}

nav ul ul {
  background: #5f6975;
  border-radius: 0px;
  padding: 0;
  position: absolute;
  top: 100%;
}

nav ul ul li {
  float: none;
  border-top: 1px solid #6b727c;
  border-bottom: 1px solid #575f6a;
  position: relative;
}

nav ul ul li a {
  padding: 15px 40px;
  color: #fff;
}

nav ul ul li a:hover {
  background: #4b545f;
}

nav ul ul ul {
  position: absolute;
  right: 100%;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
<ul>
  <li>1</li>
  <li>2
    <ul>
      <li>21</li>
      <li>22</li>
      <li>23
      <li>24
          <li>25
            <ul>
              <li>251</li>
              <li>252</li>
            </ul>
          </li>
    </ul>
    </li>
    <li>3
      <ul>
        <li>31</li>
        <li>32</li>
        <li>33</li>
      </ul>
    </li>
    <li>4
      <ul>
        <li>41</li>
        <li>42</li>
        <li>43</li>
        <li>44</li>
      </ul>
    </li>
    <li>5
    </li>
</ul>
</nav></code>```

Title: Centering nav menu on screen

Body:
Hey I'm pretty new to web development and was wondering if anyone could help me out figure my problem, I can't seem to make this menu be centered in the center quite a bunch of code in here and im not sure on which elements to focus and what where to focus exactly, if you could explain me or give a quick fix i would really appreciate some help

nav ul ul {
  display: none;
  text-align: center;
}

nav ul li:hover>ul {
  display: block;
  text-align: center;
}

nav ul {
  background: #efefef;
  background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -webkit-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
  padding: 0 20px;
  border-radius: 10px;
  list-style: none;
  position: relative;
  display: inline-table;
  text-align: center;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
  text-align: center;
}

nav ul li {
  float: left;
}

nav ul li:hover {
  background: #4b545f;
  background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -webkit-linear-gradient(top, #4f5964 0%, #5f6975 40%);
}

nav ul li:hover a {
  color: #fff;
}

nav ul li a {
  display: block;
  padding: 25px 40px;
  color: #757575;
  text-decoration: none;
}

nav ul ul {
  background: #5f6975;
  border-radius: 0px;
  padding: 0;
  position: absolute;
  top: 100%;
}

nav ul ul li {
  float: none;
  border-top: 1px solid #6b727c;
  border-bottom: 1px solid #575f6a;
  position: relative;
}

nav ul ul li a {
  padding: 15px 40px;
  color: #fff;
}

nav ul ul li a:hover {
  background: #4b545f;
}

nav ul ul ul {
  position: absolute;
  right: 100%;
  top: 0;
}

1

2

21

22

23

24

25

251

252

3

31

32

33

4

41

42

43

44

5

Body:
Check this:
If it okay, I will explain.

 nav{
     text-align:center;
 }
nav ul ul {
  display: none;
  text-align: center;
}

nav ul li:hover>ul {
  display: block;
  text-align: center;
  width: 88px;
}

nav ul {
  background: #efefef;
  background: linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -moz-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  background: -webkit-linear-gradient(top, #efefef 0%, #bbbbbb 100%);
  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.15);
  padding: 0 20px;
  border-radius: 10px;
  list-style: none;
  position: relative;
  display: inline-table;
  text-align: center;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
  text-align: center;
}

nav ul li {
  float: left;
}

nav ul li:hover {
  background: #4b545f;
  background: linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -moz-linear-gradient(top, #4f5964 0%, #5f6975 40%);
  background: -webkit-linear-gradient(top, #4f5964 0%, #5f6975 40%);
}

nav ul li:hover a {
  color: #fff;
}

nav ul li a {
  display: block;
  padding: 25px 40px;
  color: #757575;
  text-decoration: none;
}

nav ul ul {
  background: #5f6975;
  border-radius: 0px;
  padding: 0;
  position: absolute;
  top: 100%;
}

nav ul ul li {
  float: none;
  border-top: 1px solid #6b727c;
  border-bottom: 1px solid #575f6a;
  position: relative;
}

nav ul ul li a {
  padding: 15px 40px;
  color: #fff;
}

nav ul ul li a:hover {
  background: #4b545f;
}

nav ul ul ul {
  position: absolute;
  right: 100%;
  top: 0;
}

<nav>
<ul>
  <li><a href="#">1</a></li>
  <li><a href="#">2</a>
    <ul>
      <li><a href="#">21</a></li>
      <li><a href="#">22</a></li>
      <li><a href="#">23</a>
      <li><a href="#">24</a>
          <li><a href="">25</a>
            <ul>
              <li><a href="#">251</a></li>
              <li><a href="#">252</a></li>
            </ul>
          </li>
    </ul>
    </li>
    <li><a href="#">3</a>
      <ul>
        <li><a href="#">31</a></li>
        <li><a href="#">32</a></li>
        <li><a href="#">33</a></li>
      </ul>
    </li>
    <li><a href="#">4</a>
      <ul>
        <li><a href="#">41</a></li>
        <li><a href="#">42</a></li>
        <li><a href="#">43</a></li>
        <li><a href="#">44</a></li>
      </ul>
    </li>
    <li><a href="#">5</a>
    </li>
</ul>
</nav>


问:
Java parallelStream not showing correct result
I was doing some performance evaluation of Java aggeragate operations to iterate over collections. I was doing an evaluation of performance stream and parallelStream. But I found that the output of parallelStream is wrong most of the times. For example in the following code i got wrong output from parallelStream more than 80% of the time:

```<code>    public class ParallelStreamPerformance {
    static int totaleven = 0;
    public static void main(String[] args) {
        List<Integer> randomList = new ArrayList<>();
        Random rnd = new Random();
        for(int i = 0 ;i < 1000;i++) {
            int r = rnd.nextInt(500000);
            randomList.add(r);
        }

        long s1 = System.currentTimeMillis();

        randomList.stream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);

        totaleven = 0;
        long s2 = System.currentTimeMillis();

        randomList.parallelStream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e2 = System.currentTimeMillis();
        System.out.println(e2 - s2);
    }
    public static void count() {
        totaleven++;
    }
}
</code>```

My question is: Am I using parallelStream in a wrong way? Is there any way to ensure the correctness of parallelStream.
Thanks

答:
Instead of using the forEach to increment a counter you can use the terminal operation Stream:count

For example

```<code>totaleven = randomList.stream().filter(e -> e % 2 ==0).count();
totaleven = 0;
totaleven = randomList.parallelStream().filter(e -> e % 2 ==0).count();
</code>```

totaleven would need to be changed to data type long or casting applied.

Body:
I was doing some performance evaluation of Java aggeragate operations to iterate over collections. I was doing an evaluation of performance stream and parallelStream. But I found that the output of parallelStream is wrong most of the times. For example in the following code i got wrong output from parallelStream more than 80% of the time:

    public class ParallelStreamPerformance {
    static int totaleven = 0;
    public static void main(String[] args) {
        List<Integer> randomList = new ArrayList<>();
        Random rnd = new Random();
        for(int i = 0 ;i < 1000;i++) {
            int r = rnd.nextInt(500000);
            randomList.add(r);
        }

        long s1 = System.currentTimeMillis();

        randomList.stream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);

        totaleven = 0;
        long s2 = System.currentTimeMillis();

        randomList.parallelStream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e2 = System.currentTimeMillis();
        System.out.println(e2 - s2);
    }
    public static void count() {
        totaleven++;
    }
}

My question is: Am I using parallelStream in a wrong way? Is there any way to ensure the correctness of parallelStream.
Thanks

Body:
Instead of using the forEach to increment a counter you can use the terminal operation Stream:count

For example

totaleven = randomList.stream().filter(e -> e % 2 ==0).count();
totaleven = 0;
totaleven = randomList.parallelStream().filter(e -> e % 2 ==0).count();

totaleven would need to be changed to data type long or casting applied.


问:
In-App Purchases stuck in "Missing Metadata" state
I am trying to set up in-app purchases but I don't know how to get rid of the "Missing Metadata" shown below.

The only yellow dot I see from the page is the "Localizations" section, but I completed the "Display Name" and "Description".

I don't know what else I can do or what I am doing wrong.

答: In my case the problem was that the price wasn't specified; I didn't actually have sufficient permissions to set a price (my role was 'Developer') so the section didn't appear and I didn't notice it was missing.</p>

ContentLicense: CC BY-SA 4.0


问:
How call the function on multiDatesPicker date select
I need to call the function on  multiDatesPicker date select event.

```<code>I have used below  code for display the multidateselect,

  $('#from-input').multiDatesPicker();
</code>```

Here, I need to call the function on date select in multiDatesPicker. How can I do. Please help me.

答:
use onSelect</p>

```<code>$('.date').multiDatesPicker({
   onSelect: function(date){ //do something with the date}
})
</code>```

Body:
I need to call the function on  multiDatesPicker date select event.

I have used below  code for display the multidateselect,

  $('#from-input').multiDatesPicker();

Here, I need to call the function on date select in multiDatesPicker. How can I do. Please help me.

Body:
use onSelect

$('.date').multiDatesPicker({
   onSelect: function(date){ //do something with the date}
})


问:
Get error in django project?
My GitHub https://github.com/Loctarogar/line
Get this error.

```<code>NoReverseMatch at /account/login/

Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name

settings
#authentification information
from django.core.urlresolvers import reverse_lazy

LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
</code>```

I get this error when enter login and password and press "Log-in" button.

account/urls.py

```<code>from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^$', views.dashboard, name='dashboard'),
    url(r'^login/$', auth_views.login, name='login'),
    url(r"^logout/$", auth_views.logout, name="logout"),
    url(r"^loguot-then-login/$", auth_views.logout_then_login, name="logout_then_login"),
    ]
</code>```

shop/shop/urls.py

```<code>from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^account/', include('account.urls', namespace="account")),
    url(r'^cart/', include('cart.urls', namespace='cart')),
    url(r'^', include('goods.urls', namespace='goods')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)
</code>```

答:
You are using the namespace account, so you need to include that when you reverse the URL.

```<code>LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
</code>```

Note that you can simply use the name of the URL pattern, and Django will reverse it for you:

```<code>LOGIN_REDIRECT_URL = 'account:dashboard'
</code>```

Title: Get error in django project?

Body:
My GitHub https://github.com/Loctarogar/line
Get this error.

NoReverseMatch at /account/login/

Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name

settings
#authentification information
from django.core.urlresolvers import reverse_lazy

LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')

I get this error when enter login and password and press "Log-in" button.

account/urls.py

from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^$', views.dashboard, name='dashboard'),
    url(r'^login/$', auth_views.login, name='login'),
    url(r"^logout/$", auth_views.logout, name="logout"),
    url(r"^loguot-then-login/$", auth_views.logout_then_login, name="logout_then_login"),
    ]

shop/shop/urls.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^account/', include('account.urls', namespace="account")),
    url(r'^cart/', include('cart.urls', namespace='cart')),
    url(r'^', include('goods.urls', namespace='goods')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

Body:
You are using the namespace account, so you need to include that when you reverse the URL.

LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')

Note that you can simply use the name of the URL pattern, and Django will reverse it for you:

LOGIN_REDIRECT_URL = 'account:dashboard'


问:
Python appending empty list
I am very new to Python and trying to learn by trial-and-error, so my question may sound naive for the community.

Let's say I have two empty lists with only the first element defined:

```<code>a = [[]]*20
a[0] = 0
b = [[]]*20
b[0] = 1
</code>```

I want to use a for loop for creating the other elements of the lists:

```<code>x = 20
for i in range(1,x):
    a[i] = b[i-1],
    b[i] = a[i-1]+b[i-1]
</code>```

What I obtain is the following error:TypeError: can only concatenate tuple (not "int") to tuple.
Basically I am trying to reproduce the fibonacci series (a famous starting point in Python tutorial), but I would like to experiment other ways of obtaining the same output.

Thank you!

答:
The problem is on this line:

```<code>a[i] = b[i-1],
</code>```

Notice the comma at the end? That makes python think you're dealing in tuples. Remove it and the error will be gone.

Title: Python appending empty list

Body:
I am very new to Python and trying to learn by trial-and-error, so my question may sound naive for the community.

Let's say I have two empty lists with only the first element defined:

a = [[]]*20
a[0] = 0
b = [[]]*20
b[0] = 1

I want to use a for loop for creating the other elements of the lists:

x = 20
for i in range(1,x):
    a[i] = b[i-1],
    b[i] = a[i-1]+b[i-1]

What I obtain is the following error:TypeError: can only concatenate tuple (not "int") to tuple.
Basically I am trying to reproduce the fibonacci series (a famous starting point in Python tutorial), but I would like to experiment other ways of obtaining the same output.

Thank you!

Body:
The problem is on this line:

a[i] = b[i-1],

Notice the comma at the end? That makes python think you're dealing in tuples. Remove it and the error will be gone.


问:
Python 3.x A program thats control if some requirments true
My purpose with this program is to take input from student and make sure that
he/she typed 3 digit number. Neither less than 3 or greater than 3 and it shouldnt be string. All this above  if something wrong, program should ask again until its become true </p>

```<code>def studentID():
       try:
           number=int(input("sutedent IDS:"))
           try:
                assert len(number)==3

           except AssertionError:
               print("Must be 3 digit number.")
               studentID()

       except ValueError:
           print("Please enter an integer.")
           studentID()

       except TypeError:
           print("What is wrong with you?")
           studentID()
</code>```

答:
ints don't have a len.  You'll have to convert it back to a string to check its length.

```<code>def studentid():
    try:
        num = int(input('student ID:'))
        if len(str(num)) != 3:
            print('Please enter a 3-digit number')
            return studentid()
        return num
    except ValueError:
        print('Please enter a 3-digit number')
        return studentid()
</code>```

You also probably want to return the num to the caller.  Note that we cast the input to an int then back into a string.  This is because in some recent versions of Python (3.6+), you can have underscores in int literals, so int('1_2') would be a valid 3 character input that evaluates to a 2 digit number

Body:
My purpose with this program is to take input from student and make sure that
he/she typed 3 digit number. Neither less than 3 or greater than 3 and it shouldnt be string. All this above  if something wrong, program should ask again until its become true

def studentID():
       try:
           number=int(input("sutedent IDS:"))
           try:
                assert len(number)==3

           except AssertionError:
               print("Must be 3 digit number.")
               studentID()

       except ValueError:
           print("Please enter an integer.")
           studentID()

       except TypeError:
           print("What is wrong with you?")
           studentID()

Body:
ints don't have a len.  You'll have to convert it back to a string to check its length.

def studentid():
    try:
        num = int(input('student ID:'))
        if len(str(num)) != 3:
            print('Please enter a 3-digit number')
            return studentid()
        return num
    except ValueError:
        print('Please enter a 3-digit number')
        return studentid()

You also probably want to return the num to the caller.  Note that we cast the input to an int then back into a string.  This is because in some recent versions of Python (3.6+), you can have underscores in int literals, so int('1_2') would be a valid 3 character input that evaluates to a 2 digit number