问:
Python Tkinter GUI program: SyntaxError: invalid syntax?
So I'm not new to python or programing in general, but am still learning with python. I am working on a program for me and some of my friends. and I was making the GUI, and code, for the login screen, when I kept getting this syntax error for one of my functions. And I have no idea as to what may be causing it. If someone could provide some assistance it would be greatly appreciated. p.s. I'll only be posting the part I've been having an error with, and only what is, or that I feel, is necessary to help show what's going on, and I'm using python 3.x if that helps.</p>

```<code># Login Setup
loginW = Tk()

# Password Authentication Function
def Authentication():

    valid = 'pythonprogramming'

    if (pwordE = valid):
        # Syntax Error for the above line
        mp = Tk()
        loginW.destroy()
        # Main Program here
        mp.mainloop()

    else:
        errorW = Tk()
        errorL = Label(errorW, text='Invalid Password!')

        errorW.mainloop()

pwordL = Label(loginW, text='Password: ')
pwordE = Entry(loginW, show='*')

logBtn = Button(loginW, text='Login')
logBtn.bind("<Button-1>", Authentication)

pwordL.pack(row=0)
pwordE.pack(row=0, column=1)
logBtn.pack(row=1, columnspan=2)

loginW.mainloop()
</code>```

答:
Your code has several errors:

Change pack to grid.

change pwordE = valid to pwordE.get() == valid

add argument event to Authentication function

complete code:

```<code># Login Setup
loginW = Tk()

# Password Authentication Function
def Authentication(event):

    valid = 'pythonprogramming'

    if pwordE.get() == valid:
        # Syntax Error for the above line
        mp = Tk()
        loginW.destroy()
        # Main Program here
        mp.mainloop()

    else:
        errorW = Tk()
        errorL = Label(errorW, text='Invalid Password!')
        errorL.grid(row=0, column=0)
        errorW.mainloop()

pwordL = Label(loginW, text='Password: ')
pwordE = Entry(loginW, show='*')

logBtn = Button(loginW, text='Login')
logBtn.bind("<Button-1>", Authentication)

pwordL.grid(row=0, column=0)
pwordE.grid(row=0, column=1)
logBtn.grid(row=1, columnspan=2)

loginW.mainloop()
</code>```

Screenshots:

Correct Password:

Incorrect Password:

Body:
So I'm not new to python or programing in general, but am still learning with python. I am working on a program for me and some of my friends. and I was making the GUI, and code, for the login screen, when I kept getting this syntax error for one of my functions. And I have no idea as to what may be causing it. If someone could provide some assistance it would be greatly appreciated. p.s. I'll only be posting the part I've been having an error with, and only what is, or that I feel, is necessary to help show what's going on, and I'm using python 3.x if that helps.

# Login Setup
loginW = Tk()

# Password Authentication Function
def Authentication():

    valid = 'pythonprogramming'

    if (pwordE = valid):
        # Syntax Error for the above line
        mp = Tk()
        loginW.destroy()
        # Main Program here
        mp.mainloop()

    else:
        errorW = Tk()
        errorL = Label(errorW, text='Invalid Password!')

        errorW.mainloop()

pwordL = Label(loginW, text='Password: ')
pwordE = Entry(loginW, show='*')

logBtn = Button(loginW, text='Login')
logBtn.bind("<Button-1>", Authentication)

pwordL.pack(row=0)
pwordE.pack(row=0, column=1)
logBtn.pack(row=1, columnspan=2)

loginW.mainloop()

Body:
Your code has several errors:

Change pack to grid.

change pwordE = valid to pwordE.get() == valid

add argument event to Authentication function

complete code:

# Login Setup
loginW = Tk()

# Password Authentication Function
def Authentication(event):

    valid = 'pythonprogramming'

    if pwordE.get() == valid:
        # Syntax Error for the above line
        mp = Tk()
        loginW.destroy()
        # Main Program here
        mp.mainloop()

    else:
        errorW = Tk()
        errorL = Label(errorW, text='Invalid Password!')
        errorL.grid(row=0, column=0)
        errorW.mainloop()

pwordL = Label(loginW, text='Password: ')
pwordE = Entry(loginW, show='*')

logBtn = Button(loginW, text='Login')
logBtn.bind("<Button-1>", Authentication)

pwordL.grid(row=0, column=0)
pwordE.grid(row=0, column=1)
logBtn.grid(row=1, columnspan=2)

loginW.mainloop()

Screenshots:

Correct Password:

Incorrect Password:


来源: stackexchange

问:
getting the last item in a javascript object
If I have an object like:

```<code>{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }
</code>```

If I don't know in advance that the list goes up to 'c', other than looping through the object, is there a way to get the last item in the object (e.g. 'carrot')?

答:
Use an array, not an object literal, if order matters.

```<code>const list = ['apple', 'banana', 'carrot'];
</code>```

Or something like

```<code>const dict = {
 'a' : ['apple', 'awesome'],
 'b' : ['best friend']
};
</code>```

Or even..

```<code>const dict = [{letter:'a', list:['apple', 'awesome']},
              {letter:'b', list:['best friend']}];
</code>```

The keys for dict are not guaranteed at all to be in order.

ContentLicense: CC BY-SA 2.5

Body:
If I have an object like:

{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }

If I don't know in advance that the list goes up to 'c', other than looping through the object, is there a way to get the last item in the object (e.g. 'carrot')?

Body:
Use an array, not an object literal, if order matters.

const list = ['apple', 'banana', 'carrot'];

Or something like

const dict = {
 'a' : ['apple', 'awesome'],
 'b' : ['best friend']
};

Or even..

const dict = [{letter:'a', list:['apple', 'awesome']},
              {letter:'b', list:['best friend']}];

The keys for dict are not guaranteed at all to be in order.

ContentLicense: CC BY-SA 4.0


问:
Undeclared identifier, in a node class
I have 2 files: Node.h, Node.cpp,

In Node.h, I create the prototype for the Node class. In the prototype I create a string array 'name'. In the Node.cpp class, I tried to use a function that gives 'name' a value, but i keep getting undeclared identifier even though i identified 'name' in Node.h

node.h

```<code>#include "iostream"
#include "string.h"
#include "stdafx.h"
#include "stdio.h"

template<class T>
class Node{

        char name[256];
        bool useable;

    public:
        //Constructors
        Node();
        Node(const T& item, Node<T>* ptrnext = NULL);

        T data;
        //Access to next Node
        Node<T>* nextNode();
        //List modification
        void insertAfter(Node<T>* p);
        Node<T>* deleteAfter();
        Node<T>* getNode(const T& item, Node<T>* nextptr = NULL);
        //Data Retrieval
        char *getName();
        void *setName(char[]);
        bool isUsable();

};
</code>```

node.cpp

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

//Default Constructor
template<class T>
Node<T>::Node(){

}

//This constructor sets the next pointer of a node and the data contained in that node
template<class T>
Node<T>::Node(const T& item,Node<T>* ptrnext){
    this->data = item;
    this->next = ptrnext;
}

//This method inserts a node after the current node
template<class T>
void Node<T>::insertAfter(Node<T> *p){
    //Links the rest of list to the Node<T>* p
    p->next = this->next;

    //Links the previous node to this one
   this-> next = p;
}

//This method deletes the current node from the list then returns it.
template<class T>
Node<T> * Node<T>::deleteAfter(){

    Node<T>* temp = next;

    if(next !=NULL){
        next = next->next;
    }

    return temp;
}

template<class T>
Node<T> * getNode(const T& item, Node<T>* nextptr = NULL){
    Node<T>* newnode; //Local pointer for new node
    newNode = new Node<T>(item,nextptr);
    if (newNode == NULL){
        printf("Error Allocating Memory");
        exit(1);
    }
    return newNode;

}

void setName(char input[256]){
    strncpy(name,input,sizeof(name));

}
</code>```

答:
I see three things immediately wrong with the following code.

```<code>void setName(char input[256]){
    strncpy(name,input,sizeof(name));
}
</code>```

You did not provide the class name.  This is therefore declaring a static function, and not a class member.  You also forgot to do this on your getNode function.

You left out the template statement.

You put a template implementation in a cpp file.  Be aware that you cannot compile the cpp file as an object -- it must be included in a header, or you can ditch the file altogether and move your implementation into your header.

ContentLicense: CC BY-SA 3.0

Title: Undeclared identifier, in a node class

Body:
I have 2 files: Node.h, Node.cpp,

In Node.h, I create the prototype for the Node class. In the prototype I create a string array 'name'. In the Node.cpp class, I tried to use a function that gives 'name' a value, but i keep getting undeclared identifier even though i identified 'name' in Node.h

node.h

#include "iostream"
#include "string.h"
#include "stdafx.h"
#include "stdio.h"

template<class T>
class Node{

        char name[256];
        bool useable;

    public:
        //Constructors
        Node();
        Node(const T& item, Node<T>* ptrnext = NULL);

        T data;
        //Access to next Node
        Node<T>* nextNode();
        //List modification
        void insertAfter(Node<T>* p);
        Node<T>* deleteAfter();
        Node<T>* getNode(const T& item, Node<T>* nextptr = NULL);
        //Data Retrieval
        char *getName();
        void *setName(char[]);
        bool isUsable();

};

node.cpp

#include "Node.h"

//Default Constructor
template<class T>
Node<T>::Node(){

}

//This constructor sets the next pointer of a node and the data contained in that node
template<class T>
Node<T>::Node(const T& item,Node<T>* ptrnext){
    this->data = item;
    this->next = ptrnext;
}

//This method inserts a node after the current node
template<class T>
void Node<T>::insertAfter(Node<T> *p){
    //Links the rest of list to the Node<T>* p
    p->next = this->next;

    //Links the previous node to this one
   this-> next = p;
}

//This method deletes the current node from the list then returns it.
template<class T>
Node<T> * Node<T>::deleteAfter(){

    Node<T>* temp = next;

    if(next !=NULL){
        next = next->next;
    }

    return temp;
}

template<class T>
Node<T> * getNode(const T& item, Node<T>* nextptr = NULL){
    Node<T>* newnode; //Local pointer for new node
    newNode = new Node<T>(item,nextptr);
    if (newNode == NULL){
        printf("Error Allocating Memory");
        exit(1);
    }
    return newNode;

}

void setName(char input[256]){
    strncpy(name,input,sizeof(name));

}

Body:
I see three things immediately wrong with the following code.

void setName(char input[256]){
    strncpy(name,input,sizeof(name));
}

You did not provide the class name.  This is therefore declaring a static function, and not a class member.  You also forgot to do this on your getNode function.

You left out the template statement.

You put a template implementation in a cpp file.  Be aware that you cannot compile the cpp file as an object -- it must be included in a header, or you can ditch the file altogether and move your implementation into your header.


问:
Creating a dictionary schema with Mongoose
I am trying to store a dictionary of objects using Mongoose. Realizing that I lose the change detection for saving with using the Mixed type, I was hoping I could create a schema that would not require the Mixed type.

There are plenty of examples of creating schemas for arrays of objects, but not dictionaries of objects. Is it possible to do this?

Format:

```<code>{
    ObjectId : {
        "attempts" : {
            "response" : String,
            "timestamp" : Date
        },
        "complete" : Boolean
    }
}
</code>```

答:
You can have your dictionary like this with meta being a dictionary:

```<code>var UserSchema = new Schema({
  meta: {
    votes: Number,
    favs:  Number
  }
  first_name:  String,
  last_name: String,
  profile_pic:   String,
  gender: String,
  timezone: Number
  date: { type: Date, default: Date.now },
  updated: { type: Date, default: Date.now },
  country: {id: Number, name: String}

});
</code>```

Body:
I am trying to store a dictionary of objects using Mongoose. Realizing that I lose the change detection for saving with using the Mixed type, I was hoping I could create a schema that would not require the Mixed type.

There are plenty of examples of creating schemas for arrays of objects, but not dictionaries of objects. Is it possible to do this?

Format:

{
    ObjectId : {
        "attempts" : {
            "response" : String,
            "timestamp" : Date
        },
        "complete" : Boolean
    }
}

Body:
You can have your dictionary like this with meta being a dictionary:

var UserSchema = new Schema({
  meta: {
    votes: Number,
    favs:  Number
  }
  first_name:  String,
  last_name: String,
  profile_pic:   String,
  gender: String,
  timezone: Number
  date: { type: Date, default: Date.now },
  updated: { type: Date, default: Date.now },
  country: {id: Number, name: String}

});


问:
Unable to Set Initializer for Custom UICollectionView Cell Class
I am trying to set an initializer for a custom UICollectionViewCell class and I am receiving an error. I am new to Swift and understand that a model class must have a relevant initializer in order to use items from the class. Here is my code and the error I am receiving:

答:
you need to include the initializer for NSCoder:

```<code>public required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    // do something here if you need ...
}
</code>```

That should fix it for you.

Body:
you need to include the initializer for NSCoder:

public required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    // do something here if you need ...
}

That should fix it for you.


问:
Python statsmodel.tsa.MarkovAutoregression using current real GNP/GDP data
I have been using statsmodel.tsa.MarkovAutoregressio to replicate Hamilton's markov switching model published in 1989. If using the Hamilton data (real GNP in 1982 dollar) I could have the same result as the code example / the paper showed. However, when I used current available real GNP or GDP data (in 2009 dollar) and took their log difference (quarterly) as input, the model doesn't give satisfactory results.

I plotted the log difference of Hamilton gnp and that's from the current available real GNP. They are quite close with slight differences.

Can anyone enlighten me why it is the case? Does it have anything to do with the seasonality adjustment of current GNP data? If so, is there is any way to counter it?

Result using current available GNP

Result using paper provided GNP

答:
You write:

the model doesn't give satisfactory results.

But what you mean is that the model isn't giving you the results you expect / want. i.e., you want the model to pick out periods the NBER has labeled as "Recessions", but the Markov switching model is simply finding the parameters which maximize the likelihood function for the data.

(The rest of the post shows results that are taken from this Jupyter notebook: http://nbviewer.jupyter.org/gist/ChadFulton/a5d24d32ba3b7b2e381e43a232342f1f)

(I'll also note that I double-checked these results using E-views, and it agrees with Statsmodels' output almost exactly).

The raw dataset is the growth rate (log difference * 100) of real GNP; the Hamilton dataset versus one found on the Federal Reserve Economic Database are shown here, with grey bars indicating NBER-dated recessions:

In this case, the model is an AR(4) on the growth rate of real GNP, with a regime-specific intercept; the model allows two regimes. The idea is that "recessions" should correspond to a low (or negative) average growth rate and expansions should correspond to a higher average growth rate.

Model 1: Hamilton's dataset: Maximum likelihood estimation of parameters

From the model applied to Hamilton's (1989) dataset, we get the following estimated parameters:

```<code>                         Markov Switching Model Results
================================================================================
Dep. Variable:                 Hamilton   No. Observations:                  131
Model:             MarkovAutoregression   Log Likelihood                -181.263
Date:                  Sun, 02 Apr 2017   AIC                            380.527
Time:                          19:52:31   BIC                            406.404
Sample:                      04-01-1951   HQIC                           391.042
                           - 10-01-1984
Covariance Type:                 approx
                             Regime 0 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         -0.3588      0.265     -1.356      0.175      -0.877       0.160
                             Regime 1 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const          1.1635      0.075     15.614      0.000       1.017       1.310
                           Non-switching parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
sigma2         0.5914      0.103      5.761      0.000       0.390       0.793
ar.L1          0.0135      0.120      0.112      0.911      -0.222       0.249
ar.L2         -0.0575      0.138     -0.418      0.676      -0.327       0.212
ar.L3         -0.2470      0.107     -2.310      0.021      -0.457      -0.037
ar.L4         -0.2129      0.111     -1.926      0.054      -0.430       0.004
                         Regime transition parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
p[0->0]        0.7547      0.097      7.819      0.000       0.565       0.944
p[1->0]        0.0959      0.038      2.542      0.011       0.022       0.170
==============================================================================
</code>```

and the time series of the probability of operating in regime 0 (which here corresponds to a negative growth rate, i.e. a recession) looks like:

Model 2: Updated dataset: Maximum likelihood estimation of parameters

Now, as you saw, we can instead fit the model using the "updated" dataset (which looks pretty much like the original dataset), to get the following parameters and regime probabilities:

```<code>                         Markov Switching Model Results
================================================================================
Dep. Variable:                   GNPC96   No. Observations:                  131
Model:             MarkovAutoregression   Log Likelihood                -188.002
Date:                  Sun, 02 Apr 2017   AIC                            394.005
Time:                          20:00:58   BIC                            419.882
Sample:                      04-01-1951   HQIC                           404.520
                           - 10-01-1984
Covariance Type:                 approx
                             Regime 0 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         -1.2475      3.470     -0.359      0.719      -8.049       5.554
                             Regime 1 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const          0.9364      0.453      2.066      0.039       0.048       1.825
                           Non-switching parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
sigma2         0.8509      0.561      1.516      0.130      -0.249       1.951
ar.L1          0.3437      0.189      1.821      0.069      -0.026       0.714
ar.L2          0.0919      0.143      0.645      0.519      -0.187       0.371
ar.L3         -0.0846      0.251     -0.337      0.736      -0.577       0.408
ar.L4         -0.1727      0.258     -0.669      0.503      -0.678       0.333
                         Regime transition parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
p[0->0]        0.0002      1.705      0.000      1.000      -3.341       3.341
p[1->0]        0.0397      0.186      0.213      0.831      -0.326       0.405
==============================================================================
</code>```

To understand what the model is doing, look at the intercepts in the two regimes. In Hamilton's model, the "low" regime has an intercept of -0.35, whereas with the updated data, the "low" regime has an intercept of -1.25.

What that tells us is that with the updated dataset, the model is doing a "better job" fitting the data (in terms of a higher likelihood) by choosing the "low" regime to be much deeper recessions. In particular, looking back at the GNP data series, it's apparent that it's using the "low" regime to fit the very low growth in the late 1950's and early 1980's.

In contrast, the fitted parameters from Hamilton's model allow the "low" regime to fit "moderately low" growth rates that cover a wider range of recessions.

We can't compare these two models' outcomes using e.g. the log-likelihood values because they're using different datasets. One thing we could try, though is to use the fitted parameters from Hamilton's dataset on the updated GNP data. Doing that, we get the following result:

Model 3: Updated dataset using parameters estimated on Hamilton's dataset

```<code>                         Markov Switching Model Results
================================================================================
Dep. Variable:                   GNPC96   No. Observations:                  131
Model:             MarkovAutoregression   Log Likelihood                -191.807
Date:                  Sun, 02 Apr 2017   AIC                            401.614
Time:                          19:52:52   BIC                            427.491
Sample:                      04-01-1951   HQIC                           412.129
                           - 10-01-1984
Covariance Type:                    opg
                             Regime 0 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         -0.3588      0.185     -1.939      0.053      -0.722       0.004
                             Regime 1 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const          1.1635      0.083     13.967      0.000       1.000       1.327
                           Non-switching parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
sigma2         0.5914      0.090      6.604      0.000       0.416       0.767
ar.L1          0.0135      0.100      0.134      0.893      -0.183       0.210
ar.L2         -0.0575      0.088     -0.651      0.515      -0.231       0.116
ar.L3         -0.2470      0.104     -2.384      0.017      -0.450      -0.044
ar.L4         -0.2129      0.084     -2.524      0.012      -0.378      -0.048
                         Regime transition parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
p[0->0]        0.7547      0.100      7.563      0.000       0.559       0.950
p[1->0]        0.0959      0.051      1.872      0.061      -0.005       0.196
==============================================================================
</code>```

This looks more like what you expected / wanted, and that's because as I mentioned above, the "low" regime intercept of 0.35 makes the "low" regime a good fit for more time periods in the sample. But notice that the log-likelihood here is -191.8, whereas in Model 2 the log-likelihood was -188.0.

Thus even though this model looks more like what you wanted, it does not fit the data as well.

(Note again that you can't compare these log-likelihoods to the -181.3 from Model 1, because that is using a different dataset).

Body:
You write:

the model doesn't give satisfactory results.

But what you mean is that the model isn't giving you the results you expect / want. i.e., you want the model to pick out periods the NBER has labeled as "Recessions", but the Markov switching model is simply finding the parameters which maximize the likelihood function for the data.

(The rest of the post shows results that are taken from this Jupyter notebook: http://nbviewer.jupyter.org/gist/ChadFulton/a5d24d32ba3b7b2e381e43a232342f1f)

(I'll also note that I double-checked these results using E-views, and it agrees with Statsmodels' output almost exactly).

The raw dataset is the growth rate (log difference * 100) of real GNP; the Hamilton dataset versus one found on the Federal Reserve Economic Database are shown here, with grey bars indicating NBER-dated recessions:

In this case, the model is an AR(4) on the growth rate of real GNP, with a regime-specific intercept; the model allows two regimes. The idea is that "recessions" should correspond to a low (or negative) average growth rate and expansions should correspond to a higher average growth rate.

Model 1: Hamilton's dataset: Maximum likelihood estimation of parameters

From the model applied to Hamilton's (1989) dataset, we get the following estimated parameters:

                         Markov Switching Model Results
================================================================================
Dep. Variable:                 Hamilton   No. Observations:                  131
Model:             MarkovAutoregression   Log Likelihood                -181.263
Date:                  Sun, 02 Apr 2017   AIC                            380.527
Time:                          19:52:31   BIC                            406.404
Sample:                      04-01-1951   HQIC                           391.042
                           - 10-01-1984
Covariance Type:                 approx
                             Regime 0 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         -0.3588      0.265     -1.356      0.175      -0.877       0.160
                             Regime 1 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const          1.1635      0.075     15.614      0.000       1.017       1.310
                           Non-switching parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
sigma2         0.5914      0.103      5.761      0.000       0.390       0.793
ar.L1          0.0135      0.120      0.112      0.911      -0.222       0.249
ar.L2         -0.0575      0.138     -0.418      0.676      -0.327       0.212
ar.L3         -0.2470      0.107     -2.310      0.021      -0.457      -0.037
ar.L4         -0.2129      0.111     -1.926      0.054      -0.430       0.004
                         Regime transition parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
p[0->0]        0.7547      0.097      7.819      0.000       0.565       0.944
p[1->0]        0.0959      0.038      2.542      0.011       0.022       0.170
==============================================================================

and the time series of the probability of operating in regime 0 (which here corresponds to a negative growth rate, i.e. a recession) looks like:

Model 2: Updated dataset: Maximum likelihood estimation of parameters

Now, as you saw, we can instead fit the model using the "updated" dataset (which looks pretty much like the original dataset), to get the following parameters and regime probabilities:

                         Markov Switching Model Results
================================================================================
Dep. Variable:                   GNPC96   No. Observations:                  131
Model:             MarkovAutoregression   Log Likelihood                -188.002
Date:                  Sun, 02 Apr 2017   AIC                            394.005
Time:                          20:00:58   BIC                            419.882
Sample:                      04-01-1951   HQIC                           404.520
                           - 10-01-1984
Covariance Type:                 approx
                             Regime 0 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         -1.2475      3.470     -0.359      0.719      -8.049       5.554
                             Regime 1 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const          0.9364      0.453      2.066      0.039       0.048       1.825
                           Non-switching parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
sigma2         0.8509      0.561      1.516      0.130      -0.249       1.951
ar.L1          0.3437      0.189      1.821      0.069      -0.026       0.714
ar.L2          0.0919      0.143      0.645      0.519      -0.187       0.371
ar.L3         -0.0846      0.251     -0.337      0.736      -0.577       0.408
ar.L4         -0.1727      0.258     -0.669      0.503      -0.678       0.333
                         Regime transition parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
p[0->0]        0.0002      1.705      0.000      1.000      -3.341       3.341
p[1->0]        0.0397      0.186      0.213      0.831      -0.326       0.405
==============================================================================

To understand what the model is doing, look at the intercepts in the two regimes. In Hamilton's model, the "low" regime has an intercept of -0.35, whereas with the updated data, the "low" regime has an intercept of -1.25.

What that tells us is that with the updated dataset, the model is doing a "better job" fitting the data (in terms of a higher likelihood) by choosing the "low" regime to be much deeper recessions. In particular, looking back at the GNP data series, it's apparent that it's using the "low" regime to fit the very low growth in the late 1950's and early 1980's.

In contrast, the fitted parameters from Hamilton's model allow the "low" regime to fit "moderately low" growth rates that cover a wider range of recessions.

We can't compare these two models' outcomes using e.g. the log-likelihood values because they're using different datasets. One thing we could try, though is to use the fitted parameters from Hamilton's dataset on the updated GNP data. Doing that, we get the following result:

Model 3: Updated dataset using parameters estimated on Hamilton's dataset

                         Markov Switching Model Results
================================================================================
Dep. Variable:                   GNPC96   No. Observations:                  131
Model:             MarkovAutoregression   Log Likelihood                -191.807
Date:                  Sun, 02 Apr 2017   AIC                            401.614
Time:                          19:52:52   BIC                            427.491
Sample:                      04-01-1951   HQIC                           412.129
                           - 10-01-1984
Covariance Type:                    opg
                             Regime 0 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const         -0.3588      0.185     -1.939      0.053      -0.722       0.004
                             Regime 1 parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
const          1.1635      0.083     13.967      0.000       1.000       1.327
                           Non-switching parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
sigma2         0.5914      0.090      6.604      0.000       0.416       0.767
ar.L1          0.0135      0.100      0.134      0.893      -0.183       0.210
ar.L2         -0.0575      0.088     -0.651      0.515      -0.231       0.116
ar.L3         -0.2470      0.104     -2.384      0.017      -0.450      -0.044
ar.L4         -0.2129      0.084     -2.524      0.012      -0.378      -0.048
                         Regime transition parameters
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
p[0->0]        0.7547      0.100      7.563      0.000       0.559       0.950
p[1->0]        0.0959      0.051      1.872      0.061      -0.005       0.196
==============================================================================

This looks more like what you expected / wanted, and that's because as I mentioned above, the "low" regime intercept of 0.35 makes the "low" regime a good fit for more time periods in the sample. But notice that the log-likelihood here is -191.8, whereas in Model 2 the log-likelihood was -188.0.

Thus even though this model looks more like what you wanted, it does not fit the data as well.

(Note again that you can't compare these log-likelihoods to the -181.3 from Model 1, because that is using a different dataset).


问:
Existing Xcode/Swift3 App Suddenly Does Not Recognize Parse Framework
I have an app that has been published to the App Store for almost a year now.  The app has been using parse framework (not installed with cocoapods) all this time and works fine.

I recently opened the existing project for this app in Xcode after a few weeks of working on a different project (new project does not use parse and is not related to existing app in any way) and suddenly the project has an error "No such module 'Parse'"

I have read every thread on stackoverflow, GitHub, and other random places related to this topic.  I have tried every suggestion I have found in these resources and nothing is fixing the error.

I have done the following:

deleted all derived data, quit Xcode, reopened project & cleaned

adjust the search framework paths in the target build settings (tried this about a dozen times)

deleted the parse framework and added back, cleaned project

I would be eternally grateful for any assistance in resolving this error.  I've spent over 2 weeks trying to resolve.

答:
I have FINALLY resolved this issue.

root cause:  the framework files that are referenced within the project were originally stored on my desktop.  I recently cleaned my desktop and deleted files I thought I didn't need anymore...wrong!  the parse framework files were there and moved/deleted.

fix:  for me, I needed to get the original files back so I was able to reinstall the framework files by getting them from the original location I got them (pulled them in from a parse starter project I downloaded from GitHub).  bottom line is that I needed to reinstate the framework files.

the frameworks should have the suitcase icon as shown below:

if the suitcase icon is not there then the frameworks are not installed correctly.


问:
In general, does replacing AND with a pair of nested IFs speed things up?
I'm weighing the differences between

```<code>If[condition1 AND condition2, A, B]
</code>```

and

```<code>If[condition1, If[condition2, A, B], B]
</code>```

My thinking: the nested IFs will be faster.

My reasoning: By nesting the IFs, condition2 is evaluated only when condition1 is true. In what I'm doing, that means condition2 will be evaluated fewer times than in the first option above.

AND is the usual logical "and" (true if and only if both premises are true). By IF, I mean IF[condition, when condition is true, when condition is false].

I hope my question is not too ill-posed; I'm sure there are examples where the first option will run faster. I was just hoping that something is true in general.

Thank you.

答:
Are you asking about a specific language or just in general?

Many, but not all, languages have short circuit AND and ORoperators where they stop evaluation when they know the answer. For AND that means if the left side if false the answer is false and the right side does not need to be evaluated. For OR if the left side is true, then the answer is true and the rights side does not need to be evaluated.

For languages without short circute evaluation, you may get some speed improvement with nested ifs, because less work will have to be done. Whether that improvement is worth making the code harder to follow will depend on the situation.

Body:
I'm weighing the differences between

If[condition1 AND condition2, A, B]

and

If[condition1, If[condition2, A, B], B]

My thinking: the nested IFs will be faster.

My reasoning: By nesting the IFs, condition2 is evaluated only when condition1 is true. In what I'm doing, that means condition2 will be evaluated fewer times than in the first option above.

AND is the usual logical "and" (true if and only if both premises are true). By IF, I mean IF[condition, when condition is true, when condition is false].

I hope my question is not too ill-posed; I'm sure there are examples where the first option will run faster. I was just hoping that something is true in general.

Thank you.


问:
Run different liquibase scripts based on SQL Server version
I am trying to use liquibase to add members to a role, but the SQL is different from SQL Server 2008 to 2012.

SQL Server 2008:

```<code>exec sp_addrolemember db_datareader, MYUSER
</code>```

SQL Server 2012:

```<code>ALTER ROLE db_datawriter ADD MEMBER MYUSER
</code>```

The following SQL when run via liquibase against SQL Server 2012 works correctly, but when ran against SQL Server 2008 it fails and says:

Incorrect syntax near the keyword 'ADD'

Code:

```<code>DECLARE @ver nvarchar(50),
        @intVer int,
        @ver2008 int = 10

SET @ver = CAST(serverproperty('ProductVersion') AS nvarchar)
SET @intVer = CAST(SUBSTRING(@ver, 1, CHARINDEX('.', @ver) - 1) AS int)

IF (@intVer = @ver2008)
    exec sp_addrolemember db_datawriter, MYUSER
ELSE
    ALTER ROLE db_datawriter ADD MEMBER MYUSER;
</code>```

I tried separating the versions, putting SQL Server 2008 in one file and 2012 in another and using a 'precondition' at the top of the changelog (outside of a changeset). But there are only 2 OnFail options, HALT, which stops the entire update, or WARN, which just continues the script, both of which do not give me what I need.

I need to be able for the script to figure out which version of SQL Server it is working with and only run that particular liquibase script, whether it be a changeset or changelog.

答:
The compilation of the entire batch will fail if the syntax is unrecognized. You can work around the issue by wrapping the statements in EXECUTE or by using sp_executesql.</p>

```<code>IF (@intVer = @ver2008)
    EXECUTE(N'exec sp_addrolemember db_datawriter, MYUSER;')
ELSE
    EXECUTE(N'ALTER ROLE db_datawriter ADD MEMBER MYUSER;');
</code>```

Body:
I am trying to use liquibase to add members to a role, but the SQL is different from SQL Server 2008 to 2012.

SQL Server 2008:

exec sp_addrolemember db_datareader, MYUSER

SQL Server 2012:

ALTER ROLE db_datawriter ADD MEMBER MYUSER

The following SQL when run via liquibase against SQL Server 2012 works correctly, but when ran against SQL Server 2008 it fails and says:

Incorrect syntax near the keyword 'ADD'

Code:

DECLARE @ver nvarchar(50),
        @intVer int,
        @ver2008 int = 10

SET @ver = CAST(serverproperty('ProductVersion') AS nvarchar)
SET @intVer = CAST(SUBSTRING(@ver, 1, CHARINDEX('.', @ver) - 1) AS int)

IF (@intVer = @ver2008)
    exec sp_addrolemember db_datawriter, MYUSER
ELSE
    ALTER ROLE db_datawriter ADD MEMBER MYUSER;

I tried separating the versions, putting SQL Server 2008 in one file and 2012 in another and using a 'precondition' at the top of the changelog (outside of a changeset). But there are only 2 OnFail options, HALT, which stops the entire update, or WARN, which just continues the script, both of which do not give me what I need.

I need to be able for the script to figure out which version of SQL Server it is working with and only run that particular liquibase script, whether it be a changeset or changelog.

Body:
The compilation of the entire batch will fail if the syntax is unrecognized. You can work around the issue by wrapping the statements in EXECUTE or by using sp_executesql.

IF (@intVer = @ver2008)
    EXECUTE(N'exec sp_addrolemember db_datawriter, MYUSER;')
ELSE
    EXECUTE(N'ALTER ROLE db_datawriter ADD MEMBER MYUSER;');


问:
C# Problems importing a file to an array and put each character in it's own index
I have a problem importing a text file to an array and put each character in it's own index?
Here is my code:

```<code> class Program
{
    static void Main(string[] args)
    {
        string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        Console.WriteLine(content);
        // Loop through array.
        for (int i = 0; i < array.Length; i++)
        {
            // Get character from array.
            char letter = array[i];
            // Display each letter.
            Console.Write("Letter: " + letter);
           // Console.WriteLine(letter);
        }
    }
}
</code>```

The problem is it only display some of the characters? Now if I change the code a little to this:

```<code>class Program
{
    static void Main(string[] args)
    {
        string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        Console.WriteLine(content);
        // Loop through array.
        for (int i = 0; i < array.Length; i++)
        {
            // Get character from array.
            char letter = array[i];
            // Display each letter.
            Console.Write("Letter: " + letter);
            //Console.WriteLine(letter);
        }
    }
}
</code>```

Then it display all the charaters in the array, but when I try to find out what index each character are in and add the 'i' to this code  Console.Write("Letter: " + letter); so the code looks like this:

```<code> class Program
{
    static void Main(string[] args)
    {
        string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        Console.WriteLine(content);
        // Loop through array.
        for (int i = 0; i < array.Length; i++)
        {
            // Get character from array.
            char letter = array[i];
            // Display each letter.
            Console.Write(" Letter: " + letter + "  " + i);
            //Console.WriteLine(letter);
        }
    }
}
</code>```

The result go crazy and look like this:
Output Vindue
The text file is the one below, and I placed it in the debug folder in my project so I didn't had to provide a path.

TextFile

答:
I tried the following code and it seems to work, if this still doesn't work it's likely you're using the wrong encoding type and the file has a different encoding than UTF-8.

If that is the case then open the file in an editor like Notepad++ and see what the encoding for the file is

EDIT
The reason it looks like it was starting at line 191 instead of 0 was you were exceeding the buffer height of the console, so below I've added code to set the buffer height to it's maximum. depending on the application you might want to use a smaller value.

```<code>class Program{
    static void Main(string[] args){
        //Increase Console Buffer Height
        Console.BufferHeight = Int16.MaxValue - 1;
        string content = File.ReadAllText(@"Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        // Loop through array
        for (int i =0; i<array.Length; i++) {
            string letter = arrray[i].ToString()
                .Replace("\r","\\r").Replace("\n", "\\n")
                .Replace("\t","\\t").Replace(" ","<space>");
            // Display each letter
            Console.WriteLine("Letter {0}: {1}", i, letter);
        }
        Console.ReadLine();
    }
}
</code>```

Body:
I have a problem importing a text file to an array and put each character in it's own index?
Here is my code:

 class Program
{
    static void Main(string[] args)
    {
        string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        Console.WriteLine(content);
        // Loop through array.
        for (int i = 0; i < array.Length; i++)
        {
            // Get character from array.
            char letter = array[i];
            // Display each letter.
            Console.Write("Letter: " + letter);
           // Console.WriteLine(letter);
        }
    }
}

The problem is it only display some of the characters? Now if I change the code a little to this:

class Program
{
    static void Main(string[] args)
    {
        string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        Console.WriteLine(content);
        // Loop through array.
        for (int i = 0; i < array.Length; i++)
        {
            // Get character from array.
            char letter = array[i];
            // Display each letter.
            Console.Write("Letter: " + letter);
            //Console.WriteLine(letter);
        }
    }
}

Then it display all the charaters in the array, but when I try to find out what index each character are in and add the 'i' to this code  Console.Write("Letter: " + letter); so the code looks like this:

 class Program
{
    static void Main(string[] args)
    {
        string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        Console.WriteLine(content);
        // Loop through array.
        for (int i = 0; i < array.Length; i++)
        {
            // Get character from array.
            char letter = array[i];
            // Display each letter.
            Console.Write(" Letter: " + letter + "  " + i);
            //Console.WriteLine(letter);
        }
    }
}

The result go crazy and look like this:
Output Vindue
The text file is the one below, and I placed it in the debug folder in my project so I didn't had to provide a path.

TextFile

Body:
I tried the following code and it seems to work, if this still doesn't work it's likely you're using the wrong encoding type and the file has a different encoding than UTF-8.

If that is the case then open the file in an editor like Notepad++ and see what the encoding for the file is

EDIT
The reason it looks like it was starting at line 191 instead of 0 was you were exceeding the buffer height of the console, so below I've added code to set the buffer height to it's maximum. depending on the application you might want to use a smaller value.

class Program{
    static void Main(string[] args){
        //Increase Console Buffer Height
        Console.BufferHeight = Int16.MaxValue - 1;
        string content = File.ReadAllText(@"Labyrint.txt", Encoding.UTF8);

        // Use ToCharArray to convert string to array.
        char[] array = content.ToCharArray();

        // Loop through array
        for (int i =0; i<array.Length; i++) {
            string letter = arrray[i].ToString()
                .Replace("\r","\\r").Replace("\n", "\\n")
                .Replace("\t","\\t").Replace(" ","<space>");
            // Display each letter
            Console.WriteLine("Letter {0}: {1}", i, letter);
        }
        Console.ReadLine();
    }
}


问:
What's wrong? I can't seem to close this code out
I cant figure out how to close this out properly, no matter where i add a bracket it breaks the code.
I appreciate the help, thanks :)

```<code>            int NewID = Convert.ToInt32(Adapter.InsertQuery()); // new relationship id
            if (!Session.GetHabbo().Relationships.ContainsKey(Them))
                Session.GetHabbo().Relationships.Add(Them, new Relationship(NewID, Them, 3)); // create the relationship

            Session.GetHabbo().GetMessenger().UpdateFriend(Them, Session, true);
        }

        else

          {
            Habbo Habbo = PlusEnvironment.GetHabboById(Them);
            if (Habbo != null)
            {
                MessengerBuddy Bud = null;
                if (Session.GetHabbo().GetMessenger().TryGetFriend(Them, out Bud))
                    Session.SendMessage(new FriendListUpdateComposer(Session, Bud));
            }
        }
        return false;
    }
</code>```

P.S I'm still new to this.

答:
This seems like a simple fix, but if you format your code this sort of stuff usually sticks out. In Visual Studio you can hit Ctrl+K, Ctrl+D (in succession) and it'll format your code to the default.

```<code>int NewID = Convert.ToInt32(Adapter.InsertQuery()); // new relationship id
if (!Session.GetHabbo().Relationships.ContainsKey(Them))
    Session.GetHabbo().Relationships.Add(Them, new Relationship(NewID, Them, 3)); // create the relationship

    Session.GetHabbo().GetMessenger().UpdateFriend(Them, Session, true);
}
else
{
    Habbo Habbo = PlusEnvironment.GetHabboById(Them);
    if (Habbo != null)
    {
        MessengerBuddy Bud = null;
        if (Session.GetHabbo().GetMessenger().TryGetFriend(Them, out Bud))
            Session.SendMessage(new FriendListUpdateComposer(Session, Bud));
        }
    }
    return false;
}
</code>```

Alright. Now that that's done. You're, in general, missing your beginning brackets on your if-statements.

```<code>int NewID = Convert.ToInt32(Adapter.InsertQuery()); // new relationship id
if (!Session.GetHabbo().Relationships.ContainsKey(Them))
{ // Added here
    Session.GetHabbo().Relationships.Add(Them, new Relationship(NewID, Them, 3)); // create the relationship

    Session.GetHabbo().GetMessenger().UpdateFriend(Them, Session, true);
}
else
{
    Habbo Habbo = PlusEnvironment.GetHabboById(Them);
    if (Habbo != null)
    {
        MessengerBuddy Bud = null;
        if (Session.GetHabbo().GetMessenger().TryGetFriend(Them, out Bud))
        { // Added here.
            Session.SendMessage(new FriendListUpdateComposer(Session, Bud));
        }
    }
    return false;
}
</code>```

So if you add those two brackets noted by the // Added here comments, that should work.

Body:
I cant figure out how to close this out properly, no matter where i add a bracket it breaks the code.
I appreciate the help, thanks :)

            int NewID = Convert.ToInt32(Adapter.InsertQuery()); // new relationship id
            if (!Session.GetHabbo().Relationships.ContainsKey(Them))
                Session.GetHabbo().Relationships.Add(Them, new Relationship(NewID, Them, 3)); // create the relationship

            Session.GetHabbo().GetMessenger().UpdateFriend(Them, Session, true);
        }

        else

          {
            Habbo Habbo = PlusEnvironment.GetHabboById(Them);
            if (Habbo != null)
            {
                MessengerBuddy Bud = null;
                if (Session.GetHabbo().GetMessenger().TryGetFriend(Them, out Bud))
                    Session.SendMessage(new FriendListUpdateComposer(Session, Bud));
            }
        }
        return false;
    }

P.S I'm still new to this.

Body:
This seems like a simple fix, but if you format your code this sort of stuff usually sticks out. In Visual Studio you can hit Ctrl+K, Ctrl+D (in succession) and it'll format your code to the default.

int NewID = Convert.ToInt32(Adapter.InsertQuery()); // new relationship id
if (!Session.GetHabbo().Relationships.ContainsKey(Them))
    Session.GetHabbo().Relationships.Add(Them, new Relationship(NewID, Them, 3)); // create the relationship

    Session.GetHabbo().GetMessenger().UpdateFriend(Them, Session, true);
}
else
{
    Habbo Habbo = PlusEnvironment.GetHabboById(Them);
    if (Habbo != null)
    {
        MessengerBuddy Bud = null;
        if (Session.GetHabbo().GetMessenger().TryGetFriend(Them, out Bud))
            Session.SendMessage(new FriendListUpdateComposer(Session, Bud));
        }
    }
    return false;
}

Alright. Now that that's done. You're, in general, missing your beginning brackets on your if-statements.

int NewID = Convert.ToInt32(Adapter.InsertQuery()); // new relationship id
if (!Session.GetHabbo().Relationships.ContainsKey(Them))
{ // Added here
    Session.GetHabbo().Relationships.Add(Them, new Relationship(NewID, Them, 3)); // create the relationship

    Session.GetHabbo().GetMessenger().UpdateFriend(Them, Session, true);
}
else
{
    Habbo Habbo = PlusEnvironment.GetHabboById(Them);
    if (Habbo != null)
    {
        MessengerBuddy Bud = null;
        if (Session.GetHabbo().GetMessenger().TryGetFriend(Them, out Bud))
        { // Added here.
            Session.SendMessage(new FriendListUpdateComposer(Session, Bud));
        }
    }
    return false;
}

So if you add those two brackets noted by the // Added here comments, that should work.


问:
Create DOM hierarchically
I have a list of keys and values and I intend to create an xml based on this information.

My list return:

```<code>1 person
2 information
3 name
3 surname
2 address
3 street
3 country
</code>```

And I want to generate an xml:

```<code><xml>
    <person>
        <information>
            <name></name>
            <surname></surname>
        </information>
        <address>
            <street></street>
            <country></country>
        </address>
    </person>
</xml>
</code>```

I have a list of elements, while traversing these elements would create the xml document hierarchically. I already have this code:

```<code>var elements = document.getElementsByClassName('elements');
var xml = document.createElement('xml');

for (var i = 0; i < elements.length; i++) {
    var key = elements[i].getAttribute('data-key');
    var value = elements[i].getAttribute('data-value');

    console.log(key +' -> '+ value);

    // HERE: create new elements appendChild "var xml"
}
</code>```

答:
Note: this is untested and I need to step away. But, this should give you a starting point with comments.</p>

```<code>var elements = document.getElementsByClassName('elements');
var xml = document.createElement('xml');
var curElem = xml;
var curDepth = 0;

for (var i = 0; i < elements.length; i++) {
    var key = elements[i].getAttribute('data-key');
    var value = elements[i].getAttribute('data-value');

    console.log(key +' -> '+ value);

    // HERE: create new elements appendChild "var xml"

    // Create the new element
    var elem = document.createElement(value);

    // If we are further down the hierarchy, simply add the child
    if (key > curDepth) {
        curElem.appendChild(elem);
    } else if (key == curDepth) {
        // We are a sibling of our current containing element
        // so simply add to the parent
        curElem.parentElement.appendChild(elem);
        curElem = elem;
    } else if (key < curDepth) {
        // We are at some point ABOVE our current element
        // so start walking UP until we reach the level indicated
        // and then add the element to the parent
        while (curDepth >= key) {
            curElem = curElem.parentElement;
            curDepth--;
        }
        curElem.parentElement.appendChild(elem);
    }
    curElem = elem;
    curDepth = key;
}
</code>```

Title: Create DOM hierarchically

Body:
I have a list of keys and values and I intend to create an xml based on this information.

My list return:

1 person
2 information
3 name
3 surname
2 address
3 street
3 country

And I want to generate an xml:

<xml>
    <person>
        <information>
            <name></name>
            <surname></surname>
        </information>
        <address>
            <street></street>
            <country></country>
        </address>
    </person>
</xml>

I have a list of elements, while traversing these elements would create the xml document hierarchically. I already have this code:

var elements = document.getElementsByClassName('elements');
var xml = document.createElement('xml');

for (var i = 0; i < elements.length; i++) {
    var key = elements[i].getAttribute('data-key');
    var value = elements[i].getAttribute('data-value');

    console.log(key +' -> '+ value);

    // HERE: create new elements appendChild "var xml"
}

Body:
Note: this is untested and I need to step away. But, this should give you a starting point with comments.

var elements = document.getElementsByClassName('elements');
var xml = document.createElement('xml');
var curElem = xml;
var curDepth = 0;

for (var i = 0; i < elements.length; i++) {
    var key = elements[i].getAttribute('data-key');
    var value = elements[i].getAttribute('data-value');

    console.log(key +' -> '+ value);

    // HERE: create new elements appendChild "var xml"

    // Create the new element
    var elem = document.createElement(value);

    // If we are further down the hierarchy, simply add the child
    if (key > curDepth) {
        curElem.appendChild(elem);
    } else if (key == curDepth) {
        // We are a sibling of our current containing element
        // so simply add to the parent
        curElem.parentElement.appendChild(elem);
        curElem = elem;
    } else if (key < curDepth) {
        // We are at some point ABOVE our current element
        // so start walking UP until we reach the level indicated
        // and then add the element to the parent
        while (curDepth >= key) {
            curElem = curElem.parentElement;
            curDepth--;
        }
        curElem.parentElement.appendChild(elem);
    }
    curElem = elem;
    curDepth = key;
}


问:
highlight navigation dropdown
I want my dropdown link to highlight, but also the link in the top of that dropdown. If you have a look at http://rezolve.4pixels.com/banks-and-telcos/home/banks-and-telcos.php and you click the last link in any of the dropdowns they work perfectly (they highlight their own 'li' and the parent 'li'). I just can't work out why only the last link in each dropdown does what I want ie none of the others apart from the last. I'd have thought 'parents' would pick up all ancestor 'li'

My script is this:

```<code>$(document).ready(function(){
    "use strict";
  var currentPageUrl = location.href;
  $('.nk-nav li a').each(function(){
      $(this).parents("li").toggleClass('active', this.href === currentPageUrl);
  });
});
</code>```

答:
I don't know why it "partially" works...

I don't think it is because of your script.

You'll notice that console.log(currentPageUrl); returns the full address.

(including http://rezolve.4pixels.com).

Your script compares this to the relative URL.

(without http://rezolve.4pixels.com)

So it can't be matching really often.

So here is a script I suggest you to try...

```<code>$(document).ready(function(){
  "use strict";

  var currentPageUrl = location.href;
  console.log(currentPageUrl);

  $('.nk-drop-item').find('a').each(function(){
    if( "http://rezolve.4pixels.com"+ $(this).attr("href") === currentPageUrl ){
      $(this).closest(".nk-drop-item").addClass('active');
    }
  });
});
</code>```

But I don't know if there will be interference with what is actually highlighting...

Title: highlight navigation dropdown

Body:
I want my dropdown link to highlight, but also the link in the top of that dropdown. If you have a look at http://rezolve.4pixels.com/banks-and-telcos/home/banks-and-telcos.php and you click the last link in any of the dropdowns they work perfectly (they highlight their own 'li' and the parent 'li'). I just can't work out why only the last link in each dropdown does what I want ie none of the others apart from the last. I'd have thought 'parents' would pick up all ancestor 'li'

My script is this:

$(document).ready(function(){
    "use strict";
  var currentPageUrl = location.href;
  $('.nk-nav li a').each(function(){
      $(this).parents("li").toggleClass('active', this.href === currentPageUrl);
  });
});

Body:
I don't know why it "partially" works...

I don't think it is because of your script.

You'll notice that console.log(currentPageUrl); returns the full address.

(including http://rezolve.4pixels.com).

Your script compares this to the relative URL.

(without http://rezolve.4pixels.com)

So it can't be matching really often.

So here is a script I suggest you to try...

$(document).ready(function(){
  "use strict";

  var currentPageUrl = location.href;
  console.log(currentPageUrl);

  $('.nk-drop-item').find('a').each(function(){
    if( "http://rezolve.4pixels.com"+ $(this).attr("href") === currentPageUrl ){
      $(this).closest(".nk-drop-item").addClass('active');
    }
  });
});

But I don't know if there will be interference with what is actually highlighting...


问:
Regex finding aa but not aaa with grep
Can't figure out the regex pattern for matching aa but not aaa.

```<code>x <- c("ab", "abc", "abcc", "abccc", "abcccc", "abccccc")

grep(pattern="c{2,3}", x, value=TRUE, perl=TRUE)
## [1] "abcc"    "abccc"   "abcccc"  "abccccc"

grep(pattern="^((?!c{4,}).)*$", x, value=TRUE, perl=TRUE)
## [1] "ab"    "abc"   "abcc"  "abccc"
</code>```

But what's the pattern to yield:

```<code>grep(pattern=..., x, value=TRUE, perl=TRUE)
## [1] "abcc"  "abccc"
</code>```

答:
This should work for your test cases:</p>

```<code>^[^c]+c{2,3}$
</code>```

Title: Regex finding aa but not aaa with grep

Body:
Can't figure out the regex pattern for matching aa but not aaa.

x <- c("ab", "abc", "abcc", "abccc", "abcccc", "abccccc")

grep(pattern="c{2,3}", x, value=TRUE, perl=TRUE)
## [1] "abcc"    "abccc"   "abcccc"  "abccccc"

grep(pattern="^((?!c{4,}).)*$", x, value=TRUE, perl=TRUE)
## [1] "ab"    "abc"   "abcc"  "abccc"

But what's the pattern to yield:

grep(pattern=..., x, value=TRUE, perl=TRUE)
## [1] "abcc"  "abccc"

Body:
This should work for your test cases:

^[^c]+c{2,3}$


问:
Jupyter Notebook: ImportError: cannot import name 'default'
When trying to start Jupyter with the command Jupyter Notebook, I am getting this below error:

```<code>File "/anaconda/bin/jupyter-notebook", line 4, in <module>
import notebook.notebookapp
File "/anaconda/lib/python3.6/site-packages/notebook/notebookapp.py",
line 63, in <module>
from .services.contents.manager import ContentsManager
File "/anaconda/lib/python3.6/site-
packages/notebook/services/contents/manager.py", line 16, in <module>
from nbformat import sign, validate, ValidationError
File "/anaconda/lib/python3.6/site-packages/nbformat/sign.py", line 24,
in <module>
from traitlets import (
ImportError: cannot import name 'default'
</code>```

Any idea what is missing?

答: I uninstalled traitlets package and reinstalled it. The problem went away. Not sure how it broke in the first place.</p>

Body:
When trying to start Jupyter with the command Jupyter Notebook, I am getting this below error:

File "/anaconda/bin/jupyter-notebook", line 4, in <module>
import notebook.notebookapp
File "/anaconda/lib/python3.6/site-packages/notebook/notebookapp.py",
line 63, in <module>
from .services.contents.manager import ContentsManager
File "/anaconda/lib/python3.6/site-
packages/notebook/services/contents/manager.py", line 16, in <module>
from nbformat import sign, validate, ValidationError
File "/anaconda/lib/python3.6/site-packages/nbformat/sign.py", line 24,
in <module>
from traitlets import (
ImportError: cannot import name 'default'

Any idea what is missing?


问:
Cascading DropdownList for Asp.Net MVC with Razor
I'm trying to have a pair of cascading drop downs that narrow down a list of cities based on a selected state. So far I have this:
View:

```<code><div class="form-group">
            @Html.LabelFor(model => model.CollLocation,  htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="col-md-6">
                    @Html.DropDownList("stateCol", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Select a state")
                    @Html.ValidationMessageFor(model => model.CollLocation, "", new { @class = "text-danger" })
                </div>
                <div class="col-md-6">
                    @Html.DropDownList("CollLocation", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Select a city")
                    @Html.ValidationMessageFor(model => model.CollLocation, "", new { @class = "text-danger" })
                </div>
</code>```

And this controller:

```<code>// GET: Coll/Create
public ActionResult Create()
{
    var stateColl = db.ZipCodes.OrderBy(c => c.state).Select(c => c.state).Distinct();

    var cityCol = db.ZipCodes.Select(C => C.primary_city).Distinct();

    ViewBag.stateCol = new SelectList(stateColl);
    ViewBag.ArRecID = new SelectList(db.ArRecs, "ArRecID", "ArZipID");
    ViewBag.CollLocation = new SelectList(cityCol);
    return View();
}

// POST: Coll/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CollID,ArRecID,CollName,CollDescr,CollValue,CollOwner,CollLocation,DateCreated,ModBy,ModDate,CreatedBy")] Collateral collateral)
{
    if (ModelState.IsValid)
    {
        db.Coll.Add(coll);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.ArRecID = new SelectList(db.ArRecs, "ArRecID", "ArZipID", coll.ArRecID);
    ViewBag.CollLocation = new SelectList(db.ZipCodes, "zip", "primary_city", coll.CollLocation).Distinct();
    return View(collateral);
}
</code>```

In my ZipCodes model I have zip, primary_city, and state. In the CollLocation, I want to be able to see only the cites that are in the state selected in the stateCol dropdown. Both the drop downs work for me but, they're not working together. I tried other tutorial and answers, butt they only left me scratching my head even more. Any help will be greatly appreciated.

答:
You will need to make Ajax request every time when you change your State dropdown. Thus, when State dropdown changed, a JavaScript function should make an Ajax request to your controller to query the Zipcode you want.

You can download my project in Github and have a look 2 files"\Views\ClientOrder\Create.cshtml" and  "\RiceStoreScripts\ClientOrder.js"

hongyichao/MVCRiceStore

Body:
I'm trying to have a pair of cascading drop downs that narrow down a list of cities based on a selected state. So far I have this:
View:

            @Html.LabelFor(model => model.CollLocation,  htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.DropDownList("stateCol", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Select a state")
                    @Html.ValidationMessageFor(model => model.CollLocation, "", new { @class = "text-danger" })

                    @Html.DropDownList("CollLocation", null, htmlAttributes: new { @class = "form-control" }, optionLabel: "Select a city")
                    @Html.ValidationMessageFor(model => model.CollLocation, "", new { @class = "text-danger" })

And this controller:

// GET: Coll/Create
public ActionResult Create()
{
    var stateColl = db.ZipCodes.OrderBy(c => c.state).Select(c => c.state).Distinct();

    var cityCol = db.ZipCodes.Select(C => C.primary_city).Distinct();

    ViewBag.stateCol = new SelectList(stateColl);
    ViewBag.ArRecID = new SelectList(db.ArRecs, "ArRecID", "ArZipID");
    ViewBag.CollLocation = new SelectList(cityCol);
    return View();
}

// POST: Coll/Create

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CollID,ArRecID,CollName,CollDescr,CollValue,CollOwner,CollLocation,DateCreated,ModBy,ModDate,CreatedBy")] Collateral collateral)
{
    if (ModelState.IsValid)
    {
        db.Coll.Add(coll);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.ArRecID = new SelectList(db.ArRecs, "ArRecID", "ArZipID", coll.ArRecID);
    ViewBag.CollLocation = new SelectList(db.ZipCodes, "zip", "primary_city", coll.CollLocation).Distinct();
    return View(collateral);
}

In my ZipCodes model I have zip, primary_city, and state. In the CollLocation, I want to be able to see only the cites that are in the state selected in the stateCol dropdown. Both the drop downs work for me but, they're not working together. I tried other tutorial and answers, butt they only left me scratching my head even more. Any help will be greatly appreciated.


问:
Java Queue, Dequeue and Printing All Values Within The Queued/Dequeued List
Hello I think I'm really having a hard time with this part. I'm making a program that accepts a value from the user a first name and last name, and then Queues it (CASE1).  Then is able to dequeue it (CASE2) and finally show everything on the list. There are no errors on the IDE, but I cant get the result that I want, At CASE 2 it throws the exception error, means that the list that gets passed to it is empty. At CASE 3 no values are shown. How do I fix this?</p>

```<code>import java.util.*;
import java.util.Iterator;

class Customer2 {
    public String lastName;
    public String firstName;
    public Customer2() {
    }
    public Customer2(String last, String first) {
       this.lastName = last;
       this.firstName = first;
    }
    public String toString() {
       return firstName + " " + lastName;
    }
 }
class HourlyCustomer2 extends Customer2 {
    public double hourlyRate;
    public HourlyCustomer2(String last, String first) {
       super(last, first);
    }
 }

class Queue1<E> {

    private LinkedList<E> list = new LinkedList<E>();

    public void enqueue(E item) {
        list.addLast(item);
    }

    public E dequeue() {

        // return a Customer2 with null values if empty? (up to you)

            return list.remove(0);
    }

    public E isNotEnd(){

        return list.getLast();
    }

    public boolean hasItems() {

        return !list.isEmpty();
    }

    public boolean isEmpty() {

        return list.isEmpty();
    }

    public Iterator<E> iterator() {

        return list.iterator();
    }

    public E removeFirst() {

        return list.removeFirst();
    }

    public E getFirst() {

        return list.getFirst();
    }

    public int size() {

        return list.size();
    }

    public boolean hasNext() {

        return false;
    }

    public void addItems(Queue1<? extends E> q) {

        while (q.hasNext()) list.addLast(q.dequeue());
    }
}

public class something {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String input1;
        String input2;
        int choice = 1000;

        Queue1<Customer2> empList;
        empList = new Queue1<Customer2>();
        Queue1<HourlyCustomer2> hList;
        hList = new Queue1<HourlyCustomer2>();

        do {

            System.out.println("================");
            System.out.println("Queue Operations Menu");
            System.out.println("================");
            System.out.println("1,Enquene");
            System.out.println("2,Dequeue");
            System.out.println("3,View queue");
            System.out.println("0, Quit\n");
            System.out.println("Enter Choice:");

            try {

                choice = sc.nextInt();

                switch(choice) {

                    case 1:

                        System.out.println("\nPlease enter last name:  ");
                        input1 = sc.next();
                        System.out.println("\nPlease enter first name:  ");
                        input2 = sc.next();
                        hList.enqueue(new HourlyCustomer2(input1, input2));
                        empList.addItems(hList);

                        System.out.println("\n"+(input2 + " " +  input1) + " is successful queued");

                        break;

                    case 2:

                        if (empList.isEmpty()) {
                            System.out.println("The queue is empty!");
                        }
                        else
                        {
                        System.out.println("\nDequeued customer: "  +empList.getFirst());
                        empList.removeFirst();
                        }

                        System.out.println("\nNext customer in queue: "  +empList.getFirst()+"\n");

                        break;

                    case 3:

                        System.out.println("\nThe Customer's names are: \n");

                        Iterator<Customer2> it = empList.iterator();

                        while (it.hasNext()) {

                              System.out.println("\nThe customers' names are: \n");
                        }

                        break;

                    case 0:

                        System.exit(0);

                    default:

                        System.out.println("Invalid choice");
                }
            }
            catch(InputMismatchException e) {

                System.out.println("Please enter 1-5, 0 to quit");
                sc.nextLine();
            }

        } while(choice != 0);
    }
}
</code>```

答:
Look at your custom queue; you forgot to put the logic in your hasNext method. It will always return false. Therefore your addItems loop will never add any items to the queue.

If you need a hint towards how to do the hasNext(), my recommendation is to look at the size of your list and make a simple comparison.

public boolean hasNext() {

    return false;
}

public void addItems(Queue1<? extends E> q) {

    while (q.hasNext()) list.addLast(q.dequeue());
}
```

PS: I noticed that your code also shows the next in line. You might want to check if it's empty or hasNext() before that to not get a crash if the list was empty after that dequeuing.

Body:
Hello I think I'm really having a hard time with this part. I'm making a program that accepts a value from the user a first name and last name, and then Queues it (CASE1).  Then is able to dequeue it (CASE2) and finally show everything on the list. There are no errors on the IDE, but I cant get the result that I want, At CASE 2 it throws the exception error, means that the list that gets passed to it is empty. At CASE 3 no values are shown. How do I fix this?

import java.util.*;
import java.util.Iterator;

class Customer2 {
    public String lastName;
    public String firstName;
    public Customer2() {
    }
    public Customer2(String last, String first) {
       this.lastName = last;
       this.firstName = first;
    }
    public String toString() {
       return firstName + " " + lastName;
    }
 }
class HourlyCustomer2 extends Customer2 {
    public double hourlyRate;
    public HourlyCustomer2(String last, String first) {
       super(last, first);
    }
 }

class Queue1<E> {

    private LinkedList<E> list = new LinkedList<E>();

    public void enqueue(E item) {
        list.addLast(item);
    }

    public E dequeue() {

        // return a Customer2 with null values if empty? (up to you)

            return list.remove(0);
    }

    public E isNotEnd(){

        return list.getLast();
    }

    public boolean hasItems() {

        return !list.isEmpty();
    }

    public boolean isEmpty() {

        return list.isEmpty();
    }

    public Iterator<E> iterator() {

        return list.iterator();
    }

    public E removeFirst() {

        return list.removeFirst();
    }

    public E getFirst() {

        return list.getFirst();
    }

    public int size() {

        return list.size();
    }

    public boolean hasNext() {

        return false;
    }

    public void addItems(Queue1<? extends E> q) {

        while (q.hasNext()) list.addLast(q.dequeue());
    }
}

public class something {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String input1;
        String input2;
        int choice = 1000;

        Queue1<Customer2> empList;
        empList = new Queue1<Customer2>();
        Queue1<HourlyCustomer2> hList;
        hList = new Queue1<HourlyCustomer2>();

        do {

            System.out.println("================");
            System.out.println("Queue Operations Menu");
            System.out.println("================");
            System.out.println("1,Enquene");
            System.out.println("2,Dequeue");
            System.out.println("3,View queue");
            System.out.println("0, Quit\n");
            System.out.println("Enter Choice:");

            try {

                choice = sc.nextInt();

                switch(choice) {

                    case 1:

                        System.out.println("\nPlease enter last name:  ");
                        input1 = sc.next();
                        System.out.println("\nPlease enter first name:  ");
                        input2 = sc.next();
                        hList.enqueue(new HourlyCustomer2(input1, input2));
                        empList.addItems(hList);

                        System.out.println("\n"+(input2 + " " +  input1) + " is successful queued");

                        break;

                    case 2:

                        if (empList.isEmpty()) {
                            System.out.println("The queue is empty!");
                        }
                        else
                        {
                        System.out.println("\nDequeued customer: "  +empList.getFirst());
                        empList.removeFirst();
                        }

                        System.out.println("\nNext customer in queue: "  +empList.getFirst()+"\n");

                        break;

                    case 3:

                        System.out.println("\nThe Customer's names are: \n");

                        Iterator<Customer2> it = empList.iterator();

                        while (it.hasNext()) {

                              System.out.println("\nThe customers' names are: \n");
                        }

                        break;

                    case 0:

                        System.exit(0);

                    default:

                        System.out.println("Invalid choice");
                }
            }
            catch(InputMismatchException e) {

                System.out.println("Please enter 1-5, 0 to quit");
                sc.nextLine();
            }

        } while(choice != 0);
    }
}

Body:
Look at your custom queue; you forgot to put the logic in your hasNext method. It will always return false. Therefore your addItems loop will never add any items to the queue.

If you need a hint towards how to do the hasNext(), my recommendation is to look at the size of your list and make a simple comparison.

public boolean hasNext() {

    return false;
}

public void addItems(Queue1<? extends E> q) {

    while (q.hasNext()) list.addLast(q.dequeue());
}

PS: I noticed that your code also shows the next in line. You might want to check if it's empty or hasNext() before that to not get a crash if the list was empty after that dequeuing.


问:
Efficient Multi-threading in C
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

```<code> for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

```<code> for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }
</code>```

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?

答:
Don't try to split it into pieces and assign one to each thread. First, that's a lot of work. Second, that performs very poorly under all kinds of realistic conditions.

For example, suppose you have a machine with four physical cores and eight virtual cores and you create four threads and give each one quarter of the work. If one physical core is occupied when your code runs, two of your threads will share a physical core. When the two "fast" threads that have their own physical core finish, you'll have three physical cores but only two threads running. Yuck.

Why arrange things so you have to figure out the optimal division? It's extra work and it makes your code slow if you figure things out wrong. Don't do that.

Instead, divided the work into sensible chunks, and let each thread use the following algorithm:

Is there a chunk of work that has not been started?

If no, wait and go to step 1.

Do that chunk of work.

Go to step 1.

So you can divide your matrix work into a large number of convenient piece and create a pool with a sensible number of threads. Then the threads can run at whatever concurrency works best, and so long as there's enough work left to do, all cores will stay busy.

In other words, you are thinking about the problem the wrong way and trying to do the scheduler's work. Don't try to assign specific work to specific threads -- it's too hard to get it right.

Title: Efficient Multi-threading in C

Body:
I'm currently in the introductory stages of writing multi-threaded programs in C. I understand how to create separate threads with completely separate functions but I'm wanting to understand how programmers in the field break down a single task to take advantage of multi-threading. I've gone through several exercises for synchronizing separate threads but nothing good when it comes to breaking down a single task and making it quicker with multiple threads. I'd really appreciate some wisdom when it comes to solving these types of problems and explain how and why you would attack a problem in that particular way.

As an example, lets say this is the task I'm trying to tackle with multiple threads. [It multiplies two matrices together creating the c matrix with n x p dimensions.] And lets also say we can input how many threads we want to run between 1 and t (even though there won't be a significant performance difference in threads >= 4) so it's obvious how to attack it.

 for (i = 0; i < n; i++){
     for (j = 0; j < p; j++){
         c[i][j] = 0;
         for (k = 0; k < m; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

My first thoughts are to basically divide each loop up according to how many threads. So, for t threads,

 for (i = 0; i < n / t; i++){
     for (j = 0; j < p / t; j++){
         c[i][j] = 0;
         for (k = 0; k < m / t; k++){
             c[i][j] += a[i][k] * b[k][j];
         }
      }
  }

And then synchronizing them with semaphores. But this would have to separate each part of the problem into t-cohesive threads that don't overlap or miss any of the matrices. This seems a little much and I have a feeling there's a better way to attack it. How would you guys go about this?


问:
Get visual graph of heap memory usage in Java over a span of time
I am currently using Visual VM to monitor the heap memory usage of my Java application. However I would like to somehow see the heap memory usage over a span of time like for example a day and not just get a snapshot.I would like to be able to leave Visual VM or a tool on and let it log the memory usage and then later after one day, I can go back and see a graph of it. Is there a way to do this using Visual VM? If yes, how? If not, what tool can I used to do this?</p>

答: Try the Memory tab in JConsole. JConsole is also included with the Oracle JDK, like JVisualVM, so you should already have it. It has a time range of "all" which should work for what you want to do. It will look like this:


问:
How to break a string in C with /
I have a string with the following pattern :

```<code>char *str = "ai/aj/module_mat.mod";
</code>```

and I want to select module_mat as my final string for the further logic. I have tried to used rindex() so that I can get the final part of the string. But I am not able to do this in C. What am I doing wrong?

The code I am trying is -

```<code>char *first = rindex(str, "/");
char *first = strtok(first, ".");
</code>```

答:
Your mistake is right here:

```<code>char *str = "ai/aj/module_mat.mod";
</code>```

Since str points to a constant, this should be:

```<code>const char *str = "ai/aj/module_mat.mod";
</code>```

Now your compiler should show you the other problems.

Similarly:

```<code>char *first = rindex(str, "/");
</code>```

Since rindex is returning a pointer into the constant you passed it, that pointer should also be const.

```<code>char *first = strtok(first, ".");
</code>```

Hmm, what do the docs for strtok say:

If a delimiter byte is found, it is overwritten with a null byte
  to terminate the current token, and strtok() saves a pointer to the following byte; ...

So strtok modifies the thing the pointer points to, so passing it a pointer to a constant is bad! You can't modify a constant.

Title: How to break a string in C with /

Body:
I have a string with the following pattern :

char *str = "ai/aj/module_mat.mod";

and I want to select module_mat as my final string for the further logic. I have tried to used rindex() so that I can get the final part of the string. But I am not able to do this in C. What am I doing wrong?

The code I am trying is -

char *first = rindex(str, "/");
char *first = strtok(first, ".");

Body:
Your mistake is right here:

char *str = "ai/aj/module_mat.mod";

Since str points to a constant, this should be:

const char *str = "ai/aj/module_mat.mod";

Now your compiler should show you the other problems.

Similarly:

char *first = rindex(str, "/");

Since rindex is returning a pointer into the constant you passed it, that pointer should also be const.

char *first = strtok(first, ".");

Hmm, what do the docs for strtok say:

If a delimiter byte is found, it is overwritten with a null byte
  to terminate the current token, and strtok() saves a pointer to the following byte; ...

So strtok modifies the thing the pointer points to, so passing it a pointer to a constant is bad! You can't modify a constant.


问:
C programming: Sorting Structures with two parameters
I'm Now trying to sort the Last names and Company names. The user has to enter either a last name or company name (only one). this is my code right now:

```<code>struct store {
unsigned long phone_num;
char *first_name;
char *last_name;
char *company_name;
char *email;
};
typedef struct store store;

void findContact(FILE *fp, long fileEnd)
{
/*variables*/
char fName [100];
char lName [100];
char cName [100];
char email [100];

int i, length;
int count = 1;
int size = sizeof(long);
int usize = sizeof(unsigned long);

unsigned long phone;

long nextPosition = 0;
long fNamePosition = 0;
long lNamePosition = 0;
long cNamePosition = 0;
long emailPosition = 0;

store *list;
list = malloc(sizeof(store));

/*Search for Contact position in file*/
fseek(fp, 0, SEEK_SET); /*Seeks to beginning of file*/
do {
    i = count - 1;

    fread(&phone, usize, 1, fp); /*reads phonenumber of contact*/
    fread(&fNamePosition, size , 1, fp);
    fread(&lNamePosition, size, 1, fp);
    fread(&cNamePosition, size, 1, fp);
    fread(&emailPosition, size, 1, fp);
    fread(&nextPosition, size, 1, fp);

    if(fNamePosition != 0) {

        fseek(fp,fNamePosition,SEEK_SET);
        if(lNamePosition == 0) {
          length = cNamePosition - fNamePosition;
        } else {
          length = lNamePosition - fNamePosition;
        }
        fread(fName,sizeof(char),length,fp);
    } else {
        strcpy(fName," ");
    }

    if(lNamePosition != 0) {
        fseek(fp,lNamePosition,SEEK_SET);
        if (cNamePosition == 0) {
          length = emailPosition - lNamePosition;
        } else {
          length = cNamePosition - lNamePosition;
        }
        fread(lName,sizeof(char), length,fp);
    } else {
        strcpy(lName," ");
    }

    if(cNamePosition != 0) {
        fseek(fp,cNamePosition,SEEK_SET);
        length = emailPosition-cNamePosition;
        fread(cName,sizeof(char), length,fp);
    } else {
        strcpy(cName," ");
    }

    fseek(fp,emailPosition,SEEK_SET);
    length = nextPosition - emailPosition;
    fread(email,sizeof(char),length,fp);

    list = realloc(list, count * sizeof(store));

    list[i].phone_num = phone;
    list[i].first_name = (char *) malloc(strlen(fName) + 1);
    strcpy(list[i].first_name, fName);
    list[i].last_name = (char *) malloc(strlen(lName) + 1);
    strcpy(list[i].last_name, lName);
    list[i].company_name = (char *) malloc(strlen(cName) + 1);
    strcpy(list[i].company_name, cName);
    list[i].email = (char *) malloc(strlen(email) + 1);
    strcpy(list[i].email, email);

    count++;

} while (ftell(fp) != fileEnd);

count--;

qsort(list, count, sizeof(store), compareStore);

/*Prints output*/
for(i=0;i<count;i++) {
    printf("First Name: %s\n", list[i].first_name);
    printf("Last Name: %s\n", list[i].last_name);
    printf("Company Name: %s\n", list[i].company_name);
    printf("Phone Number (enter only numbers): %ld\n", list[i].phone_num);
    printf("Email: %s\n", list[i].email);

    free(list[i].first_name);
    free(list[i].last_name);
    free(list[i].company_name);
    free(list[i].email);
}

free(list);
return;
}

int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    return (strcmp(bb->last_name, aa->last_name));
}
</code>```

This is my output as of now. It should consider both last name and company name as the same parameters and then sort them:

```<code>First Name: Andre
Last Name: D'Souza
Company Name:
Phone Number (enter only numbers): 6474000964
Email: adsouz03@mail.com
First Name:
Last Name:
Company Name: University of Guelph
Phone Number (enter only numbers): 5192137299
Email: uog@mail.com
First Name: Raf
Last Name:
Company Name: Raffy Taffy
Phone Number (enter only numbers): 1234567
Email: raf@mail.com
</code>```

答:
Not a complete answer, because this looks like homework, but: if your compareStore() needs to compare either the last name or the company name, whichever is set, then it should contain a conditional.

In your case, you need a way to tell whether last_name or company_name is set.  You can set the unused pointer to NULL and test if (a->last_name).  You could also add an enum field.

If you can change the definition of your struct, you don’t really need two char * fields that will be used the same way, only one at a time.  You can have one field, interpreted differently.

Finally, (Sorry for the unwarranted criticism.) you normally shouldn’t suppress static type checking like you did with the void* parameters.  It’s there to stop you from shooting yourself in the foot.  In this case, though, the function is an input to qsort() and therefore one of the rare unavoidable exceptions.

Body:
I'm Now trying to sort the Last names and Company names. The user has to enter either a last name or company name (only one). this is my code right now:

struct store {
unsigned long phone_num;
char *first_name;
char *last_name;
char *company_name;
char *email;
};
typedef struct store store;

void findContact(FILE *fp, long fileEnd)
{
/*variables*/
char fName [100];
char lName [100];
char cName [100];
char email [100];

int i, length;
int count = 1;
int size = sizeof(long);
int usize = sizeof(unsigned long);

unsigned long phone;

long nextPosition = 0;
long fNamePosition = 0;
long lNamePosition = 0;
long cNamePosition = 0;
long emailPosition = 0;

store *list;
list = malloc(sizeof(store));

/*Search for Contact position in file*/
fseek(fp, 0, SEEK_SET); /*Seeks to beginning of file*/
do {
    i = count - 1;

    fread(&phone, usize, 1, fp); /*reads phonenumber of contact*/
    fread(&fNamePosition, size , 1, fp);
    fread(&lNamePosition, size, 1, fp);
    fread(&cNamePosition, size, 1, fp);
    fread(&emailPosition, size, 1, fp);
    fread(&nextPosition, size, 1, fp);

    if(fNamePosition != 0) {

        fseek(fp,fNamePosition,SEEK_SET);
        if(lNamePosition == 0) {
          length = cNamePosition - fNamePosition;
        } else {
          length = lNamePosition - fNamePosition;
        }
        fread(fName,sizeof(char),length,fp);
    } else {
        strcpy(fName," ");
    }

    if(lNamePosition != 0) {
        fseek(fp,lNamePosition,SEEK_SET);
        if (cNamePosition == 0) {
          length = emailPosition - lNamePosition;
        } else {
          length = cNamePosition - lNamePosition;
        }
        fread(lName,sizeof(char), length,fp);
    } else {
        strcpy(lName," ");
    }

    if(cNamePosition != 0) {
        fseek(fp,cNamePosition,SEEK_SET);
        length = emailPosition-cNamePosition;
        fread(cName,sizeof(char), length,fp);
    } else {
        strcpy(cName," ");
    }

    fseek(fp,emailPosition,SEEK_SET);
    length = nextPosition - emailPosition;
    fread(email,sizeof(char),length,fp);

    list = realloc(list, count * sizeof(store));

    list[i].phone_num = phone;
    list[i].first_name = (char *) malloc(strlen(fName) + 1);
    strcpy(list[i].first_name, fName);
    list[i].last_name = (char *) malloc(strlen(lName) + 1);
    strcpy(list[i].last_name, lName);
    list[i].company_name = (char *) malloc(strlen(cName) + 1);
    strcpy(list[i].company_name, cName);
    list[i].email = (char *) malloc(strlen(email) + 1);
    strcpy(list[i].email, email);

    count++;

} while (ftell(fp) != fileEnd);

count--;

qsort(list, count, sizeof(store), compareStore);

/*Prints output*/
for(i=0;i<count;i++) {
    printf("First Name: %s\n", list[i].first_name);
    printf("Last Name: %s\n", list[i].last_name);
    printf("Company Name: %s\n", list[i].company_name);
    printf("Phone Number (enter only numbers): %ld\n", list[i].phone_num);
    printf("Email: %s\n", list[i].email);

    free(list[i].first_name);
    free(list[i].last_name);
    free(list[i].company_name);
    free(list[i].email);
}

free(list);
return;
}

int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    return (strcmp(bb->last_name, aa->last_name));
}

This is my output as of now. It should consider both last name and company name as the same parameters and then sort them:

First Name: Andre
Last Name: D'Souza
Company Name:
Phone Number (enter only numbers): 6474000964
Email: adsouz03@mail.com
First Name:
Last Name:
Company Name: University of Guelph
Phone Number (enter only numbers): 5192137299
Email: uog@mail.com
First Name: Raf
Last Name:
Company Name: Raffy Taffy
Phone Number (enter only numbers): 1234567
Email: raf@mail.com