问:
Avoid Angular2 to systematically submit form on button click
Ok so maybe this is unclear. Get this form:

```<code><form (ngSubmit)="submit()" #crisisForm="ngForm">
   <input type="text" name="name" [(ngModel)]="crisis.name">
   <button type="submit">Submit</button>
   <button type="button" (click)="preview()">Preview</button>
   <button type="reset" (click)="reset()">Reset</button>
</form>
</code>```

Why do all buttons trigger the submit() function ? And how to avoid that ?

答:
You have to import FormsModule from '@angular/forms' in your app.module.ts</p>

```<code>import { FormsModule } from '@angular/forms';
 @NgModule({
  imports: [
    FormsModule
 ],
 })
</code>```

Body:
Ok so maybe this is unclear. Get this form:

<form (ngSubmit)="submit()" #crisisForm="ngForm">
   <input type="text" name="name" [(ngModel)]="crisis.name">
   <button type="submit">Submit</button>
   <button type="button" (click)="preview()">Preview</button>
   <button type="reset" (click)="reset()">Reset</button>
</form>

Why do all buttons trigger the submit() function ? And how to avoid that ?

Body:
You have to import FormsModule from '@angular/forms' in your app.module.ts

import { FormsModule } from '@angular/forms';
 @NgModule({
  imports: [
    FormsModule
 ],
 })


来源: stackexchange

问:
Bender's decomposition example in CPLEX's Python
[![enter image description here][1]][1]I am running "bendersatsp.py" from the examples proposed by CPLEX via eclips. I have only added the path of atsp.dat in main clause where "filename=" is defined. After running that, it seems it executes only for len(sys.argv)=1 and gives me the following results. Do you know what is the problem and why it does not completely run?</p>

```<code>  Usage:     bendersatsp.py {0|1} [filename]
  0:        Benders' cuts only used as lazy constraints,
            to separate integer infeasible solutions.
  1:        Benders' cuts also used as user cuts,
            to separate fractional infeasible solutions.
  filename: ATSP instance file name.
       File C:\Program Files (x86)\IBM\ILOG\CPLEX_Studio1261\cplex\examples/data/atsp.dat used if no name is provided.
</code>```

答:
The 0|1 argument is required. For example, you'll need to run the script like so:

```<code>python bendersatsp.py 0 "C:\Program Files (x86)\IBM\ILOG\CPLEX_Studio1261\cplex\examples/data/atsp.dat"
</code>```

Or, assuming you have changed the default filename path:

```<code>python bendersatsp.py 0
</code>```

I've added some comments to the code that parses the command line arguments below to try and make this clear:

```<code>if __name__ == "__main__":
    # If there are not 1 or 2 arguments then exit (recall that
    # sys.argv[0] is the program name itself (i.e., "bendersatsp.py")
    if len(sys.argv) != 2 and len(sys.argv) != 3:
        usage()
        sys.exit(-1)
    # If the first argument is not "0" or "1" then exit.
    if sys.argv[1] not in  ["0", "1"]:
        usage()
        sys.exit(-1)
    # Store the second argument in filename if there is one.
    if len(sys.argv) == 3:
        filename = sys.argv[2]
    else:
        # Otherwise, use the following default.
        filename = "../../../examples/data/atsp.dat"
    # Pass the arguments into the bendersATSP function.
    bendersATSP(sys.argv[1][0], filename)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
[![enter image description here][1]][1]I am running "bendersatsp.py" from the examples proposed by CPLEX via eclips. I have only added the path of atsp.dat in main clause where "filename=" is defined. After running that, it seems it executes only for len(sys.argv)=1 and gives me the following results. Do you know what is the problem and why it does not completely run?

  Usage:     bendersatsp.py {0|1} [filename]
  0:        Benders' cuts only used as lazy constraints,
            to separate integer infeasible solutions.
  1:        Benders' cuts also used as user cuts,
            to separate fractional infeasible solutions.
  filename: ATSP instance file name.
       File C:\Program Files (x86)\IBM\ILOG\CPLEX_Studio1261\cplex\examples/data/atsp.dat used if no name is provided.

Body:
The 0|1 argument is required. For example, you'll need to run the script like so:

python bendersatsp.py 0 "C:\Program Files (x86)\IBM\ILOG\CPLEX_Studio1261\cplex\examples/data/atsp.dat"

Or, assuming you have changed the default filename path:

python bendersatsp.py 0

I've added some comments to the code that parses the command line arguments below to try and make this clear:

if __name__ == "__main__":
    # If there are not 1 or 2 arguments then exit (recall that
    # sys.argv[0] is the program name itself (i.e., "bendersatsp.py")
    if len(sys.argv) != 2 and len(sys.argv) != 3:
        usage()
        sys.exit(-1)
    # If the first argument is not "0" or "1" then exit.
    if sys.argv[1] not in  ["0", "1"]:
        usage()
        sys.exit(-1)
    # Store the second argument in filename if there is one.
    if len(sys.argv) == 3:
        filename = sys.argv[2]
    else:
        # Otherwise, use the following default.
        filename = "../../../examples/data/atsp.dat"
    # Pass the arguments into the bendersATSP function.
    bendersATSP(sys.argv[1][0], filename)


问:
Qt : C++ dynamic parameter GUI for plugin parameters
My Qt based application is extensible via plugins ( http://doc.qt.io/archives/4.6/plugins-howto.html#the-lower-level-api-extending-qt-applications) .

These plugins can have its own parameters.(int,double,String, enumerations..etc)

What I want to do is, define this parameters in an XML and generate the GUI dynamically by parsing the XML file.

I found somewhat similar architecture here - http://www.slicer.org/slicerWiki/index.php/Slicer3:Execution_Model_Documentation#Slicer3_GUI_Generation

Is there any library/framework that I can use with Qt for this.Or do I have to manually write my own code from parsing XML,mapping parameters into Maps , generate GUI checking the XML element...etc

Any tips?

答: You might want to look into QML.</p>

Body: You might want to look into QML.


问:
Why in PHP printf() "g" type-specifier gives wrong value?
As per documentation,
"g - shorter of %e and %f"

I have executed this statement:

```<code>printf("e:%1\$.3e\nf:%1\$.3f\ng:%1\$.3g", .123e2);
</code>```

And this is output:

```<code>e:1.230e+1 // long value
f:12.300 // shorter value
g:12.3 // here g gives something else
</code>```

Why "g" gives something else, am I getting the docs wrong?

```<code>$ php -v
PHP 7.1.10 (cli) (built: Oct 19 2017 15:16:13) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
    with Xdebug v2.5.1, Copyright (c) 2002-2017, by Derick Rethans
</code>```

答:
sprintf() eventually delegates to the sprintf(3) C function. From the printf(3) man page:

```<code>Precision

   [...] This gives ... the maximum number of significant digits for g and G
   conversions...
</code>```

Therefore the PHP documentation is, at best, inaccurate.

Body:
As per documentation,
"g - shorter of %e and %f"

I have executed this statement:

printf("e:%1\$.3e\nf:%1\$.3f\ng:%1\$.3g", .123e2);

And this is output:

e:1.230e+1 // long value
f:12.300 // shorter value
g:12.3 // here g gives something else

Why "g" gives something else, am I getting the docs wrong?

$ php -v
PHP 7.1.10 (cli) (built: Oct 19 2017 15:16:13) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
    with Xdebug v2.5.1, Copyright (c) 2002-2017, by Derick Rethans

Body:
sprintf() eventually delegates to the sprintf(3) C function. From the printf(3) man page:

Precision

   [...] This gives ... the maximum number of significant digits for g and G
   conversions...

Therefore the PHP documentation is, at best, inaccurate.


问:
Converting a list of strings to a list of int for machine learning
I have a table with a column corresponding to the education level : "phd", "undergrad", etc.

I would like to change those features to 0, 1, 2..... in order to use the data as an input of a machine learning algorithm.

Is there a way in Python to automatically map those string features to integers?

答:
You will likely not want to feed the data as it is to a machine learning algorithm - for instance, if a phd is a 2 and a masters is a 1, does that mean that the phd is twice as good? You might instead use "one hot encoding" and create a binary matrix (i.e. 1's & 0's) that you can feed.

There are multiple libraries to do this, i.e. one such: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

Good luck!

```<code>         BA MS PHD
Person A  0  0  0
Person B  1  0  0
Person C  0  0  1
...
</code>```

Body:
You will likely not want to feed the data as it is to a machine learning algorithm - for instance, if a phd is a 2 and a masters is a 1, does that mean that the phd is twice as good? You might instead use "one hot encoding" and create a binary matrix (i.e. 1's & 0's) that you can feed.

There are multiple libraries to do this, i.e. one such: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

Good luck!

         BA MS PHD
Person A  0  0  0
Person B  1  0  0
Person C  0  0  1
...


问:
Calling state changing functions from mapStateToProps
I am new to react-redux and I was surprised to see an example where a function, in this case being getVisiblieTodos, is called inside mapStateToProps. This function should be called in a reducer since it changes state? Is the code breaking "good form" for the sake of brevity? Is it okay to do this in general?

I am looking at code from this link

```<code>import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_ALL':
      return todos
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed)
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed)
  }
}

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

export default VisibleTodoList
</code>```

答:
todos in this component is a calculated property based on the state of the reducer, and it is not changing any state.

It's okay to transform properties comming from recuders that are used only by one component (they are called selectors). Imagine that you use todos in other components, you will not want to make changes in one component like filtering and seeing that in the other components. If this is the case, it's fine to do it.

Also, it is a good property of your reducer to store only the needed data. More state is more complexity in the app, and more overhead to calculate new states.

Body:
I am new to react-redux and I was surprised to see an example where a function, in this case being getVisiblieTodos, is called inside mapStateToProps. This function should be called in a reducer since it changes state? Is the code breaking "good form" for the sake of brevity? Is it okay to do this in general?

I am looking at code from this link

import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_ALL':
      return todos
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed)
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed)
  }
}

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

export default VisibleTodoList


问:
Saving 2 plots into one PDF with 2 pages?
Let's say I have from output 2 matplotlib plots in my jupyter notebook (for example purposes these charts are the exact same).

```<code>import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

# Note that using plt.subplots below is equivalent to using
# fig = plt.figure and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

fig.savefig("test.png")
plt.show()
</code>```

How can I save these 2 charts into a single PDF with each chart having its own page, instead of having them combined onto a single page?

答:
You could use something like this:

I took your sample code and slightly adapted it to the multipage example from matplotlib.

```<code>import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

import matplotlib.pyplot as plt
import numpy as np

with PdfPages('multipage_pdf.pdf') as pdf:
    # Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # Note that using plt.subplots below is equivalent to using
    # fig = plt.figure and then ax = fig.add_subplot(111)
    #fig, ax = plt.subplots()
    plt.plot(t, s)

    #ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks')
    #ax.grid()
    plt.title("Page one")
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    plt.title("PAGE TWO")
    # Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # Note that using plt.subplots below is equivalent to using
    # fig = plt.figure and then ax = fig.add_subplot(111)
    fig, ax = plt.subplots()
    ax.plot(t, s)

    ax.set(xlabel='time (s)', ylabel='voltage (mV)',
        title='About as simple as it gets, folks')
    ax.grid()

    pdf.savefig()
    plt.close()
</code>```

This results in a nice two page pdf on my mac unsing python 3.
This is not intended to be the final solution but should be a good starting point for you oto go on.
You can also add pdf metadata, insert text and much more.

remark for osx users: I had problems with the example from matplotlib due to the line:

```<code>plt.rc('text', usetex=True)
</code>```

This resulted in a LaTex error.

```<code>RuntimeError: LaTeX was not able to process the following string:
b'lp'
Here is the full report generated by LaTeX:
</code>```

Just set

```<code>usetex=False
</code>```

as a first workaround to get going.

Body:
Let's say I have from output 2 matplotlib plots in my jupyter notebook (for example purposes these charts are the exact same).

import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

# Note that using plt.subplots below is equivalent to using
# fig = plt.figure and then ax = fig.add_subplot(111)
fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

fig.savefig("test.png")
plt.show()

How can I save these 2 charts into a single PDF with each chart having its own page, instead of having them combined onto a single page?

Body:
You could use something like this:

I took your sample code and slightly adapted it to the multipage example from matplotlib.

import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

import matplotlib.pyplot as plt
import numpy as np

with PdfPages('multipage_pdf.pdf') as pdf:
    # Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # Note that using plt.subplots below is equivalent to using
    # fig = plt.figure and then ax = fig.add_subplot(111)
    #fig, ax = plt.subplots()
    plt.plot(t, s)

    #ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks')
    #ax.grid()
    plt.title("Page one")
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    plt.title("PAGE TWO")
    # Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # Note that using plt.subplots below is equivalent to using
    # fig = plt.figure and then ax = fig.add_subplot(111)
    fig, ax = plt.subplots()
    ax.plot(t, s)

    ax.set(xlabel='time (s)', ylabel='voltage (mV)',
        title='About as simple as it gets, folks')
    ax.grid()

    pdf.savefig()
    plt.close()

This results in a nice two page pdf on my mac unsing python 3.
This is not intended to be the final solution but should be a good starting point for you oto go on.
You can also add pdf metadata, insert text and much more.

remark for osx users: I had problems with the example from matplotlib due to the line:

plt.rc('text', usetex=True)

This resulted in a LaTex error.

RuntimeError: LaTeX was not able to process the following string:
b'lp'
Here is the full report generated by LaTeX:

Just set

usetex=False

as a first workaround to get going.


问:
Image Recognition using Supervised or Unsupervised Learning
I am familiar with supervised Learning methods (SVM, Maximum Entropy, Bayes Classifiers) for textual classification, but for image I cannot figure out where I should start from.

I have a set of human images (exclusively women) whom I've to classify as being beautiful or not. The first hurdle I am facing is "Feature selection". I thought to take hair shape, complexion, eye shape as features but they are becoming too complex to detect.
OCR in comparison seems comparatively easier as the shapes can be put in black & white format and find best match with the known symbols.

I am also ready to explore unsupervised learning methods if that is more useful.
Please provide me pointers as to how should I begin with.
Any free to use libraries would be really great (could be in any language)!

答:
If you want to classify beatiful/not beautiful, you want to use supervised learning because unsupervised learning has no idea about the concept "beautiful", you have to introduce that via labels.

As a pointer to get you started, there is a recent paper on facial beauty on ECCV 2010 (you can find it on http://dgray.info/), in the introduction there are lots of references to other papers.

ContentLicense: CC BY-SA 2.5


问:
Excel VBA - Get copied cell address when the active/selected cell is different
When using VBA in Excel, is there any way to get the address of a copied cell when the active/selected cell is different?  The cell would be copied before running the macro.

For example, let's say cell R1 is currently copied, but the selected cell and the view (what I'm seeing on screen) is over somewhere in column ZAA.  As a simple example, I want to essentially zoom back to the area with the copied cell without having to scroll over manually looking for it.

答:
First of all I just want to say that all of the solutions for this are quite hacky.

I think the best "hacky" method that works probably has a ton of edge cases, but I would just grab CTRL+C and CTRL+X (cut and copy shortcuts) and do things with them.

This won't work with the context menu cut and copy methods - there are ways to try to get those, but they are buggy (mainly bugs if you copy one thing and then copy another thing without resetting the CutCopyMode) I'm not sure if there is a way to detect a "new" cut/copy when an old one is currently active (you certainly can't do this by checking Application.CutCopyMode).

One other (potentially?) nice thing about this method is that it actually follows the range you cut when you paste it ... so if you jump again, you will see where it was moved to (note that if cutting and pasting to new sheet, this doesn't work).

In the Workbook Object:

```<code>Private Sub Workbook_Open()
Application.OnKey "^c", "CopyFired"
Application.OnKey "^x", "CutFired"
End Sub
</code>```

In a module:

```<code>Dim CutCopyRange As Range
Sub CopyFired()
Set CutCopyRange = Selection
Selection.Copy
End Sub

Sub CutFired()
Set CutCopyRange = Selection
Selection.Cut
End Sub

Sub JumpToRange()
'You can add CutCopyRange.Parent.Select if you switch worksheets
'But this will not follow a cut->paste from one sheet to another properly
'The Range seems to update itself, but not its parent.
If Not CutCopyRange Is Nothing Then CutCopyRange.Select
End Sub
</code>```

You may also want to setup Worksheet_Change captures to clear the CutCopyRange if Application.CutCopyMode is false, but I wouldn't mess with all that. Provided they use CTRL+C to copy and CTRL+X to cut, you should be able to capture it by simply capturing the presses.

Note that this code likely also has bugs if you try to cut/copy objects on a worksheet.

Call JumpToRange to jump to the current range - if it's on a different sheet, you likely need to select the sheet first - there may be some additional code associated with this.

I think you can also use ScrollTo instead of Select, but that's dealer's choice I suppose.

Body:
First of all I just want to say that all of the solutions for this are quite hacky.

I think the best "hacky" method that works probably has a ton of edge cases, but I would just grab CTRL+C and CTRL+X (cut and copy shortcuts) and do things with them.

This won't work with the context menu cut and copy methods - there are ways to try to get those, but they are buggy (mainly bugs if you copy one thing and then copy another thing without resetting the CutCopyMode) I'm not sure if there is a way to detect a "new" cut/copy when an old one is currently active (you certainly can't do this by checking Application.CutCopyMode).

One other (potentially?) nice thing about this method is that it actually follows the range you cut when you paste it ... so if you jump again, you will see where it was moved to (note that if cutting and pasting to new sheet, this doesn't work).

In the Workbook Object:

Private Sub Workbook_Open()
Application.OnKey "^c", "CopyFired"
Application.OnKey "^x", "CutFired"
End Sub

In a module:

Dim CutCopyRange As Range
Sub CopyFired()
Set CutCopyRange = Selection
Selection.Copy
End Sub

Sub CutFired()
Set CutCopyRange = Selection
Selection.Cut
End Sub

Sub JumpToRange()
'You can add CutCopyRange.Parent.Select if you switch worksheets
'But this will not follow a cut->paste from one sheet to another properly
'The Range seems to update itself, but not its parent.
If Not CutCopyRange Is Nothing Then CutCopyRange.Select
End Sub

You may also want to setup Worksheet_Change captures to clear the CutCopyRange if Application.CutCopyMode is false, but I wouldn't mess with all that. Provided they use CTRL+C to copy and CTRL+X to cut, you should be able to capture it by simply capturing the presses.

Note that this code likely also has bugs if you try to cut/copy objects on a worksheet.

Call JumpToRange to jump to the current range - if it's on a different sheet, you likely need to select the sheet first - there may be some additional code associated with this.

I think you can also use ScrollTo instead of Select, but that's dealer's choice I suppose.


问:
Overcoming Issues When Downloading a CSV File for Parsing. Linux vs Windows New Line Charachter
I am attempting to analyze stock data using historical Stock prices. This data can be downloaded from Yahoo Finance(https://finance.yahoo.com/quote/AAPL/history?p=AAPL) as a CSV file. However when I download the file it is organized as one line and not separated by a new line at the end of each row. I have read that this is because different OS uses different characters to denote new lines. Are there ways to overcome this issue when downloading a file or in a text editor, or should I modify my code to accommodate the format the files are downloaded in. I am coding in C++ on Windows 10 and viewing files in NotePad. (Im also new to StackOverFlow so advice on asking questions is appreciated.)

Example:
How the code should be

2017-10-16,157.899994,160.000000,157.649994,159.880005,159.307312,24121500

2017-10-17,159.779999,160.869995,159.229996,160.470001,159.895203,18997300

2017-10-18,160.419998,160.710007,159.600006,159.759995,159.187729,16374200

2017-10-19,156.750000,157.080002,155.020004,155.979996,155.421280,42584200

2017-10-20,156.610001,157.750000,155.960007,156.250000,155.690308,23974100

How it is downloaded

2017-10-16,157.899994,160.000000,157.649994,159.880005,159.307312,241215002017-10-17,159.779999,160.869995,159.229996,160.470001,159.895203,189973002017-10-18,160.419998,160.710007,159.600006,159.759995,159.187729,163742002017-10-19,156.750000,157.080002,155.020004,155.979996,155.421280,425842002017-10-20,156.610001,157.750000,155.960007,156.250000,155.690308,23974100

my code to read in the file

```<code>void Stock::readData(filename){
ifstream stream;
stream.open(fileName);

if(stream.fail()){
    cout << "The file " << fileName <<" failed to open." << endl;
    return;
}

string line ="";
cout << line << endl;

while(!stream.eof()){

   // cout << '*' << endl;
    getline(stream,line);
   //cout << line << endl;

    string parsed[7];

    int num = Spliter(line, ',', parsed, 7);

    string tempDate;
    float tempOpen;
    float tempHigh;
    float tempLow;
    float tempClose;
    float tempCloseAdj;
    float tempVolume;

    /*for(int i=0; i<num; i++){
        cout << parsed[i] << endl;
   }*/

    tempDate = parsed[0];
    tempOpen = stof(parsed[1]);
    tempHigh = stof(parsed[2]);
    tempLow = stof(parsed[3]);
    tempClose = stof(parsed[4]);
    tempCloseAdj = stof(parsed[5]);
    tempVolume = stof(parsed[6]);

/*
    cout <<(tempDate) << " ";
    cout << (tempOpen)<< " ";
    cout << (tempHigh)<< " ";
    cout << (tempLow)<< " ";
    cout << (tempClose)<< " ";
    cout << tempCloseAdj<< " ";
    cout << (tempVolume) << endl;
*/

    vector<float> v;

    dates.push_back(tempDate);
    data.push_back(v);
    data[numberOfDays].push_back(tempOpen);
    data[numberOfDays].push_back(tempHigh);
    data[numberOfDays].push_back(tempLow);
    data[numberOfDays].push_back(tempClose);
    data[numberOfDays].push_back(tempCloseAdj);
    data[numberOfDays].push_back(tempVolume);
   // cout << '#' << endl;

    numberOfDays++;
}

stream.close();
</code>```

}

答: I figured out the problem. In order to convert the EOL line endings between platforms like Mac, Windoxs or Unix download a text editor such as Notepad++. Open the file in notepadd++ and go to the edit tab. Find the EOL COnversion button and use it to convert the file. </p>

Body:
I am attempting to analyze stock data using historical Stock prices. This data can be downloaded from Yahoo Finance(https://finance.yahoo.com/quote/AAPL/history?p=AAPL) as a CSV file. However when I download the file it is organized as one line and not separated by a new line at the end of each row. I have read that this is because different OS uses different characters to denote new lines. Are there ways to overcome this issue when downloading a file or in a text editor, or should I modify my code to accommodate the format the files are downloaded in. I am coding in C++ on Windows 10 and viewing files in NotePad. (Im also new to StackOverFlow so advice on asking questions is appreciated.)

Example:
How the code should be

2017-10-16,157.899994,160.000000,157.649994,159.880005,159.307312,24121500

2017-10-17,159.779999,160.869995,159.229996,160.470001,159.895203,18997300

2017-10-18,160.419998,160.710007,159.600006,159.759995,159.187729,16374200

2017-10-19,156.750000,157.080002,155.020004,155.979996,155.421280,42584200

2017-10-20,156.610001,157.750000,155.960007,156.250000,155.690308,23974100

How it is downloaded

2017-10-16,157.899994,160.000000,157.649994,159.880005,159.307312,241215002017-10-17,159.779999,160.869995,159.229996,160.470001,159.895203,189973002017-10-18,160.419998,160.710007,159.600006,159.759995,159.187729,163742002017-10-19,156.750000,157.080002,155.020004,155.979996,155.421280,425842002017-10-20,156.610001,157.750000,155.960007,156.250000,155.690308,23974100

my code to read in the file

void Stock::readData(filename){
ifstream stream;
stream.open(fileName);

if(stream.fail()){
    cout << "The file " << fileName <<" failed to open." << endl;
    return;
}

string line ="";
cout << line << endl;

while(!stream.eof()){

   // cout << '*' << endl;
    getline(stream,line);
   //cout << line << endl;

    string parsed[7];

    int num = Spliter(line, ',', parsed, 7);

    string tempDate;
    float tempOpen;
    float tempHigh;
    float tempLow;
    float tempClose;
    float tempCloseAdj;
    float tempVolume;

    /*for(int i=0; i<num; i++){
        cout << parsed[i] << endl;
   }*/

    tempDate = parsed[0];
    tempOpen = stof(parsed[1]);
    tempHigh = stof(parsed[2]);
    tempLow = stof(parsed[3]);
    tempClose = stof(parsed[4]);
    tempCloseAdj = stof(parsed[5]);
    tempVolume = stof(parsed[6]);

/*
    cout <<(tempDate) << " ";
    cout << (tempOpen)<< " ";
    cout << (tempHigh)<< " ";
    cout << (tempLow)<< " ";
    cout << (tempClose)<< " ";
    cout << tempCloseAdj<< " ";
    cout << (tempVolume) << endl;
*/

    vector<float> v;

    dates.push_back(tempDate);
    data.push_back(v);
    data[numberOfDays].push_back(tempOpen);
    data[numberOfDays].push_back(tempHigh);
    data[numberOfDays].push_back(tempLow);
    data[numberOfDays].push_back(tempClose);
    data[numberOfDays].push_back(tempCloseAdj);
    data[numberOfDays].push_back(tempVolume);
   // cout << '#' << endl;

    numberOfDays++;
}

stream.close();

}


问:
windows batch copy command not working
windows batch copy cmd alone not working properly

@echo off
FOR /F "tokens=2-4 delims=/ " %%i IN ('date /t') DO SET DATE=%%k%%i%%j
REN \\server1\vinoth_new\vinoth\Test"*.txt*" SubroQuePrint.txt
copy \\server1\vinoth_new\vinoth\Test\SubroQuePrint.txt \\server1\vinoth_new
move /Y \\server1\vinoth_new\SubroQuePrint.txt
\\server1\vinoth_new\Test\%DATE%SubroQuePrint.txt
```

答:
Adopt @Compo's comment by separating your last two lines with a space instead of newline.

The end of your copy command is a bit weird.
Add a \ at the end, alternatively a \ followed by desired filename:

```<code>copy  \\server1\vinoth_new\vinoth\Test\SubroQuePrint.txt \\server1\vinoth_new\cp_SubroQuePrint.txt
</code>```

Title: windows batch copy command not working

Body:
Adopt @Compo's comment by separating your last two lines with a space instead of newline.

The end of your copy command is a bit weird.
Add a \ at the end, alternatively a \ followed by desired filename:

copy  \\server1\vinoth_new\vinoth\Test\SubroQuePrint.txt \\server1\vinoth_new\cp_SubroQuePrint.txt


答:
You may see getVisibleTodos as a reducer because it includes  "switch .. case" block or/and because it has 2 arguments . However, it is not a rule.

A redux reducer ( by definition) changes store state according to dispatched action , and that's why it takes two arguments ( store state + dispatched action ) and it returns new state for the store without mutation.

getVisibleTodos here is a helper function which filter an array according to string (filter).

Also , filter is not a redux-action, it is just string that decides todos to be rendered.

I may agree with you it is something weird , and if we can see the whole application (reducers, actions,... ) we can decide if it is best practices or not .

Title: Calling state changing functions from mapStateToProps


问:
Caused by: java.lang.NullPointerException at org.apache.spark.sql.Dataset
Below I provide my code. I iterate over the DataFrame prodRows and for each product_PK I find some matching sub-list of product_PKs from prodRows.

```<code>  numRecProducts = 10
  var listOfProducts: Map[Long,Array[(Long, Int)]] = Map()
  prodRows.foreach{ row : Row =>
      val product_PK = row.get(row.fieldIndex("product_PK")).toString.toLong
      val gender = row.get(row.fieldIndex("gender_PK")).toString
      val selection = prodRows.filter($"gender_PK" === gender || $"gender_PK" === "UNISEX").limit(numRecProducts).select($"product_PK")
      var productList: Array[(Long, Int)] = Array()
      if (!selection.rdd.isEmpty()) {
        productList = selection.rdd.map(x => (x(0).toString.toLong,1)).collect()
      }
    listOfProducts = listOfProducts + (product_PK -> productList)
  }
</code>```

But when I execute it, it gives me the following error. It looks like selection is empty in some iterations. However, I do not understand how can I handle this error:

```<code>Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1690)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1678)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1677)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1677)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:855)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:855)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:855)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1905)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1860)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1849)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:671)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2022)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2043)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2062)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2087)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1.apply(RDD.scala:918)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1.apply(RDD.scala:916)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.foreach(RDD.scala:916)
    at org.apache.spark.sql.Dataset$$anonfun$foreach$1.apply$mcV$sp(Dataset.scala:2325)
    at org.apache.spark.sql.Dataset$$anonfun$foreach$1.apply(Dataset.scala:2325)
    at org.apache.spark.sql.Dataset$$anonfun$foreach$1.apply(Dataset.scala:2325)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
    at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2823)
    at org.apache.spark.sql.Dataset.foreach(Dataset.scala:2324)
    at org.test.ComputeNumSim.run(ComputeNumSim.scala:69)
    at org.test.ComputeNumSimRunner$.main(ComputeNumSimRunner.scala:19)
    at org.test.ComputeNumSimRunner.main(ComputeNumSimRunner.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$2.run(ApplicationMaster.scala:635)
Caused by: java.lang.NullPointerException
    at org.apache.spark.sql.Dataset.<init>(Dataset.scala:170)
    at org.apache.spark.sql.Dataset$.apply(Dataset.scala:61)
    at org.apache.spark.sql.Dataset.withTypedPlan(Dataset.scala:2877)
    at org.apache.spark.sql.Dataset.filter(Dataset.scala:1304)
    at org.test.ComputeNumSim$$anonfun$run$1.apply(ComputeNumSim.scala:74)
    at org.test.ComputeNumSim$$anonfun$run$1.apply(ComputeNumSim.scala:69)
    at scala.collection.Iterator$class.foreach(Iterator.scala:893)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:108)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
</code>```

What does it mean and how can I handle it?

答:
You cannot access any of Spark's "driver-side" abstractions (RDDs, DataFrames, Datasets, SparkSession...) from within a function passed on to one of Spark's DataFrame/RDD transformations. You also cannot update driver-side mutable objects from within these functions.

In your case - you're trying to use prodRows and selection (both are DataFrames) within a function passed to DataFrame.foreach. You're also trying to update listOfProducts (a local driver-side variable) from within that same function.

Why?

DataFrames, RDDs, and SparkSession only exist on your Driver application. They serve as a "handle" to access data distributed over the cluster of worker machines.

Functions passed to RDD/DataFrame transformations get serialized and sent to that cluster, to be executed on the data partitions on each of the worker machines. When the serialized DataFrames/RDDs get deserialized on those machines - they are useless, they can't still represent the data on the cluster as they are just hollow copies of the ones created on the driver application, which actually maintains a connection to the cluster machines

For the same reason, attempting to update driver-side variables will fail: the variables (starting out as empty, in most cases) will be serialized, deserialized on each of the workers, get updated locally on the workers, and stay there... the original driver-side variable will remain unchanged

How can you solve this?
When working with Spark, especially with DataFrames, you should try to avoid "iteration" over the data, and use DataFrame's declarative operations instead. In most cases, when you want to reference data of another DataFrame for each record in your DataFrame, you'd want to use join to create a new DataFrame with records combining data from the two DataFrames.

In this specific case, here's a roughly equivalent solution that does what you're trying to do, if I managed to conclude it correctly. Try to use this and read the DataFrame documentation to figure out the details:

```<code>import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import spark.implicits._

val numRecProducts = 10

val result = prodRows.as("left")
  // self-join by gender:
  .join(prodRows.as("right"), $"left.gender_PK" === $"right.gender_PK" || $"right.gender_PK" === "UNISEX")
  // limit to 10 results per record:
  .withColumn("rn", row_number().over(Window.partitionBy($"left.product_PK").orderBy($"right.product_PK")))
  .filter($"rn" <= numRecProducts).drop($"rn")
  // group and collect_list to create products column:
  .groupBy($"left.product_PK" as "product_PK")
  .agg(collect_list(struct($"right.product_PK", lit(1))) as "products")
</code>```

Body:
Below I provide my code. I iterate over the DataFrame prodRows and for each product_PK I find some matching sub-list of product_PKs from prodRows.

  numRecProducts = 10
  var listOfProducts: Map[Long,Array[(Long, Int)]] = Map()
  prodRows.foreach{ row : Row =>
      val product_PK = row.get(row.fieldIndex("product_PK")).toString.toLong
      val gender = row.get(row.fieldIndex("gender_PK")).toString
      val selection = prodRows.filter($"gender_PK" === gender || $"gender_PK" === "UNISEX").limit(numRecProducts).select($"product_PK")
      var productList: Array[(Long, Int)] = Array()
      if (!selection.rdd.isEmpty()) {
        productList = selection.rdd.map(x => (x(0).toString.toLong,1)).collect()
      }
    listOfProducts = listOfProducts + (product_PK -> productList)
  }

But when I execute it, it gives me the following error. It looks like selection is empty in some iterations. However, I do not understand how can I handle this error:

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1690)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1678)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1677)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1677)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:855)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:855)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:855)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1905)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1860)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1849)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:671)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2022)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2043)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2062)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2087)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1.apply(RDD.scala:918)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1.apply(RDD.scala:916)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.foreach(RDD.scala:916)
    at org.apache.spark.sql.Dataset$$anonfun$foreach$1.apply$mcV$sp(Dataset.scala:2325)
    at org.apache.spark.sql.Dataset$$anonfun$foreach$1.apply(Dataset.scala:2325)
    at org.apache.spark.sql.Dataset$$anonfun$foreach$1.apply(Dataset.scala:2325)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
    at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2823)
    at org.apache.spark.sql.Dataset.foreach(Dataset.scala:2324)
    at org.test.ComputeNumSim.run(ComputeNumSim.scala:69)
    at org.test.ComputeNumSimRunner$.main(ComputeNumSimRunner.scala:19)
    at org.test.ComputeNumSimRunner.main(ComputeNumSimRunner.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.yarn.ApplicationMaster$$anon$2.run(ApplicationMaster.scala:635)
Caused by: java.lang.NullPointerException
    at org.apache.spark.sql.Dataset.<init>(Dataset.scala:170)
    at org.apache.spark.sql.Dataset$.apply(Dataset.scala:61)
    at org.apache.spark.sql.Dataset.withTypedPlan(Dataset.scala:2877)
    at org.apache.spark.sql.Dataset.filter(Dataset.scala:1304)
    at org.test.ComputeNumSim$$anonfun$run$1.apply(ComputeNumSim.scala:74)
    at org.test.ComputeNumSim$$anonfun$run$1.apply(ComputeNumSim.scala:69)
    at scala.collection.Iterator$class.foreach(Iterator.scala:893)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
    at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:108)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)

What does it mean and how can I handle it?

Body:
You cannot access any of Spark's "driver-side" abstractions (RDDs, DataFrames, Datasets, SparkSession...) from within a function passed on to one of Spark's DataFrame/RDD transformations. You also cannot update driver-side mutable objects from within these functions.

In your case - you're trying to use prodRows and selection (both are DataFrames) within a function passed to DataFrame.foreach. You're also trying to update listOfProducts (a local driver-side variable) from within that same function.

Why?

DataFrames, RDDs, and SparkSession only exist on your Driver application. They serve as a "handle" to access data distributed over the cluster of worker machines.

Functions passed to RDD/DataFrame transformations get serialized and sent to that cluster, to be executed on the data partitions on each of the worker machines. When the serialized DataFrames/RDDs get deserialized on those machines - they are useless, they can't still represent the data on the cluster as they are just hollow copies of the ones created on the driver application, which actually maintains a connection to the cluster machines

For the same reason, attempting to update driver-side variables will fail: the variables (starting out as empty, in most cases) will be serialized, deserialized on each of the workers, get updated locally on the workers, and stay there... the original driver-side variable will remain unchanged

How can you solve this?
When working with Spark, especially with DataFrames, you should try to avoid "iteration" over the data, and use DataFrame's declarative operations instead. In most cases, when you want to reference data of another DataFrame for each record in your DataFrame, you'd want to use join to create a new DataFrame with records combining data from the two DataFrames.

In this specific case, here's a roughly equivalent solution that does what you're trying to do, if I managed to conclude it correctly. Try to use this and read the DataFrame documentation to figure out the details:

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
import spark.implicits._

val numRecProducts = 10

val result = prodRows.as("left")
  // self-join by gender:
  .join(prodRows.as("right"), $"left.gender_PK" === $"right.gender_PK" || $"right.gender_PK" === "UNISEX")
  // limit to 10 results per record:
  .withColumn("rn", row_number().over(Window.partitionBy($"left.product_PK").orderBy($"right.product_PK")))
  .filter($"rn" <= numRecProducts).drop($"rn")
  // group and collect_list to create products column:
  .groupBy($"left.product_PK" as "product_PK")
  .agg(collect_list(struct($"right.product_PK", lit(1))) as "products")


问:
Can objects names be used to create an instance of that object?
So i'm learning to code in javascript, and right now i have a practice example of inheritance by prototype. The thing is, i have to achieve something like this:

```<code>var human = {}
var worker = human.create()
var dev = worker.create()

var adrian = dev.create("Adrian",28,20000)
</code>```

The two points in the excercise go as follow:
1) To get rid of Object.create
2) To get rid of properties assignations Ex: adrian.age = 28;

I already know how to somehow do this on the "Classical Model" but im at a loss as to how to use my object name along with .create

I thought about creating a constructor function and use that to create an instance, but the result is undefined, because i don't have an object created to begin with

答:
I am not sure what your task actually is. It could be the following:

Learning to work with Prototypes

Although the .create method does not exist on a plain object you could make it available.

Try starting by outputting the object itself:

```<code>Object.prototype.create = function(){
  console.log('Hello I am the object itself', this);
};

({foo: 'bar'}).create();
</code>```

Then you could take this and think of how to actually make a copy of that. E.g. by using:

```<code>Object.prototype.create = function(){
  return Object.assign({}, this); // shallow copy
};

const human = {name: 'Max'};
const worker = human.create();
</code>```

By this you basically created a shallow fork of human with your worker. Now if you want to go one step further -> just parametrize your function to take some arguments and add more props to your newly created object.

Body:
So i'm learning to code in javascript, and right now i have a practice example of inheritance by prototype. The thing is, i have to achieve something like this:

var human = {}
var worker = human.create()
var dev = worker.create()

var adrian = dev.create("Adrian",28,20000)

The two points in the excercise go as follow:
1) To get rid of Object.create
2) To get rid of properties assignations Ex: adrian.age = 28;

I already know how to somehow do this on the "Classical Model" but im at a loss as to how to use my object name along with .create

I thought about creating a constructor function and use that to create an instance, but the result is undefined, because i don't have an object created to begin with

Body:
I am not sure what your task actually is. It could be the following:

Learning to work with Prototypes

Although the .create method does not exist on a plain object you could make it available.

Try starting by outputting the object itself:

Object.prototype.create = function(){
  console.log('Hello I am the object itself', this);
};

({foo: 'bar'}).create();

Then you could take this and think of how to actually make a copy of that. E.g. by using:

Object.prototype.create = function(){
  return Object.assign({}, this); // shallow copy
};

const human = {name: 'Max'};
const worker = human.create();

By this you basically created a shallow fork of human with your worker. Now if you want to go one step further -> just parametrize your function to take some arguments and add more props to your newly created object.


问:
How to validate start date and end date in angular?
I am building component in angular in which I want start date to be greater than end date. I am wondering what changes I need to make in my HTML and TS codes to get it done. The snippets of HTML and TS codes which I am using are:

HTML:

```<code><form class="unavailability-form" [formGroup]="unavailabilityForm" *ngIf="loaded">
<div class="component-title" matDialogTitle>
   {{'PORTAL.TEXTUNAVAILABILITY' | translate}}
</div>
<mat-toolbar>
   <div class="container"
      fxLayout="row"
      fxLayout.xs="column"
      fxLayoutGap.xs="0">
      <div>
         <h1>{{componentTitle}}</h1>
      </div>
   </div>
</mat-toolbar>
<mat-dialog-content>
   <div class="container" fxLayout="row" fxLayout.xs="column" fxLayoutGap.xs="0" fxLayoutGap="10px">
      <div class="item item-1" fxFlex="50%" fxFlexOrder="1">
         <mat-form-field>
            <input matInput [matDatepicker]="picker" placeholder="{{'PORTALSTARTDATE' | translate}}"  type="text" formControlName="startDate" [(ngModel)]="availability.startDate" [readonly]="!componentPermission.writePermission">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
         </mat-form-field>
      </div>
      <div class="item item-2" fxFlex="50%" fxFlexOrder="1">
         <mat-form-field>
            <input matInput [matDatepicker]="picker" placeholder="{{'PORTAL.ENDDATE' | translate}}"  type="text" formControlName="endDate" [(ngModel)]="availability.endDate" [readonly]="!componentPermission.writePermission">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
         </mat-form-field>
      </div>
   </div>
   <div class="item item-1" fxFlex="50%" fxFlexOrder="1">
      <mat-form-field>
         <input matInput placeholder="{{'PORTAL.UNAVAILABILITYREASON' | translate}}" type="text" formControlName="unavailabilityReason" [(ngModel)]="availability.unavailabilityReason" [readonly]="!componentPermission.writePermission">
      </mat-form-field>
   </div>
</mat-dialog-content>
<mat-dialog-actions>
   <div class="container" fxLayout="row" fxLayout.xs="column" fxLayoutGap.xs="0">
      <div class="item item-1" fxFlex="100%">
         <button mat-raised-button color="primary" [disabled]="!locationForm.valid || !componentPermission.writePermission" (click)="onSave()">{{'PORTAL.CONFIRM' | translate}}</button>
         <button mat-raised-button [matDialogClose]="canceled" color="primary">{{'PORTAL.CANCEL' | translate}}</button>
      </div>
   </div>
</mat-dialog-actions>
</form>
</code>```

TS:

```<code>  validateForm() {
    this.unavailabilityForm = this.formBuilder.group({
      'startDate': [''],
      'endDate': [''],
      'unavailabilityReason': ['']
    });
  }
</code>```

In the above code, {{PORTAL.___}} text refers to the value from the database.

答:
Please note that you cannot use ngModel within your form. You have to feed form from your component with data. Here is form with removed ngModel:

```<code><mat-dialog-content>
   <form [formGroup]="unavailabilityForm " novalidate fxFlex>
      <div class="container" fxLayout="row" fxLayout.xs="column" fxLayoutGap.xs="0" fxLayoutGap="10px">
         <div class="item item-1" fxFlex="50%" fxFlexOrder="1">
            <mat-form-field>
               <input matInput [matDatepicker]="picker" placeholder="{{'PORTALSTARTDATE' | translate}}"  type="text" formControlName="startDate" [readonly]="!componentPermission.writePermission">
               <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
               <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>
         </div>
         <div class="item item-2" fxFlex="50%" fxFlexOrder="1">
            <mat-form-field>
               <input matInput [matDatepicker]="picker" placeholder="{{'PORTAL.ENDDATE' | translate}}"  type="text" formControlName="endDate" [readonly]="!componentPermission.writePermission">
               <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
               <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>
         </div>
      </div>
      <div class="item item-1" fxFlex="50%" fxFlexOrder="1">
         <mat-form-field>
            <input matInput placeholder="{{'PORTAL.UNAVAILABILITYREASON' | translate}}" type="text" formControlName="unavailabilityReason"  [readonly]="!componentPermission.writePermission">
         </mat-form-field>
      </div>
   </form>
</mat-dialog-content>
</code>```

Then you need to initialize form and add FormGroup level validator to your group. Also I feed data to your form:

```<code>initForm() {
    this.unavailabilityForm = this.formBuilder.group({
      'startDate': [availability.startDate],
      'endDate': [availability.endDate],
      'unavailabilityReason': [availability.unavailabilityReason]
    }, validateDate);
  }
</code>```

Your custom validator function in FormGroup will be validateDate.

Custom validator function should be like this:

```<code>function validateDate(group: FormGroup) {
  ///TODO: Implement some better validation logic
  const invalid = group.get('startDate').value > group.get('endDate').value;

  ///TODO: Implement some logic to mark controls dirty if is necessary.

  return invalid ? { 'invalidDate': true } : null;
}
</code>```

In custom validator on FormGroup level you can you can access to all controls form that group and perform validation. Please note that value of your form will be string so, if you are working with Date you will need better logic to compare dates.

Also please not that group level validator maybe will not display validation feedback, so you will need manually to mark controls to be dirty if is necessary.

Body:
I am building component in angular in which I want start date to be greater than end date. I am wondering what changes I need to make in my HTML and TS codes to get it done. The snippets of HTML and TS codes which I am using are:

HTML:

<form class="unavailability-form" [formGroup]="unavailabilityForm" *ngIf="loaded">

   {{'PORTAL.TEXTUNAVAILABILITY' | translate}}

<mat-toolbar>

{{componentTitle}}

</mat-toolbar>
<mat-dialog-content>

         <mat-form-field>
            <input matInput [matDatepicker]="picker" placeholder="{{'PORTALSTARTDATE' | translate}}"  type="text" formControlName="startDate" [(ngModel)]="availability.startDate" [readonly]="!componentPermission.writePermission">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
         </mat-form-field>

         <mat-form-field>
            <input matInput [matDatepicker]="picker" placeholder="{{'PORTAL.ENDDATE' | translate}}"  type="text" formControlName="endDate" [(ngModel)]="availability.endDate" [readonly]="!componentPermission.writePermission">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
         </mat-form-field>

      <mat-form-field>
         <input matInput placeholder="{{'PORTAL.UNAVAILABILITYREASON' | translate}}" type="text" formControlName="unavailabilityReason" [(ngModel)]="availability.unavailabilityReason" [readonly]="!componentPermission.writePermission">
      </mat-form-field>

</mat-dialog-content>
<mat-dialog-actions>

         <button mat-raised-button color="primary" [disabled]="!locationForm.valid || !componentPermission.writePermission" (click)="onSave()">{{'PORTAL.CONFIRM' | translate}}</button>
         <button mat-raised-button [matDialogClose]="canceled" color="primary">{{'PORTAL.CANCEL' | translate}}</button>

</mat-dialog-actions>
</form>

TS:

  validateForm() {
    this.unavailabilityForm = this.formBuilder.group({
      'startDate': [''],
      'endDate': [''],
      'unavailabilityReason': ['']
    });
  }

In the above code, {{PORTAL.___}} text refers to the value from the database.

Body:
Please note that you cannot use ngModel within your form. You have to feed form from your component with data. Here is form with removed ngModel:

<mat-dialog-content>
   <form [formGroup]="unavailabilityForm " novalidate fxFlex>
      <div class="container" fxLayout="row" fxLayout.xs="column" fxLayoutGap.xs="0" fxLayoutGap="10px">
         <div class="item item-1" fxFlex="50%" fxFlexOrder="1">
            <mat-form-field>
               <input matInput [matDatepicker]="picker" placeholder="{{'PORTALSTARTDATE' | translate}}"  type="text" formControlName="startDate" [readonly]="!componentPermission.writePermission">
               <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
               <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>
         </div>
         <div class="item item-2" fxFlex="50%" fxFlexOrder="1">
            <mat-form-field>
               <input matInput [matDatepicker]="picker" placeholder="{{'PORTAL.ENDDATE' | translate}}"  type="text" formControlName="endDate" [readonly]="!componentPermission.writePermission">
               <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
               <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>
         </div>
      </div>
      <div class="item item-1" fxFlex="50%" fxFlexOrder="1">
         <mat-form-field>
            <input matInput placeholder="{{'PORTAL.UNAVAILABILITYREASON' | translate}}" type="text" formControlName="unavailabilityReason"  [readonly]="!componentPermission.writePermission">
         </mat-form-field>
      </div>
   </form>
</mat-dialog-content>

Then you need to initialize form and add FormGroup level validator to your group. Also I feed data to your form:

initForm() {
    this.unavailabilityForm = this.formBuilder.group({
      'startDate': [availability.startDate],
      'endDate': [availability.endDate],
      'unavailabilityReason': [availability.unavailabilityReason]
    }, validateDate);
  }

Your custom validator function in FormGroup will be validateDate.

Custom validator function should be like this:

function validateDate(group: FormGroup) {
  ///TODO: Implement some better validation logic
  const invalid = group.get('startDate').value > group.get('endDate').value;

  ///TODO: Implement some logic to mark controls dirty if is necessary.

  return invalid ? { 'invalidDate': true } : null;
}

In custom validator on FormGroup level you can you can access to all controls form that group and perform validation. Please note that value of your form will be string so, if you are working with Date you will need better logic to compare dates.

Also please not that group level validator maybe will not display validation feedback, so you will need manually to mark controls to be dirty if is necessary.


答: The problem is that you try to access prodRows from within prodRows.foreach. You cannot use a dataframe within a transformation, dataframes only exist on the driver.

Title: Caused by: java.lang.NullPointerException at org.apache.spark.sql.Dataset


答:
In plain javascript you write your constructor as a function. So to write a constructor function for a human, you would write:

function human(name, age) {
  this.name = name;
  this.age = age;
}

const adrian = new human("Adrian", 28);

console.log(adrian.name, adrian.age); // prints the objects properties

console.log(JSON.stringify(adrian)); // prints the created object as json string```

Title: Can objects names be used to create an instance of that object?


问:
cli tool in docker container is slow
What shoul I expect performance wise when using docker for cli tool?
Seems like when I try running this tool in docker - it is a lot slower. Am I doing it wrong?

So I ahve a test.html file with this content:

```<code><html><!--sdfsf--></html>
</code>```

Installed on my box - very fast:

```<code>$ time html-minifier --remove-comments <test.html
<html></html>
real    0m0.098s
user    0m0.088s
sys 0m0.013s
</code>```

Running in docker -> takes a lot longer:

```<code>time docker run -i chuyskywalker/node-html-minifier html-minifier --remove-comments <test.html
<html></html>

real    0m1.061s
user    0m0.019s
sys 0m0.012s
</code>```

EDIT: My machine is Fedora Linux 25. Docker was installed from docker official repositories.

答:
There are a couple things to note here:

Docker on macOS or Windows is actually running in a virtual machine. This virtual machine will come with some overhead and may also be limited in how many actual CPUs and memory it has access to.

Docker container do have a startup time (which can be 1 second or more).

If you are mounting volumes or piping in data to standard input, it can be slower as it has to travel through the Docker client to the Docker host.

You didn't mention how Docker was installed or the host platform. But if you are on Windows or macOS then #1 and #3 will definitely account for some of the time.

One thing you can do is move the time command inside the container (if the utility is available in the image) to get a closer representation of the actual process time:

```<code>docker run -i chuyskywalker/node-html-minifier time html-minifier --remove-comments <test.html
</code>```

Title: cli tool in docker container is slow

Body:
What shoul I expect performance wise when using docker for cli tool?
Seems like when I try running this tool in docker - it is a lot slower. Am I doing it wrong?

So I ahve a test.html file with this content:

Installed on my box - very fast:

$ time html-minifier --remove-comments <test.html

real    0m0.098s
user    0m0.088s
sys 0m0.013s

Running in docker -> takes a lot longer:

time docker run -i chuyskywalker/node-html-minifier html-minifier --remove-comments <test.html

real    0m1.061s
user    0m0.019s
sys 0m0.012s

EDIT: My machine is Fedora Linux 25. Docker was installed from docker official repositories.

Body:
There are a couple things to note here:

Docker on macOS or Windows is actually running in a virtual machine. This virtual machine will come with some overhead and may also be limited in how many actual CPUs and memory it has access to.

Docker container do have a startup time (which can be 1 second or more).

If you are mounting volumes or piping in data to standard input, it can be slower as it has to travel through the Docker client to the Docker host.

You didn't mention how Docker was installed or the host platform. But if you are on Windows or macOS then #1 and #3 will definitely account for some of the time.

One thing you can do is move the time command inside the container (if the utility is available in the image) to get a closer representation of the actual process time:

docker run -i chuyskywalker/node-html-minifier time html-minifier --remove-comments <test.html


问:
setValue on select FormControl with ngx-translate - Angular 2
I have a select FormControl inside a reactive form that I am using pipe translate from the ngx-translate library on. On initialization of the FormControl in my creation of the FormGroup the value is reflecting just fine in the DOM, and you can actually see the translation. However, when I try to reset, setValue, or patchValue on the FormControl the pipe translate does not seem to like it at all. I can console.log the value of the FormControl after resetting it and actually see the value change. It just does not reflect this change in the DOM. I have also tried adding a (ngModelChange) to the FormControl to watch the value change after resetting it and this works as well, but does not reflect it in the DOM. My desired result would be to use reset since I can set the value of the control and reset the state of the control all in one pass. It is the weirdest behavior I have seen, and I cannot figure this out. If I remove the pipe translate the reset of the value works perfectly fine and reflects the value in the DOM. Any help would be appreciated! Here is the following code:</p>

```<code>this.shopInfoForm = this._formBuilder.group({
  name: [this._settings.name],
  brand: [this._settings.brands[0]],
  language: [this._settings.language]
});

get language() { return this.shopInfoForm.get('language'); }

this.language.reset(this._settings.language);

<div class="input-group">
  <span class="input-group-addon">Language</span>
  <select formControlName="language" class="form-control">
    <option *ngFor="let language of languages">{{language.langLabelId.toString() | translate}}</option>
  </select>
</div>
</code>```

答:
Just in case anyone runs into this same problem. It all had to do with the value attribute on the option tag. I updated my code in the DOM to look like this:

```<code><option *ngFor="let language of languages" value="{{language.langLabelId}}">{{language.langLabelId.toString() | translate}}</option>
</code>```

and it works just fine now.

Body:
I have a select FormControl inside a reactive form that I am using pipe translate from the ngx-translate library on. On initialization of the FormControl in my creation of the FormGroup the value is reflecting just fine in the DOM, and you can actually see the translation. However, when I try to reset, setValue, or patchValue on the FormControl the pipe translate does not seem to like it at all. I can console.log the value of the FormControl after resetting it and actually see the value change. It just does not reflect this change in the DOM. I have also tried adding a (ngModelChange) to the FormControl to watch the value change after resetting it and this works as well, but does not reflect it in the DOM. My desired result would be to use reset since I can set the value of the control and reset the state of the control all in one pass. It is the weirdest behavior I have seen, and I cannot figure this out. If I remove the pipe translate the reset of the value works perfectly fine and reflects the value in the DOM. Any help would be appreciated! Here is the following code:

this.shopInfoForm = this._formBuilder.group({
  name: [this._settings.name],
  brand: [this._settings.brands[0]],
  language: [this._settings.language]
});

get language() { return this.shopInfoForm.get('language'); }

this.language.reset(this._settings.language);

  Language
  <select formControlName="language" class="form-control">
    <option *ngFor="let language of languages">{{language.langLabelId.toString() | translate}}</option>
  </select>

Body:
Just in case anyone runs into this same problem. It all had to do with the value attribute on the option tag. I updated my code in the DOM to look like this:

<option *ngFor="let language of languages" value="{{language.langLabelId}}">{{language.langLabelId.toString() | translate}}</option>

and it works just fine now.


问:
Operator from Ethereum contract _;
Sorry if it is duplicated question.
What does "_" operator make?

This code is from Ethereum contract manual:
https://ethereum.org/token#deploying

```<code>contract owned {
    address public owner;

    function owned() {
        owner = msg.sender;
    }

    modifier onlyOwner {
        if (msg.sender != owner) throw;
        _;
    }

    function transferOwnership(address newOwner) onlyOwner {
        owner = newOwner;
    }
}
</code>```

答:
It is used inside modifiers.

"The function body is inserted where the special symbol "_" in the
  definition of a modifier appears."

Reference:
Contracts — Solidity 0.4.19 documentation

And in case it is used only once in a modifier, you can see it as following:
After the return variables are assigned, the _ returns the control flow to what is next to the current modifier (next to the current modifier could be the next modifier or the function).

You can see a detailed explanation and example in the answer at:
Are underscores _ in modifiers code or are they just meant to look cool?

Title: Operator from Ethereum contract _;

Body:
Sorry if it is duplicated question.
What does "_" operator make?

This code is from Ethereum contract manual:
https://ethereum.org/token#deploying

contract owned {
    address public owner;

    function owned() {
        owner = msg.sender;
    }

    modifier onlyOwner {
        if (msg.sender != owner) throw;
        _;
    }

    function transferOwnership(address newOwner) onlyOwner {
        owner = newOwner;
    }
}


问:
custom validation markup in Rails(3)
I'm trying to accomplish the following mark-up for all my form elements

```<code><div class="input-container">
  <label>Topic Title</label>
  <div class="input-holder">
    <input type="text" />
  </div>
</div>

<div class="textarea-container">
  <label>Post</label>
  <div class="textarea-holder">
    <textarea></textarea>
  </div>
</div>
</code>```

invalid fields mark-up:

```<code><div class="input-container alert">
  <label>Topic Title</label>
  <div class="input-holder">
    <input type="text" />
  </div>
</div>
<div class="textarea-container alert">
  <label>Post</label>
  <div class="textarea-holder">
    <textarea></textarea>
  </div>
</div>
</code>```

here's my current haml markup:

```<code>.input-container
  = f.label :title, 'Topic Title'
  .input-holder
    = f.text_field :title
.textarea-container
  = f.label :body, 'Post'
  .textarea-holder
    = f.text_area(:body, :size => "60x10")
</code>```

Now what would I need to do if I want the container divs to have the alert class when a field in my form is invalid?

答:
It might be best to use either the formtastic or simple_form gems which out of the box support highlighting an individual invalid field.

I'm almost certain they do this by changing the CSS class on the field or its container, which you could also hook into in your stylesheets.

Title: custom validation markup in Rails(3)

Body:
I'm trying to accomplish the following mark-up for all my form elements

  Topic Title

    <input type="text" />

  Post

    <textarea></textarea>

invalid fields mark-up:

  Topic Title

    <input type="text" />

  Post

    <textarea></textarea>

here's my current haml markup:

.input-container
  = f.label :title, 'Topic Title'
  .input-holder
    = f.text_field :title
.textarea-container
  = f.label :body, 'Post'
  .textarea-holder
    = f.text_area(:body, :size => "60x10")

Now what would I need to do if I want the container divs to have the alert class when a field in my form is invalid?


问:
Google Maps using custom icon for marker sometimes doesn't show up
I am getting weird and unpredictable behavior when specifying an icon to use with google.maps.Markers.  Basically, the markers show up (with default icon) if I don't specify an icon property, but if I do specify the icon property, no markers show up (although I have other case where I can get a custom icon to show, so that's why it's weird).

Here's the relevant code:

```<code>              function initMap() {
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng)
                  });
                });

                ...calculate bounds..

                var map = new google.maps.Map(document.getElementById('route_log_map_map'), {
                  position: bounds.getCenter(),
                  zoom: 15
                });

                ...other unrelated code...

                for(i=0; i < markers.length; i++) {
                   markers[i].setMap(map);
                }
              }
</code>```

This is called with:

```<code><script src="https://maps.googleapis.com/maps/api/js?key=...key...&callback=initMap" async="" defer=""></script>
</code>```

and the above results in:

Obviously that's a lousy marker to use in this case (there's almost 2000 points), so if I change the marker creation to be like this:

```<code>                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 1
                    }
                  });
                });
</code>```

the markers don't show up (and there's no errors either) (note those blue circles are unrelated to this code):

EDIT

This is interesting.  It works if the array I'm building the markers from has only one element, but fails to display if it has more than one.  E.g. this works and displays one marker:

```<code>                var route_log = [
                  {lat: 41.86219805, lng: -71.04886590000001}
                ];
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 10
                    }
                  });
                });
</code>```

but this displays no markers (only change is to add another element to the array):

```<code>                var route_log = [
                  {lat: 41.86219805, lng: -71.04886590000001},
                  {lat: 41.87219805, lng: -71.05886590000001}
                ];
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 10
                    }
                  });
                });
</code>```

答:
Wow.

I have position in the options to the new google.maps.Map call.  It should be center, which is required.  position is not even a valid option for google.maps.MapOptions.

I blame the Google Maps API for this one. :-)

Body:
I am getting weird and unpredictable behavior when specifying an icon to use with google.maps.Markers.  Basically, the markers show up (with default icon) if I don't specify an icon property, but if I do specify the icon property, no markers show up (although I have other case where I can get a custom icon to show, so that's why it's weird).

Here's the relevant code:

              function initMap() {
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng)
                  });
                });

                ...calculate bounds..

                var map = new google.maps.Map(document.getElementById('route_log_map_map'), {
                  position: bounds.getCenter(),
                  zoom: 15
                });

                ...other unrelated code...

                for(i=0; i < markers.length; i++) {
                   markers[i].setMap(map);
                }
              }

This is called with:

and the above results in:

Obviously that's a lousy marker to use in this case (there's almost 2000 points), so if I change the marker creation to be like this:

                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 1
                    }
                  });
                });

the markers don't show up (and there's no errors either) (note those blue circles are unrelated to this code):

EDIT

This is interesting.  It works if the array I'm building the markers from has only one element, but fails to display if it has more than one.  E.g. this works and displays one marker:

                var route_log = [
                  {lat: 41.86219805, lng: -71.04886590000001}
                ];
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 10
                    }
                  });
                });

but this displays no markers (only change is to add another element to the array):

                var route_log = [
                  {lat: 41.86219805, lng: -71.04886590000001},
                  {lat: 41.87219805, lng: -71.05886590000001}
                ];
                var markers = route_log.map(function(segment) {
                  return new google.maps.Marker({
                    position: new google.maps.LatLng(segment.lat, segment.lng),
                    icon: {
                      path: google.maps.SymbolPath.CIRCLE,
                      scale: 10
                    }
                  });
                });


问:
Image on the top of a multi-column layout with CSS
I have a two column layout (using the CSS multi-column layout module) and I'd like to have an image at the top of the second column. It seems like I have to place the image myself so that it's in the place in the text where the break will be.

The problem is I want the columns to be evenly filled as well.

Is there any way to solve this without JavaScript? This uses a div instead of an image but the idea is to place the red block at the top of its column.

.col-2 {
    -webkit-column-count:2;
    -moz-column-count:2;
    column-count:2;
    width:800px;
}

.block {
    width:100%;
    height:100px;
    background-color:red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam blandit neque sed eros posuere molestie. Quisque mattis ante ac mauris iaculis semper vehicula nibh condimentum. Pellentesque scelerisque euismod metus a sodales. Praesent dolor nisl, consectetur at tincidunt eu, dapibus at orci. Etiam congue metus id sapien rutrum euismod. Proin porttitor rhoncus hendrerit. Phasellus pellentesque venenatis felis a eleifend. Suspendisse pretium placerat hendrerit. Praesent tempus risus in ligula condimentum egestas. Vivamus vitae nunc massa, luctus egestas lectus. Vivamus at turpis sed nisl molestie vulputate. Vivamus nec tortor et ante consectetur dignissim ac in odio. Cras et nisl non enim congue scelerisque. Curabitur in condimentum eros. Curabitur vehicula augue id neque dignissim vitae venenatis nisi feugiat.

Curabitur tristique ullamcorper neque, ac sodales eros suscipit eu. Nulla pretium accumsan lacus, non fermentum felis lacinia mattis. Sed quis turpis eros. Nullam ut turpis libero. Nam quis magna ac tortor elementum pulvinar. Quisque rutrum eleifend elit, eget consectetur nulla dapibus ac. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean rhoncus commodo tellus, sit amet pulvinar mi vehicula non. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi mollis dignissim felis, et posuere quam molestie nec. Duis sit amet pulvinar dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut lorem justo, lobortis id imperdiet nec, lobortis varius mauris. Nullam sit amet nulla arcu. Nullam ornare posuere leo vitae rhoncus.

Sed venenatis dui sapien. Praesent sed enim lacus, vitae venenatis metus. Aenean bibendum nibh a risus scelerisque blandit. Maecenas nibh enim, pulvinar in interdum quis, rhoncus ut orci. Vestibulum a ullamcorper ante. Nulla facilisi. Pellentesque placerat ullamcorper diam at mattis. Aliquam posuere suscipit metus sed sollicitudin. Phasellus in quam odio, ac scelerisque purus. Morbi at nunc odio, nec aliquam urna. Proin mi orci, varius vitae dapibus ac, consequat id purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a dui lectus, ut congue nunc. Cras diam tortor, auctor in vehicula vitae, egestas eget neque. In nisi odio, laoreet a convallis in, varius at risus.
    <div class="block"></div>
</div></code>```

答:
The CSS3 spec has a "column-break" style, but it has only been implemented in Webkit. It would do exactly what you are looking for, but only in Safari and Chrome sadly.

You would need to have your column breaking element fall within the normal flow of your content, and add the following style:

```<code>div.block {
  width: 100px; /* this shouldn't be more than your column width */
  height: 100px;
  -webkit-column-break-before: always;
}
</code>```

Example (View in Safari/Chrome)

http://css-infos.net/property/-webkit-column-break-before

http://www.w3.org/TR/css3-multicol/#column-breaks

Body:
I have a two column layout (using the CSS multi-column layout module) and I'd like to have an image at the top of the second column. It seems like I have to place the image myself so that it's in the place in the text where the break will be.

The problem is I want the columns to be evenly filled as well.

Is there any way to solve this without JavaScript? This uses a div instead of an image but the idea is to place the red block at the top of its column.

.col-2 {
    -webkit-column-count:2;
    -moz-column-count:2;
    column-count:2;
    width:800px;
}

.block {
    width:100%;
    height:100px;
    background-color:red;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam blandit neque sed eros posuere molestie. Quisque mattis ante ac mauris iaculis semper vehicula nibh condimentum. Pellentesque scelerisque euismod metus a sodales. Praesent dolor nisl, consectetur at tincidunt eu, dapibus at orci. Etiam congue metus id sapien rutrum euismod. Proin porttitor rhoncus hendrerit. Phasellus pellentesque venenatis felis a eleifend. Suspendisse pretium placerat hendrerit. Praesent tempus risus in ligula condimentum egestas. Vivamus vitae nunc massa, luctus egestas lectus. Vivamus at turpis sed nisl molestie vulputate. Vivamus nec tortor et ante consectetur dignissim ac in odio. Cras et nisl non enim congue scelerisque. Curabitur in condimentum eros. Curabitur vehicula augue id neque dignissim vitae venenatis nisi feugiat.

Curabitur tristique ullamcorper neque, ac sodales eros suscipit eu. Nulla pretium accumsan lacus, non fermentum felis lacinia mattis. Sed quis turpis eros. Nullam ut turpis libero. Nam quis magna ac tortor elementum pulvinar. Quisque rutrum eleifend elit, eget consectetur nulla dapibus ac. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aenean rhoncus commodo tellus, sit amet pulvinar mi vehicula non. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi mollis dignissim felis, et posuere quam molestie nec. Duis sit amet pulvinar dui. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut lorem justo, lobortis id imperdiet nec, lobortis varius mauris. Nullam sit amet nulla arcu. Nullam ornare posuere leo vitae rhoncus.

Sed venenatis dui sapien. Praesent sed enim lacus, vitae venenatis metus. Aenean bibendum nibh a risus scelerisque blandit. Maecenas nibh enim, pulvinar in interdum quis, rhoncus ut orci. Vestibulum a ullamcorper ante. Nulla facilisi. Pellentesque placerat ullamcorper diam at mattis. Aliquam posuere suscipit metus sed sollicitudin. Phasellus in quam odio, ac scelerisque purus. Morbi at nunc odio, nec aliquam urna. Proin mi orci, varius vitae dapibus ac, consequat id purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a dui lectus, ut congue nunc. Cras diam tortor, auctor in vehicula vitae, egestas eget neque. In nisi odio, laoreet a convallis in, varius at risus.

Body:
The CSS3 spec has a "column-break" style, but it has only been implemented in Webkit. It would do exactly what you are looking for, but only in Safari and Chrome sadly.

You would need to have your column breaking element fall within the normal flow of your content, and add the following style:

div.block {
  width: 100px; /* this shouldn't be more than your column width */
  height: 100px;
  -webkit-column-break-before: always;
}

Example (View in Safari/Chrome)

http://css-infos.net/property/-webkit-column-break-before

http://www.w3.org/TR/css3-multicol/#column-breaks


问:
How do I change the background color of the placeholder in jquery-ui sortable
I'm trying to color the background color of the placeholder in a sortable table red.
I can't however make it work.
I already tried the commonly used way of styling it with a class in a css file, but without succes.

```<code>placeholder: 'ui-sortable-placeholder',
</code>```

css

```<code>.ui-sortable-placeholder{
        background-color: red;
}
</code>```

nor did styling it in javascript directly work.

```<code>start: function(e, ui) {
ui.placeholder.css({
  "visibility":"visible",
  "background-color": "red"
});
</code>```

},

The preferred outcome would be a solution directly in javascript

var fixHelper = function(e, ui) {
  ui.children().each(function() {
    $(this).width($(this).width());
  });
  return ui;
};

$("table tbody").sortable({
  axis: 'y',
  containment: 'parent',
  revert: true,
  helper: fixHelper,
  start: function(e, ui) {
    ui.placeholder.css({
      "visibility":"visible",
      "background-color": "red"
    });
  },

}).disableSelection();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 500px;
}

td,
th {
  border: 1px solid #cacaca;
  text-align: left;
  padding: 8px;
  background-color: #f5f5f5;
}

th {
  background-color: #dce0e3;
}

.ui-sortable-placeholder {
  background-color: #fff;
  outline: 0px dashed black;
  padding: 0px 0px;
}</code>```

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />

    Company
    Contact
    Country

      Alfreds Futterkiste
      Maria Anders
      Germany

      Centro comercial
      Francisco Chang
      Mexico

      Ernst Handel
      Roland Mendel
      Austria

      Island Trading
      Helen Bennett
      UK

      Laughing Bacchus
      Yoshi Tannamuri
      Canada

      Magazzini Alimentari
      Giovanni Rovelli
      Italy

```

答:
Try this:

var fixHelper = function(e, ui) {
  ui.children().each(function() {
    $(this).width($(this).width());
  });
  return ui;
};

$("table tbody").sortable({
  axis: 'y',
  containment: 'parent',
  revert: true,
  helper: fixHelper,
  placeholder: "my-ui-placeholder"
}).disableSelection();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 500px;
}

td,
th {
  border: 1px solid #cacaca;
  text-align: left;
  padding: 8px;
  background-color: #f5f5f5;
}

th {
  background-color: #dce0e3;
}

.my-ui-placeholder {
  outline: 0px dashed black;
  padding: 0px 0px;
}

.my-ui-placeholder td {
  background-color: #fff;
  border: 0;
}</code>```

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />

    Company
    Contact
    Country

      Alfreds Futterkiste
      Maria Anders
      Germany

      Centro comercial
      Francisco Chang
      Mexico

      Ernst Handel
      Roland Mendel
      Austria

      Island Trading
      Helen Bennett
      UK

      Laughing Bacchus
      Yoshi Tannamuri
      Canada

      Magazzini Alimentari
      Giovanni Rovelli
      Italy

```

Remember that this is being added to the tr, and it will have td elements within it. So your CSS has to apply to both.

Body:
I'm trying to color the background color of the placeholder in a sortable table red.
I can't however make it work.
I already tried the commonly used way of styling it with a class in a css file, but without succes.

placeholder: 'ui-sortable-placeholder',

css

.ui-sortable-placeholder{
        background-color: red;
}

nor did styling it in javascript directly work.

start: function(e, ui) {
ui.placeholder.css({
  "visibility":"visible",
  "background-color": "red"
});

},

The preferred outcome would be a solution directly in javascript

var fixHelper = function(e, ui) {
  ui.children().each(function() {
    $(this).width($(this).width());
  });
  return ui;
};

$("table tbody").sortable({
  axis: 'y',
  containment: 'parent',
  revert: true,
  helper: fixHelper,
  start: function(e, ui) {
    ui.placeholder.css({
      "visibility":"visible",
      "background-color": "red"
    });
  },

}).disableSelection();

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 500px;
}

td,
th {
  border: 1px solid #cacaca;
  text-align: left;
  padding: 8px;
  background-color: #f5f5f5;
}

th {
  background-color: #dce0e3;
}

.ui-sortable-placeholder {
  background-color: #fff;
  outline: 0px dashed black;
  padding: 0px 0px;
}

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />

    Company
    Contact
    Country

      Alfreds Futterkiste
      Maria Anders
      Germany

      Centro comercial
      Francisco Chang
      Mexico

      Ernst Handel
      Roland Mendel
      Austria

      Island Trading
      Helen Bennett
      UK

      Laughing Bacchus
      Yoshi Tannamuri
      Canada

      Magazzini Alimentari
      Giovanni Rovelli
      Italy

Body:
Try this:

var fixHelper = function(e, ui) {
  ui.children().each(function() {
    $(this).width($(this).width());
  });
  return ui;
};

$("table tbody").sortable({
  axis: 'y',
  containment: 'parent',
  revert: true,
  helper: fixHelper,
  placeholder: "my-ui-placeholder"
}).disableSelection();

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 500px;
}

td,
th {
  border: 1px solid #cacaca;
  text-align: left;
  padding: 8px;
  background-color: #f5f5f5;
}

th {
  background-color: #dce0e3;
}

.my-ui-placeholder {
  outline: 0px dashed black;
  padding: 0px 0px;
}

.my-ui-placeholder td {
  background-color: #fff;
  border: 0;
}

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tbody>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus </td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari </td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </tbody>
</table>

Remember that this is being added to the tr, and it will have td elements within it. So your CSS has to apply to both.


问:
Intel HAXM on macOS high sierra (10.13)
Is there any way of using Android emulator on High Sierra (10.13)?

When I run

```<code>./HAXM\ installation -u
</code>```

It says:

```<code>HAXM silent installation only supports macOS from 10.8 to 10.12 !
</code>```

答:
You can use Google's 6.2.1's silent_installer.sh to properly install HAXM on High Sierra:

https://dl.google.com/android/repository/extras/intel/haxm-macosx_r6_2_1.zip

Otherwise use Android Studio's SDK Manager to download and install it for you:

This was not introduced until 6.2.1(Google Distribution only) which looks like a hotfix from the 6.2.0 version which would throw the following message:

```<code>HAXM silent installation only supports macOS from 10.8 to 10.12!
</code>```

If you don't want to use HAXM, you can use the Hypervisor.Framework by ensuring you have installed Android Emulator 26.1.3

Documentation

The emulator is now fully compatible with macOS 10.13 High Sierra through either Hypervisor.Framework or HAXM 6.2.0.

https://developer.android.com/studio/releases/emulator.html#26-1-3

Title: Intel HAXM on macOS high sierra (10.13)

Body:
Is there any way of using Android emulator on High Sierra (10.13)?

When I run

./HAXM\ installation -u

It says:

HAXM silent installation only supports macOS from 10.8 to 10.12 !

Body:
You can use Google's 6.2.1's silent_installer.sh to properly install HAXM on High Sierra:

https://dl.google.com/android/repository/extras/intel/haxm-macosx_r6_2_1.zip

Otherwise use Android Studio's SDK Manager to download and install it for you:

This was not introduced until 6.2.1(Google Distribution only) which looks like a hotfix from the 6.2.0 version which would throw the following message:

HAXM silent installation only supports macOS from 10.8 to 10.12!

If you don't want to use HAXM, you can use the Hypervisor.Framework by ensuring you have installed Android Emulator 26.1.3

Documentation

The emulator is now fully compatible with macOS 10.13 High Sierra through either Hypervisor.Framework or HAXM 6.2.0.

https://developer.android.com/studio/releases/emulator.html#26-1-3


问:
Python Django user model extension
I want to add phone number feild to user model and I would like to verify email and phone when we add user to the list. I would like to know your comments on it.

Make a userapi which will integrate with Google or Facebook for authentication

this will also verify phone number using third party.

Is my approach correct? If you can provide code snippets on model, apiview it will very useful.

Thanks
Kay

答:
You can customize the existing user model to include any fields you like and authenticate on any fields.
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/

Django also has support for social auth here's a guide:
https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html.

Your question is vague if you could be more specific, we could add more useful information.

Title: Python Django user model extension